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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e129467877b0104af7dda4e18452dfa0dcd2725 | 1,953 | java | Java | suifeng-common/src/main/java/org/suifeng/baseframework/common/util/EhCacheUtil.java | lxc3219/suifeng | 829f098ff5ad3ae9d35086b9ddfeb19d4d4c672b | [
"Apache-2.0"
] | null | null | null | suifeng-common/src/main/java/org/suifeng/baseframework/common/util/EhCacheUtil.java | lxc3219/suifeng | 829f098ff5ad3ae9d35086b9ddfeb19d4d4c672b | [
"Apache-2.0"
] | null | null | null | suifeng-common/src/main/java/org/suifeng/baseframework/common/util/EhCacheUtil.java | lxc3219/suifeng | 829f098ff5ad3ae9d35086b9ddfeb19d4d4c672b | [
"Apache-2.0"
] | null | null | null | 21.7 | 72 | 0.539683 | 7,834 | package org.suifeng.baseframework.common.util;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* Ehcache工具类
* Created by shuzheng on 2016/10/15.
*/
public class EhCacheUtil {
/**
* 获取缓存
* @param cacheName
* @return
*/
private static Cache getCache(String cacheName) {
CacheManager cacheManager = CacheManager.getInstance();
if (null == cacheManager) {
return null;
}
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
return null;
}
return cache;
}
/**
* 新增缓存记录
* @param cacheName
* @param key
* @param value
*/
public static void put(String cacheName, String key, Object value) {
Cache cache = getCache(cacheName);
if (null != cache) {
Element element = new Element(key, value);
cache.put(element);
}
}
/**
* 删除缓存记录
* @param cacheName
* @param key
* @return
*/
public static boolean remove(String cacheName, String key) {
Cache cache = getCache(cacheName);
if (null == cache) {
return false;
}
return cache.remove(key);
}
/**
* 删除全部缓存记录
* @param cacheName
* @return
*/
public static void removeAll(String cacheName) {
Cache cache = getCache(cacheName);
if (null != cache) {
cache.removeAll();
}
}
/**
* 获取缓存记录
* @param cacheName
* @param key
* @return
*/
public static Object get(String cacheName, String key) {
Cache cache = getCache(cacheName);
if (null == cache) {
return null;
}
Element cacheElement = cache.get(key);
if (null == cacheElement) {
return null;
}
return cacheElement.getObjectValue();
}
}
|
3e1294f0fc8996261bf92182ef530c1d75f95ec9 | 12,155 | java | Java | plugins/com.github.icelyframework.activitystorming/src/com/github/icelyframework/activitystorming/impl/DomainEventImpl.java | IcelyFramework/icely-activity-storming | 60bf490ba5cae7aff619f2c6ddf9be53b86c80a4 | [
"MIT"
] | 2 | 2021-01-12T20:54:29.000Z | 2021-01-18T17:10:48.000Z | plugins/com.github.icelyframework.activitystorming/src/com/github/icelyframework/activitystorming/impl/DomainEventImpl.java | IcelyFramework/icely-activity-storming | 60bf490ba5cae7aff619f2c6ddf9be53b86c80a4 | [
"MIT"
] | 1 | 2021-01-20T06:40:39.000Z | 2021-01-20T06:40:39.000Z | plugins/com.github.icelyframework.activitystorming/src/com/github/icelyframework/activitystorming/impl/DomainEventImpl.java | IcelyFramework/icely-activity-storming | 60bf490ba5cae7aff619f2c6ddf9be53b86c80a4 | [
"MIT"
] | null | null | null | 30.850254 | 162 | 0.710325 | 7,835 | /**
*/
package com.github.icelyframework.activitystorming.impl;
import com.github.icelyframework.activitystorming.ActivitystormingPackage;
import com.github.icelyframework.activitystorming.ConstraintPin;
import com.github.icelyframework.activitystorming.DomainEvent;
import com.github.icelyframework.activitystorming.ReadModel;
import com.github.icelyframework.activitystorming.Supplier;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Domain Event</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link com.github.icelyframework.activitystorming.impl.DomainEventImpl#getReadmodel <em>Readmodel</em>}</li>
* <li>{@link com.github.icelyframework.activitystorming.impl.DomainEventImpl#getSupplier <em>Supplier</em>}</li>
* <li>{@link com.github.icelyframework.activitystorming.impl.DomainEventImpl#getConstraint <em>Constraint</em>}</li>
* </ul>
*
* @generated
*/
public class DomainEventImpl extends ObjectNodeImpl implements DomainEvent {
/**
* The cached value of the '{@link #getReadmodel() <em>Readmodel</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReadmodel()
* @generated
* @ordered
*/
protected ReadModel readmodel;
/**
* The cached value of the '{@link #getSupplier() <em>Supplier</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSupplier()
* @generated
* @ordered
*/
protected Supplier supplier;
/**
* The cached value of the '{@link #getConstraint() <em>Constraint</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getConstraint()
* @generated
* @ordered
*/
protected ConstraintPin constraint;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DomainEventImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ActivitystormingPackage.Literals.DOMAIN_EVENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ReadModel getReadmodel() {
if (readmodel != null && readmodel.eIsProxy()) {
InternalEObject oldReadmodel = (InternalEObject)readmodel;
readmodel = (ReadModel)eResolveProxy(oldReadmodel);
if (readmodel != oldReadmodel) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ActivitystormingPackage.DOMAIN_EVENT__READMODEL, oldReadmodel, readmodel));
}
}
return readmodel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReadModel basicGetReadmodel() {
return readmodel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetReadmodel(ReadModel newReadmodel, NotificationChain msgs) {
ReadModel oldReadmodel = readmodel;
readmodel = newReadmodel;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ActivitystormingPackage.DOMAIN_EVENT__READMODEL, oldReadmodel, newReadmodel);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setReadmodel(ReadModel newReadmodel) {
if (newReadmodel != readmodel) {
NotificationChain msgs = null;
if (readmodel != null)
msgs = ((InternalEObject)readmodel).eInverseRemove(this, ActivitystormingPackage.READ_MODEL__EVENT, ReadModel.class, msgs);
if (newReadmodel != null)
msgs = ((InternalEObject)newReadmodel).eInverseAdd(this, ActivitystormingPackage.READ_MODEL__EVENT, ReadModel.class, msgs);
msgs = basicSetReadmodel(newReadmodel, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ActivitystormingPackage.DOMAIN_EVENT__READMODEL, newReadmodel, newReadmodel));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Supplier getSupplier() {
if (supplier != null && supplier.eIsProxy()) {
InternalEObject oldSupplier = (InternalEObject)supplier;
supplier = (Supplier)eResolveProxy(oldSupplier);
if (supplier != oldSupplier) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER, oldSupplier, supplier));
}
}
return supplier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Supplier basicGetSupplier() {
return supplier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSupplier(Supplier newSupplier, NotificationChain msgs) {
Supplier oldSupplier = supplier;
supplier = newSupplier;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER, oldSupplier, newSupplier);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setSupplier(Supplier newSupplier) {
if (newSupplier != supplier) {
NotificationChain msgs = null;
if (supplier != null)
msgs = ((InternalEObject)supplier).eInverseRemove(this, ActivitystormingPackage.SUPPLIER__TRIGGERS, Supplier.class, msgs);
if (newSupplier != null)
msgs = ((InternalEObject)newSupplier).eInverseAdd(this, ActivitystormingPackage.SUPPLIER__TRIGGERS, Supplier.class, msgs);
msgs = basicSetSupplier(newSupplier, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER, newSupplier, newSupplier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ConstraintPin getConstraint() {
if (constraint != null && constraint.eIsProxy()) {
InternalEObject oldConstraint = (InternalEObject)constraint;
constraint = (ConstraintPin)eResolveProxy(oldConstraint);
if (constraint != oldConstraint) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT, oldConstraint, constraint));
}
}
return constraint;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConstraintPin basicGetConstraint() {
return constraint;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetConstraint(ConstraintPin newConstraint, NotificationChain msgs) {
ConstraintPin oldConstraint = constraint;
constraint = newConstraint;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT, oldConstraint, newConstraint);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setConstraint(ConstraintPin newConstraint) {
if (newConstraint != constraint) {
NotificationChain msgs = null;
if (constraint != null)
msgs = ((InternalEObject)constraint).eInverseRemove(this, ActivitystormingPackage.CONSTRAINT_PIN__TRIGGERS, ConstraintPin.class, msgs);
if (newConstraint != null)
msgs = ((InternalEObject)newConstraint).eInverseAdd(this, ActivitystormingPackage.CONSTRAINT_PIN__TRIGGERS, ConstraintPin.class, msgs);
msgs = basicSetConstraint(newConstraint, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT, newConstraint, newConstraint));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ActivitystormingPackage.DOMAIN_EVENT__READMODEL:
if (readmodel != null)
msgs = ((InternalEObject)readmodel).eInverseRemove(this, ActivitystormingPackage.READ_MODEL__EVENT, ReadModel.class, msgs);
return basicSetReadmodel((ReadModel)otherEnd, msgs);
case ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER:
if (supplier != null)
msgs = ((InternalEObject)supplier).eInverseRemove(this, ActivitystormingPackage.SUPPLIER__TRIGGERS, Supplier.class, msgs);
return basicSetSupplier((Supplier)otherEnd, msgs);
case ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT:
if (constraint != null)
msgs = ((InternalEObject)constraint).eInverseRemove(this, ActivitystormingPackage.CONSTRAINT_PIN__TRIGGERS, ConstraintPin.class, msgs);
return basicSetConstraint((ConstraintPin)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ActivitystormingPackage.DOMAIN_EVENT__READMODEL:
return basicSetReadmodel(null, msgs);
case ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER:
return basicSetSupplier(null, msgs);
case ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT:
return basicSetConstraint(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ActivitystormingPackage.DOMAIN_EVENT__READMODEL:
if (resolve) return getReadmodel();
return basicGetReadmodel();
case ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER:
if (resolve) return getSupplier();
return basicGetSupplier();
case ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT:
if (resolve) return getConstraint();
return basicGetConstraint();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ActivitystormingPackage.DOMAIN_EVENT__READMODEL:
setReadmodel((ReadModel)newValue);
return;
case ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER:
setSupplier((Supplier)newValue);
return;
case ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT:
setConstraint((ConstraintPin)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ActivitystormingPackage.DOMAIN_EVENT__READMODEL:
setReadmodel((ReadModel)null);
return;
case ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER:
setSupplier((Supplier)null);
return;
case ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT:
setConstraint((ConstraintPin)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ActivitystormingPackage.DOMAIN_EVENT__READMODEL:
return readmodel != null;
case ActivitystormingPackage.DOMAIN_EVENT__SUPPLIER:
return supplier != null;
case ActivitystormingPackage.DOMAIN_EVENT__CONSTRAINT:
return constraint != null;
}
return super.eIsSet(featureID);
}
} //DomainEventImpl
|
3e12957795cae296a36d59d2a2aa0411bb59bdd4 | 636 | java | Java | AlbUtil/src/alb/util/exception/NotYetImplementedException.java | sofimrtn/Gestion_Hospital_IPS | ce484523efc391cd43d39662c208c4cf83fde6e6 | [
"MIT"
] | null | null | null | AlbUtil/src/alb/util/exception/NotYetImplementedException.java | sofimrtn/Gestion_Hospital_IPS | ce484523efc391cd43d39662c208c4cf83fde6e6 | [
"MIT"
] | null | null | null | AlbUtil/src/alb/util/exception/NotYetImplementedException.java | sofimrtn/Gestion_Hospital_IPS | ce484523efc391cd43d39662c208c4cf83fde6e6 | [
"MIT"
] | null | null | null | 23.555556 | 94 | 0.792453 | 7,836 | package alb.util.exception;
public class NotYetImplementedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotYetImplementedException() {
}
public NotYetImplementedException(String message) {
super(message);
}
public NotYetImplementedException(Throwable cause) {
super(cause);
}
public NotYetImplementedException(String message, Throwable cause) {
super(message, cause);
}
public NotYetImplementedException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
3e12965fa9c016f2f44ac1a9c8bde3318aeb690f | 3,100 | java | Java | google/cloud/gaming/v1/google-cloud-gaming-v1-java/proto-google-cloud-gaming-v1-java/src/main/java/com/google/cloud/gaming/v1/ScheduleOrBuilder.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/gaming/v1/google-cloud-gaming-v1-java/proto-google-cloud-gaming-v1-java/src/main/java/com/google/cloud/gaming/v1/ScheduleOrBuilder.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/gaming/v1/google-cloud-gaming-v1-java/proto-google-cloud-gaming-v1-java/src/main/java/com/google/cloud/gaming/v1/ScheduleOrBuilder.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | 26.271186 | 82 | 0.641935 | 7,837 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/gaming/v1/common.proto
package com.google.cloud.gaming.v1;
public interface ScheduleOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.gaming.v1.Schedule)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The start time of the event.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 1;</code>
* @return Whether the startTime field is set.
*/
boolean hasStartTime();
/**
* <pre>
* The start time of the event.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 1;</code>
* @return The startTime.
*/
com.google.protobuf.Timestamp getStartTime();
/**
* <pre>
* The start time of the event.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 1;</code>
*/
com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder();
/**
* <pre>
* The end time of the event.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 2;</code>
* @return Whether the endTime field is set.
*/
boolean hasEndTime();
/**
* <pre>
* The end time of the event.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 2;</code>
* @return The endTime.
*/
com.google.protobuf.Timestamp getEndTime();
/**
* <pre>
* The end time of the event.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 2;</code>
*/
com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder();
/**
* <pre>
* The duration for the cron job event. The duration of the event is effective
* after the cron job's start time.
* </pre>
*
* <code>.google.protobuf.Duration cron_job_duration = 3;</code>
* @return Whether the cronJobDuration field is set.
*/
boolean hasCronJobDuration();
/**
* <pre>
* The duration for the cron job event. The duration of the event is effective
* after the cron job's start time.
* </pre>
*
* <code>.google.protobuf.Duration cron_job_duration = 3;</code>
* @return The cronJobDuration.
*/
com.google.protobuf.Duration getCronJobDuration();
/**
* <pre>
* The duration for the cron job event. The duration of the event is effective
* after the cron job's start time.
* </pre>
*
* <code>.google.protobuf.Duration cron_job_duration = 3;</code>
*/
com.google.protobuf.DurationOrBuilder getCronJobDurationOrBuilder();
/**
* <pre>
* The cron definition of the scheduled event. See
* https://en.wikipedia.org/wiki/Cron. Cron spec specifies the local time as
* defined by the realm.
* </pre>
*
* <code>string cron_spec = 4;</code>
* @return The cronSpec.
*/
java.lang.String getCronSpec();
/**
* <pre>
* The cron definition of the scheduled event. See
* https://en.wikipedia.org/wiki/Cron. Cron spec specifies the local time as
* defined by the realm.
* </pre>
*
* <code>string cron_spec = 4;</code>
* @return The bytes for cronSpec.
*/
com.google.protobuf.ByteString
getCronSpecBytes();
}
|
3e1296f9094b6f43e921df81c08210017cf59a34 | 79 | java | Java | Paipai/TEst1107/src/Master.java | EmmaLiuPie/Sisters-coding | ea4c3c1419e32a0911b18af320984a913e286dcb | [
"Unlicense"
] | 2 | 2020-11-12T03:23:14.000Z | 2020-11-12T06:10:58.000Z | Paipai/TEst1107/src/Master.java | EmmaLiuPie/Sisters-coding | ea4c3c1419e32a0911b18af320984a913e286dcb | [
"Unlicense"
] | null | null | null | Paipai/TEst1107/src/Master.java | EmmaLiuPie/Sisters-coding | ea4c3c1419e32a0911b18af320984a913e286dcb | [
"Unlicense"
] | null | null | null | 11.285714 | 29 | 0.493671 | 7,838 | public class Master {
public void feed(Pet p){
p.eat();
}
}
|
3e129811d0e23363f8ed193a07465e6cb5c55bc2 | 1,102 | java | Java | src/main/java/org/leaguemodel/interfaces/IPlayers.java | kethan-kumar/DHL | f0c6a7c81dbb31001fd23f2e7ab99c5231c0e20b | [
"Apache-2.0"
] | 1 | 2021-05-08T07:16:06.000Z | 2021-05-08T07:16:06.000Z | src/main/java/org/leaguemodel/interfaces/IPlayers.java | kethan-kumar/DHL | f0c6a7c81dbb31001fd23f2e7ab99c5231c0e20b | [
"Apache-2.0"
] | null | null | null | src/main/java/org/leaguemodel/interfaces/IPlayers.java | kethan-kumar/DHL | f0c6a7c81dbb31001fd23f2e7ab99c5231c0e20b | [
"Apache-2.0"
] | null | null | null | 17.21875 | 49 | 0.700544 | 7,839 | /* @Author: Siddhant Ashutosh */
package org.leaguemodel.interfaces;
public interface IPlayers {
Integer getSaving();
void setSaving(Integer saving);
String getPosition();
void setPosition(String position);
String getPlayerName();
void setPlayerName(String playerName);
boolean isCaptain();
void setCaptain(boolean isCaptain);
void setIsCaptain(boolean captain);
Integer getAge();
void setAge(Integer age);
Integer getSkating();
void setSkating(Integer skating);
Integer getShooting();
void setShooting(Integer shooting);
Integer getChecking();
void setChecking(Integer checking);
int getNoOfDaysInjured();
void setNoOfDaysInjured(int noOfDaysInjured);
boolean isRetired();
void setRetired(boolean retired);
Integer getBirthDay();
void setBirthDay(Integer birthDay);
Integer getBirthMonth();
void setBirthMonth(Integer birthMonth);
Integer getBirthYear();
void setBirthYear(Integer birthYear);
boolean getIsActive();
void setIsActive(boolean isActive);
}
|
3e12987828b34a6634a5404ff1fee46e4ab73177 | 1,010 | java | Java | src/main/java/com/example/ejemplomongo/model/entities/Cliente.java | hulkike-spring/springboot-mongo | 60c7f75e9064382b2d6ce334cc063f6cf3f699a7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/ejemplomongo/model/entities/Cliente.java | hulkike-spring/springboot-mongo | 60c7f75e9064382b2d6ce334cc063f6cf3f699a7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/ejemplomongo/model/entities/Cliente.java | hulkike-spring/springboot-mongo | 60c7f75e9064382b2d6ce334cc063f6cf3f699a7 | [
"Apache-2.0"
] | null | null | null | 21.489362 | 113 | 0.709901 | 7,840 | package com.example.ejemplomongo.model.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="clientes")// como se va llamar la coleccion en mongo
public class Cliente {
@Id
private int idCliente;
private String nombre;
private String direccion;
private int edad;
public int getIdCliente() {
return idCliente;
}
public void setIdCliente(int idCliente) {
this.idCliente = idCliente;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
@Override
public String toString() {
return "Cliente [idCliente=" + idCliente + ", nombre=" + nombre + ", direccion=" + direccion + ", edad=" + edad
+ "]";
}
}
|
3e1298a36878fcb0c31edc20d22d4e0b656f7b0b | 6,627 | java | Java | src/test/java/org/simplify4u/plugins/sign/openpgp/PGPKeyInfoTest.java | s4u/sign-maven-plugin | 31a1a1081a2420f8287378960d3491b4386b0613 | [
"Apache-2.0"
] | 36 | 2020-12-19T14:18:37.000Z | 2021-12-28T03:11:46.000Z | src/test/java/org/simplify4u/plugins/sign/openpgp/PGPKeyInfoTest.java | s4u/sign-maven-plugin | 31a1a1081a2420f8287378960d3491b4386b0613 | [
"Apache-2.0"
] | 107 | 2020-12-19T09:40:22.000Z | 2022-03-14T23:50:49.000Z | src/test/java/org/simplify4u/plugins/sign/openpgp/PGPKeyInfoTest.java | s4u/sign-maven-plugin | 31a1a1081a2420f8287378960d3491b4386b0613 | [
"Apache-2.0"
] | 4 | 2020-12-28T14:11:24.000Z | 2021-04-21T13:52:11.000Z | 36.016304 | 115 | 0.655349 | 7,841 | /*
* Copyright 2020 Slawomir Jaranowski
*
* 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.simplify4u.plugins.sign.openpgp;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junitpioneer.jupiter.SetEnvironmentVariable;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
@ExtendWith(MockitoExtension.class)
class PGPKeyInfoTest {
private static final String KEY_ID_STR = "ABCDEF0123456789";
private static final long KEY_ID = 0xABCDEF0123456789L;
private static final String KEY_PASS_STR = "pass";
private static final char[] KEY_PASS = KEY_PASS_STR.toCharArray();
private static final File KEY_FILE = new File(PGPKeyInfo.class.getResource("/priv-key-no-pass.asc").getFile());
@Mock(name = "org.simplify4u.plugins.sign.openpgp.PGPKeyInfo")
Logger logger;
@Test
void keyFromFileAllPropertiesSet() throws IOException {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.keyId(KEY_ID_STR)
.keyPass(KEY_PASS_STR)
.keyFile(KEY_FILE)
.build();
// then
assertThat(keyInfo.getId()).isEqualTo(KEY_ID);
assertThat(keyInfo.getPass()).isEqualTo(KEY_PASS);
assertThat(keyInfo.getKey()).hasSameContentAs(Files.newInputStream(KEY_FILE.toPath()));
verify(logger).debug("No {} set as environment variable", "SIGN_KEY_ID");
verify(logger).debug("No {} set as environment variable", "SIGN_KEY_PASS");
verify(logger).debug("No {} set as environment variable", "SIGN_KEY");
verifyNoMoreInteractions(logger);
}
@Test
void keyFromFile() throws IOException {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.keyFile(KEY_FILE)
.build();
// then
assertThat(keyInfo.getId()).isNull();
assertThat(keyInfo.getPass()).isNull();
assertThat(keyInfo.getKey()).hasSameContentAs(Files.newInputStream(KEY_FILE.toPath()));
}
@Test
@SetEnvironmentVariable(key = "SIGN_KEY", value = "signKey from environment")
@SetEnvironmentVariable(key = "SIGN_KEY_ID", value = KEY_ID_STR)
@SetEnvironmentVariable(key = "SIGN_KEY_PASS", value = KEY_PASS_STR)
void keyDataFromEnv() {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.keyId("aaa")
.keyPass("bbb")
.keyFile(new File("fff"))
.build();
// then
assertThat(keyInfo.getId()).isEqualTo(KEY_ID);
assertThat(keyInfo.getPass()).isEqualTo(KEY_PASS);
assertThat(keyInfo.getKey()).hasContent("signKey from environment");
verify(logger).debug("Retrieved {} configuration from environment variable", "SIGN_KEY_ID");
verify(logger).debug("Retrieved {} configuration from environment variable", "SIGN_KEY_PASS");
verify(logger).debug("Retrieved {} configuration from environment variable", "SIGN_KEY");
verifyNoMoreInteractions(logger);
}
@Test
@SetEnvironmentVariable(key = "SIGN_KEY", value = "")
@SetEnvironmentVariable(key = "SIGN_KEY_ID", value = "")
@SetEnvironmentVariable(key = "SIGN_KEY_PASS", value = "")
void allowEmptyValueInEnvVariable() throws IOException {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.keyId(KEY_ID_STR)
.keyPass(KEY_PASS_STR)
.keyFile(KEY_FILE)
.build();
// then
assertThat(keyInfo.getId()).isEqualTo(KEY_ID);
assertThat(keyInfo.getPass()).isEqualTo(KEY_PASS);
assertThat(keyInfo.getKey()).hasSameContentAs(Files.newInputStream(KEY_FILE.toPath()));
verify(logger).debug("No {} set as environment variable", "SIGN_KEY_ID");
verify(logger).debug("No {} set as environment variable", "SIGN_KEY_PASS");
verify(logger).debug("No {} set as environment variable", "SIGN_KEY");
verifyNoMoreInteractions(logger);
}
@Test
@SetEnvironmentVariable(key = "SIGN_KEY", value = "signKey from environment")
void keyFromEnvWithFile() {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.keyFile(KEY_FILE)
.build();
// then
assertThat(keyInfo.getId()).isNull();
assertThat(keyInfo.getPass()).isNull();
assertThat(keyInfo.getKey()).hasContent("signKey from environment");
}
@Test
void invalidKeyIdThrowException() {
PGPKeyInfo.PGPKeyInfoBuilder keyInfoBuilder = PGPKeyInfo.builder()
.keyId("xxx");
assertThatThrownBy(keyInfoBuilder::build)
.isExactlyInstanceOf(PGPSignerException.class)
.hasMessageStartingWith("Invalid keyId: For input string: \"xxx\"")
.hasNoCause();
}
@Test
@SetEnvironmentVariable(key = "SIGN_KEY", value = "signKey from environment")
@SetEnvironmentVariable(key = "SIGN_KEY_ID", value = "null")
void nullStringInEnvironmentValueShouldBeFiltered() {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.build();
// then
assertThat(keyInfo.getId()).isNull();
assertThat(keyInfo.getPass()).isNull();
assertThat(keyInfo.getKey()).hasContent("signKey from environment");
}
@Test
void passDecryptorShouldBeCalled() {
// when
PGPKeyInfo keyInfo = PGPKeyInfo.builder()
.passDecryptor(String::toUpperCase)
.keyPass(KEY_PASS_STR)
.keyFile(KEY_FILE)
.build();
// then
assertThat(keyInfo.getPass()).isEqualTo(KEY_PASS_STR.toUpperCase().toCharArray());
}
}
|
3e1298bead2ff9ba6bfb3d302d88f8daf5aa97c6 | 30,231 | java | Java | build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/client/gui/screens/Screen.java | AlgorithmLX/IndustrialLevel | 727d90a9404c2967ec2d3ba8dadbd1276b1ad81f | [
"MIT"
] | null | null | null | build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/client/gui/screens/Screen.java | AlgorithmLX/IndustrialLevel | 727d90a9404c2967ec2d3ba8dadbd1276b1ad81f | [
"MIT"
] | null | null | null | build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/client/gui/screens/Screen.java | AlgorithmLX/IndustrialLevel | 727d90a9404c2967ec2d3ba8dadbd1276b1ad81f | [
"MIT"
] | null | null | null | 44.326979 | 244 | 0.69313 | 7,842 | package net.minecraft.client.gui.screens;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.BufferUploader;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import com.mojang.math.Matrix4f;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.CrashReport;
import net.minecraft.CrashReportCategory;
import net.minecraft.ReportedException;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.client.gui.components.Widget;
import net.minecraft.client.gui.components.events.AbstractContainerEventHandler;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.narration.NarratableEntry;
import net.minecraft.client.gui.narration.NarratedElementType;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.narration.ScreenNarrationCollector;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@OnlyIn(Dist.CLIENT)
public abstract class Screen extends AbstractContainerEventHandler implements Widget {
private static final Logger LOGGER = LogManager.getLogger();
private static final Set<String> ALLOWED_PROTOCOLS = Sets.newHashSet("http", "https");
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
private static final Component USAGE_NARRATION = new TranslatableComponent("narrator.screen.usage");
protected final Component title;
private final List<GuiEventListener> children = Lists.newArrayList();
private final List<NarratableEntry> narratables = Lists.newArrayList();
@Nullable
protected Minecraft minecraft;
protected ItemRenderer itemRenderer;
public int width;
public int height;
public final List<Widget> renderables = Lists.newArrayList();
public boolean passEvents;
protected Font font;
@Nullable
private URI clickedLink;
private static final long NARRATE_SUPPRESS_AFTER_INIT_TIME = TimeUnit.SECONDS.toMillis(2L);
private static final long NARRATE_DELAY_NARRATOR_ENABLED = NARRATE_SUPPRESS_AFTER_INIT_TIME;
private static final long NARRATE_DELAY_MOUSE_MOVE = 750L;
private static final long NARRATE_DELAY_MOUSE_ACTION = 200L;
private static final long NARRATE_DELAY_KEYBOARD_ACTION = 200L;
private final ScreenNarrationCollector narrationState = new ScreenNarrationCollector();
private long narrationSuppressTime = Long.MIN_VALUE;
private long nextNarrationTime = Long.MAX_VALUE;
@Nullable
private NarratableEntry lastNarratable;
protected Screen(Component p_96550_) {
this.title = p_96550_;
}
public Component getTitle() {
return this.title;
}
public Component getNarrationMessage() {
return this.getTitle();
}
public void render(PoseStack p_96562_, int p_96563_, int p_96564_, float p_96565_) {
for(Widget widget : this.renderables) {
widget.render(p_96562_, p_96563_, p_96564_, p_96565_);
}
}
public boolean keyPressed(int p_96552_, int p_96553_, int p_96554_) {
if (p_96552_ == 256 && this.shouldCloseOnEsc()) {
this.onClose();
return true;
} else if (p_96552_ == 258) {
boolean flag = !hasShiftDown();
if (!this.changeFocus(flag)) {
this.changeFocus(flag);
}
return false;
} else {
return super.keyPressed(p_96552_, p_96553_, p_96554_);
}
}
public boolean shouldCloseOnEsc() {
return true;
}
public void onClose() {
this.minecraft.popGuiLayer();
}
protected <T extends GuiEventListener & Widget & NarratableEntry> T addRenderableWidget(T p_169406_) {
this.renderables.add(p_169406_);
return this.addWidget(p_169406_);
}
protected <T extends Widget> T addRenderableOnly(T p_169395_) {
this.renderables.add(p_169395_);
return p_169395_;
}
protected <T extends GuiEventListener & NarratableEntry> T addWidget(T p_96625_) {
this.children.add(p_96625_);
this.narratables.add(p_96625_);
return p_96625_;
}
protected void removeWidget(GuiEventListener p_169412_) {
if (p_169412_ instanceof Widget) {
this.renderables.remove((Widget)p_169412_);
}
if (p_169412_ instanceof NarratableEntry) {
this.narratables.remove((NarratableEntry)p_169412_);
}
this.children.remove(p_169412_);
}
protected void clearWidgets() {
this.renderables.clear();
this.children.clear();
this.narratables.clear();
}
private Font tooltipFont = null;
private ItemStack tooltipStack = ItemStack.EMPTY;
protected void renderTooltip(PoseStack p_96566_, ItemStack p_96567_, int p_96568_, int p_96569_) {
tooltipStack = p_96567_;
this.renderTooltip(p_96566_, this.getTooltipFromItem(p_96567_), p_96567_.getTooltipImage(), p_96568_, p_96569_);
tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(PoseStack poseStack, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, int x, int y, ItemStack stack) {
this.renderTooltip(poseStack, textComponents, tooltipComponent, x, y, null, stack);
}
public void renderTooltip(PoseStack poseStack, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, int x, int y, @Nullable Font font) {
this.renderTooltip(poseStack, textComponents, tooltipComponent, x, y, font, ItemStack.EMPTY);
}
public void renderTooltip(PoseStack poseStack, List<Component> textComponents, Optional<TooltipComponent> tooltipComponent, int x, int y, @Nullable Font font, ItemStack stack) {
this.tooltipFont = font;
this.tooltipStack = stack;
this.renderTooltip(poseStack, textComponents, tooltipComponent, x, y);
this.tooltipFont = null;
this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(PoseStack p_169389_, List<Component> p_169390_, Optional<TooltipComponent> p_169391_, int p_169392_, int p_169393_) {
List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_169390_, p_169391_, p_169392_, width, height, this.tooltipFont, this.font);
this.renderTooltipInternal(p_169389_, list, p_169392_, p_169393_);
}
public List<Component> getTooltipFromItem(ItemStack p_96556_) {
return p_96556_.getTooltipLines(this.minecraft.player, this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL);
}
public void renderTooltip(PoseStack p_96603_, Component p_96604_, int p_96605_, int p_96606_) {
this.renderTooltip(p_96603_, Arrays.asList(p_96604_.getVisualOrderText()), p_96605_, p_96606_);
}
public void renderComponentTooltip(PoseStack p_96598_, List<Component> p_96599_, int p_96600_, int p_96601_) {
List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_96599_, p_96600_, width, height, this.tooltipFont, this.font);
this.renderTooltipInternal(p_96598_, components, p_96600_, p_96601_);
}
public void renderComponentTooltip(PoseStack poseStack, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, ItemStack stack) {
this.renderComponentTooltip(poseStack, tooltips, mouseX, mouseY, null, stack);
}
public void renderComponentTooltip(PoseStack poseStack, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, @Nullable Font font) {
this.renderComponentTooltip(poseStack, tooltips, mouseX, mouseY, font, ItemStack.EMPTY);
}
public void renderComponentTooltip(PoseStack poseStack, List<? extends net.minecraft.network.chat.FormattedText> tooltips, int mouseX, int mouseY, @Nullable Font font, ItemStack stack) {
this.tooltipFont = font;
this.tooltipStack = stack;
List<ClientTooltipComponent> components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(stack, tooltips, mouseX, width, height, this.tooltipFont, this.font);
this.renderTooltipInternal(poseStack, components, mouseX, mouseY);
this.tooltipFont = null;
this.tooltipStack = ItemStack.EMPTY;
}
public void renderTooltip(PoseStack p_96618_, List<? extends FormattedCharSequence> p_96619_, int p_96620_, int p_96621_) {
this.renderTooltipInternal(p_96618_, p_96619_.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), p_96620_, p_96621_);
}
public void renderTooltip(PoseStack poseStack, List<? extends FormattedCharSequence> lines, int x, int y, Font font) {
this.tooltipFont = font;
this.renderTooltip(poseStack, lines, x, y);
this.tooltipFont = null;
}
private void renderTooltipInternal(PoseStack p_169384_, List<ClientTooltipComponent> p_169385_, int p_169386_, int p_169387_) {
if (!p_169385_.isEmpty()) {
net.minecraftforge.client.event.RenderTooltipEvent.Pre preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(this.tooltipStack, p_169384_, p_169386_, p_169387_, width, height, p_169385_, this.tooltipFont, this.font);
if (preEvent.isCanceled()) return;
int i = 0;
int j = p_169385_.size() == 1 ? -2 : 0;
for(ClientTooltipComponent clienttooltipcomponent : p_169385_) {
int k = clienttooltipcomponent.getWidth(preEvent.getFont());
if (k > i) {
i = k;
}
j += clienttooltipcomponent.getHeight();
}
int j2 = preEvent.getX() + 12;
int k2 = preEvent.getY() - 12;
if (j2 + i > this.width) {
j2 -= 28 + i;
}
if (k2 + j + 6 > this.height) {
k2 = this.height - j - 6;
}
p_169384_.pushPose();
int l = -267386864;
int i1 = 1347420415;
int j1 = 1344798847;
int k1 = 400;
float f = this.itemRenderer.blitOffset;
this.itemRenderer.blitOffset = 400.0F;
Tesselator tesselator = Tesselator.getInstance();
BufferBuilder bufferbuilder = tesselator.getBuilder();
RenderSystem.setShader(GameRenderer::getPositionColorShader);
bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
Matrix4f matrix4f = p_169384_.last().pose();
net.minecraftforge.client.event.RenderTooltipEvent.Color colorEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipColor(this.tooltipStack, p_169384_, j2, k2, preEvent.getFont(), p_169385_);
fillGradient(matrix4f, bufferbuilder, j2 - 3, k2 - 4, j2 + i + 3, k2 - 3, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundStart());
fillGradient(matrix4f, bufferbuilder, j2 - 3, k2 + j + 3, j2 + i + 3, k2 + j + 4, 400, colorEvent.getBackgroundEnd(), colorEvent.getBackgroundEnd());
fillGradient(matrix4f, bufferbuilder, j2 - 3, k2 - 3, j2 + i + 3, k2 + j + 3, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd());
fillGradient(matrix4f, bufferbuilder, j2 - 4, k2 - 3, j2 - 3, k2 + j + 3, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd());
fillGradient(matrix4f, bufferbuilder, j2 + i + 3, k2 - 3, j2 + i + 4, k2 + j + 3, 400, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd());
fillGradient(matrix4f, bufferbuilder, j2 - 3, k2 - 3 + 1, j2 - 3 + 1, k2 + j + 3 - 1, 400, colorEvent.getBorderStart(), colorEvent.getBorderEnd());
fillGradient(matrix4f, bufferbuilder, j2 + i + 2, k2 - 3 + 1, j2 + i + 3, k2 + j + 3 - 1, 400, colorEvent.getBorderStart(), colorEvent.getBorderEnd());
fillGradient(matrix4f, bufferbuilder, j2 - 3, k2 - 3, j2 + i + 3, k2 - 3 + 1, 400, colorEvent.getBorderStart(), colorEvent.getBorderStart());
fillGradient(matrix4f, bufferbuilder, j2 - 3, k2 + j + 2, j2 + i + 3, k2 + j + 3, 400, colorEvent.getBorderEnd(), colorEvent.getBorderEnd());
RenderSystem.enableDepthTest();
RenderSystem.disableTexture();
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
bufferbuilder.end();
BufferUploader.end(bufferbuilder);
RenderSystem.disableBlend();
RenderSystem.enableTexture();
MultiBufferSource.BufferSource multibuffersource$buffersource = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
p_169384_.translate(0.0D, 0.0D, 400.0D);
int l1 = k2;
for(int i2 = 0; i2 < p_169385_.size(); ++i2) {
ClientTooltipComponent clienttooltipcomponent1 = p_169385_.get(i2);
clienttooltipcomponent1.renderText(preEvent.getFont(), j2, l1, matrix4f, multibuffersource$buffersource);
l1 += clienttooltipcomponent1.getHeight() + (i2 == 0 ? 2 : 0);
}
multibuffersource$buffersource.endBatch();
p_169384_.popPose();
l1 = k2;
for(int l2 = 0; l2 < p_169385_.size(); ++l2) {
ClientTooltipComponent clienttooltipcomponent2 = p_169385_.get(l2);
clienttooltipcomponent2.renderImage(preEvent.getFont(), j2, l1, p_169384_, this.itemRenderer, 400);
l1 += clienttooltipcomponent2.getHeight() + (l2 == 0 ? 2 : 0);
}
this.itemRenderer.blitOffset = f;
}
}
protected void renderComponentHoverEffect(PoseStack p_96571_, @Nullable Style p_96572_, int p_96573_, int p_96574_) {
if (p_96572_ != null && p_96572_.getHoverEvent() != null) {
HoverEvent hoverevent = p_96572_.getHoverEvent();
HoverEvent.ItemStackInfo hoverevent$itemstackinfo = hoverevent.getValue(HoverEvent.Action.SHOW_ITEM);
if (hoverevent$itemstackinfo != null) {
this.renderTooltip(p_96571_, hoverevent$itemstackinfo.getItemStack(), p_96573_, p_96574_);
} else {
HoverEvent.EntityTooltipInfo hoverevent$entitytooltipinfo = hoverevent.getValue(HoverEvent.Action.SHOW_ENTITY);
if (hoverevent$entitytooltipinfo != null) {
if (this.minecraft.options.advancedItemTooltips) {
this.renderComponentTooltip(p_96571_, hoverevent$entitytooltipinfo.getTooltipLines(), p_96573_, p_96574_);
}
} else {
Component component = hoverevent.getValue(HoverEvent.Action.SHOW_TEXT);
if (component != null) {
this.renderTooltip(p_96571_, this.minecraft.font.split(component, Math.max(this.width / 2, 200)), p_96573_, p_96574_);
}
}
}
}
}
protected void insertText(String p_96587_, boolean p_96588_) {
}
public boolean handleComponentClicked(@Nullable Style p_96592_) {
if (p_96592_ == null) {
return false;
} else {
ClickEvent clickevent = p_96592_.getClickEvent();
if (hasShiftDown()) {
if (p_96592_.getInsertion() != null) {
this.insertText(p_96592_.getInsertion(), false);
}
} else if (clickevent != null) {
if (clickevent.getAction() == ClickEvent.Action.OPEN_URL) {
if (!this.minecraft.options.chatLinks) {
return false;
}
try {
URI uri = new URI(clickevent.getValue());
String s = uri.getScheme();
if (s == null) {
throw new URISyntaxException(clickevent.getValue(), "Missing protocol");
}
if (!ALLOWED_PROTOCOLS.contains(s.toLowerCase(Locale.ROOT))) {
throw new URISyntaxException(clickevent.getValue(), "Unsupported protocol: " + s.toLowerCase(Locale.ROOT));
}
if (this.minecraft.options.chatLinksPrompt) {
this.clickedLink = uri;
this.minecraft.setScreen(new ConfirmLinkScreen(this::confirmLink, clickevent.getValue(), false));
} else {
this.openLink(uri);
}
} catch (URISyntaxException urisyntaxexception) {
LOGGER.error("Can't open url for {}", clickevent, urisyntaxexception);
}
} else if (clickevent.getAction() == ClickEvent.Action.OPEN_FILE) {
URI uri1 = (new File(clickevent.getValue())).toURI();
this.openLink(uri1);
} else if (clickevent.getAction() == ClickEvent.Action.SUGGEST_COMMAND) {
this.insertText(clickevent.getValue(), true);
} else if (clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) {
this.sendMessage(clickevent.getValue(), false);
} else if (clickevent.getAction() == ClickEvent.Action.COPY_TO_CLIPBOARD) {
this.minecraft.keyboardHandler.setClipboard(clickevent.getValue());
} else {
LOGGER.error("Don't know how to handle {}", (Object)clickevent);
}
return true;
}
return false;
}
}
public void sendMessage(String p_96616_) {
this.sendMessage(p_96616_, true);
}
public void sendMessage(String p_96613_, boolean p_96614_) {
p_96613_ = net.minecraftforge.event.ForgeEventFactory.onClientSendMessage(p_96613_);
if (p_96613_.isEmpty()) return;
if (p_96614_) {
this.minecraft.gui.getChat().addRecentChat(p_96613_);
}
//if (net.minecraftforge.client.ClientCommandHandler.instance.executeCommand(mc.player, msg) != 0) return; //Forge: TODO Client command re-write
this.minecraft.player.chat(p_96613_);
}
public final void init(Minecraft p_96607_, int p_96608_, int p_96609_) {
this.minecraft = p_96607_;
this.itemRenderer = p_96607_.getItemRenderer();
this.font = p_96607_.font;
this.width = p_96608_;
this.height = p_96609_;
java.util.function.Consumer<GuiEventListener> add = (b) -> {
if (b instanceof Widget w)
this.renderables.add(w);
if (b instanceof NarratableEntry ne)
this.narratables.add(ne);
children.add(b);
};
if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.InitScreenEvent.Pre(this, this.children, add, this::removeWidget))) {
this.clearWidgets();
this.setFocused((GuiEventListener)null);
this.init();
this.triggerImmediateNarration(false);
this.suppressNarration(NARRATE_SUPPRESS_AFTER_INIT_TIME);
}
net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.InitScreenEvent.Post(this, this.children, add, this::removeWidget));
}
public List<? extends GuiEventListener> children() {
return this.children;
}
protected void init() {
}
public void tick() {
}
public void removed() {
}
public void renderBackground(PoseStack p_96557_) {
this.renderBackground(p_96557_, 0);
}
public void renderBackground(PoseStack p_96559_, int p_96560_) {
if (this.minecraft.level != null) {
this.fillGradient(p_96559_, 0, 0, this.width, this.height, -1072689136, -804253680);
net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundDrawnEvent(this, p_96559_));
} else {
this.renderDirtBackground(p_96560_);
}
}
public void renderDirtBackground(int p_96627_) {
Tesselator tesselator = Tesselator.getInstance();
BufferBuilder bufferbuilder = tesselator.getBuilder();
RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
RenderSystem.setShaderTexture(0, BACKGROUND_LOCATION);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
float f = 32.0F;
bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
bufferbuilder.vertex(0.0D, (double)this.height, 0.0D).uv(0.0F, (float)this.height / 32.0F + (float)p_96627_).color(64, 64, 64, 255).endVertex();
bufferbuilder.vertex((double)this.width, (double)this.height, 0.0D).uv((float)this.width / 32.0F, (float)this.height / 32.0F + (float)p_96627_).color(64, 64, 64, 255).endVertex();
bufferbuilder.vertex((double)this.width, 0.0D, 0.0D).uv((float)this.width / 32.0F, (float)p_96627_).color(64, 64, 64, 255).endVertex();
bufferbuilder.vertex(0.0D, 0.0D, 0.0D).uv(0.0F, (float)p_96627_).color(64, 64, 64, 255).endVertex();
tesselator.end();
net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.ScreenEvent.BackgroundDrawnEvent(this, new PoseStack()));
}
public boolean isPauseScreen() {
return true;
}
private void confirmLink(boolean p_96623_) {
if (p_96623_) {
this.openLink(this.clickedLink);
}
this.clickedLink = null;
this.minecraft.setScreen(this);
}
private void openLink(URI p_96590_) {
Util.getPlatform().openUri(p_96590_);
}
public static boolean hasControlDown() {
if (Minecraft.ON_OSX) {
return InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 343) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 347);
} else {
return InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 341) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 345);
}
}
public static boolean hasShiftDown() {
return InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 340) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 344);
}
public static boolean hasAltDown() {
return InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 342) || InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 346);
}
public static boolean isCut(int p_96629_) {
return p_96629_ == 88 && hasControlDown() && !hasShiftDown() && !hasAltDown();
}
public static boolean isPaste(int p_96631_) {
return p_96631_ == 86 && hasControlDown() && !hasShiftDown() && !hasAltDown();
}
public static boolean isCopy(int p_96633_) {
return p_96633_ == 67 && hasControlDown() && !hasShiftDown() && !hasAltDown();
}
public static boolean isSelectAll(int p_96635_) {
return p_96635_ == 65 && hasControlDown() && !hasShiftDown() && !hasAltDown();
}
public void resize(Minecraft p_96575_, int p_96576_, int p_96577_) {
this.init(p_96575_, p_96576_, p_96577_);
}
public static void wrapScreenError(Runnable p_96580_, String p_96581_, String p_96582_) {
try {
p_96580_.run();
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.forThrowable(throwable, p_96581_);
CrashReportCategory crashreportcategory = crashreport.addCategory("Affected screen");
crashreportcategory.setDetail("Screen name", () -> {
return p_96582_;
});
throw new ReportedException(crashreport);
}
}
protected boolean isValidCharacterForName(String p_96584_, char p_96585_, int p_96586_) {
int i = p_96584_.indexOf(58);
int j = p_96584_.indexOf(47);
if (p_96585_ == ':') {
return (j == -1 || p_96586_ <= j) && i == -1;
} else if (p_96585_ == '/') {
return p_96586_ > i;
} else {
return p_96585_ == '_' || p_96585_ == '-' || p_96585_ >= 'a' && p_96585_ <= 'z' || p_96585_ >= '0' && p_96585_ <= '9' || p_96585_ == '.';
}
}
public boolean isMouseOver(double p_96595_, double p_96596_) {
return true;
}
public void onFilesDrop(List<Path> p_96591_) {
}
public Minecraft getMinecraft() {
return this.minecraft;
}
private void scheduleNarration(long p_169381_, boolean p_169382_) {
this.nextNarrationTime = Util.getMillis() + p_169381_;
if (p_169382_) {
this.narrationSuppressTime = Long.MIN_VALUE;
}
}
private void suppressNarration(long p_169379_) {
this.narrationSuppressTime = Util.getMillis() + p_169379_;
}
public void afterMouseMove() {
this.scheduleNarration(750L, false);
}
public void afterMouseAction() {
this.scheduleNarration(200L, true);
}
public void afterKeyboardAction() {
this.scheduleNarration(200L, true);
}
private boolean shouldRunNarration() {
return NarratorChatListener.INSTANCE.isActive();
}
public void handleDelayedNarration() {
if (this.shouldRunNarration()) {
long i = Util.getMillis();
if (i > this.nextNarrationTime && i > this.narrationSuppressTime) {
this.runNarration(true);
this.nextNarrationTime = Long.MAX_VALUE;
}
}
}
protected void triggerImmediateNarration(boolean p_169408_) {
if (this.shouldRunNarration()) {
this.runNarration(p_169408_);
}
}
private void runNarration(boolean p_169410_) {
this.narrationState.update(this::updateNarrationState);
String s = this.narrationState.collectNarrationText(!p_169410_);
if (!s.isEmpty()) {
NarratorChatListener.INSTANCE.sayNow(s);
}
}
protected void updateNarrationState(NarrationElementOutput p_169396_) {
p_169396_.add(NarratedElementType.TITLE, this.getNarrationMessage());
p_169396_.add(NarratedElementType.USAGE, USAGE_NARRATION);
this.updateNarratedWidget(p_169396_);
}
protected void updateNarratedWidget(NarrationElementOutput p_169403_) {
ImmutableList<NarratableEntry> immutablelist = this.narratables.stream().filter(NarratableEntry::isActive).collect(ImmutableList.toImmutableList());
Screen.NarratableSearchResult screen$narratablesearchresult = findNarratableWidget(immutablelist, this.lastNarratable);
if (screen$narratablesearchresult != null) {
if (screen$narratablesearchresult.priority.isTerminal()) {
this.lastNarratable = screen$narratablesearchresult.entry;
}
if (immutablelist.size() > 1) {
p_169403_.add(NarratedElementType.POSITION, new TranslatableComponent("narrator.position.screen", screen$narratablesearchresult.index + 1, immutablelist.size()));
if (screen$narratablesearchresult.priority == NarratableEntry.NarrationPriority.FOCUSED) {
p_169403_.add(NarratedElementType.USAGE, new TranslatableComponent("narration.component_list.usage"));
}
}
screen$narratablesearchresult.entry.updateNarration(p_169403_.nest());
}
}
@Nullable
public static Screen.NarratableSearchResult findNarratableWidget(List<? extends NarratableEntry> p_169401_, @Nullable NarratableEntry p_169402_) {
Screen.NarratableSearchResult screen$narratablesearchresult = null;
Screen.NarratableSearchResult screen$narratablesearchresult1 = null;
int i = 0;
for(int j = p_169401_.size(); i < j; ++i) {
NarratableEntry narratableentry = p_169401_.get(i);
NarratableEntry.NarrationPriority narratableentry$narrationpriority = narratableentry.narrationPriority();
if (narratableentry$narrationpriority.isTerminal()) {
if (narratableentry != p_169402_) {
return new Screen.NarratableSearchResult(narratableentry, i, narratableentry$narrationpriority);
}
screen$narratablesearchresult1 = new Screen.NarratableSearchResult(narratableentry, i, narratableentry$narrationpriority);
} else if (narratableentry$narrationpriority.compareTo(screen$narratablesearchresult != null ? screen$narratablesearchresult.priority : NarratableEntry.NarrationPriority.NONE) > 0) {
screen$narratablesearchresult = new Screen.NarratableSearchResult(narratableentry, i, narratableentry$narrationpriority);
}
}
return screen$narratablesearchresult != null ? screen$narratablesearchresult : screen$narratablesearchresult1;
}
public void narrationEnabled() {
this.scheduleNarration(NARRATE_DELAY_NARRATOR_ENABLED, false);
}
@OnlyIn(Dist.CLIENT)
public static class NarratableSearchResult {
public final NarratableEntry entry;
public final int index;
public final NarratableEntry.NarrationPriority priority;
public NarratableSearchResult(NarratableEntry p_169424_, int p_169425_, NarratableEntry.NarrationPriority p_169426_) {
this.entry = p_169424_;
this.index = p_169425_;
this.priority = p_169426_;
}
}
}
|
3e12998165b2b4fd309344af46f28ad6b3794718 | 2,533 | java | Java | src/main/java/be/gschrooyen/restaurantdag/service/InschrijvingService.java | Gschrooyen/restaurantdag_organizer | ad11b8b63497edb51ce76999af5ca186d612c901 | [
"MIT"
] | null | null | null | src/main/java/be/gschrooyen/restaurantdag/service/InschrijvingService.java | Gschrooyen/restaurantdag_organizer | ad11b8b63497edb51ce76999af5ca186d612c901 | [
"MIT"
] | null | null | null | src/main/java/be/gschrooyen/restaurantdag/service/InschrijvingService.java | Gschrooyen/restaurantdag_organizer | ad11b8b63497edb51ce76999af5ca186d612c901 | [
"MIT"
] | null | null | null | 50.66 | 209 | 0.797868 | 7,843 | package be.gschrooyen.restaurantdag.service;
import be.gschrooyen.restaurantdag.model.Bestelling;
import be.gschrooyen.restaurantdag.model.Inschrijving;
import be.gschrooyen.restaurantdag.model.Restaurantdag;
import be.gschrooyen.restaurantdag.model.dto.BestellingDto;
import be.gschrooyen.restaurantdag.repositories.BestellingRepository;
import be.gschrooyen.restaurantdag.repositories.GerechtRepository;
import be.gschrooyen.restaurantdag.repositories.InschrijvingRepository;
import be.gschrooyen.restaurantdag.repositories.RestaurantdagRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class InschrijvingService {
private final RestaurantdagRepository restaurantdagRepository;
private final GerechtRepository gerechtRepository;
private final InschrijvingRepository inschrijvingRepository;
private final BestellingRepository bestellingRepository;
public InschrijvingService(RestaurantdagRepository restaurantdagRepository, GerechtRepository gerechtRepository, InschrijvingRepository inschrijvingRepository, BestellingRepository bestellingRepository) {
this.restaurantdagRepository = restaurantdagRepository;
this.gerechtRepository = gerechtRepository;
this.inschrijvingRepository = inschrijvingRepository;
this.bestellingRepository = bestellingRepository;
}
@Transactional
public Inschrijving nieuw(String naam, String groep, String tijdstip, Collection<BestellingDto> bestelling, long restaurantdagId) {
Restaurantdag r = restaurantdagRepository.getOne(restaurantdagId);
Inschrijving i = new Inschrijving(naam, groep, new ArrayList<Bestelling>(), r.getDatum().withHour(Integer.parseInt(tijdstip.substring(0, 2))).withMinute(Integer.parseInt(tijdstip.substring(3))), r);
List<Bestelling> bestellingen = bestelling.stream().map(bestellingDto -> new Bestelling(gerechtRepository.getOne(bestellingDto.getGerechtId()), bestellingDto.getAantal())).collect(Collectors.toList());
i.setBestellingen(bestellingen);
r.getInschrijvingen().add(i);
i.setRestaurantdag(r);
for (Bestelling bestelling1 : bestellingen) {
bestellingRepository.save(bestelling1);
}
Inschrijving insch = inschrijvingRepository.save(i);
restaurantdagRepository.save(r);
return insch;
}
}
|
3e1299e3d4766418a49446b8b5f47068fced5196 | 937 | java | Java | data/train/java/3e1299e3d4766418a49446b8b5f47068fced5196FoodServiceManager.java | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/java/3e1299e3d4766418a49446b8b5f47068fced5196FoodServiceManager.java | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/train/java/3e1299e3d4766418a49446b8b5f47068fced5196FoodServiceManager.java | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | 19.520833 | 70 | 0.739594 | 7,844 | package practicejsf.bean.service;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
public class FoodServiceManager implements FoodServiceCaller {
@Inject
@Curry
private FoodService curryService;
@Inject
@Noodle
private FoodService noodleService;
@Inject
@Sushi
private FoodService sushiService;
/**
* @Injectを書いた場所でBeanを生成することができる?
* しかしコンストラクタやsetterでInjectした時にどうやって呼び出すのか。
*/
// @Inject
// public FoodServiceManager(@Named("curry") FoodService curryService,
// @Named("noodle") FoodService noodleService,
// @Named("sushi") FoodService sushiService) {
// this.curryService = curryService;
// this.noodleService = noodleService;
// this.sushiService = sushiService;
// }
@Override
public List<String> callFoodService() {
List<String> foods = Arrays.asList(
curryService.getFoods(),
noodleService.getFoods(),
sushiService.getFoods()
);
return foods;
}
}
|
3e1299e92b927caec986cbecc36714d6af6f9181 | 1,446 | java | Java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpApprovalDataResult.java | kennywgx/WxJava | b07e34eab23a4ec9402bcae1f372be317e3709e6 | [
"Apache-2.0"
] | 17 | 2019-06-24T10:42:59.000Z | 2022-03-10T02:39:41.000Z | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpApprovalDataResult.java | kennywgx/WxJava | b07e34eab23a4ec9402bcae1f372be317e3709e6 | [
"Apache-2.0"
] | 11 | 2020-11-16T20:33:44.000Z | 2022-02-01T00:58:57.000Z | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpApprovalDataResult.java | kennywgx/WxJava | b07e34eab23a4ec9402bcae1f372be317e3709e6 | [
"Apache-2.0"
] | 10 | 2019-06-04T07:13:14.000Z | 2022-03-15T07:41:53.000Z | 20.657143 | 71 | 0.733057 | 7,845 | package me.chanjar.weixin.cp.bean;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import java.io.Serializable;
import java.util.Map;
/**
* @author Element
* @Package me.chanjar.weixin.cp.bean
* @date 2019-04-06 14:36
* @Description: 企业微信 OA 审批数据
*/
@Data
public class WxCpApprovalDataResult implements Serializable {
private static final long serialVersionUID = -1046940445840716590L;
@SerializedName("errcode")
private Integer errCode;
@SerializedName("errmsg")
private String errMsg;
private Integer count;
private Integer total;
@SerializedName("next_spnum")
private Long nextSpnum;
private WxCpApprovalData[] data;
@Data
public static class WxCpApprovalData implements Serializable{
private static final long serialVersionUID = -3051785319608491640L;
private String spname;
@SerializedName("apply_name")
private String applyName;
@SerializedName("apply_org")
private String applyOrg;
@SerializedName("approval_name")
private String[] approvalName;
@SerializedName("notify_name")
private String[] notifyName;
@SerializedName("sp_status")
private Integer spStatus;
@SerializedName("sp_num")
private Long spNum;
@SerializedName("apply_time")
private Long applyTime;
@SerializedName("apply_user_id")
private String applyUserId;
@SerializedName("comm")
private Map<String,String> comm;
}
}
|
3e1299f0b03e5dea10eceef10ce415cb9657c9c2 | 893 | java | Java | api/src/main/java/net/automatalib/graphs/concepts/MutableKripkeInterpretation.java | DocSkellington/automatalib | bf5a0929fc125bfa5247d69321353494b22cd039 | [
"Apache-2.0"
] | 54 | 2017-02-20T03:29:40.000Z | 2022-03-24T00:38:54.000Z | api/src/main/java/net/automatalib/graphs/concepts/MutableKripkeInterpretation.java | DocSkellington/automatalib | bf5a0929fc125bfa5247d69321353494b22cd039 | [
"Apache-2.0"
] | 27 | 2017-08-24T13:19:19.000Z | 2022-02-05T19:29:42.000Z | api/src/main/java/net/automatalib/graphs/concepts/MutableKripkeInterpretation.java | DocSkellington/automatalib | bf5a0929fc125bfa5247d69321353494b22cd039 | [
"Apache-2.0"
] | 32 | 2016-12-31T21:49:09.000Z | 2022-03-08T03:30:01.000Z | 37.208333 | 89 | 0.75252 | 7,846 | /* Copyright (C) 2013-2021 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* 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.automatalib.graphs.concepts;
import java.util.Set;
public interface MutableKripkeInterpretation<N, AP> extends KripkeInterpretation<N, AP> {
void setAtomicPropositions(N node, Set<AP> atomicPropositions);
}
|
3e1299f712192bade91dd745a0325ca7eeaac60f | 2,187 | java | Java | server/src/main/java/com/humanharvest/organz/server/controller/ConfigController.java | tomkearsley/OrgaNZ | 38bbc4f0d19bc4aa2cfd7a9f5923e7edd910414d | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/humanharvest/organz/server/controller/ConfigController.java | tomkearsley/OrgaNZ | 38bbc4f0d19bc4aa2cfd7a9f5923e7edd910414d | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/humanharvest/organz/server/controller/ConfigController.java | tomkearsley/OrgaNZ | 38bbc4f0d19bc4aa2cfd7a9f5923e7edd910414d | [
"Apache-2.0"
] | null | null | null | 40.5 | 104 | 0.762231 | 7,847 | package com.humanharvest.organz.server.controller;
import java.util.EnumSet;
import java.util.Set;
import com.humanharvest.organz.server.exceptions.GlobalControllerExceptionHandler;
import com.humanharvest.organz.state.State;
import com.humanharvest.organz.utilities.enums.Country;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigController {
/**
* The GET endpoint for getting the allowed countries that clients and clinicians can set
* @return Response entity containing an EnumSet of the allowed countries
*/
@GetMapping("/config/countries")
public ResponseEntity<EnumSet<Country>> getCountries()
throws GlobalControllerExceptionHandler.InvalidRequestException {
Set<Country> countries = State.getConfigManager().getAllowedCountries();
EnumSet<Country> countryEnumSet = EnumSet.noneOf(Country.class);
countryEnumSet.addAll(countries);
return new ResponseEntity<>(countryEnumSet, HttpStatus.OK);
}
/**
* The POST endpoint for setting the list of allowed countries
* @param authToken authentication token - the allowed countries may only be set by an administrator
* @param countries EnumSet of countries to set as the allowed countries
* @return response entity containing the http status code
*/
@PostMapping("/config/countries")
public ResponseEntity postCountries(
@RequestHeader(value = "X-Auth-Token", required = false) String authToken,
@RequestBody EnumSet<Country> countries)
throws GlobalControllerExceptionHandler.InvalidRequestException {
State.getAuthenticationManager().verifyAdminAccess(authToken);
State.getConfigManager().setAllowedCountries(countries);
return new ResponseEntity(HttpStatus.OK);
}
}
|
3e129a2353e9189b3a4a3951974224c2f211f648 | 14,805 | java | Java | okhttp-tests/src/test/java/com/squareup/okhttp/internal/OptionalMethodTest.java | derp-caf/external_okhttp | 3e85d2adb0db7d20e7b7c2553e491208959ba050 | [
"Apache-2.0"
] | 11 | 2016-02-24T01:46:14.000Z | 2021-08-25T06:27:35.000Z | okhttp-tests/src/test/java/com/squareup/okhttp/internal/OptionalMethodTest.java | derp-caf/external_okhttp | 3e85d2adb0db7d20e7b7c2553e491208959ba050 | [
"Apache-2.0"
] | 6 | 2021-06-04T03:07:59.000Z | 2021-07-04T15:02:47.000Z | okhttp-tests/src/test/java/com/squareup/okhttp/internal/OptionalMethodTest.java | derp-caf/external_okhttp | 3e85d2adb0db7d20e7b7c2553e491208959ba050 | [
"Apache-2.0"
] | 20 | 2015-03-03T12:09:18.000Z | 2020-05-12T01:54:18.000Z | 43.931751 | 109 | 0.765079 | 7,848 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp.internal;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for {@link OptionalMethod}.
*/
public class OptionalMethodTest {
@SuppressWarnings("unused")
private static class BaseClass {
public String stringMethod() {
return "string";
}
public void voidMethod() {}
}
@SuppressWarnings("unused")
private static class SubClass1 extends BaseClass {
public String subclassMethod() {
return "subclassMethod1";
}
public String methodWithArgs(String arg) {
return arg;
}
}
@SuppressWarnings("unused")
private static class SubClass2 extends BaseClass {
public int subclassMethod() {
return 1234;
}
public String methodWithArgs(String arg) {
return arg;
}
public void throwsException() throws IOException {
throw new IOException();
}
public void throwsRuntimeException() throws Exception {
throw new NumberFormatException();
}
protected void nonPublic() {}
}
private final static OptionalMethod<BaseClass> STRING_METHOD_RETURNS_ANY =
new OptionalMethod<BaseClass>(null, "stringMethod");
private final static OptionalMethod<BaseClass> STRING_METHOD_RETURNS_STRING =
new OptionalMethod<BaseClass>(String.class, "stringMethod");
private final static OptionalMethod<BaseClass> STRING_METHOD_RETURNS_INT =
new OptionalMethod<BaseClass>(Integer.TYPE, "stringMethod");
private final static OptionalMethod<BaseClass> VOID_METHOD_RETURNS_ANY =
new OptionalMethod<BaseClass>(null, "voidMethod");
private final static OptionalMethod<BaseClass> VOID_METHOD_RETURNS_VOID =
new OptionalMethod<BaseClass>(Void.TYPE, "voidMethod");
private final static OptionalMethod<BaseClass> SUBCLASS_METHOD_RETURNS_ANY =
new OptionalMethod<BaseClass>(null, "subclassMethod");
private final static OptionalMethod<BaseClass> SUBCLASS_METHOD_RETURNS_STRING =
new OptionalMethod<BaseClass>(String.class, "subclassMethod");
private final static OptionalMethod<BaseClass> SUBCLASS_METHOD_RETURNS_INT =
new OptionalMethod<BaseClass>(Integer.TYPE, "subclassMethod");
private final static OptionalMethod<BaseClass> METHOD_WITH_ARGS_WRONG_PARAMS =
new OptionalMethod<BaseClass>(null, "methodWithArgs", Integer.class);
private final static OptionalMethod<BaseClass> METHOD_WITH_ARGS_CORRECT_PARAMS =
new OptionalMethod<BaseClass>(null, "methodWithArgs", String.class);
private final static OptionalMethod<BaseClass> THROWS_EXCEPTION =
new OptionalMethod<BaseClass>(null, "throwsException");
private final static OptionalMethod<BaseClass> THROWS_RUNTIME_EXCEPTION =
new OptionalMethod<BaseClass>(null, "throwsRuntimeException");
private final static OptionalMethod<BaseClass> NON_PUBLIC =
new OptionalMethod<BaseClass>(null, "nonPublic");
@Test
public void isSupported() throws Exception {
{
BaseClass base = new BaseClass();
assertTrue(STRING_METHOD_RETURNS_ANY.isSupported(base));
assertTrue(STRING_METHOD_RETURNS_STRING.isSupported(base));
assertFalse(STRING_METHOD_RETURNS_INT.isSupported(base));
assertTrue(VOID_METHOD_RETURNS_ANY.isSupported(base));
assertTrue(VOID_METHOD_RETURNS_VOID.isSupported(base));
assertFalse(SUBCLASS_METHOD_RETURNS_ANY.isSupported(base));
assertFalse(SUBCLASS_METHOD_RETURNS_STRING.isSupported(base));
assertFalse(SUBCLASS_METHOD_RETURNS_INT.isSupported(base));
assertFalse(METHOD_WITH_ARGS_WRONG_PARAMS.isSupported(base));
assertFalse(METHOD_WITH_ARGS_CORRECT_PARAMS.isSupported(base));
}
{
SubClass1 subClass1 = new SubClass1();
assertTrue(STRING_METHOD_RETURNS_ANY.isSupported(subClass1));
assertTrue(STRING_METHOD_RETURNS_STRING.isSupported(subClass1));
assertFalse(STRING_METHOD_RETURNS_INT.isSupported(subClass1));
assertTrue(VOID_METHOD_RETURNS_ANY.isSupported(subClass1));
assertTrue(VOID_METHOD_RETURNS_VOID.isSupported(subClass1));
assertTrue(SUBCLASS_METHOD_RETURNS_ANY.isSupported(subClass1));
assertTrue(SUBCLASS_METHOD_RETURNS_STRING.isSupported(subClass1));
assertFalse(SUBCLASS_METHOD_RETURNS_INT.isSupported(subClass1));
assertFalse(METHOD_WITH_ARGS_WRONG_PARAMS.isSupported(subClass1));
assertTrue(METHOD_WITH_ARGS_CORRECT_PARAMS.isSupported(subClass1));
}
{
SubClass2 subClass2 = new SubClass2();
assertTrue(STRING_METHOD_RETURNS_ANY.isSupported(subClass2));
assertTrue(STRING_METHOD_RETURNS_STRING.isSupported(subClass2));
assertFalse(STRING_METHOD_RETURNS_INT.isSupported(subClass2));
assertTrue(VOID_METHOD_RETURNS_ANY.isSupported(subClass2));
assertTrue(VOID_METHOD_RETURNS_VOID.isSupported(subClass2));
assertTrue(SUBCLASS_METHOD_RETURNS_ANY.isSupported(subClass2));
assertFalse(SUBCLASS_METHOD_RETURNS_STRING.isSupported(subClass2));
assertTrue(SUBCLASS_METHOD_RETURNS_INT.isSupported(subClass2));
assertFalse(METHOD_WITH_ARGS_WRONG_PARAMS.isSupported(subClass2));
assertTrue(METHOD_WITH_ARGS_CORRECT_PARAMS.isSupported(subClass2));
}
}
@Test
public void invoke() throws Exception {
{
BaseClass base = new BaseClass();
assertEquals("string", STRING_METHOD_RETURNS_STRING.invoke(base));
assertEquals("string", STRING_METHOD_RETURNS_ANY.invoke(base));
assertErrorOnInvoke(STRING_METHOD_RETURNS_INT, base);
assertNull(VOID_METHOD_RETURNS_ANY.invoke(base));
assertNull(VOID_METHOD_RETURNS_VOID.invoke(base));
assertErrorOnInvoke(SUBCLASS_METHOD_RETURNS_ANY, base);
assertErrorOnInvoke(SUBCLASS_METHOD_RETURNS_STRING, base);
assertErrorOnInvoke(SUBCLASS_METHOD_RETURNS_INT, base);
assertErrorOnInvoke(METHOD_WITH_ARGS_WRONG_PARAMS, base);
assertErrorOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, base);
}
{
SubClass1 subClass1 = new SubClass1();
assertEquals("string", STRING_METHOD_RETURNS_STRING.invoke(subClass1));
assertEquals("string", STRING_METHOD_RETURNS_ANY.invoke(subClass1));
assertErrorOnInvoke(STRING_METHOD_RETURNS_INT, subClass1);
assertNull(VOID_METHOD_RETURNS_ANY.invoke(subClass1));
assertNull(VOID_METHOD_RETURNS_VOID.invoke(subClass1));
assertEquals("subclassMethod1", SUBCLASS_METHOD_RETURNS_ANY.invoke(subClass1));
assertEquals("subclassMethod1", SUBCLASS_METHOD_RETURNS_STRING.invoke(subClass1));
assertErrorOnInvoke(SUBCLASS_METHOD_RETURNS_INT, subClass1);
assertErrorOnInvoke(METHOD_WITH_ARGS_WRONG_PARAMS, subClass1);
assertEquals("arg", METHOD_WITH_ARGS_CORRECT_PARAMS.invoke(subClass1, "arg"));
}
{
SubClass2 subClass2 = new SubClass2();
assertEquals("string", STRING_METHOD_RETURNS_STRING.invoke(subClass2));
assertEquals("string", STRING_METHOD_RETURNS_ANY.invoke(subClass2));
assertErrorOnInvoke(STRING_METHOD_RETURNS_INT, subClass2);
assertNull(VOID_METHOD_RETURNS_ANY.invoke(subClass2));
assertNull(VOID_METHOD_RETURNS_VOID.invoke(subClass2));
assertEquals(1234, SUBCLASS_METHOD_RETURNS_ANY.invoke(subClass2));
assertErrorOnInvoke(SUBCLASS_METHOD_RETURNS_STRING, subClass2);
assertEquals(1234, SUBCLASS_METHOD_RETURNS_INT.invoke(subClass2));
assertErrorOnInvoke(METHOD_WITH_ARGS_WRONG_PARAMS, subClass2);
assertEquals("arg", METHOD_WITH_ARGS_CORRECT_PARAMS.invoke(subClass2, "arg"));
}
}
@Test
public void invokeBadArgs() throws Exception {
SubClass1 subClass1 = new SubClass1();
assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1); // no args
assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, 123);
assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, true);
assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, new Object());
assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, "one", "two");
}
@Test
public void invokeWithException() throws Exception {
SubClass2 subClass2 = new SubClass2();
try {
THROWS_EXCEPTION.invoke(subClass2);
} catch (InvocationTargetException expected) {
assertTrue(expected.getTargetException() instanceof IOException);
}
try {
THROWS_RUNTIME_EXCEPTION.invoke(subClass2);
} catch (InvocationTargetException expected) {
assertTrue(expected.getTargetException() instanceof NumberFormatException);
}
}
@Test
public void invokeNonPublic() throws Exception {
SubClass2 subClass2 = new SubClass2();
assertFalse(NON_PUBLIC.isSupported(subClass2));
assertErrorOnInvoke(NON_PUBLIC, subClass2);
}
@Test
public void invokeOptional() throws Exception {
{
BaseClass base = new BaseClass();
assertEquals("string", STRING_METHOD_RETURNS_STRING.invokeOptional(base));
assertEquals("string", STRING_METHOD_RETURNS_ANY.invokeOptional(base));
assertNull(STRING_METHOD_RETURNS_INT.invokeOptional(base));
assertNull(VOID_METHOD_RETURNS_ANY.invokeOptional(base));
assertNull(VOID_METHOD_RETURNS_VOID.invokeOptional(base));
assertNull(SUBCLASS_METHOD_RETURNS_ANY.invokeOptional(base));
assertNull(SUBCLASS_METHOD_RETURNS_STRING.invokeOptional(base));
assertNull(SUBCLASS_METHOD_RETURNS_INT.invokeOptional(base));
assertNull(METHOD_WITH_ARGS_WRONG_PARAMS.invokeOptional(base));
assertNull(METHOD_WITH_ARGS_CORRECT_PARAMS.invokeOptional(base));
}
{
SubClass1 subClass1 = new SubClass1();
assertEquals("string", STRING_METHOD_RETURNS_STRING.invokeOptional(subClass1));
assertEquals("string", STRING_METHOD_RETURNS_ANY.invokeOptional(subClass1));
assertNull(STRING_METHOD_RETURNS_INT.invokeOptional(subClass1));
assertNull(VOID_METHOD_RETURNS_ANY.invokeOptional(subClass1));
assertNull(VOID_METHOD_RETURNS_VOID.invokeOptional(subClass1));
assertEquals("subclassMethod1", SUBCLASS_METHOD_RETURNS_ANY.invokeOptional(subClass1));
assertEquals("subclassMethod1", SUBCLASS_METHOD_RETURNS_STRING.invokeOptional(subClass1));
assertNull(SUBCLASS_METHOD_RETURNS_INT.invokeOptional(subClass1));
assertNull(METHOD_WITH_ARGS_WRONG_PARAMS.invokeOptional(subClass1));
assertEquals("arg", METHOD_WITH_ARGS_CORRECT_PARAMS.invokeOptional(subClass1, "arg"));
}
{
SubClass2 subClass2 = new SubClass2();
assertEquals("string", STRING_METHOD_RETURNS_STRING.invokeOptional(subClass2));
assertEquals("string", STRING_METHOD_RETURNS_ANY.invokeOptional(subClass2));
assertNull(STRING_METHOD_RETURNS_INT.invokeOptional(subClass2));
assertNull(VOID_METHOD_RETURNS_ANY.invokeOptional(subClass2));
assertNull(VOID_METHOD_RETURNS_VOID.invokeOptional(subClass2));
assertEquals(1234, SUBCLASS_METHOD_RETURNS_ANY.invokeOptional(subClass2));
assertNull(SUBCLASS_METHOD_RETURNS_STRING.invokeOptional(subClass2));
assertEquals(1234, SUBCLASS_METHOD_RETURNS_INT.invokeOptional(subClass2));
assertNull(METHOD_WITH_ARGS_WRONG_PARAMS.invokeOptional(subClass2));
assertEquals("arg", METHOD_WITH_ARGS_CORRECT_PARAMS.invokeOptional(subClass2, "arg"));
}
}
@Test
public void invokeOptionalBadArgs() throws Exception {
SubClass1 subClass1 = new SubClass1();
assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1); // no args
assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, 123);
assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, true);
assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, new Object());
assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, "one", "two");
}
@Test
public void invokeOptionalWithException() throws Exception {
SubClass2 subClass2 = new SubClass2();
try {
THROWS_EXCEPTION.invokeOptional(subClass2);
} catch (InvocationTargetException expected) {
assertTrue(expected.getTargetException() instanceof IOException);
}
try {
THROWS_RUNTIME_EXCEPTION.invokeOptional(subClass2);
} catch (InvocationTargetException expected) {
assertTrue(expected.getTargetException() instanceof NumberFormatException);
}
}
@Test
public void invokeOptionalNonPublic() throws Exception {
SubClass2 subClass2 = new SubClass2();
assertFalse(NON_PUBLIC.isSupported(subClass2));
assertErrorOnInvokeOptional(NON_PUBLIC, subClass2);
}
private static <T> void assertErrorOnInvoke(
OptionalMethod<T> optionalMethod, T base, Object... args) throws Exception {
try {
optionalMethod.invoke(base, args);
fail();
} catch (Error expected) {
}
}
private static <T> void assertIllegalArgumentExceptionOnInvoke(
OptionalMethod<T> optionalMethod, T base, Object... args) throws Exception {
try {
optionalMethod.invoke(base, args);
fail();
} catch (IllegalArgumentException expected) {
}
}
private static <T> void assertErrorOnInvokeOptional(
OptionalMethod<T> optionalMethod, T base, Object... args) throws Exception {
try {
optionalMethod.invokeOptional(base, args);
fail();
} catch (Error expected) {
}
}
private static <T> void assertIllegalArgumentExceptionOnInvokeOptional(
OptionalMethod<T> optionalMethod, T base, Object... args) throws Exception {
try {
optionalMethod.invokeOptional(base, args);
fail();
} catch (IllegalArgumentException expected) {
}
}
}
|
3e129a46f663de88bbb0f8d0e8e224f1337efba6 | 7,736 | java | Java | CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/block/MCBlockState.java | democat3457/CraftTweaker | 7d4121746593e9d47d1469848d295430b2e98c50 | [
"MIT"
] | null | null | null | CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/block/MCBlockState.java | democat3457/CraftTweaker | 7d4121746593e9d47d1469848d295430b2e98c50 | [
"MIT"
] | null | null | null | CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/block/MCBlockState.java | democat3457/CraftTweaker | 7d4121746593e9d47d1469848d295430b2e98c50 | [
"MIT"
] | null | null | null | 36.319249 | 164 | 0.62319 | 7,849 | package crafttweaker.mc1120.block;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.api.block.*;
import crafttweaker.api.world.*;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import java.util.*;
public class MCBlockState extends MCBlockProperties implements crafttweaker.api.block.IBlockState {
private final IBlockState blockState;
private IBlock block;
public MCBlockState(IBlockState blockState) {
super(blockState);
this.blockState = blockState;
Block block = blockState.getBlock();
int meta = block.getMetaFromState(blockState);
this.block = new MCSpecificBlock(block, meta);
}
@Override
public IBlock getBlock() {
return block;
}
@Override
public int getMeta() {
return block.getMeta();
}
@Override
public boolean isReplaceable(IWorld world, IBlockPos blockPos) {
return blockState.getBlock().isReplaceable((World) world.getInternal(), (BlockPos) blockPos.getInternal());
}
@Override
public int compare(crafttweaker.api.block.IBlockState other) {
int result = 0;
if(!this.getInternal().equals(other.getInternal())) {
if(blockState.getBlock().equals(((IBlockState) other.getInternal()).getBlock())) {
result = Integer.compare(this.getMeta(), other.getMeta());
} else {
int blockId = ((ForgeRegistry<Block>) ForgeRegistries.BLOCKS).getID(((IBlockState) this.getInternal()).getBlock());
int otherBlockId = ((ForgeRegistry<Block>) ForgeRegistries.BLOCKS).getID(((IBlockState) other.getInternal()).getBlock());
result = Integer.compare(blockId, otherBlockId);
}
}
return result;
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public crafttweaker.api.block.IBlockState withProperty(String name, String value) {
IProperty property = blockState.getBlock().getBlockState().getProperty(name);
if (property == null) {
CraftTweakerAPI.logWarning("Invalid property name");
} else {
//noinspection unchecked
Optional<? extends Comparable> propValue = property.parseValue(value);
if (propValue.isPresent()) {
//noinspection unchecked
return new MCBlockState(blockState.withProperty(property, propValue.get()));
}
CraftTweakerAPI.logWarning("Invalid property value");
}
return this;
}
@Override
public List<String> getPropertyNames() {
List<String> props = new ArrayList<>();
for (IProperty<?> prop : blockState.getPropertyKeys()) {
props.add(prop.getName());
}
return ImmutableList.copyOf(props);
}
@Override
public String getPropertyValue(String name) {
IProperty<?> prop = blockState.getBlock().getBlockState().getProperty(name);
if (prop != null) {
//noinspection unchecked
return blockState.getValue(prop).toString();
}
CraftTweakerAPI.logWarning("Invalid property name");
return "";
}
@Override
public List<String> getAllowedValuesForProperty(String name) {
IProperty<?> prop = blockState.getBlock().getBlockState().getProperty(name);
if (prop != null) {
List<String> values = new ArrayList<>();
//noinspection unchecked
prop.getAllowedValues().forEach(v -> values.add(v.toString()));
return values;
}
CraftTweakerAPI.logWarning("Invalid property name");
return ImmutableList.of();
}
@Override
public Map<String, String> getProperties() {
Map<String, String> props = new HashMap<>();
for (Map.Entry<IProperty<?>, Comparable<?>> entry : blockState.getProperties().entrySet()) {
props.put(entry.getKey().getName(), entry.getValue().toString());
}
return ImmutableMap.copyOf(props);
}
@Override
public IBlockStateMatcher matchBlock() {
return new BlockStateMatcher(this);
}
@Override
public boolean matches(crafttweaker.api.block.IBlockState other) {
return compare(other) == 0;
}
@Override
public IBlockStateMatcher or(IBlockStateMatcher matcher) {
return new BlockStateMatcherOr(this, matcher);
}
@Override
public Collection<crafttweaker.api.block.IBlockState> getMatchingBlockStates() {
return ImmutableList.of(this);
}
@Override
public IBlockStateMatcher allowValuesForProperty(String name, String... values) {
CraftTweakerAPI.logWarning("IBlockStateMatcher#allowValuesForProperty is deprecated. Please use IBlockStateMatcher#withMatchedValuesForProperty instead.");
return withMatchedValuesForProperty(name, values);
}
@Override
public IBlockStateMatcher withMatchedValuesForProperty(String name, String... values) {
Map<String, List<String>> newProps = new HashMap<>();
List<String> newValues = ImmutableList.copyOf(values);
if (newValues.contains("*") && newValues.size() > 1) {
newProps.put(name, ImmutableList.of("*"));
} else {
newProps.put(name, newValues);
}
return new BlockStateMatcher(this, newProps);
}
@Override
public List<String> getMatchedValuesForProperty(String name) {
return ImmutableList.of(getPropertyValue(name));
}
@Override
public Map<String, List<String>> getMatchedProperties() {
Map<String, List<String>> props = new HashMap<>();
for(Map.Entry<String,String> entry : getProperties().entrySet()) {
props.put(entry.getKey(), ImmutableList.of(entry.getValue()));
}
return ImmutableMap.copyOf(props);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("<blockstate:");
builder.append(blockState.getBlock().getRegistryName());
if (!blockState.getProperties().isEmpty()) {
builder.append(":");
StringJoiner joiner = new StringJoiner(",");
for (Map.Entry<IProperty<?>, Comparable<?>> entry : blockState.getProperties().entrySet()) {
joiner.add(entry.getKey().getName() + "=" + entry.getValue());
}
builder.append(joiner);
}
return builder.append(">").toString();
}
@Override
public boolean isCompound() {
return false;
}
@Override
public String toCommandString() {
return toString();
}
@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;
MCBlockState that = (MCBlockState) o;
return Objects.equals(blockState, that.blockState) && Objects.equals(block, that.block);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), blockState, block);
}
}
|
3e129cd2c9550a8c1e25ff49d6d0f56a38435772 | 1,510 | java | Java | database-plugins/src/test/java/io/cdap/plugin/DBConfigTest.java | shubhampatil17/hydrator-plugins | 39368d63183efcd7db38d36d530dc8434470b88a | [
"Apache-2.0"
] | 33 | 2015-11-02T06:17:19.000Z | 2018-02-28T10:06:21.000Z | database-plugins/src/test/java/io/cdap/plugin/DBConfigTest.java | shubhampatil17/hydrator-plugins | 39368d63183efcd7db38d36d530dc8434470b88a | [
"Apache-2.0"
] | 696 | 2015-10-19T15:33:58.000Z | 2018-11-09T06:12:01.000Z | database-plugins/src/test/java/io/cdap/plugin/DBConfigTest.java | shubhampatil17/hydrator-plugins | 39368d63183efcd7db38d36d530dc8434470b88a | [
"Apache-2.0"
] | 42 | 2019-02-12T11:58:23.000Z | 2022-03-30T13:54:54.000Z | 27.962963 | 80 | 0.686755 | 7,850 | /*
* Copyright © 2016-2019 Cask Data, 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 io.cdap.plugin;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for the db config.
*/
public class DBConfigTest {
@Test
public void testQueryClean() {
TestDBConfig config = new TestDBConfig("select * from table; ; ;; ;;; ;");
Assert.assertEquals("select * from table", config.query);
config = new TestDBConfig("select * from table;");
Assert.assertEquals("select * from table", config.query);
config = new TestDBConfig("select * from table");
Assert.assertEquals("select * from table", config.query);
}
@Test
public void testCleanDumbQuery() {
TestDBConfig config = new TestDBConfig("; ; ;; ;;; ;");
Assert.assertEquals("", config.query);
}
/**
* Test config.
*/
private static class TestDBConfig extends DBConfig {
private String query;
TestDBConfig(String query) {
this.query = cleanQuery(query);
}
}
}
|
3e129d31c2f73592833759aaa02d660f15955d57 | 506 | java | Java | depsWorkSpace/bc-java-master/core/src/main/java/org/mightyfish/asn1/util/Dump.java | GLC-Project/java-experiment | b03b224b8d5028dd578ca0e7df85d7d09a26688e | [
"MIT",
"Unlicense"
] | 2 | 2016-01-26T11:24:52.000Z | 2016-02-11T05:17:47.000Z | depsWorkSpace/bc-java-master/core/src/main/java/org/mightyfish/asn1/util/Dump.java | goldcoin/goldcoin-2 | b03b224b8d5028dd578ca0e7df85d7d09a26688e | [
"MIT",
"Unlicense"
] | null | null | null | depsWorkSpace/bc-java-master/core/src/main/java/org/mightyfish/asn1/util/Dump.java | goldcoin/goldcoin-2 | b03b224b8d5028dd578ca0e7df85d7d09a26688e | [
"MIT",
"Unlicense"
] | 2 | 2020-01-30T21:56:54.000Z | 2021-03-19T02:06:59.000Z | 22 | 59 | 0.612648 | 7,851 | package org.mightyfish.asn1.util;
import java.io.FileInputStream;
import org.mightyfish.asn1.ASN1InputStream;
public class Dump
{
public static void main(
String args[])
throws Exception
{
FileInputStream fIn = new FileInputStream(args[0]);
ASN1InputStream bIn = new ASN1InputStream(fIn);
Object obj = null;
while ((obj = bIn.readObject()) != null)
{
System.out.println(ASN1Dump.dumpAsString(obj));
}
}
}
|
3e129ec4ad23a30f0b46b4436fdb212ec9f6a2f6 | 840 | java | Java | src/main/java/com/aoizz/communitymarket/controller/system/SystemUserController.java | chenimin/springboot-shiro-jtw | 9720e94496595847bf6202ad8d613a4e3bcff5c3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/aoizz/communitymarket/controller/system/SystemUserController.java | chenimin/springboot-shiro-jtw | 9720e94496595847bf6202ad8d613a4e3bcff5c3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/aoizz/communitymarket/controller/system/SystemUserController.java | chenimin/springboot-shiro-jtw | 9720e94496595847bf6202ad8d613a4e3bcff5c3 | [
"Apache-2.0"
] | null | null | null | 22.702703 | 66 | 0.725 | 7,852 | package com.aoizz.communitymarket.controller.system;
import com.aoizz.communitymarket.entity.system.SystemUser;
import com.aoizz.communitymarket.service.system.SystemUserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* (`system_user`)表控制层
*
* @author xxxxx
*/
@RestController
@RequestMapping("`system_user`")
public class SystemUserController {
/**
* 服务对象
*/
@Resource
private SystemUserService systemUserService;
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@GetMapping("selectOne")
public SystemUser selectOne(Integer id) {
return systemUserService.getById(id);
}
}
|
3e129f39d8584982e3c2ce6b47c582a597ed39dc | 1,920 | java | Java | src/bpmn/connectionobject/ConnectionObject.java | leandroungari/ExperProtocol | 872fc7bbe537545204a3a84c10dd6282c3c3eea8 | [
"MIT"
] | null | null | null | src/bpmn/connectionobject/ConnectionObject.java | leandroungari/ExperProtocol | 872fc7bbe537545204a3a84c10dd6282c3c3eea8 | [
"MIT"
] | null | null | null | src/bpmn/connectionobject/ConnectionObject.java | leandroungari/ExperProtocol | 872fc7bbe537545204a3a84c10dd6282c3c3eea8 | [
"MIT"
] | null | null | null | 19.591837 | 106 | 0.635938 | 7,853 | /*
* 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 bpmn.connectionobject;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
*
* @author leandroungari
*/
@XStreamAlias("ConnectionObject")
public class ConnectionObject {
private String id;
private String origem;
private String destino;
private String tipo;
private int pontoOrigem;
private int pontoDestino;
public ConnectionObject(String id, String origem, String destino, int pontoOrigem, int pontoDestino) {
this.id = id;
this.origem = origem;
this.destino = destino;
this.pontoOrigem = pontoOrigem;
this.pontoDestino = pontoDestino;
}
public ConnectionObject() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrigem() {
return origem;
}
public void setOrigem(String origem) {
this.origem = origem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public int getPontoOrigem() {
return pontoOrigem;
}
public void setPontoOrigem(int pontoOrigem) {
this.pontoOrigem = pontoOrigem;
}
public int getPontoDestino() {
return pontoDestino;
}
public void setPontoDestino(int pontoDestino) {
this.pontoDestino = pontoDestino;
}
public String getTipo() {
return tipo;
}
public void setTipo(String type) {
this.tipo = type;
}
}
|
3e129fe652d07e67488da0589adaebf60a1435c3 | 103 | java | Java | java/java-tests/testData/codeInsight/completion/smartType/EmptyListInReturn2-out.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 5 | 2015-12-19T15:27:30.000Z | 2019-08-17T10:07:23.000Z | java/java-tests/testData/codeInsight/completion/smartType/EmptyListInReturn2-out.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | java/java-tests/testData/codeInsight/completion/smartType/EmptyListInReturn2-out.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 20.6 | 52 | 0.660194 | 7,854 | class Foo {
java.util.List<String> foo() {
return java.util.Collections.emptyList();<caret>
}
} |
3e12a00419dfe5ff668221b0c1cf56415728f595 | 2,336 | java | Java | sample-app/FaceUISDK/src/main/java/com/gemalto/idp/mobile/authentication/mode/face/ui/VerificationCallback.java | opoto/idcloud-sample-android | d63e058c6e29c0c8de0497ac91330b7ce083b156 | [
"MIT"
] | null | null | null | sample-app/FaceUISDK/src/main/java/com/gemalto/idp/mobile/authentication/mode/face/ui/VerificationCallback.java | opoto/idcloud-sample-android | d63e058c6e29c0c8de0497ac91330b7ce083b156 | [
"MIT"
] | null | null | null | sample-app/FaceUISDK/src/main/java/com/gemalto/idp/mobile/authentication/mode/face/ui/VerificationCallback.java | opoto/idcloud-sample-android | d63e058c6e29c0c8de0497ac91330b7ce083b156 | [
"MIT"
] | null | null | null | 33.855072 | 98 | 0.724315 | 7,855 | /*
* MIT License
*
* Copyright (c) 2020 Thales DIS
*
* 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.
*
* IMPORTANT: This source code is intended to serve training information purposes only.
* Please make sure to review our IdCloud documentation, including security guidelines.
*/
package com.gemalto.idp.mobile.authentication.mode.face.ui;
import com.gemalto.idp.mobile.authentication.AuthInput;
import com.gemalto.idp.mobile.authentication.mode.face.FaceAuthStatus;
import com.gemalto.idp.mobile.core.IdpException;
/**
* Callback from the verification fragment
*/
public interface VerificationCallback {
/**
* On verification success. AuthInput object is returned.
* @param authInput
*/
void onVerificationSuccess(final AuthInput authInput);
/**
* On verification cancelled.
*/
void onCancel();
/**
* On verification failed. Check status to see why.
* @param status
*/
void onVerificationFailed(FaceAuthStatus status);
/**
* On verification retry. (invoked on single failure)
* @param status
* @param remainingRetries
*/
void onVerificationRetry(FaceAuthStatus status, int remainingRetries);
/**
* Error in internal SDK.
* @param e
*/
void onError(IdpException e);
}
|
3e12a12a22dee3a5f4c4569183a33ed740cf136f | 5,260 | java | Java | blueprint/plugin/blueprint-maven-plugin/src/test/java/org/apache/aries/blueprint/plugin/EnableAnnotationTest.java | aguibert/aries | f8a242901ef5b43074786ef8a6a3cd5742398a96 | [
"Apache-2.0"
] | 75 | 2015-01-09T20:20:37.000Z | 2022-03-22T13:22:30.000Z | blueprint/plugin/blueprint-maven-plugin/src/test/java/org/apache/aries/blueprint/plugin/EnableAnnotationTest.java | aguibert/aries | f8a242901ef5b43074786ef8a6a3cd5742398a96 | [
"Apache-2.0"
] | 77 | 2015-02-06T11:24:25.000Z | 2022-03-18T17:41:52.000Z | blueprint/plugin/blueprint-maven-plugin/src/test/java/org/apache/aries/blueprint/plugin/EnableAnnotationTest.java | coheigea/aries | 457551c4dda9ceca2e57572c121c605afb52db36 | [
"Apache-2.0"
] | 157 | 2015-01-12T20:43:13.000Z | 2022-01-31T12:11:40.000Z | 38.962963 | 139 | 0.741065 | 7,856 | /**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.aries.blueprint.plugin;
import org.apache.aries.blueprint.plugin.model.Blueprint;
import org.apache.aries.blueprint.plugin.test.transactionenable.TxBean;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.xbean.finder.ClassFinder;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.aries.blueprint.plugin.FilteredClassFinder.findClasses;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class EnableAnnotationTest {
private static final String NS_JPA = "http://aries.apache.org/xmlns/jpa/v1.1.0";
private static final String NS_TX1_0 = "http://aries.apache.org/xmlns/transactions/v1.0.0";
private static final String NS_TX1_1 = "http://aries.apache.org/xmlns/transactions/v1.1.0";
private static final String NS_TX1_2 = "http://aries.apache.org/xmlns/transactions/v1.2.0";
private static Set<Class<?>> beanClasses;
private XPath xpath;
private Document document;
private byte[] xmlAsBytes;
@BeforeClass
public static void setUp() throws Exception {
ClassFinder classFinder = new ClassFinder(EnableAnnotationTest.class.getClassLoader());
beanClasses = findClasses(classFinder, Arrays.asList(
TxBean.class.getPackage().getName()));
}
private void writeXML(String namespace, String enableAnnotations) throws XMLStreamException,
UnsupportedEncodingException, ParserConfigurationException, SAXException, IOException {
Set<String> namespaces = new HashSet<>(Arrays.asList(NS_JPA, namespace));
Map<String, String> customParameters = new HashMap<>();
customParameters.put("transaction.enableAnnotation", enableAnnotations);
BlueprintConfigurationImpl blueprintConfiguration = new BlueprintConfigurationImpl(namespaces, null, customParameters, null, null);
Blueprint blueprint = new Blueprint(blueprintConfiguration, beanClasses);
ByteArrayOutputStream os = new ByteArrayOutputStream();
new BlueprintFileWriter(os).write(blueprint);
xmlAsBytes = os.toByteArray();
System.out.println(new String(xmlAsBytes, "UTF-8"));
document = readToDocument(xmlAsBytes, false);
xpath = XPathFactory.newInstance().newXPath();
}
@Test
public void testNS1_0() throws Exception {
writeXML(NS_TX1_0, "true");
assertNull(getEnableAnnotationTx1());
}
@Test
public void testNS1_1() throws Exception {
writeXML(NS_TX1_1, "true");
assertNull(getEnableAnnotationTx1());
}
@Test
public void testNS1_2_enabled() throws Exception {
writeXML(NS_TX1_2, "true");
assertNotNull(getEnableAnnotationTx1());
}
@Test
public void testNS1_2_disabled() throws Exception {
writeXML(NS_TX1_2, "false");
assertNull(getEnableAnnotationTx1());
}
@Test
public void testNS1_2_default() throws Exception {
writeXML(NS_TX1_2, null);
assertNotNull(getEnableAnnotationTx1());
}
private Document readToDocument(byte[] xmlAsBytes, boolean nameSpaceAware)
throws ParserConfigurationException,
SAXException, IOException {
InputStream is = new ByteArrayInputStream(xmlAsBytes);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(nameSpaceAware);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
return builder.parse(is);
}
private Node getEnableAnnotationTx1() throws XPathExpressionException {
return (Node) xpath.evaluate("/blueprint/enable-annotations", document, XPathConstants.NODE);
}
}
|
3e12a18c6242936d634ef588ad51f7717d1ed0fe | 378 | java | Java | mobile_app1/module1183/src/main/java/module1183packageJava0/Foo1505.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 70 | 2021-01-22T16:48:06.000Z | 2022-02-16T10:37:33.000Z | mobile_app1/module1183/src/main/java/module1183packageJava0/Foo1505.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 16 | 2021-01-22T20:52:52.000Z | 2021-08-09T17:51:24.000Z | mobile_app1/module1183/src/main/java/module1183packageJava0/Foo1505.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 5 | 2021-01-26T13:53:49.000Z | 2021-08-11T20:10:57.000Z | 11.8125 | 48 | 0.579365 | 7,857 | package module1183packageJava0;
import java.lang.Integer;
public class Foo1505 {
Integer int0;
public void foo0() {
new module1183packageJava0.Foo1504().foo5();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
}
|
3e12a1a22693cb527afc90e66a87c22a79551f72 | 12,219 | java | Java | platform/android/sdk/src/com/ansca/corona/VideoActivity.java | pakorns/corona | 7e12e32395c08b57ca1e43f656fa6c13d90c8778 | [
"MIT"
] | 1,968 | 2018-12-30T21:14:22.000Z | 2022-03-31T23:48:16.000Z | platform/android/sdk/src/com/ansca/corona/VideoActivity.java | pakorns/corona | 7e12e32395c08b57ca1e43f656fa6c13d90c8778 | [
"MIT"
] | 303 | 2019-01-02T19:36:43.000Z | 2022-03-31T23:52:45.000Z | platform/android/sdk/src/com/ansca/corona/VideoActivity.java | pakorns/corona | 7e12e32395c08b57ca1e43f656fa6c13d90c8778 | [
"MIT"
] | 254 | 2019-01-02T19:05:52.000Z | 2022-03-30T06:32:28.000Z | 37.845201 | 123 | 0.726685 | 7,858 | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: upchh@example.com
//
//////////////////////////////////////////////////////////////////////////////
package com.ansca.corona;
/**
* Activity used to play a video file or stream via Corona's media.playVideo() function.
* Example usage:
* android.content.Intent myIntent = new android.content.Intent(myActivity, VideoActivity.class);
* myIntent.putExtra("video_uri", "http://www.mydomain.com/myvideo.mp3" );
* myIntent.putExtra("video_id", uniqueIntegerIdForThisActivity);
* myIntent.putExtra("media_controls_enabled", true);
* myActivity.startActivity(myIntent);
*/
public class VideoActivity extends android.app.Activity {
/** View used to display the video. */
private CoronaVideoView fVideoView;
/** Unique integer ID assigned to this activity by this application's MediaManager class. */
private long fVideoId;
/** Set true if the activity's onPause() was called. Set false if currently active. */
private boolean fWasActivityPaused;
/** Set true if the video view is currently suspended. Set false if running/resumed. */
private boolean fWasVideoSuspended;
/** Broadcast receiver which receives and handles screen related events. */
private ScreenEventHandler fScreenEventHandler;
/** Animated spinner indicating that something is loading. */
private android.widget.ProgressBar fLoadingIndicatorView;
/**
* Initializes this activity's UI and member variables.
*/
@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Wrap this activity context with a new context using the newest theme available on the system.
// This way, child views can use the newest theme and this activity can use the fullscreen theme.
int themeId;
if (android.os.Build.VERSION.SDK_INT >= 14) {
themeId = 16974120; // android.R.style.Theme_DeviceDefault
}
else if (android.os.Build.VERSION.SDK_INT >= 11) {
themeId = 16973931; // android.R.style.Theme_Holo
}
else {
themeId = android.R.style.Theme_Dialog;
}
android.view.ContextThemeWrapper themedContextWrapper;
themedContextWrapper = new android.view.ContextThemeWrapper(this, themeId);
// Listen for when the screen turns off/on and when the screen lock is hidden/shown.
// We need this to avoid playing a video while the screen lock is covering up the activity.
fScreenEventHandler = new ScreenEventHandler(this);
// Create the video view and center it within the window.
android.widget.FrameLayout layout = new android.widget.FrameLayout(themedContextWrapper);
layout.setBackgroundColor(android.graphics.Color.BLACK);
setContentView(layout);
android.widget.FrameLayout.LayoutParams layoutParams;
layoutParams = new android.widget.FrameLayout.LayoutParams(
android.widget.FrameLayout.LayoutParams.FILL_PARENT,
android.widget.FrameLayout.LayoutParams.FILL_PARENT,
android.view.Gravity.CENTER_HORIZONTAL | android.view.Gravity.CENTER_VERTICAL);
fVideoView = new CoronaVideoView(themedContextWrapper);
layout.addView(fVideoView, layoutParams);
// Set up the volume controls to adjust the "media" volume instead of the default "ringer" volume.
setVolumeControlStream(android.media.AudioManager.STREAM_MUSIC);
// Create an loading indicator and place it on top of the video view.
// Will be shown while the video is loading.
fLoadingIndicatorView = new android.widget.ProgressBar(themedContextWrapper);
fLoadingIndicatorView.setLayoutParams(new android.widget.FrameLayout.LayoutParams(
android.widget.FrameLayout.LayoutParams.WRAP_CONTENT,
android.widget.FrameLayout.LayoutParams.WRAP_CONTENT,
android.view.Gravity.CENTER));
layout.addView(fLoadingIndicatorView);
// Set up listeners to show/hide the loading indicator while the video is loading/loaded.
fVideoView.setOnPreparedListener(new android.media.MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(android.media.MediaPlayer mediaPlayer) {
// *** A new media player was created. ***
// Hide the loading indicator. The video is usuallly loaded when a new player has been created.
fLoadingIndicatorView.setVisibility(android.view.View.GONE);
// Set up info listeners on the media player to know when it is buffering, such as during a seek.
// Note: There is a bug on some devices (ex: LG Nexus 4) where buffering events will never be received.
mediaPlayer.setOnInfoListener(new android.media.MediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(android.media.MediaPlayer mediaPlayer, int what, int extra) {
fLoadingIndicatorView.setVisibility(android.view.View.GONE);
switch (what) {
case android.media.MediaPlayer.MEDIA_INFO_BUFFERING_START:
// Show the loading indicating while the video is buffering. It can't play right now.
fLoadingIndicatorView.setVisibility(android.view.View.VISIBLE);
break;
case android.media.MediaPlayer.MEDIA_INFO_BUFFERING_END:
// Hide the loading indicating when the video has finished buffering,
// indicating that the video can now play at its current position.
fLoadingIndicatorView.setVisibility(android.view.View.GONE);
break;
}
return false;
}
});
}
});
// Set up this activity to automatically close once the video ends or if an error has been encountered.
fVideoView.setOnCompletionListener(new android.media.MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(android.media.MediaPlayer player) {
for (com.ansca.corona.CoronaRuntime runtime : com.ansca.corona.CoronaRuntimeProvider.getAllCoronaRuntimes()) {
if (!runtime.wasDisposed()) {
runtime.getTaskDispatcher().send(new com.ansca.corona.events.VideoEndedTask(fVideoId));
}
MediaManager mediaManager = runtime.getController().getMediaManager();
if (mediaManager != null) {
mediaManager.resumeAll();
}
}
finish();
}
});
// Set up the video view and start playing.
if (getIntent().getExtras().getBoolean("media_controls_enabled")) {
fVideoView.setMediaController(new android.widget.MediaController(themedContextWrapper));
}
fVideoView.setVideoURIUsingCoronaProxy(android.net.Uri.parse(getIntent().getExtras().getString("video_uri")));
fVideoId = getIntent().getExtras().getLong("video_id");
fWasActivityPaused = false;
fWasVideoSuspended = false;
fVideoView.start();
}
/**
* Closes this activity.
* Overriden to prevent this activity from doing a slide-out animation.
*/
@Override
public void finish() {
// Have the base class close this window.
super.finish();
// If this activity is flagged to not show transition animations, then disable the slide-out animation.
if ((getIntent().getFlags() & android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
overridePendingTransition(0, 0);
}
}
/** Called when the back key has been pressed. */
@Override
public void onBackPressed() {
// Let the base class finish/close the activity.
super.onBackPressed();
// Traverse all active Corona runtimes.
for (CoronaRuntime runtime : CoronaRuntimeProvider.getAllCoronaRuntimes()) {
// Dispatch a Lua completion event.
if (!runtime.wasDisposed()) {
runtime.getTaskDispatcher().send(new com.ansca.corona.events.VideoEndedTask(fVideoId));
}
// Resume all other media content belonging to the runtime.
MediaManager mediaManager = runtime.getController().getMediaManager();
if (mediaManager != null) {
mediaManager.resumeAll();
}
}
}
/** Called when the activity is no longer visible or active. */
@Override
protected void onPause() {
super.onPause();
// Suspend video playback.
fWasActivityPaused = true;
updateSuspendResumeState();
}
/**
* Called when the activity has been brought to the foreground.
* Note: The lock screen might be covering up the activity during a resume.
*/
@Override
protected void onResume() {
super.onResume();
// Resume video back to its last playback state.
fWasActivityPaused = false;
updateSuspendResumeState();
}
/** Called just before the activity has been closed and destroyed. */
@Override
protected void onDestroy() {
// Unregister the following event handler from the system.
if (fScreenEventHandler != null) {
fScreenEventHandler.dispose();
fScreenEventHandler = null;
}
// Destroy this activity.
super.onDestroy();
}
/** Suspends or resumes the video view based on the current state of the activity and screen lock. */
private void updateSuspendResumeState() {
if (fWasActivityPaused) {
// The activity is currently paused.
// Suspend the video if not done already.
if (fWasVideoSuspended == false) {
fWasVideoSuspended = true;
fVideoView.suspend();
}
}
else if (isScreenLocked() == false) {
// The activity is currently active and the screen is unlocked.
// Resume the video if not done already.
// Note: Many devices will call the activity's onResume() method while the screen lock is still displayed.
// We should never resume the video while the screen lock is shown, because the video can't be seen.
if (fWasVideoSuspended) {
fWasVideoSuspended = false;
fVideoView.resume();
}
}
}
/**
* Determines if the screen is currently locked and does not allow user interaction. This includes when the screen is off.
* @return Returns true if screen is locked. Returns false if screen is unlocked and allows user interaction.
*/
private boolean isScreenLocked() {
android.app.KeyguardManager keyguardManager;
keyguardManager = (android.app.KeyguardManager)getSystemService(android.content.Context.KEYGUARD_SERVICE);
return keyguardManager.inKeyguardRestrictedInputMode();
}
/** Private class used to listen for broadcasted screen events. */
private static class ScreenEventHandler extends android.content.BroadcastReceiver {
/** The video activity that owns this object. */
private VideoActivity fVideoActivity;
/**
* Creates a new event handler for broadcasted screen events.
* @param videoActivity The video activity that owns this object. Cannot be null.
*/
public ScreenEventHandler(VideoActivity videoActivity) {
super();
// Validate.
if (videoActivity == null) {
throw new NullPointerException();
}
// Initialize member variables.
fVideoActivity = videoActivity;
// Register this broadcast receiver.
android.content.IntentFilter intentFilter = new android.content.IntentFilter();
intentFilter.addAction(android.content.Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(android.content.Intent.ACTION_SCREEN_ON);
intentFilter.addAction(android.content.Intent.ACTION_USER_PRESENT);
fVideoActivity.registerReceiver(this, intentFilter);
}
/**
* Unregisters and disables this broadcast receiver.
* Must be called by the video activity's onDestroy() method.
*/
public void dispose() {
fVideoActivity.unregisterReceiver(this);
}
/**
* This method is called when a screen event is being broadcasted.
* @param context The context in which the receiver is running.
* @param intent The intent being received. This contains the event.
*/
@Override
public void onReceive(android.content.Context context, android.content.Intent intent) {
// Validate.
if (intent == null) {
return;
}
// Fetch the event's unique string key.
String actionName = intent.getAction();
if ((actionName == null) || (actionName.length() <= 0)) {
return;
}
// Update the video's suspend/resume state if the screen's current state has changed.
if (actionName.equals(android.content.Intent.ACTION_SCREEN_OFF) ||
actionName.equals(android.content.Intent.ACTION_SCREEN_ON) ||
actionName.equals(android.content.Intent.ACTION_USER_PRESENT))
{
fVideoActivity.updateSuspendResumeState();
}
}
}
}
|
3e12a1a41a1a29bf048af1b1b9cea1f7fe899f61 | 823 | java | Java | ego-item/src/main/java/com/ego/item/controller/TbItemParamItemController.java | tianyuchena/ego | bd30328a89a2e0ac316f2edb61fef4f0f8ce568f | [
"AFL-3.0"
] | null | null | null | ego-item/src/main/java/com/ego/item/controller/TbItemParamItemController.java | tianyuchena/ego | bd30328a89a2e0ac316f2edb61fef4f0f8ce568f | [
"AFL-3.0"
] | 2 | 2020-06-30T23:10:34.000Z | 2022-03-31T20:47:48.000Z | ego-item/src/main/java/com/ego/item/controller/TbItemParamItemController.java | tianyuchena/ego | bd30328a89a2e0ac316f2edb61fef4f0f8ce568f | [
"AFL-3.0"
] | null | null | null | 27.433333 | 93 | 0.770352 | 7,859 | package com.ego.item.controller;
import com.ego.item.service.TbItemParamItemService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* @Auther: cty
* @Date: 2020/5/26 22:37
* @Description:
* @version: 1.0
*/
@Controller
public class TbItemParamItemController {
@Resource
private TbItemParamItemService tbItemParamItemServiceImpl;
@RequestMapping(value = "item/param/{itemId}.html", produces = "text/html;charset=utf-8")
@ResponseBody
public String showParamItem(@PathVariable long itemId)
{
return tbItemParamItemServiceImpl.showParamItem(itemId);
}
}
|
3e12a253d33f522e862468b5143aca09501af362 | 274 | java | Java | src/main/java/top/atstudy/component/user/vo/req/AdminUserQuery.java | HDXin/advistory-platform | 7ecb29f5ba7fe6e3b2e47daf5e277549328e2726 | [
"Apache-2.0"
] | null | null | null | src/main/java/top/atstudy/component/user/vo/req/AdminUserQuery.java | HDXin/advistory-platform | 7ecb29f5ba7fe6e3b2e47daf5e277549328e2726 | [
"Apache-2.0"
] | null | null | null | src/main/java/top/atstudy/component/user/vo/req/AdminUserQuery.java | HDXin/advistory-platform | 7ecb29f5ba7fe6e3b2e47daf5e277549328e2726 | [
"Apache-2.0"
] | null | null | null | 17.125 | 48 | 0.613139 | 7,860 | package top.atstudy.component.user.vo.req;
import top.atstudy.component.base.Pagination;
/**
* AdminUser 条件查询包装对象模板
*
* =========================================
* <p>
* Contributors :
* Mybatis auto generator
*/
public class AdminUserQuery extends Pagination {
}
|
3e12a27ee4050f046072e81ca15d58ff4debf0f2 | 2,416 | java | Java | Monorail (copy 1)/src/monorail/Monorail.java | bavShehata/learningJava | 5d49630815750ee326187cbc02aeb271b950766e | [
"MIT"
] | null | null | null | Monorail (copy 1)/src/monorail/Monorail.java | bavShehata/learningJava | 5d49630815750ee326187cbc02aeb271b950766e | [
"MIT"
] | null | null | null | Monorail (copy 1)/src/monorail/Monorail.java | bavShehata/learningJava | 5d49630815750ee326187cbc02aeb271b950766e | [
"MIT"
] | null | null | null | 35.014493 | 89 | 0.59106 | 7,861 | package monorail;
import java.util.ArrayList; // import the ArrayList class
import java.io.*;
public class Monorail {
// A function that writes an arraylist of objects to a file
public static void writeArrayList(String o, Object obj) {
try {
FileOutputStream fos = new FileOutputStream(o + ".txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
} catch (IOException e) {
System.out.println("File doesn't exist: " + o + ".txt");
}
}
// A function that reads an arraylist of objects to a file
public static Object readArrayList(String o) {
try {
FileInputStream fis = new FileInputStream(o + ".txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Object arrayList = ois.readObject();
ois.close();
fis.close();
return arrayList;
} catch (IOException e) {
System.out.println("File doesn't exist: " + o + ".txt");
} catch (ClassNotFoundException e) {
System.out.println("Class not found: " + o);
}
return new Object();
}
public static ArrayList<Route> routes = new ArrayList<Route>();
public static ArrayList<Ticket> tickets = new ArrayList<>();
public static ArrayList<Passenger> passengers = new ArrayList<>();
public static void main(String[] args) {
tickets.add(new Ticket(0)); tickets.add(new Ticket(1));
tickets.add(new Ticket(2));
System.out.println("Here are current tickets: ");
for (Ticket t : tickets) {
System.out.println(t.display());
}
writeArrayList("Ticket", tickets);
System.out.println("Data written successfully");
tickets.clear();
System.out.println("ArrayList Cleared successfully\nHere are current tickets: ");
for (Ticket t : tickets) {
System.out.println(t.display());
}
tickets = (ArrayList<Ticket>) readArrayList("Ticket");
System.out.println("Data read successfully");
System.out.println("Here are current tickets: ");
for (Ticket t : tickets) {
System.out.println(t.display());
}
PassengerMethodsUI PMUI = new PassengerMethodsUI();
PMUI.setVisible(true);
}
}
|
3e12a29c10ae80bfe19da848334bc3d4f8f4a731 | 3,670 | java | Java | src/itcl/itcl/lang/Migrate.java | fabrice-ducos/jaclin | 4a984f1178bc4c5159530125723c925d8f0071ac | [
"TCL"
] | null | null | null | src/itcl/itcl/lang/Migrate.java | fabrice-ducos/jaclin | 4a984f1178bc4c5159530125723c925d8f0071ac | [
"TCL"
] | null | null | null | src/itcl/itcl/lang/Migrate.java | fabrice-ducos/jaclin | 4a984f1178bc4c5159530125723c925d8f0071ac | [
"TCL"
] | null | null | null | 28.695313 | 84 | 0.539069 | 7,862 | /*
* ------------------------------------------------------------------------
* PACKAGE: [incr Tcl]
* DESCRIPTION: Object-Oriented Extensions to Tcl
*
* This file contains procedures that belong in the Tcl/Tk core.
* Hopefully, they'll migrate there soon.
*
* ========================================================================
* AUTHOR: Michael J. McLennan
* Bell Labs Innovations for Lucent Technologies
* kenaa@example.com
* http://www.tcltk.com/itcl
*
* RCS: $Id: Migrate.java,v 1.4 2005/01/31 21:19:03 mo Exp $
* ========================================================================
* Copyright (c) 1993-1998 Lucent Technologies, Inc.
* ------------------------------------------------------------------------
* See the file "license.itcl" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
package itcl.lang;
import tcl.lang.*;
class Migrate {
/*
*----------------------------------------------------------------------
*
* _Tcl_GetCallFrame -> Migrate.GetCallFrame
*
* Checks the call stack and returns the call frame some number
* of levels up. It is often useful to know the invocation
* context for a command.
*
* Results:
* Returns a token for the call frame 0 or more levels up in
* the call stack.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static
CallFrame
GetCallFrame(
Interp interp, // interpreter being queried
int level) // number of levels up in the call stack (>= 0)
{
if (level < 0) {
Util.Assert(false, "Migrate.GetCallFrame called with bad number of levels");
}
return ItclAccess.getCallFrame(interp, level);
}
/*
*----------------------------------------------------------------------
*
* _Tcl_ActivateCallFrame -> Migrate.ActivateCallFrame
*
* Makes an existing call frame the current frame on the
* call stack. Usually called in conjunction with
* GetCallFrame to simulate the effect of an "uplevel"
* command.
*
* Note that this procedure is different from Tcl_PushCallFrame,
* which adds a new call frame to the call stack. This procedure
* assumes that the call frame is already initialized, and it
* merely activates it on the call stack.
*
* Results:
* Returns a token for the call frame that was in effect before
* activating the new context. That call frame can be restored
* by calling _Tcl_ActivateCallFrame again.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static
CallFrame
ActivateCallFrame(
Interp interp, // interpreter being queried
CallFrame frame) // call frame to be activated
{
return ItclAccess.activateCallFrame(interp, frame);
}
/*
*----------------------------------------------------------------------
*
* _TclNewVar -> Migrate.NewVar
*
* Create a new variable that will eventually be
* entered into a hashtable.
*
* Results:
* The return value is a reference to the new variable structure. It is
* marked as a scalar variable (and not a link or array variable). Its
* value initially is null. The variable is not part of any hash table
* yet. Since it will be in a hashtable and not in a call frame, its
* name field is set null. It is initially marked as undefined.
*
* Side effects:
* Storage gets allocated.
*
*----------------------------------------------------------------------
*/
static
Var
NewVar()
{
return ItclAccess.newVar();
}
} // end class Migrate
|
3e12a29e547492f070abaf7cae21cb522eb1c38b | 391 | java | Java | InstantNoodlesMaster/src/me/evis/mobile/noodle/StartTimerWidget4Provider.java | evisong/noodlesmaster | ac841a30a25bd4907d35d505142ca93f1f76a878 | [
"Apache-2.0"
] | 2 | 2015-02-28T05:26:13.000Z | 2015-07-16T09:30:04.000Z | InstantNoodlesMaster/src/me/evis/mobile/noodle/StartTimerWidget4Provider.java | evisong/noodlesmaster | ac841a30a25bd4907d35d505142ca93f1f76a878 | [
"Apache-2.0"
] | null | null | null | InstantNoodlesMaster/src/me/evis/mobile/noodle/StartTimerWidget4Provider.java | evisong/noodlesmaster | ac841a30a25bd4907d35d505142ca93f1f76a878 | [
"Apache-2.0"
] | null | null | null | 23 | 82 | 0.680307 | 7,863 | package me.evis.mobile.noodle;
import android.content.Context;
public class StartTimerWidget4Provider extends AbstractStartTimerWidgetProvider {
@Override
protected String getTotalSecsLabel(Context context) {
return context.getString(R.string.widget4_label);
}
@Override
protected int getTotalSecs() {
return 4 * 60 + 30;
};
}
|
3e12a429f862e793e72710c8d30b732a2a41a550 | 843 | java | Java | Day 16/Toggle.java | AmishaTomar0303/Daily-Work | 1f759f6ee83c00ff34cdd9c992f443429146799b | [
"MIT"
] | null | null | null | Day 16/Toggle.java | AmishaTomar0303/Daily-Work | 1f759f6ee83c00ff34cdd9c992f443429146799b | [
"MIT"
] | null | null | null | Day 16/Toggle.java | AmishaTomar0303/Daily-Work | 1f759f6ee83c00ff34cdd9c992f443429146799b | [
"MIT"
] | null | null | null | 22.783784 | 58 | 0.502966 | 7,864 | package com.cognizant;
import java.util.Scanner;
public class Toggle {
public static void main(String []args) {
System.out.println("Enter a String");
Scanner scan= new Scanner(System.in);
String a= scan.nextLine();
System.out.println(toggleString(a));
}
public static String toggleString(String sentence)
{
String toggled = "";
for(int i=0; i<sentence.length(); i++)
{
char letter = sentence.charAt(i);
if(i%2==0)
{
letter = Character.toLowerCase(letter);
toggled = toggled + letter;
}
else
{
letter = Character.toUpperCase(letter);
toggled = toggled + letter;
}
}
return toggled;
}}
|
3e12a44c06aadf788cccd29d53c854c8cc73d452 | 1,917 | java | Java | src/test/java/controller/TurnTest.java | estebanzuniga/final-reality-estebanzuniga | 7806560c071b40cd87a694ea04a3d04f30bb7af9 | [
"CC-BY-4.0"
] | null | null | null | src/test/java/controller/TurnTest.java | estebanzuniga/final-reality-estebanzuniga | 7806560c071b40cd87a694ea04a3d04f30bb7af9 | [
"CC-BY-4.0"
] | null | null | null | src/test/java/controller/TurnTest.java | estebanzuniga/final-reality-estebanzuniga | 7806560c071b40cd87a694ea04a3d04f30bb7af9 | [
"CC-BY-4.0"
] | null | null | null | 33.631579 | 66 | 0.643192 | 7,865 | package controller;
import com.github.estebanzuniga.finalreality.model.weapon.IWeapon;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TurnTest extends GameControllerTest {
@BeforeEach
void setup() {
super.basicSetUp();
}
@Test
void checkPlayerTurnTest() {
for (IWeapon weapon : testEngineerWeaponList) {
checkPlayerTurn(testEngineer, testEnemy, weapon);
}
for (IWeapon weapon : testKnightWeaponList) {
checkPlayerTurn(testKnight, testEnemy, weapon);
}
for (IWeapon weapon : testThiefWeaponList) {
checkPlayerTurn(testThief, testEnemy, weapon);
}
for (IWeapon weapon : testWhiteMageWeaponList) {
checkPlayerTurn(testWhiteMage, testEnemy, weapon);
}
for (IWeapon weapon : testBlackMageWeaponList) {
checkPlayerTurn(testBlackMage, testEnemy, weapon);
}
}
@Test
void checkEnemyTurnTest() {
for (IWeapon weapon : testEngineerWeaponList) {
controllerTest.equipWeapon(testEngineer, weapon);
checkEnemyTurn(testEnemy, testEngineer);
}
for (IWeapon weapon : testKnightWeaponList) {
controllerTest.equipWeapon(testKnight, weapon);
checkEnemyTurn(testEnemy, testKnight);
}
for (IWeapon weapon : testThiefWeaponList) {
controllerTest.equipWeapon(testThief, weapon);
checkEnemyTurn(testEnemy, testThief);
}
for (IWeapon weapon : testWhiteMageWeaponList) {
controllerTest.equipWeapon(testWhiteMage, weapon);
checkEnemyTurn(testEnemy, testWhiteMage);
}
for (IWeapon weapon : testBlackMageWeaponList) {
controllerTest.equipWeapon(testBlackMage, weapon);
checkEnemyTurn(testEnemy, testBlackMage);
}
}
}
|
3e12a4fda357f6c6148280eabde82913d430926b | 7,899 | java | Java | src/test/java/com/dukeacademy/testexecutor/models/JavaFileTest.java | limhawjia/DukeAcademy | 1309d2afc19cdb3bc8ac017181edfc4c43914027 | [
"MIT"
] | 1 | 2020-01-24T19:35:21.000Z | 2020-01-24T19:35:21.000Z | src/test/java/com/dukeacademy/testexecutor/models/JavaFileTest.java | alxkohh/main | 1309d2afc19cdb3bc8ac017181edfc4c43914027 | [
"MIT"
] | 117 | 2019-09-13T07:50:37.000Z | 2019-11-14T06:15:09.000Z | src/test/java/com/dukeacademy/testexecutor/models/JavaFileTest.java | alxkohh/main | 1309d2afc19cdb3bc8ac017181edfc4c43914027 | [
"MIT"
] | 4 | 2019-09-06T15:18:35.000Z | 2021-04-18T19:58:02.000Z | 43.163934 | 111 | 0.698949 | 7,866 | package com.dukeacademy.testexecutor.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.dukeacademy.testexecutor.environment.exceptions.JavaFileCreationException;
import com.dukeacademy.testexecutor.exceptions.IncorrectCanonicalNameException;
class JavaFileTest {
@TempDir public Path tempFolder;
private final String fooProgram = "public class Foo {}";
private final String insideFooProgram = "package packaged.inside;\n"
+ "public class Foo {}";
/**
* Instance creation should succeed if the class file actually exists.
* @throws IOException
*/
@Test void testJavaFileConstructorFileExists() throws IOException, JavaFileCreationException,
IncorrectCanonicalNameException {
String basePath = tempFolder.toString();
Path filePath = tempFolder.resolve("Foo.java");
filePath.toFile().createNewFile();
Files.writeString(filePath, fooProgram);
new JavaFile("Foo", basePath);
// Tests when the class is packaged
Path packageFolders = tempFolder.resolve("packaged").resolve("inside");
packageFolders.toFile().mkdirs();
Path packagedFilePath = packageFolders.resolve("Foo.java");
packagedFilePath.toFile().createNewFile();
Files.writeString(packagedFilePath, insideFooProgram);
new JavaFile("packaged.inside.Foo", basePath);
}
@Test void testJavaFileConstructorAndGetters() throws IOException, JavaFileCreationException,
IncorrectCanonicalNameException {
String basePath = tempFolder.toString();
Path filePath = tempFolder.resolve("Foo.java");
filePath.toFile().createNewFile();
Files.writeString(filePath, fooProgram);
JavaFile fooFile = new JavaFile("Foo", basePath);
assertEquals("Foo", fooFile.getCanonicalName());
assertEquals(basePath, fooFile.getClassPath());
// Tests when the class is packaged
Path packageFolders = tempFolder.resolve("packaged").resolve("inside");
packageFolders.toFile().mkdirs();
Path packagedFilePath = packageFolders.resolve("Foo.java");
packagedFilePath.toFile().createNewFile();
Files.writeString(packagedFilePath, insideFooProgram);
JavaFile packagedFooFile = new JavaFile("packaged.inside.Foo", basePath);
assertEquals("packaged.inside.Foo", packagedFooFile.getCanonicalName());
assertEquals(basePath, packagedFooFile.getClassPath());
}
@Test void testJavaFileConstructorMismatchedCanonicalName() {
// TODO
}
/**
* Instance creation should fail if the class does not exist. A FileNotFoundException should be thrown.
*/
@Test void testJavaFileConstructorFileDoesNotExists() throws IOException {
String basePath = tempFolder.toString();
assertThrows(FileNotFoundException.class, () -> new JavaFile("Foo", basePath));
assertThrows(FileNotFoundException.class, () -> new JavaFile("", basePath));
assertThrows(FileNotFoundException.class, () -> new JavaFile("Foo", ""));
// Tests when another file exists in the folder
tempFolder.resolve("Bar.class").toFile().createNewFile();
assertThrows(FileNotFoundException.class, () -> new JavaFile("Foo", basePath));
// Tests when the classpath is wrong
assertThrows(FileNotFoundException.class, () -> new JavaFile("Bar", "/duke/academy"));
// Tests when package is not reflected in canonical name
Path packageFolders = tempFolder.resolve("packaged").resolve("inside");
packageFolders.toFile().mkdirs();
packageFolders.resolve("Foo.java").toFile().createNewFile();
assertThrows(FileNotFoundException.class, () -> new JavaFile("Foo", basePath));
}
@Test void testJavaFileConstructorNullArguments() {
String basePath = tempFolder.toString();
assertThrows(NullPointerException.class, () -> new JavaFile(null, basePath));
assertThrows(NullPointerException.class, () -> new JavaFile("Foo", null));
}
@Test
void testGetAbsolutePath() throws IOException, JavaFileCreationException, IncorrectCanonicalNameException {
String basePath = tempFolder.toString();
Path fooPath = tempFolder.resolve("Foo.java");
fooPath.toFile().createNewFile();
Files.writeString(fooPath, fooProgram);
String fooExpectedAbsolutePath = fooPath.toString();
String fooActualAbsolutePath = new JavaFile("Foo", basePath).getAbsolutePath();
assertEquals(fooExpectedAbsolutePath, fooActualAbsolutePath);
// Check absolute path for packaged classes
Path fooPackageFolders = tempFolder.resolve("packaged").resolve("inside");
fooPackageFolders.toFile().mkdirs();
Path fooInsidePath = fooPackageFolders.resolve("Foo.java");
fooInsidePath.toFile().createNewFile();
Files.writeString(fooInsidePath, insideFooProgram);
String fooInsideExpectedPath = fooInsidePath.toString();
String fooInsideActualPath = new JavaFile("packaged.inside.Foo", basePath)
.getAbsolutePath();
assertEquals(fooInsideExpectedPath, fooInsideActualPath);
}
@Test
void testGetFile() throws IOException, JavaFileCreationException, IncorrectCanonicalNameException {
String basePath = tempFolder.toString();
Path fooPath = tempFolder.resolve("Foo.java");
fooPath.toFile().createNewFile();
Files.writeString(fooPath, fooProgram);
File expectedFooFile = fooPath.toFile();
File actualFooFile = new JavaFile("Foo", basePath).getFile();
assertEquals(expectedFooFile, actualFooFile);
// Check File for packaged classes.
Path fooPackageFolders = tempFolder.resolve("packaged").resolve("inside");
fooPackageFolders.toFile().mkdirs();
Path insideFooPath = fooPackageFolders.resolve("Foo.java");
insideFooPath.toFile().createNewFile();
Files.writeString(insideFooPath, insideFooProgram);
File expectedInsideFooFile = insideFooPath.toFile();
File actualInsideFooFile = new JavaFile("packaged.inside.Foo", basePath).getFile();
assertEquals(expectedInsideFooFile, actualInsideFooFile);
}
@Test
void testEquals() throws IOException, JavaFileCreationException, IncorrectCanonicalNameException {
String basePath = tempFolder.toString();
Path fooPath = tempFolder.resolve("Foo.java");
fooPath.toFile().createNewFile();
Files.writeString(fooPath, fooProgram);
Path barPath = tempFolder.resolve("Bar.java");
barPath.toFile().createNewFile();
Files.writeString(barPath, "public class Bar {}");
JavaFile fooFile1 = new JavaFile("Foo", basePath);
JavaFile fooFile2 = new JavaFile("Foo", basePath);
assertEquals(fooFile1, fooFile2);
JavaFile barFile = new JavaFile("Bar", basePath);
assertNotEquals(fooFile1, barFile);
// Tests for classes with the same name but different class paths.
Path packageFolders = tempFolder.resolve("packaged").resolve("inside");
packageFolders.toFile().mkdirs();
Path packagedFooPath = packageFolders.resolve("Foo.java");
packagedFooPath.toFile().createNewFile();
Files.writeString(packagedFooPath, insideFooProgram);
JavaFile packagedFooFile = new JavaFile("packaged.inside.Foo", basePath);
assertNotEquals(fooFile1, packagedFooFile);
}
}
|
3e12a538c63f183d166812475895f7e66fa6afd9 | 3,418 | java | Java | AssignmentII/Back-5/Network.java | niallmartinryan/Telecommunications-II | 99790d9d67bdb4965f3581338427dd331d4791fc | [
"MIT"
] | null | null | null | AssignmentII/Back-5/Network.java | niallmartinryan/Telecommunications-II | 99790d9d67bdb4965f3581338427dd331d4791fc | [
"MIT"
] | null | null | null | AssignmentII/Back-5/Network.java | niallmartinryan/Telecommunications-II | 99790d9d67bdb4965f3581338427dd331d4791fc | [
"MIT"
] | null | null | null | 28.247934 | 136 | 0.625219 | 7,867 | import processing.core.PApplet;
import java.util.Random;
import java.util.*;
import processing.core.PApplet;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetSocketAddress; //trying this for the moment
import java.util.ArrayList;
import tcdIO.*;
public class Network extends PApplet{
//processing stuff
public static int MIN_DISTANCE = 150;
public static final int LAPTOP_MAX_SIZE = 40;
public static final int SMARTPHONE_MAX_SIZE = 40;
public static final int EDGE_MAX_SIZE = 100;
public int laptopCount =0;
public int smartPhoneCount =0;
public int edgeCount =0;
Laptop [] laptops;
int laptopGraphicsLength = 0;
int smartPhoneGraphicsLength =0;
SmartPhone [] smartPhones;
Edge [] edges;
Network(){
this.laptops = new Laptop[LAPTOP_MAX_SIZE];
this.smartPhones = new SmartPhone[SMARTPHONE_MAX_SIZE];
this.edges = new Edge[EDGE_MAX_SIZE];
}
// is the post-increment
public void add(SmartPhone phone){
smartPhones[smartPhoneCount++] = phone;
}
public void add(Laptop lap){
laptops[laptopCount++] = lap;
}
public void add(Laptop [] laps){
for(int i=0;i<laps.length;i++,laptopCount++){
laptops[laptopCount] = laps[i];
}
}
public void add(SmartPhone [] phones){
for(int i=0;i<phones.length;i++,smartPhoneCount++){
smartPhones[smartPhoneCount] = phones[i];
}
}
public void add(Edge edge){
edges[edgeCount++] = edge;
}
public void add(Edge [] edges){
for(int i=0;i<edges.length;i++,edgeCount++){
this.edges[edgeCount] = edges[i];
}
}
public void drawNetwork(PApplet app){
for(int i =0; i< laptopCount;i++){
laptops[i].LaptopGraphics.drawLaptops(app);
}
for(int i =0; i< smartPhoneCount;i++){
smartPhones[i].smartPhoneGraphics.drawSmartPhones(app);
}
for(int i=0; i< edgeCount;i++){
edges[i].drawEdges(app);
}
}
// change this method to include height and width? or just remove them
public boolean checkCollisions(int xpos, int ypos, int width, int height){
for(int i=0; i< laptopGraphicsLength;i++){
if(MIN_DISTANCE < Math.sqrt((xpos - laptops[i].LaptopGraphics.xpos)^2 +(ypos - laptops[i].LaptopGraphics.ypos)^2)){
return false;
}
}
for(int i=0; i< smartPhoneGraphicsLength;i++){
if(MIN_DISTANCE < Math.sqrt((xpos - smartPhones[i].smartPhoneGraphics.xpos)^2 +(ypos - smartPhones[i].smartPhoneGraphics.ypos)^2)){
return false;
}
}
return true;
}
public Laptop getLaptop(int id){
for(int i=0;i<laptopCount;i++){
if(laptops[i].id == id){
return laptops[i];
}
}
return null; // not found
}
// public SmartPhone getSmartPhone(){
//
// }
// if returns true.. didnt find any conflicts
public boolean checkEdges(Edge edge){
boolean match = true;
for(int i=0;i< edgeCount;i++){
if(!edges[i].checkEdges(edge)){
return false;
}
}
return match;
}
public void printEdges(){
System.out.println("---------EDGES--------\n");
for(int i=0; i< edgeCount;i++){
Edge currentEdge = edges[i];
System.out.println("Edge - " +currentEdge.x1 +" -" +
currentEdge.x2 + " -" + currentEdge.y1 + " -" + currentEdge.y2 + "\n" );
}
System.out.println("=======================");
}
}
|
3e12a5945c61e8a59d2e7a090f836f3641c19858 | 11,780 | java | Java | src/intTest/java/com/vmware/vim25/ws/WSClientIntTest.java | peachlin/yavijava | 27fd2c5826115782d5eeb934f86e3e39240179cd | [
"BSD-3-Clause"
] | 130 | 2015-05-19T00:10:23.000Z | 2022-03-14T13:35:25.000Z | src/intTest/java/com/vmware/vim25/ws/WSClientIntTest.java | peachlin/yavijava | 27fd2c5826115782d5eeb934f86e3e39240179cd | [
"BSD-3-Clause"
] | 168 | 2015-05-05T04:33:47.000Z | 2022-03-10T05:52:08.000Z | src/intTest/java/com/vmware/vim25/ws/WSClientIntTest.java | peachlin/yavijava | 27fd2c5826115782d5eeb934f86e3e39240179cd | [
"BSD-3-Clause"
] | 118 | 2015-05-03T22:48:41.000Z | 2022-01-07T10:51:35.000Z | 35.481928 | 159 | 0.650424 | 7,868 | package com.vmware.vim25.ws;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import javax.net.ssl.*;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.utility.LoadVcenterProps;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ObjectContent;
import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.util.PropertyCollectorUtil;
public class WSClientIntTest {
private static final Logger log = Logger.getLogger(WSClientIntTest.class);
/**
* Counter for created factory in {@link CustomWSClient}.
*/
private int createdSSLFactory = 0;
/**
* Counter for computed thumbprint in {@link CustomWSClient}.
*/
private int computedThumbprint = 0;
SoapClient wsClient = null;
@Before
public void setUp() throws Exception {
if (null == LoadVcenterProps.url || null == LoadVcenterProps.userName
|| null == LoadVcenterProps.password
|| null == LoadVcenterProps.secondUrl
|| null == LoadVcenterProps.badUrl
|| null == LoadVcenterProps.sslThumbprint
|| "".equals(LoadVcenterProps.url.trim())
|| "".equals(LoadVcenterProps.secondUrl.trim())
|| "".equals(LoadVcenterProps.badUrl.trim())
|| "".equals(LoadVcenterProps.userName.trim())
|| "".equals(LoadVcenterProps.password.trim())
|| "".equals(LoadVcenterProps.sslThumbprint.trim())) {
throw new Exception("Vcenter credentials not loaded");
}
createdSSLFactory = 0;
computedThumbprint = 0;
ServiceInstance si = null;
try {
si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if(si != null) {
wsClient = new WSClient(LoadVcenterProps.url, true);
wsClient.setVimNameSpace(ServiceInstance.VIM25_NAMESPACE);
wsClient.setSoapActionOnApiVersion("5.5");
wsClient.setCookie(si.getSessionManager().getServerConnection()
.getVimService().getWsc().getCookie());
}
}
/**
* This method will test that you can ignore ssl to a vcenter but it doesnt trust
* every cert on the net and will fail trying to connect to my jenkins server
*/
@Test(expected = SSLHandshakeException.class)
public void testIgnoreSslDoesNotTrustAllCertsOnline() throws Exception {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url), LoadVcenterProps.userName, LoadVcenterProps.password, true);
// if we get here we were successful ignoring the self signed cert from vcenter
assert si.getServerClock() instanceof Calendar;
URL badUrl = new URL(LoadVcenterProps.badUrl);
HttpsURLConnection myURLConnection = (HttpsURLConnection) badUrl.openConnection();
// this should throw a handshake exception
myURLConnection.connect();
}
/**
* This method will test that you can ignore ssl to a vcenter but it doesnt trust
* every cert on the net and will fail trying to connect to my jenkins server
*/
@Test
public void testIgnoreSslAllowsMultiplevCentersToBeIgnored() throws Exception {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url), LoadVcenterProps.userName, LoadVcenterProps.password, true);
// if we get here we were successful ignoring the self signed cert from vcenter
assert si.getServerClock() instanceof Calendar;
ServiceInstance serviceInstance = new ServiceInstance(new URL(LoadVcenterProps.secondUrl), LoadVcenterProps.userName, LoadVcenterProps.password, true);
assert serviceInstance.currentTime() instanceof Calendar;
}
/**
* This method should fail with ssl handshake exception
* the vcenter used in your properties file should be running on ssl
* and you should not have its cert imported in your keystore. For these
* tests I rely on a vCenter Server Appliance running simulator.
*/
@Test
public void testDoNotIgnoreSslFailsOnSelfSignedCertNotInKeyStore() throws Exception {
Throwable t = null;
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url), LoadVcenterProps.userName, LoadVcenterProps.password, false);
}
catch (RemoteException re) {
t = re;
}
assert t.getCause() instanceof SSLHandshakeException;
}
/**
* This test method will bring all the host systems under particular
* vCenter.
*/
@Test
public void testGetHosts() {
ObjectContent[] hostSystems = null;
try {
hostSystems = (ObjectContent[]) wsClient.invoke(
"RetrieveProperties", buildGetHostsArgs(),
"ObjectContent[]");
if (hostSystems == null) {
hostSystems = (ObjectContent[]) wsClient.invoke(
"RetrieveProperties", buildGetHostsArgs(),
"ObjectContent[]");
}
} catch (RemoteException e) {
e.printStackTrace();
}
Assert.assertNotNull(hostSystems);
Assert.assertNotEquals(0, hostSystems.length);
}
/**
* This test method will test marshalling feature of the Soap Client.
*/
@Test
public void testReqMarshall() {
String soapPayload = wsClient.marshall("RetrieveProperties",
buildGetHostsArgs());
Assert.assertNotNull(soapPayload);
}
/**
* This test will confirm that the internal SSL socket factory is initiate only once in the WSClient (Issue #38).
*/
@Test
public void testSSLSocketFactoryInitialization() throws Exception {
CustomWSClient client = new CustomWSClient(LoadVcenterProps.url, true);
Assert.assertEquals(1, createdSSLFactory);
try {
client.invoke("RetrieveProperties", buildGetHostsArgs(), "ObjectContent[]");
} catch (RemoteException e) {
}
Assert.assertEquals(1, createdSSLFactory);
try {
client.invoke("RetrieveProperties", buildGetHostsArgs(), "ObjectContent[]");
} catch (RemoteException e) {
}
Assert.assertEquals(1, createdSSLFactory);
}
/**
* Tests the SSL factory is only created once when a trust manager is provided.
*/
@Test
public void testSSLSocketFactoryInitWithTrustManager() throws Exception {
CustomWSClient client = new CustomWSClient(LoadVcenterProps.url, false, new TrustAllManager());
Assert.assertEquals(1, createdSSLFactory);
try {
client.invoke("RetrieveProperties", buildGetHostsArgs(), "ObjectContent[]");
} catch (RemoteException e) {
}
Assert.assertEquals(1, createdSSLFactory);
try {
client.invoke("RetrieveProperties", buildGetHostsArgs(), "ObjectContent[]");
} catch (RemoteException e) {
}
Assert.assertEquals(1, createdSSLFactory);
}
/**
* This method will build the request payload.
*
* @return Argument[]
*/
private Argument[] buildGetHostsArgs() {
Argument[] paras = new Argument[2];
SelectionSpec[] selectionSpecs = null;
ManagedObjectReference mor = new ManagedObjectReference();
mor.setType("PropertyCollector");
mor.setVal("propertyCollector");
selectionSpecs = PropertyCollectorUtil.buildFullTraversalV4();
// Need to set the vcenter specific details here.
ManagedObjectReference vcenterMor = new ManagedObjectReference();
vcenterMor.setType("Folder");
vcenterMor.setVal("group-d1");
ObjectSpec os = new ObjectSpec();
os.setObj(vcenterMor);
os.setSkip(Boolean.FALSE);
os.setSelectSet(selectionSpecs);
String[][] typeinfo = new String[][] { new String[] { "HostSystem",
"name", }, };
PropertySpec[] propspecary = PropertyCollectorUtil
.buildPropertySpecArray(typeinfo);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.setObjectSet(new ObjectSpec[] { os });
spec.setPropSet(propspecary);
paras[0] = new Argument("_this", "ManagedObjectReference", mor);
paras[1] = new Argument("specSet", "PropertyFilterSpec[]",
new PropertyFilterSpec[] { spec });
return paras;
}
/**
* This test verifies that the computed thumbprint is correct and that it is computed only once.
* @author Hubert Verstraete
*/
@Test
public void testServerThumbprintInit() throws Exception {
CustomWSClient client = new CustomWSClient(LoadVcenterProps.url, true);
try {
client.invoke("RetrieveProperties", buildGetHostsArgs(), "ObjectContent[]");
} catch (RemoteException e) {
}
Assert.assertEquals(1, computedThumbprint);
try {
client.invoke("RetrieveProperties", buildGetHostsArgs(), "ObjectContent[]");
} catch (RemoteException e) {
}
Assert.assertEquals(1, computedThumbprint);
Assert.assertEquals("The computed SSL Server Thumbprint is invalid.", client.getServerThumbprint(), LoadVcenterProps.sslThumbprint);
}
/**
* This extension of the WSClient will create count the number of time the {@link SSLSocketFactory} was created.
*
* @author Francis Beaulé
*
* This extension also counts the number of time the Server {@link thumbprint} is computed.
* @author Hubert Verstraete
*
*/
private class CustomWSClient extends WSClient {
public CustomWSClient(String serverUrl, boolean ignoreCert) throws MalformedURLException, RemoteException {
super(serverUrl, ignoreCert);
}
public CustomWSClient(String serverUrl, boolean ignoreCert, TrustManager trustManager) throws MalformedURLException, RemoteException {
super(serverUrl, ignoreCert, trustManager);
}
/**
* {@inheritDoc}
*/
@Override
protected SSLSocketFactory getTrustAllSocketFactory(boolean ignoreCert) throws RemoteException {
++createdSSLFactory;
return super.getTrustAllSocketFactory(ignoreCert);
}
@Override
protected SSLSocketFactory getCustomTrustManagerSocketFactory(TrustManager trustManager) throws RemoteException {
++createdSSLFactory;
return super.getCustomTrustManagerSocketFactory(trustManager);
}
@Override
public void setServerThumbprint(String thumbprint) {
++computedThumbprint;
super.setServerThumbprint(thumbprint);
}
}
private static class TrustAllManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
}
}
|
3e12a5ad8820f579f287132a2728be90748cb069 | 2,294 | java | Java | app/src/main/java/com/example/charmer/moving/utils/MycollectAdapter.java | hellcharmer/MOVING | c11b1ebd495bd3966c54023ad5bffab5ef1e1df2 | [
"Apache-2.0"
] | 2 | 2021-01-28T04:07:45.000Z | 2021-02-22T01:53:57.000Z | app/src/main/java/com/example/charmer/moving/utils/MycollectAdapter.java | hellcharmer/REMOVING | c11b1ebd495bd3966c54023ad5bffab5ef1e1df2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/charmer/moving/utils/MycollectAdapter.java | hellcharmer/REMOVING | c11b1ebd495bd3966c54023ad5bffab5ef1e1df2 | [
"Apache-2.0"
] | null | null | null | 26.367816 | 154 | 0.689625 | 7,869 | package com.example.charmer.moving.utils;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.charmer.moving.R;
import com.example.charmer.moving.contantData.HttpUtils;
import com.example.charmer.moving.pojo.ZixunInfo;
import java.util.List;
/**
* Created by loongggdroid on 2016/5/19.
*/
public class MycollectAdapter extends RecyclerView.Adapter<MycollectAdapter.ViewHolder> {
// 数据集
private List<ZixunInfo> exerciseList ;
public MycollectAdapter(List<ZixunInfo> exerciseList) {
super();
this.exerciseList = exerciseList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// 创建一个View,简单起见直接使用系统提供的布局,就是一个TextView
View view = View.inflate(viewGroup.getContext(), R.layout.search_result_list, null);
// 创建一个ViewHolder
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
// 绑定数据到ViewHolder上
ZixunInfo zixun = exerciseList.get(i);
viewHolder.tv_xiangxi.setText(zixun.getZixun_likes()+"人收藏 ·"+zixun.getPublisher()+" · "+ DateUtils.getGapTimeFromNow(zixun.getZixun_issuedate()));
viewHolder.tv_name.setText(zixun.getZixun_name());
xUtilsImageUtils.display(viewHolder.iv_picture, HttpUtils.hoster + "zixunpictures/"+zixun.getZixun_photo().split(",")[0]);
}
@Override
public int getItemCount() {
return exerciseList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView iv_picture;
TextView tv_xiangxi;
TextView tv_name;
public ViewHolder(View itemView) {
super(itemView);
iv_picture = ((ImageView) itemView.findViewById(R.id.iv_searchresult_picture));
tv_xiangxi = ((TextView) itemView.findViewById(R.id.tv_searchresult_tg));
tv_name = ((TextView) itemView.findViewById(R.id.tv_searchresult_title));
//字体加粗
TextPaint tp = tv_name.getPaint();
tp.setFakeBoldText(true);
}
}
}
|
3e12a7639c137140f4dd804de4422fcc14f1efe4 | 4,272 | java | Java | rocket-app/src/main/java/cn/wilton/rocket/service/impl/RoleServiceImpl.java | wiltonicp/Rocket-admin | 8464a3b9012a54a1fce438ee24f440cf53de484d | [
"Apache-2.0"
] | 2 | 2021-01-21T07:59:36.000Z | 2021-01-21T07:59:52.000Z | rocket-app/src/main/java/cn/wilton/rocket/service/impl/RoleServiceImpl.java | wiltonicp/Rocket-admin | 8464a3b9012a54a1fce438ee24f440cf53de484d | [
"Apache-2.0"
] | null | null | null | rocket-app/src/main/java/cn/wilton/rocket/service/impl/RoleServiceImpl.java | wiltonicp/Rocket-admin | 8464a3b9012a54a1fce438ee24f440cf53de484d | [
"Apache-2.0"
] | 1 | 2021-08-03T07:23:35.000Z | 2021-08-03T07:23:35.000Z | 36.538462 | 109 | 0.723743 | 7,870 | package cn.wilton.rocket.service.impl;
import cn.wilton.rocket.common.constant.RocketConstant;
import cn.wilton.rocket.common.entity.QueryRequest;
import cn.wilton.rocket.common.entity.system.Role;
import cn.wilton.rocket.common.entity.system.RoleMenu;
import cn.wilton.rocket.common.util.SortUtil;
import cn.wilton.rocket.mapper.RoleMapper;
import cn.wilton.rocket.service.IRoleMenuService;
import cn.wilton.rocket.service.IRoleService;
import cn.wilton.rocket.service.IUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.javafx.binding.StringConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* @author Ranger
* @since 2021/3/10
* @email upchh@example.com
*/
@Slf4j
@Service("roleService")
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
private final IRoleMenuService roleMenuService;
private final IUserRoleService userRoleService;
@Override
public IPage<Role> findRoles(Role role, QueryRequest request) {
Page<Role> page = new Page<>(request.getPageNum(), request.getPageSize());
SortUtil.handlePageSort(request, page, "createdTime", RocketConstant.ORDER_DESC, false);
return this.baseMapper.findRolePage(page, role);
}
@Override
public List<Role> findUserRole(String userName) {
return baseMapper.findUserRole(userName);
}
@Override
public List<Role> findAllRoles() {
LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.orderByAsc(Role::getRoleId);
return this.baseMapper.selectList(queryWrapper);
}
@Override
public Role findByName(String roleName) {
return baseMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, roleName));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void createRole(Role role) {
role.setCreatedTime(LocalDateTime.now());
this.save(role);
if (StringUtils.isNotBlank(role.getMenuIds())) {
String[] menuIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(role.getMenuIds(), ",");
setRoleMenus(role, menuIds);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteRoles(String[] roleIds) {
List<String> list = Arrays.asList(roleIds);
baseMapper.deleteBatchIds(list);
this.roleMenuService.deleteRoleMenusByRoleId(roleIds);
this.userRoleService.deleteUserRolesByRoleId(roleIds);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateRole(Role role) {
role.setRoleName(null);
role.setModifyTime(LocalDateTime.now());
baseMapper.updateById(role);
roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, role.getRoleId()));
if (StringUtils.isNotBlank(role.getMenuIds())) {
String[] menuIds = StringUtils.splitByWholeSeparatorPreserveAllTokens(role.getMenuIds(), ",");
setRoleMenus(role, menuIds);
}
}
private void setRoleMenus(Role role, String[] menuIds) {
List<RoleMenu> roleMenus = new ArrayList<>();
Arrays.stream(menuIds).forEach(menuId -> {
RoleMenu roleMenu = new RoleMenu();
if (StringUtils.isNotBlank(menuId)) {
roleMenu.setMenuId(Long.valueOf(menuId));
}
roleMenu.setRoleId(role.getRoleId());
roleMenus.add(roleMenu);
});
this.roleMenuService.saveBatch(roleMenus);
}
}
|
3e12a785a3f1bfa1447dff743fc0d530c6012c55 | 620 | java | Java | java-netty/src/main/java/com/jailmango/netty/lightman/netty/app/packet/request/ListGroupMembersRequestPacket.java | JailMango/learning-java | bdf61ed211376f671a7993cccb510ea05d3867ac | [
"Apache-2.0"
] | null | null | null | java-netty/src/main/java/com/jailmango/netty/lightman/netty/app/packet/request/ListGroupMembersRequestPacket.java | JailMango/learning-java | bdf61ed211376f671a7993cccb510ea05d3867ac | [
"Apache-2.0"
] | 9 | 2018-10-22T10:56:04.000Z | 2019-04-30T01:34:18.000Z | java-netty/src/main/java/com/jailmango/netty/lightman/netty/app/packet/request/ListGroupMembersRequestPacket.java | JailMango/learning-java | bdf61ed211376f671a7993cccb510ea05d3867ac | [
"Apache-2.0"
] | null | null | null | 21.37931 | 69 | 0.730645 | 7,871 | package com.jailmango.netty.lightman.netty.app.packet.request;
import lombok.Data;
import com.jailmango.netty.lightman.netty.app.packet.Packet;
import com.jailmango.netty.lightman.netty.app.packet.command.Command;
/**
* ListGroupMembersRequestPacket
*
* @author jailmango
* @CreateDate 2019/11/25
* @see com.jailmango.netty.lightman.netty.app.packet.request
* @since R9.0
*/
@Data
public class ListGroupMembersRequestPacket extends Packet {
/**
* groupName
*/
private String groupName;
@Override
public Byte getCommand() {
return Command.LIST_GROUP_MEMBERS_REQUEST;
}
}
|
3e12a7bd5c6c4672fc9e05265e3418827b31e0fd | 1,962 | java | Java | tiles-autotag-jsp/src/main/java/org/apache/tiles/autotag/jsp/TLDGenerator.java | nlebas/tiles-autotag | db2bc2e45e7ecb33f7cdbe100551cd0ba2bbc827 | [
"BSD-3-Clause"
] | 1 | 2021-11-10T19:00:49.000Z | 2021-11-10T19:00:49.000Z | tiles-autotag-jsp/src/main/java/org/apache/tiles/autotag/jsp/TLDGenerator.java | nlebas/tiles-autotag | db2bc2e45e7ecb33f7cdbe100551cd0ba2bbc827 | [
"BSD-3-Clause"
] | null | null | null | tiles-autotag-jsp/src/main/java/org/apache/tiles/autotag/jsp/TLDGenerator.java | nlebas/tiles-autotag | db2bc2e45e7ecb33f7cdbe100551cd0ba2bbc827 | [
"BSD-3-Clause"
] | 8 | 2015-12-07T22:40:11.000Z | 2021-11-10T19:00:40.000Z | 30.65625 | 72 | 0.712029 | 7,872 | /*
* $Id$
*
* 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.tiles.autotag.jsp;
import java.util.Map;
import org.apache.tiles.autotag.generate.AbstractTemplateSuiteGenerator;
import org.apache.tiles.autotag.model.TemplateSuite;
import org.apache.velocity.app.VelocityEngine;
/**
* Generates the TLD file, using a template suite.
*
* @version $Rev$ $Date$
*/
public class TLDGenerator extends AbstractTemplateSuiteGenerator {
/**
* Constructor.
*
* @param velocityEngine The Velocity engine.
*/
public TLDGenerator(VelocityEngine velocityEngine) {
super(velocityEngine);
}
@Override
protected String getTemplatePath(String packageName,
TemplateSuite suite, Map<String, String> parameters) {
return "/org/apache/tiles/autotag/jsp/tld.vm";
}
@Override
protected String getFilename(String packageName,
TemplateSuite suite, Map<String, String> parameters) {
return suite.getName() + "-jsp.tld";
}
@Override
protected String getDirectoryName(String packageName,
TemplateSuite suite, Map<String, String> parameters) {
return "META-INF/tld/";
}
}
|
3e12a7ea7c2e1d2774f99c49ba99ab9f724382a9 | 1,463 | java | Java | src/LC25.java | quaeast/Leetcode | 1de87102097a8b28056cf40500e79e2e8742452e | [
"MIT"
] | 3 | 2019-11-02T04:33:22.000Z | 2021-05-10T01:14:08.000Z | src/LC25.java | quaeast/Leetcode | 1de87102097a8b28056cf40500e79e2e8742452e | [
"MIT"
] | null | null | null | src/LC25.java | quaeast/Leetcode | 1de87102097a8b28056cf40500e79e2e8742452e | [
"MIT"
] | null | null | null | 21.202899 | 57 | 0.412167 | 7,873 | import java.nio.IntBuffer;
import java.util.function.Predicate;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution25 {
public ListNode reverseKGroup(ListNode head, int k) {
int length = 0;
for (ListNode i = head; i != null; i = i.next) {
length++;
}
if (k <= 1 || head == null) {
return head;
}
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode pre = preHead;
ListNode cur = pre.next;
ListNode next = cur.next;
ListNode groupPre = pre;//it has no need to init
for (int i = 0;; i++) {
if (i % k == 0) {
groupPre = pre;
if(length-i<k){
break;
}
}
pre.next = next;
cur.next = groupPre.next;
groupPre.next = cur;
if(next==null){
break;
}
pre = pre.next == next ? pre : cur;
cur = next;
next = next.next;
}
return preHead.next;
}
}
/*
[]
1
[1,2,3,4,5]
0
[1,2,3,4,5]
1
[1,2,3,4,5]
2
[1, 2, 3]
3
[1, 2, 3, 4]
3
[1,2,3,4,5]
3
[1, 2, 3,4 ,5, 6]
3
*/
public class LC25 {
}
|
3e12a7f2b2fc1dba1942c34bbe6e462d4eb65664 | 8,716 | java | Java | integration-tests/cucumber-tests-platform/src/test/java/org/opensmartgridplatform/cucumber/platform/core/builders/FirmwareFileBuilder.java | ahiguerat/open-smart-grid-platform | 10e70f5752d9ec674b6ab26dd45b15a42c572f5e | [
"Apache-2.0"
] | null | null | null | integration-tests/cucumber-tests-platform/src/test/java/org/opensmartgridplatform/cucumber/platform/core/builders/FirmwareFileBuilder.java | ahiguerat/open-smart-grid-platform | 10e70f5752d9ec674b6ab26dd45b15a42c572f5e | [
"Apache-2.0"
] | null | null | null | integration-tests/cucumber-tests-platform/src/test/java/org/opensmartgridplatform/cucumber/platform/core/builders/FirmwareFileBuilder.java | ahiguerat/open-smart-grid-platform | 10e70f5752d9ec674b6ab26dd45b15a42c572f5e | [
"Apache-2.0"
] | null | null | null | 47.89011 | 203 | 0.76721 | 7,874 | /**
* Copyright 2016 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.cucumber.platform.core.builders;
import java.util.Map;
import org.opensmartgridplatform.cucumber.platform.PlatformDefaults;
import org.opensmartgridplatform.cucumber.platform.PlatformKeys;
import org.opensmartgridplatform.domain.core.entities.DeviceModel;
import org.opensmartgridplatform.domain.core.entities.FirmwareFile;
import org.opensmartgridplatform.domain.core.repositories.FirmwareModuleRepository;
import org.opensmartgridplatform.domain.core.valueobjects.FirmwareModuleData;
public class FirmwareFileBuilder implements CucumberBuilder<FirmwareFile> {
private DeviceModel deviceModel;
private String filename;
private String description = PlatformDefaults.FIRMWARE_DESCRIPTION;
private boolean pushToNewDevices = PlatformDefaults.FIRMWARE_PUSH_TO_NEW_DEVICE;
private String moduleVersionComm = PlatformDefaults.FIRMWARE_MODULE_VERSION_COMM;
private String moduleVersionFunc = PlatformDefaults.FIRMWARE_MODULE_VERSION_FUNC;
private String moduleVersionMa = PlatformDefaults.FIRMWARE_MODULE_VERSION_MA;
private String moduleVersionMbus = PlatformDefaults.FIRMWARE_MODULE_VERSION_MBUS;
private String moduleVersionSec = PlatformDefaults.FIRMWARE_MODULE_VERSION_SEC;
private String moduleVersionMBusDriverActive = PlatformDefaults.FIRMWARE_MODULE_VERSION_M_BUS_DRIVER_ACTIVE;
// RTU modules
private String moduleVersionXmlInt = PlatformDefaults.FIRMWARE_MODULE_VERSION_XMLINT;
private String moduleVersionXml2ccp = PlatformDefaults.FIRMWARE_MODULE_VERSION_XML2CCP;
private String moduleVersionLibmmslite = PlatformDefaults.FIRMWARE_MODULE_VERSION_LIBMMSLITE;
private String moduleVersionEkorccp = PlatformDefaults.FIRMWARE_MODULE_VERSION_EKORCCP;
private String moduleVersionDimxccp = PlatformDefaults.FIRMWARE_MODULE_VERSION_DIMXCCP;
private String moduleVersionRtuschemas = PlatformDefaults.FIRMWARE_MODULE_VERSION_RTUSCHEMAS;
private String moduleVersionLocaltime = PlatformDefaults.FIRMWARE_MODULE_VERSION_LOCALTIME;
private String moduleVersionLibxsdset = PlatformDefaults.FIRMWARE_MODULE_VERSION_LIBXSDSET;
private String moduleVersionFreedisk = PlatformDefaults.FIRMWARE_MODULE_VERSION_FREEDISK;
private String moduleVersionEkorrtuws = PlatformDefaults.FIRMWARE_MODULE_VERSION_EKORRTUWS;
private String moduleVersionEkorWeb = PlatformDefaults.FIRMWARE_MODULE_VERSION_EKORWEB;
private String moduleVersionCcpC = PlatformDefaults.FIRMWARE_MODULE_VERSION_CCPC;
private String moduleVersionDarmccp = PlatformDefaults.FIRMWARE_MODULE_VERSION_DARMCCP;
private String moduleVersionExpect = PlatformDefaults.FIRMWARE_MODULE_VERSION_EXPECT;
private String moduleVersionOpenssh = PlatformDefaults.FIRMWARE_MODULE_VERSION_OPENSSH;
private String moduleVersionOpenssl = PlatformDefaults.FIRMWARE_MODULE_VERSION_OPENSSL;
private String moduleVersionProftpd = PlatformDefaults.FIRMWARE_MODULE_VERSION_PROFTPD;
private String moduleVersionTcpdump = PlatformDefaults.FIRMWARE_MODULE_VERSION_TCPDUMP;
private byte file[];
private String hash;
public FirmwareFileBuilder withDeviceModel(final DeviceModel deviceModel) {
this.deviceModel = deviceModel;
return this;
}
public FirmwareFileBuilder withFilename(final String filename) {
this.filename = filename;
return this;
}
public FirmwareFileBuilder withDescription(final String description) {
this.description = description;
return this;
}
public FirmwareFileBuilder withPushToNewDevices(final boolean pushToNewDevices) {
this.pushToNewDevices = pushToNewDevices;
return this;
}
public FirmwareFileBuilder withModuleVersionComm(final String moduleVersionComm) {
this.moduleVersionComm = moduleVersionComm;
return this;
}
public FirmwareFileBuilder withModuleVersionFunc(final String moduleVersionFunc) {
this.moduleVersionFunc = moduleVersionFunc;
return this;
}
public FirmwareFileBuilder withModuleVersionMa(final String moduleVersionMa) {
this.moduleVersionMa = moduleVersionMa;
return this;
}
public FirmwareFileBuilder withModuleVersionMbus(final String moduleVersionMbus) {
this.moduleVersionMbus = moduleVersionMbus;
return this;
}
public FirmwareFileBuilder withModuleVersionSec(final String moduleVersionSec) {
this.moduleVersionSec = moduleVersionSec;
return this;
}
public FirmwareFileBuilder withFile(final byte[] file) {
this.file = file;
return this;
}
public FirmwareFileBuilder withHash(final String hash) {
this.hash = hash;
return this;
}
@Override
public FirmwareFile build() {
throw new UnsupportedOperationException(
"Firmware module version configuration model in test builders needs to be made more generic. For now call: build(firmwareModuleRepository, isForSmartMeters)");
}
public FirmwareFile build(final FirmwareModuleRepository firmwareModuleRepository, final boolean isForSmartMeters) {
final FirmwareFile.Builder firmwareFileBuilder = new FirmwareFile.Builder();
firmwareFileBuilder.withFilename(this.filename)
.withDescription(this.description)
.withPushToNewDevices(this.pushToNewDevices)
.withFile(this.file)
.withHash(this.hash);
final FirmwareFile firmwareFile = firmwareFileBuilder.build();
if (this.deviceModel != null) {
firmwareFile.addDeviceModel(this.deviceModel);
}
firmwareFile.updateFirmwareModuleData(new FirmwareModuleData(this.moduleVersionComm, this.moduleVersionFunc,
this.moduleVersionMa, this.moduleVersionMbus, this.moduleVersionSec, this.moduleVersionMBusDriverActive, this.moduleVersionXmlInt, this.moduleVersionXml2ccp, this.moduleVersionLibmmslite,
this.moduleVersionEkorccp, this.moduleVersionDimxccp, this.moduleVersionRtuschemas, this.moduleVersionLocaltime,
this.moduleVersionLibxsdset, this.moduleVersionFreedisk, this.moduleVersionEkorrtuws, this.moduleVersionEkorWeb, this.moduleVersionCcpC,
this.moduleVersionDarmccp, this.moduleVersionExpect, this.moduleVersionOpenssh, this.moduleVersionOpenssl,
this.moduleVersionProftpd, this.moduleVersionTcpdump)
.getVersionsByModule(firmwareModuleRepository, isForSmartMeters));
return firmwareFile;
}
@Override
public FirmwareFileBuilder withSettings(final Map<String, String> inputSettings) {
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_FILE_FILENAME)) {
this.withFilename(inputSettings.get(PlatformKeys.FIRMWARE_FILE_FILENAME));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_DESCRIPTION)) {
this.withDescription(inputSettings.get(PlatformKeys.FIRMWARE_DESCRIPTION));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_PUSH_TO_NEW_DEVICES)) {
this.withPushToNewDevices(
Boolean.parseBoolean(inputSettings.get(PlatformKeys.FIRMWARE_PUSH_TO_NEW_DEVICES)));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_MODULE_VERSION_COMM)) {
this.withModuleVersionComm(inputSettings.get(PlatformKeys.FIRMWARE_MODULE_VERSION_COMM));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_MODULE_VERSION_FUNC)) {
this.withModuleVersionFunc(inputSettings.get(PlatformKeys.FIRMWARE_MODULE_VERSION_FUNC));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_MODULE_VERSION_MA)) {
this.withModuleVersionMa(inputSettings.get(PlatformKeys.FIRMWARE_MODULE_VERSION_MA));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_MODULE_VERSION_MBUS)) {
this.withModuleVersionMbus(inputSettings.get(PlatformKeys.FIRMWARE_MODULE_VERSION_MBUS));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_MODULE_VERSION_SEC)) {
this.withModuleVersionSec(inputSettings.get(PlatformKeys.FIRMWARE_MODULE_VERSION_SEC));
}
if (inputSettings.containsKey(PlatformKeys.FIRMWARE_HASH)) {
this.withHash(inputSettings.get(PlatformKeys.FIRMWARE_HASH));
}
return this;
}
}
|
3e12a83fc3cc834284ca554a1bde32c687c4e88b | 2,543 | java | Java | src/main/java/ftb/lib/api/client/model/Group.java | cosmicdan/FTBUtilitiesAW2 | 15580ba0446124da585ac5b52d681cf84e41fc27 | [
"MIT"
] | null | null | null | src/main/java/ftb/lib/api/client/model/Group.java | cosmicdan/FTBUtilitiesAW2 | 15580ba0446124da585ac5b52d681cf84e41fc27 | [
"MIT"
] | null | null | null | src/main/java/ftb/lib/api/client/model/Group.java | cosmicdan/FTBUtilitiesAW2 | 15580ba0446124da585ac5b52d681cf84e41fc27 | [
"MIT"
] | null | null | null | 23.766355 | 72 | 0.627998 | 7,875 | package ftb.lib.api.client.model;
import cpw.mods.fml.relauncher.*;
import ftb.lib.api.client.GlStateManager;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;
import java.util.*;
/**
* Made by LatvianModder
*/
@SideOnly(Side.CLIENT)
public class Group
{
public OBJModel parent;
public String groupName;
public final List<Face> faces;
private int listID = -1;
public Vector3f pos, rotation, offset;
public Group(OBJModel m, String s)
{
parent = m;
groupName = s;
faces = new ArrayList<>();
pos = new Vector3f();
rotation = new Vector3f();
offset = new Vector3f();
}
public void render()
{
if(listID == -1)
{
if(parent.texVertices == null) GlStateManager.disableTexture2D();
else GlStateManager.enableTexture2D();
GlStateManager.color(1F, 1F, 1F, 1F);
listID = GL11.glGenLists(1);
GL11.glNewList(listID, GL11.GL_COMPILE);
float posX0 = 0F, posY0 = 0F, posZ0 = 0F;
float vSize = 0F;
for(int i = 0; i < faces.size(); i++)
{
Face f = faces.get(i);
GL11.glBegin(f.drawMode);
for(int j = 0; j < f.verticies.length; j++)
{
Vector3f v = parent.vertices.get(f.verticies[j]);
if(f.texVerticies != null)
{
Vector3f vt = parent.texVertices.get(f.texVerticies[j]);
if(vt.z == -1F) GL11.glTexCoord2f(vt.x, vt.y);
else GL11.glTexCoord3f(vt.x, vt.y, vt.z);
}
Vector3f vn = parent.vertexNormals.get(f.normals[j]);
if(vn != null) GL11.glNormal3f(vn.x, vn.y, vn.z);
else GL11.glNormal3f(0F, 1F, 0F);
GL11.glVertex3f(v.x, v.y, v.z);
posX0 += v.x;
posY0 += v.y;
posZ0 += v.z;
vSize++;
}
GL11.glEnd();
}
GL11.glEndList();
pos.x = posX0 / vSize;
pos.y = posY0 / vSize;
pos.z = posZ0 / vSize;
}
boolean hasOffset = offset.lengthSquared() != 0F;
boolean hasRotation = rotation.lengthSquared() != 0F;
if(hasOffset || hasRotation)
{
GlStateManager.pushMatrix();
GlStateManager.translate(pos.x, pos.y, pos.z);
if(hasOffset) GlStateManager.translate(offset.x, offset.y, offset.z);
if(hasRotation)
{
GlStateManager.rotate(rotation.y, 0F, 1F, 0F);
GlStateManager.rotate(rotation.x, 1F, 0F, 0F);
GlStateManager.rotate(rotation.z, 0F, 0F, 1F);
}
if(hasOffset) GlStateManager.translate(offset.x, offset.y, offset.z);
GlStateManager.translate(-pos.x, -pos.y, -pos.z);
GL11.glCallList(listID);
GlStateManager.popMatrix();
}
else GL11.glCallList(listID);
}
} |
3e12a863a6a6a38ccf1e51d1c88b17ca01155504 | 1,576 | java | Java | agribusiness-product/src/main/java/com/wtt/agribusiness/product/exception/AgribusinessExceptionControllerAdvice.java | lesileqin/Agribusiness | 1fc746256a7552c9cc687c802552efcd663b7abf | [
"Apache-2.0"
] | 3 | 2021-12-19T14:06:20.000Z | 2022-03-26T13:31:53.000Z | agribusiness-product/src/main/java/com/wtt/agribusiness/product/exception/AgribusinessExceptionControllerAdvice.java | lesileqin/Agribusiness | 1fc746256a7552c9cc687c802552efcd663b7abf | [
"Apache-2.0"
] | null | null | null | agribusiness-product/src/main/java/com/wtt/agribusiness/product/exception/AgribusinessExceptionControllerAdvice.java | lesileqin/Agribusiness | 1fc746256a7552c9cc687c802552efcd663b7abf | [
"Apache-2.0"
] | null | null | null | 33.510638 | 122 | 0.756825 | 7,876 | package com.wtt.agribusiness.product.exception;
import com.wtt.common.exception.BizCodeEnume;
import com.wtt.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
/**
* 集中处理所有异常
* @author Wang TianTian
* @email efpyi@example.com
* @date 2021/2/24 16点17分
* */
@Slf4j
@RestControllerAdvice(basePackages = "com.wtt.agribusiness.product.controller")
public class AgribusinessExceptionControllerAdvice {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleVaildException(MethodArgumentNotValidException e){
log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String,String> errorMap = new HashMap<>();
bindingResult.getFieldErrors().forEach((fieldError)->{
errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
});
//抽取状态码和错误信息到common的exception包下,封装为枚举类,直接取用
return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
}
//如果匹配不到任何异常
@ExceptionHandler(value = Throwable.class)
public R handleException(){
return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
}
}
|
3e12a896cc63e567665ab6979f75362ac23b2a17 | 328 | java | Java | src/main/java/com/triggerme/app/model/AuthToken.java | kishorer06/trigger-me-backend | bf1396970556f76f2f94d1b328d8a17eef8254da | [
"MIT"
] | null | null | null | src/main/java/com/triggerme/app/model/AuthToken.java | kishorer06/trigger-me-backend | bf1396970556f76f2f94d1b328d8a17eef8254da | [
"MIT"
] | null | null | null | src/main/java/com/triggerme/app/model/AuthToken.java | kishorer06/trigger-me-backend | bf1396970556f76f2f94d1b328d8a17eef8254da | [
"MIT"
] | null | null | null | 13.666667 | 40 | 0.591463 | 7,877 | package com.triggerme.app.model;
public class AuthToken {
private String token;
public AuthToken(){
}
public AuthToken(String token){
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
|
3e12aa3cb938984a15673a024740b0166e98b237 | 1,560 | java | Java | optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/devui/OptaPlannerDevUIProperties.java | artysidorenko/optaplanner | 6557c2599260f6673feed4aab9f2958befe13daf | [
"Apache-2.0"
] | 2,400 | 2017-03-14T14:16:18.000Z | 2022-03-31T09:18:47.000Z | optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/devui/OptaPlannerDevUIProperties.java | artysidorenko/optaplanner | 6557c2599260f6673feed4aab9f2958befe13daf | [
"Apache-2.0"
] | 1,312 | 2017-03-13T14:57:10.000Z | 2022-03-30T14:50:37.000Z | optaplanner-quarkus-integration/optaplanner-quarkus/runtime/src/main/java/org/optaplanner/quarkus/devui/OptaPlannerDevUIProperties.java | artysidorenko/optaplanner | 6557c2599260f6673feed4aab9f2958befe13daf | [
"Apache-2.0"
] | 635 | 2017-03-16T13:17:14.000Z | 2022-03-25T01:12:38.000Z | 34.666667 | 125 | 0.753846 | 7,878 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.quarkus.devui;
import java.util.List;
public class OptaPlannerDevUIProperties {
private final OptaPlannerModelProperties optaPlannerModelProperties;
private final String effectiveSolverConfigXML;
private final List<String> constraintList;
public OptaPlannerDevUIProperties(OptaPlannerModelProperties optaPlannerModelProperties, String effectiveSolverConfigXML,
List<String> constraintList) {
this.optaPlannerModelProperties = optaPlannerModelProperties;
this.effectiveSolverConfigXML = effectiveSolverConfigXML;
this.constraintList = constraintList;
}
public OptaPlannerModelProperties getOptaPlannerModelProperties() {
return optaPlannerModelProperties;
}
public String getEffectiveSolverConfig() {
return effectiveSolverConfigXML;
}
public List<String> getConstraintList() {
return constraintList;
}
}
|
3e12aa97a9fad9d046c072b899a4bb2dd2aa9b5d | 838 | java | Java | Steamworks/src/org/usfirst/frc/team3164/robot/electrical/AnalogDistance.java | stealthtigers3164/2017_FRC3164_Steamworks | 501946e5e845eddab5b5891858239a9d346a113a | [
"BSD-3-Clause"
] | null | null | null | Steamworks/src/org/usfirst/frc/team3164/robot/electrical/AnalogDistance.java | stealthtigers3164/2017_FRC3164_Steamworks | 501946e5e845eddab5b5891858239a9d346a113a | [
"BSD-3-Clause"
] | null | null | null | Steamworks/src/org/usfirst/frc/team3164/robot/electrical/AnalogDistance.java | stealthtigers3164/2017_FRC3164_Steamworks | 501946e5e845eddab5b5891858239a9d346a113a | [
"BSD-3-Clause"
] | null | null | null | 19.488372 | 80 | 0.699284 | 7,879 | package org.usfirst.frc.team3164.robot.electrical;
import edu.wpi.first.wpilibj.AnalogInput;
public class AnalogDistance {
private AnalogInput distSensor;
private double distance = 0;
/**
* Analog distance sensor class, setup for MaxBotix HRLV 1013 Ultrasonic Sensor
* @param port analog port
*/
AnalogDistance(int port) {
this.distSensor = new AnalogInput(port);
}
/**
* A scaled voltage value (determined by sensor not by us)
* @return
*/
public double getVoltage() {
return this.distSensor.getVoltage();
}
/**
* A scaled voltage value, determined by code
* Oversamples, more stable
* @return
*/
public double getVoltageAvg() {
return this.distSensor.getAverageVoltage();
}
/**
* Returns distance in meters
* @return
*/
public double getDistance() {
return this.distance;
}
}
|
3e12aadeaa6ae0a1854a9e4cf588b2ebc8f64b21 | 186 | java | Java | src/main/java/com/app/constants/Config.java | Digital-Geenie/Anonymous_Chatting | f7152736bfe163f7b80363a20b76b1c5d596d0b3 | [
"MIT"
] | 1 | 2019-01-27T20:17:04.000Z | 2019-01-27T20:17:04.000Z | src/main/java/com/app/constants/Config.java | Digital-Geenie/Anonymous_Chatting | f7152736bfe163f7b80363a20b76b1c5d596d0b3 | [
"MIT"
] | null | null | null | src/main/java/com/app/constants/Config.java | Digital-Geenie/Anonymous_Chatting | f7152736bfe163f7b80363a20b76b1c5d596d0b3 | [
"MIT"
] | null | null | null | 18.6 | 64 | 0.704301 | 7,880 | package com.app.constants;
/**
* Created by Joe on 5/28/2014.
*/
public class Config {
// Google Project Number
public static final String GOOGLE_PROJECT_ID = "457425993000";
}
|
3e12ab00eadec0150b7e9b4f87c5d337e5977fa2 | 754 | java | Java | src/org/appwork/swing/components/tooltips/config/ExtTooltipSettings.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | 2 | 2015-08-30T13:01:19.000Z | 2020-06-07T19:54:25.000Z | src/org/appwork/swing/components/tooltips/config/ExtTooltipSettings.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | null | null | null | src/org/appwork/swing/components/tooltips/config/ExtTooltipSettings.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | null | null | null | 25.166667 | 87 | 0.700662 | 7,881 | /**
* Copyright (c) 2009 - 2011 AppWork UG(haftungsbeschränkt) <anpch@example.com>
*
* This file is part of org.appwork.swing.components.tooltips.config
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.appwork.swing.components.tooltips.config;
import org.appwork.storage.config.ConfigInterface;
import org.appwork.storage.config.annotations.DefaultIntValue;
/**
* @author thomas
*
*/
public interface ExtTooltipSettings extends ConfigInterface {
/**
* @return
*/
@DefaultIntValue(0xffffff)
int getForegroundColor();
void setForegroundColor(int rgb);
}
|
3e12af62b91d19ed0b858e4154399232a95a5b4a | 1,811 | java | Java | modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverFilesRecoveryException.java | focampo/elasticsearch | bd87f8de3ac84eb408d5ada0976664545c9228a0 | [
"Apache-2.0"
] | 1 | 2018-11-08T05:31:08.000Z | 2018-11-08T05:31:08.000Z | modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverFilesRecoveryException.java | bcui/elasticsearch | 7dfe48c33b9d1bb926a7f6fff0aab9de3076cf03 | [
"Apache-2.0"
] | null | null | null | modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverFilesRecoveryException.java | bcui/elasticsearch | 7dfe48c33b9d1bb926a7f6fff0aab9de3076cf03 | [
"Apache-2.0"
] | null | null | null | 36.22 | 126 | 0.755384 | 7,882 | /*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.indices.recovery;
import org.elasticsearch.ElasticSearchWrapperException;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.shard.IndexShardException;
import org.elasticsearch.index.shard.ShardId;
/**
* @author kimchy (shay.banon)
*/
public class RecoverFilesRecoveryException extends IndexShardException implements ElasticSearchWrapperException {
private final int numberOfFiles;
private final ByteSizeValue totalFilesSize;
public RecoverFilesRecoveryException(ShardId shardId, int numberOfFiles, ByteSizeValue totalFilesSize, Throwable cause) {
super(shardId, "Failed to transfer [" + numberOfFiles + "] files with total size of [" + totalFilesSize + "]", cause);
this.numberOfFiles = numberOfFiles;
this.totalFilesSize = totalFilesSize;
}
public int numberOfFiles() {
return numberOfFiles;
}
public ByteSizeValue totalFilesSize() {
return totalFilesSize;
}
}
|
3e12b02327beec16af514292bd05da6ca68ad041 | 2,002 | java | Java | android/BeyondAR_Framework/src/com/beyondar/android/opengl/renderable/IRenderable.java | joanpuigsanz/beyondar | b58d1e65084a6345363ff5a5a41bca8634753b45 | [
"Apache-2.0"
] | 1 | 2015-05-29T10:31:33.000Z | 2015-05-29T10:31:33.000Z | android/BeyondAR_Framework/src/com/beyondar/android/opengl/renderable/IRenderable.java | joanpuigsanz/beyondar | b58d1e65084a6345363ff5a5a41bca8634753b45 | [
"Apache-2.0"
] | null | null | null | android/BeyondAR_Framework/src/com/beyondar/android/opengl/renderable/IRenderable.java | joanpuigsanz/beyondar | b58d1e65084a6345363ff5a5a41bca8634753b45 | [
"Apache-2.0"
] | null | null | null | 28.197183 | 77 | 0.726274 | 7,883 | /*
* Copyright (C) 2013 BeyondAR
*
* 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.beyondar.android.opengl.renderable;
import javax.microedition.khronos.opengles.GL10;
import com.beyondar.android.opengl.texture.Texture;
import com.beyondar.android.opengl.views.ARRenderer;
import com.beyondar.android.util.math.geom.Plane;
import com.beyondar.android.util.math.geom.Point3;
import com.beyondar.android.world.objects.BeyondarObject;
/**
* @author Joan Puig Sanz
*
*/
public interface IRenderable {
/** The draw method to be used by OpenGL */
public void draw(GL10 gl, Texture defaultTexture);
/**
* Update the renderer before the draw method is called.
*
* @param time
* The time mark.
* @param distance
* The distance form the camera in meters.
* @return True to force to paint the object, false otherwise. If false, the
* {@link ARRenderer} will draw it if it close enough to the camera
*/
public boolean update(long time, double distance,
BeyondarObject beyondarObject);
/**
* This method is called when the renderable is not painted because is too
* far
*/
public void onNotRendered(double dst);
public Texture getTexture();
public Plane getPlane();
public void setPosition(float x, float y, float z);
public Point3 getPosition();
public void setAngle(float x, float y, float z);
public Point3 getAngle();
public long getTimeFlag();
// public void setGeoObject(GeoObject object);
}
|
3e12b078d1d652f894c35758344703af82c89310 | 248 | java | Java | wit-core/src/main/java/org/febit/wit/resolvers/SetResolver.java | Andyfoo/wit | 794138cdbe9c5d4289ded8f7f4eb1cd1a96917ee | [
"BSD-3-Clause"
] | 20 | 2016-12-06T03:51:08.000Z | 2021-12-31T08:45:47.000Z | wit-core/src/main/java/org/febit/wit/resolvers/SetResolver.java | Amy2303/wit | 89ee29efbc5633b79c30c3c7b953c9f4130575af | [
"BSD-3-Clause"
] | 17 | 2017-10-05T09:45:52.000Z | 2021-03-28T05:08:16.000Z | wit-core/src/main/java/org/febit/wit/resolvers/SetResolver.java | Amy2303/wit | 89ee29efbc5633b79c30c3c7b953c9f4130575af | [
"BSD-3-Clause"
] | 8 | 2017-07-22T06:51:23.000Z | 2022-03-30T01:59:34.000Z | 20.666667 | 62 | 0.693548 | 7,884 | // Copyright (c) 2013-present, febit.org. All Rights Reserved.
package org.febit.wit.resolvers;
/**
* @param <T>
* @author zqq90
*/
public interface SetResolver<T> extends Resolver<T> {
void set(T object, Object property, Object value);
}
|
3e12b12d730930990a1cf27b2a5754101e0bd6ac | 3,329 | java | Java | src/main/java/com/fast/programming/service/example/loop/DateIterator.java | ybw2016/fast-functional-programming | 071f9c7b11d779beb19f0d8759d02e4adaa88f48 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/fast/programming/service/example/loop/DateIterator.java | ybw2016/fast-functional-programming | 071f9c7b11d779beb19f0d8759d02e4adaa88f48 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/fast/programming/service/example/loop/DateIterator.java | ybw2016/fast-functional-programming | 071f9c7b11d779beb19f0d8759d02e4adaa88f48 | [
"Apache-2.0"
] | null | null | null | 30.824074 | 96 | 0.628117 | 7,885 | package com.fast.programming.service.example.loop;
import com.fast.programming.service.FeatureBase;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 日期段处理
*
* @author bowen.yan
* @date 2018-08-08
*/
public class DateIterator extends FeatureBase {
@Override
protected String getComment() {
return "日期处理 -> 使用无限流再创建时间段很方便";
}
@Override
protected void runOld() {
LocalDate startDate = LocalDate.of(2018, 7, 25);
LocalDate endDate = LocalDate.of(2018, 8, 2);
LocalDate currDate = startDate;
while (!currDate.isAfter(endDate)) {
System.out.println(currDate);
currDate = currDate.plusDays(1);
}
}
@Override
protected void runNew() {
String startDate = "2018-07-25";
String endDate = "2018-08-02";
getPeriodDates(startDate, endDate).forEach(System.out::println);
System.out.println();
}
private static final String PATTERN_SHORT_TIME = "yyyy-MM-dd";
private static final String PATTERN_INIT_DATE = "yyyyMMdd";
/**
* 日期格式转换.
*
* @param inputDate 现有日期串
* @param srcPattern 现有格式
* @param targetPattern 目标格式
* @return 目标字符串
*/
public static String parse(String inputDate, String srcPattern, String targetPattern) {
LocalDate srcDate = LocalDate.parse(inputDate, DateTimeFormatter.ofPattern(srcPattern));
return srcDate.format(DateTimeFormatter.ofPattern(targetPattern));
}
/**
* 收集起始时间到结束时间之间所有的时间并以字符串集合方式返回.
* startDate = "2018-07-30"
* endDate = "2018-08-02"
* 返回集合:
* 2018-07-30
* 2018-07-31
* 2018-08-01
* 2018-08-02
*
* @param startDate yyyyMMdd、yyyy-MM-dd
* @param endDate yyyyMMdd、yyyy-MM-dd
* @return 日期集合
*/
public static List<String> getPeriodDates(String startDate, String endDate) {
if (!startDate.contains("-")) {
startDate = parse(startDate, PATTERN_INIT_DATE, PATTERN_SHORT_TIME);
}
if (!endDate.contains("-")) {
endDate = parse(endDate, PATTERN_INIT_DATE, PATTERN_SHORT_TIME);
}
return getPeriodDates(LocalDate.parse(startDate), LocalDate.parse(endDate));
}
/**
* 收集起始时间到结束时间之间所有的时间并以字符串集合方式返回
*/
public static List<String> getPeriodDates(LocalDate startDate, LocalDate endDate) {
// 用起始时间作为流的源头,按照每次加一天的方式创建一个无限流
return Stream.iterate(startDate, currDate -> currDate.plusDays(1))
// 截断无限流,长度为起始时间和结束时间的差+1个
.limit(ChronoUnit.DAYS.between(startDate, endDate) + 1)
// 由于最后要的是字符串,所以map转换一下
.map(currDate -> currDate.toString())
// 把流收集为List
.collect(Collectors.toList());
}
public static void main(String[] args) {
String startDate = "2018-07-25";
String endDate = "2018-08-02";
getPeriodDates(startDate, endDate).forEach(System.out::println);
System.out.println();
startDate = "20180725";
endDate = "20180802";
getPeriodDates(startDate, endDate).forEach(System.out::println);
}
}
|
3e12b1a5258a52094ef479c2267f8e59c9ad8000 | 4,479 | java | Java | src/main/java/fi/aalto/cs/apluscourses/intellij/actions/DownloadSubmissionAction.java | Aalto-LeTech/aplus-courses | 93f99f71f0b774c3e15a38115f01006f932d2392 | [
"MIT"
] | null | null | null | src/main/java/fi/aalto/cs/apluscourses/intellij/actions/DownloadSubmissionAction.java | Aalto-LeTech/aplus-courses | 93f99f71f0b774c3e15a38115f01006f932d2392 | [
"MIT"
] | 127 | 2021-09-29T13:13:02.000Z | 2022-03-31T13:41:41.000Z | src/main/java/fi/aalto/cs/apluscourses/intellij/actions/DownloadSubmissionAction.java | Aalto-LeTech/aplus-courses | 93f99f71f0b774c3e15a38115f01006f932d2392 | [
"MIT"
] | 2 | 2021-10-02T09:13:17.000Z | 2021-11-24T16:44:29.000Z | 42.254717 | 109 | 0.766466 | 7,886 | package fi.aalto.cs.apluscourses.intellij.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import fi.aalto.cs.apluscourses.intellij.notifications.DefaultNotifier;
import fi.aalto.cs.apluscourses.intellij.notifications.ExerciseNotSelectedNotification;
import fi.aalto.cs.apluscourses.intellij.notifications.Notifier;
import fi.aalto.cs.apluscourses.intellij.services.MainViewModelProvider;
import fi.aalto.cs.apluscourses.intellij.services.PluginSettings;
import fi.aalto.cs.apluscourses.intellij.utils.Interfaces;
import fi.aalto.cs.apluscourses.intellij.utils.SubmissionDownloader;
import fi.aalto.cs.apluscourses.model.DummySubmissionResult;
import fi.aalto.cs.apluscourses.model.SubmissionResult;
import fi.aalto.cs.apluscourses.presentation.exercise.ExerciseViewModel;
import fi.aalto.cs.apluscourses.presentation.exercise.ExercisesTreeViewModel;
import fi.aalto.cs.apluscourses.presentation.exercise.SubmissionResultViewModel;
import fi.aalto.cs.apluscourses.utils.APlusLogger;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
public class DownloadSubmissionAction extends AnAction {
private static final Logger logger = APlusLogger.logger;
@NotNull
private final MainViewModelProvider mainViewModelProvider;
@NotNull
private final Notifier notifier;
@NotNull
private final Interfaces.AssistantModeProvider assistantModeProvider;
/**
* Constructor with reasonable defaults.
*/
public DownloadSubmissionAction() {
this(
PluginSettings.getInstance(),
new DefaultNotifier(),
() -> PluginSettings.getInstance().isAssistantMode()
);
}
/**
* Construct an exercise submission action with the given parameters. This constructor is useful
* for testing purposes.
*/
public DownloadSubmissionAction(@NotNull MainViewModelProvider mainViewModelProvider,
@NotNull Notifier notifier,
@NotNull Interfaces.AssistantModeProvider assistantModeProvider) {
this.mainViewModelProvider = mainViewModelProvider;
this.notifier = notifier;
this.assistantModeProvider = assistantModeProvider;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
logger.info("Starting DownloadSubmissionAction");
var project = e.getProject();
var mainViewModel = mainViewModelProvider.getMainViewModel(project);
var courseViewModel = mainViewModel.courseViewModel.get();
var exercisesTreeViewModel = mainViewModel.exercisesViewModel.get();
if (project == null || courseViewModel == null || exercisesTreeViewModel == null) {
return;
}
var selectedItem = exercisesTreeViewModel.getSelectedItem();
if (!(selectedItem instanceof SubmissionResultViewModel)) {
logger.info("Selected item not submission result");
return;
}
var selection = (ExercisesTreeViewModel.ExerciseTreeSelection) exercisesTreeViewModel.findSelected();
var selectedExercise = selection.getExercise();
var selectedExerciseGroup = selection.getExerciseGroup();
if (selectedExercise == null || selectedExerciseGroup == null) {
notifier.notifyAndHide(new ExerciseNotSelectedNotification(), project);
return;
}
var exercise = selectedExercise.getModel();
var course = courseViewModel.getModel();
new SubmissionDownloader().downloadSubmission(project, course, exercise,
(SubmissionResult) selectedItem.getModel());
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setVisible(assistantModeProvider.isAssistantMode());
e.getPresentation().setEnabled(false);
var mainViewModel = mainViewModelProvider.getMainViewModel(e.getProject());
var courseViewModel = mainViewModel.courseViewModel.get();
var exercisesTreeViewModel = mainViewModel.exercisesViewModel.get();
if (courseViewModel != null && exercisesTreeViewModel != null) {
var selection = (ExercisesTreeViewModel.ExerciseTreeSelection) exercisesTreeViewModel.findSelected();
ExerciseViewModel selectedExercise = selection.getExercise();
var selectedItem = exercisesTreeViewModel.getSelectedItem();
e.getPresentation().setEnabled(selectedItem instanceof SubmissionResultViewModel
&& selectedExercise != null
&& (selectedExercise.isSubmittable() || selectedItem.getModel() instanceof DummySubmissionResult));
}
}
}
|
3e12b1b16bfc00bd004d2c615391d667b84a0eda | 1,525 | java | Java | app/src/main/java/com/ecosystem/kin/app/model/SignInRepo.java | degyes/kin-ecosystem-android-sdk | e4bed0996ef7c1a527feb409a393d4dff1483799 | [
"MIT"
] | null | null | null | app/src/main/java/com/ecosystem/kin/app/model/SignInRepo.java | degyes/kin-ecosystem-android-sdk | e4bed0996ef7c1a527feb409a393d4dff1483799 | [
"MIT"
] | null | null | null | app/src/main/java/com/ecosystem/kin/app/model/SignInRepo.java | degyes/kin-ecosystem-android-sdk | e4bed0996ef7c1a527feb409a393d4dff1483799 | [
"MIT"
] | null | null | null | 34.659091 | 120 | 0.731803 | 7,887 | package com.ecosystem.kin.app.model;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.ecosystem.kin.app.BuildConfig;
import com.ecosystem.kin.app.JwtUtil;
import com.kin.ecosystem.common.model.WhitelistData;
import java.util.UUID;
public class SignInRepo {
private final static String USER_PREFERENCE_FILE_KEY = "USER_PREFERENCE_FILE_KEY";
private final static String USER_UUID_KEY = "USER_UUID_KEY";
public static WhitelistData getWhitelistSignInData(Context context, @NonNull String appId, @NonNull String apiKey) {
return new WhitelistData(getUserId(context), appId, apiKey);
}
public static String getJWT(Context context) {
return JwtUtil.generateSignInExampleJWT(getAppId(), getUserId(context));
}
@NonNull
private static String getAppId() {
return BuildConfig.SAMPLE_APP_ID;
}
private static SharedPreferences getSharedPreferences(Context context) {
return context
.getSharedPreferences(USER_PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
}
public static String getUserId(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
String userID = sharedPreferences.getString(USER_UUID_KEY, null);
if (userID == null) {
userID = UUID.randomUUID().toString();
sharedPreferences.edit().putString(USER_UUID_KEY, userID).apply();
}
return userID;
}
}
|
3e12b21352f7c57c519233295d5780d2e0a1b94b | 390 | java | Java | src/test/java/com/esfak47/common/job/JobTest.java | esfak47/core | f42ab73c866a0c6fbb8d40405f47fca6a63b0bdc | [
"Apache-2.0"
] | 1 | 2020-03-18T04:17:00.000Z | 2020-03-18T04:17:00.000Z | src/test/java/com/esfak47/common/job/JobTest.java | esfak47/core | f42ab73c866a0c6fbb8d40405f47fca6a63b0bdc | [
"Apache-2.0"
] | 2 | 2021-12-18T18:25:28.000Z | 2022-01-04T16:41:58.000Z | src/test/java/com/esfak47/common/job/JobTest.java | esfak47/core | f42ab73c866a0c6fbb8d40405f47fca6a63b0bdc | [
"Apache-2.0"
] | 2 | 2018-12-16T15:43:32.000Z | 2018-12-18T15:30:19.000Z | 16.956522 | 85 | 0.694872 | 7,888 | package com.esfak47.common.job;
import org.junit.Test;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* @author tony
* @date 2018/4/24
*/
public class JobTest {
@Test
public void test() {
ServiceLoader<JobManager> jobManagers = ServiceLoader.load(JobManager.class);
Iterator<JobManager> jobManagerIterator = jobManagers.iterator();
}
}
|
3e12b382e7a73161536b7924a494673ea0e803e1 | 1,736 | java | Java | patterntesting-rt/src/test/java/patterntesting/runtime/log/test/CityRepo.java | oboehm/PatternTesting2 | 667cb549379023a3f7e114bb9bd88cd3ed19987d | [
"Apache-2.0"
] | 1 | 2021-01-31T19:50:43.000Z | 2021-01-31T19:50:43.000Z | patterntesting-rt/src/test/java/patterntesting/runtime/log/test/CityRepo.java | oboehm/PatternTesting2 | 667cb549379023a3f7e114bb9bd88cd3ed19987d | [
"Apache-2.0"
] | 11 | 2020-04-05T19:03:45.000Z | 2022-01-11T21:37:09.000Z | patterntesting-rt/src/test/java/patterntesting/runtime/log/test/CityRepo.java | oboehm/PatternTesting2 | 667cb549379023a3f7e114bb9bd88cd3ed19987d | [
"Apache-2.0"
] | null | null | null | 24.7 | 74 | 0.646038 | 7,889 | /*
* $Id: CityRepo.java,v 1.4 2016/12/18 20:19:38 oboehm Exp $
*
* Copyright (c) 2015 by Oliver Boehm
*
* 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 orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 02.06.2015 by oliver (envkt@example.com)
*/
package patterntesting.runtime.log.test;
import java.util.ArrayList;
import java.util.Collection;
import patterntesting.runtime.exception.NotFoundException;
/**
* A simple repository to store cities. This class is abstract because
* it provides only static methods.
*
* @author oliver
* @version $Revision: 1.4 $
* @since 1.6 (02.06.2015)
*/
public abstract class CityRepo {
private static Collection<City> cities = new ArrayList<>();
/** No need to instantiate it. */
private CityRepo() {
}
/**
* Adds the city.
*
* @param city the city
*/
public static void addCity(final City city) {
cities.add(city);
}
/**
* Gets the city.
*
* @param name the name
* @return the city
*/
public static City getCity(final String name) {
for (City city : cities) {
if (name.equals(city.getName())) {
return city;
}
}
throw new NotFoundException(name);
}
}
|
3e12b48318c861b27192cee91268b21b955d70e2 | 2,405 | java | Java | aCis_gameserver/java/net/sf/l2j/gameserver/network/clientpackets/RequestExEnchantSkillInfo.java | naustagic/L2JNetwork_Interlude | 62cf8dabb032f1d4529e3877f2f724ebc5060ad7 | [
"MIT"
] | null | null | null | aCis_gameserver/java/net/sf/l2j/gameserver/network/clientpackets/RequestExEnchantSkillInfo.java | naustagic/L2JNetwork_Interlude | 62cf8dabb032f1d4529e3877f2f724ebc5060ad7 | [
"MIT"
] | null | null | null | aCis_gameserver/java/net/sf/l2j/gameserver/network/clientpackets/RequestExEnchantSkillInfo.java | naustagic/L2JNetwork_Interlude | 62cf8dabb032f1d4529e3877f2f724ebc5060ad7 | [
"MIT"
] | null | null | null | 28.975904 | 149 | 0.70894 | 7,890 | package net.sf.l2j.gameserver.network.clientpackets;
import net.sf.l2j.Config;
import net.sf.l2j.gameserver.data.SkillTable;
import net.sf.l2j.gameserver.data.SkillTreeTable;
import net.sf.l2j.gameserver.model.L2EnchantSkillData;
import net.sf.l2j.gameserver.model.L2EnchantSkillLearn;
import net.sf.l2j.gameserver.model.L2Skill;
import net.sf.l2j.gameserver.model.actor.Npc;
import net.sf.l2j.gameserver.model.actor.instance.Player;
import net.sf.l2j.gameserver.network.serverpackets.ExEnchantSkillInfo;
/**
* Format chdd c: (id) 0xD0 h: (subid) 0x06 d: skill id d: skill lvl
* @author -Wooden-
*/
public final class RequestExEnchantSkillInfo extends L2GameClientPacket
{
private int _skillId;
private int _skillLevel;
@Override
protected void readImpl()
{
_skillId = readD();
_skillLevel = readD();
}
@Override
protected void runImpl()
{
if (_skillId <= 0 || _skillLevel <= 0)
return;
Player activeChar = getClient().getActiveChar();
if (activeChar == null)
return;
if (activeChar.getClassId().level() < 3 || activeChar.getLevel() < 76)
return;
final Npc trainer = activeChar.getCurrentFolkNPC();
if (trainer == null)
return;
if (!activeChar.isInsideRadius(trainer, Npc.INTERACTION_DISTANCE, false, false) && !activeChar.isGM())
return;
if (activeChar.getSkillLevel(_skillId) >= _skillLevel)
return;
final L2Skill skill = SkillTable.getInstance().getInfo(_skillId, _skillLevel);
if (skill == null)
return;
if (!trainer.getTemplate().canTeach(activeChar.getClassId()))
return;
// Try to find enchant skill.
for (L2EnchantSkillLearn esl : SkillTreeTable.getInstance().getAvailableEnchantSkills(activeChar))
{
if (esl == null)
continue;
if (esl.getId() == _skillId && esl.getLevel() == _skillLevel)
{
L2EnchantSkillData data = SkillTreeTable.getInstance().getEnchantSkillData(esl.getEnchant());
// Enchant skill or enchant data not found.
if (data == null)
return;
// Send ExEnchantSkillInfo packet.
ExEnchantSkillInfo esi = new ExEnchantSkillInfo(_skillId, _skillLevel, data.getCostSp(), data.getCostExp(), data.getRate(activeChar.getLevel()));
if (Config.ES_SP_BOOK_NEEDED)
if (data.getItemId() != 0 && data.getItemCount() != 0)
esi.addRequirement(4, data.getItemId(), data.getItemCount(), 0);
sendPacket(esi);
break;
}
}
}
} |
3e12b6241f8b19de84f4ea613e0848d92c18ac5d | 1,383 | java | Java | src/main/java/org/fuber/cabservice/fubercabservice/controller/GlobalExceptionHandlerController.java | sumantav19/CabService | 9dbadcc2e13501bcb1719b47cee8be9d22f16bbe | [
"Unlicense"
] | null | null | null | src/main/java/org/fuber/cabservice/fubercabservice/controller/GlobalExceptionHandlerController.java | sumantav19/CabService | 9dbadcc2e13501bcb1719b47cee8be9d22f16bbe | [
"Unlicense"
] | null | null | null | src/main/java/org/fuber/cabservice/fubercabservice/controller/GlobalExceptionHandlerController.java | sumantav19/CabService | 9dbadcc2e13501bcb1719b47cee8be9d22f16bbe | [
"Unlicense"
] | null | null | null | 37.378378 | 67 | 0.842372 | 7,891 | package org.fuber.cabservice.fubercabservice.controller;
import org.fuber.cabservice.exception.ExceptionBody;
import org.fuber.cabservice.exception.InvalidBookingIdException;
import org.fuber.cabservice.exception.InvalidCabTypeException;
import org.fuber.cabservice.exception.NoCabFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@ControllerAdvice
@RestController
public class GlobalExceptionHandlerController {
@ResponseStatus(value=HttpStatus.NOT_FOUND)
@ExceptionHandler(value = InvalidBookingIdException.class)
public ExceptionBody handleException(InvalidBookingIdException e){
return new ExceptionBody(HttpStatus.NOT_FOUND, e.getMessage());
}
@ResponseStatus(value=HttpStatus.OK)
@ExceptionHandler(value = NoCabFoundException.class)
public ExceptionBody handleException(NoCabFoundException e){
return new ExceptionBody(HttpStatus.OK, e.getMessage());
}
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = InvalidCabTypeException.class)
public ExceptionBody handleException(InvalidCabTypeException e){
return new ExceptionBody(HttpStatus.OK, e.getMessage());
}
}
|
3e12b63decaa4fa5e2ecf00fe03f255ee217f3b0 | 175 | java | Java | plugin/virtualRouterProvider/src/main/java/org/zstack/network/service/virtualrouter/APIGetVirtualRouterOfferingReply.java | jxg01713/zstack | 182fb094e9a6ef89cf010583d457a9bf4f033f33 | [
"Apache-2.0"
] | null | null | null | plugin/virtualRouterProvider/src/main/java/org/zstack/network/service/virtualrouter/APIGetVirtualRouterOfferingReply.java | jxg01713/zstack | 182fb094e9a6ef89cf010583d457a9bf4f033f33 | [
"Apache-2.0"
] | 6 | 2020-02-28T01:26:39.000Z | 2021-03-19T20:23:19.000Z | plugin/virtualRouterProvider/src/main/java/org/zstack/network/service/virtualrouter/APIGetVirtualRouterOfferingReply.java | jxg01713/zstack | 182fb094e9a6ef89cf010583d457a9bf4f033f33 | [
"Apache-2.0"
] | null | null | null | 21.875 | 68 | 0.811429 | 7,892 | package org.zstack.network.service.virtualrouter;
import org.zstack.header.search.APIGetReply;
public class APIGetVirtualRouterOfferingReply extends APIGetReply {
}
|
3e12b6c01eb8c463d4e43de4810f09f1ec53a98d | 800 | java | Java | mcoq/src/main/java/edu/utexas/ece/mcoq8_10/mutation/RightEmptyConcat.java | EngineeringSoftware/mCoq | fbeb89402931f477eed41c855c4f2b010b2cd82e | [
"Apache-2.0"
] | 21 | 2020-01-19T14:38:10.000Z | 2022-02-16T22:00:48.000Z | mcoq/src/main/java/edu/utexas/ece/mcoq8_10/mutation/RightEmptyConcat.java | EngineeringSoftware/mCoq | fbeb89402931f477eed41c855c4f2b010b2cd82e | [
"Apache-2.0"
] | 4 | 2020-05-14T16:25:12.000Z | 2020-05-23T20:35:51.000Z | mcoq/src/main/java/edu/utexas/ece/mcoq8_10/mutation/RightEmptyConcat.java | EngineeringSoftware/mCoq | fbeb89402931f477eed41c855c4f2b010b2cd82e | [
"Apache-2.0"
] | 2 | 2020-01-17T20:23:28.000Z | 2020-02-13T20:05:15.000Z | 29 | 106 | 0.657635 | 7,893 | package edu.utexas.ece.mcoq8_10.mutation;
import de.tudresden.inf.lat.jsexp.Sexp;
import edu.utexas.ece.mcoq8_10.util.SexpUtils;
/**
* Replaces "l1 ++ l2" with "l1" OR "app l1 l2" with "l1".
*
* @author Ahmet Celik <dycjh@example.com>
* @author Marinela Parovic <nnheo@example.com>
*/
public class RightEmptyConcat extends MutateConcat {
private Sexp expToMutate(Sexp sexp) {
return sexp.get(ONE).get(TWO).get(ZERO).get(ONE).get(ZERO);
}
@Override
public void mutate(Sexp sexp) {
if (canMutateCNotation(sexp)) {
expToMutate(sexp).set(ONE, SexpUtils.newEmptyListSexp8_9());
}
else if(canMutateCApp(sexp)) {
sexp.get(ONE).get(TWO).get(ONE).get(ZERO).get(ZERO).set(ONE, SexpUtils.newEmptyListSexp8_9());
}
}
}
|
3e12b7130d279038b43b4e94ac01c32362959b2f | 2,138 | java | Java | app/src/main/java/cn/xcom/banjing/sp/UserSp.java | QiangzhenZhu/52tongcheng | f9c19bd1f8c64118dc1e14e73df40499d383e11f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/cn/xcom/banjing/sp/UserSp.java | QiangzhenZhu/52tongcheng | f9c19bd1f8c64118dc1e14e73df40499d383e11f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/cn/xcom/banjing/sp/UserSp.java | QiangzhenZhu/52tongcheng | f9c19bd1f8c64118dc1e14e73df40499d383e11f | [
"Apache-2.0"
] | 1 | 2019-06-30T06:32:39.000Z | 2019-06-30T06:32:39.000Z | 24.860465 | 63 | 0.648737 | 7,894 | package cn.xcom.banjing.sp;
import android.content.Context;
import android.content.SharedPreferences;
import cn.xcom.banjing.bean.UserInfo;
public class UserSp extends BaseSp<UserInfo> {
public UserSp(Context context) {
super(context, "user_sp");
}
@Override
public void read(UserInfo user) {
// 安全检查
if (user == null) {
user = new UserInfo();
}
if (getSP().contains("userId")) {
user.setUserId(getSP().getString("userId", ""));
}
if (getSP().contains("userPhone")) {
user.setUserPhone(getSP().getString("userPhone", ""));
}
if (getSP().contains("userCode")) {
user.setUserCode(getSP().getString("userCode", ""));
}
if (getSP().contains("userName")) {
user.setUserName(getSP().getString("userName", ""));
}
if (getSP().contains("userPassword")) {
user.setUserPassword(getSP().getString("userPassword", ""));
}
if (getSP().contains("userGender")) {
user.setUserGender(getSP().getString("userGender", ""));
}
if (getSP().contains("userImg")) {
user.setUserImg(getSP().getString("userImg", ""));
}
}
@Override
public UserInfo read() {
UserInfo result = null;
result = new UserInfo();
read(result);
return result;
}
@Override
public void write(UserInfo user) {
SharedPreferences.Editor editor = getSP().edit();
if (!user.getUserId().equals("")) {
editor.putString("userId", user.getUserId());
}
if (!user.getUserPhone().equals("")) {
editor.putString("userPhone", user.getUserPhone());
}
if (!user.getUserPhone().equals("")) {
editor.putString("userCode", user.getUserCode());
}
if (!user.getUserName().equals("")) {
editor.putString("userName", user.getUserName());
}
if (!user.getUserPassword().equals("")) {
editor.putString("userPassword", user.getUserPassword());
}
if (!user.getUserGender().equals("")) {
editor.putString("userGender", user.getUserGender());
}
if (!user.getUserImg().equals("")) {
editor.putString("userImg", user.getUserImg());
}
editor.commit();
}
@Override
public void clear() {
SharedPreferences.Editor editor = getSP().edit();
editor.clear();
editor.commit();
}
} |
3e12b7c557a0348e96961d25b19872ee9653e676 | 875 | java | Java | src/math/Boj1188.java | minuk8932/Algorithm_BaekJoon | 9ba6e6669d7cdde622c7d527fef77c2035bf2528 | [
"Apache-2.0"
] | 3 | 2019-05-10T08:23:46.000Z | 2020-08-20T10:35:30.000Z | src/math/Boj1188.java | minuk8932/Algorithm_BaekJoon | 9ba6e6669d7cdde622c7d527fef77c2035bf2528 | [
"Apache-2.0"
] | null | null | null | src/math/Boj1188.java | minuk8932/Algorithm_BaekJoon | 9ba6e6669d7cdde622c7d527fef77c2035bf2528 | [
"Apache-2.0"
] | 3 | 2019-05-15T13:06:50.000Z | 2021-04-19T08:40:40.000Z | 21.875 | 75 | 0.660571 | 7,895 | package math;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author minchoba
* 백준 1188번: 음식평론가
*
* @see https://www.acmicpc.net/problem/1188/
*
*/
public class Boj1188 {
private static final String SPACE = " ";
public static void main(String[] args) throws Exception{
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), SPACE);
int N = Integer.parseInt(st.nextToken()); // 소세지 수
int M = Integer.parseInt(st.nextToken()); // 평론가의 수
System.out.println(M - gcd(N, M));
}
/**
* 유클리드 호제법
* @param num1: 소세지 수
* @param num2: 평론가의 수
* @return 최종적으로 최대 공약수 반환
*/
private static int gcd(int num1, int num2) {
if(num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
}
|
3e12b8979aa910089a05c3743f32c3a423120bcd | 25,063 | java | Java | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/output/AutodetectResultProcessorTests.java | yangsongbai/elasticsearch | d3ccada06f44f9ee1d37c75a7653001bec11fdb1 | [
"Apache-2.0"
] | 1 | 2020-05-11T06:37:58.000Z | 2020-05-11T06:37:58.000Z | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/output/AutodetectResultProcessorTests.java | yangsongbai/elasticsearch | d3ccada06f44f9ee1d37c75a7653001bec11fdb1 | [
"Apache-2.0"
] | 1 | 2020-05-25T06:13:16.000Z | 2020-05-25T06:13:16.000Z | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/output/AutodetectResultProcessorTests.java | lionxu/elasticsearch | 11111695dc83b43ed2df744ea88f6bebcf2cbc10 | [
"Apache-2.0"
] | null | null | null | 49.143137 | 139 | 0.737063 | 7,896 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ml.job.process.autodetect.output;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.Scheduler;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.ml.action.UpdateJobAction;
import org.elasticsearch.xpack.core.ml.annotations.Annotation;
import org.elasticsearch.xpack.core.ml.annotations.AnnotationPersister;
import org.elasticsearch.xpack.core.ml.job.config.JobUpdate;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.output.FlushAcknowledgement;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSizeStats;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSnapshot;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.Quantiles;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.TimingStats;
import org.elasticsearch.xpack.core.ml.job.results.AnomalyRecord;
import org.elasticsearch.xpack.core.ml.job.results.Bucket;
import org.elasticsearch.xpack.core.ml.job.results.CategoryDefinition;
import org.elasticsearch.xpack.core.ml.job.results.Influencer;
import org.elasticsearch.xpack.core.ml.job.results.ModelPlot;
import org.elasticsearch.xpack.core.security.user.XPackUser;
import org.elasticsearch.xpack.ml.job.persistence.JobResultsPersister;
import org.elasticsearch.xpack.ml.job.process.autodetect.AutodetectProcess;
import org.elasticsearch.xpack.ml.job.process.normalizer.Renormalizer;
import org.elasticsearch.xpack.ml.job.results.AutodetectResult;
import org.elasticsearch.xpack.ml.notifications.AnomalyDetectionAuditor;
import org.junit.After;
import org.junit.Before;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeoutException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class AutodetectResultProcessorTests extends ESTestCase {
private static final String JOB_ID = "valid_id";
private static final long BUCKET_SPAN_MS = 1000;
private static final Instant CURRENT_TIME = Instant.ofEpochMilli(2000000000);
private ThreadPool threadPool;
private Client client;
private AnomalyDetectionAuditor auditor;
private Renormalizer renormalizer;
private JobResultsPersister persister;
private JobResultsPersister.Builder bulkBuilder;
private AnnotationPersister annotationPersister;
private AutodetectProcess process;
private FlushListener flushListener;
private AutodetectResultProcessor processorUnderTest;
private ScheduledThreadPoolExecutor executor;
@Before
public void setUpMocks() {
executor = new Scheduler.SafeScheduledThreadPoolExecutor(1);
client = mock(Client.class);
threadPool = mock(ThreadPool.class);
when(client.threadPool()).thenReturn(threadPool);
when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));
auditor = mock(AnomalyDetectionAuditor.class);
renormalizer = mock(Renormalizer.class);
persister = mock(JobResultsPersister.class);
bulkBuilder = mock(JobResultsPersister.Builder.class);
annotationPersister = mock(AnnotationPersister.class);
when(persister.bulkPersisterBuilder(eq(JOB_ID), any())).thenReturn(bulkBuilder);
process = mock(AutodetectProcess.class);
flushListener = mock(FlushListener.class);
processorUnderTest = new AutodetectResultProcessor(
client,
auditor,
JOB_ID,
renormalizer,
persister,
annotationPersister,
process,
new ModelSizeStats.Builder(JOB_ID).setTimestamp(new Date(BUCKET_SPAN_MS)).build(),
new TimingStats(JOB_ID),
Clock.fixed(CURRENT_TIME, ZoneId.systemDefault()),
flushListener);
}
@After
public void cleanup() {
verifyNoMoreInteractions(auditor, renormalizer, persister, annotationPersister);
executor.shutdown();
}
public void testProcess() throws TimeoutException {
AutodetectResult autodetectResult = mock(AutodetectResult.class);
when(process.readAutodetectResults()).thenReturn(Arrays.asList(autodetectResult).iterator());
processorUnderTest.process();
processorUnderTest.awaitCompletion();
assertThat(processorUnderTest.completionLatch.getCount(), is(equalTo(0L)));
verify(renormalizer).waitUntilIdle();
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).commitResultWrites(JOB_ID);
verify(persister).commitStateWrites(JOB_ID);
}
public void testProcessResult_bucket() {
when(bulkBuilder.persistTimingStats(any(TimingStats.class))).thenReturn(bulkBuilder);
when(bulkBuilder.persistBucket(any(Bucket.class))).thenReturn(bulkBuilder);
AutodetectResult result = mock(AutodetectResult.class);
Bucket bucket = new Bucket(JOB_ID, new Date(), BUCKET_SPAN_MS);
when(result.getBucket()).thenReturn(bucket);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(bulkBuilder).persistTimingStats(any(TimingStats.class));
verify(bulkBuilder).persistBucket(bucket);
verify(bulkBuilder).executeRequest();
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister, never()).deleteInterimResults(JOB_ID);
}
public void testProcessResult_bucket_deleteInterimRequired() {
when(bulkBuilder.persistTimingStats(any(TimingStats.class))).thenReturn(bulkBuilder);
when(bulkBuilder.persistBucket(any(Bucket.class))).thenReturn(bulkBuilder);
AutodetectResult result = mock(AutodetectResult.class);
Bucket bucket = new Bucket(JOB_ID, new Date(), BUCKET_SPAN_MS);
when(result.getBucket()).thenReturn(bucket);
processorUnderTest.processResult(result);
assertFalse(processorUnderTest.isDeleteInterimRequired());
verify(bulkBuilder).persistTimingStats(any(TimingStats.class));
verify(bulkBuilder).persistBucket(bucket);
verify(bulkBuilder).executeRequest();
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).deleteInterimResults(JOB_ID);
}
public void testProcessResult_records() {
AutodetectResult result = mock(AutodetectResult.class);
List<AnomalyRecord> records =
Arrays.asList(
new AnomalyRecord(JOB_ID, new Date(123), 123),
new AnomalyRecord(JOB_ID, new Date(123), 123));
when(result.getRecords()).thenReturn(records);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(bulkBuilder).persistRecords(records);
verify(bulkBuilder, never()).executeRequest();
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
}
public void testProcessResult_influencers() {
AutodetectResult result = mock(AutodetectResult.class);
List<Influencer> influencers =
Arrays.asList(
new Influencer(JOB_ID, "infField", "infValue", new Date(123), 123),
new Influencer(JOB_ID, "infField2", "infValue2", new Date(123), 123));
when(result.getInfluencers()).thenReturn(influencers);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(bulkBuilder).persistInfluencers(influencers);
verify(bulkBuilder, never()).executeRequest();
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
}
public void testProcessResult_categoryDefinition() {
AutodetectResult result = mock(AutodetectResult.class);
CategoryDefinition categoryDefinition = mock(CategoryDefinition.class);
when(categoryDefinition.getCategoryId()).thenReturn(1L);
when(result.getCategoryDefinition()).thenReturn(categoryDefinition);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(bulkBuilder, never()).executeRequest();
verify(persister).persistCategoryDefinition(eq(categoryDefinition), any());
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
}
public void testProcessResult_flushAcknowledgement() {
AutodetectResult result = mock(AutodetectResult.class);
FlushAcknowledgement flushAcknowledgement = mock(FlushAcknowledgement.class);
when(flushAcknowledgement.getId()).thenReturn(JOB_ID);
when(result.getFlushAcknowledgement()).thenReturn(flushAcknowledgement);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
assertTrue(processorUnderTest.isDeleteInterimRequired());
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(flushListener).acknowledgeFlush(flushAcknowledgement, null);
verify(persister).commitResultWrites(JOB_ID);
verify(bulkBuilder).executeRequest();
}
public void testProcessResult_flushAcknowledgementMustBeProcessedLast() {
AutodetectResult result = mock(AutodetectResult.class);
FlushAcknowledgement flushAcknowledgement = mock(FlushAcknowledgement.class);
when(flushAcknowledgement.getId()).thenReturn(JOB_ID);
when(result.getFlushAcknowledgement()).thenReturn(flushAcknowledgement);
CategoryDefinition categoryDefinition = mock(CategoryDefinition.class);
when(categoryDefinition.getCategoryId()).thenReturn(1L);
when(result.getCategoryDefinition()).thenReturn(categoryDefinition);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
assertTrue(processorUnderTest.isDeleteInterimRequired());
InOrder inOrder = inOrder(persister, bulkBuilder, flushListener);
inOrder.verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
inOrder.verify(persister).persistCategoryDefinition(eq(categoryDefinition), any());
inOrder.verify(bulkBuilder).executeRequest();
inOrder.verify(persister).commitResultWrites(JOB_ID);
inOrder.verify(flushListener).acknowledgeFlush(flushAcknowledgement, null);
}
public void testProcessResult_modelPlot() {
AutodetectResult result = mock(AutodetectResult.class);
ModelPlot modelPlot = mock(ModelPlot.class);
when(result.getModelPlot()).thenReturn(modelPlot);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(bulkBuilder).persistModelPlot(modelPlot);
}
public void testProcessResult_modelSizeStats() {
AutodetectResult result = mock(AutodetectResult.class);
ModelSizeStats modelSizeStats = mock(ModelSizeStats.class);
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
assertThat(processorUnderTest.modelSizeStats(), is(equalTo(modelSizeStats)));
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).persistModelSizeStats(eq(modelSizeStats), any());
}
public void testProcessResult_modelSizeStatsWithMemoryStatusChanges() {
AutodetectResult result = mock(AutodetectResult.class);
processorUnderTest.setDeleteInterimRequired(false);
// First one with soft_limit
ModelSizeStats modelSizeStats = new ModelSizeStats.Builder(JOB_ID).setMemoryStatus(ModelSizeStats.MemoryStatus.SOFT_LIMIT).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
// Another with soft_limit
modelSizeStats = new ModelSizeStats.Builder(JOB_ID).setMemoryStatus(ModelSizeStats.MemoryStatus.SOFT_LIMIT).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
// Now with hard_limit
modelSizeStats = new ModelSizeStats.Builder(JOB_ID)
.setMemoryStatus(ModelSizeStats.MemoryStatus.HARD_LIMIT)
.setModelBytesMemoryLimit(new ByteSizeValue(512, ByteSizeUnit.MB).getBytes())
.setModelBytesExceeded(new ByteSizeValue(1, ByteSizeUnit.KB).getBytes())
.build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
// And another with hard_limit
modelSizeStats = new ModelSizeStats.Builder(JOB_ID).setMemoryStatus(ModelSizeStats.MemoryStatus.HARD_LIMIT).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister, times(4)).persistModelSizeStats(any(ModelSizeStats.class), any());
// We should have only fired two notifications: one for soft_limit and one for hard_limit
verify(auditor).warning(JOB_ID, Messages.getMessage(Messages.JOB_AUDIT_MEMORY_STATUS_SOFT_LIMIT));
verify(auditor).error(JOB_ID, Messages.getMessage(Messages.JOB_AUDIT_MEMORY_STATUS_HARD_LIMIT, "512mb", "1kb"));
}
public void testProcessResult_modelSizeStatsWithCategorizationStatusChanges() {
AutodetectResult result = mock(AutodetectResult.class);
processorUnderTest.setDeleteInterimRequired(false);
// First one with ok
ModelSizeStats modelSizeStats =
new ModelSizeStats.Builder(JOB_ID).setCategorizationStatus(ModelSizeStats.CategorizationStatus.OK).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
// Now one with warn
modelSizeStats = new ModelSizeStats.Builder(JOB_ID).setCategorizationStatus(ModelSizeStats.CategorizationStatus.WARN).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
// Another with warn
modelSizeStats = new ModelSizeStats.Builder(JOB_ID).setCategorizationStatus(ModelSizeStats.CategorizationStatus.WARN).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister, times(3)).persistModelSizeStats(any(ModelSizeStats.class), any());
// We should have only fired one notification; only the change from ok to warn should have fired, not the subsequent warn
verify(auditor).warning(JOB_ID, Messages.getMessage(Messages.JOB_AUDIT_CATEGORIZATION_STATUS_WARN, "warn", 0));
}
public void testProcessResult_modelSizeStatsWithFirstCategorizationStatusWarn() {
AutodetectResult result = mock(AutodetectResult.class);
processorUnderTest.setDeleteInterimRequired(false);
// First one with warn - this works because a default constructed ModelSizeStats has CategorizationStatus.OK
ModelSizeStats modelSizeStats =
new ModelSizeStats.Builder(JOB_ID).setCategorizationStatus(ModelSizeStats.CategorizationStatus.WARN).build();
when(result.getModelSizeStats()).thenReturn(modelSizeStats);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).persistModelSizeStats(any(ModelSizeStats.class), any());
// We should have only fired one notification; only the change from ok to warn should have fired, not the subsequent warn
verify(auditor).warning(JOB_ID, Messages.getMessage(Messages.JOB_AUDIT_CATEGORIZATION_STATUS_WARN, "warn", 0));
}
public void testProcessResult_modelSnapshot() {
AutodetectResult result = mock(AutodetectResult.class);
ModelSnapshot modelSnapshot = new ModelSnapshot.Builder(JOB_ID)
.setSnapshotId("a_snapshot_id")
.setLatestResultTimeStamp(Date.from(Instant.ofEpochMilli(1000_000_000)))
.setTimestamp(Date.from(Instant.ofEpochMilli(2000_000_000)))
.setMinVersion(Version.CURRENT)
.build();
when(result.getModelSnapshot()).thenReturn(modelSnapshot);
IndexResponse indexResponse = new IndexResponse(new ShardId("ml", "uid", 0), "1", 0L, 0L, 0L, true);
when(persister.persistModelSnapshot(any(), any(), any()))
.thenReturn(new BulkResponse(new BulkItemResponse[]{new BulkItemResponse(0, DocWriteRequest.OpType.INDEX, indexResponse)}, 0));
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).persistModelSnapshot(eq(modelSnapshot), eq(WriteRequest.RefreshPolicy.IMMEDIATE), any());
ArgumentCaptor<Annotation> annotationCaptor = ArgumentCaptor.forClass(Annotation.class);
verify(annotationPersister).persistAnnotation(
eq(ModelSnapshot.annotationDocumentId(modelSnapshot)), annotationCaptor.capture(), any());
Annotation annotation = annotationCaptor.getValue();
Annotation expectedAnnotation =
new Annotation.Builder()
.setAnnotation("Job model snapshot with id [a_snapshot_id] stored")
.setCreateTime(Date.from(CURRENT_TIME))
.setCreateUsername(XPackUser.NAME)
.setTimestamp(Date.from(Instant.ofEpochMilli(1000_000_000)))
.setEndTimestamp(Date.from(Instant.ofEpochMilli(1000_000_000)))
.setJobId(JOB_ID)
.setModifiedTime(Date.from(CURRENT_TIME))
.setModifiedUsername(XPackUser.NAME)
.setType("annotation")
.build();
assertThat(annotation, is(equalTo(expectedAnnotation)));
UpdateJobAction.Request expectedJobUpdateRequest = UpdateJobAction.Request.internal(JOB_ID,
new JobUpdate.Builder(JOB_ID).setModelSnapshotId("a_snapshot_id").build());
verify(client).execute(same(UpdateJobAction.INSTANCE), eq(expectedJobUpdateRequest), any());
}
public void testProcessResult_quantiles_givenRenormalizationIsEnabled() {
AutodetectResult result = mock(AutodetectResult.class);
Quantiles quantiles = mock(Quantiles.class);
when(result.getQuantiles()).thenReturn(quantiles);
when(renormalizer.isEnabled()).thenReturn(true);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).persistQuantiles(eq(quantiles), any());
verify(bulkBuilder).executeRequest();
verify(persister).commitResultWrites(JOB_ID);
verify(renormalizer).isEnabled();
verify(renormalizer).renormalize(quantiles);
}
public void testProcessResult_quantiles_givenRenormalizationIsDisabled() {
AutodetectResult result = mock(AutodetectResult.class);
Quantiles quantiles = mock(Quantiles.class);
when(result.getQuantiles()).thenReturn(quantiles);
when(renormalizer.isEnabled()).thenReturn(false);
processorUnderTest.setDeleteInterimRequired(false);
processorUnderTest.processResult(result);
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).persistQuantiles(eq(quantiles), any());
verify(bulkBuilder).executeRequest();
verify(renormalizer).isEnabled();
}
public void testAwaitCompletion() throws TimeoutException {
AutodetectResult autodetectResult = mock(AutodetectResult.class);
when(process.readAutodetectResults()).thenReturn(Arrays.asList(autodetectResult).iterator());
processorUnderTest.process();
processorUnderTest.awaitCompletion();
assertThat(processorUnderTest.completionLatch.getCount(), is(equalTo(0L)));
assertThat(processorUnderTest.updateModelSnapshotSemaphore.availablePermits(), is(equalTo(1)));
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).commitResultWrites(JOB_ID);
verify(persister).commitStateWrites(JOB_ID);
verify(renormalizer).waitUntilIdle();
}
public void testPersisterThrowingDoesntBlockProcessing() {
AutodetectResult autodetectResult = mock(AutodetectResult.class);
ModelSnapshot modelSnapshot = mock(ModelSnapshot.class);
when(autodetectResult.getModelSnapshot()).thenReturn(modelSnapshot);
when(process.isProcessAlive()).thenReturn(true);
when(process.isProcessAliveAfterWaiting()).thenReturn(true);
when(process.readAutodetectResults()).thenReturn(Arrays.asList(autodetectResult, autodetectResult).iterator());
doThrow(new ElasticsearchException("this test throws")).when(persister).persistModelSnapshot(any(), any(), any());
processorUnderTest.process();
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister, times(2)).persistModelSnapshot(any(), eq(WriteRequest.RefreshPolicy.IMMEDIATE), any());
}
public void testParsingErrorSetsFailed() throws Exception {
@SuppressWarnings("unchecked")
Iterator<AutodetectResult> iterator = mock(Iterator.class);
when(iterator.hasNext()).thenThrow(new ElasticsearchParseException("this test throws"));
when(process.readAutodetectResults()).thenReturn(iterator);
assertFalse(processorUnderTest.isFailed());
processorUnderTest.process();
assertTrue(processorUnderTest.isFailed());
// Wait for flush should return immediately
FlushAcknowledgement flushAcknowledgement =
processorUnderTest.waitForFlushAcknowledgement(JOB_ID, Duration.of(300, ChronoUnit.SECONDS));
assertThat(flushAcknowledgement, is(nullValue()));
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
}
public void testKill() throws TimeoutException {
AutodetectResult autodetectResult = mock(AutodetectResult.class);
when(process.readAutodetectResults()).thenReturn(Arrays.asList(autodetectResult).iterator());
processorUnderTest.setProcessKilled();
processorUnderTest.process();
processorUnderTest.awaitCompletion();
assertThat(processorUnderTest.completionLatch.getCount(), is(equalTo(0L)));
assertThat(processorUnderTest.updateModelSnapshotSemaphore.availablePermits(), is(equalTo(1)));
verify(persister).bulkPersisterBuilder(eq(JOB_ID), any());
verify(persister).commitResultWrites(JOB_ID);
verify(persister).commitStateWrites(JOB_ID);
verify(renormalizer, never()).renormalize(any());
verify(renormalizer).shutdown();
verify(renormalizer).waitUntilIdle();
verify(flushListener).clear();
}
}
|
3e12b91f5304e422072d1fd9c49488ca765c7d46 | 4,339 | java | Java | main/plugins/org.talend.designer.esb.components.ws.consumer/src/main/java/org/talend/designer/esb/webservice/ui/AbstractTableViewPart.java | coheigea/tesb-studio-se | 1c4c0edab09e7317cbcc7d50fa16962cc6f60125 | [
"Apache-2.0"
] | 22 | 2015-02-03T22:52:51.000Z | 2021-02-15T17:25:20.000Z | main/plugins/org.talend.designer.esb.components.ws.consumer/src/main/java/org/talend/designer/esb/webservice/ui/AbstractTableViewPart.java | coheigea/tesb-studio-se | 1c4c0edab09e7317cbcc7d50fa16962cc6f60125 | [
"Apache-2.0"
] | 209 | 2015-03-24T06:29:46.000Z | 2022-03-29T06:03:53.000Z | main/plugins/org.talend.designer.esb.components.ws.consumer/src/main/java/org/talend/designer/esb/webservice/ui/AbstractTableViewPart.java | coheigea/tesb-studio-se | 1c4c0edab09e7317cbcc7d50fa16962cc6f60125 | [
"Apache-2.0"
] | 73 | 2015-02-15T09:39:12.000Z | 2022-03-18T10:50:19.000Z | 34.712 | 111 | 0.77322 | 7,897 | package org.talend.designer.esb.webservice.ui;
import java.util.EventListener;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.talend.commons.ui.swt.advanced.dataeditor.AbstractDataTableEditorView;
import org.talend.commons.ui.swt.extended.table.ExtendedTableModel;
import org.talend.commons.ui.swt.tableviewer.TableViewerCreator;
import org.talend.commons.ui.swt.tableviewer.TableViewerCreatorColumn;
import org.talend.commons.utils.data.bean.IBeanPropertyAccessors;
public abstract class AbstractTableViewPart<T extends EventListener,U> extends AbstractWebServiceUIPart<T> {
protected DataTableEditorView tableView;
public AbstractTableViewPart(T eventListener) {
super(eventListener);
}
abstract String getLabelKey();
abstract ExtendedTableModel<U> getTableModel();
abstract String getItemLabel(U item);
abstract void itemSelected(U item);
@Override
@SuppressWarnings("unchecked")
final Control createControl(Composite parent) {
tableView = createTableView(parent, getLabelKey(), getTableModel());
final Table table = tableView.getTable();
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableItem[] item = table.getSelection();
U currentPortName = (U) item[0].getData();
itemSelected(currentPortName);
}
});
return table;
}
protected class DataTableEditorView extends AbstractDataTableEditorView<U> {
private IBeanPropertyAccessors<U, String> accessors;
public DataTableEditorView(Composite parent, ExtendedTableModel<U> model,
IBeanPropertyAccessors<U, String> accessors) {
super(parent, SWT.NONE, model, false, true, false, false);
this.accessors = accessors;
initGraphicComponents();
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.minimumHeight = 150;
this.getMainComposite().setLayoutData(gridData);
GridLayout layout = (GridLayout) this.getMainComposite().getLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
}
protected void setTableViewerCreatorOptions(TableViewerCreator<U> newTableViewerCreator) {
super.setTableViewerCreatorOptions(newTableViewerCreator);
newTableViewerCreator.setHeaderVisible(false);
newTableViewerCreator.setVerticalScroll(true);
newTableViewerCreator.setReadOnly(true);
}
protected void createColumns(TableViewerCreator<U> tableViewerCreator, Table table) {
TableViewerCreatorColumn<U, String> rowColumn = new TableViewerCreatorColumn<U, String>(tableViewerCreator);
rowColumn.setBeanPropertyAccessors(accessors);
rowColumn.setWeight(60);
rowColumn.setModifiable(true);
rowColumn.setMinimumWidth(60);
rowColumn.setCellEditor(new TextCellEditor(tableViewerCreator.getTable()));
}
};
/**
* Creates the table view with giving i18n titleKey, paramList, and accessor
* to String. The parent Composite need to be grid layout.
*/
private DataTableEditorView createTableView(Composite parent, String titleKey, ExtendedTableModel<U> model) {
Label label = new Label(parent, SWT.NONE);
label.setText(Messages.getString(titleKey));
label.setLayoutData(new GridData(SWT.NONE, SWT.TOP, false, false));
DataTableEditorView view = new DataTableEditorView(parent, model, createAccessor());
int horizontalSpan = ((GridLayout) parent.getLayout()).numColumns - 1;
view.getMainComposite().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, horizontalSpan, 1));
return view;
}
private IBeanPropertyAccessors<U, String> createAccessor() {
return new IBeanPropertyAccessors<U, String>() {
@Override
public String get(U bean) {
return getItemLabel(bean);
}
@Override
public void set(U bean, String value) {
}
};
}
protected boolean selectFirstElement() {
int itemCount = tableView.getTable().getItemCount();
if(itemCount < 1) {
return false;
}
tableView.getTable().select(0);
return true;
}
}
|
3e12b9b1ca6b8cae3cc479c14d137a2036148633 | 2,271 | java | Java | src/main/java/org/irlab/model/services/TipoServiceImpl.java | lauracoya1/ADSI-GRUPOB | 2aa4449a04b7ab913f24c09e826b516a1924a300 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/irlab/model/services/TipoServiceImpl.java | lauracoya1/ADSI-GRUPOB | 2aa4449a04b7ab913f24c09e826b516a1924a300 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/irlab/model/services/TipoServiceImpl.java | lauracoya1/ADSI-GRUPOB | 2aa4449a04b7ab913f24c09e826b516a1924a300 | [
"Apache-2.0"
] | null | null | null | 26.406977 | 105 | 0.581242 | 7,898 | package org.irlab.model.services;
import java.util.List;
import com.google.common.base.Preconditions;
import org.irlab.common.AppEntityManagerFactory;
import jakarta.persistence.EntityManager;
import javax.annotation.Nonnull;
import org.irlab.model.entities.Tipo;
import org.irlab.model.daos.TipoDao;
import org.irlab.model.exceptions.TipoNotFoundException;
public class TipoServiceImpl implements TipoService {
@Override
public boolean exists(@Nonnull String nombre) {
Preconditions.checkNotNull(nombre, "Nombre cannot be null");
if (nombre.equals("")) {
return false;
}
EntityManager em = AppEntityManagerFactory.getInstance().createEntityManager();
try {
boolean exists = TipoDao
.findByNombre(em, nombre)
.map(t -> {
return true;
}).orElseThrow(() -> new TipoNotFoundException(String.format("with nombre %s", nombre)));
return exists;
} catch (TipoNotFoundException e) {
return false;
} catch ( Exception e ) {
throw e;
} finally {
em.close();
}
}
@Override
public List<Tipo> listAllTipos() {
EntityManager em = AppEntityManagerFactory.getInstance().createEntityManager();
try {
List<Tipo> tiposList = TipoDao.getAllTipos(em);
em.getTransaction().begin();
em.getTransaction().commit();
return tiposList;
} catch (Exception e) {
em.getTransaction().rollback();
throw e;
} finally {
em.close();
}
}
@Override
public void insertTipo(@Nonnull Tipo tipo) {
Preconditions.checkNotNull(tipo, "Tipo cannot be null");
if (exists(tipo.getNombre())){
System.out.println("Tipo already present");
return;
}
EntityManager em = AppEntityManagerFactory.getInstance().createEntityManager();
try {
em.getTransaction().begin();
TipoDao.update(em, tipo);
em.getTransaction().commit();
} catch (Exception e) {
throw e;
} finally {
em.close();
}
}
}
|
3e12b9e81339a448ef694ebdfa79c65dee527233 | 2,361 | java | Java | src/test/java/flowerstore/FlowerTest.java | alinamuliak/flowerStore | 2efca13b0f469a177750f87b0748e13db938fd39 | [
"MIT"
] | null | null | null | src/test/java/flowerstore/FlowerTest.java | alinamuliak/flowerStore | 2efca13b0f469a177750f87b0748e13db938fd39 | [
"MIT"
] | null | null | null | src/test/java/flowerstore/FlowerTest.java | alinamuliak/flowerStore | 2efca13b0f469a177750f87b0748e13db938fd39 | [
"MIT"
] | null | null | null | 29.148148 | 86 | 0.60864 | 7,899 | package flowerstore;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FlowerTest {
private Flower chamomile;
private Flower rose;
private Flower tulip;
@BeforeEach
void setUp() {
this.chamomile = new Flower(10, 15, new int[]{0, 1, 2}, FlowerType.CHAMOMILE);
this.rose = new Flower(5, 8, new int[]{1, 1, 1}, FlowerType.ROSE);
this.tulip = new Flower(7, 10, new int[]{2, 1, 3}, FlowerType.TULIP);
}
//
@Test
void getPrice() {
assertEquals(10, chamomile.getPrice());
assertEquals(5, rose.getPrice());
assertEquals(7, tulip.getPrice());
}
@Test
void setPrice() {
chamomile.setPrice(20);
assertEquals(20, chamomile.getPrice());
rose.setPrice(10);
assertEquals(10, rose.getPrice());
}
@Test
void getSepalLength() {
assertEquals(15, chamomile.getSepalLength());
assertEquals(8, rose.getSepalLength());
assertEquals(10, tulip.getSepalLength());
}
@Test
void setSepalLength() {
tulip.setSepalLength(15);
assertEquals(15, chamomile.getSepalLength());
rose.setSepalLength(5);
assertEquals(5, rose.getSepalLength());
}
@Test
void getColor() {
assertArrayEquals(new int[]{0, 1, 2}, chamomile.getColor());
assertArrayEquals(new int[]{1, 1, 1}, rose.getColor());
assertArrayEquals(new int[]{2, 1, 3}, tulip.getColor());
}
@Test
void setColor() {
tulip.setColor(new int[]{5, 4, 3});
assertArrayEquals(new int[]{5, 4, 3}, tulip.getColor());
chamomile.setColor(new int[]{7, 7, 7});
assertArrayEquals(new int[]{7, 7, 7}, chamomile.getColor());
int[] color = new int[] {1, 1, 0};
rose.setColor(color);
color[0] = 5;
assertArrayEquals(new int[] {1, 1, 0}, rose.getColor());
}
@Test
void getFlowerType() {
assertEquals(FlowerType.CHAMOMILE, chamomile.getFlowerType());
assertEquals(FlowerType.ROSE, rose.getFlowerType());
assertEquals(FlowerType.TULIP, tulip.getFlowerType());
}
@Test
void setFlowerType() {
chamomile.setFlowerType(FlowerType.ROSE);
assertEquals(FlowerType.ROSE, chamomile.getFlowerType());
}
} |
3e12ba30a3960c624110d921dc1d11f88179ad82 | 33,330 | java | Java | android-31/src/com/android/ims/rcs/uce/request/UceRequestManager.java | Pixelated-Project/aosp-android-jar | 72ae25d4fc6414e071fc1f52dd78080b84d524f8 | [
"MIT"
] | 93 | 2020-10-11T04:37:16.000Z | 2022-03-24T13:18:49.000Z | android-31/src/com/android/ims/rcs/uce/request/UceRequestManager.java | huangjxdev/aosp-android-jar | e22b61576b05ff7483180cb4d245921d66c26ee4 | [
"MIT"
] | 3 | 2020-10-11T04:27:44.000Z | 2022-01-19T01:31:52.000Z | android-31/src/com/android/ims/rcs/uce/request/UceRequestManager.java | huangjxdev/aosp-android-jar | e22b61576b05ff7483180cb4d245921d66c26ee4 | [
"MIT"
] | 10 | 2020-11-23T02:41:58.000Z | 2022-03-06T00:56:52.000Z | 40.156627 | 100 | 0.650075 | 7,900 | /*
* Copyright (C) 2020 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.android.ims.rcs.uce.request;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.ims.RcsContactUceCapability;
import android.telephony.ims.RcsContactUceCapability.CapabilityMechanism;
import android.telephony.ims.RcsUceAdapter;
import android.telephony.ims.aidl.IOptionsRequestCallback;
import android.telephony.ims.aidl.IRcsUceControllerCallback;
import android.text.TextUtils;
import android.util.Log;
import com.android.ims.rcs.uce.UceController;
import com.android.ims.rcs.uce.UceController.UceControllerCallback;
import com.android.ims.rcs.uce.UceDeviceState;
import com.android.ims.rcs.uce.UceDeviceState.DeviceStateResult;
import com.android.ims.rcs.uce.eab.EabCapabilityResult;
import com.android.ims.rcs.uce.options.OptionsController;
import com.android.ims.rcs.uce.presence.subscribe.SubscribeController;
import com.android.ims.rcs.uce.request.UceRequest.UceRequestType;
import com.android.ims.rcs.uce.request.UceRequestCoordinator.UceRequestUpdate;
import com.android.ims.rcs.uce.util.UceUtils;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.os.SomeArgs;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Managers the capabilities requests and the availability requests from UceController.
*/
public class UceRequestManager {
private static final String LOG_TAG = UceUtils.getLogPrefix() + "UceRequestManager";
/**
* Testing interface used to mock UceUtils in testing.
*/
@VisibleForTesting
public interface UceUtilsProxy {
/**
* The interface for {@link UceUtils#isPresenceCapExchangeEnabled(Context, int)} used for
* testing.
*/
boolean isPresenceCapExchangeEnabled(Context context, int subId);
/**
* The interface for {@link UceUtils#isPresenceSupported(Context, int)} used for testing.
*/
boolean isPresenceSupported(Context context, int subId);
/**
* The interface for {@link UceUtils#isSipOptionsSupported(Context, int)} used for testing.
*/
boolean isSipOptionsSupported(Context context, int subId);
/**
* @return true when the Presence group subscribe is enabled.
*/
boolean isPresenceGroupSubscribeEnabled(Context context, int subId);
/**
* Retrieve the maximum number of contacts that can be included in a request.
*/
int getRclMaxNumberEntries(int subId);
/**
* @return true if the given phone number is blocked by the network.
*/
boolean isNumberBlocked(Context context, String phoneNumber);
}
private static UceUtilsProxy sUceUtilsProxy = new UceUtilsProxy() {
@Override
public boolean isPresenceCapExchangeEnabled(Context context, int subId) {
return UceUtils.isPresenceCapExchangeEnabled(context, subId);
}
@Override
public boolean isPresenceSupported(Context context, int subId) {
return UceUtils.isPresenceSupported(context, subId);
}
@Override
public boolean isSipOptionsSupported(Context context, int subId) {
return UceUtils.isSipOptionsSupported(context, subId);
}
@Override
public boolean isPresenceGroupSubscribeEnabled(Context context, int subId) {
return UceUtils.isPresenceGroupSubscribeEnabled(context, subId);
}
@Override
public int getRclMaxNumberEntries(int subId) {
return UceUtils.getRclMaxNumberEntries(subId);
}
@Override
public boolean isNumberBlocked(Context context, String phoneNumber) {
return UceUtils.isNumberBlocked(context, phoneNumber);
}
};
@VisibleForTesting
public void setsUceUtilsProxy(UceUtilsProxy uceUtilsProxy) {
sUceUtilsProxy = uceUtilsProxy;
}
/**
* The callback interface to receive the request and the result from the UceRequest.
*/
public interface RequestManagerCallback {
/**
* Notify sending the UceRequest
*/
void notifySendingRequest(long coordinator, long taskId, long delayTimeMs);
/**
* Retrieve the contact capabilities from the cache.
*/
List<EabCapabilityResult> getCapabilitiesFromCache(List<Uri> uriList);
/**
* Retrieve the contact availability from the cache.
*/
EabCapabilityResult getAvailabilityFromCache(Uri uri);
/**
* Store the given contact capabilities to the cache.
*/
void saveCapabilities(List<RcsContactUceCapability> contactCapabilities);
/**
* Retrieve the device's capabilities.
*/
RcsContactUceCapability getDeviceCapabilities(@CapabilityMechanism int capMechanism);
/**
* Get the device state to check whether the device is disallowed by the network or not.
*/
DeviceStateResult getDeviceState();
/**
* Refresh the device state. It is called when receive the UCE request response.
*/
void refreshDeviceState(int sipCode, String reason);
/**
* Notify that the UceRequest associated with the given taskId encounters error.
*/
void notifyRequestError(long requestCoordinatorId, long taskId);
/**
* Notify that the UceRequest received the onCommandError callback from the ImsService.
*/
void notifyCommandError(long requestCoordinatorId, long taskId);
/**
* Notify that the UceRequest received the onNetworkResponse callback from the ImsService.
*/
void notifyNetworkResponse(long requestCoordinatorId, long taskId);
/**
* Notify that the UceRequest received the onTerminated callback from the ImsService.
*/
void notifyTerminated(long requestCoordinatorId, long taskId);
/**
* Notify that some contacts are not RCS anymore. It will updated the cached capabilities
* and trigger the callback IRcsUceControllerCallback#onCapabilitiesReceived
*/
void notifyResourceTerminated(long requestCoordinatorId, long taskId);
/**
* Notify that the capabilities updates. It will update the cached and trigger the callback
* IRcsUceControllerCallback#onCapabilitiesReceived
*/
void notifyCapabilitiesUpdated(long requestCoordinatorId, long taskId);
/**
* Notify that some of the request capabilities can be retrieved from the cached.
*/
void notifyCachedCapabilitiesUpdated(long requestCoordinatorId, long taskId);
/**
* Notify that all the requested capabilities can be retrieved from the cache. It does not
* need to request capabilities from the network.
*/
void notifyNoNeedRequestFromNetwork(long requestCoordinatorId, long taskId);
/**
* Notify that the remote options request is done. This is sent by RemoteOptionsRequest and
* it will notify the RemoteOptionsCoordinator to handle it.
*/
void notifyRemoteRequestDone(long requestCoordinatorId, long taskId);
/**
* Set the timer for the request timeout. It will cancel the request when the time is up.
*/
void setRequestTimeoutTimer(long requestCoordinatorId, long taskId, long timeoutAfterMs);
/**
* Remove the timeout timer of the capabilities request.
*/
void removeRequestTimeoutTimer(long taskId);
/**
* Notify that the UceRequest has finished. This is sent by UceRequestCoordinator.
*/
void notifyUceRequestFinished(long requestCoordinatorId, long taskId);
/**
* Notify that the RequestCoordinator has finished. This is sent by UceRequestCoordinator
* to remove the coordinator from the UceRequestRepository.
*/
void notifyRequestCoordinatorFinished(long requestCoordinatorId);
}
private RequestManagerCallback mRequestMgrCallback = new RequestManagerCallback() {
@Override
public void notifySendingRequest(long coordinatorId, long taskId, long delayTimeMs) {
mHandler.sendRequestMessage(coordinatorId, taskId, delayTimeMs);
}
@Override
public List<EabCapabilityResult> getCapabilitiesFromCache(List<Uri> uriList) {
return mControllerCallback.getCapabilitiesFromCache(uriList);
}
@Override
public EabCapabilityResult getAvailabilityFromCache(Uri uri) {
return mControllerCallback.getAvailabilityFromCache(uri);
}
@Override
public void saveCapabilities(List<RcsContactUceCapability> contactCapabilities) {
mControllerCallback.saveCapabilities(contactCapabilities);
}
@Override
public RcsContactUceCapability getDeviceCapabilities(@CapabilityMechanism int mechanism) {
return mControllerCallback.getDeviceCapabilities(mechanism);
}
@Override
public DeviceStateResult getDeviceState() {
return mControllerCallback.getDeviceState();
}
@Override
public void refreshDeviceState(int sipCode, String reason) {
mControllerCallback.refreshDeviceState(sipCode, reason,
UceController.REQUEST_TYPE_CAPABILITY);
}
@Override
public void notifyRequestError(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_ERROR);
}
@Override
public void notifyCommandError(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_COMMAND_ERROR);
}
@Override
public void notifyNetworkResponse(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_NETWORK_RESPONSE);
}
@Override
public void notifyTerminated(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_TERMINATED);
}
@Override
public void notifyResourceTerminated(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_RESOURCE_TERMINATED);
}
@Override
public void notifyCapabilitiesUpdated(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_CAPABILITY_UPDATE);
}
@Override
public void notifyCachedCapabilitiesUpdated(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_CACHED_CAPABILITY_UPDATE);
}
@Override
public void notifyNoNeedRequestFromNetwork(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_NO_NEED_REQUEST_FROM_NETWORK);
}
@Override
public void notifyRemoteRequestDone(long requestCoordinatorId, long taskId) {
mHandler.sendRequestUpdatedMessage(requestCoordinatorId, taskId,
UceRequestCoordinator.REQUEST_UPDATE_REMOTE_REQUEST_DONE);
}
@Override
public void setRequestTimeoutTimer(long coordinatorId, long taskId, long timeoutAfterMs) {
mHandler.sendRequestTimeoutTimerMessage(coordinatorId, taskId, timeoutAfterMs);
}
@Override
public void removeRequestTimeoutTimer(long taskId) {
mHandler.removeRequestTimeoutTimer(taskId);
}
@Override
public void notifyUceRequestFinished(long requestCoordinatorId, long taskId) {
mHandler.sendRequestFinishedMessage(requestCoordinatorId, taskId);
}
@Override
public void notifyRequestCoordinatorFinished(long requestCoordinatorId) {
mHandler.sendRequestCoordinatorFinishedMessage(requestCoordinatorId);
}
};
private final int mSubId;
private final Context mContext;
private final UceRequestHandler mHandler;
private final UceRequestRepository mRequestRepository;
private volatile boolean mIsDestroyed;
private OptionsController mOptionsCtrl;
private SubscribeController mSubscribeCtrl;
private UceControllerCallback mControllerCallback;
public UceRequestManager(Context context, int subId, Looper looper, UceControllerCallback c) {
mSubId = subId;
mContext = context;
mControllerCallback = c;
mHandler = new UceRequestHandler(this, looper);
mRequestRepository = new UceRequestRepository(subId, mRequestMgrCallback);
logi("create");
}
@VisibleForTesting
public UceRequestManager(Context context, int subId, Looper looper, UceControllerCallback c,
UceRequestRepository requestRepository) {
mSubId = subId;
mContext = context;
mControllerCallback = c;
mHandler = new UceRequestHandler(this, looper);
mRequestRepository = requestRepository;
}
/**
* Set the OptionsController for requestiong capabilities by OPTIONS mechanism.
*/
public void setOptionsController(OptionsController controller) {
mOptionsCtrl = controller;
}
/**
* Set the SubscribeController for requesting capabilities by Subscribe mechanism.
*/
public void setSubscribeController(SubscribeController controller) {
mSubscribeCtrl = controller;
}
/**
* Notify that the request manager instance is destroyed.
*/
public void onDestroy() {
logi("onDestroy");
mIsDestroyed = true;
mHandler.onDestroy();
mRequestRepository.onDestroy();
}
/**
* Send a new capability request. It is called by UceController.
*/
public void sendCapabilityRequest(List<Uri> uriList, boolean skipFromCache,
IRcsUceControllerCallback callback) throws RemoteException {
if (mIsDestroyed) {
callback.onError(RcsUceAdapter.ERROR_GENERIC_FAILURE, 0L);
return;
}
sendRequestInternal(UceRequest.REQUEST_TYPE_CAPABILITY, uriList, skipFromCache, callback);
}
/**
* Send a new availability request. It is called by UceController.
*/
public void sendAvailabilityRequest(Uri uri, IRcsUceControllerCallback callback)
throws RemoteException {
if (mIsDestroyed) {
callback.onError(RcsUceAdapter.ERROR_GENERIC_FAILURE, 0L);
return;
}
sendRequestInternal(UceRequest.REQUEST_TYPE_AVAILABILITY,
Collections.singletonList(uri), false /* skipFromCache */, callback);
}
private void sendRequestInternal(@UceRequestType int type, List<Uri> uriList,
boolean skipFromCache, IRcsUceControllerCallback callback) throws RemoteException {
UceRequestCoordinator requestCoordinator = null;
if (sUceUtilsProxy.isPresenceCapExchangeEnabled(mContext, mSubId) &&
sUceUtilsProxy.isPresenceSupported(mContext, mSubId)) {
requestCoordinator = createSubscribeRequestCoordinator(type, uriList, skipFromCache,
callback);
} else if (sUceUtilsProxy.isSipOptionsSupported(mContext, mSubId)) {
requestCoordinator = createOptionsRequestCoordinator(type, uriList, callback);
}
if (requestCoordinator == null) {
logw("sendRequestInternal: Neither Presence nor OPTIONS are supported");
callback.onError(RcsUceAdapter.ERROR_NOT_ENABLED, 0L);
return;
}
StringBuilder builder = new StringBuilder("sendRequestInternal: ");
builder.append("requestType=").append(type)
.append(", requestCoordinatorId=").append(requestCoordinator.getCoordinatorId())
.append(", taskId={")
.append(requestCoordinator.getActivatedRequestTaskIds().stream()
.map(Object::toString).collect(Collectors.joining(","))).append("}");
logd(builder.toString());
// Add this RequestCoordinator to the UceRequestRepository.
addRequestCoordinator(requestCoordinator);
}
private UceRequestCoordinator createSubscribeRequestCoordinator(final @UceRequestType int type,
final List<Uri> uriList, boolean skipFromCache, IRcsUceControllerCallback callback) {
SubscribeRequestCoordinator.Builder builder;
if (!sUceUtilsProxy.isPresenceGroupSubscribeEnabled(mContext, mSubId)) {
// When the group subscribe is disabled, each contact is required to be encapsulated
// into individual UceRequest.
List<UceRequest> requestList = new ArrayList<>();
uriList.forEach(uri -> {
List<Uri> individualUri = Collections.singletonList(uri);
UceRequest request = createSubscribeRequest(type, individualUri, skipFromCache);
requestList.add(request);
});
builder = new SubscribeRequestCoordinator.Builder(mSubId, requestList,
mRequestMgrCallback);
builder.setCapabilitiesCallback(callback);
} else {
// Even when the group subscribe is supported by the network, the number of contacts in
// a UceRequest still cannot exceed the maximum.
List<UceRequest> requestList = new ArrayList<>();
final int rclMaxNumber = sUceUtilsProxy.getRclMaxNumberEntries(mSubId);
int numRequestCoordinators = uriList.size() / rclMaxNumber;
for (int count = 0; count < numRequestCoordinators; count++) {
List<Uri> subUriList = new ArrayList<>();
for (int index = 0; index < rclMaxNumber; index++) {
subUriList.add(uriList.get(count * rclMaxNumber + index));
}
requestList.add(createSubscribeRequest(type, subUriList, skipFromCache));
}
List<Uri> subUriList = new ArrayList<>();
for (int i = numRequestCoordinators * rclMaxNumber; i < uriList.size(); i++) {
subUriList.add(uriList.get(i));
}
requestList.add(createSubscribeRequest(type, subUriList, skipFromCache));
builder = new SubscribeRequestCoordinator.Builder(mSubId, requestList,
mRequestMgrCallback);
builder.setCapabilitiesCallback(callback);
}
return builder.build();
}
private UceRequestCoordinator createOptionsRequestCoordinator(@UceRequestType int type,
List<Uri> uriList, IRcsUceControllerCallback callback) {
OptionsRequestCoordinator.Builder builder;
List<UceRequest> requestList = new ArrayList<>();
uriList.forEach(uri -> {
List<Uri> individualUri = Collections.singletonList(uri);
UceRequest request = createOptionsRequest(type, individualUri, false);
requestList.add(request);
});
builder = new OptionsRequestCoordinator.Builder(mSubId, requestList, mRequestMgrCallback);
builder.setCapabilitiesCallback(callback);
return builder.build();
}
private CapabilityRequest createSubscribeRequest(int type, List<Uri> uriList,
boolean skipFromCache) {
CapabilityRequest request = new SubscribeRequest(mSubId, type, mRequestMgrCallback,
mSubscribeCtrl);
request.setContactUri(uriList);
request.setSkipGettingFromCache(skipFromCache);
return request;
}
private CapabilityRequest createOptionsRequest(int type, List<Uri> uriList,
boolean skipFromCache) {
CapabilityRequest request = new OptionsRequest(mSubId, type, mRequestMgrCallback,
mOptionsCtrl);
request.setContactUri(uriList);
request.setSkipGettingFromCache(skipFromCache);
return request;
}
/**
* Retrieve the device's capabilities. This request is from the ImsService to send the
* capabilities to the remote side.
*/
public void retrieveCapabilitiesForRemote(Uri contactUri, List<String> remoteCapabilities,
IOptionsRequestCallback requestCallback) {
RemoteOptionsRequest request = new RemoteOptionsRequest(mSubId, mRequestMgrCallback);
request.setContactUri(Collections.singletonList(contactUri));
request.setRemoteFeatureTags(remoteCapabilities);
// If the remote number is blocked, do not send capabilities back.
String number = getNumberFromUri(contactUri);
if (!TextUtils.isEmpty(number)) {
request.setIsRemoteNumberBlocked(sUceUtilsProxy.isNumberBlocked(mContext, number));
}
// Create the RemoteOptionsCoordinator instance
RemoteOptionsCoordinator.Builder CoordBuilder = new RemoteOptionsCoordinator.Builder(
mSubId, Collections.singletonList(request), mRequestMgrCallback);
CoordBuilder.setOptionsRequestCallback(requestCallback);
RemoteOptionsCoordinator requestCoordinator = CoordBuilder.build();
StringBuilder builder = new StringBuilder("retrieveCapabilitiesForRemote: ");
builder.append("requestCoordinatorId ").append(requestCoordinator.getCoordinatorId())
.append(", taskId={")
.append(requestCoordinator.getActivatedRequestTaskIds().stream()
.map(Object::toString).collect(Collectors.joining(","))).append("}");
logd(builder.toString());
// Add this RequestCoordinator to the UceRequestRepository.
addRequestCoordinator(requestCoordinator);
}
private static class UceRequestHandler extends Handler {
private static final int EVENT_EXECUTE_REQUEST = 1;
private static final int EVENT_REQUEST_UPDATED = 2;
private static final int EVENT_REQUEST_TIMEOUT = 3;
private static final int EVENT_REQUEST_FINISHED = 4;
private static final int EVENT_COORDINATOR_FINISHED = 5;
private final Map<Long, SomeArgs> mRequestTimeoutTimers;
private final WeakReference<UceRequestManager> mUceRequestMgrRef;
public UceRequestHandler(UceRequestManager requestManager, Looper looper) {
super(looper);
mRequestTimeoutTimers = new HashMap<>();
mUceRequestMgrRef = new WeakReference<>(requestManager);
}
/**
* Send the capabilities request message.
*/
public void sendRequestMessage(Long coordinatorId, Long taskId, long delayTimeMs) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = coordinatorId;
args.arg2 = taskId;
Message message = obtainMessage();
message.what = EVENT_EXECUTE_REQUEST;
message.obj = args;
sendMessageDelayed(message, delayTimeMs);
}
/**
* Send the Uce request updated message.
*/
public void sendRequestUpdatedMessage(Long coordinatorId, Long taskId,
@UceRequestUpdate int requestEvent) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = coordinatorId;
args.arg2 = taskId;
args.argi1 = requestEvent;
Message message = obtainMessage();
message.what = EVENT_REQUEST_UPDATED;
message.obj = args;
sendMessage(message);
}
/**
* Set the timeout timer to cancel the capabilities request.
*/
public void sendRequestTimeoutTimerMessage(Long coordId, Long taskId, Long timeoutAfterMs) {
synchronized (mRequestTimeoutTimers) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = coordId;
args.arg2 = taskId;
// Add the message object to the collection. It can be used to find this message
// when the request is completed and remove the timeout timer.
mRequestTimeoutTimers.put(taskId, args);
Message message = obtainMessage();
message.what = EVENT_REQUEST_TIMEOUT;
message.obj = args;
sendMessageDelayed(message, timeoutAfterMs);
}
}
/**
* Remove the timeout timer because the capabilities request is finished.
*/
public void removeRequestTimeoutTimer(Long taskId) {
synchronized (mRequestTimeoutTimers) {
SomeArgs args = mRequestTimeoutTimers.remove(taskId);
if (args == null) {
return;
}
Log.d(LOG_TAG, "removeRequestTimeoutTimer: taskId=" + taskId);
removeMessages(EVENT_REQUEST_TIMEOUT, args);
args.recycle();
}
}
public void sendRequestFinishedMessage(Long coordinatorId, Long taskId) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = coordinatorId;
args.arg2 = taskId;
Message message = obtainMessage();
message.what = EVENT_REQUEST_FINISHED;
message.obj = args;
sendMessage(message);
}
/**
* Finish the UceRequestCoordinator associated with the given id.
*/
public void sendRequestCoordinatorFinishedMessage(Long coordinatorId) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = coordinatorId;
Message message = obtainMessage();
message.what = EVENT_COORDINATOR_FINISHED;
message.obj = args;
sendMessage(message);
}
/**
* Remove all the messages from the handler
*/
public void onDestroy() {
removeCallbacksAndMessages(null);
// Recycle all the arguments in the mRequestTimeoutTimers
synchronized (mRequestTimeoutTimers) {
mRequestTimeoutTimers.forEach((taskId, args) -> {
try {
args.recycle();
} catch (Exception e) {}
});
mRequestTimeoutTimers.clear();
}
}
@Override
public void handleMessage(Message msg) {
UceRequestManager requestManager = mUceRequestMgrRef.get();
if (requestManager == null) {
return;
}
SomeArgs args = (SomeArgs) msg.obj;
final Long coordinatorId = (Long) args.arg1;
final Long taskId = (Long) Optional.ofNullable(args.arg2).orElse(-1L);
final Integer requestEvent = Optional.of(args.argi1).orElse(-1);
args.recycle();
requestManager.logd("handleMessage: " + EVENT_DESCRIPTION.get(msg.what)
+ ", coordinatorId=" + coordinatorId + ", taskId=" + taskId);
switch (msg.what) {
case EVENT_EXECUTE_REQUEST: {
UceRequest request = requestManager.getUceRequest(taskId);
if (request == null) {
requestManager.logw("handleMessage: cannot find request, taskId=" + taskId);
return;
}
request.executeRequest();
break;
}
case EVENT_REQUEST_UPDATED: {
UceRequestCoordinator requestCoordinator =
requestManager.getRequestCoordinator(coordinatorId);
if (requestCoordinator == null) {
requestManager.logw("handleMessage: cannot find UceRequestCoordinator");
return;
}
requestCoordinator.onRequestUpdated(taskId, requestEvent);
break;
}
case EVENT_REQUEST_TIMEOUT: {
UceRequestCoordinator requestCoordinator =
requestManager.getRequestCoordinator(coordinatorId);
if (requestCoordinator == null) {
requestManager.logw("handleMessage: cannot find UceRequestCoordinator");
return;
}
// The timeout timer is triggered, remove this record from the collection.
synchronized (mRequestTimeoutTimers) {
mRequestTimeoutTimers.remove(taskId);
}
// Notify that the request is timeout.
requestCoordinator.onRequestUpdated(taskId,
UceRequestCoordinator.REQUEST_UPDATE_TIMEOUT);
break;
}
case EVENT_REQUEST_FINISHED: {
// Notify the repository that the request is finished.
requestManager.notifyRepositoryRequestFinished(taskId);
break;
}
case EVENT_COORDINATOR_FINISHED: {
UceRequestCoordinator requestCoordinator =
requestManager.removeRequestCoordinator(coordinatorId);
if (requestCoordinator != null) {
requestCoordinator.onFinish();
}
break;
}
default: {
break;
}
}
}
private static Map<Integer, String> EVENT_DESCRIPTION = new HashMap<>();
static {
EVENT_DESCRIPTION.put(EVENT_EXECUTE_REQUEST, "EXECUTE_REQUEST");
EVENT_DESCRIPTION.put(EVENT_REQUEST_UPDATED, "REQUEST_UPDATE");
EVENT_DESCRIPTION.put(EVENT_REQUEST_TIMEOUT, "REQUEST_TIMEOUT");
EVENT_DESCRIPTION.put(EVENT_REQUEST_FINISHED, "REQUEST_FINISHED");
EVENT_DESCRIPTION.put(EVENT_COORDINATOR_FINISHED, "REMOVE_COORDINATOR");
}
}
private void addRequestCoordinator(UceRequestCoordinator coordinator) {
mRequestRepository.addRequestCoordinator(coordinator);
}
private UceRequestCoordinator removeRequestCoordinator(Long coordinatorId) {
return mRequestRepository.removeRequestCoordinator(coordinatorId);
}
private UceRequestCoordinator getRequestCoordinator(Long coordinatorId) {
return mRequestRepository.getRequestCoordinator(coordinatorId);
}
private UceRequest getUceRequest(Long taskId) {
return mRequestRepository.getUceRequest(taskId);
}
private void notifyRepositoryRequestFinished(Long taskId) {
mRequestRepository.notifyRequestFinished(taskId);
}
@VisibleForTesting
public UceRequestHandler getUceRequestHandler() {
return mHandler;
}
@VisibleForTesting
public RequestManagerCallback getRequestManagerCallback() {
return mRequestMgrCallback;
}
private void logi(String log) {
Log.i(LOG_TAG, getLogPrefix().append(log).toString());
}
private void logd(String log) {
Log.d(LOG_TAG, getLogPrefix().append(log).toString());
}
private void logw(String log) {
Log.w(LOG_TAG, getLogPrefix().append(log).toString());
}
private StringBuilder getLogPrefix() {
StringBuilder builder = new StringBuilder("[");
builder.append(mSubId);
builder.append("] ");
return builder;
}
private String getNumberFromUri(Uri uri) {
if (uri == null) return null;
String number = uri.getSchemeSpecificPart();
String[] numberParts = number.split("[@;:]");
if (numberParts.length == 0) {
return null;
}
return numberParts[0];
}
}
|
3e12bb220b6a8095fc1e9d65551640687d2b7850 | 811 | java | Java | Computers/src/Showcase.java | vieck/Udemy-Java-Square-One | b03087c058d8db68e54a9497058214cd37cef14e | [
"MIT"
] | null | null | null | Computers/src/Showcase.java | vieck/Udemy-Java-Square-One | b03087c058d8db68e54a9497058214cd37cef14e | [
"MIT"
] | null | null | null | Computers/src/Showcase.java | vieck/Udemy-Java-Square-One | b03087c058d8db68e54a9497058214cd37cef14e | [
"MIT"
] | null | null | null | 35.26087 | 90 | 0.618989 | 7,901 | /**
* Created by mvieck on 12/30/16.
*/
public class Showcase {
public static void main(String[] args) {
Desktop gamingComputer = new Desktop(
"GamesForDesktops",123456,660,true, true);
Desktop regularComputer = new Desktop(
"StandardDesktops",111111,550,true, false);
Desktop lowEndDesktop = new Desktop(
"LowEndDesktops",1000001,320,false, false);
Laptop updatedLaptop = new Laptop(
"NewLaptops",100000, 340, true, true, true);
Laptop oldLaptop = new Laptop("OutdatedCompany",2000002, 230, true, false, false);
gamingComputer.printSpecs();
regularComputer.printSpecs();
lowEndDesktop.printSpecs();
updatedLaptop.printSpecs();
oldLaptop.printSpecs();
}
}
|
3e12bb30e226c2743916503c3308ff5d93992fcc | 240 | java | Java | games/src/space-invader-clone/javasrc/src/graphics/Renderable.java | kamil-sita/xge-games-archive | 53177d377e100bb0244c17ed05e9278205f377aa | [
"MIT"
] | 1 | 2020-07-06T09:06:44.000Z | 2020-07-06T09:06:44.000Z | games/src/space-invader-clone/javasrc/src/graphics/Renderable.java | kamil-sita/xge-games-archive | 53177d377e100bb0244c17ed05e9278205f377aa | [
"MIT"
] | null | null | null | games/src/space-invader-clone/javasrc/src/graphics/Renderable.java | kamil-sita/xge-games-archive | 53177d377e100bb0244c17ed05e9278205f377aa | [
"MIT"
] | null | null | null | 21.818182 | 60 | 0.754167 | 7,902 | package graphics;
import java.awt.*;
public interface Renderable {
void setRotation(double rotation);
void render(Graphics2D graphics2D, boolean isDebugging);
boolean isRenderOnTop();
RenderPriority getRenderPriority();
}
|
3e12bb4467ec684d7990d379fc991c1a2d0f39a4 | 1,282 | java | Java | test/org/traccar/protocol/H02FrameDecoderTest.java | ksbhatt1107/TRACCAR | 227c9e4d087da882fbaad71cd67e26fd194864ee | [
"Apache-2.0"
] | null | null | null | test/org/traccar/protocol/H02FrameDecoderTest.java | ksbhatt1107/TRACCAR | 227c9e4d087da882fbaad71cd67e26fd194864ee | [
"Apache-2.0"
] | null | null | null | test/org/traccar/protocol/H02FrameDecoderTest.java | ksbhatt1107/TRACCAR | 227c9e4d087da882fbaad71cd67e26fd194864ee | [
"Apache-2.0"
] | null | null | null | 48.206897 | 280 | 0.807582 | 7,903 | package org.traccar.protocol;
import org.junit.Assert;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class H02FrameDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
H02FrameDecoder decoder = new H02FrameDecoder(0);
Assert.assertEquals(
binary("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"),
decoder.decode(null, null, binary("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b")));
Assert.assertEquals(
binary("2a48512c3335333538383036303031353536382c56312c3139333530352c412c3830392e303031302c532c333435342e383939372c572c302e30302c302e30302c3239313031332c65666666666266662c3030303264342c3030303030622c3030353338352c3030353261612c323523"),
decoder.decode(null, null, binary("2a48512c3335333538383036303031353536382c56312c3139333530352c412c3830392e303031302c532c333435342e383939372c572c302e30302c302e30302c3239313031332c65666666666266662c3030303264342c3030303030622c3030353338352c3030353261612c323523")));
Assert.assertEquals(
binary("24430025645511183817091319355128000465632432000100ffe7fbffff0000"),
decoder.decode(null, null, binary("24430025645511183817091319355128000465632432000100ffe7fbffff0000")));
}
}
|
3e12bbe444b14babaef4c4e1ef7ce9575e6bd173 | 2,680 | java | Java | src/main/java/free/lucifer/cvino/lowapi/Layer.java | DenisLAD/OpenVINO-C-Api-Java-Bridge | 5aed3b26736c66dbd140280b92f4a13a491f6769 | [
"MIT"
] | null | null | null | src/main/java/free/lucifer/cvino/lowapi/Layer.java | DenisLAD/OpenVINO-C-Api-Java-Bridge | 5aed3b26736c66dbd140280b92f4a13a491f6769 | [
"MIT"
] | null | null | null | src/main/java/free/lucifer/cvino/lowapi/Layer.java | DenisLAD/OpenVINO-C-Api-Java-Bridge | 5aed3b26736c66dbd140280b92f4a13a491f6769 | [
"MIT"
] | null | null | null | 30.804598 | 104 | 0.651493 | 7,904 | /*
* The MIT License
*
* Copyright 2021 Lucifer.
*
* 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 free.lucifer.cvino.lowapi;
import com.sun.jna.Pointer;
import free.lucifer.cvino.lowapi.enums.Layout;
import free.lucifer.cvino.lowapi.enums.Precision;
/**
*
* @author Lucifer
*/
abstract class Layer {
private final Pointer network;
private final String name;
protected Layout layout;
protected Precision precision;
private final int[] dimesnsions;
public Layer(Pointer network, String name, Layout layout, Precision precision, int[] dimesnsions) {
this.network = network;
this.name = name;
this.layout = layout;
this.precision = precision;
this.dimesnsions = dimesnsions;
}
public String getName() {
return name;
}
public Pointer getNetwork() {
return network;
}
public Layout getLayout() {
return layout;
}
public Precision getPrecision() {
return precision;
}
public int[] getDimesnsions() {
return dimesnsions;
}
public abstract void setLayout(Layout layout);
public abstract void setPrecision(Precision precision);
public static String toString(int[] dimesnsions) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < dimesnsions.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(dimesnsions[i]);
}
sb.append("]");
return sb.toString();
}
}
|
3e12bc051374c1bb4e7c2783b5812c54b90b29f7 | 275 | java | Java | src/com/wildsmith/material/list/ListRow.java | vivian8725118/MaterialDesignSupport | 8b276466dc9104d3dca38b7585739ddd3f6dc44d | [
"MIT"
] | null | null | null | src/com/wildsmith/material/list/ListRow.java | vivian8725118/MaterialDesignSupport | 8b276466dc9104d3dca38b7585739ddd3f6dc44d | [
"MIT"
] | null | null | null | src/com/wildsmith/material/list/ListRow.java | vivian8725118/MaterialDesignSupport | 8b276466dc9104d3dca38b7585739ddd3f6dc44d | [
"MIT"
] | null | null | null | 27.5 | 107 | 0.810909 | 7,905 | package com.wildsmith.material.list;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
public abstract class ListRow {
public abstract View getView(LayoutInflater inflater, View contentView, Context context, int position);
} |
3e12bc2d53b0ded369169e8fac52fe8681339798 | 7,534 | java | Java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/CodeSigning.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 1 | 2019-02-08T21:30:20.000Z | 2019-02-08T21:30:20.000Z | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/CodeSigning.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/CodeSigning.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 1 | 2021-09-24T08:30:03.000Z | 2021-09-24T08:30:03.000Z | 31.523013 | 147 | 0.635784 | 7,906 | /*
* Copyright 2013-2018 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>
* Describes the method to use when code signing a file.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CodeSigning implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The ID of the AWSSignerJob which was created to sign the file.
* </p>
*/
private String awsSignerJobId;
/**
* <p>
* Describes the code-signing job.
* </p>
*/
private StartSigningJobParameter startSigningJobParameter;
/**
* <p>
* A custom method for code signing a file.
* </p>
*/
private CustomCodeSigning customCodeSigning;
/**
* <p>
* The ID of the AWSSignerJob which was created to sign the file.
* </p>
*
* @param awsSignerJobId
* The ID of the AWSSignerJob which was created to sign the file.
*/
public void setAwsSignerJobId(String awsSignerJobId) {
this.awsSignerJobId = awsSignerJobId;
}
/**
* <p>
* The ID of the AWSSignerJob which was created to sign the file.
* </p>
*
* @return The ID of the AWSSignerJob which was created to sign the file.
*/
public String getAwsSignerJobId() {
return this.awsSignerJobId;
}
/**
* <p>
* The ID of the AWSSignerJob which was created to sign the file.
* </p>
*
* @param awsSignerJobId
* The ID of the AWSSignerJob which was created to sign the file.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CodeSigning withAwsSignerJobId(String awsSignerJobId) {
setAwsSignerJobId(awsSignerJobId);
return this;
}
/**
* <p>
* Describes the code-signing job.
* </p>
*
* @param startSigningJobParameter
* Describes the code-signing job.
*/
public void setStartSigningJobParameter(StartSigningJobParameter startSigningJobParameter) {
this.startSigningJobParameter = startSigningJobParameter;
}
/**
* <p>
* Describes the code-signing job.
* </p>
*
* @return Describes the code-signing job.
*/
public StartSigningJobParameter getStartSigningJobParameter() {
return this.startSigningJobParameter;
}
/**
* <p>
* Describes the code-signing job.
* </p>
*
* @param startSigningJobParameter
* Describes the code-signing job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CodeSigning withStartSigningJobParameter(StartSigningJobParameter startSigningJobParameter) {
setStartSigningJobParameter(startSigningJobParameter);
return this;
}
/**
* <p>
* A custom method for code signing a file.
* </p>
*
* @param customCodeSigning
* A custom method for code signing a file.
*/
public void setCustomCodeSigning(CustomCodeSigning customCodeSigning) {
this.customCodeSigning = customCodeSigning;
}
/**
* <p>
* A custom method for code signing a file.
* </p>
*
* @return A custom method for code signing a file.
*/
public CustomCodeSigning getCustomCodeSigning() {
return this.customCodeSigning;
}
/**
* <p>
* A custom method for code signing a file.
* </p>
*
* @param customCodeSigning
* A custom method for code signing a file.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CodeSigning withCustomCodeSigning(CustomCodeSigning customCodeSigning) {
setCustomCodeSigning(customCodeSigning);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAwsSignerJobId() != null)
sb.append("AwsSignerJobId: ").append(getAwsSignerJobId()).append(",");
if (getStartSigningJobParameter() != null)
sb.append("StartSigningJobParameter: ").append(getStartSigningJobParameter()).append(",");
if (getCustomCodeSigning() != null)
sb.append("CustomCodeSigning: ").append(getCustomCodeSigning());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CodeSigning == false)
return false;
CodeSigning other = (CodeSigning) obj;
if (other.getAwsSignerJobId() == null ^ this.getAwsSignerJobId() == null)
return false;
if (other.getAwsSignerJobId() != null && other.getAwsSignerJobId().equals(this.getAwsSignerJobId()) == false)
return false;
if (other.getStartSigningJobParameter() == null ^ this.getStartSigningJobParameter() == null)
return false;
if (other.getStartSigningJobParameter() != null && other.getStartSigningJobParameter().equals(this.getStartSigningJobParameter()) == false)
return false;
if (other.getCustomCodeSigning() == null ^ this.getCustomCodeSigning() == null)
return false;
if (other.getCustomCodeSigning() != null && other.getCustomCodeSigning().equals(this.getCustomCodeSigning()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAwsSignerJobId() == null) ? 0 : getAwsSignerJobId().hashCode());
hashCode = prime * hashCode + ((getStartSigningJobParameter() == null) ? 0 : getStartSigningJobParameter().hashCode());
hashCode = prime * hashCode + ((getCustomCodeSigning() == null) ? 0 : getCustomCodeSigning().hashCode());
return hashCode;
}
@Override
public CodeSigning clone() {
try {
return (CodeSigning) 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.CodeSigningMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
3e12bd93346b5c09ca992db8796d9ca107d63c4f | 12,156 | java | Java | src/msf/fc/failure/status/FcFailureStatusReadListScenario.java | multi-service-fabric/fabric-controller | 2b9788ff5e3a95ce1b82c4a80464592effe45e82 | [
"Apache-2.0"
] | 2 | 2018-03-19T03:45:16.000Z | 2018-09-10T01:45:42.000Z | src/msf/fc/failure/status/FcFailureStatusReadListScenario.java | multi-service-fabric/fabric-controller | 2b9788ff5e3a95ce1b82c4a80464592effe45e82 | [
"Apache-2.0"
] | null | null | null | src/msf/fc/failure/status/FcFailureStatusReadListScenario.java | multi-service-fabric/fabric-controller | 2b9788ff5e3a95ce1b82c4a80464592effe45e82 | [
"Apache-2.0"
] | 1 | 2020-04-02T01:18:38.000Z | 2020-04-02T01:18:38.000Z | 42.652632 | 120 | 0.743912 | 7,907 |
package msf.fc.failure.status;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.eclipse.jetty.http.HttpStatus;
import msf.fc.common.config.FcConfigManager;
import msf.fc.common.data.FcNode;
import msf.fc.db.dao.clusters.FcNodeDao;
import msf.fc.rest.ec.node.interfaces.breakout.data.entity.BreakoutIfEcEntity;
import msf.fc.rest.ec.node.interfaces.data.InterfaceReadListEcResponseBody;
import msf.fc.rest.ec.node.interfaces.data.entity.InterfacesEcEntity;
import msf.fc.rest.ec.node.interfaces.lag.data.entity.LagIfEcEntity;
import msf.fc.rest.ec.node.interfaces.physical.data.entity.PhysicalIfEcEntity;
import msf.fc.rest.ec.node.interfaces.vlan.data.VlanIfReadListEcResponseBody;
import msf.fc.rest.ec.node.interfaces.vlan.data.entity.VlanIfEcEntity;
import msf.fc.rest.ec.node.nodes.data.NodeReadListEcResponseBody;
import msf.fc.rest.ec.node.nodes.data.entity.NodeEcEntity;
import msf.mfcfc.common.constant.ClusterType;
import msf.mfcfc.common.constant.FailureStatus;
import msf.mfcfc.common.constant.InterfaceOperationStatus;
import msf.mfcfc.common.constant.InterfaceType;
import msf.mfcfc.common.constant.NodeStatus;
import msf.mfcfc.common.constant.OperationType;
import msf.mfcfc.common.constant.SynchronousType;
import msf.mfcfc.common.constant.SystemInterfaceType;
import msf.mfcfc.common.exception.MsfException;
import msf.mfcfc.common.log.MsfLogger;
import msf.mfcfc.core.scenario.RestResponseBase;
import msf.mfcfc.db.SessionWrapper;
import msf.mfcfc.failure.logicalif.data.entity.LogicalIfStatusIfEntity;
import msf.mfcfc.failure.status.data.FailureStatusReadListResponseBody;
import msf.mfcfc.failure.status.data.FailureStatusRequest;
import msf.mfcfc.failure.status.data.entity.FailureStatusClusterFailureEntity;
import msf.mfcfc.failure.status.data.entity.FailureStatusClusterUnitEntity;
import msf.mfcfc.failure.status.data.entity.FailureStatusIfFailureEntity;
import msf.mfcfc.failure.status.data.entity.FailureStatusNodeFailureEntity;
import msf.mfcfc.failure.status.data.entity.FailureStatusPhysicalUnitEntity;
import msf.mfcfc.failure.status.data.entity.FailureStatusSliceUnitEntity;
/**
* Implementation class for the failure information list acquisition.
*
* @author NTT
*
*/
public class FcFailureStatusReadListScenario extends FcAbstractFailureStatusScenarioBase<FailureStatusRequest> {
private static final MsfLogger logger = MsfLogger.getInstance(FcFailureStatusReadListScenario.class);
/**
* Constructor.
*
* <p>
* Set the "operation type" and "system interface type" as arguments
* </p>
*
* @param operationType
* Operation type
* @param systemInterfaceType
* System interface type
*
*/
public FcFailureStatusReadListScenario(OperationType operationType, SystemInterfaceType systemInterfaceType) {
this.operationType = operationType;
this.systemIfType = systemInterfaceType;
this.syncType = SynchronousType.SYNC;
}
@Override
protected void checkParameter(FailureStatusRequest request) throws MsfException {
try {
logger.methodStart(new String[] { "request" }, new Object[] { request });
} finally {
logger.methodEnd();
}
}
@Override
protected RestResponseBase executeImpl() throws MsfException {
try {
logger.methodStart();
SessionWrapper session = new SessionWrapper();
try {
session.openSession();
int clusterId = FcConfigManager.getInstance().getSystemConfSwClusterData().getSwCluster().getSwClusterId();
Map<InterfaceType, Map<String, List<LogicalIfStatusIfEntity>>> ifInfoEcMap = new HashMap<>();
ifInfoEcMap.put(InterfaceType.PHYSICAL_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
ifInfoEcMap.put(InterfaceType.BREAKOUT_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
ifInfoEcMap.put(InterfaceType.LAG_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
ifInfoEcMap.put(InterfaceType.VLAN_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
Map<InterfaceType, Map<String, List<LogicalIfStatusIfEntity>>> ifInfoEcAllMap = new HashMap<>();
ifInfoEcAllMap.put(InterfaceType.PHYSICAL_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
ifInfoEcAllMap.put(InterfaceType.BREAKOUT_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
ifInfoEcAllMap.put(InterfaceType.LAG_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
ifInfoEcAllMap.put(InterfaceType.VLAN_IF, new HashMap<String, List<LogicalIfStatusIfEntity>>());
NodeReadListEcResponseBody ecListResponse = sendNodeReadList();
FcNodeDao fcNodeDao = new FcNodeDao();
List<FailureStatusIfFailureEntity> ifs = new ArrayList<>();
Map<String, FcNode> fcNodeMap = new HashMap<>();
for (NodeEcEntity node : ecListResponse.getNodeList()) {
String ecNodeId = node.getNodeId();
InterfaceReadListEcResponseBody ifListResponse = sendIfReadList(ecNodeId);
VlanIfReadListEcResponseBody vlanIfListResponse = sendVlanIfReadList(ecNodeId);
if (!fcNodeMap.containsKey(ecNodeId)) {
FcNode fcNode = fcNodeDao.readByEcNodeId(session, Integer.valueOf(ecNodeId));
fcNodeMap.put(ecNodeId, fcNode);
}
FcNode fcNode = fcNodeMap.get(ecNodeId);
if (fcNode == null) {
logger.info(
"Failure status create skipped(Physical Unit :Ifs)."
+ " Target Node not found. NodeEcEntity={0}, InterfacesEcEntityList={1}, VlanIfEcEntityList={2}.",
node, ifListResponse.getIfs(), ToStringBuilder.reflectionToString(vlanIfListResponse.getVlanIfList()));
continue;
}
updateIfInfoEcAllMap(fcNode, clusterId, ifListResponse.getIfs(), vlanIfListResponse.getVlanIfList(),
ifInfoEcMap, ifInfoEcAllMap, ifs);
if (!NodeStatus.IN_SERVICE.getMessage().equals(node.getNodeState())) {
updateAllIfStateToDown(node.getNodeId(), ifInfoEcMap);
updateAllIfStateToDown(node.getNodeId(), ifInfoEcAllMap);
}
}
List<FailureStatusNodeFailureEntity> nodes = getNodesStatus(fcNodeMap, ecListResponse.getNodeList(), clusterId);
FailureStatusSliceUnitEntity sliceEntity = createSliceNotifyInfo(session, ifInfoEcMap, ifInfoEcAllMap);
Map<ClusterType, Map<String, FailureStatus>> clusterFailureMap = createClusterNotifyInfo(session, ifInfoEcMap,
ifInfoEcAllMap);
List<FailureStatusClusterFailureEntity> clusters = getClusterFailureEntityList(clusterFailureMap, clusterId);
RestResponseBase responseBase = createFailureReadListResponse(nodes, ifs, clusters, sliceEntity);
return responseBase;
} catch (MsfException msfException) {
logger.error(msfException.getMessage(), msfException);
throw msfException;
} finally {
session.closeSession();
}
} finally {
logger.methodEnd();
}
}
private void updateIfInfoEcAllMap(FcNode fcNode, int clusterId, InterfacesEcEntity ifEcEntity,
List<VlanIfEcEntity> vlanEcEntity, Map<InterfaceType, Map<String, List<LogicalIfStatusIfEntity>>> ifInfoEcMap,
Map<InterfaceType, Map<String, List<LogicalIfStatusIfEntity>>> ifInfoEcAllMap,
List<FailureStatusIfFailureEntity> physicalIfEntityList) {
String ecNodeId = fcNode.getEcNodeId().toString();
for (PhysicalIfEcEntity physicalIf : ifEcEntity.getPhysicalIfList()) {
LogicalIfStatusIfEntity logicalIfPhysical = getLogicalIfFromPhysicalIf(physicalIf, ecNodeId);
FailureStatusIfFailureEntity ifFailureEntity = getIfFailureEntity(logicalIfPhysical, fcNode, clusterId);
if (ifFailureEntity == null) {
logger.info("Create lusterInfoMap and Failure notify skipped(Physical Unit :PhysicalIf)."
+ " IF state is empty. LogicalIfStatusIfEntity={0}.", logicalIfPhysical);
continue;
}
setMap(ifInfoEcMap.get(InterfaceType.PHYSICAL_IF), logicalIfPhysical);
setMap(ifInfoEcAllMap.get(InterfaceType.PHYSICAL_IF), logicalIfPhysical);
physicalIfEntityList.add(ifFailureEntity);
}
for (BreakoutIfEcEntity breakoutIf : ifEcEntity.getBreakoutIfList()) {
LogicalIfStatusIfEntity logicalIfBreakout = getLogicalIfFromBreakoutIf(breakoutIf, ecNodeId);
setMap(ifInfoEcMap.get(InterfaceType.BREAKOUT_IF), logicalIfBreakout);
setMap(ifInfoEcAllMap.get(InterfaceType.BREAKOUT_IF), logicalIfBreakout);
physicalIfEntityList.add(getIfFailureEntity(logicalIfBreakout, fcNode, clusterId));
}
for (LagIfEcEntity lagIf : ifEcEntity.getLagIfList()) {
LogicalIfStatusIfEntity logicalIfLag = getLogicalIfFromLagIf(lagIf, ecNodeId);
setMap(ifInfoEcMap.get(InterfaceType.LAG_IF), logicalIfLag);
setMap(ifInfoEcAllMap.get(InterfaceType.LAG_IF), logicalIfLag);
physicalIfEntityList.add(getIfFailureEntity(logicalIfLag, fcNode, clusterId));
}
sortFailureStatusIfFailureEntity(physicalIfEntityList);
if (vlanEcEntity == null) {
return;
}
for (VlanIfEcEntity vlanIf : vlanEcEntity) {
InterfaceOperationStatus vlanIfStatus = InterfaceOperationStatus.getEnumFromMessage(vlanIf.getIfState());
if (InterfaceOperationStatus.UP != vlanIfStatus && InterfaceOperationStatus.DOWN != vlanIfStatus) {
continue;
}
LogicalIfStatusIfEntity logicalIfVlan = getLogicalIfFromVlanIf(vlanIf, ecNodeId);
setMap(ifInfoEcMap.get(InterfaceType.VLAN_IF), logicalIfVlan);
setMap(ifInfoEcAllMap.get(InterfaceType.VLAN_IF), logicalIfVlan);
}
}
private RestResponseBase createFailureReadListResponse(List<FailureStatusNodeFailureEntity> nodes,
List<FailureStatusIfFailureEntity> ifs, List<FailureStatusClusterFailureEntity> clusters,
FailureStatusSliceUnitEntity sliceEntity) {
FailureStatusReadListResponseBody body = new FailureStatusReadListResponseBody();
if (!nodes.isEmpty() || !ifs.isEmpty()) {
FailureStatusPhysicalUnitEntity physicalUnit = new FailureStatusPhysicalUnitEntity();
if (!nodes.isEmpty()) {
physicalUnit.setNodeList(nodes);
}
if (!ifs.isEmpty()) {
physicalUnit.setIfList(ifs);
}
body.setPhysicalUnit(physicalUnit);
}
if (!clusters.isEmpty()) {
FailureStatusClusterUnitEntity clusterUnit = new FailureStatusClusterUnitEntity();
clusterUnit.setClusterList(clusters);
body.setClusterUnit(clusterUnit);
}
body.setSliceUnit(sliceEntity);
return createRestResponse(body, HttpStatus.OK_200);
}
private List<FailureStatusNodeFailureEntity> getNodesStatus(Map<String, FcNode> fcNodeMap,
List<NodeEcEntity> allNodes, int clusterId) {
List<FailureStatusNodeFailureEntity> nodes = new ArrayList<>();
for (NodeEcEntity nodeEcEntity : allNodes) {
FcNode fcNode = fcNodeMap.get(nodeEcEntity.getNodeId());
if (fcNode == null) {
logger.info("Failure status create skipped(Physical Unit :Nodes). Target Node not found. NodeEcEntity={0}.",
nodeEcEntity);
continue;
}
String nodeType = fcNode.getNodeTypeEnum().getSingularMessage();
Integer nodeId = fcNode.getNodeId();
if (NodeStatus.IN_SERVICE.getMessage().equals(nodeEcEntity.getNodeState())) {
nodes.add(getNodeFailureEntity(clusterId, nodeType, FailureStatus.UP, nodeId));
} else {
nodes.add(getNodeFailureEntity(clusterId, nodeType, FailureStatus.DOWN, nodeId));
}
}
sortFailureStatusNodeFailureEntity(nodes);
return nodes;
}
private FailureStatusNodeFailureEntity getNodeFailureEntity(int clusterId, String fabricType, FailureStatus status,
Integer nodeId) {
FailureStatusNodeFailureEntity node = new FailureStatusNodeFailureEntity();
node.setClusterId(String.valueOf(clusterId));
node.setFabricType(fabricType);
node.setFailureStatusEnum(status);
node.setNodeId(nodeId.toString());
return node;
}
}
|
3e12be31ced5767f64067301647e350cb7ecf722 | 7,480 | java | Java | src/main/java/org/squiddev/cctweaks/lua/lib/ArgumentHelper.java | SquidDev-CC/CCTweaks-Lua | cdc36e8db66539d77ca536f4eab6e36f03ccd35b | [
"MIT"
] | 4 | 2016-05-27T15:14:45.000Z | 2017-08-06T04:01:26.000Z | src/main/java/org/squiddev/cctweaks/lua/lib/ArgumentHelper.java | SquidDev-CC/CCTweaks-Lua | cdc36e8db66539d77ca536f4eab6e36f03ccd35b | [
"MIT"
] | 20 | 2016-04-04T16:21:26.000Z | 2017-11-18T07:59:10.000Z | src/main/java/org/squiddev/cctweaks/lua/lib/ArgumentHelper.java | SquidDev-CC/CCTweaks-Lua | cdc36e8db66539d77ca536f4eab6e36f03ccd35b | [
"MIT"
] | 5 | 2016-10-24T01:30:09.000Z | 2019-12-29T18:44:18.000Z | 30.781893 | 127 | 0.677005 | 7,908 | package org.squiddev.cctweaks.lua.lib;
import dan200.computercraft.api.lua.LuaException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
/**
* Various helpers for arguments
*/
public final class ArgumentHelper {
private ArgumentHelper() {
throw new IllegalStateException("Cannot instantiate singleton " + getClass().getName());
}
@Nonnull
public static String getType(@Nullable Object type) {
if (type == null) return "nil";
if (type instanceof String) return "string";
if (type instanceof Boolean) return "boolean";
if (type instanceof Number) return "number";
if (type instanceof Map) return "table";
Class<?> klass = type.getClass();
if (klass.isArray()) {
StringBuilder name = new StringBuilder();
while (klass.isArray()) {
name.append("[]");
klass = klass.getComponentType();
}
name.insert(0, klass.getName());
return name.toString();
} else {
return klass.getName();
}
}
@Nonnull
public static LuaException badArgument(@Nullable Object object, int index, @Nonnull String expected) {
return new LuaException("Expected " + expected + " for argument " + (index + 1) + ", got " + getType(object));
}
@Nonnull
public static LuaException badKey(@Nullable Object object, Object key, @Nonnull String expected) {
return new LuaException("Expected " + expected + " for key " + key + ", got " + getType(object));
}
public static double getNumber(@Nonnull Object[] args, int index) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value instanceof Number) {
return ((Number) value).doubleValue();
} else {
throw badArgument(value, index, "number");
}
}
public static double getNumber(@Nonnull Map<?, ?> args, Object key) throws LuaException {
Object value = args.get(key);
if (value instanceof Number) {
return ((Number) value).doubleValue();
} else {
throw badKey(value, key, "number");
}
}
public static int getInt(@Nonnull Object[] args, int index) throws LuaException {
return (int) getNumber(args, index);
}
public static int getInt(@Nonnull Map<?, ?> args, Object key) throws LuaException {
return (int) getNumber(args, key);
}
public static boolean getBoolean(@Nonnull Object[] args, int index) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value instanceof Boolean) {
return (Boolean) value;
} else {
throw badArgument(value, index, "boolean");
}
}
@Nonnull
public static String getString(@Nonnull Object[] args, int index) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value instanceof String) {
return (String) value;
} else {
throw badArgument(value, index, "string");
}
}
@Nonnull
public static String getString(@Nonnull Map<?, ?> args, Object key) throws LuaException {
Object value = args.get(key);
if (value instanceof String) {
return (String) value;
} else {
throw badKey(value, key, "string");
}
}
@SuppressWarnings("unchecked")
@Nonnull
public static Map<Object, Object> getTable(@Nonnull Object[] args, int index) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value instanceof Map) {
return (Map<Object, Object>) value;
} else {
throw badArgument(value, index, "table");
}
}
@SuppressWarnings("unchecked")
@Nonnull
public static <T extends Enum<T>> T getEnum(@Nonnull Object[] args, int index, Class<T> klass) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value instanceof String) {
String name = (String) value;
try {
return Enum.valueOf(klass, name.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
throw new LuaException("Bad name '" + name.toLowerCase(Locale.ENGLISH) + "' for argument " + (index + 1));
}
} else {
throw badArgument(value, index, "string");
}
}
@SuppressWarnings("unchecked")
@Nonnull
public static UUID getUUID(@Nonnull Object[] args, int index) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value instanceof String) {
String uuid = ((String) value).toLowerCase(Locale.ENGLISH);
try {
return UUID.fromString(uuid);
} catch (IllegalArgumentException e) {
throw new LuaException("Bad uuid '" + uuid + "' for argument " + (index + 1));
}
} else {
throw badArgument(value, index, "string");
}
}
public static double optNumber(@Nonnull Object[] args, int index, double def) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value == null) {
return def;
} else if (value instanceof Number) {
return ((Number) value).doubleValue();
} else {
throw badArgument(value, index, "number");
}
}
public static int optInt(@Nonnull Object[] args, int index, int def) throws LuaException {
return (int) optNumber(args, index, def);
}
public static boolean optBoolean(@Nonnull Object[] args, int index, boolean def) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value == null) {
return def;
} else if (value instanceof Boolean) {
return (Boolean) value;
} else {
throw badArgument(value, index, "boolean");
}
}
public static String optString(@Nonnull Object[] args, int index, String def) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value == null) {
return def;
} else if (value instanceof String) {
return (String) value;
} else {
throw badArgument(value, index, "string");
}
}
public static String optString(@Nonnull Map<?, ?> args, Object key, String def) throws LuaException {
Object value = args.get(key);
if (value == null) {
return def;
} else if (value instanceof String) {
return (String) value;
} else {
throw badKey(value, key, "string");
}
}
@SuppressWarnings("unchecked")
@Nonnull
public static <T extends Enum<T>> T optEnum(@Nonnull Object[] args, int index, Class<T> klass, T def) throws LuaException {
if (index >= args.length || args[index] == null) {
return def;
} else {
return getEnum(args, index, klass);
}
}
@SuppressWarnings("unchecked")
public static Map<Object, Object> optTable(@Nonnull Object[] args, int index, Map<Object, Object> def) throws LuaException {
Object value = index < args.length ? args[index] : null;
if (value == null) {
return def;
} else if (value instanceof Map) {
return (Map<Object, Object>) value;
} else {
throw badArgument(value, index, "table");
}
}
@SuppressWarnings("unchecked")
public static Map<Object, Object> optTable(@Nonnull Map<?, ?> args, Object key, Map<Object, Object> def) throws LuaException {
Object value = args.get(key);
if (value == null) {
return def;
} else if (value instanceof Map) {
return (Map<Object, Object>) value;
} else {
throw badKey(value, key, "table");
}
}
public static void assertBetween(double value, double min, double max, String message) throws LuaException {
if (value < min || value > max) {
throw new LuaException(String.format(message, "between " + min + " and " + max));
}
}
public static void assertBetween(int value, int min, int max, String message) throws LuaException {
if (value < min || value > max) {
throw new LuaException(String.format(message, "between " + min + " and " + max));
}
}
}
|
3e12bfa6f9f942a4fda11a4b88f1af031acf8ba5 | 2,592 | java | Java | WeaponMechanics/src/main/java/me/deecaad/weaponmechanics/weapon/scope/ScopeLevel.java | MechanicsMain/MechanicsMain | 71d4642052f9b41d1ef0a5a30da5b5f04850639e | [
"MIT"
] | 11 | 2021-12-26T02:25:09.000Z | 2022-03-27T09:26:57.000Z | WeaponMechanics/src/main/java/me/deecaad/weaponmechanics/weapon/scope/ScopeLevel.java | MechanicsMain/MechanicsMain | 71d4642052f9b41d1ef0a5a30da5b5f04850639e | [
"MIT"
] | 57 | 2021-12-25T20:06:27.000Z | 2022-03-29T12:40:50.000Z | WeaponMechanics/src/main/java/me/deecaad/weaponmechanics/weapon/scope/ScopeLevel.java | MechanicsMain/MechanicsMain | 71d4642052f9b41d1ef0a5a30da5b5f04850639e | [
"MIT"
] | 1 | 2022-03-27T09:27:01.000Z | 2022-03-27T09:27:01.000Z | 33.662338 | 142 | 0.565972 | 7,909 | package me.deecaad.weaponmechanics.weapon.scope;
import me.deecaad.core.utils.LogLevel;
import static me.deecaad.weaponmechanics.WeaponMechanics.debug;
public class ScopeLevel {
private static float[] scopeLevels = getScopeLevels();
/**
* Don't let anyone instantiate this class
*/
private ScopeLevel() { }
private static float[] getScopeLevels() {
scopeLevels = new float[32];
// Default is 0.1
// -> PacketPlayOutAbilities (walk speed)
scopeLevels[0] = (float) 0.11;
scopeLevels[1] = (float) 0.13;
scopeLevels[2] = (float) 0.15;
scopeLevels[3] = (float) 0.17;
scopeLevels[4] = (float) 0.19;
scopeLevels[5] = (float) 0.2;
scopeLevels[6] = (float) 0.23;
scopeLevels[7] = (float) 0.26;
scopeLevels[8] = (float) 0.29;
scopeLevels[9] = (float) 0.33;
scopeLevels[10] = (float) 0.4;
scopeLevels[11] = (float) 0.6;
scopeLevels[12] = (float) 0.9;
scopeLevels[13] = (float) -0.9;
scopeLevels[14] = (float) -0.6;
scopeLevels[15] = (float) -0.4;
scopeLevels[16] = (float) -0.33;
scopeLevels[17] = (float) -0.29;
scopeLevels[18] = (float) -0.26;
scopeLevels[19] = (float) -0.23;
scopeLevels[20] = (float) -0.2;
scopeLevels[21] = (float) -0.19;
scopeLevels[22] = (float) -0.18;
scopeLevels[23] = (float) -0.17;
scopeLevels[24] = (float) -0.16;
scopeLevels[25] = (float) -0.155;
scopeLevels[26] = (float) -0.15;
scopeLevels[27] = (float) -0.145;
scopeLevels[28] = (float) -0.14;
scopeLevels[29] = (float) -0.135;
scopeLevels[30] = (float) -0.13;
scopeLevels[31] = (float) -0.125;
return scopeLevels;
}
/**
* From this one you can fetch the scope level values.
* It can be either be for attributes or abilities
*
* @param level the scope level
* @return the amount of zoom (when using abilities or attributes depending on level)
*/
public static float getScope(int level) {
if (level < 1 || level > 32) {
debug.log(LogLevel.ERROR,
"Tried to get scope level of " + level + ", but only levels between 1 and 32 are allowed.",
new IllegalArgumentException("Tried to get scope level of " + level + ", but only levels between 1 and 32 are allowed."));
return 0;
}
// -1 because array list index starts at 0 ;)
return scopeLevels[level - 1];
}
} |
3e12bfa8313627405c9e951a25868fcefb0473ee | 16,511 | java | Java | build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_f168a4caadba96d678ce39542d9d1fea/net/minecraft/client/MainWindow.java | sqcode06/RealIndustry | 28fd6bfc81a52ad33d3523905cd3fcb82a1dc994 | [
"Apache-2.0"
] | 1 | 2021-01-04T11:34:52.000Z | 2021-01-04T11:34:52.000Z | build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_f168a4caadba96d678ce39542d9d1fea/net/minecraft/client/MainWindow.java | sqcode06/RealIndustry | 28fd6bfc81a52ad33d3523905cd3fcb82a1dc994 | [
"Apache-2.0"
] | null | null | null | build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_f168a4caadba96d678ce39542d9d1fea/net/minecraft/client/MainWindow.java | sqcode06/RealIndustry | 28fd6bfc81a52ad33d3523905cd3fcb82a1dc994 | [
"Apache-2.0"
] | null | null | null | 35.129787 | 228 | 0.678033 | 7,910 | package net.minecraft.client;
import com.mojang.blaze3d.platform.GLX;
import com.mojang.blaze3d.systems.RenderSystem;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Optional;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import net.minecraft.client.renderer.IWindowEventListener;
import net.minecraft.client.renderer.MonitorHandler;
import net.minecraft.client.renderer.ScreenSize;
import net.minecraft.client.renderer.VideoMode;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.util.InputMappings;
import net.minecraft.client.util.UndeclaredException;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.PointerBuffer;
import org.lwjgl.glfw.Callbacks;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWImage;
import org.lwjgl.glfw.GLFWImage.Buffer;
import org.lwjgl.opengl.GL;
import org.lwjgl.stb.STBImage;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.util.tinyfd.TinyFileDialogs;
@OnlyIn(Dist.CLIENT)
public final class MainWindow implements AutoCloseable {
private static final Logger LOGGER = LogManager.getLogger();
private final GLFWErrorCallback defaultErrorCallback = GLFWErrorCallback.create(this::defaultErrorCallback);
private final IWindowEventListener eventHandler;
private final MonitorHandler screenManager;
private final long window;
private int windowedX;
private int windowedY;
private int windowedWidth;
private int windowedHeight;
private Optional<VideoMode> preferredFullscreenVideoMode;
private boolean fullscreen;
private boolean actuallyFullscreen;
private int x;
private int y;
private int width;
private int height;
private int framebufferWidth;
private int framebufferHeight;
private int guiScaledWidth;
private int guiScaledHeight;
private double guiScale;
private String errorSection = "";
private boolean dirty;
private int framerateLimit;
private boolean vsync;
public MainWindow(IWindowEventListener p_i51170_1_, MonitorHandler p_i51170_2_, ScreenSize p_i51170_3_, @Nullable String p_i51170_4_, String p_i51170_5_) {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
this.screenManager = p_i51170_2_;
this.setBootErrorCallback();
this.setErrorSection("Pre startup");
this.eventHandler = p_i51170_1_;
Optional<VideoMode> optional = VideoMode.read(p_i51170_4_);
if (optional.isPresent()) {
this.preferredFullscreenVideoMode = optional;
} else if (p_i51170_3_.fullscreenWidth.isPresent() && p_i51170_3_.fullscreenHeight.isPresent()) {
this.preferredFullscreenVideoMode = Optional.of(new VideoMode(p_i51170_3_.fullscreenWidth.getAsInt(), p_i51170_3_.fullscreenHeight.getAsInt(), 8, 8, 8, 60));
} else {
this.preferredFullscreenVideoMode = Optional.empty();
}
this.actuallyFullscreen = this.fullscreen = p_i51170_3_.isFullscreen;
Monitor monitor = p_i51170_2_.getMonitor(GLFW.glfwGetPrimaryMonitor());
this.windowedWidth = this.width = p_i51170_3_.width > 0 ? p_i51170_3_.width : 1;
this.windowedHeight = this.height = p_i51170_3_.height > 0 ? p_i51170_3_.height : 1;
GLFW.glfwDefaultWindowHints();
GLFW.glfwWindowHint(139265, 196609);
GLFW.glfwWindowHint(139275, 221185);
GLFW.glfwWindowHint(139266, 2);
GLFW.glfwWindowHint(139267, 0);
GLFW.glfwWindowHint(139272, 0);
this.window = net.minecraftforge.fml.loading.progress.EarlyProgressVisualization.INSTANCE.handOffWindow(()->this.width, ()->this.height, ()->p_i51170_5_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L);
if (monitor != null) {
VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty());
this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2;
this.windowedY = this.y = monitor.getY() + videomode.getHeight() / 2 - this.height / 2;
} else {
int[] aint1 = new int[1];
int[] aint = new int[1];
GLFW.glfwGetWindowPos(this.window, aint1, aint);
this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0];
}
GLFW.glfwMakeContextCurrent(this.window);
GL.createCapabilities();
this.setMode();
this.refreshFramebufferSize();
GLFW.glfwSetFramebufferSizeCallback(this.window, this::onFramebufferResize);
GLFW.glfwSetWindowPosCallback(this.window, this::onMove);
GLFW.glfwSetWindowSizeCallback(this.window, this::onResize);
GLFW.glfwSetWindowFocusCallback(this.window, this::onFocus);
GLFW.glfwSetCursorEnterCallback(this.window, this::onEnter);
}
public int getRefreshRate() {
RenderSystem.assertThread(RenderSystem::isOnRenderThread);
return GLX._getRefreshRate(this);
}
public boolean shouldClose() {
return GLX._shouldClose(this);
}
public static void checkGlfwError(BiConsumer<Integer, String> p_211162_0_) {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
try (MemoryStack memorystack = MemoryStack.stackPush()) {
PointerBuffer pointerbuffer = memorystack.mallocPointer(1);
int i = GLFW.glfwGetError(pointerbuffer);
if (i != 0) {
long j = pointerbuffer.get();
String s = j == 0L ? "" : MemoryUtil.memUTF8(j);
p_211162_0_.accept(i, s);
}
}
}
public void setIcon(InputStream p_216529_1_, InputStream p_216529_2_) {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
try (MemoryStack memorystack = MemoryStack.stackPush()) {
if (p_216529_1_ == null) {
throw new FileNotFoundException("icons/icon_16x16.png");
}
if (p_216529_2_ == null) {
throw new FileNotFoundException("icons/icon_32x32.png");
}
IntBuffer intbuffer = memorystack.mallocInt(1);
IntBuffer intbuffer1 = memorystack.mallocInt(1);
IntBuffer intbuffer2 = memorystack.mallocInt(1);
Buffer buffer = GLFWImage.mallocStack(2, memorystack);
ByteBuffer bytebuffer = this.readIconPixels(p_216529_1_, intbuffer, intbuffer1, intbuffer2);
if (bytebuffer == null) {
throw new IllegalStateException("Could not load icon: " + STBImage.stbi_failure_reason());
}
buffer.position(0);
buffer.width(intbuffer.get(0));
buffer.height(intbuffer1.get(0));
buffer.pixels(bytebuffer);
ByteBuffer bytebuffer1 = this.readIconPixels(p_216529_2_, intbuffer, intbuffer1, intbuffer2);
if (bytebuffer1 == null) {
throw new IllegalStateException("Could not load icon: " + STBImage.stbi_failure_reason());
}
buffer.position(1);
buffer.width(intbuffer.get(0));
buffer.height(intbuffer1.get(0));
buffer.pixels(bytebuffer1);
buffer.position(0);
GLFW.glfwSetWindowIcon(this.window, buffer);
STBImage.stbi_image_free(bytebuffer);
STBImage.stbi_image_free(bytebuffer1);
} catch (IOException ioexception) {
LOGGER.error("Couldn't set icon", (Throwable)ioexception);
}
}
@Nullable
private ByteBuffer readIconPixels(InputStream p_198111_1_, IntBuffer p_198111_2_, IntBuffer p_198111_3_, IntBuffer p_198111_4_) throws IOException {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
ByteBuffer bytebuffer = null;
ByteBuffer bytebuffer1;
try {
bytebuffer = TextureUtil.readResource(p_198111_1_);
((java.nio.Buffer)bytebuffer).rewind();
bytebuffer1 = STBImage.stbi_load_from_memory(bytebuffer, p_198111_2_, p_198111_3_, p_198111_4_, 0);
} finally {
if (bytebuffer != null) {
MemoryUtil.memFree(bytebuffer);
}
}
return bytebuffer1;
}
public void setErrorSection(String p_227799_1_) {
this.errorSection = p_227799_1_;
}
private void setBootErrorCallback() {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
GLFW.glfwSetErrorCallback(MainWindow::bootCrash);
}
private static void bootCrash(int p_208034_0_, long p_208034_1_) {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
String s = "GLFW error " + p_208034_0_ + ": " + MemoryUtil.memUTF8(p_208034_1_);
TinyFileDialogs.tinyfd_messageBox("Minecraft", s + ".\n\nPlease make sure you have up-to-date drivers (see aka.ms/mcdriver for instructions).", "ok", "error", false);
throw new MainWindow.GlException(s);
}
public void defaultErrorCallback(int p_198084_1_, long p_198084_2_) {
RenderSystem.assertThread(RenderSystem::isOnRenderThread);
String s = MemoryUtil.memUTF8(p_198084_2_);
LOGGER.error("########## GL ERROR ##########");
LOGGER.error("@ {}", (Object)this.errorSection);
LOGGER.error("{}: {}", p_198084_1_, s);
}
public void setDefaultErrorCallback() {
GLFWErrorCallback glfwerrorcallback = GLFW.glfwSetErrorCallback(this.defaultErrorCallback);
if (glfwerrorcallback != null) {
glfwerrorcallback.free();
}
}
public void updateVsync(boolean p_216523_1_) {
RenderSystem.assertThread(RenderSystem::isOnRenderThreadOrInit);
this.vsync = p_216523_1_;
GLFW.glfwSwapInterval(p_216523_1_ ? 1 : 0);
}
public void close() {
RenderSystem.assertThread(RenderSystem::isOnRenderThread);
Callbacks.glfwFreeCallbacks(this.window);
this.defaultErrorCallback.close();
GLFW.glfwDestroyWindow(this.window);
GLFW.glfwTerminate();
}
private void onMove(long p_198080_1_, int p_198080_3_, int p_198080_4_) {
this.x = p_198080_3_;
this.y = p_198080_4_;
}
private void onFramebufferResize(long p_198102_1_, int p_198102_3_, int p_198102_4_) {
if (p_198102_1_ == this.window) {
int i = this.getWidth();
int j = this.getHeight();
if (p_198102_3_ != 0 && p_198102_4_ != 0) {
this.framebufferWidth = p_198102_3_;
this.framebufferHeight = p_198102_4_;
if (this.getWidth() != i || this.getHeight() != j) {
this.eventHandler.resizeDisplay();
}
}
}
}
private void refreshFramebufferSize() {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
int[] aint = new int[1];
int[] aint1 = new int[1];
GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
this.framebufferWidth = aint[0];
this.framebufferHeight = aint1[0];
if (this.framebufferHeight == 0 || this.framebufferWidth==0) net.minecraftforge.fml.loading.progress.EarlyProgressVisualization.INSTANCE.updateFBSize(w->this.framebufferWidth=w, h->this.framebufferHeight=h);
}
private void onResize(long p_198089_1_, int p_198089_3_, int p_198089_4_) {
this.width = p_198089_3_;
this.height = p_198089_4_;
}
private void onFocus(long p_198095_1_, boolean p_198095_3_) {
if (p_198095_1_ == this.window) {
this.eventHandler.setWindowActive(p_198095_3_);
}
}
private void onEnter(long p_241553_1_, boolean p_241553_3_) {
if (p_241553_3_) {
this.eventHandler.cursorEntered();
}
}
public void setFramerateLimit(int p_216526_1_) {
this.framerateLimit = p_216526_1_;
}
public int getFramerateLimit() {
return this.framerateLimit;
}
public void updateDisplay() {
RenderSystem.flipFrame(this.window);
if (this.fullscreen != this.actuallyFullscreen) {
this.actuallyFullscreen = this.fullscreen;
this.updateFullscreen(this.vsync);
}
}
public Optional<VideoMode> getPreferredFullscreenVideoMode() {
return this.preferredFullscreenVideoMode;
}
public void setPreferredFullscreenVideoMode(Optional<VideoMode> p_224797_1_) {
boolean flag = !p_224797_1_.equals(this.preferredFullscreenVideoMode);
this.preferredFullscreenVideoMode = p_224797_1_;
if (flag) {
this.dirty = true;
}
}
public void changeFullscreenVideoMode() {
if (this.fullscreen && this.dirty) {
this.dirty = false;
this.setMode();
this.eventHandler.resizeDisplay();
}
}
private void setMode() {
RenderSystem.assertThread(RenderSystem::isInInitPhase);
boolean flag = GLFW.glfwGetWindowMonitor(this.window) != 0L;
if (this.fullscreen) {
Monitor monitor = this.screenManager.findBestMonitor(this);
if (monitor == null) {
LOGGER.warn("Failed to find suitable monitor for fullscreen mode");
this.fullscreen = false;
} else {
VideoMode videomode = monitor.getPreferredVidMode(this.preferredFullscreenVideoMode);
if (!flag) {
this.windowedX = this.x;
this.windowedY = this.y;
this.windowedWidth = this.width;
this.windowedHeight = this.height;
}
this.x = 0;
this.y = 0;
this.width = videomode.getWidth();
this.height = videomode.getHeight();
GLFW.glfwSetWindowMonitor(this.window, monitor.getMonitor(), this.x, this.y, this.width, this.height, videomode.getRefreshRate());
}
} else {
this.x = this.windowedX;
this.y = this.windowedY;
this.width = this.windowedWidth;
this.height = this.windowedHeight;
GLFW.glfwSetWindowMonitor(this.window, 0L, this.x, this.y, this.width, this.height, -1);
}
}
public void toggleFullScreen() {
this.fullscreen = !this.fullscreen;
}
private void updateFullscreen(boolean p_216527_1_) {
RenderSystem.assertThread(RenderSystem::isOnRenderThread);
try {
this.setMode();
this.eventHandler.resizeDisplay();
this.updateVsync(p_216527_1_);
this.updateDisplay();
} catch (Exception exception) {
LOGGER.error("Couldn't toggle fullscreen", (Throwable)exception);
}
}
public int calculateScale(int p_216521_1_, boolean p_216521_2_) {
int i;
for(i = 1; i != p_216521_1_ && i < this.framebufferWidth && i < this.framebufferHeight && this.framebufferWidth / (i + 1) >= 320 && this.framebufferHeight / (i + 1) >= 240; ++i) {
}
if (p_216521_2_ && i % 2 != 0) {
++i;
}
return i;
}
public void setGuiScale(double p_216525_1_) {
this.guiScale = p_216525_1_;
int i = (int)((double)this.framebufferWidth / p_216525_1_);
this.guiScaledWidth = (double)this.framebufferWidth / p_216525_1_ > (double)i ? i + 1 : i;
int j = (int)((double)this.framebufferHeight / p_216525_1_);
this.guiScaledHeight = (double)this.framebufferHeight / p_216525_1_ > (double)j ? j + 1 : j;
}
public void setTitle(String p_230148_1_) {
GLFW.glfwSetWindowTitle(this.window, p_230148_1_);
}
public long getWindow() {
return this.window;
}
public boolean isFullscreen() {
return this.fullscreen;
}
public int getWidth() {
return this.framebufferWidth;
}
public int getHeight() {
return this.framebufferHeight;
}
public int getScreenWidth() {
return this.width;
}
public int getScreenHeight() {
return this.height;
}
public int getGuiScaledWidth() {
return this.guiScaledWidth;
}
public int getGuiScaledHeight() {
return this.guiScaledHeight;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public double getGuiScale() {
return this.guiScale;
}
@Nullable
public Monitor findBestMonitor() {
return this.screenManager.findBestMonitor(this);
}
public void updateRawMouseInput(boolean p_224798_1_) {
InputMappings.updateRawMouseInput(this.window, p_224798_1_);
}
@OnlyIn(Dist.CLIENT)
public static class GlException extends UndeclaredException {
private GlException(String p_i225902_1_) {
super(p_i225902_1_);
}
}
}
|
3e12c0640c316dee9a5294e622edb1b4c9560c39 | 207 | java | Java | core/src/main/java/com/pipai/wf/artemis/components/SphericalCoordinateComponent.java | applepi07/wf | 6906895037c29af3ec7df7c54ffea227c56560ff | [
"Apache-2.0"
] | 3 | 2016-03-05T21:54:08.000Z | 2016-09-02T13:48:57.000Z | core/src/main/java/com/pipai/wf/artemis/components/SphericalCoordinateComponent.java | applepi07/wf | 6906895037c29af3ec7df7c54ffea227c56560ff | [
"Apache-2.0"
] | 2 | 2015-09-18T05:26:35.000Z | 2015-10-02T07:29:27.000Z | core/src/main/java/com/pipai/wf/artemis/components/SphericalCoordinateComponent.java | cypai/wf | 6906895037c29af3ec7df7c54ffea227c56560ff | [
"Apache-2.0"
] | null | null | null | 17.25 | 62 | 0.753623 | 7,911 | package com.pipai.wf.artemis.components;
import com.artemis.Component;
public class SphericalCoordinateComponent extends Component {
public float r;
public float theta;
public float phi;
}
|
3e12c1bd165e1af74bc3fbccc9a55c4cd7e60116 | 2,283 | java | Java | java/src/com/swiftnav/sbp/system/MsgStartup.java | zk20/libsbp | 041c5055f5db422258ebb3ce3f8e9f6e5d3e5fa9 | [
"MIT"
] | 65 | 2015-03-25T10:28:10.000Z | 2022-02-24T12:36:49.000Z | java/src/com/swiftnav/sbp/system/MsgStartup.java | zk20/libsbp | 041c5055f5db422258ebb3ce3f8e9f6e5d3e5fa9 | [
"MIT"
] | 654 | 2015-03-24T17:43:55.000Z | 2022-03-31T21:42:49.000Z | java/src/com/swiftnav/sbp/system/MsgStartup.java | zk20/libsbp | 041c5055f5db422258ebb3ce3f8e9f6e5d3e5fa9 | [
"MIT"
] | 110 | 2015-03-24T17:38:35.000Z | 2022-03-21T02:05:19.000Z | 28.5375 | 96 | 0.677617 | 7,912 | /* Copyright (C) 2015-2021 Swift Navigation Inc.
* Contact: https://support.swiftnav.com
*
* This source is subject to the license found in the file 'LICENSE' which must
* be be distributed together with this source. All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
package com.swiftnav.sbp.system;
// This file was auto-generated from yaml/swiftnav/sbp/system.yaml by generate.py.
// Do not modify by hand!
import com.swiftnav.sbp.SBPBinaryException;
import com.swiftnav.sbp.SBPMessage;
import org.json.JSONObject;
/**
* SBP class for message MSG_STARTUP (0xFF00).
*
* <p>You can have MSG_STARTUP inherent its fields directly from an inherited SBP object, or
* construct it inline using a dict of its fields.
*
* <p>The system start-up message is sent once on system start-up. It notifies the host or other
* attached devices that the system has started and is now ready to respond to commands or
* configuration requests.
*/
public class MsgStartup extends SBPMessage {
public static final int TYPE = 0xFF00;
/** Cause of startup */
public int cause;
/** Startup type */
public int startup_type;
/** Reserved */
public int reserved;
public MsgStartup(int sender) {
super(sender, TYPE);
}
public MsgStartup() {
super(TYPE);
}
public MsgStartup(SBPMessage msg) throws SBPBinaryException {
super(msg);
assert msg.type == TYPE;
}
@Override
protected void parse(Parser parser) throws SBPBinaryException {
/* Parse fields from binary */
cause = parser.getU8();
startup_type = parser.getU8();
reserved = parser.getU16();
}
@Override
protected void build(Builder builder) {
builder.putU8(cause);
builder.putU8(startup_type);
builder.putU16(reserved);
}
@Override
public JSONObject toJSON() {
JSONObject obj = super.toJSON();
obj.put("cause", cause);
obj.put("startup_type", startup_type);
obj.put("reserved", reserved);
return obj;
}
}
|
3e12c24f9e419d00cbc89b4ad1466529889b8798 | 1,321 | java | Java | kieker-monitoring/src/kieker/monitoring/queue/behavior/InsertBehavior.java | bestzy6/kiekerSQL | 2eafee661ba0b9d330079ae017019c32c5dda436 | [
"Apache-2.0"
] | 56 | 2015-12-16T13:02:58.000Z | 2022-02-21T22:02:10.000Z | kieker-monitoring/src/kieker/monitoring/queue/behavior/InsertBehavior.java | bestzy6/kiekerSQL | 2eafee661ba0b9d330079ae017019c32c5dda436 | [
"Apache-2.0"
] | 72 | 2016-10-11T09:30:03.000Z | 2022-02-16T21:54:48.000Z | kieker-monitoring/src/kieker/monitoring/queue/behavior/InsertBehavior.java | bestzy6/kiekerSQL | 2eafee661ba0b9d330079ae017019c32c5dda436 | [
"Apache-2.0"
] | 50 | 2015-11-11T14:06:43.000Z | 2022-02-27T17:17:13.000Z | 33.871795 | 123 | 0.617714 | 7,913 | /***************************************************************************
* Copyright 2021 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.monitoring.queue.behavior;
/**
* @author Christian Wulf (chw)
*
* @param <E>
* the type of the element which should be inserted into the queue.
* @since 1.13
*/
public interface InsertBehavior<E> { // NOCS (should start without an "I" for reasons of readability)
/**
* @param element
* element to be inserted
*
* @return <code>true</code> if the element after this <code>element</code> can be inserted, otherwise <code>false</code>.
*
* @since 1.13
*/
boolean insert(E element);
}
|
3e12c400a96a11f504fa283fb27916fdc87991c9 | 11,333 | java | Java | components/camel-jmx/src/generated/java/org/apache/camel/component/jmx/JMXEndpointConfigurer.java | DragoiNicolae/camel | 9fbc54678680d2bf00b0004963f32a08bf4d0515 | [
"Apache-2.0"
] | 1 | 2020-04-15T09:17:24.000Z | 2020-04-15T09:17:24.000Z | components/camel-jmx/src/generated/java/org/apache/camel/component/jmx/JMXEndpointConfigurer.java | DragoiNicolae/camel | 9fbc54678680d2bf00b0004963f32a08bf4d0515 | [
"Apache-2.0"
] | null | null | null | components/camel-jmx/src/generated/java/org/apache/camel/component/jmx/JMXEndpointConfigurer.java | DragoiNicolae/camel | 9fbc54678680d2bf00b0004963f32a08bf4d0515 | [
"Apache-2.0"
] | null | null | null | 54.22488 | 151 | 0.700432 | 7,914 | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.jmx;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class JMXEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
JMXEndpoint target = (JMXEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "differencemode":
case "differenceMode": target.setDifferenceMode(property(camelContext, boolean.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "executorservice":
case "executorService": target.setExecutorService(property(camelContext, java.util.concurrent.ExecutorService.class, value)); return true;
case "format": target.setFormat(property(camelContext, java.lang.String.class, value)); return true;
case "granularityperiod":
case "granularityPeriod": target.setGranularityPeriod(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "handback": target.setHandback(property(camelContext, java.lang.Object.class, value)); return true;
case "initthreshold":
case "initThreshold": target.setInitThreshold(property(camelContext, int.class, value)); return true;
case "modulus": target.setModulus(property(camelContext, int.class, value)); return true;
case "monitortype":
case "monitorType": target.setMonitorType(property(camelContext, java.lang.String.class, value)); return true;
case "notificationfilter":
case "notificationFilter": target.setNotificationFilter(property(camelContext, javax.management.NotificationFilter.class, value)); return true;
case "notifydiffer":
case "notifyDiffer": target.setNotifyDiffer(property(camelContext, boolean.class, value)); return true;
case "notifyhigh":
case "notifyHigh": target.setNotifyHigh(property(camelContext, boolean.class, value)); return true;
case "notifylow":
case "notifyLow": target.setNotifyLow(property(camelContext, boolean.class, value)); return true;
case "notifymatch":
case "notifyMatch": target.setNotifyMatch(property(camelContext, boolean.class, value)); return true;
case "objectdomain":
case "objectDomain": target.setObjectDomain(property(camelContext, java.lang.String.class, value)); return true;
case "objectname":
case "objectName": target.setObjectName(property(camelContext, java.lang.String.class, value)); return true;
case "objectproperties":
case "objectProperties": target.setObjectProperties(property(camelContext, java.util.Map.class, value)); return true;
case "observedattribute":
case "observedAttribute": target.setObservedAttribute(property(camelContext, java.lang.String.class, value)); return true;
case "offset": target.setOffset(property(camelContext, int.class, value)); return true;
case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "reconnectdelay":
case "reconnectDelay": target.setReconnectDelay(property(camelContext, int.class, value)); return true;
case "reconnectonconnectionfailure":
case "reconnectOnConnectionFailure": target.setReconnectOnConnectionFailure(property(camelContext, boolean.class, value)); return true;
case "stringtocompare":
case "stringToCompare": target.setStringToCompare(property(camelContext, java.lang.String.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
case "testconnectiononstartup":
case "testConnectionOnStartup": target.setTestConnectionOnStartup(property(camelContext, boolean.class, value)); return true;
case "thresholdhigh":
case "thresholdHigh": target.setThresholdHigh(property(camelContext, java.lang.Double.class, value)); return true;
case "thresholdlow":
case "thresholdLow": target.setThresholdLow(property(camelContext, java.lang.Double.class, value)); return true;
case "user": target.setUser(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "differencemode":
case "differenceMode": return boolean.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "executorservice":
case "executorService": return java.util.concurrent.ExecutorService.class;
case "format": return java.lang.String.class;
case "granularityperiod":
case "granularityPeriod": return long.class;
case "handback": return java.lang.Object.class;
case "initthreshold":
case "initThreshold": return int.class;
case "modulus": return int.class;
case "monitortype":
case "monitorType": return java.lang.String.class;
case "notificationfilter":
case "notificationFilter": return javax.management.NotificationFilter.class;
case "notifydiffer":
case "notifyDiffer": return boolean.class;
case "notifyhigh":
case "notifyHigh": return boolean.class;
case "notifylow":
case "notifyLow": return boolean.class;
case "notifymatch":
case "notifyMatch": return boolean.class;
case "objectdomain":
case "objectDomain": return java.lang.String.class;
case "objectname":
case "objectName": return java.lang.String.class;
case "objectproperties":
case "objectProperties": return java.util.Map.class;
case "observedattribute":
case "observedAttribute": return java.lang.String.class;
case "offset": return int.class;
case "password": return java.lang.String.class;
case "reconnectdelay":
case "reconnectDelay": return int.class;
case "reconnectonconnectionfailure":
case "reconnectOnConnectionFailure": return boolean.class;
case "stringtocompare":
case "stringToCompare": return java.lang.String.class;
case "synchronous": return boolean.class;
case "testconnectiononstartup":
case "testConnectionOnStartup": return boolean.class;
case "thresholdhigh":
case "thresholdHigh": return java.lang.Double.class;
case "thresholdlow":
case "thresholdLow": return java.lang.Double.class;
case "user": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
JMXEndpoint target = (JMXEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": return target.isBasicPropertyBinding();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "differencemode":
case "differenceMode": return target.isDifferenceMode();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "executorservice":
case "executorService": return target.getExecutorService();
case "format": return target.getFormat();
case "granularityperiod":
case "granularityPeriod": return target.getGranularityPeriod();
case "handback": return target.getHandback();
case "initthreshold":
case "initThreshold": return target.getInitThreshold();
case "modulus": return target.getModulus();
case "monitortype":
case "monitorType": return target.getMonitorType();
case "notificationfilter":
case "notificationFilter": return target.getNotificationFilter();
case "notifydiffer":
case "notifyDiffer": return target.isNotifyDiffer();
case "notifyhigh":
case "notifyHigh": return target.isNotifyHigh();
case "notifylow":
case "notifyLow": return target.isNotifyLow();
case "notifymatch":
case "notifyMatch": return target.isNotifyMatch();
case "objectdomain":
case "objectDomain": return target.getObjectDomain();
case "objectname":
case "objectName": return target.getObjectName();
case "objectproperties":
case "objectProperties": return target.getObjectProperties();
case "observedattribute":
case "observedAttribute": return target.getObservedAttribute();
case "offset": return target.getOffset();
case "password": return target.getPassword();
case "reconnectdelay":
case "reconnectDelay": return target.getReconnectDelay();
case "reconnectonconnectionfailure":
case "reconnectOnConnectionFailure": return target.isReconnectOnConnectionFailure();
case "stringtocompare":
case "stringToCompare": return target.getStringToCompare();
case "synchronous": return target.isSynchronous();
case "testconnectiononstartup":
case "testConnectionOnStartup": return target.isTestConnectionOnStartup();
case "thresholdhigh":
case "thresholdHigh": return target.getThresholdHigh();
case "thresholdlow":
case "thresholdLow": return target.getThresholdLow();
case "user": return target.getUser();
default: return null;
}
}
}
|
3e12c43d245fa49731bb549c2d27d00cf4ba00c0 | 8,417 | java | Java | RocLang/robotcontrol.parent/robotcontrol/src-gen/robotcontrol/AbstractRocRuntimeModule.java | idobrusin/RocLang | 9dce499f99af1e57f26c6b0348a5c80c466f09e9 | [
"MIT"
] | 4 | 2019-06-13T07:19:01.000Z | 2021-10-30T15:28:41.000Z | RocLang/robotcontrol.parent/robotcontrol/src-gen/robotcontrol/AbstractRocRuntimeModule.java | idobrusin/RocLang | 9dce499f99af1e57f26c6b0348a5c80c466f09e9 | [
"MIT"
] | null | null | null | RocLang/robotcontrol.parent/robotcontrol/src-gen/robotcontrol/AbstractRocRuntimeModule.java | idobrusin/RocLang | 9dce499f99af1e57f26c6b0348a5c80c466f09e9 | [
"MIT"
] | null | null | null | 43.164103 | 170 | 0.830462 | 7,915 | /*
* generated by Xtext 2.10.0
*/
package robotcontrol;
import com.google.inject.Binder;
import com.google.inject.Provider;
import com.google.inject.name.Names;
import java.util.Properties;
import org.eclipse.xtext.Constants;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.generator.IGenerator2;
import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider;
import org.eclipse.xtext.naming.IQualifiedNameProvider;
import org.eclipse.xtext.parser.IParser;
import org.eclipse.xtext.parser.ITokenToStringConverter;
import org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider;
import org.eclipse.xtext.parser.antlr.AntlrTokenToStringConverter;
import org.eclipse.xtext.parser.antlr.IAntlrTokenFileProvider;
import org.eclipse.xtext.parser.antlr.ITokenDefProvider;
import org.eclipse.xtext.parser.antlr.Lexer;
import org.eclipse.xtext.parser.antlr.LexerBindings;
import org.eclipse.xtext.parser.antlr.LexerProvider;
import org.eclipse.xtext.resource.IContainer;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.resource.containers.IAllContainersState;
import org.eclipse.xtext.resource.containers.ResourceSetBasedAllContainersStateProvider;
import org.eclipse.xtext.resource.containers.StateBasedContainerManager;
import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider;
import org.eclipse.xtext.resource.impl.ResourceSetBasedResourceDescriptions;
import org.eclipse.xtext.scoping.IGlobalScopeProvider;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.eclipse.xtext.scoping.IgnoreCaseLinking;
import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider;
import org.eclipse.xtext.scoping.impl.DefaultGlobalScopeProvider;
import org.eclipse.xtext.scoping.impl.ImportedNamespaceAwareLocalScopeProvider;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.serializer.impl.Serializer;
import org.eclipse.xtext.serializer.sequencer.ISemanticSequencer;
import org.eclipse.xtext.serializer.sequencer.ISyntacticSequencer;
import org.eclipse.xtext.service.DefaultRuntimeModule;
import org.eclipse.xtext.service.SingletonBinding;
import robotcontrol.generator.RocGenerator;
import robotcontrol.parser.antlr.RocAntlrTokenFileProvider;
import robotcontrol.parser.antlr.RocParser;
import robotcontrol.parser.antlr.internal.InternalRocLexer;
import robotcontrol.scoping.RocScopeProvider;
import robotcontrol.serializer.RocSemanticSequencer;
import robotcontrol.serializer.RocSyntacticSequencer;
import robotcontrol.services.RocGrammarAccess;
import robotcontrol.validation.RocValidator;
/**
* Manual modifications go to {@link RocRuntimeModule}.
*/
@SuppressWarnings("all")
public abstract class AbstractRocRuntimeModule extends DefaultRuntimeModule {
protected Properties properties = null;
@Override
public void configure(Binder binder) {
properties = tryBindProperties(binder, "robotcontrol/Roc.properties");
super.configure(binder);
}
public void configureLanguageName(Binder binder) {
binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("robotcontrol.Roc");
}
public void configureFileExtensions(Binder binder) {
if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null)
binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("roc");
}
// contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2
public ClassLoader bindClassLoaderToInstance() {
return getClass().getClassLoader();
}
// contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2
public Class<? extends IGrammarAccess> bindIGrammarAccess() {
return RocGrammarAccess.class;
}
// contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
public Class<? extends ISemanticSequencer> bindISemanticSequencer() {
return RocSemanticSequencer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
public Class<? extends ISyntacticSequencer> bindISyntacticSequencer() {
return RocSyntacticSequencer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
public Class<? extends ISerializer> bindISerializer() {
return Serializer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IParser> bindIParser() {
return RocParser.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends ITokenToStringConverter> bindITokenToStringConverter() {
return AntlrTokenToStringConverter.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IAntlrTokenFileProvider> bindIAntlrTokenFileProvider() {
return RocAntlrTokenFileProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends Lexer> bindLexer() {
return InternalRocLexer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends ITokenDefProvider> bindITokenDefProvider() {
return AntlrTokenDefProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Provider<InternalRocLexer> provideInternalRocLexer() {
return LexerProvider.create(InternalRocLexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureRuntimeLexer(Binder binder) {
binder.bind(Lexer.class)
.annotatedWith(Names.named(LexerBindings.RUNTIME))
.to(InternalRocLexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2
@SingletonBinding(eager=true)
public Class<? extends RocValidator> bindRocValidator() {
return RocValidator.class;
}
// contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2
public Class<? extends IScopeProvider> bindIScopeProvider() {
return RocScopeProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2
public void configureIScopeProviderDelegate(Binder binder) {
binder.bind(IScopeProvider.class).annotatedWith(Names.named(AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(ImportedNamespaceAwareLocalScopeProvider.class);
}
// contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2
public Class<? extends IGlobalScopeProvider> bindIGlobalScopeProvider() {
return DefaultGlobalScopeProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2
public void configureIgnoreCaseLinking(Binder binder) {
binder.bindConstant().annotatedWith(IgnoreCaseLinking.class).to(false);
}
// contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2
public Class<? extends IQualifiedNameProvider> bindIQualifiedNameProvider() {
return DefaultDeclarativeQualifiedNameProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends IContainer.Manager> bindIContainer$Manager() {
return StateBasedContainerManager.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends IAllContainersState.Provider> bindIAllContainersState$Provider() {
return ResourceSetBasedAllContainersStateProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public void configureIResourceDescriptions(Binder binder) {
binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class);
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public void configureIResourceDescriptionsPersisted(Binder binder) {
binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class);
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public Class<? extends IGenerator2> bindIGenerator2() {
return RocGenerator.class;
}
}
|
3e12c46e7ea5a8cd4dfb536e581fc594797f4b16 | 2,515 | java | Java | src/test/java/test/alipsa/ymp/YearMonthPickerTest.java | Alipsa/fx-yearmonth-picker | 9b77be5edac096bf5e4cdb9f5176c180ab2595a1 | [
"MIT"
] | null | null | null | src/test/java/test/alipsa/ymp/YearMonthPickerTest.java | Alipsa/fx-yearmonth-picker | 9b77be5edac096bf5e4cdb9f5176c180ab2595a1 | [
"MIT"
] | null | null | null | src/test/java/test/alipsa/ymp/YearMonthPickerTest.java | Alipsa/fx-yearmonth-picker | 9b77be5edac096bf5e4cdb9f5176c180ab2595a1 | [
"MIT"
] | null | null | null | 34.930556 | 102 | 0.700199 | 7,916 | package test.alipsa.ymp;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import se.alipsa.ymp.YearMonthPicker;
import se.alipsa.ymp.YearMonthPickerCombo;
import org.junit.jupiter.api.Test;
import java.time.YearMonth;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class YearMonthPickerTest {
@BeforeAll
public static void setupJavaFX() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch( 1 );
// initializes JavaFX environment
Platform.startup( () -> {
/* No need to do anything here */
System.out.println("Starting javaFX");
} );
latch.countDown();
latch.await();
}
@AfterAll
public static void tearDown() {
System.out.println("Stopping javaFX");
Platform.exit();
}
@Test
public void testYearMonthPicker() {
System.out.println("Running testYearMonthPicker");
YearMonthPicker ymp = new YearMonthPicker();
ymp.setValue(YearMonth.of(2022, 5));
ymp.setOnAction(a -> ymp.setValue(ymp.getValue().plusMonths(1)));
Event.fireEvent(ymp, new ActionEvent());
assertEquals(YearMonth.of(2022, 6), ymp.getValue());
YearMonthPicker picker = new YearMonthPicker(YearMonth.of(2019, 1), YearMonth.of(2020, 8),
YearMonth.of(2019,12), Locale.SIMPLIFIED_CHINESE, "MMMM", "yyyy MMMM");
assertEquals(YearMonth.of(2019, 12), picker.getValue());
}
@Test
public void testYearMonthPickerCombo() {
System.out.println("Running testYearMonthPickerCombo");
YearMonthPickerCombo ympc2 = new YearMonthPickerCombo(YearMonth.now().minusYears(2),
YearMonth.now().plusYears(2), YearMonth.now(), Locale.forLanguageTag("sv-SE"), "MMMM yy");
ympc2.setOnAction(a -> ympc2.setValue(ympc2.getValue().minusYears(1)));
Event.fireEvent(ympc2, new ActionEvent());
assertEquals(YearMonth.now().minusYears(1), ympc2.getValue());
}
}
|
3e12c4924ac0916389922fe5211a78278840ea8f | 14,124 | java | Java | src/main/java/com/garowing/gameexp/game/rts/skill/constants/EffectType.java | cool112/game | 61071efa6498825f9cbcc7722420c6cd399bb3ab | [
"MIT"
] | null | null | null | src/main/java/com/garowing/gameexp/game/rts/skill/constants/EffectType.java | cool112/game | 61071efa6498825f9cbcc7722420c6cd399bb3ab | [
"MIT"
] | null | null | null | src/main/java/com/garowing/gameexp/game/rts/skill/constants/EffectType.java | cool112/game | 61071efa6498825f9cbcc7722420c6cd399bb3ab | [
"MIT"
] | null | null | null | 29.302905 | 103 | 0.757434 | 7,917 | package com.garowing.gameexp.game.rts.skill.constants;
import com.garowing.gameexp.game.rts.skill.script.effect.active.AttackBasedHealPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.ChargeIgnorePathPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.ChargePrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.CompositeEffectPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.CopyUnitPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.EnergyAddPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.InstantKillPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.KnockbackPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.ModInitEnergyPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.NormalAttackPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.NormalHarmPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.RaiseRandomDeadPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.RebirthPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.ReplaceSkillPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.SacredHarmPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.SuicidePrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.active.SummonUnitPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.aureole.DynamicEffectAureolePrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.aureole.FixEffectAureolePrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.aureole.GeneratorAureolePrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.aureole.SerialGeneratorAureolePrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.BaseAttrBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.BleedingBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.DistanceVarPtAttrBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.DizzyBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.EffectModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.EffectTargetEnergyModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.EffectTargetHpModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.EffectTargetStatusModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.EffectTargetTypeModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ExitSceneBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.FixModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.FrozenBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ImmuneEffectBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ImmuneGeneralSkillBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ImmuneSkillBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ImmuneStatusBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ImmuneStealthPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.InvincibleStatusBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.LaunchedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.PetrifactBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.PoisonBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.PretendDieBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ShieldBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.ShortCircuitBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.SkillModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.StealthBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.TimeVarPtAttrBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.UnitCountFixModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.UnitCountModifiedBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.buff.WeakBuffPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.AttackEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.BeAttackedEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.BeSkillHarmEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.BlockEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.CampCompareEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.DieEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.EnterSceneEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.KillEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.LowHpEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.OtherDieEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.SkillHarmEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.TargetChangeForceEndTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.TroopNumEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.UseCardEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.script.effect.trigger.UseGeneralSkillEffectTriggerPrototype;
import com.garowing.gameexp.game.rts.skill.template.EffectPrototype;
/**
* 效果类型
* @author seg
*
*/
public enum EffectType
{
/* =================ACTIVE(1)============== */
/**
* 普通攻击效果,带攻击判定,可以格挡、闪避、暴击
*/
NORMAL_ATTACK (EffectTopType.ACTIVE, 1, NormalAttackPrototype.class),
/**
* 普通伤害
*/
NORMAL_HARM (EffectTopType.ACTIVE, 2, NormalHarmPrototype.class),
/**
* 基于攻击力治疗
*/
ATK_BASED_HEAL (EffectTopType.ACTIVE, 3, AttackBasedHealPrototype.class),
/**
* 击退
*/
KNOCKBACK (EffectTopType.ACTIVE, 4, KnockbackPrototype.class),
/**
* 组合
*/
COMPOSITE (EffectTopType.ACTIVE, 5, CompositeEffectPrototype.class),
/**
* 增加能量
*/
ENERGY_ADD (EffectTopType.ACTIVE, 6, EnergyAddPrototype.class),
/**
* 自杀效果
*/
SUICIDE (EffectTopType.ACTIVE, 7, SuicidePrototype.class),
/**
* 技能替换效果
*/
REPLACE_SKILL (EffectTopType.ACTIVE, 8, ReplaceSkillPrototype.class),
/**
* 冲锋
*/
CHARGE (EffectTopType.ACTIVE, 9, ChargePrototype.class),
/**
* 修改初始能量点
*/
MOD_INIT_ENERGY (EffectTopType.ACTIVE, 10, ModInitEnergyPrototype.class),
/**
* 即死
*/
INSTANT_KILL (EffectTopType.ACTIVE, 11, InstantKillPrototype.class),
/**
* 神圣伤害
*/
SACRED_HARM (EffectTopType.ACTIVE, 12, SacredHarmPrototype.class),
/**
* 忽视路径冲锋
*/
CHARGE_IGNORE_PATH (EffectTopType.ACTIVE, 13, ChargeIgnorePathPrototype.class),
/* =================BUFF(2)============== */
/**
* 基础属性buff
*/
BASE_ATTR_BUFF (EffectTopType.BUFF, 1, BaseAttrBuffPrototype.class),
/**
* 时间变量buff
*/
TIME_VAR_BUFF (EffectTopType.BUFF, 2, TimeVarPtAttrBuffPrototype.class),
/**
* 距离变量buff
*/
DISTANCE_VAR_BUFF (EffectTopType.BUFF, 3, DistanceVarPtAttrBuffPrototype.class),
/**
* 眩晕buff
*/
DIZZY_BUFF (EffectTopType.BUFF, 4, DizzyBuffPrototype.class),
/**
* 中毒buff
*/
POISON_BUFF (EffectTopType.BUFF, 5, PoisonBuffPrototype.class),
/**
* 隐身buff
*/
STEALTH_BUFF (EffectTopType.BUFF, 6, StealthBuffPrototype.class),
/**
* 免疫隐身buff
*/
IMMUNE_STEALTH_BUFF (EffectTopType.BUFF, 7, ImmuneStealthPrototype.class),
/**
* 虚弱buff
*/
WEAK_BUFF (EffectTopType.BUFF, 8, WeakBuffPrototype.class),
/**
* 免疫效果buff
*/
IMMUSE_EFFECT_BUFF (EffectTopType.BUFF, 9, ImmuneEffectBuffPrototype.class),
/**
* 流血buff
*/
BLEEDING_BUFF (EffectTopType.BUFF, 10, BleedingBuffPrototype.class),
/**
* 效果修改buff
*/
EFFECT_MOD_BUFF (EffectTopType.BUFF, 11, EffectModifiedBuffPrototype.class),
/**
* 固定修正值buff
*/
FIX_MOD_BUFF (EffectTopType.BUFF, 12, FixModifiedBuffPrototype.class),
/**
* 技能修正值buff
*/
SKILL_MOD_BUFF (EffectTopType.BUFF, 13, SkillModifiedBuffPrototype.class),
/**
* 效果-目标血量修正值buff
*/
TARGET_HP_MOD_BUFF (EffectTopType.BUFF, 14, EffectTargetHpModifiedBuffPrototype.class),
/**
* 效果-目标状态修正值buff
*/
TARGET_STATUS_MOD_BUFF (EffectTopType.BUFF, 15, EffectTargetStatusModifiedBuffPrototype.class),
/**
* 效果-目标类型修正值buff
*/
TARGET_TYPE_MOD_BUFF (EffectTopType.BUFF, 16, EffectTargetTypeModifiedBuffPrototype.class),
/**
* 单位数量修正值buff
*/
UNIT_COUNT_MOD_BUFF (EffectTopType.BUFF, 17, UnitCountModifiedBuffPrototype.class),
/**
* 冰冻buff
*/
FROZEN_BUFF (EffectTopType.BUFF, 18, FrozenBuffPrototype.class),
/**
* 状态免疫buff
*/
IMMUSE_STATUS_BUFF (EffectTopType.BUFF, 19, ImmuneStatusBuffPrototype.class),
/**
* 击飞buff
*/
LAUNCHED_BUFF (EffectTopType.BUFF, 20, LaunchedBuffPrototype.class),
/**
* 石化buff
*/
PETRIFACT_BUFF (EffectTopType.BUFF, 21, PetrifactBuffPrototype.class),
/**
* 单位数量固定修正buff
*/
UNIT_COUNT_FIX_MOD_BUFF (EffectTopType.BUFF, 22, UnitCountFixModifiedBuffPrototype.class),
/**
* 短路buff
*/
SHORT_CIRCUIT_BUFF (EffectTopType.BUFF, 23, ShortCircuitBuffPrototype.class),
/**
* 护盾buff
*/
SHIELD_BUFF (EffectTopType.BUFF, 24, ShieldBuffPrototype.class),
/**
* 无敌buff
*/
INVINCIBLE_BUFF (EffectTopType.BUFF, 25, InvincibleStatusBuffPrototype.class),
/**
* 假死buff
*/
PRETEND_DIE_BUFF (EffectTopType.BUFF, 26, PretendDieBuffPrototype.class),
/**
* 离场buff
*/
EXIT_SCENE_BUFF (EffectTopType.BUFF, 27, ExitSceneBuffPrototype.class),
/**
* 目标能量点修正buff
*/
TARGET_ENERGY_BUFF (EffectTopType.BUFF, 28, EffectTargetEnergyModifiedBuffPrototype.class),
/**
* 免疫技能buff
*/
IMMUSE_SKILL_BUFF (EffectTopType.BUFF, 29, ImmuneSkillBuffPrototype.class),
/**
* 免疫将军技能buff
*/
IMMUSE_GENERAL_SKILL_BUFF(EffectTopType.BUFF, 30, ImmuneGeneralSkillBuffPrototype.class),
/* =================TRIGGER(3)============== */
/**
* 攻击触发
*/
ATTACK_TRIGGER (EffectTopType.TRIGGER, 1, AttackEffectTriggerPrototype.class),
/**
* 被攻击攻击触发
*/
BE_ATTACKED_TRIGGER (EffectTopType.TRIGGER, 2, BeAttackedEffectTriggerPrototype.class),
/**
* 死亡效果触发器
*/
DIE_TRIGGER (EffectTopType.TRIGGER, 3, DieEffectTriggerPrototype.class),
/**
* 杀死效果触发器
*/
KILL_TRIGGER (EffectTopType.TRIGGER, 4, KillEffectTriggerPrototype.class),
/**
* 进入战场效果触发器
*/
ENTER_SCENE_TRIGGER (EffectTopType.TRIGGER, 5, EnterSceneEffectTriggerPrototype.class),
/**
* 其他单位死亡
*/
OTHER_DIE_TRIGGER (EffectTopType.TRIGGER, 6, OtherDieEffectTriggerPrototype.class),
/**
* 部队数量门限
*/
TROOP_NUM_TRIGGER (EffectTopType.TRIGGER, 7, TroopNumEffectTriggerPrototype.class),
/**
* 使用卡牌
*/
USE_CARD_TRIGGER (EffectTopType.TRIGGER, 8, UseCardEffectTriggerPrototype.class),
/**
* 阵营部队数量比较
*/
CAMP_COMP_TRIGGER (EffectTopType.TRIGGER, 9, CampCompareEffectTriggerPrototype.class),
/**
* 攻击触发格挡
*/
BLOCK_TRIGGER (EffectTopType.TRIGGER, 10, BlockEffectTriggerPrototype.class),
/**
* 目标改变触发结束效果
*/
TARGET_CHANGE_END_TRIGGER(EffectTopType.TRIGGER, 11, TargetChangeForceEndTriggerPrototype.class),
/**
* 低血量触发
*/
LOW_HP_TRIGGER (EffectTopType.TRIGGER, 12, LowHpEffectTriggerPrototype.class),
/**
* 技能伤害触发
*/
SKILL_HARM_TRIGGER (EffectTopType.TRIGGER, 13, SkillHarmEffectTriggerPrototype.class),
/**
* 被技能伤害触发
*/
BE_SKILL_HARMED_TRIGGER (EffectTopType.TRIGGER, 14, BeSkillHarmEffectTriggerPrototype.class),
/**
* 使用将军技能触发
*/
GENERAL_SKILL_TRIGGER (EffectTopType.TRIGGER, 15, UseGeneralSkillEffectTriggerPrototype.class),
/* =================SUMMON(4)============== */
/**
* 基础召唤效果
*/
SUMMON (EffectTopType.SUMMON, 1, SummonUnitPrototype.class),
/**
* 随机亡灵复生
*/
RAISE_RANDOM_DEAD (EffectTopType.SUMMON, 2, RaiseRandomDeadPrototype.class),
/**
* 复制单位
*/
COPY_UNIT (EffectTopType.SUMMON, 3, CopyUnitPrototype.class),
/**
* 重生
*/
REBIRTH (EffectTopType.SUMMON, 4, RebirthPrototype.class),
/* =================AUREOLE(5)============== */
/**
* 固定效果光环
*/
FIX_EFFECT_AURE (EffectTopType.AUREOLE, 1, FixEffectAureolePrototype.class),
/**
* 动态效果光环
*/
DYNAMIC_EFFECT_AURE (EffectTopType.AUREOLE, 2, DynamicEffectAureolePrototype.class),
/**
* 效果生成器光环
*/
GENERATOR_AURE (EffectTopType.AUREOLE, 3, GeneratorAureolePrototype.class),
/**
* 序列效果生成器光环
*/
SERIAL_GENERATOR_AURE (EffectTopType.AUREOLE, 4, SerialGeneratorAureolePrototype.class);
/**
* 大类,主动-1、buff-2、触发-3
*/
private int topType;
/**
* 子id
*/
private int subId;
/**
* 编号
*/
private int code;
/**
* 实现类
*/
private Class<? extends EffectPrototype> implClass;
private EffectType(int topType, int subId, Class<? extends EffectPrototype> implClass)
{
this.topType = topType;
this.subId = subId;
this.code = topType * 1000 + subId;
this.implClass = implClass;
}
/**
* 根据id获取类型
* @param templateId
* @return
*/
public static EffectType getTypeById(int templateId)
{
EffectType[] types = EffectType.values();
for(EffectType type : types)
{
if(type.getCode() == templateId)
return type;
}
return null;
}
public int getCode()
{
return code;
}
public Class<? extends EffectPrototype> getImplClass()
{
return implClass;
}
public int getTopType()
{
return topType;
}
public int getSubId()
{
return subId;
}
}
|
3e12c5792c058bb023771c7afa4c9cda4b77cf4f | 3,292 | java | Java | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/dto/NotifyForOperationsEnum.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/dto/NotifyForOperationsEnum.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | 23 | 2021-03-23T00:01:38.000Z | 2022-01-04T16:47:34.000Z | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/dto/NotifyForOperationsEnum.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | 18.59887 | 810 | 0.796173 | 7,918 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.component.salesforce.internal.dto
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|salesforce
operator|.
name|internal
operator|.
name|dto
package|;
end_package
begin_import
import|import
name|com
operator|.
name|fasterxml
operator|.
name|jackson
operator|.
name|annotation
operator|.
name|JsonCreator
import|;
end_import
begin_import
import|import
name|com
operator|.
name|fasterxml
operator|.
name|jackson
operator|.
name|annotation
operator|.
name|JsonValue
import|;
end_import
begin_comment
comment|/** * Salesforce Enumeration DTO for picklist NotifyForOperations */
end_comment
begin_enum
DECL|enum|NotifyForOperationsEnum
specifier|public
enum|enum
name|NotifyForOperationsEnum
block|{
comment|// All
DECL|enumConstant|ALL
name|ALL
argument_list|(
literal|"All"
argument_list|)
block|,
comment|// Create
DECL|enumConstant|CREATE
name|CREATE
argument_list|(
literal|"Create"
argument_list|)
block|,
comment|// Extended
DECL|enumConstant|EXTENDED
name|EXTENDED
argument_list|(
literal|"Extended"
argument_list|)
block|,
comment|// Update
DECL|enumConstant|UPDATE
name|UPDATE
argument_list|(
literal|"Update"
argument_list|)
block|;
DECL|field|value
specifier|final
name|String
name|value
decl_stmt|;
DECL|method|NotifyForOperationsEnum (String value)
name|NotifyForOperationsEnum
parameter_list|(
name|String
name|value
parameter_list|)
block|{
name|this
operator|.
name|value
operator|=
name|value
expr_stmt|;
block|}
annotation|@
name|JsonValue
DECL|method|value ()
specifier|public
name|String
name|value
parameter_list|()
block|{
return|return
name|this
operator|.
name|value
return|;
block|}
annotation|@
name|JsonCreator
DECL|method|forValue (String value)
specifier|public
specifier|static
name|NotifyForOperationsEnum
name|forValue
parameter_list|(
name|String
name|value
parameter_list|)
block|{
for|for
control|(
name|NotifyForOperationsEnum
name|e
range|:
name|NotifyForOperationsEnum
operator|.
name|values
argument_list|()
control|)
block|{
if|if
condition|(
name|e
operator|.
name|value
operator|.
name|equals
argument_list|(
name|value
argument_list|)
condition|)
block|{
return|return
name|e
return|;
block|}
block|}
throw|throw
operator|new
name|IllegalArgumentException
argument_list|(
name|value
argument_list|)
throw|;
block|}
block|}
end_enum
end_unit
|
3e12c57af83eddb526369ff617e05fe71b9b4b68 | 320 | java | Java | android-query/src/androidTest/java/net/frju/androidquery/integration/models/Log.java | FredJul/AndroidQuery | 377fa32a147c09085070f025bb4e824f539faa57 | [
"Apache-2.0"
] | 23 | 2016-11-26T23:21:40.000Z | 2020-12-06T14:13:51.000Z | android-query/src/androidTest/java/net/frju/androidquery/integration/models/Log.java | FredJul/AndroidQuery | 377fa32a147c09085070f025bb4e824f539faa57 | [
"Apache-2.0"
] | 1 | 2017-02-13T10:58:31.000Z | 2017-02-13T15:22:13.000Z | android-query/src/androidTest/java/net/frju/androidquery/integration/models/Log.java | FredJul/AndroidQuery | 377fa32a147c09085070f025bb4e824f539faa57 | [
"Apache-2.0"
] | 7 | 2016-12-05T04:52:04.000Z | 2022-03-12T18:58:09.000Z | 24.615385 | 56 | 0.778125 | 7,919 | package net.frju.androidquery.integration.models;
import net.frju.androidquery.annotation.DbField;
import net.frju.androidquery.annotation.DbModel;
@DbModel(databaseProvider = LocalDatabaseProvider.class)
public class Log {
@DbField(primaryKey = true)
public long id;
@DbField
public long timestamp;
}
|
3e12c5d0b5dcb4f82e980ea770ea0e88f87f5563 | 4,418 | java | Java | BluetoothChat/Application/src/main/java/com/example/android/bluetoothchat/WrapperIntentService.java | xu6148152/binea_project | 3288eb96bca4cb2297abfecca70248841015acf8 | [
"MIT"
] | null | null | null | BluetoothChat/Application/src/main/java/com/example/android/bluetoothchat/WrapperIntentService.java | xu6148152/binea_project | 3288eb96bca4cb2297abfecca70248841015acf8 | [
"MIT"
] | null | null | null | BluetoothChat/Application/src/main/java/com/example/android/bluetoothchat/WrapperIntentService.java | xu6148152/binea_project | 3288eb96bca4cb2297abfecca70248841015acf8 | [
"MIT"
] | null | null | null | 32.725926 | 86 | 0.665007 | 7,920 | package com.example.android.bluetoothchat;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
/**
* Created by xubinggui on 8/3/15.
*/
public abstract class WrapperIntentService extends Service {
protected static final String TAG = WrapperIntentService.class.getSimpleName();
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public WrapperIntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see Service#onBind
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
protected abstract void onHandleIntent(Intent intent);
public void clearQueue() {
Log.i(TAG, "All requests removed from queue");
mServiceHandler.removeMessages(0);
}
}
|
3e12c791aae40ce76439198d4481c9efbf749fd7 | 1,362 | java | Java | hzq-system/src/main/java/com/hzq/system/service/impl/SysLogininforServiceImpl.java | huangzhiqiang653/hzq-springboot | def65ec64fe88e63dea95facadabdf49d2d95e95 | [
"MIT"
] | null | null | null | hzq-system/src/main/java/com/hzq/system/service/impl/SysLogininforServiceImpl.java | huangzhiqiang653/hzq-springboot | def65ec64fe88e63dea95facadabdf49d2d95e95 | [
"MIT"
] | null | null | null | hzq-system/src/main/java/com/hzq/system/service/impl/SysLogininforServiceImpl.java | huangzhiqiang653/hzq-springboot | def65ec64fe88e63dea95facadabdf49d2d95e95 | [
"MIT"
] | null | null | null | 21.619048 | 79 | 0.685022 | 7,921 | package com.hzq.system.service.impl;
import com.hzq.common.support.Convert;
import com.hzq.system.domain.SysLogininfor;
import com.hzq.system.mapper.SysLogininforMapper;
import com.hzq.system.service.ISysLogininforService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* 系统访问日志情况信息 服务层处理
*
* @author 黄智强
*/
@Service
public class SysLogininforServiceImpl implements ISysLogininforService {
@Resource
private SysLogininforMapper logininforMapper;
/**
* 新增系统登录日志
*
* @param logininfor 访问日志对象
*/
@Override
public void insertLogininfor(SysLogininfor logininfor) {
logininforMapper.insertLogininfor(logininfor);
}
/**
* 查询系统登录日志集合
*
* @param logininfor 访问日志对象
* @return 登录记录集合
*/
@Override
public List<SysLogininfor> selectLogininforList(SysLogininfor logininfor) {
return logininforMapper.selectLogininforList(logininfor);
}
/**
* 批量删除系统登录日志
*
* @param ids 需要删除的数据
* @return
*/
@Override
public int deleteLogininforByIds(String ids) {
return logininforMapper.deleteLogininforByIds(Convert.toStrArray(ids));
}
/**
* 清空系统登录日志
*/
@Override
public void cleanLogininfor() {
logininforMapper.cleanLogininfor();
}
}
|
3e12c792936b560633519123d1a1729d604ebbb8 | 758 | java | Java | src/main/java/slimeknights/tconstruct/smeltery/block/BlockTinkerFluid.java | dujinhuachinaeddie/tkc | 6117b171ca30c00d6bf505d4fde93d5a59e28403 | [
"MIT"
] | null | null | null | src/main/java/slimeknights/tconstruct/smeltery/block/BlockTinkerFluid.java | dujinhuachinaeddie/tkc | 6117b171ca30c00d6bf505d4fde93d5a59e28403 | [
"MIT"
] | null | null | null | src/main/java/slimeknights/tconstruct/smeltery/block/BlockTinkerFluid.java | dujinhuachinaeddie/tkc | 6117b171ca30c00d6bf505d4fde93d5a59e28403 | [
"MIT"
] | null | null | null | 25.266667 | 59 | 0.778364 | 7,922 | package slimeknights.tconstruct.smeltery.block;
import net.minecraft.block.material.Material;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import javax.annotation.Nonnull;
import slimeknights.tconstruct.library.TinkerRegistry;
public class BlockTinkerFluid extends BlockFluidClassic {
public BlockTinkerFluid(Fluid fluid, Material material) {
super(fluid, material);
setCreativeTab(TinkerRegistry.tabSmeltery);
}
@Nonnull
@Override
public String getUnlocalizedName() {
Fluid fluid = FluidRegistry.getFluid(fluidName);
if(fluid != null) {
return fluid.getUnlocalizedName();
}
return super.getUnlocalizedName();
}
}
|
3e12c933c92a4ac4d2c865650ee6b90fba193648 | 7,664 | java | Java | prince-of-versions/src/main/java/co/infinum/princeofversions/PrinceOfVersionsConfig.java | stephen-moon/Android-Prince-of-Versions | 1a56b41150400cf5dd2863503701bc5a37777871 | [
"Apache-2.0"
] | null | null | null | prince-of-versions/src/main/java/co/infinum/princeofversions/PrinceOfVersionsConfig.java | stephen-moon/Android-Prince-of-Versions | 1a56b41150400cf5dd2863503701bc5a37777871 | [
"Apache-2.0"
] | null | null | null | prince-of-versions/src/main/java/co/infinum/princeofversions/PrinceOfVersionsConfig.java | stephen-moon/Android-Prince-of-Versions | 1a56b41150400cf5dd2863503701bc5a37777871 | [
"Apache-2.0"
] | null | null | null | 28.490706 | 138 | 0.579201 | 7,923 | package co.infinum.princeofversions;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This class holds loaded data from config resource.
*/
public final class PrinceOfVersionsConfig {
/**
* Mandatory version
*/
@Nullable
private final Version mandatoryVersion;
/**
* Optional version
*/
@Nullable
private final Version optionalVersion;
/**
* Notification type
*/
private final NotificationType optionalNotificationType;
/**
* Metadata of the update configuration
*/
private final Map<String, String> metadata;
PrinceOfVersionsConfig(
@Nullable String mandatoryVersion,
int mandatoryMinSdk,
@Nullable String optionalVersion,
int optionalMinSdk,
@Nonnull NotificationType optionalNotificationType,
@Nonnull Map<String, String> metadata) {
this.mandatoryVersion = (mandatoryVersion != null && mandatoryMinSdk > 0) ? new Version(mandatoryVersion, mandatoryMinSdk) : null;
this.optionalVersion = (optionalVersion != null && optionalMinSdk > 0) ? new Version(optionalVersion, optionalMinSdk) : null;
this.optionalNotificationType = optionalNotificationType;
this.metadata = metadata;
}
@Nullable
Version getMandatoryVersion() {
return mandatoryVersion;
}
@Nullable
Version getOptionalVersion() {
return optionalVersion;
}
NotificationType getOptionalNotificationType() {
return optionalNotificationType;
}
Map<String, String> getMetadata() {
return metadata;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PrinceOfVersionsConfig)) {
return false;
}
final PrinceOfVersionsConfig that = (PrinceOfVersionsConfig) o;
if (getMandatoryVersion() != null ? !getMandatoryVersion().equals(that.getMandatoryVersion())
: that.getMandatoryVersion() != null) {
return false;
}
if (getOptionalVersion() != null ? !getOptionalVersion().equals(that.getOptionalVersion()) : that.getOptionalVersion() != null) {
return false;
}
if (getOptionalNotificationType() != that.getOptionalNotificationType()) {
return false;
}
return getMetadata().equals(that.getMetadata());
}
@Override
public int hashCode() {
int result = getMandatoryVersion() != null ? getMandatoryVersion().hashCode() : 0;
result = 31 * result + (getOptionalVersion() != null ? getOptionalVersion().hashCode() : 0);
result = 31 * result + getOptionalNotificationType().hashCode();
result = 31 * result + getMetadata().hashCode();
return result;
}
@Override
public String toString() {
return "PrinceOfVersionsConfig{"
+ "mandatoryVersion=" + mandatoryVersion
+ ", optionalVersion=" + optionalVersion
+ ", optionalNotificationType=" + optionalNotificationType
+ ", metadata=" + metadata
+ '}';
}
static class Version {
/**
* Version string
*/
private final String version;
/**
* MinSdk for update
*/
private final int minSdk;
Version(final String version, final int minSdk) {
this.version = version;
this.minSdk = minSdk;
}
String getVersion() {
return version;
}
int getMinSdk() {
return minSdk;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Version)) {
return false;
}
final Version version1 = (Version) o;
if (getMinSdk() != version1.getMinSdk()) {
return false;
}
return getVersion().equals(version1.getVersion());
}
@Override
public int hashCode() {
int result = getVersion().hashCode();
result = 31 * result + getMinSdk();
return result;
}
@Override
public String toString() {
return "Version{"
+ "version='" + version + '\''
+ ", minSdk=" + minSdk
+ '}';
}
}
/**
* Builds a new {@link PrinceOfVersionsConfig}.
* All methods are optional.
*/
public static class Builder {
@Nullable
private String mandatoryVersion;
private int mandatoryMinSdk = 1;
@Nullable
private String optionalVersion;
private int optionalMinSdk = 1;
@Nullable
private NotificationType optionalNotificationType;
@Nullable
private Map<String, String> metadata;
public Builder() {
}
/**
* Set a new mandatory version string.
* @param mandatoryVersion Mandatory version name
* @return this builder
*/
public Builder withMandatoryVersion(String mandatoryVersion) {
this.mandatoryVersion = mandatoryVersion;
return this;
}
/**
* Set a new minSdk value of mandatory app version.
* @param mandatoryMinSdk MinSdk value of mandatory app version
* @return this builder
*/
public Builder withMandatoryMinSdk(int mandatoryMinSdk) {
this.mandatoryMinSdk = mandatoryMinSdk;
return this;
}
/**
* Set a new optional version string.
* @param optionalVersion Optional version name
* @return this builder
*/
public Builder withOptionalVersion(String optionalVersion) {
this.optionalVersion = optionalVersion;
return this;
}
/**
* Set a new minSdk value of optional app version.
* @param optionalMinSdk MinSdk value of optional app version
* @return this builder
*/
public Builder withOptionalMinSdk(int optionalMinSdk) {
this.optionalMinSdk = optionalMinSdk;
return this;
}
/**
* Set a new notification type of optional update.
* @param optionalNotificationType Notification type
* @return this builder
*/
public Builder withOptionalNotificationType(NotificationType optionalNotificationType) {
this.optionalNotificationType = optionalNotificationType;
return this;
}
/**
* Set new metadata about the update.
* @param metadata String to string map
* @return this builder
*/
public Builder withMetadata(Map<String, String> metadata) {
this.metadata = metadata;
return this;
}
/**
* Create the {@link PrinceOfVersionsConfig} instance using the configured values.
* @return A new {@link PrinceOfVersionsConfig} instance
*/
public PrinceOfVersionsConfig build() {
return new PrinceOfVersionsConfig(
mandatoryVersion,
mandatoryMinSdk,
optionalVersion,
optionalMinSdk,
optionalNotificationType != null ? optionalNotificationType : NotificationType.ONCE,
metadata != null ? metadata : new HashMap<String, String>());
}
}
}
|
3e12ca6c639e466741eb498162a7d53d7b52ac85 | 740 | java | Java | src/main/java/net/lightbody/bmp/core/har/HarNameVersion.java | datasift/browsermob-proxy | 3c9ae8f40afbf151aeac57d52670f3258b41ad31 | [
"Apache-2.0"
] | 1 | 2019-04-24T15:35:58.000Z | 2019-04-24T15:35:58.000Z | src/main/java/net/lightbody/bmp/core/har/HarNameVersion.java | iandow/browsermob-proxy | d1931452dc50f985d924ded7cc8f535b336142e3 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/lightbody/bmp/core/har/HarNameVersion.java | iandow/browsermob-proxy | d1931452dc50f985d924ded7cc8f535b336142e3 | [
"Apache-2.0"
] | null | null | null | 18.5 | 56 | 0.6 | 7,924 | package net.lightbody.bmp.core.har;
public class HarNameVersion {
private String name;
private String version;
private String comment = "";
public HarNameVersion() {
}
public HarNameVersion(String name, String version) {
this.name = name;
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
|
3e12cafc22b8efcb216ac27579a98cc4071582a3 | 1,842 | java | Java | src/main/java/Calculator.java | maciek1651g/CurrencyCalculator | e051e63ad5be3182b028b6d9e742d1f2ae8773ed | [
"MIT"
] | null | null | null | src/main/java/Calculator.java | maciek1651g/CurrencyCalculator | e051e63ad5be3182b028b6d9e742d1f2ae8773ed | [
"MIT"
] | null | null | null | src/main/java/Calculator.java | maciek1651g/CurrencyCalculator | e051e63ad5be3182b028b6d9e742d1f2ae8773ed | [
"MIT"
] | null | null | null | 39.191489 | 160 | 0.686754 | 7,925 | import java.math.BigDecimal;
import java.util.Currency;
import java.util.InputMismatchException;
import java.util.Optional;
import java.util.Scanner;
public class Calculator {
private final static String DEFAULT_CURRENCY = "EUR";
private final static String FILEPATH = "eurofxref-daily.xml";
public static void main(String[] args) {
final ExchangeRateXMLParser exchangeRateXMLParser = new ExchangeRateXMLParser(FILEPATH);
final Optional<CurrencyExchangeRate> currencyExchangeRate = exchangeRateXMLParser.parseCurrencyExchangeRates();
if(!currencyExchangeRate.isPresent()) {
System.out.println("Could Not Read Data From File!");
}
final CurrencyCalculator currencyCalculator = new CurrencyCalculator(currencyExchangeRate.get());
try {
final Scanner scanner = new Scanner(System.in);
System.out.print("Provide value to convert("+DEFAULT_CURRENCY+"): ");
final double source = scanner.nextDouble();
System.out.print("Provide target currency: ");
final String targetCurrency = scanner.next();
final Currency currency = Currency.getInstance(targetCurrency.toUpperCase());
final Money converted = currencyCalculator.convertCurrency(new Money(BigDecimal.valueOf(source), Currency.getInstance(DEFAULT_CURRENCY)), currency);
System.out.println("Calculated value: " + converted.value() + " " + converted.currency().getCurrencyCode());
} catch(CurrencyNotFoundException e) {
System.out.println("Currency Not Found!");
} catch (IllegalArgumentException e) {
System.out.println("Invalid Currency Provided!");
} catch (InputMismatchException e) {
System.out.println("Invalid Input Data Format!");
}
}
}
|
3e12cb637b9a801247f802f0b8a1e805303837e1 | 22,608 | java | Java | common/java/apps/org/klomp/snark/ExtensionHandler.java | mhatta/Nightweb | b6e58eec6722dfb9df0e3de2de600c222729c96b | [
"Unlicense"
] | 10 | 2018-10-25T13:42:00.000Z | 2019-02-03T17:38:48.000Z | common/java/apps/org/klomp/snark/ExtensionHandler.java | mhatta/Nightweb | b6e58eec6722dfb9df0e3de2de600c222729c96b | [
"Unlicense"
] | null | null | null | common/java/apps/org/klomp/snark/ExtensionHandler.java | mhatta/Nightweb | b6e58eec6722dfb9df0e3de2de600c222729c96b | [
"Unlicense"
] | null | null | null | 40.661871 | 139 | 0.526318 | 7,926 | package org.klomp.snark;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.util.Log;
import org.klomp.snark.bencode.BDecoder;
import org.klomp.snark.bencode.BEncoder;
import org.klomp.snark.bencode.BEValue;
import org.klomp.snark.comments.Comment;
import org.klomp.snark.comments.CommentSet;
/**
* REF: BEP 10 Extension Protocol
* @since 0.8.2
* @author zzz
*/
abstract class ExtensionHandler {
public static final int ID_HANDSHAKE = 0;
public static final int ID_METADATA = 1;
public static final String TYPE_METADATA = "ut_metadata";
public static final int ID_PEX = 2;
/** not ut_pex since the compact format is different */
public static final String TYPE_PEX = "i2p_pex";
public static final int ID_DHT = 3;
/** not using the option bit since the compact format is different */
public static final String TYPE_DHT = "i2p_dht";
/** @since 0.9.31 */
public static final int ID_COMMENT = 4;
/** @since 0.9.31 */
public static final String TYPE_COMMENT = "ut_comment";
/** Pieces * SHA1 Hash length, + 25% extra for file names, bencoding overhead, etc */
private static final int MAX_METADATA_SIZE = Storage.MAX_PIECES * 20 * 5 / 4;
private static final int PARALLEL_REQUESTS = 3;
/**
* @param metasize -1 if unknown
* @param pexAndMetadata advertise these capabilities
* @param dht advertise DHT capability
* @param comment advertise ut_comment capability
* @return bencoded outgoing handshake message
*/
public static byte[] getHandshake(int metasize, boolean pexAndMetadata, boolean dht, boolean uploadOnly, boolean comment) {
Map<String, Object> handshake = new HashMap<String, Object>();
Map<String, Integer> m = new HashMap<String, Integer>();
if (pexAndMetadata) {
m.put(TYPE_METADATA, Integer.valueOf(ID_METADATA));
m.put(TYPE_PEX, Integer.valueOf(ID_PEX));
if (metasize >= 0)
handshake.put("metadata_size", Integer.valueOf(metasize));
}
if (dht) {
m.put(TYPE_DHT, Integer.valueOf(ID_DHT));
}
if (comment) {
m.put(TYPE_COMMENT, Integer.valueOf(ID_COMMENT));
}
// include the map even if empty so the far-end doesn't NPE
handshake.put("m", m);
handshake.put("p", Integer.valueOf(TrackerClient.PORT));
handshake.put("v", "I2PSnark");
handshake.put("reqq", Integer.valueOf(5));
// BEP 21
if (uploadOnly)
handshake.put("upload_only", Integer.valueOf(1));
return BEncoder.bencode(handshake);
}
public static void handleMessage(Peer peer, PeerListener listener, int id, byte[] bs) {
Log log = I2PAppContext.getGlobalContext().logManager().getLog(ExtensionHandler.class);
if (log.shouldLog(Log.INFO))
log.info("Got extension msg " + id + " length " + bs.length + " from " + peer);
if (id == ID_HANDSHAKE)
handleHandshake(peer, listener, bs, log);
else if (id == ID_METADATA)
handleMetadata(peer, listener, bs, log);
else if (id == ID_PEX)
handlePEX(peer, listener, bs, log);
else if (id == ID_DHT)
handleDHT(peer, listener, bs, log);
else if (id == ID_COMMENT)
handleComment(peer, listener, bs, log);
else if (log.shouldLog(Log.INFO))
log.info("Unknown extension msg " + id + " from " + peer);
}
private static void handleHandshake(Peer peer, PeerListener listener, byte[] bs, Log log) {
if (log.shouldLog(Log.DEBUG))
log.debug("Got handshake msg from " + peer);
try {
// this throws NPE on missing keys
InputStream is = new ByteArrayInputStream(bs);
BDecoder dec = new BDecoder(is);
BEValue bev = dec.bdecodeMap();
Map<String, BEValue> map = bev.getMap();
peer.setHandshakeMap(map);
Map<String, BEValue> msgmap = map.get("m").getMap();
if (log.shouldLog(Log.DEBUG))
log.debug("Peer " + peer + " supports extensions: " + msgmap.keySet());
//if (msgmap.get(TYPE_PEX) != null) {
// if (log.shouldLog(Log.DEBUG))
// log.debug("Peer supports PEX extension: " + peer);
// // peer state calls peer listener calls sendPEX()
//}
//if (msgmap.get(TYPE_DHT) != null) {
// if (log.shouldLog(Log.DEBUG))
// log.debug("Peer supports DHT extension: " + peer);
// // peer state calls peer listener calls sendDHT()
//}
MagnetState state = peer.getMagnetState();
if (msgmap.get(TYPE_METADATA) == null) {
if (log.shouldLog(Log.DEBUG))
log.debug("Peer does not support metadata extension: " + peer);
// drop if we need metainfo and we haven't found anybody yet
synchronized(state) {
if (!state.isInitialized()) {
if (log.shouldLog(Log.DEBUG))
log.debug("Dropping peer, we need metadata! " + peer);
peer.disconnect();
}
}
return;
}
BEValue msize = map.get("metadata_size");
if (msize == null) {
if (log.shouldLog(Log.DEBUG))
log.debug("Peer does not have the metainfo size yet: " + peer);
// drop if we need metainfo and we haven't found anybody yet
synchronized(state) {
if (!state.isInitialized()) {
if (log.shouldLog(Log.DEBUG))
log.debug("Dropping peer, we need metadata! " + peer);
peer.disconnect();
}
}
return;
}
int metaSize = msize.getInt();
if (log.shouldLog(Log.DEBUG))
log.debug("Got the metainfo size: " + metaSize);
int remaining;
synchronized(state) {
if (state.isComplete())
return;
if (state.isInitialized()) {
if (state.getSize() != metaSize) {
if (log.shouldLog(Log.DEBUG))
log.debug("Wrong metainfo size " + metaSize + " from: " + peer);
peer.disconnect();
return;
}
} else {
// initialize it
if (metaSize > MAX_METADATA_SIZE) {
if (log.shouldLog(Log.DEBUG))
log.debug("Huge metainfo size " + metaSize + " from: " + peer);
peer.disconnect(false);
return;
}
if (log.shouldLog(Log.INFO))
log.info("Initialized state, metadata size = " + metaSize + " from " + peer);
state.initialize(metaSize);
}
remaining = state.chunksRemaining();
}
// send requests for chunks
int count = Math.min(remaining, PARALLEL_REQUESTS);
for (int i = 0; i < count; i++) {
int chk;
synchronized(state) {
chk = state.getNextRequest();
}
if (log.shouldLog(Log.INFO))
log.info("Request chunk " + chk + " from " + peer);
sendRequest(peer, chk);
}
} catch (Exception e) {
if (log.shouldLog(Log.WARN))
log.warn("Handshake exception from " + peer, e);
}
}
private static final int TYPE_REQUEST = 0;
private static final int TYPE_DATA = 1;
private static final int TYPE_REJECT = 2;
/**
* REF: BEP 9
* @since 0.8.4
*/
private static void handleMetadata(Peer peer, PeerListener listener, byte[] bs, Log log) {
if (log.shouldLog(Log.DEBUG))
log.debug("Got metadata msg from " + peer);
try {
InputStream is = new ByteArrayInputStream(bs);
BDecoder dec = new BDecoder(is);
BEValue bev = dec.bdecodeMap();
Map<String, BEValue> map = bev.getMap();
int type = map.get("msg_type").getInt();
int piece = map.get("piece").getInt();
MagnetState state = peer.getMagnetState();
if (type == TYPE_REQUEST) {
if (log.shouldLog(Log.DEBUG))
log.debug("Got request for " + piece + " from: " + peer);
byte[] pc;
int totalSize;
synchronized(state) {
pc = state.getChunk(piece);
totalSize = state.getSize();
}
sendPiece(peer, piece, pc, totalSize);
// Do this here because PeerConnectionOut only reports for PIECE messages
peer.uploaded(pc.length);
listener.uploaded(peer, pc.length);
} else if (type == TYPE_DATA) {
// On close reading of BEP 9, this is the total metadata size.
// Prior to 0.9.21, we sent the piece size, so we can't count on it.
// just ignore it. The actual length will be verified in saveChunk()
//int size = map.get("total_size").getInt();
//if (log.shouldLog(Log.DEBUG))
// log.debug("Got data for " + piece + " length " + size + " from: " + peer);
boolean done;
int chk = -1;
synchronized(state) {
if (state.isComplete())
return;
int len = is.available();
peer.downloaded(len);
listener.downloaded(peer, len);
// this checks the size
done = state.saveChunk(piece, bs, bs.length - len, len);
if (log.shouldLog(Log.INFO))
log.info("Got chunk " + piece + " from " + peer);
if (!done)
chk = state.getNextRequest();
}
// out of the lock
if (done) {
// Done!
// PeerState will call the listener (peer coord), who will
// check to see if the MagnetState has it
if (log.shouldLog(Log.WARN))
log.warn("Got last chunk from " + peer);
} else {
// get the next chunk
if (log.shouldLog(Log.INFO))
log.info("Request chunk " + chk + " from " + peer);
sendRequest(peer, chk);
}
} else if (type == TYPE_REJECT) {
if (log.shouldLog(Log.WARN))
log.warn("Got reject msg from " + peer);
peer.disconnect(false);
} else {
if (log.shouldLog(Log.WARN))
log.warn("Got unknown metadata msg from " + peer);
peer.disconnect(false);
}
} catch (Exception e) {
if (log.shouldLog(Log.INFO))
log.info("Metadata ext. msg. exception from " + peer, e);
// fatal ?
peer.disconnect(false);
}
}
private static void sendRequest(Peer peer, int piece) {
sendMessage(peer, TYPE_REQUEST, piece);
}
/****
private static void sendReject(Peer peer, int piece) {
sendMessage(peer, TYPE_REJECT, piece);
}
****/
/** REQUEST and REJECT are the same except for message type */
private static void sendMessage(Peer peer, int type, int piece) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("msg_type", Integer.valueOf(type));
map.put("piece", Integer.valueOf(piece));
byte[] payload = BEncoder.bencode(map);
try {
int hisMsgCode = peer.getHandshakeMap().get("m").getMap().get(TYPE_METADATA).getInt();
peer.sendExtension(hisMsgCode, payload);
} catch (Exception e) {
// NPE, no metadata capability
//if (log.shouldLog(Log.INFO))
// log.info("Metadata send req msg exception to " + peer, e);
}
}
private static void sendPiece(Peer peer, int piece, byte[] data, int totalSize) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("msg_type", Integer.valueOf(TYPE_DATA));
map.put("piece", Integer.valueOf(piece));
// BEP 9
// "This key has the same semantics as the 'metadata_size' in the extension header"
// which apparently means the same value. Fixed in 0.9.21.
//map.put("total_size", Integer.valueOf(data.length));
map.put("total_size", Integer.valueOf(totalSize));
byte[] dict = BEncoder.bencode(map);
byte[] payload = new byte[dict.length + data.length];
System.arraycopy(dict, 0, payload, 0, dict.length);
System.arraycopy(data, 0, payload, dict.length, data.length);
try {
int hisMsgCode = peer.getHandshakeMap().get("m").getMap().get(TYPE_METADATA).getInt();
peer.sendExtension(hisMsgCode, payload);
} catch (Exception e) {
// NPE, no metadata caps
//if (log.shouldLog(Log.INFO))
// log.info("Metadata send piece msg exception to " + peer, e);
}
}
private static final int HASH_LENGTH = 32;
/**
* Can't find a published standard for this anywhere.
* See the libtorrent code.
* Here we use the "added" key as a single string of concatenated
* 32-byte peer hashes.
* added.f and dropped unsupported
* @since 0.8.4
*/
private static void handlePEX(Peer peer, PeerListener listener, byte[] bs, Log log) {
if (log.shouldLog(Log.DEBUG))
log.debug("Got PEX msg from " + peer);
try {
InputStream is = new ByteArrayInputStream(bs);
BDecoder dec = new BDecoder(is);
BEValue bev = dec.bdecodeMap();
Map<String, BEValue> map = bev.getMap();
bev = map.get("added");
if (bev == null)
return;
byte[] ids = bev.getBytes();
if (ids.length < HASH_LENGTH)
return;
int len = Math.min(ids.length, (I2PSnarkUtil.MAX_CONNECTIONS - 1) * HASH_LENGTH);
List<PeerID> peers = new ArrayList<PeerID>(len / HASH_LENGTH);
for (int off = 0; off < len; off += HASH_LENGTH) {
byte[] hash = new byte[HASH_LENGTH];
System.arraycopy(ids, off, hash, 0, HASH_LENGTH);
if (DataHelper.eq(hash, peer.getPeerID().getDestHash()))
continue;
PeerID pID = new PeerID(hash, listener.getUtil());
peers.add(pID);
}
// could include ourselves, listener must remove
listener.gotPeers(peer, peers);
} catch (Exception e) {
if (log.shouldLog(Log.INFO))
log.info("PEX msg exception from " + peer, e);
//peer.disconnect(false);
}
}
/**
* Receive the DHT port numbers
* @since DHT
*/
private static void handleDHT(Peer peer, PeerListener listener, byte[] bs, Log log) {
if (log.shouldLog(Log.DEBUG))
log.debug("Got DHT msg from " + peer);
try {
InputStream is = new ByteArrayInputStream(bs);
BDecoder dec = new BDecoder(is);
BEValue bev = dec.bdecodeMap();
Map<String, BEValue> map = bev.getMap();
int qport = map.get("port").getInt();
int rport = map.get("rport").getInt();
listener.gotPort(peer, qport, rport);
} catch (Exception e) {
if (log.shouldLog(Log.INFO))
log.info("DHT msg exception from " + peer, e);
//peer.disconnect(false);
}
}
/**
* added.f and dropped unsupported
* @param pList non-null
* @since 0.8.4
*/
public static void sendPEX(Peer peer, List<Peer> pList) {
if (pList.isEmpty())
return;
Map<String, Object> map = new HashMap<String, Object>();
byte[] peers = new byte[HASH_LENGTH * pList.size()];
int off = 0;
for (Peer p : pList) {
System.arraycopy(p.getPeerID().getDestHash(), 0, peers, off, HASH_LENGTH);
off += HASH_LENGTH;
}
map.put("added", peers);
byte[] payload = BEncoder.bencode(map);
try {
int hisMsgCode = peer.getHandshakeMap().get("m").getMap().get(TYPE_PEX).getInt();
peer.sendExtension(hisMsgCode, payload);
} catch (Exception e) {
// NPE, no PEX caps
//if (log.shouldLog(Log.INFO))
// log.info("PEX msg exception to " + peer, e);
}
}
/**
* Send the DHT port numbers
* @since DHT
*/
public static void sendDHT(Peer peer, int qport, int rport) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("port", Integer.valueOf(qport));
map.put("rport", Integer.valueOf(rport));
byte[] payload = BEncoder.bencode(map);
try {
int hisMsgCode = peer.getHandshakeMap().get("m").getMap().get(TYPE_DHT).getInt();
peer.sendExtension(hisMsgCode, payload);
} catch (Exception e) {
// NPE, no DHT caps
//if (log.shouldLog(Log.INFO))
// log.info("DHT msg exception to " + peer, e);
}
}
/**
* Handle comment request and response
*
* Ref: https://blinkenlights.ch/ccms/software/bittorrent.html
* Ref: https://github.com/adrian-bl/bitflu/blob/3cb7fe887dbdea8132e4fa36fbbf5f26cf992db3/plugins/Bitflu/20_DownloadBitTorrent.pm#L3403
* @since 0.9.31
*/
private static void handleComment(Peer peer, PeerListener listener, byte[] bs, Log log) {
if (log.shouldLog(Log.DEBUG))
log.debug("Got comment msg from " + peer);
try {
InputStream is = new ByteArrayInputStream(bs);
BDecoder dec = new BDecoder(is);
BEValue bev = dec.bdecodeMap();
Map<String, BEValue> map = bev.getMap();
int type = map.get("msg_type").getInt();
if (type == 0) {
// request
int num = 20;
BEValue b = map.get("num");
if (b != null)
num = b.getInt();
listener.gotCommentReq(peer, num);
} else if (type == 1) {
// response
List<BEValue> list = map.get("comments").getList();
if (list.isEmpty())
return;
List<Comment> comments = new ArrayList<Comment>(list.size());
long now = I2PAppContext.getGlobalContext().clock().now();
for (BEValue li : list) {
Map<String, BEValue> m = li.getMap();
String owner = m.get("owner").getString();
String text = m.get("text").getString();
// 0-5 range for rating is enforced by Comment constructor
int rating = m.get("like").getInt();
long time = now - (Math.max(0, m.get("timestamp").getInt()) * 1000L);
Comment c = new Comment(text, owner, rating, time, false);
comments.add(c);
}
listener.gotComments(peer, comments);
} else {
if (log.shouldLog(Log.INFO))
log.info("Unknown comment msg type " + type + " from " + peer);
}
} catch (Exception e) {
if (log.shouldLog(Log.INFO))
log.info("Comment msg exception from " + peer, e);
//peer.disconnect(false);
}
}
private static final byte[] COMMENTS_FILTER = new byte[64];
/**
* Send comment request
* @since 0.9.31
*/
public static void sendCommentReq(Peer peer, int num) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("msg_type", Integer.valueOf(0));
map.put("num", Integer.valueOf(num));
map.put("filter", COMMENTS_FILTER);
byte[] payload = BEncoder.bencode(map);
try {
int hisMsgCode = peer.getHandshakeMap().get("m").getMap().get(TYPE_COMMENT).getInt();
peer.sendExtension(hisMsgCode, payload);
} catch (Exception e) {
// NPE, no caps
}
}
/**
* Send comments
* Caller must sync on comments
* @param num max to send
* @param comments non-null
* @since 0.9.31
*/
public static void locked_sendComments(Peer peer, int num, CommentSet comments) {
int toSend = Math.min(num, comments.size());
if (toSend <= 0)
return;
Map<String, Object> map = new HashMap<String, Object>();
map.put("msg_type", Integer.valueOf(1));
List<Object> lc = new ArrayList<Object>(toSend);
long now = I2PAppContext.getGlobalContext().clock().now();
int i = 0;
for (Comment c : comments) {
if (i++ >= toSend)
break;
Map<String, Object> mc = new HashMap<String, Object>();
String s = c.getName();
mc.put("owner", s != null ? s : "");
s = c.getText();
mc.put("text", s != null ? s : "");
mc.put("like", Integer.valueOf(c.getRating()));
mc.put("timestamp", Long.valueOf((now - c.getTime()) / 1000L));
lc.add(mc);
}
map.put("comments", lc);
byte[] payload = BEncoder.bencode(map);
try {
int hisMsgCode = peer.getHandshakeMap().get("m").getMap().get(TYPE_COMMENT).getInt();
peer.sendExtension(hisMsgCode, payload);
} catch (Exception e) {
// NPE, no caps
}
}
}
|
3e12cb7c46ae5d2d4d48914a1feb2251805b9f42 | 3,494 | java | Java | app/src/main/java/org/projectbuendia/client/sync/controllers/PatientsSyncWorker.java | projectbuendia/client | 244e5dc32f5af5a646138d45eb2eaad95b5173c4 | [
"Apache-2.0"
] | 41 | 2015-04-21T21:01:57.000Z | 2019-06-24T23:28:29.000Z | app/src/main/java/org/projectbuendia/client/sync/controllers/PatientsSyncWorker.java | projectbuendia/client | 244e5dc32f5af5a646138d45eb2eaad95b5173c4 | [
"Apache-2.0"
] | 342 | 2015-08-20T15:07:44.000Z | 2019-11-26T04:56:44.000Z | app/src/main/java/org/projectbuendia/client/sync/controllers/PatientsSyncWorker.java | projectbuendia/client | 244e5dc32f5af5a646138d45eb2eaad95b5173c4 | [
"Apache-2.0"
] | 42 | 2015-08-12T13:08:11.000Z | 2019-06-24T23:55:41.000Z | 38.822222 | 89 | 0.710361 | 7,927 | /*
* Copyright 2015 The Project Buendia Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at: http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distrib-
* uted 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
* specific language governing permissions and limitations under the License.
*/
package org.projectbuendia.client.sync.controllers;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.SyncResult;
import android.net.Uri;
import org.projectbuendia.client.App;
import org.projectbuendia.client.json.JsonPatient;
import org.projectbuendia.models.Patient;
import org.projectbuendia.client.providers.Contracts;
import org.projectbuendia.client.utils.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* Handles syncing patients. Uses an incremental sync mechanism - see
* {@link IncrementalSyncWorker} for details.
*/
public class PatientsSyncWorker extends IncrementalSyncWorker<JsonPatient> {
private static final Logger LOG = Logger.create();
private Set<String> patientUuidsToUpdate = new HashSet<>();
public PatientsSyncWorker() {
super("patients", Contracts.Table.PATIENTS, JsonPatient.class);
}
@Override public void initialize(
ContentResolver resolver, SyncResult result, ContentProviderClient client) {
patientUuidsToUpdate.clear();
}
@Override protected ArrayList<ContentProviderOperation> getUpdateOps(
JsonPatient[] patients, SyncResult syncResult) {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
int numInserts = 0;
int numDeletes = 0;
for (JsonPatient patient : patients) {
if (patient.voided) {
numDeletes++;
ops.add(makeDeleteOpForPatientUuid(patient.uuid));
} else {
numInserts++;
ops.add(makeInsertOpForPatient(patient));
}
patientUuidsToUpdate.add(patient.uuid);
}
LOG.d("Patients: %d inserts, %d deletes", numInserts, numDeletes);
syncResult.stats.numInserts += numInserts;
syncResult.stats.numDeletes += numDeletes;
return ops;
}
private static ContentProviderOperation makeInsertOpForPatient(JsonPatient patient) {
return ContentProviderOperation.newInsert(Contracts.Patients.URI)
.withValues(Patient.fromJson(patient).toContentValues()).build();
}
private static ContentProviderOperation makeDeleteOpForPatientUuid(String uuid) {
Uri uri = Contracts.Patients.URI.buildUpon().appendPath(uuid).build();
return ContentProviderOperation.newDelete(uri).build();
}
@Override public void finalize(
ContentResolver resolver, SyncResult result, ContentProviderClient client) {
for (String uuid : patientUuidsToUpdate) {
App.getModel().denormalizeObservations(App.getCrudEventBus(), uuid);
}
if (result.stats.numInserts + result.stats.numDeletes > 0) {
resolver.notifyChange(Contracts.Patients.URI, null, false);
}
}
}
|
3e12cbae801e8629aa1138fcf1cb1b2612dbd732 | 1,221 | java | Java | addressbook-web-tests/src/test/java/stqa/addressbook/appmanager/NavigationHelper.java | yurikars/TARepo | e4c0a30eae58281903162454eabdecf70edb14ba | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/stqa/addressbook/appmanager/NavigationHelper.java | yurikars/TARepo | e4c0a30eae58281903162454eabdecf70edb14ba | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/stqa/addressbook/appmanager/NavigationHelper.java | yurikars/TARepo | e4c0a30eae58281903162454eabdecf70edb14ba | [
"Apache-2.0"
] | null | null | null | 27.133333 | 101 | 0.574939 | 7,928 | package stqa.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class NavigationHelper extends HelperBase {
public NavigationHelper(WebDriver wd) {
super(wd);
}
public void group() {
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Groups")
&& isElementPresent(By.name("new"))){
return;
}
click(By.linkText("groups"));
}
public void contactsCreationPage(){
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Edit / add address book entry")
&& isElementPresent(By.name("submit")) ){
return;
}
click(By.linkText("add new"));
}
public void contactsListPage(){
if (isElementPresent(By.cssSelector("input[type='text']"))) {
return;
}
click(By.linkText("home"));
}
public void gotoHomePage(){
if (isElementPresent(By.id("maintable"))){
return;
}
click(By.linkText("home"));
}
}
|
3e12cbc9d0c0bdd62c40fcc23a71fbb54fa9ee7d | 1,676 | java | Java | src/model/shapes/RightTriangle.java | Jmoore314/JPaint | 0c242972d237d2cff2185511ee468be30785d34f | [
"MIT"
] | null | null | null | src/model/shapes/RightTriangle.java | Jmoore314/JPaint | 0c242972d237d2cff2185511ee468be30785d34f | [
"MIT"
] | null | null | null | src/model/shapes/RightTriangle.java | Jmoore314/JPaint | 0c242972d237d2cff2185511ee468be30785d34f | [
"MIT"
] | null | null | null | 19.717647 | 142 | 0.7321 | 7,929 | package model.shapes;
import model.ShapeColor;
import model.ShapeShadingType;
import model.interfaces.IShape;
public class RightTriangle implements IShape {
private int xMin;
private int yMin;
private int width;
private int height;
private ShapeColor primaryColor;
private ShapeColor secondaryColor;
private ShapeShadingType shade;
public RightTriangle(ShapeColor primaryColor, ShapeColor secondaryColor, ShapeShadingType shade, int xMin, int yMin, int width, int height) {
this.primaryColor = primaryColor;
this.secondaryColor = secondaryColor;
this.shade = shade;
this.xMin = xMin;
this.yMin = yMin;
this.width = width;
this.height = height;
}
public int getMinX() {
return xMin;
}
public void setMinX(int newXMin) {
this.xMin = newXMin;
}
public int getMinY() {
return yMin;
}
public void setMinY(int newYMin) {
this.yMin = newYMin;
}
public int getWidth() {
return width;
}
public void setWidth(int newWidth) {
this.width = newWidth;
}
public int getHeight() {
return height;
}
public void setHeight(int newHeight) {
this.height = newHeight;
}
public ShapeColor getPrimaryColor() {
return primaryColor;
}
public void setPrimaryColor(ShapeColor newPrimaryColor) {
this.primaryColor = newPrimaryColor;
}
public ShapeColor getSecondaryColor() {
return secondaryColor;
}
public void setSecondaryColor(ShapeColor newSecondaryColor) {
this.secondaryColor = newSecondaryColor;
}
public ShapeShadingType getShade() {
return shade;
}
public void setShade(ShapeShadingType newShade) {
this.shade = newShade;
}
public String toString() {
return "RIGHT_TRIANGLE";
}
} |
3e12cbff5d5917a27c5a5dcac2f7fdeb368fd25d | 288 | java | Java | test/transform/resource/after-ecj/LoggerConfigOnRecord.java | mankeyl/lombok | d3b763f9dab4a46e88ff10bc2132fb6f12fda639 | [
"MIT"
] | 9,959 | 2015-01-02T21:02:36.000Z | 2021-04-22T20:07:49.000Z | test/transform/resource/after-ecj/LoggerConfigOnRecord.java | mankeyl/lombok | d3b763f9dab4a46e88ff10bc2132fb6f12fda639 | [
"MIT"
] | 2,007 | 2015-01-29T19:56:09.000Z | 2021-04-21T14:46:05.000Z | test/transform/resource/after-ecj/LoggerConfigOnRecord.java | mankeyl/lombok | d3b763f9dab4a46e88ff10bc2132fb6f12fda639 | [
"MIT"
] | 2,147 | 2015-01-04T01:49:48.000Z | 2021-04-22T13:32:19.000Z | 24 | 63 | 0.663194 | 7,930 | // version 14:
import lombok.extern.slf4j.Slf4j;
public @Slf4j record LoggerConfigOnRecord(String a, String b) {
/* Implicit */ private final String a;
/* Implicit */ private final String b;
public LoggerConfigOnRecord(String a, String b) {
super();
.a = a;
.b = b;
}
}
|
3e12cc236bc5c935d035c19231ec7bff5033929f | 720 | java | Java | backend/src/main/java/com/manager/configuration/security/WebMvcConfig.java | vdvorak83/taskManager | cde490082fcc0bdebb0ff991bd78fff891f68372 | [
"Apache-2.0"
] | 1 | 2020-10-10T18:07:17.000Z | 2020-10-10T18:07:17.000Z | backend/src/main/java/com/manager/configuration/security/WebMvcConfig.java | VardanMatevosyan/taskManager | bd920ecfbb065f78f5fcdb63c1c24f022913dcf1 | [
"Apache-2.0"
] | 11 | 2020-04-30T07:40:53.000Z | 2022-03-02T04:39:15.000Z | backend/src/main/java/com/manager/configuration/security/WebMvcConfig.java | vdvorak83/taskManager | cde490082fcc0bdebb0ff991bd78fff891f68372 | [
"Apache-2.0"
] | 1 | 2020-07-30T13:40:20.000Z | 2020-07-30T13:40:20.000Z | 34.285714 | 83 | 0.684722 | 7,931 | package com.manager.configuration.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final long MAX_AGE_SECS = 3600;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(MAX_AGE_SECS);
}
} |
3e12ccda61ae285edf994548eabdd23421820075 | 1,207 | java | Java | src/test/java/gov/di_ipv_core/step_definitions/KbvStubSmokeSteps.java | alphagov/di-ipv-core-tests | a1357bfd01219898fbb8442c648a6955df47e238 | [
"MIT"
] | null | null | null | src/test/java/gov/di_ipv_core/step_definitions/KbvStubSmokeSteps.java | alphagov/di-ipv-core-tests | a1357bfd01219898fbb8442c648a6955df47e238 | [
"MIT"
] | 1 | 2022-01-27T15:53:55.000Z | 2022-01-27T15:54:49.000Z | src/test/java/gov/di_ipv_core/step_definitions/KbvStubSmokeSteps.java | alphagov/di-ipv-core-tests | a1357bfd01219898fbb8442c648a6955df47e238 | [
"MIT"
] | null | null | null | 32.621622 | 75 | 0.714167 | 7,932 | package gov.di_ipv_core.step_definitions;
import gov.di_ipv_core.pages.IpvCoreFrontPage;
import gov.di_ipv_core.pages.SupplyDataPage;
import gov.di_ipv_core.utilities.BrowserUtils;
import io.cucumber.java.en.When;
public class KbvStubSmokeSteps {
String myData;
@When("I click on Kbv\\(Stub)")
public void i_click_on_kbv_stub() {
new IpvCoreFrontPage().KbvStub.click();
BrowserUtils.waitForPageToLoad(10);
}
@When("I supply my data in JSON format")
public void i_supply_my_data_in_json_format() {
myData = "{\"Hakan\":\"1234\"}";
new SupplyDataPage().supplyDataInJSONFormatBox.sendKeys(myData);
BrowserUtils.waitForPageToLoad(10);
}
@When("I supply my gpg45 verification value")
public void i_supply_my_gpg45_verification_value() {
myData = "2";
new SupplyDataPage().supplyGpg45VerificationValue.sendKeys(myData);
BrowserUtils.waitForPageToLoad(10);
}
@When("I click on Submit data and generate auth code")
public void i_click_on_submit_data_and_generate_auth_code() {
new SupplyDataPage().SubmitDataAndGenerateAuthCode.click();
BrowserUtils.waitForPageToLoad(10);
}
}
|
3e12cdd44705a64bf01f2de3cd94963a32fe202c | 1,048 | java | Java | ruoyi-admin/src/main/java/com/ruoyi/system/service/IWmsInOrderService.java | liushengGitHub/wms | dbd9e4c400b9aa9c2fd49c49153775b56b6176cd | [
"MIT"
] | null | null | null | ruoyi-admin/src/main/java/com/ruoyi/system/service/IWmsInOrderService.java | liushengGitHub/wms | dbd9e4c400b9aa9c2fd49c49153775b56b6176cd | [
"MIT"
] | 1 | 2021-09-20T20:58:28.000Z | 2021-09-20T20:58:28.000Z | ruoyi-admin/src/main/java/com/ruoyi/system/service/IWmsInOrderService.java | liushengGitHub/wms | dbd9e4c400b9aa9c2fd49c49153775b56b6176cd | [
"MIT"
] | null | null | null | 16.903226 | 72 | 0.571565 | 7,933 | package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.system.domain.WmsInOrder;
/**
* 入库单Service接口
*
* @author ruoyi
* @date 2020-04-04
*/
public interface IWmsInOrderService
{
/**
* 查询入库单
*
* @param id 入库单ID
* @return 入库单
*/
public WmsInOrder selectWmsInOrderById(Long id);
/**
* 查询入库单列表
*
* @param wmsInOrder 入库单
* @return 入库单集合
*/
public List<WmsInOrder> selectWmsInOrderList(WmsInOrder wmsInOrder);
/**
* 新增入库单
*
* @param wmsInOrder 入库单
* @return 结果
*/
public int insertWmsInOrder(WmsInOrder wmsInOrder);
/**
* 修改入库单
*
* @param wmsInOrder 入库单
* @return 结果
*/
public int updateWmsInOrder(WmsInOrder wmsInOrder);
/**
* 批量删除入库单
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteWmsInOrderByIds(String ids);
/**
* 删除入库单信息
*
* @param id 入库单ID
* @return 结果
*/
public int deleteWmsInOrderById(Long id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.