hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
3cac2b2c1eb317a770bd87f6f06676514da0a72f
| 1,829 |
package eu.nimble.service.catalogue.validation;
import com.google.common.base.Strings;
import eu.nimble.service.catalogue.exception.NimbleExceptionMessageCode;
import eu.nimble.service.model.ubl.catalogue.CatalogueType;
import eu.nimble.service.model.ubl.commonaggregatecomponents.CatalogueLineType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Created by suat on 07-Aug-18.
*/
public class CatalogueValidator {
private static Logger logger = LoggerFactory.getLogger(CatalogueValidator.class);
private List<String> errorMessages = new ArrayList<>();
private List<List<String>> errorParameters = new ArrayList<>();
private CatalogueType catalogueType;
public CatalogueValidator(CatalogueType catalogueType) {
this.catalogueType = catalogueType;
}
public ValidationMessages validate() {
idExists();
validateLines();
logger.info("Catalogue: {} validated", catalogueType.getUUID());
return new ValidationMessages(errorMessages,errorParameters);
}
private void idExists() {
if(Strings.isNullOrEmpty(catalogueType.getID())) {
errorMessages.add(NimbleExceptionMessageCode.BAD_REQUEST_NO_ID_FOR_CATALOGUE.toString());
errorParameters.add(new ArrayList<>());
}
}
private void validateLines() {
for (CatalogueLineType line : catalogueType.getCatalogueLine()) {
CatalogueLineValidator catalogueLineValidator = new CatalogueLineValidator(catalogueType, line);
ValidationMessages validationMessages = catalogueLineValidator.validate();
errorMessages.addAll(validationMessages.getErrorMessages());
errorParameters.addAll(validationMessages.getErrorParameters());
}
}
}
| 34.509434 | 108 | 0.731001 |
7f699c020c541f7758933d3d8890939f22680d3d
| 1,883 |
package me.streib.janis.dbaufzug;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class Launcher {
public static void main(String[] args) throws Exception {
new Thread(new Updater(60 * 60 * 1000)).start();// hourly
DBAufzugConfiguration conf;
if (args.length != 1) {
InputStream ins;
File confFile = new File("conf/dbaufzug.properties");
if (confFile.exists()) {
ins = new FileInputStream(confFile);
} else {
ins = Launcher.class.getResourceAsStream("dbaufzug.properties");
}
conf = new DBAufzugConfiguration(ins);
} else {
conf = new DBAufzugConfiguration(new FileInputStream(new File(
args[0])));
}
DatabaseConnection.init(conf);
Server s = new Server(new InetSocketAddress(conf.getHostName(),
conf.getPort()));
((QueuedThreadPool) s.getThreadPool()).setMaxThreads(20);
ServletContextHandler h = new ServletContextHandler(
ServletContextHandler.SESSIONS);
h.setInitParameter(SessionManager.__SessionCookieProperty, "DB-Session");
h.addServlet(DBAufzug.class, "/*");
HandlerList hl = new HandlerList();
hl.setHandlers(new Handler[] { generateStaticContext(), h });
s.setHandler(hl);
s.start();
}
private static Handler generateStaticContext() {
final ResourceHandler rh = new ResourceHandler();
rh.setResourceBase("static/");
ContextHandler ch = new ContextHandler("/static");
ch.setHandler(rh);
return ch;
}
}
| 33.625 | 75 | 0.749336 |
8bf94d4cc9fd779e1fb25dddccfaf224bf6fa903
| 407 |
/*
* NEC Mobile Backend Platform
*
* Copyright (c) 2013-2018, NEC Corporation.
*/
package com.nec.baas.object;
import com.nec.baas.core.*;
/**
* オブジェクトバケット取得用コールバック。
* @since 1.0
*/
public interface NbObjectBucketCallback extends NbCallback<NbObjectBucket> {
/**
* オブジェクトバケットの取得に成功した場合に呼び出される。<br>
* @param bucket 取得したオブジェクトバケット。
*/
void onSuccess(NbObjectBucket bucket);
}
| 18.5 | 76 | 0.687961 |
55ff7f922c0ce846e78454904b4d0273a7033bf5
| 2,536 |
package it.cosenonjaviste.security.jwt.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.*;
public class JwtTokenVerifierTest {
private static final String SECRET = "a secret";
private static String token;
@BeforeClass
public static void before() {
token = JWT.create()
.withClaim(JwtConstants.USER_ID, "foo")
.withArrayClaim(JwtConstants.ROLES, new String[] {"role1", "role2"})
.sign(Algorithm.HMAC256(SECRET));
}
@Test
public void testVerify() {
JwtTokenVerifier verifier = JwtTokenVerifier.create(SECRET);
assertTrue(verifier.verify(token));
assertFalse(verifier.verify("not_a_token"));
}
@Test
public void testVerifyCreatingWithCustomAlgorithm() {
Algorithm algorithm = Algorithm.HMAC512(SECRET);
JwtTokenVerifier verifier = JwtTokenVerifier.create(algorithm);
assertFalse(verifier.verify(token));
String newToken = JWT.create()
.withClaim(JwtConstants.USER_ID, "foo")
.withArrayClaim(JwtConstants.ROLES, new String[]{"role1", "role2"})
.sign(algorithm);
assertTrue(verifier.verify(newToken));
}
@Test
public void testVerifyOrThrow() {
JwtTokenVerifier verifier = JwtTokenVerifier.create(SECRET);
verifier.verifyOrThrow(token);
try {
verifier.verifyOrThrow("not_a_token");
fail("should not be here!");
} catch (Exception e) {
assertTrue(e instanceof JWTVerificationException);
}
}
@Test
public void testGetUserId() {
JwtTokenVerifier verifier = JwtTokenVerifier.create(SECRET);
assertTrue(verifier.verify(token));
assertNotNull(verifier.getUserId());
assertEquals("foo", verifier.getUserId());
}
@Test
public void testGetRoles() {
JwtTokenVerifier verifier = JwtTokenVerifier.create(SECRET);
assertTrue(verifier.verify(token));
assertNotNull(verifier.getRoles());
assertEquals(2, verifier.getRoles().size());
assertEquals(Arrays.asList("role1", "role2"), verifier.getRoles());
}
@Test(expected = IllegalStateException.class)
public void shouldThrowIllegalStateExceptionWhenGetUserId() {
JwtTokenVerifier verifier = JwtTokenVerifier.create(SECRET);
assertNotNull(verifier.getUserId());
}
@Test(expected = IllegalStateException.class)
public void shouldThrowIllegalStateExceptionWhenGetRoles() {
JwtTokenVerifier verifier = JwtTokenVerifier.create(SECRET);
assertNotNull(verifier.getRoles());
}
}
| 26.978723 | 72 | 0.751972 |
10ac3be95cd4e3c20677f45758be0d0ae86854f6
| 46,193 |
/**
* Copyright 2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.maven.core.util.kubernetes;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerPort;
import io.fabric8.kubernetes.api.model.ContainerPortBuilder;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.EnvVarBuilder;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesListBuilder;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LabelSelectorBuilder;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.PodSpecBuilder;
import io.fabric8.kubernetes.api.model.PodStatus;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ReplicationControllerSpec;
import io.fabric8.kubernetes.api.model.apps.DaemonSet;
import io.fabric8.kubernetes.api.model.apps.DaemonSetSpec;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.api.model.apps.DeploymentSpec;
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.api.model.apps.ReplicaSetSpec;
import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import io.fabric8.kubernetes.api.model.apps.StatefulSetSpec;
import io.fabric8.kubernetes.api.model.batch.Job;
import io.fabric8.kubernetes.api.model.batch.JobSpec;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.internal.HasMetadataComparator;
import io.fabric8.maven.core.util.FileUtil;
import io.fabric8.maven.core.config.PlatformMode;
import io.fabric8.maven.core.model.GroupArtifactVersion;
import io.fabric8.maven.core.util.MapUtil;
import io.fabric8.maven.core.util.ResourceUtil;
import io.fabric8.maven.core.util.ResourceVersioning;
import io.fabric8.maven.docker.config.ImageConfiguration;
import io.fabric8.maven.docker.util.ImageName;
import io.fabric8.maven.docker.util.Logger;
import io.fabric8.openshift.api.model.Build;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.DeploymentConfigSpec;
import io.fabric8.openshift.api.model.Template;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.fabric8.maven.core.util.Constants.RESOURCE_APP_CATALOG_ANNOTATION;
import static io.fabric8.maven.core.util.Constants.RESOURCE_SOURCE_URL_ANNOTATION;
/**
* Utility class for handling Kubernetes resource descriptors
*
* @author roland
* @since 02/05/16
*/
public class KubernetesResourceUtil {
private static final transient org.slf4j.Logger LOG = LoggerFactory.getLogger(KubernetesResourceUtil.class);
public static final String API_VERSION = "v1";
public static final String API_EXTENSIONS_VERSION = "extensions/v1beta1";
public static final String API_APPS_VERSION = "apps/v1";
public static final String JOB_VERSION = "batch/v1";
public static final String OPENSHIFT_V1_VERSION = "apps.openshift.io/v1";
public static final String CRONJOB_VERSION = "batch/v1beta1";
public static final String RBAC_VERSION = "rbac.authorization.k8s.io/v1";
public static final ResourceVersioning DEFAULT_RESOURCE_VERSIONING = new ResourceVersioning()
.withCoreVersion(API_VERSION)
.withExtensionsVersion(API_EXTENSIONS_VERSION)
.withAppsVersion(API_APPS_VERSION)
.withOpenshiftV1Version(OPENSHIFT_V1_VERSION)
.withJobVersion(JOB_VERSION)
.withCronJobVersion(CRONJOB_VERSION)
.withRbacVersion(RBAC_VERSION);
public static final HashSet<Class<?>> SIMPLE_FIELD_TYPES = new HashSet<>();
public static final String CONTAINER_NAME_REGEX = "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$";
protected static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX";
/**
* Read all Kubernetes resource fragments from a directory and create a {@link KubernetesListBuilder} which
* can be adapted later.
*
* @param apiVersions the api versions to use
* @param defaultName the default name to use when none is given
* @param resourceFiles files to add.
* @return the list builder
* @throws IOException
*/
public static KubernetesListBuilder readResourceFragmentsFrom(PlatformMode platformMode, ResourceVersioning apiVersions,
String defaultName,
File[] resourceFiles) throws IOException {
KubernetesListBuilder builder = new KubernetesListBuilder();
if (resourceFiles != null) {
for (File file : resourceFiles) {
if(file.getName().endsWith("cr.yml") || file.getName().endsWith("cr.yaml")) // Don't process custom resources
continue;
HasMetadata resource = getResource(platformMode, apiVersions, file, defaultName);
builder.addToItems(resource);
}
}
return builder;
}
/**
* Read a Kubernetes resource fragment and add meta information extracted from the filename
* to the resource descriptor. I.e. the following elements are added if not provided in the fragment:
*
* <ul>
* <li>name - Name of the resource added to metadata</li>
* <li>kind - Resource's kind</li>
* <li>apiVersion - API version (given as parameter to this method)</li>
* </ul>
*
*
* @param apiVersions the API versions to add if not given.
* @param file file to read, whose name must match {@link #FILENAME_PATTERN}. @return map holding the fragment
* @param appName resource name specifying resources belonging to this application
*/
public static HasMetadata getResource(PlatformMode platformMode, ResourceVersioning apiVersions,
File file, String appName) throws IOException {
Map<String,Object> fragment = readAndEnrichFragment(platformMode, apiVersions, file, appName);
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.convertValue(fragment, HasMetadata.class);
} catch (ClassCastException exp) {
throw new IllegalArgumentException(String.format("Resource fragment %s has an invalid syntax (%s)", file.getPath(), exp.getMessage()));
}
}
public static File[] listResourceFragments(File localResourceDir, List<String> remotes, Logger log) {
File[] resourceFiles = KubernetesResourceUtil.listResourceFragments(localResourceDir);
if(remotes != null) {
File[] remoteResourceFiles = KubernetesResourceUtil.listRemoteResourceFragments(remotes, log);
if (remoteResourceFiles.length > 0) {
resourceFiles = ArrayUtils.addAll(resourceFiles, remoteResourceFiles);
}
}
return resourceFiles;
}
public static File[] listResourceFragments(File resourceDir) {
final Pattern filenamePattern = Pattern.compile(FILENAME_PATTERN);
final Pattern exludePattern = Pattern.compile(PROFILES_PATTERN);
return resourceDir.listFiles((File dir, String name) -> filenamePattern.matcher(name).matches() && !exludePattern.matcher(name).matches());
}
public static File[] listRemoteResourceFragments(List<String> remotes, Logger log) {
if (remotes != null && !remotes.isEmpty()) {
final File remoteResources = FileUtil.createTempDirectory();
FileUtil.downloadRemotes(remoteResources, remotes, log);
if (remoteResources.isDirectory()) {
return remoteResources.listFiles();
}
}
return new File[0];
}
// ========================================================================================================
protected final static Map<String,String> FILENAME_TO_KIND_MAPPER = new HashMap<>();
protected final static Map<String,String> KIND_TO_FILENAME_MAPPER = new HashMap<>();
static {
initializeKindFilenameMapper();
}
protected final static void initializeKindFilenameMapper() {
final Map<String, List<String>> mappings = KindFilenameMapperUtil.loadMappings();
updateKindFilenameMapper(mappings);
}
protected final static void remove(String kind, String filename) {
FILENAME_TO_KIND_MAPPER.remove(filename);
KIND_TO_FILENAME_MAPPER.remove(kind);
}
public final static void updateKindFilenameMapper(final Map<String, List<String>> mappings) {
final Set<Map.Entry<String, List<String>>> entries = mappings.entrySet();
for (Map.Entry<String, List<String>> entry : entries) {
final List<String> filenameTypes = entry.getValue();
final String kind = entry.getKey();
for (String filenameType : filenameTypes) {
FILENAME_TO_KIND_MAPPER.put(filenameType, kind);
}
// In previous version, last one wins, so we do the same.
KIND_TO_FILENAME_MAPPER.put(kind, filenameTypes.get(filenameTypes.size() - 1));
}
}
private static final String FILENAME_PATTERN = "^(?<name>.*?)(-(?<type>[^-]+))?\\.(?<ext>yaml|yml|json)$";
private static final String PROFILES_PATTERN = "^profiles?\\.ya?ml$";
// Read fragment and add default values
private static Map<String, Object> readAndEnrichFragment(PlatformMode platformMode, ResourceVersioning apiVersions,
File file, String appName) throws IOException {
Pattern pattern = Pattern.compile(FILENAME_PATTERN, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(file.getName());
if (!matcher.matches()) {
throw new IllegalArgumentException(
String.format("Resource file name '%s' does not match pattern <name>-<type>.(yaml|yml|json)", file.getName()));
}
String name = matcher.group("name");
String type = matcher.group("type");
String ext = matcher.group("ext").toLowerCase();
String kind;
Map<String,Object> fragment = readFragment(file, ext);
if (type != null) {
kind = getAndValidateKindFromType(file, type);
} else {
// Try name as type
kind = FILENAME_TO_KIND_MAPPER.get(name.toLowerCase());
if (kind != null) {
// Name is in fact the type, so lets erase the name.
name = null;
}
}
addKind(fragment, kind, file.getName());
String apiVersion = apiVersions.getCoreVersion();
switch ((String)fragment.get("kind")) {
case "Ingress" :
apiVersion = apiVersions.getExtensionsVersion();
break;
case "StatefulSet" :
case "Deployment" :
apiVersion = apiVersions.getAppsVersion();
break;
case "Job" :
apiVersion = apiVersions.getJobVersion();
break;
case "DeploymentConfig" :
apiVersion = platformMode == PlatformMode.openshift ? apiVersions.getOpenshiftV1version(): apiVersion;
break;
case "CronJob" :
apiVersion = apiVersions.getCronJobVersion();
break;
case "ClusterRole" :
case "ClusterRoleBinding" :
case "Role" :
case "RoleBinding" :
apiVersion = apiVersions.getRbacVersion();
break;
}
addIfNotExistent(fragment, "apiVersion", apiVersion);
Map<String, Object> metaMap = getMetadata(fragment);
// No name means: generated app name should be taken as resource name
addIfNotExistent(metaMap, "name", StringUtils.isNotBlank(name) ? name : appName);
return fragment;
}
private static String getAndValidateKindFromType(File file, String type) {
String kind;
kind = FILENAME_TO_KIND_MAPPER.get(type.toLowerCase());
if (kind == null) {
throw new IllegalArgumentException(
String.format("Unknown type '%s' for file %s. Must be one of : %s",
type, file.getName(), StringUtils.join(FILENAME_TO_KIND_MAPPER.keySet().iterator(), ", ")));
}
return kind;
}
private static void addKind(Map<String, Object> fragment, String kind, String fileName) {
if (kind == null && !fragment.containsKey("kind")) {
throw new IllegalArgumentException(
"No type given as part of the file name (e.g. 'app-rc.yml') " +
"and no 'Kind' defined in resource descriptor " + fileName);
}
addIfNotExistent(fragment, "kind", kind);
}
public static void removeItemFromKubernetesBuilder(KubernetesListBuilder builder, HasMetadata item) {
List<HasMetadata> items = builder.buildItems();
List<HasMetadata> newListItems = new ArrayList<>();
for(HasMetadata listItem : items) {
if(!listItem.equals(item)) {
newListItems.add(listItem);
}
}
builder.withItems(newListItems);
}
// ===============================================================================================
private static Map<String, Object> getMetadata(Map<String, Object> fragment) {
Object mo = fragment.get("metadata");
Map<String, Object> meta;
if (mo == null) {
meta = new HashMap<>();
fragment.put("metadata", meta);
return meta;
} else if (mo instanceof Map) {
return (Map<String, Object>) mo;
} else {
throw new IllegalArgumentException("Metadata is expected to be a Map, not a " + mo.getClass());
}
}
private static void addIfNotExistent(Map<String, Object> fragment, String key, String value) {
if (!fragment.containsKey(key)) {
fragment.put(key, value);
}
}
private static Map<String,Object> readFragment(File file, String ext) throws IOException {
ObjectMapper mapper = new ObjectMapper("json".equals(ext) ? new JsonFactory() : new YAMLFactory());
TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
try {
Map<String, Object> ret = mapper.readValue(file, typeRef);
return ret != null ? ret : new HashMap<String, Object>();
} catch (JsonProcessingException e) {
throw new JsonProcessingException(String.format("[%s] %s", file, e.getMessage()), e.getLocation(), e) {};
}
}
public static String getNameWithSuffix(String name, String kind) {
String suffix = KIND_TO_FILENAME_MAPPER.get(kind);
return suffix != null ? name + "-" + suffix : name;
}
public static String extractContainerName(GroupArtifactVersion groupArtifactVersion, ImageConfiguration imageConfig) {
String alias = imageConfig.getAlias();
return alias != null ? alias : extractImageUser(imageConfig.getName(), groupArtifactVersion.getGroupId()) + "-" + groupArtifactVersion.getArtifactId();
}
private static String extractImageUser(String image, String groupId) {
ImageName name = new ImageName(image);
String imageUser = name.getUser();
String projectGroupId = groupId;
if(imageUser != null) {
return imageUser;
} else {
if(projectGroupId == null || projectGroupId.matches(CONTAINER_NAME_REGEX)) {
return projectGroupId;
}
else {
return projectGroupId.replaceAll("[^a-zA-Z0-9-]", "").replaceFirst("^-*(.*?)-*$","$1");
}
}
}
public static Map<String, String> removeVersionSelector(Map<String, String> selector) {
Map<String, String> answer = new HashMap<>(selector);
answer.remove("version");
return answer;
}
public static boolean checkForKind(KubernetesListBuilder builder, String... kinds) {
Set<String> kindSet = new HashSet<>(Arrays.asList(kinds));
for (HasMetadata item : builder.getItems()) {
if (kindSet.contains(item.getKind())) {
return true;
}
}
return false;
}
public static boolean addPort(List<ContainerPort> ports, String portNumberText, String portName, Logger log) {
if (StringUtils.isBlank(portNumberText)) {
return false;
}
int portValue;
try {
portValue = Integer.parseInt(portNumberText);
} catch (NumberFormatException e) {
log.warn("Could not parse remote debugging port %s as an integer: %s", portNumberText, e);
return false;
}
for (ContainerPort port : ports) {
String name = port.getName();
Integer containerPort = port.getContainerPort();
if (containerPort != null && containerPort.intValue() == portValue) {
return false;
}
}
ports.add(new ContainerPortBuilder().withName(portName).withContainerPort(portValue).build());
return true;
}
public static boolean setEnvVar(List<EnvVar> envVarList, String name, String value) {
for (EnvVar envVar : envVarList) {
String envVarName = envVar.getName();
if (Objects.equals(name, envVarName)) {
String oldValue = envVar.getValue();
if (Objects.equals(value, oldValue)) {
return false;
} else {
envVar.setValue(value);
return true;
}
}
}
EnvVar env = new EnvVarBuilder().withName(name).withValue(value).build();
envVarList.add(env);
return true;
}
public static String getEnvVar(List<EnvVar> envVarList, String name, String defaultValue) {
String answer = defaultValue;
if (envVarList != null) {
for (EnvVar envVar : envVarList) {
String envVarName = envVar.getName();
if (Objects.equals(name, envVarName)) {
String value = envVar.getValue();
if (StringUtils.isNotBlank(value)) {
return value;
}
}
}
}
return answer;
}
public static boolean removeEnvVar(List<EnvVar> envVarList, String name) {
boolean removed = false;
for (Iterator<EnvVar> it = envVarList.iterator(); it.hasNext(); ) {
EnvVar envVar = it.next();
String envVarName = envVar.getName();
if (name.equals(envVarName)) {
it.remove();
removed = true;
}
}
return removed;
}
/**
* Convert a map of env vars to a list of K8s EnvVar objects.
* @param envVars the name-value map containing env vars which must not be null
* @return list of converted env vars
*/
public static List<EnvVar> convertToEnvVarList(Map<String, String> envVars) {
List<EnvVar> envList = new LinkedList<>();
for (Map.Entry<String, String> entry : envVars.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if (name != null) {
EnvVar env = new EnvVarBuilder().withName(name).withValue(value).build();
envList.add(env);
}
}
return envList;
}
public static void validateKubernetesMasterUrl(URL masterUrl) throws MojoExecutionException {
if (masterUrl == null || StringUtils.isBlank(masterUrl.toString())) {
throw new MojoExecutionException("Cannot find Kubernetes master URL. Have you started a cluster via `mvn fabric8:cluster-start` or connected to a remote cluster via `kubectl`?");
}
}
public static void handleKubernetesClientException(KubernetesClientException e, Logger logger) throws MojoExecutionException {
Throwable cause = e.getCause();
if (cause instanceof UnknownHostException) {
logger.error("Could not connect to kubernetes cluster!");
logger.error("Have you started a local cluster via `mvn fabric8:cluster-start` or connected to a remote cluster via `kubectl`?");
logger.info("For more help see: http://fabric8.io/guide/getStarted/");
logger.error("Connection error: %s", cause);
String message = "Could not connect to kubernetes cluster. Have you started a cluster via `mvn fabric8:cluster-start` or connected to a remote cluster via `kubectl`? Error: " + cause;
throw new MojoExecutionException(message, e);
} else {
throw new MojoExecutionException(e.getMessage(), e);
}
}
public static String getBuildStatusPhase(Build build) {
if (build != null && build.getStatus() != null) {
return build.getStatus().getPhase();
}
return null;
}
public static String getBuildStatusReason(Build build) {
if (build != null && build.getStatus() != null) {
String reason = build.getStatus().getReason();
String phase = build.getStatus().getPhase();
if (StringUtils.isNotBlank(phase)) {
if (StringUtils.isNotBlank(reason)) {
return phase + ": " + reason;
} else {
return phase;
}
} else {
return StringUtils.defaultIfEmpty(reason, "");
}
}
return "";
}
public static Pod getNewestPod(Collection<Pod> pods) {
if (pods == null || pods.isEmpty()) {
return null;
}
List<Pod> sortedPods = new ArrayList<>(pods);
Collections.sort(sortedPods, (p1, p2) -> {
Date t1 = getCreationTimestamp(p1);
Date t2 = getCreationTimestamp(p2);
if (t1 != null) {
if (t2 == null) {
return 1;
} else {
return t1.compareTo(t2);
}
} else if (t2 == null) {
return 0;
}
return -1;
});
return sortedPods.get(sortedPods.size() - 1);
}
public static Date getCreationTimestamp(HasMetadata hasMetadata) {
ObjectMeta metadata = hasMetadata.getMetadata();
if (metadata != null) {
return parseTimestamp(metadata.getCreationTimestamp());
}
return null;
}
private static Date parseTimestamp(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
return parseDate(text);
}
public static Date parseDate(String text) {
try {
return new SimpleDateFormat(DATE_TIME_FORMAT).parse(text);
} catch (ParseException e) {
LOG.warn("Unable to parse date: " + text, e);
return null;
}
}
public static boolean podHasContainerImage(Pod pod, String imageName) {
if (pod != null) {
PodSpec spec = pod.getSpec();
if (spec != null) {
List<Container> containers = spec.getContainers();
if (containers != null) {
for (Container container : containers) {
if (Objects.equals(imageName, container.getImage())) {
return true;
}
}
}
}
}
return false;
}
public static String getDockerContainerID(Pod pod) {
PodStatus status = pod.getStatus();
if (status != null) {
List<ContainerStatus> containerStatuses = status.getContainerStatuses();
if (containerStatuses != null) {
for (ContainerStatus containerStatus : containerStatuses) {
String containerID = containerStatus.getContainerID();
if (StringUtils.isNotBlank(containerID)) {
String prefix = "://";
int idx = containerID.indexOf(prefix);
if (idx > 0) {
return containerID.substring(idx + prefix.length());
}
return containerID;
}
}
}
}
return null;
}
public static boolean isNewerResource(HasMetadata newer, HasMetadata older) {
Date t1 = getCreationTimestamp(newer);
Date t2 = getCreationTimestamp(older);
return t1 != null && (t2 == null || t1.compareTo(t2) > 0);
}
/**
* Uses reflection to copy over default values from the defaultValues object to the targetValues
* object similar to the following:
*
* <code>
\ * if( values.get${FIELD}() == null ) {
* values.(with|set){FIELD}(defaultValues.get${FIELD});
* }
* </code>
*
* Only fields that which use primitives, boxed primitives, or String object are copied.
*
* @param targetValues
* @param defaultValues
*/
public static void mergeSimpleFields(Object targetValues, Object defaultValues) {
Class<?> tc = targetValues.getClass();
Class<?> sc = defaultValues.getClass();
for (Method targetGetMethod : tc.getMethods()) {
if (!targetGetMethod.getName().startsWith("get")) {
continue;
}
Class<?> fieldType = targetGetMethod.getReturnType();
if (!SIMPLE_FIELD_TYPES.contains(fieldType)) {
continue;
}
String fieldName = targetGetMethod.getName().substring(3);
Method withMethod = null;
try {
withMethod = tc.getMethod("with" + fieldName, fieldType);
} catch (NoSuchMethodException e) {
try {
withMethod = tc.getMethod("set" + fieldName, fieldType);
} catch (NoSuchMethodException e2) {
continue;
}
}
Method sourceGetMethod = null;
try {
sourceGetMethod = sc.getMethod("get" + fieldName);
} catch (NoSuchMethodException e) {
continue;
}
try {
if (targetGetMethod.invoke(targetValues) == null) {
withMethod.invoke(targetValues, sourceGetMethod.invoke(defaultValues));
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
}
public static String mergePodSpec(PodSpecBuilder builder, PodSpec defaultPodSpec, String defaultName) {
return mergePodSpec(builder, defaultPodSpec, defaultName, false);
}
public static String mergePodSpec(PodSpecBuilder builder, PodSpec defaultPodSpec, String defaultName, boolean sidecarEnabled) {
String defaultApplicationContainerName = null;
List<Container> containers = builder.buildContainers();
List<Container> defaultContainers = defaultPodSpec.getContainers();
int size = defaultContainers.size();
if (size > 0) {
if (containers == null || containers.isEmpty()) {
builder.addToContainers(defaultContainers.toArray(new Container[size]));
} else {
int idx = 0;
for (Container defaultContainer : defaultContainers) {
Container container = null;
if(sidecarEnabled) { // Consider container as sidecar
for (Container fragmentContainer : containers) {
if (fragmentContainer.getName() == null || fragmentContainer.getName().equals(defaultContainer.getName())) {
container = fragmentContainer;
defaultApplicationContainerName = defaultContainer.getName();
break;
}
}
if (container == null) {
container = new Container();
containers.add(container);
}
} else { // Old behavior
if (idx < containers.size()) {
container = containers.get(idx);
} else {
container = new Container();
containers.add(container);
}
}
mergeSimpleFields(container, defaultContainer);
List<EnvVar> defaultEnv = defaultContainer.getEnv();
if (defaultEnv != null) {
for (EnvVar envVar : defaultEnv) {
ensureHasEnv(container, envVar);
}
}
List<ContainerPort> defaultPorts = defaultContainer.getPorts();
if (defaultPorts != null) {
for (ContainerPort port : defaultPorts) {
ensureHasPort(container, port);
}
}
if (container.getReadinessProbe() == null) {
container.setReadinessProbe(defaultContainer.getReadinessProbe());
}
if (container.getLivenessProbe() == null) {
container.setLivenessProbe(defaultContainer.getLivenessProbe());
}
if (container.getSecurityContext() == null) {
container.setSecurityContext(defaultContainer.getSecurityContext());
}
idx++;
}
builder.withContainers(containers);
}
} else if (!containers.isEmpty()) {
// lets default the container name if there's none specified in the custom yaml file
for (Container container : containers) {
if (StringUtils.isBlank(container.getName())) {
container.setName(defaultName);
break; // do it for one container only, but not necessarily the first one
}
}
builder.withContainers(containers);
}
return defaultApplicationContainerName; // Return the main application container's name.
}
private static void ensureHasEnv(Container container, EnvVar envVar) {
List<EnvVar> envVars = container.getEnv();
if (envVars == null) {
envVars = new ArrayList<>();
container.setEnv(envVars);
}
for (EnvVar var : envVars) {
if (Objects.equals(var.getName(), envVar.getName())) {
// lets replace the object so that we can update the value or valueFrom
envVars.remove(var);
envVars.add(envVar);
return;
}
}
envVars.add(envVar);
}
private static void ensureHasPort(Container container, ContainerPort port) {
List<ContainerPort> ports = container.getPorts();
if (ports == null) {
ports = new ArrayList<>();
container.setPorts(ports);
}
for (ContainerPort cp : ports) {
String n1 = cp.getName();
String n2 = port.getName();
if (n1 != null && n2 != null && n1.equals(n2)) {
return;
}
Integer p1 = cp.getContainerPort();
Integer p2 = port.getContainerPort();
if (p1 != null && p2 != null && p1.intValue() == p2.intValue()) {
return;
}
}
ports.add(port);
}
public static String getSourceUrlAnnotation(HasMetadata item) {
return KubernetesHelper.getOrCreateAnnotations(item).get(RESOURCE_SOURCE_URL_ANNOTATION);
}
public static void setSourceUrlAnnotationIfNotSet(HasMetadata item, String sourceUrl) {
Map<String, String> annotations = KubernetesHelper.getOrCreateAnnotations(item);
if (!annotations.containsKey(RESOURCE_SOURCE_URL_ANNOTATION)) {
annotations.put(RESOURCE_SOURCE_URL_ANNOTATION, sourceUrl);
item.getMetadata().setAnnotations(annotations);
}
}
public static boolean isAppCatalogResource(HasMetadata templateOrConfigMap) {
String catalogAnnotation = KubernetesHelper.getOrCreateAnnotations(templateOrConfigMap).get(RESOURCE_APP_CATALOG_ANNOTATION);
return "true".equals(catalogAnnotation);
}
public static Set<HasMetadata> loadResources(File manifest) throws IOException {
Object dto = ResourceUtil.load(manifest, KubernetesResource.class);
if (dto == null) {
throw new IllegalStateException("Cannot load kubernetes manifest " + manifest);
}
if (dto instanceof Template) {
Template template = (Template) dto;
dto = OpenshiftHelper.processTemplatesLocally(template, false);
}
Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
entities.addAll(KubernetesHelper.toItemList(dto));
return entities;
}
public static LabelSelector getPodLabelSelector(Set<HasMetadata> entities) {
LabelSelector chosenSelector = null;
for (HasMetadata entity : entities) {
LabelSelector selector = getPodLabelSelector(entity);
if (selector != null) {
if (chosenSelector != null && !chosenSelector.equals(selector)) {
throw new IllegalArgumentException("Multiple selectors found for the given entities: " + chosenSelector + " - " + selector);
}
chosenSelector = selector;
}
}
return chosenSelector;
}
public static LabelSelector getPodLabelSelector(HasMetadata entity) {
LabelSelector selector = null;
if (entity instanceof Deployment) {
Deployment resource = (Deployment) entity;
DeploymentSpec spec = resource.getSpec();
if (spec != null) {
selector = spec.getSelector();
}
} else if (entity instanceof ReplicaSet) {
ReplicaSet resource = (ReplicaSet) entity;
ReplicaSetSpec spec = resource.getSpec();
if (spec != null) {
selector = spec.getSelector();
}
} else if (entity instanceof DeploymentConfig) {
DeploymentConfig resource = (DeploymentConfig) entity;
DeploymentConfigSpec spec = resource.getSpec();
if (spec != null) {
selector = toLabelSelector(spec.getSelector());
}
} else if (entity instanceof ReplicationController) {
ReplicationController resource = (ReplicationController) entity;
ReplicationControllerSpec spec = resource.getSpec();
if (spec != null) {
selector = toLabelSelector(spec.getSelector());
}
} else if (entity instanceof DaemonSet) {
DaemonSet resource = (DaemonSet) entity;
DaemonSetSpec spec = resource.getSpec();
if (spec != null) {
selector = spec.getSelector();
}
} else if (entity instanceof StatefulSet) {
StatefulSet resource = (StatefulSet) entity;
StatefulSetSpec spec = resource.getSpec();
if (spec != null) {
selector = spec.getSelector();
}
} else if (entity instanceof Job) {
Job resource = (Job) entity;
JobSpec spec = resource.getSpec();
if (spec != null) {
selector = spec.getSelector();
}
}
return selector;
}
private static LabelSelector toLabelSelector(Map<String, String> matchLabels) {
if (matchLabels != null && !matchLabels.isEmpty()) {
return new LabelSelectorBuilder().withMatchLabels(matchLabels).build();
}
return null;
}
/**
* Merges the given resources together into a single resource.
*
* If switchOnLocalCustomisation is false then the overrides from item2 are merged into item1
*
* @return the newly merged resources
*/
public static HasMetadata mergeResources(HasMetadata item1, HasMetadata item2, Logger log, boolean switchOnLocalCustomisation) {
if (item1 instanceof Deployment && item2 instanceof Deployment) {
return mergeDeployments((Deployment) item1, (Deployment) item2, log, switchOnLocalCustomisation);
}
if (item1 instanceof ConfigMap && item2 instanceof ConfigMap) {
ConfigMap cm1 = (ConfigMap) item1;
ConfigMap cm2 = (ConfigMap) item2;
return mergeConfigMaps(cm1, cm2, log, switchOnLocalCustomisation);
}
mergeMetadata(item1, item2);
return item1;
}
protected static HasMetadata mergeConfigMaps(ConfigMap cm1, ConfigMap cm2, Logger log, boolean switchOnLocalCustomisation) {
ConfigMap cm1OrCopy = cm1;
if (!switchOnLocalCustomisation) {
// lets copy the original to avoid modifying it
cm1OrCopy = new ConfigMapBuilder(cm1OrCopy).build();
}
log.info("Merging 2 resources for " + KubernetesHelper.getKind(cm1OrCopy) + " " + KubernetesHelper.getName(cm1OrCopy) + " from " + getSourceUrlAnnotation(cm1OrCopy) + " and " + getSourceUrlAnnotation(cm2) +
" and removing " + getSourceUrlAnnotation(cm1OrCopy));
cm1OrCopy.setData(mergeMapsAndRemoveEmptyStrings(cm2.getData(), cm1OrCopy.getData()));
mergeMetadata(cm1OrCopy, cm2);
return cm1OrCopy;
}
protected static HasMetadata mergeDeployments(Deployment resource1, Deployment resource2, Logger log, boolean switchOnLocalCustomisation) {
Deployment resource1OrCopy = resource1;
if (!switchOnLocalCustomisation) {
// lets copy the original to avoid modifying it
resource1OrCopy = new DeploymentBuilder(resource1OrCopy).build();
}
HasMetadata answer = resource1OrCopy;
DeploymentSpec spec1 = resource1OrCopy.getSpec();
DeploymentSpec spec2 = resource2.getSpec();
if (spec1 == null) {
resource1OrCopy.setSpec(spec2);
} else {
PodTemplateSpec template1 = spec1.getTemplate();
PodTemplateSpec template2 = null;
if (spec2 != null) {
template2 = spec2.getTemplate();
}
if (template1 != null && template2 != null) {
mergeMetadata(template1, template2);
}
if (template1 == null) {
spec1.setTemplate(template2);
} else {
PodSpec podSpec1 = template1.getSpec();
PodSpec podSpec2 = null;
if (template2 != null) {
podSpec2 = template2.getSpec();
}
if (podSpec1 == null) {
template1.setSpec(podSpec2);
} else {
String defaultName = null;
PodTemplateSpec updateTemplate = template1;
if (switchOnLocalCustomisation) {
HasMetadata override = resource2;
if (isLocalCustomisation(podSpec1)) {
updateTemplate = template2;
PodSpec tmp = podSpec1;
podSpec1 = podSpec2;
podSpec2 = tmp;
} else {
answer = resource2;
override = resource1OrCopy;
}
mergeMetadata(answer, override);
} else {
mergeMetadata(resource1OrCopy, resource2);
}
if (updateTemplate != null) {
if (podSpec2 == null) {
updateTemplate.setSpec(podSpec1);
} else {
PodSpecBuilder podSpecBuilder = new PodSpecBuilder(podSpec1);
mergePodSpec(podSpecBuilder, podSpec2, defaultName);
updateTemplate.setSpec(podSpecBuilder.build());
}
}
return answer;
}
}
}
log.info("Merging 2 resources for " + KubernetesHelper.getKind(resource1OrCopy) + " " + KubernetesHelper.getName(resource1OrCopy) + " from " + getSourceUrlAnnotation(resource1OrCopy) + " and " + getSourceUrlAnnotation(resource2) + " and removing " + getSourceUrlAnnotation(resource1OrCopy));
return resource1OrCopy;
}
private static void mergeMetadata(PodTemplateSpec item1, PodTemplateSpec item2) {
if (item1 != null && item2 != null) {
ObjectMeta metadata1 = item1.getMetadata();
ObjectMeta metadata2 = item2.getMetadata();
if (metadata1 == null) {
item1.setMetadata(metadata2);
} else if (metadata2 != null) {
metadata1.setAnnotations(mergeMapsAndRemoveEmptyStrings(metadata2.getAnnotations(), metadata1.getAnnotations()));
metadata1.setLabels(mergeMapsAndRemoveEmptyStrings(metadata2.getLabels(), metadata1.getLabels()));
}
}
}
protected static void mergeMetadata(HasMetadata item1, HasMetadata item2) {
if (item1 != null && item2 != null) {
ObjectMeta metadata1 = item1.getMetadata();
ObjectMeta metadata2 = item2.getMetadata();
if (metadata1 == null) {
item1.setMetadata(metadata2);
} else if (metadata2 != null) {
metadata1.setAnnotations(mergeMapsAndRemoveEmptyStrings(metadata2.getAnnotations(), metadata1.getAnnotations()));
metadata1.setLabels(mergeMapsAndRemoveEmptyStrings(metadata2.getLabels(), metadata1.getLabels()));
}
}
}
/**
* Returns a merge of the given maps and then removes any resulting empty string values (which is the way to remove, say, a label or annotation
* when overriding
*/
private static Map<String, String> mergeMapsAndRemoveEmptyStrings(Map<String, String> overrideMap, Map<String, String> originalMap) {
Map<String, String> answer = MapUtil.mergeMaps(overrideMap, originalMap);
Set<Map.Entry<String, String>> entries = overrideMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
String value = entry.getValue();
if (value == null || value.isEmpty()) {
String key = entry.getKey();
answer.remove(key);
}
}
return answer;
}
// lets use presence of an image name as a clue that we are just enriching things a little
// rather than a full complete manifest
// we could also use an annotation?
private static boolean isLocalCustomisation(PodSpec podSpec) {
List<Container> containers = podSpec.getContainers() != null ? podSpec.getContainers() : Collections.<Container>emptyList();
for (Container container : containers) {
if (StringUtils.isNotBlank(container.getImage())) {
return false;
}
}
return true;
}
}
| 42.378899 | 299 | 0.600892 |
36612ba659b1da774b2b9e5c51ee087bbc0766b4
| 3,681 |
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* 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.apache.sandesha2.wsrm;
import java.util.Iterator;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPHeaderBlock;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.SandeshaException;
import org.apache.sandesha2.SandeshaTestCase;
import org.apache.sandesha2.util.Range;
public class SequenceAcknowledgementTest extends SandeshaTestCase {
SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
String rmNamespace = Sandesha2Constants.SPEC_2005_02.NS_URI;
public SequenceAcknowledgementTest() {
super("SequenceAcknowledgementTest");
}
public void testFromOMElement() throws SandeshaException {
QName name = new QName(rmNamespace, "SequenceAcknowledgement");
SequenceAcknowledgement sequenceAck = new SequenceAcknowledgement(rmNamespace, true);
SOAPEnvelope env = getSOAPEnvelope("", "SequenceAcknowledgement.xml");
sequenceAck.fromHeaderBlock((SOAPHeaderBlock) env.getHeader().getFirstChildWithName(name));
Identifier identifier = sequenceAck.getIdentifier();
assertEquals("uuid:897ee740-1624-11da-a28e-b3b9c4e71445", identifier.getIdentifier());
Iterator<Range> iterator = sequenceAck.getAcknowledgementRanges().iterator();
while (iterator.hasNext()) {
Range ackRange = (Range) iterator.next();
if (ackRange.lowerValue == 1){
assertEquals(2, ackRange.upperValue);
} else if (ackRange.lowerValue == 4) {
assertEquals(6, ackRange.upperValue);
} else if (ackRange.lowerValue == 8) {
assertEquals(10, ackRange.upperValue);
}
}
Iterator<Long> iterator2 = sequenceAck.getNackList().iterator();
while (iterator2.hasNext()) {
Long nack = (Long) iterator2.next();
if (nack.longValue() == 3) {
} else if (nack.longValue() == 7) {
} else {
fail("invalid nack : " + nack);
}
}
}
public void testToOMElement() throws Exception {
SequenceAcknowledgement seqAck = new SequenceAcknowledgement(rmNamespace, true);
Identifier identifier = new Identifier(rmNamespace);
identifier.setIndentifer("uuid:897ee740-1624-11da-a28e-b3b9c4e71445");
seqAck.setIdentifier(identifier);
SOAPEnvelope env = getEmptySOAPEnvelope();
seqAck.toHeader(env.getHeader());
OMElement sequenceAckPart = env.getHeader().getFirstChildWithName(
new QName(rmNamespace, Sandesha2Constants.WSRM_COMMON.SEQUENCE_ACK));
OMElement identifierPart = sequenceAckPart.getFirstChildWithName(
new QName(rmNamespace, Sandesha2Constants.WSRM_COMMON.IDENTIFIER));
assertEquals("uuid:897ee740-1624-11da-a28e-b3b9c4e71445", identifierPart.getText());
}
}
| 36.81 | 99 | 0.698452 |
b62cdc1bb309ee3cb24328624b3ab347e6248c73
| 6,945 |
package org.neuroph.nnet.learning;
import java.util.Iterator;
import org.neuroph.core.NeuralNetwork;
import org.neuroph.core.data.DataSet;
import org.neuroph.core.data.DataSetRow;
import org.neuroph.core.learning.SupervisedLearning;
import org.neuroph.util.NeuralNetworkCODEC;
/**
* This class implements a simulated annealing learning rule for supervised
* neural networks. It is based on the generic SimulatedAnnealing class. It is
* used in the same manner as any other training class that implements the
* SupervisedLearning interface.
* <p/>
* Simulated annealing is a common training method. It is often used in
* conjunction with a propagation training method. Simulated annealing can be
* very good when propagation training has reached a local minimum.
* <p/>
* The name and inspiration come from annealing in metallurgy, a technique
* involving heating and controlled cooling of a material to increase the size
* of its crystals and reduce their defects. The heat causes the atoms to become
* unstuck from their initial positions (a local minimum of the internal energy)
* and wander randomly through states of higher energy; the slow cooling gives
* them more chances of finding configurations with lower internal energy than
* the initial one.
*
* @author Jeff Heaton (http://www.jeffheaton.com)
*/
public class SimulatedAnnealingLearning extends SupervisedLearning {
/**
* The serial id.
*/
private static final long serialVersionUID = 1L;
/**
* The starting temperature.
*/
private double startTemperature;
/**
* The ending temperature.
*/
private double stopTemperature;
/**
* The number of cycles that will be used.
*/
private int cycles;
/**
* The current temperature.
*/
protected double temperature;
/**
* Current weights from the neural network.
*/
private double[] weights;
/**
* Best weights so far.
*/
private double[] bestWeights;
/**
* Construct a simulated annleaing trainer for a feedforward neural network.
*
* @param network The neural network to be trained.
* @param startTemp The starting temperature.
* @param stopTemp The ending temperature.
* @param cycles The number of cycles in a training iteration.
*/
public SimulatedAnnealingLearning(final NeuralNetwork network,
final double startTemp, final double stopTemp, final int cycles) {
setNeuralNetwork( network );
this.temperature = startTemp;
this.startTemperature = startTemp;
this.stopTemperature = stopTemp;
this.cycles = cycles;
this.weights = new double[NeuralNetworkCODEC
.determineArraySize(network)];
this.bestWeights = new double[NeuralNetworkCODEC
.determineArraySize(network)];
NeuralNetworkCODEC.network2array(network, this.weights);
NeuralNetworkCODEC.network2array(network, this.bestWeights);
}
public SimulatedAnnealingLearning(final NeuralNetwork network) {
this(network, 10, 2, 1000);
}
/**
* Get the best network from the training.
*
* @return The best network.
*/
public NeuralNetwork getNetwork() {
return getNeuralNetwork();
}
/**
* Randomize the weights and thresholds. This function does most of the work
* of the class. Each call to this class will randomize the data according
* to the current temperature. The higher the temperature the more
* randomness.
* @param randomChance
*/
public void randomize(double randomChance ) {
for (int i = 0; i < this.weights.length; i++)
if (Math.random() < randomChance)
{
double add = 0.5 - (Math.random());
add /= this.startTemperature;
add *= this.temperature;
this.weights[i] = this.weights[i] + add;
}
NeuralNetworkCODEC.array2network(this.weights, getNetwork());
}
/**
* Used internally to calculate the error for a training set.
*
* @param trainingSet The training set to calculate for.
* @return The error value.
*/
private double determineError(DataSet trainingSet) {
double result = 0d;
Iterator<DataSetRow> iterator = trainingSet.iterator();
while (iterator.hasNext() && !isStopped()) {
DataSetRow trainingSetRow = iterator.next();
double[] input = trainingSetRow.getInput();
getNetwork().setInput(input);
getNetwork().calculate();
double[] output = getNetwork().getOutput();
double[] desiredOutput = trainingSetRow
.getDesiredOutput();
double[] patternError = getErrorFunction().addPatternError(desiredOutput, output);
double sqrErrorSum = 0;
for (double error : patternError) {
sqrErrorSum += (error * error);
}
result += sqrErrorSum / (2 * patternError.length);
}
return result;
}
/**
* Perform one simulated annealing epoch.
*/
@Override
public void doLearningEpoch(DataSet trainingSet)
{
doLearningEpoch( trainingSet, 0.5 );
}
public void doLearningEpoch(DataSet trainingSet, double randomChance)
{
System.arraycopy(this.weights, 0, this.bestWeights, 0,
this.weights.length);
double bestError = determineError(trainingSet);
this.temperature = this.startTemperature;
for (int i = 0; i < this.cycles; i++) {
randomize( randomChance );
double currentError = determineError(trainingSet);
if (currentError < bestError) {
System.arraycopy(this.weights, 0, this.bestWeights, 0,
this.weights.length);
bestError = currentError;
} else
System.arraycopy(this.bestWeights, 0, this.weights, 0,
this.weights.length);
NeuralNetworkCODEC.array2network(this.bestWeights, getNetwork());
final double ratio = Math.exp(Math.log(this.stopTemperature
/ this.startTemperature)
/ (this.cycles - 1));
this.temperature *= ratio;
}
// the following line is probably wrong (when is reset() called?), but the result might not be used for anything
this.previousEpochError = getErrorFunction().getTotalError();
// moved stopping condition to separate method hasReachedStopCondition()
// so it can be overriden / customized in subclasses
if (hasReachedStopCondition()) {
stopLearning();
}
}
/**
* Not used.
*/
@Override
protected void calculateWeightChanges(double[] patternError) {
}
}
| 32.004608 | 120 | 0.634701 |
fe287a8b2a5d085d1be3597cdd9065282cdd8cdf
| 1,267 |
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.nio.serialization;
/**
* This is a base interface for adapting non-Portable classes to Portable.
* <p/>
* In situations where it's not possible to modify an existing class
* to implement Portable and/or it's not allowed to import a Hazelcast
* class into a domain class, it will be possible to add Portable features
* to a non-Portable object over this adapter.
* <p/>
* Sample:
*
* --- SAMPLE GOES HERE ---
*
* @see com.hazelcast.nio.serialization.Portable
*
* @param <T> type of non-Portable object
*/
// TODO: INTERFACE IS NOT DEFINED YET!
public interface PortableAdapter<T> extends Portable {
}
| 31.675 | 75 | 0.728493 |
85df08e4abbcc10e51c3eae345d8b4ee2b13ab01
| 266 |
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.logging;
/**
* @author Tony Vaagenes
*/
public interface RequestLogHandler {
void log(RequestLogEntry entry);
}
| 26.6 | 118 | 0.755639 |
5904632e4be278a258a30584a30781510c28f80c
| 1,126 |
package org.cggh.common.counters;
public class ExtendedNtAlleleCounter extends AlleleCounter {
public static final char[] ALLELES = {'A','C','G','T','*'};
public ExtendedNtAlleleCounter () {
super(ALLELES);
}
public ExtendedNtAlleleCounter (AlleleCount[] initCounters) {
super(ALLELES);
initialize (initCounters);
}
protected int getIndex(char allele) {
switch(allele) {
case 'A':
return 0;
case 'C':
return 1;
case 'G':
return 2;
case 'T':
return 3;
case '*':
return 4;
}
return -1;
}
public void setCounts(int a, int c, int g, int t, int spanDel) {
counts[0].count = a;
counts[1].count = c;
counts[2].count = g;
counts[3].count = t;
counts[4].count = spanDel;
}
public void addCounts(int a, int c, int g, int t, int spanDel) {
counts[0].count += a;
counts[1].count += c;
counts[2].count += g;
counts[3].count += t;
counts[4].count += spanDel;
}
public int[] getCounts() {
return new int[] {counts[0].count, counts[1].count, counts[2].count, counts[3].count, counts[4].count};
}
}
| 20.472727 | 106 | 0.595915 |
95cf0de001e8525e634d34acd365b4a10b35576a
| 825 |
package getta.gettaroo;
import fi.dy.masa.malilib.config.ConfigManager;
import fi.dy.masa.malilib.event.InputEventHandler;
import fi.dy.masa.malilib.interfaces.IInitializationHandler;
import getta.gettaroo.config.Callbacks;
import getta.gettaroo.config.Configs;
import getta.gettaroo.event.InputHandler;
import net.minecraft.client.MinecraftClient;
public class InitHandler implements IInitializationHandler {
@Override
public void registerModHandlers() {
ConfigManager.getInstance().registerConfigHandler(Constants.MOD_ID, new Configs());
InputEventHandler.getKeybindManager().registerKeybindProvider(InputHandler.getInstance());
InputEventHandler.getInputManager().registerMouseInputHandler(InputHandler.getInstance());
Callbacks.init(MinecraftClient.getInstance());
}
}
| 31.730769 | 98 | 0.796364 |
8bc3bec6becdd23c0e33eea70376519b1b6e72f4
| 4,317 |
package no.dcat.portal.query;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
public class HarvestQueryService extends ElasticsearchService {
private static Logger logger = LoggerFactory.getLogger(HarvestQueryService.class);
public static final String INDEX_DCAT = "dcat";
public static final String TYPE_DATA_PUBLISHER = "publisher";
public static final String QUERY_PUBLISHER = "/publisher";
/**
* @return The complete elasticsearch response on Json-format is returned..
*/
@CrossOrigin
@ApiOperation(value = "Finds all harvest catalog records for a given orgpath.")
@RequestMapping(value = "/harvest/catalog", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> listCatalogHarvestRecords(
@ApiParam("The orgpath of the publisher, e.g. /STAT or /FYLKE")
@RequestParam(value = "q", defaultValue = "", required = false) String query) {
logger.info("/harvest query: {}", query);
ResponseEntity<String> jsonError = initializeElasticsearchTransportClient();
if (jsonError != null) return jsonError;
QueryBuilder search;
if ("".equals(query)) {
search = QueryBuilders.matchAllQuery();
} else {
search = QueryBuilders.termQuery("publisher.orgPath", query);
}
SumAggregationBuilder agg1 = AggregationBuilders.sum("inserts").field("changeInformation.inserts");
SumAggregationBuilder agg2 = AggregationBuilders.sum("updates").field("changeInformation.updates");
SumAggregationBuilder agg3 = AggregationBuilders.sum("deletes").field("changeInformation.deletes");
long now = new Date().getTime();
long DAY_IN_MS = 1000 * 3600 *24;
RangeQueryBuilder range1 = QueryBuilders.rangeQuery("date").from(now - 7*DAY_IN_MS).to(now).format("epoch_millis");
RangeQueryBuilder range2 = QueryBuilders.rangeQuery("date").from(now - 30*DAY_IN_MS).to(now).format("epoch_millis");
RangeQueryBuilder range3 = QueryBuilders.rangeQuery("date").from(now - 365*DAY_IN_MS).to(now).format("epoch_millis");
AggregationBuilder last7 = AggregationBuilders.filter("last7days", range1).subAggregation(agg1).subAggregation(agg2).subAggregation(agg3);
AggregationBuilder last30 = AggregationBuilders.filter("last30days", range2).subAggregation(agg1).subAggregation(agg2).subAggregation(agg3);
AggregationBuilder last365 = AggregationBuilders.filter("last365days", range3).subAggregation(agg1).subAggregation(agg2).subAggregation(agg3);
SearchRequestBuilder searchQuery = getClient()
.prepareSearch("harvest").setTypes("catalog")
.setQuery(search)
.addAggregation(last7)
.addAggregation(last30)
.addAggregation(last365)
.setSize(0)
;
logger.trace("SEARCH: {}", searchQuery.toString());
SearchResponse response = searchQuery.execute().actionGet();
int totNumberOfCatalogRecords = (int) response.getHits().getTotalHits();
logger.debug("Found total number of catalog records: {}", totNumberOfCatalogRecords);
return new ResponseEntity<String>(response.toString(), HttpStatus.OK);
}
}
| 48.505618 | 150 | 0.732916 |
4207d1ea2bc2deaa684b1bbfe307348376452346
| 2,457 |
package org.tiwindetea.animewarfare.gui.game.gameboard;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.NumberBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import org.lomadriel.lfc.event.EventDispatcher;
import org.tiwindetea.animewarfare.logic.MarketingLadder;
import org.tiwindetea.animewarfare.net.networkevent.MarketingLadderUpdatedNetevent;
import org.tiwindetea.animewarfare.net.networkevent.MarketingLadderUpdatedNeteventListener;
public class GMarketingLadder extends AnchorPane implements MarketingLadderUpdatedNeteventListener {
private final Circle circle = new Circle();
private final Label label = new Label();
private final IntegerProperty position;
private final StringProperty nextCost;
public GMarketingLadder() {
setPrefWidth(40);
setMaxWidth(40);
setMinWidth(40);
setTranslateX(20);
this.position = new SimpleIntegerProperty(0);
this.nextCost = new SimpleStringProperty(String.valueOf(MarketingLadder.COSTS[0]));
EventDispatcher.registerListener(MarketingLadderUpdatedNetevent.class, this);
this.circle.setRadius(20);
this.circle.setFill(Color.BLANCHEDALMOND);
this.circle.setStroke(Color.BLACK);
NumberBinding binding = Bindings.subtract(heightProperty(),
Bindings.multiply(Bindings.divide(heightProperty(), 8), this.position));
this.circle.centerYProperty().bind(binding);
this.label.translateXProperty()
.bind(Bindings.subtract(this.circle.centerXProperty(),
Bindings.divide(this.label.widthProperty(), 2.)));
this.label.translateYProperty()
.bind(Bindings.subtract(this.circle.centerYProperty(),
Bindings.divide(this.label.heightProperty(), 2.)));
this.label.textProperty().bind(this.nextCost);
getChildren().addAll(this.circle, this.label);
}
public void clean() {
EventDispatcher.unregisterListener(MarketingLadderUpdatedNetevent.class, this);
}
@Override
public void handleMarketingLadderUpdate(MarketingLadderUpdatedNetevent event) {
this.position.set(event.getNewPosition());
Platform.runLater(() -> this.nextCost.setValue(String.valueOf(event.getCost())));
}
}
| 38.390625 | 100 | 0.79243 |
0c3436ee0600d6ee525b595f8d6395a4e3fdf549
| 13,845 |
package com.mathgame.plugin.sudoku.controller;
import android.app.IntentService;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.Pair;
import com.mathgame.R;
import com.mathgame.activity.SudokuHomeActivity;
import com.mathgame.appdata.Constant;
import com.mathgame.plugin.sudoku.controller.constant.Action;
import com.mathgame.plugin.sudoku.controller.constant.PrintStyle;
import com.mathgame.plugin.sudoku.controller.constant.QQWing;
import com.mathgame.plugin.sudoku.controller.constant.Symmetry;
import com.mathgame.plugin.sudoku.controller.database.DatabaseHelper;
import com.mathgame.plugin.sudoku.controller.database.model.Level;
import com.mathgame.plugin.sudoku.game.GameDifficulty;
import com.mathgame.plugin.sudoku.game.GameType;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
/**
* @author Christopher Beckmann
*/
public class GeneratorService extends IntentService {
private static final String TAG = GeneratorService.class.getSimpleName();
public static final String ACTION_GENERATE = TAG + " ACTION_GENERATE";
private static final String ACTION_STOP = TAG + " ACTION_STOP";
private static final String EXTRA_GAMETYPE = TAG + " EXTRA_GAMETYPE";
private static final String EXTRA_DIFFICULTY = TAG + " EXTRA_DIFFICULTY";
private static NotificationChannel notificationChannel;
private final QQWingOptions opts = new QQWingOptions();
private final List<Pair<GameType, GameDifficulty>> generationList = new LinkedList<>();
private final DatabaseHelper dbHelper = new DatabaseHelper(this);
private final LinkedList<int[]> generated = new LinkedList<>();
//private Handler mHandler = new Handler();
private int[] level;
public GeneratorService() {
super("Generator Service");
}
private void buildGenerationList() {
generationList.clear();
for (GameType validType : GameType.getValidGameTypes()) {
for (GameDifficulty validDifficulty : GameDifficulty.getValidDifficultyList()) {
int levelCount = dbHelper.getLevels(validDifficulty, validType).size();
Log.d(TAG, "\tType: " + validType.name() + " Difficulty: " + validDifficulty.name() + "\t: " + levelCount);
// add the missing levels to the list
for (int i = levelCount; i < NewLevelManager.PRE_SAVES_MIN; i++) {
generationList.add(new Pair<>(validType, validDifficulty));
}
}
}
// PrintGenerationList
Log.d(TAG, "### Missing Levels: ###");
int i = 0;
for (Pair<GameType, GameDifficulty> dataPair : generationList) {
Log.d(TAG, "\t" + i++ + ":\tType: " + dataPair.first.name() + " Difficulty: " + dataPair.second.name());
}
}
private void handleGenerationStop() {
stopForeground(true);
//mHandler.removeCallbacksAndMessages(null);
}
private void handleGenerationStart(Intent intent) {
GameType gameType;
GameDifficulty gameDifficulty;
try {
gameType = GameType.valueOf(intent.getExtras().getString(EXTRA_GAMETYPE, ""));
gameDifficulty = GameDifficulty.valueOf(intent.getExtras().getString(EXTRA_DIFFICULTY, ""));
} catch (IllegalArgumentException | NullPointerException e) {
gameType = null;
gameDifficulty = null;
}
if (gameType == null) {
generateLevels();
} else {
generateLevel(gameType, gameDifficulty);
}
}
private void generateLevels() {
// if we start this service multiple times while we are already generating...
// we ignore this call and just keep generating
buildGenerationList();
// generate from the list
if (generationList.size() > 0) {
// generate 1 level and wait for it to be done.
Pair<GameType, GameDifficulty> dataPair = generationList.get(0);
GameType type = dataPair.first;
GameDifficulty diff = dataPair.second;
generateLevel(type, diff);
}
}
private void generateLevel(final GameType gameType, final GameDifficulty gameDifficulty) {
generated.clear();
opts.gameDifficulty = gameDifficulty;
opts.action = Action.GENERATE;
opts.needNow = true;
opts.printSolution = false;
opts.gameType = gameType;
if (gameDifficulty == GameDifficulty.Easy && gameType == GameType.Default_9x9) {
opts.symmetry = Symmetry.ROTATE90;
} else {
opts.symmetry = Symmetry.NONE;
}
if (gameType == GameType.Default_12x12 && gameDifficulty != GameDifficulty.Challenge) {
opts.symmetry = Symmetry.ROTATE90;
}
final AtomicInteger puzzleCount = new AtomicInteger(0);
final AtomicBoolean done = new AtomicBoolean(false);
Runnable generationRunnable = new Runnable() {
// Create a new puzzle board
// and set the options
private final QQWing ss = createQQWing();
private QQWing createQQWing() {
QQWing ss = new QQWing(opts.gameType, opts.gameDifficulty);
ss.setRecordHistory(opts.printHistory || opts.printInstructions || opts.printStats || opts.gameDifficulty != GameDifficulty.Unspecified);
ss.setLogHistory(opts.logHistory);
ss.setPrintStyle(opts.printStyle);
return ss;
}
@Override
public void run() {
//android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try {
// Solve puzzle or generate puzzles
// until end of input for solving, or
// until we have generated the specified number.
while (!done.get()) {
// Record whether the puzzle was possible or
// not,
// so that we don't try to solve impossible
// givens.
boolean havePuzzle;
boolean solveImpossible;
if (opts.action == Action.GENERATE) {
// Generate a puzzle
havePuzzle = ss.generatePuzzleSymmetry(opts.symmetry);
} else {
// Read the next puzzle on STDIN
int[] puzzle = new int[QQWing.BOARD_SIZE];
if (getPuzzleToSolve(puzzle)) {
havePuzzle = ss.setPuzzle(puzzle);
if (havePuzzle) {
puzzleCount.getAndDecrement();
} else {
// Puzzle to solve is impossible.
solveImpossible = true;
}
} else {
// Set loop to terminate when nothing is
// left on STDIN
havePuzzle = false;
done.set(true);
}
puzzle = null;
}
if (opts.gameDifficulty != GameDifficulty.Unspecified) {
ss.solve();
}
if (havePuzzle) {
// Bail out if it didn't meet the difficulty
// standards for generation
if (opts.action == Action.GENERATE) {
// save the level anyways but keep going if the desired level is not yet generated
Level level = new Level();
level.setGameType(opts.gameType);
level.setDifficulty(ss.getDifficulty());
level.setPuzzle(ss.getPuzzle());
dbHelper.addLevel(level);
Log.d(TAG, "Generated: " + level.getGameType().name() + ",\t" + level.getDifficulty().name());
if (opts.gameDifficulty != GameDifficulty.Unspecified && opts.gameDifficulty != ss.getDifficulty()) {
havePuzzle = false;
// check if other threads have finished the job
if (puzzleCount.get() >= opts.numberToGenerate)
done.set(true);
} else {
int numDone = puzzleCount.incrementAndGet();
if (numDone >= opts.numberToGenerate) done.set(true);
if (numDone > opts.numberToGenerate) havePuzzle = false;
}
}
if (havePuzzle) {
generated.add(ss.getPuzzle());
}
}
}
} catch (Exception e) {
Log.e("QQWing", "Exception Occured", e);
return;
}
generationDone();
}
};
generationRunnable.run();
}
// this is called whenever a generation is done..
private void generationDone() {
// check if more can be generated
if (generationList.size() > 0) {
generateLevels();
} else {
// we are done and can close this service
handleGenerationStop();
}
}
private void showNotification(GameType gameType, GameDifficulty gameDifficulty) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (notificationChannel == null) {
notificationChannel = new NotificationChannel(Constant.GENERATOR_NOTIFICATION, getString(R.string.generator_notification), NotificationManager.IMPORTANCE_LOW);
}
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Constant.GENERATOR_NOTIFICATION);
builder.setContentTitle(getString(R.string.app_name));
builder.setContentText(getString(R.string.generating));
builder.setSubText(getString(gameType.getStringResID()) + ", " + getString(gameDifficulty.getStringResID()));
builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, SudokuHomeActivity.class), FLAG_UPDATE_CURRENT));
builder.setColor(ContextCompat.getColor(this, R.color.colorAccent));
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
builder.setWhen(0);
builder.setSmallIcon(R.drawable.splash_icon);
builder.setChannelId(Constant.GENERATOR_NOTIFICATION);
startForeground(50, builder.build());
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if (intent != null) {
String action = intent.getAction();
if (ACTION_GENERATE.equals(action)) handleGenerationStart(intent);
else if (ACTION_STOP.equals(action)) handleGenerationStop();
}
}
private boolean getPuzzleToSolve(int[] puzzle) {
if (level != null) {
if (puzzle.length == level.length) {
System.arraycopy(level, 0, puzzle, 0, level.length);
}
level = null;
return true;
}
return false;
}
private static class QQWingOptions {
final boolean printHistory = false;
final boolean printInstructions = false;
final boolean logHistory = false;
final PrintStyle printStyle = PrintStyle.READABLE;
final int numberToGenerate = 1;
final boolean printStats = false;
// defaults for options
boolean needNow = false;
boolean printPuzzle = false;
boolean printSolution = false;
boolean timer = false;
boolean countSolutions = false;
Action action = Action.NONE;
GameDifficulty gameDifficulty = GameDifficulty.Unspecified;
GameType gameType = GameType.Unspecified;
Symmetry symmetry = Symmetry.NONE;
int threads = Runtime.getRuntime().availableProcessors();
}
}
| 43.952381 | 175 | 0.555652 |
032ca3c3acc543409c504316e3686ae1b21cdb53
| 2,606 |
/*
* Copyright 2017 ThoughtWorks, 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 com.thoughtworks.go.domain;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class PipelineStateTest {
@Test
public void shouldBeEqualToAnotherPipelineStateIfAllAttributesMatch() {
PipelineState pipelineState1 = new PipelineState("p", new StageIdentifier("p", 1, "1", 1L, "s", "1"));
PipelineState pipelineState2 = new PipelineState("p", new StageIdentifier("p", 1, "1", 1L, "s", "1"));
pipelineState1.lock(1);
pipelineState2.lock(1);
assertEquals(pipelineState1, pipelineState2);
}
@Test
public void shouldBeEqualToAnotherPipelineStateIfBothDoNotHaveLockedBy() {
PipelineState pipelineState1 = new PipelineState("p");
PipelineState pipelineState2 = new PipelineState("p");
pipelineState1.lock(1);
pipelineState2.lock(1);
assertEquals(pipelineState1, pipelineState2);
}
@Test
public void shouldNotBeEqualToAnotherPipelineStateIfAllAttributesDoNotMatch() {
PipelineState pipelineState1 = new PipelineState("p", new StageIdentifier("p", 1, "1", 1L, "s", "1"));
PipelineState pipelineState2 = new PipelineState("p", new StageIdentifier("p", 1, "1", 1L, "s", "1"));
pipelineState1.lock(1);
assertNotEquals(pipelineState1, pipelineState2);
}
@Test
public void shouldSetLockedByPipelineIdWhileLockingAPipeline() {
PipelineState pipelineState = new PipelineState("p");
pipelineState.lock(100);
assertThat(pipelineState.isLocked(), is(true));
assertThat(pipelineState.getLockedByPipelineId(), is(100L));
}
@Test
public void shouldUnsetLockedByPipelineIdWhileUnlockingAPipeline() {
PipelineState pipelineState = new PipelineState("p");
pipelineState.lock(100);
pipelineState.unlock();
assertThat(pipelineState.isLocked(), is(false));
assertThat(pipelineState.getLockedByPipelineId(), is(0L));
}
}
| 37.768116 | 110 | 0.700307 |
d9e136a730cecca891c1d96ec6049666a6315cde
| 5,314 |
/** Generated Assertion Class - DO NOT CHANGE */
package au.org.greekwelfaresa.idempiere.test.assertj.u_webmenu;
import au.org.greekwelfaresa.idempiere.test.assertj.po.AbstractPOAssert;
import java.util.Objects;
import javax.annotation.Generated;
import org.compiere.model.X_U_WebMenu;
/** Generated assertion class for U_WebMenu
* @author idempiere-test (generated)
* @version Release 6.2 - $Id: d9e136a730cecca891c1d96ec6049666a6315cde $ */
@Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator")
public abstract class AbstractU_WebMenuAssert<SELF extends AbstractU_WebMenuAssert<SELF, ACTUAL>, ACTUAL extends X_U_WebMenu>
extends AbstractPOAssert<SELF, ACTUAL>
{
/** Standard Constructor */
public AbstractU_WebMenuAssert (ACTUAL actual, Class<SELF> selfType)
{
super (actual, selfType);
}
public SELF hasCategory(String expected)
{
isNotNull();
String actualField = actual.getCategory();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Category: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasDescription(String expected)
{
isNotNull();
String actualField = actual.getDescription();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Description: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF isHasSubMenu()
{
isNotNull();
if (!actual.isHasSubMenu()) {
failWithMessage("\nExpecting PO:\n <%s>\nto be HasSubMenu\nbut it was not",
getPODescription());
}
return myself;
}
public SELF isNotHasSubMenu()
{
isNotNull();
if (actual.isHasSubMenu()) {
failWithMessage("\nExpecting PO: \n <%s>\n to not be HasSubMenu\nbut it was",
getPODescription());
}
return myself;
}
public SELF hasHelp(String expected)
{
isNotNull();
String actualField = actual.getHelp();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Help: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasImageLink(String expected)
{
isNotNull();
String actualField = actual.getImageLink();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have ImageLink: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasMenuLink(String expected)
{
isNotNull();
String actualField = actual.getMenuLink();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have MenuLink: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasModule(String expected)
{
isNotNull();
String actualField = actual.getModule();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Module: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasName(String expected)
{
isNotNull();
String actualField = actual.getName();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Name: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasParentMenu_ID(int expected)
{
isNotNull();
int actualField = actual.getParentMenu_ID();
if (expected != actualField) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have ParentMenu_ID: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasPosition(String expected)
{
isNotNull();
String actualField = actual.getPosition();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Position: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasSequence(Object expected)
{
isNotNull();
bdAssert("Sequence", actual.getSequence(), expected);
return myself;
}
public SELF hasU_WebMenu_ID(int expected)
{
isNotNull();
int actualField = actual.getU_WebMenu_ID();
if (expected != actualField) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have U_WebMenu_ID: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
public SELF hasU_WebMenu_UU(String expected)
{
isNotNull();
String actualField = actual.getU_WebMenu_UU();
if (!Objects.equals(expected, actualField)) {
failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have U_WebMenu_UU: <%s>\nbut it was: <%s>",
getPODescription(), expected, actualField);
}
return myself;
}
}
| 30.895349 | 134 | 0.710764 |
72a288dac6a9e140a9b265c1c20f97a99b3d1413
| 1,951 |
package org.apache.spark.deploy;
/**
* Whether to submit, kill, or request the status of an application.
* The latter two operations are currently supported only for standalone and Mesos cluster modes.
*/
public class SparkSubmitAction {
static public scala.Enumeration.Value SUBMIT () { throw new RuntimeException(); }
static public scala.Enumeration.Value KILL () { throw new RuntimeException(); }
static public scala.Enumeration.Value REQUEST_STATUS () { throw new RuntimeException(); }
static public scala.Enumeration.Value PRINT_VERSION () { throw new RuntimeException(); }
static protected java.lang.Object readResolve () { throw new RuntimeException(); }
static public java.lang.String toString () { throw new RuntimeException(); }
static public scala.Enumeration.ValueSet values () { throw new RuntimeException(); }
static protected int nextId () { throw new RuntimeException(); }
static protected void nextId_$eq (int x$1) { throw new RuntimeException(); }
static protected scala.collection.Iterator<java.lang.String> nextName () { throw new RuntimeException(); }
static protected void nextName_$eq (scala.collection.Iterator<java.lang.String> x$1) { throw new RuntimeException(); }
static public final int maxId () { throw new RuntimeException(); }
static public final scala.Enumeration.Value apply (int x) { throw new RuntimeException(); }
static public final scala.Enumeration.Value withName (java.lang.String s) { throw new RuntimeException(); }
static protected final scala.Enumeration.Value Value () { throw new RuntimeException(); }
static protected final scala.Enumeration.Value Value (int i) { throw new RuntimeException(); }
static protected final scala.Enumeration.Value Value (java.lang.String name) { throw new RuntimeException(); }
static protected final scala.Enumeration.Value Value (int i, java.lang.String name) { throw new RuntimeException(); }
}
| 75.038462 | 122 | 0.743721 |
7f8947f64b485ddf33c10206ba3aa69cb40254ba
| 2,354 |
/*
* Copyright 2016 Open Networking Laboratory
*
* 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.onosproject.isis.controller.topology;
import org.onlab.packet.Ip4Address;
/**
* Representation of an ISIS device information.
*/
public interface DeviceInformation {
/**
* Gets system id.
*
* @return system id
*/
String systemId();
/**
* Sets system id.
*
* @param systemId system id
*/
void setSystemId(String systemId);
/**
* Gets interface ids.
*
* @return interface ids
*/
Ip4Address interfaceId();
/**
* Sets interface id.
*
* @param interfaceId interface id
*/
void setInterfaceId(Ip4Address interfaceId);
/**
* Gets area id.
*
* @return area id
*/
String areaId();
/**
* Sets area id.
*
* @param areaId area id
*/
void setAreaId(String areaId);
/**
* Gets device information is already created or not.
*
* @return true if device information is already created else false
*/
boolean isAlreadyCreated();
/**
* Sets device information is already created or not.
*
* @param alreadyCreated true if device information is already created else false
*/
void setAlreadyCreated(boolean alreadyCreated);
/**
* Gets device is dis or not.
*
* @return true if device is dis else false
*/
boolean isDis();
/**
* Sets device is dis or not.
*
* @param dis true if device is dr else false
*/
void setDis(boolean dis);
/**
* Gets neighbor id.
*
* @return neighbor id
*/
String neighborId();
/**
* Sets neighbor id.
*
* @param neighborId neighbor id
*/
void setNeighborId(String neighborId);
}
| 21.796296 | 85 | 0.614274 |
70167cce697abbb84831f4351a5da2422134d2d2
| 1,829 |
package org.assertj.core.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.util.List;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runners.model.MultipleFailureException;
public class JUnitSoftAssertionsFailureTest {
//we cannot make it a rule here, because we need to test the failure without this test failing!
//@Rule
public final JUnitSoftAssertions softly = new JUnitSoftAssertions();
@Test
public void should_report_all_errors() throws Throwable {
try {
softly.assertThat(1).isEqualTo(1);
softly.assertThat(1).isEqualTo(2);
softly.assertThat(Lists.newArrayList(1, 2)).containsOnly(1, 3);
MultipleFailureException.assertEmpty(softly.getCollector().errors());
fail("Should not reach here");
} catch (MultipleFailureException e) {
List<Throwable> failures = e.getFailures();
assertThat(failures).hasSize(2).extracting("message").contains("expected:<[2]> but was:<[1]>",
"\n" +
"Expecting:\n" +
" <[1, 2]>\n" +
"to contain only:\n" +
" <[1, 3]>\n" +
"elements not found:\n" +
" <[3]>\n" +
"and elements not expected:\n" +
" <[2]>\n");
}
}
}
| 44.609756 | 101 | 0.459267 |
ef74ab1e71a4c41f3923615f6c369880345cf2b8
| 1,399 |
/*
* Copyright (c) 2019, WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.ballerina.plugins.idea.extensions.server;
import com.google.gson.JsonObject;
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier;
/**
* Represents an AST change notification sent from client to server.
*/
public class BallerinaASTDidChange {
JsonObject ast;
VersionedTextDocumentIdentifier textDocumentIdentifier;
public JsonObject getAst() {
return ast;
}
public void setAst(JsonObject ast) {
this.ast = ast;
}
public VersionedTextDocumentIdentifier getTextDocumentIdentifier() {
return textDocumentIdentifier;
}
public void setTextDocumentIdentifier(VersionedTextDocumentIdentifier textDocumentIdentifier) {
this.textDocumentIdentifier = textDocumentIdentifier;
}
}
| 30.413043 | 99 | 0.743388 |
81732c01f127231b562eb3e781e97ab04e11630d
| 13,900 |
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.deploy.test;
import static org.hamcrest.Matchers.is;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.PathAssert;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.junit.Assert;
/**
* Allows for setting up a Jetty server for testing based on XML configuration files.
*/
public class XmlConfiguredJetty
{
private List<URL> _xmlConfigurations;
private Map<String,String> _properties = new HashMap<>();
private Server _server;
private int _serverPort;
private String _scheme = HttpScheme.HTTP.asString();
private File _jettyHome;
public XmlConfiguredJetty(TestingDir testdir) throws IOException
{
_xmlConfigurations = new ArrayList<>();
Properties properties = new Properties();
String jettyHomeBase = testdir.getDir().getAbsolutePath();
// Ensure we have a new (pristene) directory to work with.
int idx = 0;
_jettyHome = new File(jettyHomeBase + "#" + idx);
while (_jettyHome.exists())
{
idx++;
_jettyHome = new File(jettyHomeBase + "#" + idx);
}
deleteContents(_jettyHome);
// Prepare Jetty.Home (Test) dir
_jettyHome.mkdirs();
File logsDir = new File(_jettyHome,"logs");
logsDir.mkdirs();
File etcDir = new File(_jettyHome,"etc");
etcDir.mkdirs();
IO.copyFile(MavenTestingUtils.getTestResourceFile("etc/realm.properties"),new File(etcDir,"realm.properties"));
IO.copyFile(MavenTestingUtils.getTestResourceFile("etc/webdefault.xml"),new File(etcDir,"webdefault.xml"));
File webappsDir = new File(_jettyHome,"webapps");
if (webappsDir.exists())
{
deleteContents(webappsDir);
}
webappsDir.mkdirs();
File tmpDir = new File(_jettyHome,"tmp");
if (tmpDir.exists())
{
deleteContents(tmpDir);
}
tmpDir.mkdirs();
File workishDir = new File(_jettyHome,"workish");
if (workishDir.exists())
{
deleteContents(workishDir);
}
workishDir.mkdirs();
// Setup properties
System.setProperty("java.io.tmpdir",tmpDir.getAbsolutePath());
properties.setProperty("jetty.home",_jettyHome.getAbsolutePath());
System.setProperty("jetty.home",_jettyHome.getAbsolutePath());
properties.setProperty("test.basedir",MavenTestingUtils.getBasedir().getAbsolutePath());
properties.setProperty("test.resourcesdir",MavenTestingUtils.getTestResourcesDir().getAbsolutePath());
properties.setProperty("test.webapps",webappsDir.getAbsolutePath());
properties.setProperty("test.targetdir",MavenTestingUtils.getTargetDir().getAbsolutePath());
properties.setProperty("test.workdir",workishDir.getAbsolutePath());
// Write out configuration for use by ConfigurationManager.
File testConfig = new File(_jettyHome, "xml-configured-jetty.properties");
try (OutputStream out = new FileOutputStream(testConfig))
{
properties.store(out,"Generated by " + XmlConfiguredJetty.class.getName());
}
for (Object key:properties.keySet())
setProperty(String.valueOf(key),String.valueOf(properties.get(key)));
}
public void addConfiguration(File xmlConfigFile) throws MalformedURLException
{
addConfiguration(Resource.toURL(xmlConfigFile));
}
public void addConfiguration(String testConfigName) throws MalformedURLException
{
addConfiguration(MavenTestingUtils.getTestResourceFile(testConfigName));
}
public void addConfiguration(URL xmlConfig)
{
_xmlConfigurations.add(xmlConfig);
}
public void assertNoWebAppContexts()
{
List<WebAppContext> contexts = getWebAppContexts();
if (contexts.size() > 0)
{
for (WebAppContext context : contexts)
{
System.err.println("WebAppContext should not exist:\n" + context);
}
Assert.assertEquals("Contexts.size",0,contexts.size());
}
}
public String getResponse(String path) throws IOException
{
URI destUri = getServerURI().resolve(path);
URL url = destUri.toURL();
URLConnection conn = url.openConnection();
InputStream in = null;
try
{
in = conn.getInputStream();
return IO.toString(in);
}
finally
{
IO.close(in);
}
}
public void assertResponseContains(String path, String needle) throws IOException
{
// System.err.println("Issuing request to " + path);
String content = getResponse(path);
Assert.assertTrue("Content should contain <" + needle + ">, instead got <" + content + ">",content.contains(needle));
}
public void assertWebAppContextsExists(String... expectedContextPaths)
{
List<WebAppContext> contexts = getWebAppContexts();
if (expectedContextPaths.length != contexts.size())
{
System.err.println("## Expected Contexts");
for (String expected : expectedContextPaths)
{
System.err.println(expected);
}
System.err.println("## Actual Contexts");
for (WebAppContext context : contexts)
{
System.err.printf("%s ## %s%n",context.getContextPath(),context);
}
Assert.assertEquals("Contexts.size",expectedContextPaths.length,contexts.size());
}
for (String expectedPath : expectedContextPaths)
{
boolean found = false;
for (WebAppContext context : contexts)
{
if (context.getContextPath().equals(expectedPath))
{
found = true;
Assert.assertThat("Context[" + context.getContextPath() + "].state", context.getState(), is("STARTED"));
break;
}
}
Assert.assertTrue("Did not find Expected Context Path " + expectedPath,found);
}
}
private void copyFile(String type, File srcFile, File destFile) throws IOException
{
PathAssert.assertFileExists(type + " File",srcFile);
IO.copyFile(srcFile,destFile);
PathAssert.assertFileExists(type + " File",destFile);
System.err.printf("Copy %s: %s%n To %s: %s%n",type,srcFile,type,destFile);
System.err.printf("Destination Exists: %s - %s%n",destFile.exists(),destFile);
}
public void copyWebapp(String srcName, String destName) throws IOException
{
System.err.printf("Copying Webapp: %s -> %s%n",srcName,destName);
File srcDir = MavenTestingUtils.getTestResourceDir("webapps");
File destDir = new File(_jettyHome,"webapps");
File srcFile = new File(srcDir,srcName);
File destFile = new File(destDir,destName);
copyFile("Webapp",srcFile,destFile);
}
private void deleteContents(File dir)
{
// System.err.printf("Delete (dir) %s/%n",dir);
if (!dir.exists())
{
return;
}
File[] files = dir.listFiles();
if (files != null)
{
for (File file : files)
{
// Safety measure. only recursively delete within target directory.
if (file.isDirectory() && file.getAbsolutePath().contains("target" + File.separator))
{
deleteContents(file);
Assert.assertTrue("Delete failed: " + file.getAbsolutePath(),file.delete());
}
else
{
System.err.printf("Delete (file) %s%n",file);
Assert.assertTrue("Delete failed: " + file.getAbsolutePath(),file.delete());
}
}
}
}
public File getJettyDir(String name)
{
return new File(_jettyHome,name);
}
public File getJettyHome()
{
return _jettyHome;
}
public String getScheme()
{
return _scheme;
}
public Server getServer()
{
return _server;
}
public int getServerPort()
{
return _serverPort;
}
public URI getServerURI() throws UnknownHostException
{
StringBuilder uri = new StringBuilder();
URIUtil.appendSchemeHostPort(uri, getScheme(), InetAddress.getLocalHost().getHostAddress(), getServerPort());
return URI.create(uri.toString());
}
public List<WebAppContext> getWebAppContexts()
{
List<WebAppContext> contexts = new ArrayList<>();
HandlerCollection handlers = (HandlerCollection)_server.getHandler();
Handler children[] = handlers.getChildHandlers();
for (Handler handler : children)
{
if (handler instanceof WebAppContext)
{
WebAppContext context = (WebAppContext)handler;
contexts.add(context);
}
}
return contexts;
}
public void load() throws Exception
{
XmlConfiguration last = null;
Object[] obj = new Object[this._xmlConfigurations.size()];
// Configure everything
for (int i = 0; i < this._xmlConfigurations.size(); i++)
{
URL configURL = this._xmlConfigurations.get(i);
XmlConfiguration configuration = new XmlConfiguration(configURL);
if (last != null)
configuration.getIdMap().putAll(last.getIdMap());
configuration.getProperties().putAll(_properties);
obj[i] = configuration.configure();
last = configuration;
}
// Test for Server Instance.
Server foundServer = null;
int serverCount = 0;
for (int i = 0; i < this._xmlConfigurations.size(); i++)
{
if (obj[i] instanceof Server)
{
if (obj[i].equals(foundServer))
{
// Identical server instance found
break;
}
foundServer = (Server)obj[i];
serverCount++;
}
}
if (serverCount <= 0)
{
throw new Exception("Load failed to configure a " + Server.class.getName());
}
Assert.assertEquals("Server load count",1,serverCount);
this._server = foundServer;
this._server.setStopTimeout(10);
}
public void removeWebapp(String name)
{
File destDir = new File(_jettyHome,"webapps");
File contextFile = new File(destDir,name);
if (contextFile.exists())
{
Assert.assertTrue("Delete of Webapp file: " + contextFile.getAbsolutePath(),contextFile.delete());
}
}
public void setProperty(String key, String value)
{
_properties.put(key,value);
}
public void setScheme(String scheme)
{
this._scheme = scheme;
}
public void start() throws Exception
{
Assert.assertNotNull("Server should not be null (failed load?)",_server);
_server.start();
// Find the active server port.
_serverPort = -1;
Connector connectors[] = _server.getConnectors();
for (int i = 0; _serverPort<0 && i < connectors.length; i++)
{
if (connectors[i] instanceof NetworkConnector)
{
int port = ((NetworkConnector)connectors[i]).getLocalPort();
if (port>0)
_serverPort=port;
}
}
Assert.assertTrue("Server Port is between 1 and 65535. Actually <" + _serverPort + ">",(1 <= this._serverPort) && (this._serverPort <= 65535));
// Uncomment to have server start and continue to run (without exiting)
// System.err.printf("Listening to port %d%n",this.serverPort);
// server.join();
}
public void stop() throws Exception
{
_server.stop();
}
}
| 33.253589 | 151 | 0.602158 |
8d7613fa664bc98513e44377f8f033830e324f02
| 5,706 |
package com.x.bbs.assemble.control.jaxrs.permissioninfo;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.x.base.core.http.ActionResult;
import com.x.base.core.http.EffectivePerson;
import com.x.base.core.http.HttpMediaType;
import com.x.base.core.http.annotation.HttpMethodDescribe;
import com.x.base.core.logger.Logger;
import com.x.base.core.logger.LoggerFactory;
import com.x.base.core.project.jaxrs.AbstractJaxrsAction;
import com.x.base.core.project.jaxrs.ResponseFactory;
import com.x.bbs.assemble.control.jaxrs.configsetting.exception.ConfigSettingProcessException;
import com.x.bbs.assemble.control.jaxrs.permissioninfo.exception.SectionIdEmptyException;
import com.x.bbs.assemble.control.jaxrs.permissioninfo.exception.SubjectIdEmptyException;
@Path("permission")
public class PermissionInfoAction extends AbstractJaxrsAction {
private Logger logger = LoggerFactory.getLogger( PermissionInfoAction.class );
@HttpMethodDescribe(value = "查询用户在指定板块中的所有操作权限.", response = WrapOutSectionPermission.class)
@GET
@Path("section/{sectionId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public Response getSectionOperationPermissoin( @Context HttpServletRequest request, @PathParam("sectionId") String sectionId ) {
ActionResult<WrapOutSectionPermission> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
Boolean check = true;
if( check ){
if( sectionId == null || sectionId.isEmpty() ){
check = false;
Exception exception = new SectionIdEmptyException();
result.error( exception );
}
}
if(check){
try {
result = new ExcuteGetSectionOperationPermissoin().execute( request, effectivePerson, sectionId );
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ConfigSettingProcessException( e, "查询用户在指定板块中的所有操作权限时发生异常!" );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
return ResponseFactory.getDefaultActionResultResponse(result);
}
@HttpMethodDescribe(value = "查询用户对指定主题的所有操作权限.", response = WrapOutSubjectPermission.class)
@GET
@Path("subject/{subjectId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public Response getSubjectOperationPermissoin( @Context HttpServletRequest request, @PathParam("subjectId") String subjectId ) {
ActionResult<WrapOutSubjectPermission> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
Boolean check = true;
if( check ){
if( subjectId == null || subjectId.isEmpty() ){
check = false;
Exception exception = new SubjectIdEmptyException();
result.error( exception );
}
}
if(check){
try {
result = new ExcuteGetSubjectOperationPermissoin().execute( request, effectivePerson, subjectId );
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ConfigSettingProcessException( e, "查询用户对指定主题的所有操作权限时发生异常!" );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
return ResponseFactory.getDefaultActionResultResponse(result);
}
@HttpMethodDescribe(value = "查询用户中否可以在指定版块中发布主题.", response = WrapOutPermissionAble.class)
@GET
@Path("subjectPublishable/{sectionId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public Response subjectPublishable( @Context HttpServletRequest request, @PathParam("sectionId") String sectionId ) {
ActionResult<WrapOutPermissionAble> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
Boolean check = true;
if( check ){
if( sectionId == null || sectionId.isEmpty() ){
check = false;
Exception exception = new SectionIdEmptyException();
result.error( exception );
}
}
if(check){
try {
result = new ExcuteCheckSubjectPublishable().execute( request, effectivePerson, sectionId );
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ConfigSettingProcessException( e, "查询用户中否可以在指定版块中发布主题时发生异常!" );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
return ResponseFactory.getDefaultActionResultResponse(result);
}
@HttpMethodDescribe(value = "查询用户是否可以对指定主题进行回复.", response = WrapOutPermissionAble.class)
@GET
@Path("replyPublishable/{subjectId}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public Response replyPublishable( @Context HttpServletRequest request, @PathParam("subjectId") String subjectId ) {
ActionResult<WrapOutPermissionAble> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
Boolean check = true;
if( check ){
if( subjectId == null || subjectId.isEmpty() ){
check = false;
Exception exception = new SubjectIdEmptyException();
result.error( exception );
}
}
if(check){
try {
result = new ExcuteCheckReplyPublishable().execute( request, effectivePerson, subjectId );
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ConfigSettingProcessException( e, "查询用户是否可以对指定主题进行回复时发生异常!" );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
return ResponseFactory.getDefaultActionResultResponse(result);
}
}
| 38.04 | 129 | 0.754644 |
bd6acfc1b7a0b46d0ceecdef2e6ed47396cc967c
| 7,340 |
package com.sap.cloud.lm.sl.cf.core.helpers;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudfoundry.client.lib.CloudControllerClient;
import org.cloudfoundry.client.lib.domain.CloudApplication;
import org.cloudfoundry.client.lib.domain.ImmutableCloudApplication;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.sap.cloud.lm.sl.cf.core.auditlogging.AuditLoggingProvider;
import com.sap.cloud.lm.sl.cf.core.auditlogging.impl.AuditLoggingFacadeSLImpl;
import com.sap.cloud.lm.sl.cf.core.model.CloudTarget;
import com.sap.cloud.lm.sl.cf.core.model.ConfigurationEntry;
import com.sap.cloud.lm.sl.cf.core.model.ConfigurationSubscription;
import com.sap.cloud.lm.sl.cf.core.persistence.query.ConfigurationEntryQuery;
import com.sap.cloud.lm.sl.cf.core.persistence.query.ConfigurationSubscriptionQuery;
import com.sap.cloud.lm.sl.cf.core.persistence.query.Query;
import com.sap.cloud.lm.sl.cf.core.persistence.service.ConfigurationEntryService;
import com.sap.cloud.lm.sl.cf.core.persistence.service.ConfigurationSubscriptionService;
import com.sap.cloud.lm.sl.cf.core.util.ConfigurationEntriesUtil;
import com.sap.cloud.lm.sl.common.util.JsonUtil;
import com.sap.cloud.lm.sl.common.util.TestUtil;
import com.sap.cloud.lm.sl.mta.model.Version;
public class MtaConfigurationPurgerTest {
private static final int ENTRY_ID_TO_REMOVE = 0;
private static final int ENTRY_ID_TO_KEEP_1 = 1;
private static final int ENTRY_ID_TO_KEEP_2 = 2;
private static final int SUBSCRIPTION_ID_TO_REMOVE = 2;
private static final int SUBSCRIPTION_ID_TO_KEEP = 3;
private static final String APPLICATION_NAME_TO_KEEP = "app-to-keep";
private static final String APPLICATION_NAME_TO_REMOVE = "app-to-remove";
private static final String RESOURCE_LOCATION = "application-env-01.json";
private final ConfigurationEntry ENTRY_TO_DELETE = createEntry(ENTRY_ID_TO_REMOVE, "remove:true");
private final ConfigurationSubscription SUBSCRIPTION_TO_DELETE = createSubscription(SUBSCRIPTION_ID_TO_REMOVE,
APPLICATION_NAME_TO_REMOVE);
private final static String TARGET_SPACE = "space";
private final static String TARGET_ORG = "org";
@Mock
CloudControllerClient client;
@Mock
ConfigurationEntryService configurationEntryService;
@Mock(answer = Answers.RETURNS_SELF)
ConfigurationEntryQuery configurationEntryQuery;
@Mock
ConfigurationSubscriptionService configurationSubscriptionService;
@Mock(answer = Answers.RETURNS_SELF)
ConfigurationSubscriptionQuery configurationSubscriptionQuery;
@Mock
AuditLoggingFacadeSLImpl auditLoggingFacade;
private final List<Query<?, ?>> queriesToVerifyDeleteCallOn = new ArrayList<>();
private final List<Query<?, ?>> queriesToVerifyNoDeleteCallOn = new ArrayList<>();
@Before
public void setUp() throws IOException {
MockitoAnnotations.initMocks(this);
AuditLoggingProvider.setFacade(auditLoggingFacade);
initApplicationsMock();
initConfigurationEntriesMock();
initConfigurationSubscriptionsMock();
}
@Test
public void testPurge() {
MtaConfigurationPurger purger = new MtaConfigurationPurger(client, configurationEntryService, configurationSubscriptionService);
purger.purge("org", "space");
verifyConfigurationEntriesDeleted();
verifyConfigurationEntriesNotDeleted();
Mockito.verify(auditLoggingFacade)
.logConfigDelete(ENTRY_TO_DELETE);
Mockito.verify(auditLoggingFacade)
.logConfigDelete(SUBSCRIPTION_TO_DELETE);
}
private void verifyConfigurationEntriesDeleted() {
for (Query<?, ?> queryToExecuteDeleteOn : queriesToVerifyDeleteCallOn) {
Mockito.verify(queryToExecuteDeleteOn)
.delete();
}
}
private void verifyConfigurationEntriesNotDeleted() {
for (Query<?, ?> queryNotToExecuteDeleteOn : queriesToVerifyNoDeleteCallOn) {
Mockito.verify(queryNotToExecuteDeleteOn, Mockito.never())
.delete();
}
}
private void initApplicationsMock() throws IOException {
List<CloudApplication> applications = new ArrayList<>();
applications.add(createApplication(APPLICATION_NAME_TO_KEEP, getApplicationEnvFromFile(RESOURCE_LOCATION)));
applications.add(createApplication("app-2", new HashMap<>()));
Mockito.when(client.getApplications())
.thenReturn(applications);
}
private void initConfigurationEntriesMock() {
when(configurationEntryService.createQuery()).thenReturn(configurationEntryQuery);
doReturn(getConfigurationEntries()).when(configurationEntryQuery)
.list();
}
private List<ConfigurationEntry> getConfigurationEntries() {
return Arrays.asList(ENTRY_TO_DELETE, createEntry(ENTRY_ID_TO_KEEP_1, "anatz:dependency-1"),
createEntry(ENTRY_ID_TO_KEEP_2, "anatz:dependency-2"));
}
private void initConfigurationSubscriptionsMock() {
when(configurationSubscriptionService.createQuery()).thenReturn(configurationSubscriptionQuery);
doReturn(getConfigurationSubscriptions()).when(configurationSubscriptionQuery)
.list();
}
private List<ConfigurationSubscription> getConfigurationSubscriptions() {
return Arrays.asList(SUBSCRIPTION_TO_DELETE, createSubscription(SUBSCRIPTION_ID_TO_KEEP, APPLICATION_NAME_TO_KEEP));
}
private CloudApplication createApplication(String applicationName, Map<String, Object> env) {
MapToEnvironmentConverter envConverter = new MapToEnvironmentConverter(false);
return ImmutableCloudApplication.builder()
.name(applicationName)
.env(envConverter.asEnv(env))
.build();
}
private Map<String, Object> getApplicationEnvFromFile(String path) {
String envJson = TestUtil.getResourceAsString(path, MtaConfigurationPurgerTest.class);
return JsonUtil.convertJsonToMap(envJson);
}
private ConfigurationSubscription createSubscription(int id, String applicationName) {
return new ConfigurationSubscription(id, null, null, applicationName, null, null, null);
}
private ConfigurationEntry createEntry(int id, String providerId) {
return new ConfigurationEntry(id,
ConfigurationEntriesUtil.PROVIDER_NID,
providerId,
Version.parseVersion("1.0.0"),
new CloudTarget(TARGET_ORG, TARGET_SPACE),
null,
null,
null);
}
}
| 43.431953 | 136 | 0.700272 |
83fa00e12b57afb5967dec7edbcbef8fca90d869
| 1,253 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: model/user/users_online_statuses.proto
package im.turms.turms.pojo.bo.user;
public interface UsersOnlineStatusesOrBuilder extends
// @@protoc_insertion_point(interface_extends:im.turms.proto.UsersOnlineStatuses)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .im.turms.proto.UserStatusDetail user_statuses = 1;</code>
*/
java.util.List<im.turms.turms.pojo.bo.user.UserStatusDetail>
getUserStatusesList();
/**
* <code>repeated .im.turms.proto.UserStatusDetail user_statuses = 1;</code>
*/
im.turms.turms.pojo.bo.user.UserStatusDetail getUserStatuses(int index);
/**
* <code>repeated .im.turms.proto.UserStatusDetail user_statuses = 1;</code>
*/
int getUserStatusesCount();
/**
* <code>repeated .im.turms.proto.UserStatusDetail user_statuses = 1;</code>
*/
java.util.List<? extends im.turms.turms.pojo.bo.user.UserStatusDetailOrBuilder>
getUserStatusesOrBuilderList();
/**
* <code>repeated .im.turms.proto.UserStatusDetail user_statuses = 1;</code>
*/
im.turms.turms.pojo.bo.user.UserStatusDetailOrBuilder getUserStatusesOrBuilder(
int index);
}
| 32.973684 | 85 | 0.705507 |
45d66eb455a0a7b14b750aa0d1d1d24679153c08
| 569 |
package eu.fbk.rdfpro.util;
import java.util.Arrays;
import org.junit.Test;
import org.openrdf.query.algebra.ValueExpr;
import org.openrdf.query.impl.ListBindingSet;
public class AlgebraTest {
@Test
public void test() throws Throwable {
final ValueExpr expr = Algebra.parseValueExpr("CONCAT(STR(ks:mint(rdf:type)), ?x)", null,
Namespaces.DEFAULT.uriMap());
System.out.println(Algebra.evaluateValueExpr(expr, new ListBindingSet(Arrays.asList("x"),
Statements.VALUE_FACTORY.createLiteral("__test"))));
}
}
| 28.45 | 97 | 0.695958 |
e525164e328265966c9b077b2622b542f180696b
| 2,136 |
/*
* Copyright 2014-2020 Rudy De Busscher
*
* 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 be.atbash.ee.jsf.valerie.recording;
import be.atbash.ee.jsf.jerry.interceptor.AbstractRendererInterceptor;
import be.atbash.ee.jsf.jerry.interceptor.exception.SkipAfterInterceptorsException;
import be.atbash.ee.jsf.jerry.ordering.InvocationOrder;
import be.atbash.ee.jsf.jerry.storage.ComponentStorage;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import javax.faces.render.Renderer;
import javax.inject.Inject;
import java.util.List;
/**
*
*/
@ApplicationScoped
@InvocationOrder(5)
public class RecordingInterceptor extends AbstractRendererInterceptor {
@Inject
private RecordingInfoManager recordingInfoManager;
@Inject
private ComponentStorage storage;
@Override
public void afterGetConvertedValue(FacesContext facesContext, UIComponent uiComponent, Object submittedValue, Object convertedValue,
Renderer wrapped) throws ConverterException, SkipAfterInterceptorsException {
String viewId = facesContext.getViewRoot().getViewId();
String clientId = uiComponent.getClientId(facesContext);
List<RecordValueInfo> recordingInformation = (List<RecordValueInfo>) storage.getRecordingInformation(viewId, clientId);
for (RecordValueInfo recordValueInfo : recordingInformation) {
recordingInfoManager.keepInfo(facesContext, recordValueInfo, convertedValue);
}
}
}
| 36.827586 | 136 | 0.767322 |
92295cdbc584845065f71f4ad947e38d344f8942
| 431 |
package com.vaadin.fastui.backend.POJO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import java.util.List;
@Data
public class PixaBay {
@SerializedName("total")
@Expose
private Integer total;
@SerializedName("totalHits")
@Expose
private Integer totalHits;
@SerializedName("hits")
@Expose
private List<Hit> hits = null;
}
| 19.590909 | 50 | 0.721578 |
930c88f6a6016b4fbba62aef144248d16162441d
| 2,433 |
package de.teiesti.proxy;
import java.util.Iterator;
/**
* A {@code ProxyIterator} iterates over the associated proxies in the same order as a given other iterator iterates
* over the subjects. In detail: Assume you have an iterator iterating over some subject. Now you encapsulate it - by
* the help of a {@link Mapper} - within a proxy iterator. The resulting iterator behaves exactly like the given
* original except that it returns proxies pointing to the subjects.<br />
* Depending on the {@link Mapper} implementation the {@code ProxyIterator} is very fast, because a subject is not
* mapped until it is needed.
*
* @param <Proxy> the type of the proxy
* @param <Subject> the type of the subject
*/
public class ProxyIterator<Proxy, Subject> implements Iterator<Proxy> {
private Iterator<Subject> subjects;
private Mapper<Proxy, Subject> mapper;
/**
* Creates a {@code ProxyIterator} from a given subject iterator with the help of a {@link Mapper}. The mapper is
* used to create a proxy for each subject (which is needed).
*
* @param subjects an iterator over some subjects
* @param mapper a mapper which maps the subjects to the proxies
*/
public ProxyIterator(Iterator<Subject> subjects, Mapper<Proxy, Subject> mapper) {
if (subjects == null)
throw new IllegalArgumentException("subjects == null");
if (mapper == null)
throw new IllegalArgumentException("mapper == null");
this.subjects = subjects;
this.mapper = mapper;
}
/**
* Returns if this iterator has a next proxy. This method return {@code true} if and only if the underlying
* iterator has a next subject.
*
* @return if this iterator has a next proxy
*/
@Override
public boolean hasNext() {
return subjects.hasNext();
}
/**
* Returns the next proxy in this iterator. This is done in two steps: First the next subject is taken from the
* underlying iterator. Second the taken subject is converted to a proxy using the
* {@link Mapper#getProxy(Object) }-method.
* @return the next proxy
*/
@Override
public Proxy next() {
return mapper.getProxy(subjects.next());
}
/**
* Removes - if supported - the current proxy from the associated collection. This method is transparent which
* means that calling this method removes the subject from the collection which is associated to the underlying
* subject iterator.
*/
@Override
public void remove() {
subjects.remove();
}
}
| 34.267606 | 117 | 0.725442 |
56336ebd17598371bf774c174f9671cbfe5bec06
| 2,450 |
package crisscrosscrass.Tasks;
import com.jfoenix.controls.JFXCheckBox;
import javafx.application.Platform;
import javafx.scene.paint.Paint;
public class ChangeCheckBox {
private static String isInProgress = "#EEF442";
private static String isSuccessful = "#0F9D58";
private static String isNotSuccessful = "#FF0000";
private static String isStandard = "#535341";
public static void adjustStyle(boolean select, String status, JFXCheckBox editedCheckBox){
if (("complete").equals(status)){
Platform.runLater(() -> {
editedCheckBox.setStyle("-fx-background-color: transparent");
editedCheckBox.setCheckedColor(Paint.valueOf(isSuccessful));
editedCheckBox.setUnCheckedColor(Paint.valueOf(isSuccessful));
editedCheckBox.setSelected(select);
});
} else if (("progress").equals(status)){
Platform.runLater(() -> {
editedCheckBox.setStyle("-fx-background-color: "+isInProgress+"");
editedCheckBox.setCheckedColor(Paint.valueOf(isInProgress));
editedCheckBox.setUnCheckedColor(Paint.valueOf(isInProgress));
editedCheckBox.setSelected(select);
});
}else if(("nope").equals(status)){
Platform.runLater(() -> {
editedCheckBox.setStyle("-fx-background-color: transparent");
editedCheckBox.setCheckedColor(Paint.valueOf(isNotSuccessful));
editedCheckBox.setUnCheckedColor(Paint.valueOf(isNotSuccessful));
editedCheckBox.setSelected(select);
});
}else {
Platform.runLater(() -> {
editedCheckBox.setStyle("-fx-background-color: transparent");
editedCheckBox.setCheckedColor(Paint.valueOf(isStandard));
editedCheckBox.setUnCheckedColor(Paint.valueOf(isStandard));
editedCheckBox.setSelected(select);
});
}
}
public static String getIsInProgress() { return isInProgress.substring(1,7).toLowerCase(); }
public static String getIsSuccessful() {
return isSuccessful.substring(1,7).toLowerCase();
}
public static String getIsNotSuccessful() {
return isNotSuccessful.substring(1,7).toLowerCase();
}
public static String getIsStandard() {
return isStandard.substring(1,7).toLowerCase();
}
}
| 37.121212 | 96 | 0.637551 |
574266dc810dda3d2dc76eece08e6872b70b770a
| 4,656 |
package edu.udacity.java.nano;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
// Credit to Abdulla H. for adding the reference link below in Student Hub:
// https://stackoverflow.com/questions/54599169/how-to-configure-selenium-webdriver-with-spring-boot-for-ui-testing
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class WebSocketChatServerTest {
@Autowired
private Environment environment;
private static String BASE_URL;
private static String CHAT_URL;
private static final String USERNAME = "java-nano";
private static final int TIME_OUT_IN_SECONDS = 5;
private WebDriver webDriver;
@PostConstruct
public void initUrls() {
BASE_URL = "http://localhost:9090/";
CHAT_URL = "http://localhost:9090/index?username="+USERNAME;
}
@Before
public void init() {
webDriver = initWebDriver();
}
@Test
public void navigate_to_login_page() {
webDriver.get(BASE_URL);
Assert.assertEquals(webDriver.getTitle(), "Chat Room Login");
}
@Test
public void join_chat_room() {
webDriver.get(BASE_URL);
WebElement usernameInput = webDriver.findElement(By.id("username"));
usernameInput.sendKeys(USERNAME);
WebElement loginButton = webDriver.findElement(By.className("submit"));
loginButton.click();
waitForServerEndpointResponse(0);
String currentUrl = webDriver.getCurrentUrl();
Assert.assertEquals(currentUrl, String.format(CHAT_URL, USERNAME));
WebElement onlineUsers = webDriver.findElement(By.id("chat-num"));
Assert.assertEquals(onlineUsers.getText(), "1");
}
@Test
public void send_chat_message() {
String message = "Project 1";
webDriver.get(String.format(CHAT_URL, USERNAME));
int oldMessageCount = webDriver.findElements(By.className("message-content")).size();
WebElement messageInput = webDriver.findElement(By.id("msg"));
messageInput.sendKeys(message);
WebElement sendButton = webDriver.findElement(By.id("send"));
sendButton.click();
waitForServerEndpointResponse(oldMessageCount);
String expectedMessage = String.format("%s: %s", USERNAME, message);
List<WebElement> messageElements = webDriver.findElements((By.className("message-content")));
WebElement messageElement = messageElements.get(messageElements.size() - 1);
Assert.assertEquals(expectedMessage, messageElement.getText());
}
@Test
public void exit_to_app() {
webDriver.get(String.format(CHAT_URL, USERNAME));
WebElement exitButton = webDriver.findElement(By.id("exit"));
exitButton.click();
Assert.assertEquals(BASE_URL, webDriver.getCurrentUrl());
}
@After
public void finalize() {
if (webDriver != null) {
webDriver.close();
}
}
private WebDriver initWebDriver() {
String driverPath = environment.getProperty("selenium.chromedriver");
assert driverPath != null;
ChromeDriverService service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File(driverPath))
.build();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--start-minimized", "--disable-extensions", "--disable-dev-shm-usage", "--no-sandbox", "--disable-gpu");
return new ChromeDriver(service, options);
}
private void waitForServerEndpointResponse(int oldMessageCount) {
WebDriverWait wait = new WebDriverWait(webDriver, TIME_OUT_IN_SECONDS);
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.className("message-content"), oldMessageCount));
}
}
| 34.488889 | 148 | 0.710911 |
b49e3951f5c62796d7d3c58f3a8874b954d5d890
| 8,493 |
package io.github.bergturing.point.core.result;
import io.github.bergturing.point.core.result.defaults.MethodResultImpl;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* 方法结果封装的工厂接口
*
* @author bergturing@qq.com
* @see MethodResult
*/
public class MethodResultUtils {
/**
* 结果封装对象
*
* @param status 状态
* @param <S> 状态泛型
* @param <T> 结果类型泛型
* @return 方法结果封装对象
*/
public static <S, T> MethodResult<S, T> result(S status) {
return MethodResultImpl.of(status);
}
/**
* 执行处理结果
*
* @param methodResult 方法结果对象
* @param <S> 状态泛型
* @param <T> 结果类型泛型
*/
public static <S, T> ProcessBuilder<S, T> process(MethodResult<S, T> methodResult) {
return new ProcessBuilder<S, T>(methodResult);
}
/**
* 方法返回结果是否为成功
*
* @param methodResult 方法返回结果
* @param <S> 状态泛型
* @param <T> 结果值泛型
* @return 判断结果
*/
public static <S, T> Boolean isSuccess(MethodResult<S, T> methodResult) {
// 返回判断结果
return isSuccess(methodResult, () -> Boolean.TRUE);
}
/**
* 方法返回结果是否为成功
*
* @param methodResult 方法返回结果
* @param successStatuses 成功的状态
* @param <S> 状态泛型
* @param <T> 结果值泛型
* @return 判断结果
*/
public static <S, T> Boolean isSuccess(MethodResult<S, T> methodResult, S[] successStatuses) {
// 返回判断结果
return isSuccess(methodResult, () -> {
if (Objects.isNull(successStatuses)) {
return Boolean.FALSE;
}
if (Arrays.asList(successStatuses).contains(methodResult.getStatus())) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
});
}
/**
* 方法返回结果是否为成功
*
* @param methodResult 方法返回结果
* @param supplier 最终的判断逻辑
* @param <S> 状态泛型
* @param <T> 结果值泛型
* @return 判断结果
*/
public static <S, T> Boolean isSuccess(MethodResult<S, T> methodResult, BooleanSupplier supplier) {
// 结果为空
if (Objects.isNull(methodResult)) {
return false;
}
// 状态值
S status = methodResult.getStatus();
// 状态值为空
if (Objects.isNull(status)) {
return false;
}
// 判断状态值是否为Boolean类型
if (status instanceof Boolean) {
return (Boolean) status;
} else {
// 否则就是取判断逻辑结果
return supplier.getAsBoolean();
}
}
/**
* 方法返回结果处理的构建对象
*
* @param <S> 状态泛型
* @param <T> 结果值泛型
*/
public static class ProcessBuilder<S, T> {
/**
* 成功标识的集合
*/
private S[] successStatuses;
/**
* 方法返回结果对象
*/
private MethodResult<S, T> methodResult;
/**
* 根据 方法返回结果对象 创建 方法返回结果处理的构建对象
*
* @param methodResult 方法返回结果对象
*/
public ProcessBuilder(MethodResult<S, T> methodResult) {
this.methodResult = methodResult;
}
/**
* 根据 方法返回结果处理的构建对象 构造 方法返回结果处理的构建对象
*
* @param processBuilder 方法返回结果处理的构建对象
*/
ProcessBuilder(ProcessBuilder<S, T> processBuilder) {
this.successStatuses = processBuilder.successStatuses;
this.methodResult = processBuilder.methodResult;
}
/**
* 设置成功的状态值集合
*
* @param successStatuses 成功的状态值集合
* @return 构建对象
*/
public ProcessBuilder<S, T> setSuccessStatus(S[] successStatuses) {
this.successStatuses = successStatuses;
return this;
}
/**
* 方法返回结果处理的构建对象(Consumer)
*
* @param success 成功的消费逻辑对象
* @param failure 失败的消费逻辑对象
* @return 方法返回结果处理的构建对象(Consumer)
*/
public ConsumerProcessBuilder<S, T> consumer(Consumer<MethodResult<S, T>> success,
Consumer<MethodResult<S, T>> failure) {
// 创建并返回 方法返回结果处理的构建对象(Consumer)
return new ConsumerProcessBuilder<>(this, success, failure);
}
/**
* 方法返回结果处理的构建对象(Function)
*
* @param success 成功的函数逻辑对象
* @param failure 失败的函数逻辑对象
* @return 方法返回结果处理的构建对象(Function)
*/
public <R> FunctionProcessBuilder<S, T, R> function(Function<MethodResult<S, T>, R> success,
Function<MethodResult<S, T>, R> failure) {
// 创建并返回 方法返回结果处理的构建对象(Function)
return new FunctionProcessBuilder<S, T, R>(this, success, failure);
}
/**
* 方法返回结果是否为成功
*
* @return 方法返回结果是否成功
*/
Boolean isSuccess() {
if (Objects.isNull(this.successStatuses)) {
return MethodResultUtils.isSuccess(this.getMethodResult());
} else {
return MethodResultUtils.isSuccess(this.getMethodResult(), this.successStatuses);
}
}
/**
* 获取方法执行结果对象
*
* @return 方法执行结果对象
*/
MethodResult<S, T> getMethodResult() {
return this.methodResult;
}
}
/**
* 方法返回结果处理的构建对象
* 处理返回结果的方式为消费(Consumer)
*
* @param <S> 状态泛型
* @param <T> 结果值泛型
*/
public static class ConsumerProcessBuilder<S, T> extends ProcessBuilder<S, T> {
/**
* 成功的消费逻辑
*/
private Consumer<MethodResult<S, T>> success;
/**
* 失败的消费逻辑
*/
private Consumer<MethodResult<S, T>> failure;
/**
* 根据 方法返回结果处理的构建对象 构造 方法返回结果处理的构建对象(Consumer)
*
* @param processBuilder 方法返回结果处理的构建对象
* @param success 成功的消费逻辑对象
* @param failure 失败的消费逻辑对象
*/
ConsumerProcessBuilder(ProcessBuilder<S, T> processBuilder,
Consumer<MethodResult<S, T>> success,
Consumer<MethodResult<S, T>> failure) {
super(processBuilder);
this.success = success;
this.failure = failure;
}
/**
* 执行
*/
public void process() {
// 方法返回结果是否为成功
Boolean success = this.isSuccess();
// 成功
if (success && Objects.nonNull(this.success)) {
this.success.accept(this.getMethodResult());
}
// 失败
if (!success && Objects.nonNull(this.failure)) {
this.failure.accept(this.getMethodResult());
}
}
}
/**
* 方法返回结果处理的构建对象
* 处理返回结果的方式为函数(Function)
*
* @param <S> 状态泛型
* @param <T> 结果值泛型
* @param <R> 执行结果的泛型
*/
public static class FunctionProcessBuilder<S, T, R> extends ProcessBuilder<S, T> {
/**
* 成功的处理函数
*/
private Function<MethodResult<S, T>, R> success;
/**
* 失败的处理函数
*/
private Function<MethodResult<S, T>, R> failure;
/**
* 根据 方法返回结果处理的构建对象 构造 方法返回结果处理的构建对象(Function)
*
* @param processBuilder 方法返回结果处理的构建对象
* @param success 成功的函数逻辑对象
* @param failure 失败的函数逻辑对象
*/
FunctionProcessBuilder(ProcessBuilder<S, T> processBuilder,
Function<MethodResult<S, T>, R> success,
Function<MethodResult<S, T>, R> failure) {
super(processBuilder);
this.success = success;
this.failure = failure;
}
/**
* 执行
*/
public Optional<R> process() {
// 方法返回结果是否为成功
Boolean success = this.isSuccess();
// 成功
if (success && Objects.nonNull(this.success)) {
return Optional.of(this.success.apply(this.getMethodResult()));
}
// 失败
if (!success && Objects.nonNull(this.failure)) {
return Optional.of(failure.apply(this.getMethodResult()));
}
// 返回空结果
return Optional.empty();
}
}
}
| 27.047771 | 103 | 0.511362 |
af28a6fe0424f0b05179152ceb16c172363b9e0e
| 3,830 |
/*
* 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 co.edu.uniandes.kadda.galeriaarte.resources;
import co.edu.uniandes.kadda.galeriaarte.dtos.ObraDetailDTO;
import co.edu.uniandes.kadda.galeriaarte.ejb.ObraLogic;
import co.edu.uniandes.kadda.galeriaarte.entities.ObraEntity;
import co.edu.uniandes.kadda.galeriaarte.exceptions.BusinessLogicException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
/**
*
* @author jd.carrillor
*/
@Path("obras")
@Produces("application/json")
@Consumes("application/json")
@Stateless
public class ObraResource {
@Inject
ObraLogic obraLogic; // Variable para acceder a la lógica de la aplicación. Es una inyección de dependencias.
@POST
public ObraDetailDTO createObra(ObraDetailDTO obra) throws BusinessLogicException {
// Convierte el DTO (json) en un objeto Entity para ser manejado por la lógica.
ObraEntity obraEntity = obra.toEntity();
// Invoca la lógica para crear la Estudiante nueva
ObraEntity nuevaObra = obraLogic.createObra(obraEntity);
// Como debe retornar un DTO (json) se invoca el constructor del DTO con argumento el entity nuevo
return new ObraDetailDTO(nuevaObra);
}
@GET
public List<ObraDetailDTO> getObras() throws BusinessLogicException {
return listEntity2DetailDTO(obraLogic.getObras());
}
@GET
@Path("{id: \\d+}")
public ObraDetailDTO getObra(@PathParam("id") Long id) {
if (obraLogic.findObra(id) != null) {
return new ObraDetailDTO(obraLogic.findObra(id));
} else {
throw new WebApplicationException("Error3");
}
}
@PUT
@Path("{id: \\d+}")
public ObraDetailDTO updateObra(@PathParam("id") Long id, ObraDetailDTO obra) throws BusinessLogicException {
ObraEntity entity = obra.toEntity();
entity.setId(id);
ObraEntity oldEntity = obraLogic.findObra(id);
if (oldEntity == null) {
throw new WebApplicationException("El author no existe", 404);
}
return new ObraDetailDTO(obraLogic.update(entity));
}
/**
* DELETE http://localhost:8080/estudiante-web/api/estudiantes/1
*
* @param id corresponde a la Estudiante a borrar.
* @throws BusinessLogicException
*
* En caso de no existir el id de la Estudiante a actualizar se retorna un
* 404 con el mensaje.
*
*/
@DELETE
@Path("{id: \\d+}")
public void deleteObra(@PathParam("id") Long id) throws BusinessLogicException {
if (obraLogic.findObra(id) != null) {
obraLogic.delete(id);
} else {
throw new WebApplicationException("Este servicio no está implementado");
}
}
/**
*
* lista de entidades a DTO.
*
* Este método convierte una lista de objetos EstudianteEntity a una lista
* de objetos EstudianteDetailDTO (json)
*
* @param entityList corresponde a la lista de Estudiantees de tipo Entity
* que vamos a convertir a DTO.
* @return la lista de Estudiantees en forma DTO (json)
*/
private List<ObraDetailDTO> listEntity2DetailDTO(List<ObraEntity> entityList) {
List<ObraDetailDTO> list = new ArrayList<>();
for (ObraEntity entity : entityList) {
list.add(new ObraDetailDTO(entity));
}
return list;
}
}
| 30.887097 | 113 | 0.675457 |
139f9f84a06f6e753997a4d53d57c1138c45890a
| 12,678 |
package com.arrow.kronos.api;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.arrow.kronos.KronosConstants;
import com.arrow.kronos.data.Device;
import com.arrow.kronos.data.Gateway;
import com.arrow.kronos.data.TestProcedure;
import com.arrow.kronos.data.TestProcedureStep;
import com.arrow.kronos.data.TestResult;
import com.arrow.kronos.data.TestResultStep;
import com.arrow.kronos.repo.TestResultSearchParams;
import com.arrow.kronos.service.TestResultService;
import com.arrow.pegasus.data.AccessKey;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import moonstone.acn.client.model.TestProcedureStepModel;
import moonstone.acn.client.model.TestResultModel;
import moonstone.acn.client.model.TestResultStepModel;
import moonstone.acs.AcsLogicalException;
import moonstone.acs.client.model.PagingResultModel;
@RestController
@RequestMapping("/api/v1/kronos/testresults")
public class TestResultApi extends BaseApiAbstract {
@Autowired
private TestResultService testResultService;
@ApiOperation(value = "list existing TestResults")
@RequestMapping(path = "", method = RequestMethod.GET)
public PagingResultModel<TestResultModel> listTestResults(
@RequestParam(name = "testProcedureHid", required = false) String testProcedureHid,
@RequestParam(name = "objectHid", required = false) String objectHid,
@RequestParam(name = "status", required = false) String status,
@RequestParam(name = "_page", required = false, defaultValue = "0") int page,
@RequestParam(name = "_size", required = false, defaultValue = "100") int size) {
// validation
Assert.isTrue(page >= 0, "page must be positive");
Assert.isTrue(size >= 0 && size <= KronosConstants.PageResult.MAX_SIZE,
"size must be between 0 and " + KronosConstants.PageResult.MAX_SIZE);
PagingResultModel<TestResultModel> result = new PagingResultModel<>();
result.setPage(page);
PageRequest pageRequest = PageRequest.of(page, size);
TestResultSearchParams params = new TestResultSearchParams();
AccessKey accessKey = validateCanReadApplication(getProductSystemName());
params.addApplicationIds(accessKey.getApplicationId());
if (StringUtils.isNotEmpty(objectHid)) {
params.setObjectId(populateObjectIdByHid(objectHid));
}
if (StringUtils.isNotEmpty(status)) {
params.addStatuses(status);
}
if (StringUtils.isNotEmpty(testProcedureHid)) {
params.addTestProcedureIds(populateTestProcedureIdByHid(testProcedureHid));
}
List<TestResultModel> data = new ArrayList<>();
Page<TestResult> testResults = testResultService.getTestResultRepository().findTestResult(pageRequest, params);
if (testResults != null) {
testResults.forEach(testResult -> data.add(buildTestResultModel(testResult)));
}
result.setData(data);
result.setSize(pageRequest.getPageSize());
result.setTotalPages(testResults.getTotalPages());
result.setTotalSize(testResults.getTotalElements());
return result;
}
// @ApiOperation(value = "create new test result")
// @RequestMapping(path = "", method = RequestMethod.POST)
// public HidModel create(
// @ApiParam(value = "test result model", required = true)
// @RequestBody(required = false) TestResultRegistrationModel body) {
// TestResultModel model = JsonUtils.fromJson(getApiPayload(),
// TestResultModel.class);
// Assert.notNull(model, "model is null");
//
// AccessKey accessKey = validateCanWriteGateway(model.getObjectHid());
//
// TestProcedure testProcedure =
// getKronosCache().findTestProcedureByHid(model.getTestProcedureHid());
// Assert.notNull(testProcedure, "testProcedure is null");
// // TestResult findByTestProcedureId =
// testResultService.getTestResultRepository().findByTestProcedureId(testProcedure.getId());
// if (findByTestProcedureId != null) {
// throw new AcsLogicalException("duplicated test procedure id");
// }
//
// String objectId = populateObjectIdByHid(model.getObjectHid());
// Assert.hasText(objectId, "objectId is empty! hid=" +
// model.getObjectHid());
// TestResult findByObjectId =
// testResultService.getTestResultRepository().findByObjectId(objectId);
// if (findByObjectId != null) {
// throw new AcsLogicalException("duplicated object id");
// }
//
// TestResult testResult = new TestResult();
// testResult = buildTestResult(testResult, model,
// getTestProcedureStepsIds(testProcedure));
// testResult.setApplicationId(accessKey.getApplicationId());
// testResult = testResultService.create(testResult, accessKey.getId());
// return new HidModel().withHid(testResult.getHid()).withMessage("OK");
// }
// @ApiOperation(value = "update existing test result")
// @RequestMapping(path = "/{hid}", method = RequestMethod.PUT)
// public HidModel update(
// @ApiParam(value = "test result hid", required = true) @PathVariable(value
// = "hid") String hid,
// @ApiParam(value = "test result model", required = true)
// @RequestBody(required = false) TestResultRegistrationModel body) {
//
// TestResult testResult =
// testResultService.getTestResultRepository().doFindByHid(hid);
// Assert.notNull(testResult, "test result does not exist");
//
// TestResultModel model = JsonUtils.fromJson(getApiPayload(),
// TestResultModel.class);
// Assert.notNull(model, "model is null");
// AccessKey accessKey = validateCanWriteGateway(model.getObjectHid());
// Assert.isTrue(testResult.getApplicationId().equals(accessKey.getApplicationId()),
// "applicationId mismatched!");
//
// TestProcedure testProcedure =
// getKronosCache().findTestProcedureByHid(model.getTestProcedureHid());
// Assert.notNull(testProcedure, "testProcedure is null");
// if (!testProcedure.getId().equals(testResult.getTestProcedureId())) {
// TestResult findByTestProcedureId =
// testResultService.getTestResultRepository()
// .findByTestProcedureId(testProcedure.getId());
// if (findByTestProcedureId != null) {
// throw new AcsLogicalException("duplicated test procedure id");
// }
// }
//
// String objectId = populateObjectIdByHid(model.getObjectHid());
// Assert.notNull(objectId, "object was not found");
// if (!objectId.equals(testResult.getObjectId())) {
// TestResult findByObjectId =
// testResultService.getTestResultRepository().findByObjectId(objectId);
// if (findByObjectId != null) {
// throw new AcsLogicalException("duplicated object id");
// }
// }
//
// testResult = buildTestResult(testResult, model,
// getTestProcedureStepsIds(testProcedure));
// testResult = testResultService.update(testResult, accessKey.getId());
// return new HidModel().withHid(testResult.getHid()).withMessage("OK");
// }
List<String> getTestProcedureStepsIds(TestProcedure testProcedure) {
return testProcedure.getSteps().stream().map(tp -> tp.getId()).collect(Collectors.toList());
}
@ApiOperation(value = "get test result by hid")
@RequestMapping(path = "/{hid}", method = RequestMethod.GET)
public TestResultModel getTestResult(
@ApiParam(value = "test result hid", required = true) @PathVariable(value = "hid") String hid) {
Assert.notNull(hid, "testResultHid is null");
TestResult testResult = testResultService.getTestResultRepository().doFindByHid(hid);
Assert.notNull(testResult, "test result was not found");
validateCanRead(testResult.getObjectId());
return buildTestResultModel(testResult);
}
/*
* private String populateObjectHidById(TestResult testResult) { String
* objectHid = new String(); //switch (testResult.getCategory()) { //case
* DEVICE: // Device device =
* getKronosCache().findDeviceById(testResult.getObjectId()); //
* Assert.notNull(device, "device is null"); // objectHid = device.getHid();
* // break; //case GATEWAY: Gateway gateway =
* getKronosCache().findGatewayById(testResult.getObjectId());
* Assert.notNull(gateway, "gateway is null"); objectHid = gateway.getHid();
* // break; //} return objectHid; }
*/
private AccessKey validateCanRead(String objectId) {
Assert.notNull(objectId, "objectId is null");
AccessKey accessKey = null;
Gateway gateway = getKronosCache().findGatewayById(objectId);
if (gateway != null) {
accessKey = validateCanReadGateway(gateway.getHid());
} else {
Device device = getKronosCache().findDeviceById(objectId);
if (device != null) {
accessKey = validateCanReadDevice(device.getHid());
}
}
Assert.notNull(accessKey, "object was not validated");
return accessKey;
}
TestResult buildTestResult(TestResult testResult, TestResultModel model, List<String> testProcedureStepsIds) {
if (testResult == null) {
testResult = new TestResult();
}
// testResult.setCategory(model.getCategory());
testResult.setStatus(TestResult.Status.valueOf(model.getStatus()));
testResult.setTestProcedureId(populateTestProcedureIdByHid(model.getTestProcedureHid()));
testResult.setObjectId(populateObjectIdByHid(model.getObjectHid()));
testResult.setStarted(Instant.parse(model.getStarted()));
testResult.setEnded(Instant.parse(model.getEnded()));
if (model.getSteps() != null) {
// check duplicates of testProcedureStepIds
List<String> testProcedureStepIdList = model.getSteps().stream().map(s -> s.getDefinition().getId())
.collect(Collectors.toList());
Set<String> testProcedureStepIdSet = new HashSet<>(testProcedureStepIdList);
if (testProcedureStepIdList.size() != testProcedureStepIdSet.size()) {
throw new AcsLogicalException("duplicated test procedure step id");
}
List<TestResultStep> steps = new ArrayList<>();
for (TestResultStepModel stepModel : model.getSteps()) {
if (!testProcedureStepsIds.contains(stepModel.getDefinition().getId())) {
throw new AcsLogicalException("test procedure step was not found");
}
steps.add(buildTestResultStep(stepModel));
}
testResult.setSteps(steps);
}
return testResult;
}
/*
* private String populateObjectIdByHid(TestResultModel model) { String
* objectId = new String(); switch (model.getCategory()) { case DEVICE:
* Device device = getKronosCache().findDeviceByHid(model.getObjectHid());
* Assert.notNull(device, "device is null"); objectId = device.getId();
* break; case GATEWAY: Gateway gateway =
* getKronosCache().findGatewayByHid(model.getObjectHid());
* Assert.notNull(gateway, "gateway is null"); objectId = gateway.getId();
* break; } return objectId; }
*/
private String populateObjectIdByHid(String hid) {
Assert.notNull(hid, "objectHid is null");
String objectId = null;
Gateway gateway = getKronosCache().findGatewayByHid(hid);
if (gateway != null) {
objectId = gateway.getId();
} else {
Device device = getKronosCache().findDeviceByHid(hid);
if (device != null) {
objectId = device.getId();
}
}
Assert.notNull(objectId, "object was not found");
return objectId;
}
private String populateTestProcedureIdByHid(String testProcedureHid) {
Assert.notNull(testProcedureHid, "testProcedureHid is null");
TestProcedure testProcedure = getKronosCache().findTestProcedureByHid(testProcedureHid);
Assert.notNull(testProcedure, "testProcedure is null");
return testProcedure.getId();
}
private TestResultStep buildTestResultStep(TestResultStepModel stepModel) {
Assert.notNull(stepModel, "testResultStepModel is null");
TestResultStep step = new TestResultStep();
step.setComment(stepModel.getComment());
step.setError(stepModel.getError());
step.setDefinition(buildTestProcedureStep(stepModel.getDefinition()));
step.setStatus(TestResultStep.Status.valueOf(stepModel.getStatus()));
step.setStarted(Instant.parse(stepModel.getStarted()));
step.setEnded(Instant.parse(stepModel.getEnded()));
return step;
}
private TestProcedureStep buildTestProcedureStep(TestProcedureStepModel model) {
TestProcedureStep step = new TestProcedureStep();
step.setId(model.getId());
step.setDescription(model.getDescription());
step.setName(model.getName());
step.setSortOrder(model.getSortOrder());
return step;
}
}
| 40.634615 | 113 | 0.749724 |
5b7578909c15c16350762dfe274c64d7208f7e41
| 3,505 |
package me.ahornyai.httpclient;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@Getter
@Setter
public abstract class HttpRequest {
protected String url;
protected String body;
protected HashMap<String, String> headers;
protected HashMap<String, String> urlParams;
protected HashMap<String, String> bodyParams;
public HttpRequest(String url, HashMap<String, String> urlParams, HashMap<String, String> bodyParams, HashMap<String, String> headers) {
this.url = url;
this.urlParams = urlParams;
this.bodyParams = bodyParams;
this.headers = headers;
}
public HttpRequest(String url, HashMap<String, String> urlParams, HashMap<String, String> bodyParams) {
this.url = url;
this.urlParams = urlParams;
this.bodyParams = bodyParams;
}
public HttpRequest(String url, HashMap<String, String> params, boolean isUrlParams) {
this.url = url;
if (isUrlParams)
this.urlParams = params;
else
this.bodyParams = params;
}
public HttpRequest(String url) {
this.url = url;
}
public abstract void run(HttpClient client, BiConsumer<String, Integer> consumer, Consumer<Exception> exCallback, boolean async);
protected String paramBuilder(HashMap<String, String> params) {
if (params == null) return "";
boolean isFirst = true;
StringBuilder paramBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (isFirst) paramBuilder.append(encode(entry.getKey())).append("=").append(encode(entry.getValue()));
else paramBuilder.append("&").append(encode(entry.getKey())).append("=").append(encode(entry.getValue()));
isFirst = false;
}
return paramBuilder.toString();
}
protected String urlParamBuilder(HashMap<String, String> params) {
if (params == null) return "";
boolean isFirst = true;
StringBuilder paramBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (isFirst) paramBuilder.append("?").append(encode(entry.getKey())).append("=").append(encode(entry.getValue()));
else paramBuilder.append("&").append(encode(entry.getKey())).append("=").append(encode(entry.getValue()));
isFirst = false;
}
return paramBuilder.toString();
}
protected String readOutput(InputStream stream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
return sb.toString();
}
protected void applyHeaders(URLConnection connection) {
if (headers == null) return;
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
@SneakyThrows
private String encode(String str) {
return URLEncoder.encode(str, "UTF-8");
}
}
| 32.757009 | 140 | 0.659344 |
a1b97cc1a765319b9ba484de0e014b81ba1d225c
| 3,281 |
package jason.algorithm.practice;
import java.util.BitSet;
import java.util.PriorityQueue;
//http://www.programcreek.com/2014/05/leetcode-minimum-path-sum-java/
public class MinimumPathSum {
public static class QueueEntry {
int sum;
int row;
int col;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public QueueEntry(int sum, int row, int col) {
super();
this.sum = sum;
this.row = row;
this.col = col;
}
}
public static int minimumPathSum(int[][] input){
int column=input[0].length;
int row=input.length;
//int[][] neighbors={{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1,1}, {1, 0}, {1, -1}, {0, -1}};
//diagnoal walk is not allowed
int[][] neighbors={ {-1, 0}, {0, 1}, {1, 0}, {0, -1}};
QueueEntry[][] entries=new QueueEntry[row][column];
BitSet found=new BitSet(row*column);
PriorityQueue<QueueEntry> queue=new PriorityQueue<QueueEntry>(row*column, (a, b)->{
return a.sum-b.sum;
});
QueueEntry first=new QueueEntry(input[0][0], 0, 0);
entries[0][0]=first;
queue.add(first);
while (queue.peek()!=null){
QueueEntry entry=queue.poll();
int rowIndex=entry.row;
int colIndex=entry.col;
found.set(rowIndex*column+colIndex);
if (entry.col==(column-1) && entry.row==(row-1)){
//the last found.
break;
}
//walk to 8 edge
for (int[] delta: neighbors){
int neighborRow=rowIndex+delta[0];
int neighborCol=colIndex+delta[1];
if (neighborCol<0 || neighborRow<0 || neighborCol>=column || neighborRow>=row){
continue;
}
if (found.get(neighborRow*column+neighborCol)){
//already found min Path
continue;
}
QueueEntry neighborQueueEntry=entries[neighborRow][neighborCol];
if (neighborQueueEntry==null){ //never reached to neighbor before
neighborQueueEntry=new QueueEntry(entry.sum+input[neighborRow][neighborCol], neighborRow, neighborCol);
entries[neighborRow][neighborCol]=neighborQueueEntry;
queue.offer(neighborQueueEntry);
continue;
} else{
if (entry.sum+input[neighborRow][neighborCol]<neighborQueueEntry.sum){
queue.remove(neighborQueueEntry);
neighborQueueEntry.sum=entry.sum+input[neighborRow][neighborCol];
queue.offer(neighborQueueEntry);
}
}
}
}
return entries[row-1][column-1].sum;
}
//solution from web: http://www.programcreek.com/2014/05/leetcode-minimum-path-sum-java/
public static int minPathSum(int[][] grid) {
if(grid == null || grid.length==0)
return 0;
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
// initialize top row
for(int i=1; i<n; i++){
dp[0][i] = dp[0][i-1] + grid[0][i];
}
// initialize left column
for(int j=1; j<m; j++){
dp[j][0] = dp[j-1][0] + grid[j][0];
}
// fill up the dp table
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
if(dp[i-1][j] > dp[i][j-1]){
dp[i][j] = dp[i][j-1] + grid[i][j];
}else{
dp[i][j] = dp[i-1][j] + grid[i][j];
}
}
}
return dp[m-1][n-1];
}
}
| 23.604317 | 108 | 0.580006 |
a690c378a92ab37a665f8c535a4a54af5bff1345
| 1,666 |
package com.dbui.wc.util;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
public class CountUtil {
private CountUtil() {
}
public static boolean isOnAlphabet(char c) {
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
}
public static List<Path> getFilePaths(String dir) {
try (Stream<Path> paths = Files.walk(Paths.get(dir))) {
return paths.filter(Files::isRegularFile).toList();
} catch (IOException e) {
e.printStackTrace();
}
return List.of();
}
public static void countCharacter(final Path path, final Map<Character, Long> charToCount) {
try {
var lines = Files.readAllLines(path, StandardCharsets.UTF_8);
countCharacter(lines, charToCount);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void countCharacter(final Collection<String> lines, Map<Character, Long> charToCount) {
lines.forEach(string -> {
final var chars = string.toCharArray();
for (final char c : chars) {
if (CountUtil.isOnAlphabet(c)) {
charToCount.compute(c, (val, currentCount) -> {
if (currentCount == null) {
return 1L;
}
return ++currentCount;
});
}
}
});
}
}
| 29.22807 | 105 | 0.556423 |
a7f11cc73a3187372449dc0ce6eae3c0c725e2ab
| 6,601 |
package org.firstinspires.ftc.teamcode.subsystems;
import android.text.method.Touch;
import com.acmerobotics.dashboard.config.Config;
import com.ftc12835.library.hardware.management.Subsystem;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.DigitalChannel;
import com.qualcomm.robotcore.hardware.DistanceSensor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.TouchSensor;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
@Config
public class Intake implements Subsystem {
private DcMotor extenderMotor;
private DcMotor intakeMotor;
public Servo pivotServoLeft;
public Servo pivotServoRight;
private DigitalChannel intakeLimit;
DistanceSensor distance1;
DistanceSensor distance2;
private double extenderPower;
private double intakePower;
private double leftPosition;
private double rightPosition;
private OpMode opMode;
private PivotPosition currentPivotPosition = PivotPosition.UP;
public static double LEFT_DOWN = 0.95;
public static double LEFT_UP= 0.25;
public static double RIGHT_DOWN = 0.05;
public static double RIGHT_UP = 0.75;
public static double LEFT_MIDDLE = 0.7;
public static double RIGHT_MIDDLE = 0.3;
public static double LEFT_HIGH = 0.6;
public static double RIGHT_HIGH = 0.4;
public enum PivotPosition {
UP,
HIGH,
MIDDLE,
DOWN
}
public enum MineralStatus {
TWO,
ONE,
NONE
}
public Intake(OpMode opMode, boolean auto) {
this.opMode = opMode;
extenderMotor = opMode.hardwareMap.get(DcMotor.class, "EXTENDER");
extenderMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
resetExtenderEncoder();
intakeMotor = opMode.hardwareMap.get(DcMotor.class, "INTAKE");
pivotServoLeft = opMode.hardwareMap.get(Servo.class, "PIVOT_LEFT");
pivotServoRight = opMode.hardwareMap.get(Servo.class, "PIVOT_RIGHT");
intakeLimit = opMode.hardwareMap.get(DigitalChannel.class, "INTAKE_LIMIT");
distance1 = opMode.hardwareMap.get(DistanceSensor.class, "MINERAL_1");
distance2 = opMode.hardwareMap.get(DistanceSensor.class, "MINERAL_2");
intakeMotor.setDirection(DcMotorSimple.Direction.REVERSE);
if (auto) {
setIntakePivotPosition(PivotPosition.UP);
} else {
setIntakePivotPosition(PivotPosition.DOWN);
setIntakePower(-1.0);
}
}
public void resetExtenderEncoder() {
extenderMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
extenderMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
}
public void setExtenderPower(double extenderPower) {
this.extenderPower = extenderPower;
}
public void setIntakePower(double intakePower) {
this.intakePower = intakePower;
}
public void setLeftPosition(double leftPosition) {
this.leftPosition = leftPosition;
}
public void setRightPosition(double rightPosition) {
this.rightPosition = rightPosition;
}
public PivotPosition getCurrentPivotPosition() {
return currentPivotPosition;
}
public void setIntakePivotPosition(PivotPosition pivotPosition) {
currentPivotPosition = pivotPosition;
switch (pivotPosition) {
case UP:
setLeftPosition(LEFT_UP);
setRightPosition(RIGHT_UP);
break;
case HIGH:
setLeftPosition(LEFT_HIGH);
setRightPosition(RIGHT_HIGH);
break;
case MIDDLE:
setLeftPosition(LEFT_MIDDLE);
setRightPosition(RIGHT_MIDDLE);
break;
case DOWN:
setLeftPosition(LEFT_DOWN);
setRightPosition(RIGHT_DOWN);
break;
}
}
public int getExtenderPosition() {
return extenderMotor.getCurrentPosition();
}
public void dumpMarker() {
LinearOpMode linearOpMode = (LinearOpMode) opMode;
setIntakePivotPosition(PivotPosition.DOWN);
linearOpMode.sleep(900);
setIntakePivotPosition(PivotPosition.UP);
}
public void runExtenderToPosition(double power, int counts) {
LinearOpMode linearOpMode = (LinearOpMode) opMode;
setExtenderPower(power);
double realCounts = counts - 300;
while (linearOpMode.opModeIsActive()) {
if (Math.abs(getExtenderPosition()) > realCounts) {
break;
}
}
setExtenderPower(0.0);
}
public void retractExtenderToPosition(double power, int counts) {
LinearOpMode linearOpMode = (LinearOpMode) opMode;
setExtenderPower(power);
while (linearOpMode.opModeIsActive()) {
if (Math.abs(getExtenderPosition()) < counts) {
break;
}
}
setExtenderPower(0.0);
}
public void retractIntakeExtender() {
LinearOpMode linearOpMode = (LinearOpMode) opMode;
setExtenderPower(1.0);
long start = System.currentTimeMillis();
while (linearOpMode.opModeIsActive()) {
if (getIntakeLimit()) {
break;
}
if (System.currentTimeMillis() - start >= 2500) {
break;
}
}
setExtenderPower(0.0);
}
public boolean getIntakeLimit() {
return !intakeLimit.getState();
}
public double getUpperDistance() {
return distance1.getDistance(DistanceUnit.CM);
}
public double getLowerDistance() {
return distance2.getDistance(DistanceUnit.CM);
}
public MineralStatus getMineralStatus() {
if (getLowerDistance() < 5.7 && getUpperDistance() < 5.7) {
return MineralStatus.TWO;
} else if (getLowerDistance() < 5.7 || getUpperDistance() < 5.7) {
return MineralStatus.ONE;
} else {
return MineralStatus.NONE;
}
}
@Override
public void update() {
extenderMotor.setPower(extenderPower);
intakeMotor.setPower(intakePower);
pivotServoLeft.setPosition(leftPosition);
pivotServoRight.setPosition(rightPosition);
}
}
| 29.337778 | 83 | 0.652931 |
d3df7ca7687e73eb67474adb9a8a4ce9c0b75847
| 3,160 |
package com.filip.versu.view.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.filip.versu.R;
import com.filip.versu.view.viewmodel.callback.parent.IAppIntroContainerViewModel;
import com.filip.versu.view.viewmodel.parent.AppIntroContainerViewModel;
import eu.inloop.viewmodel.base.ViewModelBaseFragment;
public class IntroFragment extends ViewModelBaseFragment<IAppIntroContainerViewModel.IAppIntroContainerViewModelCallback, AppIntroContainerViewModel> implements IAppIntroContainerViewModel.IAppIntroContainerViewModelCallback {
public static enum IntroFragmentType {
ASK, VOTE, DISCOVER
}
public static final String TYPE_KEY = "type_key";
public static IntroFragment newInstance(IntroFragmentType type) {
IntroFragment introFragment = new IntroFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(TYPE_KEY, type);
introFragment.setArguments(bundle);
return introFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_intro, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView photoImageView = (ImageView) view.findViewById(R.id.onboardingImage);
TextView titleTextView = (TextView) view.findViewById(R.id.onboardingTitle);
TextView descTextView = (TextView) view.findViewById(R.id.onboardingDesc);
IntroFragmentType type = (IntroFragmentType) getArguments().getSerializable(TYPE_KEY);
if(type == IntroFragmentType.ASK) {
photoImageView.setImageResource(R.mipmap.onboarding_ask);
titleTextView.setText(R.string.ask_title);
titleTextView.setTextColor(ContextCompat.getColor(getActivity(), R.color.tab_home_underline));
descTextView.setText(R.string.ask_text);
} else if (type == IntroFragmentType.VOTE) {
photoImageView.setImageResource(R.mipmap.onboarding_vote);
titleTextView.setText(R.string.vote_title);
titleTextView.setTextColor(ContextCompat.getColor(getActivity(), R.color.tab_camera_underline));
descTextView.setText(R.string.vote_text);
} else if (type == IntroFragmentType.DISCOVER) {
photoImageView.setImageResource(R.mipmap.onboarding_discover);
titleTextView.setText(R.string.discover_title);
titleTextView.setTextColor(ContextCompat.getColor(getActivity(), R.color.tab_profile_underline));
descTextView.setText(R.string.discover_text);
}
}
@Nullable
@Override
public Class<AppIntroContainerViewModel> getViewModelClass() {
return AppIntroContainerViewModel.class;
}
}
| 39.012346 | 226 | 0.743354 |
69a988ca91f90bfb184d2c8ca707f2349525cc74
| 4,143 |
package com.soebes.itf.jupiter.extension;
/*
* 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.
*/
import com.soebes.itf.jupiter.maven.ProjectHelper;
import org.apache.maven.model.Model;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.assertj.core.api.Assertions.assertThat;
class ModelReaderTest {
private ModelReader modelReader;
@Nested
@DisplayName("A pom file which contains artifactId and version")
class PomWithoutGroupId {
@BeforeEach
void beforeEach() {
InputStream resourceAsStream = this.getClass().getResourceAsStream("/pom.xml");
Model model = ProjectHelper.readProject(resourceAsStream);
modelReader = new ModelReader(model);
}
@Test
@DisplayName("should get the correct version.")
void get_version_should_result_in_correct_version() {
assertThat(modelReader.getVersion()).isEqualTo("2.8-SNAPSHOT");
}
@Test
@DisplayName("should get the correct artifactId.")
void get_artifactId_should_result_in_correct_artifactId() {
assertThat(modelReader.getArtifactId()).isEqualTo("versions-maven-plugin");
}
@Test
@DisplayName("should get the groupId from parent.")
void get_groupId_should_return_groupId() {
assertThat(modelReader.getGroupId()).isEqualTo("org.codehaus.mojo");
}
}
@Nested
@DisplayName("A pom file which contains groupId,artifactId and version")
class PomWithGAV {
@BeforeEach
void beforeEach() {
InputStream resourceAsStream = this.getClass().getResourceAsStream("/pom-correct.xml");
Model model = ProjectHelper.readProject(resourceAsStream);
modelReader = new ModelReader(model);
}
@Test
@DisplayName("should get the correct version.")
void get_version_should_result_in_correct_version() {
assertThat(modelReader.getVersion()).isEqualTo("2.8-SNAPSHOT");
}
@Test
@DisplayName("should get the correct artifactId.")
void get_artifactId_should_result_in_correct_artifactId() {
assertThat(modelReader.getArtifactId()).isEqualTo("versions-maven-plugin");
}
@Test
@DisplayName("should get the groupId")
void get_groupId_should_return_groupId() {
assertThat(modelReader.getGroupId()).isEqualTo("org.codehaus.dela");
}
}
@Nested
@DisplayName("A pom file which contains no version but the parent does.")
class PomWithoutVersion {
@BeforeEach
void beforeEach() {
InputStream resourceAsStream = this.getClass().getResourceAsStream("/pom-version.xml");
Model model = ProjectHelper.readProject(resourceAsStream);
modelReader = new ModelReader(model);
}
@Test
@DisplayName("should get the version of the parent.")
void get_version_should_result_in_correct_version() {
assertThat(modelReader.getVersion()).isEqualTo("50");
}
@Test
@DisplayName("should get the correct artifactId.")
void get_artifactId_should_result_in_correct_artifactId() {
assertThat(modelReader.getArtifactId()).isEqualTo("versions-maven-plugin");
}
@Test
@DisplayName("should get the groupId from parent.")
void get_groupId_should_return_groupId() {
assertThat(modelReader.getGroupId()).isEqualTo("org.codehaus.dela");
}
}
}
| 31.869231 | 93 | 0.728216 |
dc99b692f3560ac693ffe12a1793dfc0d47b4a4c
| 3,257 |
package com.zazuko.spatialindexer;
import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.jena.geosparql.configuration.GeoSPARQLConfig;
import org.apache.jena.geosparql.spatial.SpatialIndexException;
import org.apache.jena.geosparql.configuration.SrsException;
import org.apache.jena.query.Dataset;
import org.apache.jena.tdb2.TDB2Factory;
public class SpatialIndexer {
private static final int EXIT_FAILURE = 1;
/**
* Setup Spatial Index using Dataset and most frequent SRS URI in Dataset.
* When no SRS URI can be found, CRS84 will be used instead.
* Spatial Index written to file once created.
*
* @param dataset
* @param spatialIndexFile
* @throws SpatialIndexException
*/
private static final void setupSpatialIndexWithoutSrsUri(Dataset dataset, File spatialIndexFile)
throws SpatialIndexException {
try {
GeoSPARQLConfig.setupSpatialIndex(dataset, spatialIndexFile);
} catch (SrsException _e) {
GeoSPARQLConfig.setupSpatialIndex(dataset, "http://www.opengis.net/def/crs/OGC/1.3/CRS84", spatialIndexFile);
}
}
/**
* Manage supported options.
*
* @return Options
*/
private static final Options configParameters() {
final Option dataset = Option
.builder("d")
.longOpt("dataset")
.desc("Path to a TDB2 dataset")
.hasArg(true)
.required(true)
.argName("dataset")
.build();
final Option spatialIndexFile = Option
.builder("i")
.longOpt("index")
.desc("Path to the spatial index file")
.hasArg(true)
.required(true)
.argName("index")
.build();
final Option srsUri = Option
.builder("s")
.longOpt("srs")
.desc("SRS URI")
.hasArg(true)
.required(false)
.argName("srs")
.build();
final Options options = new Options();
options
.addOption(dataset)
.addOption(spatialIndexFile)
.addOption(srsUri);
return options;
}
public static void main(String[] args) {
final Options options = configParameters();
final CommandLineParser parser = new DefaultParser();
CommandLine line;
try {
line = parser.parse(options, args);
} catch (ParseException e) {
System.err.println(e);
System.exit(EXIT_FAILURE);
return;
}
final String datasetPath = line.getOptionValue("dataset");
final String spatialIndexFilePath = line.getOptionValue("index");
final File spatialIndexFile = new File(spatialIndexFilePath);
final Dataset dataset = TDB2Factory.connectDataset(datasetPath);
try {
if (line.hasOption("srs")) {
final String srsUri = line.getOptionValue("srs");
GeoSPARQLConfig.setupSpatialIndex(dataset, srsUri, spatialIndexFile);
} else {
setupSpatialIndexWithoutSrsUri(dataset, spatialIndexFile);
}
} catch (SpatialIndexException e) {
System.err.println(e);
System.exit(EXIT_FAILURE);
}
}
}
| 29.080357 | 115 | 0.675161 |
53cdff8bb83d6c4f8a37d71959754bddaa680c39
| 3,086 |
/*******************************************************************************
* Copyright 2016 Sparta Systems, 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 com.spartasystems.holdmail.service;
import com.spartasystems.holdmail.domain.Message;
import com.spartasystems.holdmail.mapper.MessageListMapper;
import com.spartasystems.holdmail.mapper.MessageMapper;
import com.spartasystems.holdmail.model.MessageList;
import com.spartasystems.holdmail.persistence.MessageEntity;
import com.spartasystems.holdmail.persistence.MessageRepository;
import com.spartasystems.holdmail.smtp.OutgoingMailSender;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import javax.validation.constraints.Null;
import java.util.List;
@Component
public class MessageService {
@Autowired
private MessageRepository messageRepository;
@Autowired
private MessageMapper messageMapper;
@Autowired
private OutgoingMailSender outgoingMailSender;
@Autowired
private MessageListMapper messageListMapper;
public Message saveMessage(Message message) {
MessageEntity entity = messageMapper.fromDomain(message);
entity = messageRepository.save(entity);
return messageMapper.toDomain(entity);
}
public void deleteMessage(Long id) {
messageRepository.delete(id);
}
public Message getMessage(long messageId) {
MessageEntity entity = messageRepository.findOne(messageId);
return messageMapper.toDomain(entity);
}
public MessageList findMessages(@Null @Email String recipientEmail, Pageable pageRequest) {
List<MessageEntity> entities;
if (StringUtils.isBlank(recipientEmail)) {
entities = messageRepository.findAllByOrderByReceivedDateDesc(pageRequest);
}
else {
entities = messageRepository.findAllForRecipientOrderByReceivedDateDesc(recipientEmail, pageRequest);
}
return messageListMapper.toMessageList(entities);
}
public void forwardMessage(long messageId, @NotBlank @Email String recipientEmail) {
Message message = getMessage(messageId);
outgoingMailSender.redirectMessage(recipientEmail, message.getRawMessage());
}
}
| 32.829787 | 113 | 0.722294 |
c156c17fb6c61d9655a7e95d8843eb1729058437
| 733 |
package com.bnd.math.business.rand;
abstract class PositiveNormalDistributionProvider<T> extends AbstractRandomDistributionProvider<T> {
protected final RandomDistributionProvider<T> normalDistributionProvider;
protected PositiveNormalDistributionProvider(Class<T> clazz, RandomDistributionProvider<T> normalDistributionProvider) {
super(clazz);
this.normalDistributionProvider = normalDistributionProvider;
}
@Override
public Double mean() {
// TODO: Not entirely true
return normalDistributionProvider.mean();
}
@Override
public Double variance() {
// TODO: Not entirely true
return normalDistributionProvider.variance();
}
@Override
public T next() {
// TODO
return null;
}
}
| 25.275862 | 121 | 0.761255 |
620207d2d362ab7b00c7a101356dd51be2bbe2c1
| 612 |
package com.capitalone.dashboard.azure.repos.model;
public class Repository {
private String id;
private String name;
private String url;
private Project project;
public String getID() { return id; }
public void setID(String value) { this.id = value; }
public String getName() { return name; }
public void setName(String value) { this.name = value; }
public String getURL() { return url; }
public void setURL(String value) { this.url = value; }
public Project getProject() { return project; }
public void setProject(Project value) { this.project = value; }
}
| 29.142857 | 67 | 0.679739 |
d9cfdfdadb83f8d8f2f166a2f74d3dce17ab320e
| 1,893 |
package com.mobilebox.repl.selectors;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import com.mobilebox.repl.selectors.UISelector;
import static org.assertj.core.api.Assertions.*;
public class UISelectorTest {
@Test
public void classNameTest() {
String expected = "className(\"my.classname\")";
By locator = UISelector.className("my.classname");
assertThatByIsEqualTo(locator.toString(), expected);
}
@Test
public void descriptionTest() {
String expected = "description(\"desc\")";
By locator = UISelector.description("desc");
assertThatByIsEqualTo(locator.toString(), expected);
}
@Test
public void descriptionContainsTest() {
String expected = "descriptionContains(\"desc\")";
By locator = UISelector.descriptionContains("desc");
assertThatByIsEqualTo(locator.toString(), expected);
}
@Test
public void resourceIdTest() {
String expected = "resourceId(\"id\")";
By locator = UISelector.resourceId("id");
assertThatByIsEqualTo(locator.toString(), expected);
}
@Test
public void selectorChainingTest() {
String expected = "resourceId(\"id\").enabled(true).instance(0)";
By locator = UISelector.selectorChaining(expected);
assertThatByIsEqualTo(locator.toString(), expected);
}
@Test
public void textTest() {
String expected = "text(\"text\")";
By locator = UISelector.text("text");
assertThatByIsEqualTo(locator.toString(), expected);
}
@Test
public void textContainsTest() {
String expected = "textContains(\"text\")";
By locator = UISelector.textContains("text");
assertThatByIsEqualTo(locator.toString(), expected);
}
private void assertThatByIsEqualTo(final String actual, final String expected) {
String msg = "By.AndroidUIAutomator: new UiSelector().";
assertThat(actual).isEqualToIgnoringCase(msg + expected);
}
}
| 28.681818 | 82 | 0.707871 |
408e8ca7be01d34e62c8d9af5c7d9fa2444f90a2
| 1,512 |
package com.common.redis;
import com.common.utility.ComLogger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* @auther tonyjarjar
* @create 2017/9/8
*/
public class RedisFactory {
//redis db0
public static JedisPool redis0Pool = RedisUtil.initRedisPool("/redis0pool.properties");
//redis db1
public static JedisPool redis1Pool = RedisUtil.initRedisPool("/redis1pool.properties");
//redis db2
public static JedisPool redis2Pool = RedisUtil.initRedisPool("/redis2pool.properties");
//获取redis实例
public synchronized static Jedis getJedis(JedisPool jedisPool) {
try {
if (jedisPool != null) {
Jedis jedis = jedisPool.getResource();
return jedis;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void returnResource(final Jedis jedis) {
//方法参数被声明为final,表示它是只读的。
if (jedis != null) {
//jedisPool.returnResource(jedis);
//jedis.close()取代jedisPool.returnResource(jedis)方法将3.0版本开始
jedis.close();
}
}
public static void main(String[] args) {
try {
redis0Pool.getResource();
redis1Pool.getResource();
ComLogger.info("成功");
} catch (Exception e) {
e.printStackTrace();
ComLogger.error("失败");
}
}
}
| 24.786885 | 92 | 0.584656 |
8b88c86b09a8e1edc301ef343ded607402e6feb4
| 7,654 |
package io.syndesis.qe.rest.tests.integrations.steps;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;
import java.util.UUID;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import io.syndesis.common.model.action.Action;
import io.syndesis.common.model.action.ConnectorDescriptor;
import io.syndesis.common.model.connection.Connection;
import io.syndesis.common.model.connection.Connector;
import io.syndesis.common.model.integration.Step;
import io.syndesis.common.model.integration.StepKind;
import io.syndesis.qe.bdd.AbstractStep;
import io.syndesis.qe.bdd.entities.StepDefinition;
import io.syndesis.qe.bdd.storage.StepsStorage;
import io.syndesis.qe.endpoints.ConnectionsEndpoint;
import io.syndesis.qe.endpoints.ConnectorsEndpoint;
import io.syndesis.qe.rest.tests.util.RestTestsUtils;
import io.syndesis.qe.utils.TestUtils;
import lombok.extern.slf4j.Slf4j;
/**
* DB steps for integrations.
* <p>
* Oct 7, 2017 Red Hat
*
* @author tplevko@redhat.com
*/
@Slf4j
public class DatabaseSteps extends AbstractStep {
@Autowired
private StepsStorage steps;
@Autowired
private ConnectionsEndpoint connectionsEndpoint;
@Autowired
private ConnectorsEndpoint connectorsEndpoint;
@Then("^create start DB periodic sql invocation action step with query \"([^\"]*)\" and period \"([^\"]*)\" ms")
public void createStartDbPeriodicSqlStep(String sqlQuery, Integer ms) {
final Connector dbConnector = connectorsEndpoint.get(RestTestsUtils.Connection.DB.getId());
final Connection dbConnection = connectionsEndpoint.get(RestTestsUtils.Connector.DB.getId());
final Action dbAction = TestUtils.findConnectorAction(dbConnector, "sql-start-connector");
final Map<String, String> properties = TestUtils.map("query", sqlQuery, "schedulerExpression", ms);
final ConnectorDescriptor connectorDescriptor = getConnectorDescriptor(dbAction, properties, dbConnection.getId().get());
//to be reported: period is not part of .json step (when checked via browser).
final Step dbStep = new Step.Builder()
.stepKind(StepKind.endpoint)
.id(UUID.randomUUID().toString())
.connection(dbConnection)
.action(generateStepAction(dbAction, connectorDescriptor))
.configuredProperties(properties)
.build();
steps.getStepDefinitions().add(new StepDefinition(dbStep, connectorDescriptor));
}
@Then("^create start DB periodic stored procedure invocation action step named \"([^\"]*)\" and period \"([^\"]*)\" ms")
public void createStartDbPeriodicProcedureStep(String procedureName, Integer ms) {
final Connector dbConnector = connectorsEndpoint.get(RestTestsUtils.Connection.DB.getId());
final Connection dbConnection = connectionsEndpoint.get(RestTestsUtils.Connector.DB.getId());
final Action dbAction = TestUtils.findConnectorAction(dbConnector, "sql-stored-start-connector");
final Map<String, String> properties = TestUtils.map("procedureName", procedureName, "schedulerExpression", ms,
"template", "add_lead(VARCHAR ${body[first_and_last_name]}, VARCHAR ${body[company]}, VARCHAR ${body[phone]}, VARCHAR ${body[email]}, "
+ "VARCHAR ${body[lead_source]}, VARCHAR ${body[lead_status]}, VARCHAR ${body[rating]})");
final ConnectorDescriptor connectorDescriptor = getConnectorDescriptor(dbAction, properties, dbConnection.getId().get());
final Step dbStep = new Step.Builder()
.stepKind(StepKind.endpoint)
.id(UUID.randomUUID().toString())
.connection(dbConnection)
.action(generateStepAction(dbAction, connectorDescriptor))
.configuredProperties(properties)
.build();
steps.getStepDefinitions().add(new StepDefinition(dbStep, connectorDescriptor));
}
@Then("^create finish DB invoke sql action step with query \"([^\"]*)\"")
public void createFinishDbInvokeSqlStep(String sqlQuery) {
final Connector dbConnector = connectorsEndpoint.get(RestTestsUtils.Connection.DB.getId());
final Connection dbConnection = connectionsEndpoint.get(RestTestsUtils.Connector.DB.getId());
final Action dbAction = TestUtils.findConnectorAction(dbConnector, "sql-connector");
final Map<String, String> properties = TestUtils.map("query", sqlQuery);
final ConnectorDescriptor connectorDescriptor = getConnectorDescriptor(dbAction, properties, dbConnection.getId().get());
final Step dbStep = new Step.Builder()
.stepKind(StepKind.endpoint)
.id(UUID.randomUUID().toString())
.connection(dbConnection)
.action(generateStepAction(dbAction, connectorDescriptor))
.configuredProperties(properties)
.build();
steps.getStepDefinitions().add(new StepDefinition(dbStep, connectorDescriptor));
}
@Given("^create DB step with query: \"([^\"]*)\" and interval: (\\d+) miliseconds")
public void createDbStepWithInterval(String query, int interval) {
final Connector dbConnector = connectorsEndpoint.get(RestTestsUtils.Connection.DB.getId());
final Connection dbConnection = connectionsEndpoint.get(RestTestsUtils.Connector.DB.getId());
final Map<String, String> properties = TestUtils.map("query", query, "schedulerExpression", interval);
final Action dbAction = TestUtils.findConnectorAction(dbConnector, "sql-connector");
final ConnectorDescriptor connectorDescriptor = getConnectorDescriptor(dbAction, properties, dbConnection.getId().get());
final Step dbStep = new Step.Builder()
.stepKind(StepKind.endpoint)
.connection(dbConnection)
.id(UUID.randomUUID().toString())
.action(generateStepAction(dbAction, connectorDescriptor))
.configuredProperties(properties)
.build();
steps.getStepDefinitions().add(new StepDefinition(dbStep, connectorDescriptor));
}
@And("^create finish DB invoke stored procedure \"([^\"]*)\" action step")
public void createFinishDbInvokeProcedureStep(String procedureName) {
final Connector dbConnector = connectorsEndpoint.get(RestTestsUtils.Connection.DB.getId());
final Connection dbConnection = connectionsEndpoint.get(RestTestsUtils.Connector.DB.getId());
final Action dbAction = TestUtils.findConnectorAction(dbConnector, "sql-stored-connector");
final Map<String, String> properties = TestUtils.map("procedureName", procedureName);
final ConnectorDescriptor connectorDescriptor = getConnectorDescriptor(dbAction, properties, dbConnection.getId().get());
properties.put("template", "add_lead(VARCHAR ${body[first_and_last_name]}, VARCHAR ${body[company]}, VARCHAR ${body[phone]}, VARCHAR ${body[email]}, "
+ "VARCHAR ${body[lead_source]}, VARCHAR ${body[lead_status]}, VARCHAR ${body[rating]})");
final Step dbStep = new Step.Builder()
.stepKind(StepKind.endpoint)
.id(UUID.randomUUID().toString())
.connection(dbConnection)
.action(generateStepAction(TestUtils.findConnectorAction(dbConnector, "sql-stored-connector"), connectorDescriptor))
.configuredProperties(properties)
.build();
steps.getStepDefinitions().add(new StepDefinition(dbStep, connectorDescriptor));
}
}
| 55.463768 | 158 | 0.701333 |
1ebe40e75b595c1934768b7eef3cd79b6e77015a
| 1,005 |
package com.plivo.api.models.powerpack;
import com.plivo.api.models.base.Deleter;
import okhttp3.ResponseBody;
public class RemoveTollfree extends Deleter<Tollfree> {
private Boolean unrent;
private String number;
private String tollfree;
public RemoveTollfree(String id) {
super(id);
if (id == null) {
throw new IllegalArgumentException("powerpack uuid cannot be null");
}
this.id = id;
this.unrent = Boolean.FALSE;
}
public Boolean unrent() {
return this.unrent;
}
/**
* @param unrent Specify if the powerpack numbers should be unrent_numbers or not.
*/
public RemoveTollfree unrent(final Boolean unrent) {
this.unrent = unrent;
return this;
}
public RemoveTollfree tollfree(final String tollfree) {
this.tollfree = tollfree;
return this;
}
@Override
protected retrofit2.Call<ResponseBody> obtainCall() {
return client().getApiService().powerpackTollfreeDelete(client().getAuthId(), id, tollfree, this);
}
}
| 22.840909 | 102 | 0.702488 |
e1f86623f33f1ae647bbe6564e8f636f77c0860d
| 7,430 |
package com.fvostudio.project.mancamure;
import java.util.ArrayList;
import java.util.List;
import com.fvostudio.project.mancamure.gom.Board;
import com.fvostudio.project.mancamure.gom.BoardState;
import com.fvostudio.project.mancamure.gom.Movement;
import com.fvostudio.project.mancamure.gom.util.Vector3;
public class AwaleMovement implements Movement {
private int startingPitIndex;
// public AwaleMovement(Pit pit) {
// this.pit = pit.getSeedCount();
// this.startingPitPosition = pit.getPosition();
// }
public AwaleMovement(int startingPitIndex) {
this.startingPitIndex = startingPitIndex;
}
@Override
public void apply(Board board) {
board.changeState(getResultingState(board.getState()));
}
@Override
public AwaleBoardState getResultingState(BoardState boardState) {
assert(boardState instanceof AwaleBoardState);
AwaleBoardState state = (AwaleBoardState) boardState;
List<Integer> pits = state.getPits();
int pitCount = pits.size();
int playerPitCount = pitCount / 2;
int sowedSeedCount = pits.get(startingPitIndex);
int loopCount = sowedSeedCount / pitCount;
int playerSide = startingPitIndex / playerPitCount;
// cumulative index of the destination pit
// + loopCount : the starting pit must remain empty after the move
int destination = (startingPitIndex + sowedSeedCount + loopCount);
boolean destinationIsOnOpponentSide =
(destination % pitCount) / playerPitCount != playerSide;
ArrayList<Integer> newPits = new ArrayList<>(pits);
ArrayList<Integer> newBanks = new ArrayList<>(state.getBanks());
int playerBankIndex = state.getPlayerBankIndex();
newPits.set(startingPitIndex, 0);
for (int i = destination; i > startingPitIndex; --i) {
int realIndex = i % pitCount;
if (realIndex == startingPitIndex) {
continue;
}
newPits.set(realIndex, newPits.get(realIndex) + 1);
}
if (destinationIsOnOpponentSide) {
for (
int i = destination % pitCount;
i >= 0
&& i / playerPitCount != playerSide
&& 2 <= newPits.get(i)
&& newPits.get(i) <= 3;
--i
) {
int seedCount = newPits.get(i);
newPits.set(i, 0);
newBanks.set(playerBankIndex,
newBanks.get(playerBankIndex) + seedCount);
}
}
AwaleBoardState resultingState =
new AwaleBoardState(state, this, state.getOpponent(), newPits, newBanks);
if ( // in the resulting state the player is the opponent
resultingState.isFinalState()
&& resultingState.getRemainingOpponentSeedCount() <= 0
) {
int bankIndex = resultingState.getPlayerBankIndex();
int firstPitIndex =
resultingState.getFirstPitIndex(resultingState.getCurrentPlayer());
int lastPitIndex = firstPitIndex + playerPitCount - 1;
for (int i = firstPitIndex; i <= lastPitIndex; ++i) {
newBanks.set(bankIndex, newBanks.get(bankIndex) + newPits.get(i));
newPits.set(i, 0);
}
}
return resultingState;
}
public byte[] getSerializationFrom(AwaleBoardState state) {
List<Integer> pits = state.getPits();
int pitCount = pits.size();
int playerPitCount = pitCount / 2;
Vector3 startingPitPosition = state.getPitPosition(startingPitIndex);
int startingPitSeedCount = pits.get(startingPitIndex);
// 2: type, size
// 3: startingPit { x y seedCount }
// 2 * seedCount: destination { x y }
// 6 * 3: opponentPits { x y bank }
int serializiationSize = 2 + 3 + 2 * startingPitSeedCount + 3 * playerPitCount;
byte[] serializedMovement = new byte[serializiationSize];
serializedMovement[0] = 1;
serializedMovement[1] = (byte) serializiationSize;
int offset = 2;
serializedMovement[offset++] = (byte) (int) startingPitPosition.getX();
serializedMovement[offset++] = (byte) (int) startingPitPosition.getY();
serializedMovement[offset++] = (byte) startingPitSeedCount;
int sowedSeedCount = pits.get(startingPitIndex);
int loopCount = sowedSeedCount / pitCount;
int playerSide = startingPitIndex / playerPitCount;
// cumulative index of the destination pit
// + loopCount : the starting pit must remain empty after the move
int destination = (startingPitIndex + sowedSeedCount + loopCount);
boolean destinationIsOnOpponentSide =
(destination % pitCount) / playerPitCount != playerSide;
ArrayList<Integer> newPits = new ArrayList<>(pits);
int playerBankIndex = state.getPlayerBankIndex();
newPits.set(startingPitIndex, 0);
for (int i = startingPitIndex + 1; i <= destination; ++i) {
int realIndex = i % pitCount;
if (realIndex == startingPitIndex) {
continue;
}
newPits.set(realIndex, newPits.get(realIndex) + 1);
Vector3 pitPosition = state.getPitPosition(realIndex);
serializedMovement[offset++] = (byte) (int) pitPosition.getX();
serializedMovement[offset++] = (byte) (int) pitPosition.getY();
}
int seedToCollectOffset = 0;
for (
int i = state.getFirstPitIndex(state.getOpponent()) + playerPitCount - 1;
i >= 0 && i / playerPitCount != playerSide;
--i
) {
Vector3 pitPosition = state.getPitPosition(i);
serializedMovement[offset++] = (byte) (int) pitPosition.getX();
serializedMovement[offset++] = (byte) (int) pitPosition.getY();
if (i == destination % pitCount) {
seedToCollectOffset = offset;
}
serializedMovement[offset++] = -1;
}
if (destinationIsOnOpponentSide) {
for (
int i = destination % pitCount;
i >= 0
&& i / playerPitCount != playerSide
&& 2 <= newPits.get(i)
&& newPits.get(i) <= 3;
--i
) {
serializedMovement[seedToCollectOffset] = (byte) playerBankIndex;
seedToCollectOffset += 3;
}
AwaleBoardState resultingState = getResultingState(state);
// in the resulting state the player is the opponent
if (resultingState.isFinalState()
&& resultingState.getRemainingOpponentSeedCount() <= 0
) {
int bankIndex = resultingState.getPlayerBankIndex();
// offset of the bank of the first opponent's pit
seedToCollectOffset = 2 + 3 + 2 * startingPitSeedCount + 2;
for (int i = 0; i < 6; ++i) {
serializedMovement[seedToCollectOffset] = (byte) bankIndex;
seedToCollectOffset += 3;
}
}
}
return serializedMovement;
}
public int getStartingPitIndex() {
return startingPitIndex;
}
}
| 35.89372 | 87 | 0.588291 |
012564f8300b8fc236ba3ee7833db5f2e98e9075
| 444 |
package frc.lib.Webserver2.DashboardConfig;
public class CameraConfig extends VisibleWidgetConfig {
String streamURL = "";
public CameraConfig(){
super();
this.nominalHeight = 30;
this.nominalWidth = 40;
}
@Override
public String getJSDeclaration(){
return String.format("var widget%d = new Camera('widget%d', '%s', '%s');", idx, idx, name, streamURL);
}
}
| 23.368421 | 111 | 0.592342 |
134a55eddba13c6789b49587e9a62af964e0da81
| 1,565 |
package com.facebook.imagepipeline.memory;
import android.util.SparseIntArray;
import com.facebook.common.internal.Preconditions;
import javax.annotation.Nullable;
public class PoolParams
{
public static final int IGNORE_THREADS = -1;
public final SparseIntArray bucketSizes;
public final int maxBucketSize;
public final int maxNumThreads;
public final int maxSizeHardCap;
public final int maxSizeSoftCap;
public final int minBucketSize;
public PoolParams(int paramInt1, int paramInt2, @Nullable SparseIntArray paramSparseIntArray)
{
this(paramInt1, paramInt2, paramSparseIntArray, 0, Integer.MAX_VALUE, -1);
}
public PoolParams(int paramInt1, int paramInt2, @Nullable SparseIntArray paramSparseIntArray, int paramInt3, int paramInt4, int paramInt5)
{
if ((paramInt1 >= 0) && (paramInt2 >= paramInt1)) {}
for (boolean bool = true;; bool = false)
{
Preconditions.checkState(bool);
this.maxSizeSoftCap = paramInt1;
this.maxSizeHardCap = paramInt2;
this.bucketSizes = paramSparseIntArray;
this.minBucketSize = paramInt3;
this.maxBucketSize = paramInt4;
this.maxNumThreads = paramInt5;
return;
}
}
public PoolParams(int paramInt, @Nullable SparseIntArray paramSparseIntArray)
{
this(paramInt, paramInt, paramSparseIntArray, 0, Integer.MAX_VALUE, -1);
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/facebook/imagepipeline/memory/PoolParams.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 32.604167 | 140 | 0.729073 |
05103994b421ff573856eb5f23167eadff98b9c4
| 2,779 |
package com.aspose.imaging.examples.ModifyingImages;
import com.aspose.imaging.Image;
import com.aspose.imaging.examples.Logger;
import com.aspose.imaging.examples.Utils;
import com.aspose.imaging.fileformats.eps.EpsBinaryImage;
import com.aspose.imaging.fileformats.eps.EpsImage;
import com.aspose.imaging.fileformats.eps.EpsInterchangeImage;
import com.aspose.imaging.fileformats.eps.consts.EpsType;
import com.aspose.imaging.imageoptions.PngOptions;
public class SupportForEPSFormat
{
public static void main(String[] args)
{
Logger.startExample("SupportForEPSFormat");
String dataDir = Utils.getSharedDataDir() + "ModifyingImages/";;
try (EpsImage epsImage = (EpsImage)Image.load(dataDir+"bmpPhotoshop1bit.eps"))
{
// check if EPS image has any raster preview to proceed (for now only raster preview is supported)
if (epsImage.hasRasterPreview())
{
if (epsImage.getPhotoshopThumbnail() != null)
{
// process Photoshop thumbnail if it's present
Logger.println("process Photoshop thumbnail if it's present");
}
if (epsImage.getEpsType() == EpsType.Interchange)
{
// Get EPS Interchange subformat instance
EpsInterchangeImage epsInterchangeImage = (EpsInterchangeImage)epsImage;
if (epsInterchangeImage.getRasterPreview() != null)
{
// process black-and-white Interchange raster preview if it's present
Logger.println("process black-and-white Interchange raster preview if it's present");
}
}
else
{
// Get EPS Binary subformat instance
EpsBinaryImage epsBinaryImage = (EpsBinaryImage)epsImage;
if (epsBinaryImage.getTiffPreview() != null)
{
// process TIFF preview if it's present
Logger.println("process TIFF preview if it's present");
}
if (epsBinaryImage.getWmfPreview() != null)
{
// process WMF preview if it's present
Logger.println("process WMF preview if it's present");
}
}
// export EPS image to PNG (by default, best available quality preview is used for export)
epsImage.save(Utils.getOutDir() + "anyEpsFile.png", new PngOptions());
}
}
Logger.endExample();
}
}
| 41.477612 | 111 | 0.559194 |
6808f46723c667af17bc5e28185c7106a256c304
| 1,001 |
package com.isaacbrodsky.zztsearch.web.resources;
import com.codahale.metrics.annotation.Timed;
import com.isaacbrodsky.zztsearch.query.search.GameTextSearcher;
import com.isaacbrodsky.zztsearch.query.search.Index;
import com.isaacbrodsky.zztsearch.query.search.SearchResult;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public class SearchResource {
private final GameTextSearcher searcher;
public SearchResource(GameTextSearcher searcher) {
this.searcher = searcher;
}
@GET
@Timed
@Path("/{index}/{field}")
public SearchResult search(@PathParam("index") Index index,
@PathParam("field") String field,
@QueryParam("q") String query) throws Exception {
return searcher.search(index, field, query);
}
}
| 30.333333 | 80 | 0.709291 |
ce16cacea9f77206063f999c654b524f8995b8b4
| 4,039 |
/**
* Copyright 2011 Pablo Mendes, Max Jakob
*
* 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.dbpedia.spotlight.lucene.similarity;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TermsFilter extends Filter {
Set<Term> terms=new TreeSet<Term>();
/**
* Adds a term to the list of acceptable terms
* @param term
*/
public void addTerm(Term term)
{
terms.add(term);
}
/* (non-Javadoc)
* @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.IndexReader)
*/
@Override
public DocIdSet getDocIdSet(IndexReader reader) throws IOException
{
OpenBitSet result=new OpenBitSet(reader.maxDoc());
TermDocs td = reader.termDocs();
try {
int c = 0;
for (Iterator<Term> iter = terms.iterator(); iter.hasNext();)
{
Term term = iter.next();
td.seek(term);
while (td.next())
{
c++;
result.set(td.doc());
}
}
}
finally
{
td.close();
}
return result;
}
// public DocIdSet getDocIdSet(IndexReader reader) throws IOException
// {
// OpenBitSet[] buffer = new OpenBitSet[terms.size()];
//
// OpenBitSet result=new OpenBitSet(reader.maxDoc());
// TermDocs td = reader.termDocs();
// try {
// boolean first = true;
// for (Iterator<Term> iter = terms.iterator(); iter.hasNext();)
// {
// OpenBitSet r = new OpenBitSet(reader.maxDoc());
// Term term = iter.next();
// td.seek(term);
// while (td.next())
// {
// r.set(td.doc());
// }
// if (first)
// result = r;
// else
// result.and(r);
// first = false;
// long test1 = r.cardinality();
// long test2 = result.cardinality();
// System.out.println("r:"+test1);
// System.out.println("result:"+test2);
// }
// }
// finally
// {
// td.close();
// }
// return result;
// }
@Override
public boolean equals(Object obj)
{
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
TermsFilter test = (TermsFilter)obj;
return (terms == test.terms ||
(terms != null && terms.equals(test.terms)));
}
@Override
public int hashCode()
{
int hash=9;
for (Iterator<Term> iter = terms.iterator(); iter.hasNext();)
{
Term term = iter.next();
hash = 31 * hash + term.hashCode();
}
return hash;
}
}
| 30.368421 | 92 | 0.502104 |
05c5144ab0c9e087fbd55a9defb3263e6cd5bebc
| 3,814 |
/*******************************************************************************
* Copyright (c) 2009, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core;
import java.io.OutputStream;
import java.util.Properties;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* An interface for launchers of external commands.
*
* @since 5.1
*/
public interface ICommandLauncher {
public final static int COMMAND_CANCELED = 1;
public final static int ILLEGAL_COMMAND = -1;
public final static int OK = 0;
/**
* Sets the project that this launcher is associated with, or <code>null</code> if there is no such
* project.
*
* @param project
*/
public void setProject(IProject project);
/**
* Gets the project this launcher is associated with.
*
* @return IProject, or <code>null</code> if there is no such project.
*/
public IProject getProject();
/**
* Sets if the command should be printed out first before executing.
*/
public void showCommand(boolean show);
/**
* Returns a human readable error message corresponding to the last error encountered during command
* execution.
*
* @return A String corresponding to the error, or <code>null</code> if there has been no error.
* The message could be multi-line, however it is NOT guaranteed that it ends with end of line.
*/
public String getErrorMessage();
/**
* Sets the human readable error message corresponding to the last error encountered during command
* execution. A subsequent call to getErrorMessage() will return this string.
*
* @param error A String corresponding to the error message, or <code>null</code> if the error state is
* intended to be cleared.
*/
public void setErrorMessage(String error);
/**
* Returns an array of the command line arguments that were last used to execute a command.
*
* @return an array of type String[] corresponding to the arguments. The array can be empty, but should not
* be null.
*/
public String[] getCommandArgs();
/**
* Returns the set of environment variables in the context of which
* this launcher will execute commands.
*
* @return Properties
*/
public Properties getEnvironment();
/**
* Returns the constructed command line of the last command executed.
*
* @return String
*/
public String getCommandLine();
/**
* Execute a command
* @param env The list of environment variables in variable=value format.
* @throws CoreException if there is an error executing the command.
*/
public Process execute(IPath commandPath, String[] args, String[] env, IPath workingDirectory,
IProgressMonitor monitor) throws CoreException;
/**
* @deprecated Use {@link #waitAndRead(OutputStream, OutputStream, IProgressMonitor)} instead.
* @noreference This method is not intended to be referenced by clients.
*/
@Deprecated
public int waitAndRead(OutputStream out, OutputStream err);
/**
* Reads output form the process to the streams. A progress monitor is
* polled to test if the cancel button has been pressed. Destroys the
* process if the monitor becomes canceled override to implement a different
* way to read the process inputs
*/
public int waitAndRead(OutputStream output, OutputStream err, IProgressMonitor monitor);
}
| 32.87931 | 109 | 0.70215 |
e4f6b8671b1eef0c43c2db075c2c689a7b6a846c
| 2,936 |
package SPRY.Streaming.RealTime;
import java.util.HashMap;
import javax.realtime.AbsoluteTime;
import javax.realtime.AsyncEvent;
import javax.realtime.AsyncEventHandler;
import javax.realtime.Clock;
import javax.realtime.OneShotTimer;
import javax.realtime.RelativeTime;
/** This class is used internally by SPRY. It records the data processing latency, and its corresponding handlers */
public class LatencyMonitor {
protected static HashMap<Object, AbsoluteTime> dataToreceivingTime = new HashMap<>();
protected static HashMap<BatchedStream<?>, AsyncEvent> streamToEvent = new HashMap<>();
protected static HashMap<BatchedStream<?>, RelativeTime> streamToLatency = new HashMap<>();
protected static HashMap<BatchedStream<?>, AsyncEventHandler> streamToHanlder = new HashMap<>();
protected static HashMap<Object, RelativeTime> dataToLatency = new HashMap<>();
protected static HashMap<Object, AsyncEvent> dataToEvent = new HashMap<>();
protected static HashMap<Object, OneShotTimer> dataToTimer = new HashMap<>();
public static void addLatencyMissHandler(RelativeTime latency, AsyncEventHandler latencyMissHanlder, BatchedStream<?> stream){
if (stream != null) {
streamToLatency.put(stream, latency);
AsyncEvent latencyMiss = new AsyncEvent();
latencyMiss.setHandler(latencyMissHanlder);
streamToEvent.put(stream, latencyMiss);
streamToHanlder.put(stream, latencyMissHanlder);
}
}
public static void record(Object t, BatchedStream<?> stream) {
if (t != null) {
AbsoluteTime now = Clock.getRealtimeClock().getTime();
dataToreceivingTime.put(t, now);
dataToLatency.put(t, streamToLatency.get(stream));
dataToEvent.put(t, streamToEvent.get(stream));
if (streamToHanlder.get(stream) != null) {
OneShotTimer latencyMissMonitor = new OneShotTimer(now.add(streamToLatency.get(stream)), streamToHanlder.get(stream));
dataToTimer.put(t, latencyMissMonitor);
latencyMissMonitor.start();
}
}
}
public static void testLatencyMeet(Object t){
if (t != null) {
AbsoluteTime now = Clock.getRealtimeClock().getTime();
AbsoluteTime recTime = dataToreceivingTime.get(t);
RelativeTime latency = dataToLatency.get(t);
AsyncEvent latencyMiss = dataToEvent.get(t);
if (recTime != null && latency != null && latencyMiss!=null) {
if (dataToTimer.get(t) != null) {
try {
dataToTimer.get(t).stop();
dataToTimer.get(t).destroy();
} catch (Exception e) {}
}
System.out.println(t + "\tLatency: " + now.subtract(recTime).getMilliseconds());
if (now.subtract(recTime).compareTo(latency) > 0) latencyMiss.fire();
dataToreceivingTime.remove(t);
dataToLatency.remove(t);
dataToEvent.remove(t);
}
}
}
public static void removeTimer(Object t){
if (dataToTimer.get(t) != null) {
try {
dataToTimer.get(t).stop();
dataToTimer.get(t).destroy();
} catch (Exception e) {}
dataToTimer.remove(t);
}
}
}
| 37.641026 | 127 | 0.725817 |
d02cc4fae6969d0782bf314f04f3ebc10a5afd48
| 8,012 |
/*
Copyright 1995-2015 Esri
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.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: contracts@esri.com
*/
package com.esri.core.geometry;
class PairwiseIntersectorImpl {
// Quad_tree
private MultiPathImpl m_multi_path_impl_a;
private MultiPathImpl m_multi_path_impl_b;
private boolean m_b_paths;
private boolean m_b_quad_tree;
private boolean m_b_done;
private boolean m_b_swap_elements;
private double m_tolerance;
private int m_path_index;
private int m_element_handle;
private Envelope2D m_paths_query = new Envelope2D(); // only used for m_b_paths == true case
private QuadTreeImpl m_quad_tree;
private QuadTreeImpl.QuadTreeIteratorImpl m_qt_iter;
private SegmentIteratorImpl m_seg_iter;
// Envelope_2D_intersector
private Envelope2DIntersectorImpl m_intersector;
private int m_function;
private interface State {
static final int nextPath = 0;
static final int nextSegment = 1;
static final int iterate = 2;
}
PairwiseIntersectorImpl(MultiPathImpl multi_path_impl_a, MultiPathImpl multi_path_impl_b, double tolerance, boolean b_paths) {
m_multi_path_impl_a = multi_path_impl_a;
m_multi_path_impl_b = multi_path_impl_b;
m_b_paths = b_paths;
m_path_index = -1;
m_b_quad_tree = false;
GeometryAccelerators geometry_accelerators_a = multi_path_impl_a._getAccelerators();
if (geometry_accelerators_a != null) {
QuadTreeImpl qtree_a = (!b_paths ? geometry_accelerators_a.getQuadTree() : geometry_accelerators_a.getQuadTreeForPaths());
if (qtree_a != null) {
m_b_done = false;
m_tolerance = tolerance;
m_quad_tree = qtree_a;
m_qt_iter = m_quad_tree.getIterator();
m_b_quad_tree = true;
m_b_swap_elements = true;
m_function = State.nextPath;
if (!b_paths)
m_seg_iter = multi_path_impl_b.querySegmentIterator();
else
m_path_index = multi_path_impl_b.getPathCount(); // we will iterate backwards until we hit -1
}
}
if (!m_b_quad_tree) {
GeometryAccelerators geometry_accelerators_b = multi_path_impl_b._getAccelerators();
if (geometry_accelerators_b != null) {
QuadTreeImpl qtree_b = (!b_paths ? geometry_accelerators_b.getQuadTree() : geometry_accelerators_b.getQuadTreeForPaths());
if (qtree_b != null) {
m_b_done = false;
m_tolerance = tolerance;
m_quad_tree = qtree_b;
m_qt_iter = m_quad_tree.getIterator();
m_b_quad_tree = true;
m_b_swap_elements = false;
m_function = State.nextPath;
if (!b_paths)
m_seg_iter = multi_path_impl_a.querySegmentIterator();
else
m_path_index = multi_path_impl_a.getPathCount(); // we will iterate backwards until we hit -1
}
}
}
if (!m_b_quad_tree) {
if (!b_paths) {
m_intersector = InternalUtils.getEnvelope2DIntersector(multi_path_impl_a, multi_path_impl_b, tolerance);
} else {
boolean b_simple_a = multi_path_impl_a.getIsSimple(0.0) >= 1;
boolean b_simple_b = multi_path_impl_b.getIsSimple(0.0) >= 1;
m_intersector = InternalUtils.getEnvelope2DIntersectorForParts(multi_path_impl_a, multi_path_impl_b, tolerance, b_simple_a, b_simple_b);
}
}
}
boolean next() {
if (m_b_quad_tree) {
if (m_b_done)
return false;
boolean b_searching = true;
while (b_searching) {
switch (m_function) {
case State.nextPath:
b_searching = nextPath_();
break;
case State.nextSegment:
b_searching = nextSegment_();
break;
case State.iterate:
b_searching = iterate_();
break;
default:
throw GeometryException.GeometryInternalError();
}
}
if (m_b_done)
return false;
return true;
}
if (m_intersector == null)
return false;
return m_intersector.next();
}
int getRedElement() {
if (m_b_quad_tree) {
if (!m_b_swap_elements)
return (!m_b_paths ? m_seg_iter.getStartPointIndex() : m_path_index);
return m_quad_tree.getElement(m_element_handle);
}
return m_intersector.getRedElement(m_intersector.getHandleA());
}
int getBlueElement() {
if (m_b_quad_tree) {
if (m_b_swap_elements)
return (!m_b_paths ? m_seg_iter.getStartPointIndex() : m_path_index);
return m_quad_tree.getElement(m_element_handle);
}
return m_intersector.getBlueElement(m_intersector.getHandleB());
}
Envelope2D getRedEnvelope() {
if (!m_b_paths)
throw GeometryException.GeometryInternalError();
if (m_b_quad_tree) {
if (!m_b_swap_elements)
return m_paths_query;
return m_quad_tree.getElementExtent(m_element_handle);
}
return m_intersector.getRedEnvelope(m_intersector.getHandleA());
}
Envelope2D getBlueEnvelope() {
if (!m_b_paths)
throw GeometryException.GeometryInternalError();
if (m_b_quad_tree) {
if (m_b_swap_elements)
return m_paths_query;
return m_quad_tree.getElementExtent(m_element_handle);
}
return m_intersector.getBlueEnvelope(m_intersector.getHandleB());
}
boolean nextPath_() {
if (!m_b_paths) {
if (!m_seg_iter.nextPath()) {
m_b_done = true;
return false;
}
m_function = State.nextSegment;
return true;
}
if (--m_path_index == -1) {
m_b_done = true;
return false;
}
if (m_b_swap_elements)
m_multi_path_impl_b.queryPathEnvelope2D(m_path_index, m_paths_query);
else
m_multi_path_impl_a.queryPathEnvelope2D(m_path_index, m_paths_query);
m_qt_iter.resetIterator(m_paths_query, m_tolerance);
m_function = State.iterate;
return true;
}
boolean nextSegment_() {
if (!m_seg_iter.hasNextSegment()) {
m_function = State.nextPath;
return true;
}
Segment segment = m_seg_iter.nextSegment();
m_qt_iter.resetIterator(segment, m_tolerance);
m_function = State.iterate;
return true;
}
boolean iterate_() {
m_element_handle = m_qt_iter.next();
if (m_element_handle == -1) {
m_function = (!m_b_paths ? State.nextSegment : State.nextPath);
return true;
}
return false;
}
}
| 32.048 | 152 | 0.59698 |
881f07ff617e2f278fa6815d4fd21ed3f31d3b58
| 3,282 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.indices.mapping.put;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedRequestBuilder;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import java.util.Map;
/**
* Builder for a put mapping request
*/
public class PutMappingRequestBuilder
extends AcknowledgedRequestBuilder<PutMappingRequest, AcknowledgedResponse, PutMappingRequestBuilder> {
public PutMappingRequestBuilder(ElasticsearchClient client, PutMappingAction action) {
super(client, action, new PutMappingRequest());
}
public PutMappingRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
public PutMappingRequestBuilder setConcreteIndex(Index index) {
request.setConcreteIndex(index);
return this;
}
/**
* Specifies what type of requested indices to ignore and wildcard indices expressions.
* <p>
* For example indices that don't exist.
*/
public PutMappingRequestBuilder setIndicesOptions(IndicesOptions options) {
request.indicesOptions(options);
return this;
}
/**
* The type of the mappings.
*/
public PutMappingRequestBuilder setType(String type) {
request.type(type);
return this;
}
/**
* The mapping source definition.
*/
public PutMappingRequestBuilder setSource(XContentBuilder mappingBuilder) {
request.source(mappingBuilder);
return this;
}
/**
* The mapping source definition.
*/
public PutMappingRequestBuilder setSource(Map mappingSource) {
request.source(mappingSource);
return this;
}
/**
* The mapping source definition.
*/
public PutMappingRequestBuilder setSource(String mappingSource, XContentType xContentType) {
request.source(mappingSource, xContentType);
return this;
}
/**
* A specialized simplified mapping source method, takes the form of simple properties definition:
* ("field1", "type=string,store=true").
*/
public PutMappingRequestBuilder setSource(Object... source) {
request.source(source);
return this;
}
}
| 31.864078 | 107 | 0.719074 |
013b666a55f7b67d0d1749db81161b11ce5122bf
| 11,662 |
package name.remal.tracingspec.renderer.plantuml.sequence;
import static java.util.Objects.requireNonNull;
import static name.remal.gradle_plugins.api.BuildTimeConstants.getClassSimpleName;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
import lombok.val;
import name.remal.tracingspec.model.SpecSpanNode;
import name.remal.tracingspec.model.SpecSpanNodeVisitor;
import name.remal.tracingspec.model.SpecSpansGraph;
import name.remal.tracingspec.renderer.AbstractTracingSpecRenderer;
import name.remal.tracingspec.renderer.plantuml.AbstractTracingSpecPlantumlRenderer;
import org.jetbrains.annotations.Contract;
public class TracingSpecPlantumlSequenceRenderer extends AbstractTracingSpecPlantumlRenderer {
@Override
public String getRendererName() {
return "plantuml-sequence";
}
@Override
@SuppressWarnings({"java:S3776", "java:S1854"})
protected String renderTracingSpecImpl(SpecSpansGraph graph) {
preprocessGraph(graph);
val diagram = new Diagram();
Deque<Message> messagesStack = new ArrayDeque<>();
val rootAndAsyncNodes = collectRootAndAsyncNodes(graph);
rootAndAsyncNodes.forEach(topLevelNode -> topLevelNode.visit(new SpecSpanNodeVisitor() {
@Override
public boolean filterNode(SpecSpanNode node) {
return node.isRoot() || node.isSync() || node == topLevelNode;
}
@Override
public void visit(SpecSpanNode node) {
val lastMessage = messagesStack.peekLast();
if (lastMessage == null) {
val rootMessage = diagram.newRoot(node);
messagesStack.addLast(rootMessage);
} else {
val childMessage = lastMessage.newChild(node);
messagesStack.addLast(childMessage);
}
}
@Override
public void postVisit(SpecSpanNode node) {
val lastMessage = messagesStack.pollLast();
if (lastMessage == null) {
throw new IllegalStateException("messagesStack is empty");
}
}
}));
return diagram.toString();
}
private static void preprocessGraph(SpecSpansGraph graph) {
addIntermediateNodes(graph);
}
@SuppressWarnings("java:S3776")
private static void addIntermediateNodes(SpecSpansGraph graph) {
graph.visit(parent ->
new ArrayList<>(parent.getChildren()).forEach(child -> {
if (child.isAsync()) {
return;
}
if (getTargetServiceName(child) == null) {
// Child has target
return;
}
val intermediateChild = new SpecSpanNode();
intermediateChild.setHidden(true);
val childSourceServiceName = getSourceServiceName(child);
val parentTargetServiceName = getTargetServiceName(parent);
if (parentTargetServiceName != null) {
if (parentTargetServiceName.equals(childSourceServiceName)) {
// Parent has a target that is the same as child's source
return;
} else {
intermediateChild.setServiceName(parentTargetServiceName);
intermediateChild.setRemoteServiceName(childSourceServiceName);
}
} else {
val parentSourceServiceName = getSourceServiceName(parent);
if (Objects.equals(parentSourceServiceName, childSourceServiceName)) {
// Parent has *no* target and has the same source
return;
} else {
intermediateChild.setServiceName(parentSourceServiceName);
intermediateChild.setRemoteServiceName(childSourceServiceName);
}
}
parent.addChildAfter(intermediateChild, child);
child.setParent(intermediateChild);
})
);
}
private static String getSourceServiceName(SpecSpanNode node) {
val kind = node.getKind();
val remoteServiceName = node.getRemoteServiceName();
if (kind != null && kind.isRemoteSource()) {
if (remoteServiceName != null) {
return remoteServiceName;
}
}
return requireNonNull(
node.getServiceName(),
getClassSimpleName(AbstractTracingSpecRenderer.class) + " doesn't allow service name to be NULL"
);
}
@Nullable
private static String getTargetServiceName(SpecSpanNode node) {
val kind = node.getKind();
if (kind != null && kind.isRemoteSource()) {
val serviceName = requireNonNull(
node.getServiceName(),
getClassSimpleName(AbstractTracingSpecRenderer.class) + " doesn't allow service name to be NULL"
);
return serviceName;
}
return node.getRemoteServiceName();
}
private static List<SpecSpanNode> collectRootAndAsyncNodes(SpecSpansGraph graph) {
List<SpecSpanNode> rootAndAsyncNodes = new ArrayList<>();
graph.visit(node -> {
if (node.isRoot() || node.isAsync()) {
rootAndAsyncNodes.add(node);
}
});
return rootAndAsyncNodes;
}
private static class Diagram {
public Message newRoot(SpecSpanNode node) {
val child = new Message(null, node);
this.children.add(child);
return child;
}
private final List<Message> children = new ArrayList<>();
@Override
public String toString() {
val sb = new StringBuilder();
sb.append("@startuml");
sb.append("\nskinparam maxmessagesize 500");
sb.append("\nskinparam responseMessageBelowArrow true");
children.forEach(sb::append);
sb.append("\n@enduml");
return sb.toString();
}
}
private static class Message {
@Contract("_ -> new")
public Message newChild(SpecSpanNode node) {
val child = new Message(this, node);
this.children.add(child);
return child;
}
@Nullable
private final Message parent;
private final List<Message> children = new ArrayList<>();
private final boolean minimized;
private final boolean async;
@Nullable
private final String sourceServiceName;
private final String targetServiceName;
@Nullable
private final String name;
@Nullable
private final String description;
private final Map<String, String> tags = new LinkedHashMap<>();
@SuppressWarnings("java:S3776")
private Message(@Nullable Message parent, SpecSpanNode node) {
this.parent = parent;
this.minimized = node.isHidden();
this.async = node.isAsync();
val curSourceServiceName = getSourceServiceName(node);
val curTargetServiceName = getTargetServiceName(node);
val parentNode = node.getParent();
if (parentNode == null || curTargetServiceName != null) {
this.sourceServiceName = curSourceServiceName;
this.targetServiceName = curTargetServiceName != null ? curTargetServiceName : curSourceServiceName;
} else {
val parentTargetServiceName = getTargetServiceName(parentNode);
if (parentTargetServiceName != null) {
this.sourceServiceName = parentTargetServiceName;
this.targetServiceName = curSourceServiceName;
} else {
val parentSourceServiceName = getSourceServiceName(parentNode);
if (curSourceServiceName.equals(parentSourceServiceName)) {
this.sourceServiceName = curSourceServiceName;
this.targetServiceName = curSourceServiceName;
} else {
this.sourceServiceName = parentSourceServiceName;
this.targetServiceName = curSourceServiceName;
}
}
}
if (this.minimized) {
this.name = null;
this.description = null;
} else {
this.name = node.getName();
this.description = node.getDescription();
node.getTags().forEach((tagName, tagValue) -> {
if (isNotEmpty(tagName) && tagValue != null) {
this.tags.put(tagName, tagValue);
}
});
}
}
@Override
@SuppressWarnings("java:S3776")
public String toString() {
val hidden = minimized
&& parent != null
&& !async
&& Objects.equals(sourceServiceName, targetServiceName);
if (hidden) {
val sb = new StringBuilder();
children.forEach(sb::append);
return sb.toString();
}
val sb = new StringBuilder();
sb.append('\n');
if (parent == null && Objects.equals(sourceServiceName, targetServiceName)) {
sb.append('[');
} else if (sourceServiceName != null) {
sb.append(quoteString(sourceServiceName));
sb.append(' ');
} else {
sb.append('[');
}
if (async) {
sb.append("->>");
} else {
sb.append("->");
}
sb.append(' ');
sb.append(quoteString(targetServiceName));
if (isNotEmpty(name)) {
sb.append(": ").append(escapeString(name));
}
tags.forEach((tagName, tagValue) ->
sb.append("\\n<size:10>")
.append(escapeString(tagName))
.append('=')
.append(escapeString(tagValue))
.append("</size>")
);
if (isNotEmpty(description)) {
sb.append("\nnote left: ").append(escapeString(description));
}
val sourceShouldBeActivated = parent == null
&& !async
&& !Objects.equals(sourceServiceName, targetServiceName);
if (sourceShouldBeActivated) {
sb.append("\nactivate ").append(quoteString(sourceServiceName));
}
sb.append("\nactivate ").append(quoteString(targetServiceName));
children.forEach(sb::append);
if (async) {
sb.append("\ndeactivate ").append(quoteString(targetServiceName));
} else {
sb.append("\nreturn");
if (isNotEmpty(name)) {
sb.append(" <size:9>").append(escapeString(name)).append("</size>");
}
}
if (sourceShouldBeActivated) {
sb.append("\ndeactivate ").append(quoteString(sourceServiceName));
}
return sb.toString();
}
}
}
| 34.502959 | 116 | 0.554622 |
bbf023b6d8bd64c6736a9bbd059fb4f7caa894f1
| 5,934 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.smallrye.metrics;
import java.util.Objects;
import java.util.Optional;
import org.eclipse.microprofile.metrics.DefaultMetadata;
import org.eclipse.microprofile.metrics.MetricType;
/**
* @author hrupp
*
*/
public class ExtendedMetadata extends DefaultMetadata {
private final String mbean;
private final boolean multi;
/**
* Optional configuration to prepend the microprofile scope to the metric name
* when it is exported to the OpenMetrics format.
*
* By default, the option is empty() and will not be taken into account.
* If true, the scope is prepended to the metric name when the OpenMetrics name is generated (e.g. {@code vendor_foo}.
* If false, the scope is added to the metric tags instead (e.g. foo{microprofile_scope="vendor"}.
*
* This option has precedence over the global configuration
* {@link io.smallrye.metrics.exporters.OpenMetricsExporter#SMALLRYE_METRICS_USE_PREFIX_FOR_SCOPE}.
*/
private final Optional<Boolean> prependsScopeToOpenMetricsName;
/**
* If true, the scope in OpenMetrics export will be skipped completely.
*/
private final boolean skipsScopeInOpenMetricsExportCompletely;
/**
* Overrides the name under which the metric is presented in OpenMetrics export.
* Applies only to non-compound metrics (that means counters and gauges).
*/
private final Optional<String> openMetricsKeyOverride;
public ExtendedMetadata(String name, MetricType type) {
this(name, null, null, type, null, null, false);
}
public ExtendedMetadata(String name, MetricType type, String unit, String description,
boolean skipsScopeInOpenMetricsExportCompletely) {
this(name, null, description, type, unit, null, false, Optional.of(true), skipsScopeInOpenMetricsExportCompletely,
null);
}
public ExtendedMetadata(String name, MetricType type, String unit, String description,
boolean skipsScopeInOpenMetricsExportCompletely, String openMetricsKey) {
this(name, null, description, type, unit, null, false, Optional.of(true), skipsScopeInOpenMetricsExportCompletely,
openMetricsKey);
}
public ExtendedMetadata(String name, String displayName, String description, MetricType typeRaw, String unit) {
this(name, displayName, description, typeRaw, unit, null, false, Optional.empty());
}
public ExtendedMetadata(String name, String displayName, String description, MetricType typeRaw, String unit, String mbean,
boolean multi) {
this(name, displayName, description, typeRaw, unit, mbean, multi, Optional.empty());
}
public ExtendedMetadata(String name, String displayName, String description, MetricType typeRaw, String unit, String mbean,
boolean multi, Optional<Boolean> prependsScopeToOpenMetricsName) {
this(name, displayName, description, typeRaw, unit, mbean, multi, prependsScopeToOpenMetricsName, false, null);
}
public ExtendedMetadata(String name, String displayName, String description, MetricType typeRaw, String unit, String mbean,
boolean multi, Optional<Boolean> prependsScopeToOpenMetricsName, boolean skipsScopeInOpenMetricsExportCompletely,
String openMetricsKeyOverride) {
super(name, displayName, description, typeRaw, unit);
this.mbean = mbean;
this.multi = multi;
this.prependsScopeToOpenMetricsName = prependsScopeToOpenMetricsName;
this.skipsScopeInOpenMetricsExportCompletely = skipsScopeInOpenMetricsExportCompletely;
this.openMetricsKeyOverride = Optional.ofNullable(openMetricsKeyOverride);
}
public String getMbean() {
return mbean;
}
public boolean isMulti() {
return multi;
}
public Optional<Boolean> prependsScopeToOpenMetricsName() {
return prependsScopeToOpenMetricsName;
}
public boolean isSkipsScopeInOpenMetricsExportCompletely() {
return skipsScopeInOpenMetricsExportCompletely;
}
public Optional<String> getOpenMetricsKeyOverride() {
return openMetricsKeyOverride;
}
public static ExtendedMetadataBuilder builder() {
return new ExtendedMetadataBuilder();
}
@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;
}
ExtendedMetadata that = (ExtendedMetadata) o;
return multi == that.multi &&
Objects.equals(prependsScopeToOpenMetricsName, that.prependsScopeToOpenMetricsName) &&
Objects.equals(skipsScopeInOpenMetricsExportCompletely, that.skipsScopeInOpenMetricsExportCompletely) &&
Objects.equals(openMetricsKeyOverride, that.openMetricsKeyOverride) &&
Objects.equals(mbean, that.mbean);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), mbean, multi, prependsScopeToOpenMetricsName,
skipsScopeInOpenMetricsExportCompletely, openMetricsKeyOverride);
}
}
| 40.367347 | 127 | 0.705932 |
89304c009dc9db01a94efdd31d7dae32e6cbe523
| 373 |
package pro.gravit.launcher.modules.events;
import pro.gravit.launcher.modules.LauncherModule;
public class PostInitPhase extends LauncherModule.Event {}
/* Location: C:\Users\Main\AppData\Roaming\StreamCraf\\updates\Launcher.jar!\pro\gravit\launcher\modules\events\PostInitPhase.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
| 33.909091 | 144 | 0.745308 |
76d560dfe19f034c15a91a6efb4c73ebd1801308
| 1,416 |
package com.trickl.model.oanda.account;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.Builder;
import lombok.Data;
/** The response from the /v3/accounts/{accountId} endpoint. */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"changes",
"state",
"lastTransactionID",
})
@Data
@Builder
public class GetAccountChangesResponse {
/* The changes to the Account’s Orders, Trades and Positions since the
* specified Transaction ID. Only provided if the sinceTransactionID is
* supplied to the poll request. */
@JsonPropertyDescription(
" The changes to the Account’s Orders, Trades and Positions since the"
+ " specified Transaction ID. Only provided if the sinceTransactionID is"
+ " supplied to the poll request.")
private AccountChanges changes;
/* The Account’s current price-dependent state. */
@JsonPropertyDescription("The Account’s current price-dependent state.")
private AccountChangesState state;
/* The ID of the most recent Transaction created for the Account. */
@JsonProperty("lastTransactionID")
@JsonPropertyDescription("The ID of the most recent Transaction created for the Account")
private String lastTransactionId;
}
| 37.263158 | 91 | 0.766243 |
f6d0c73757269d37ee1f8316ce97ae35a898deb6
| 3,961 |
/*
* 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.cassandra.cql3.restrictions;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.statements.Bound;
import org.apache.cassandra.db.IndexExpression;
import org.apache.cassandra.db.index.SecondaryIndexManager;
import org.apache.cassandra.exceptions.InvalidRequestException;
/**
* A restriction/clause on a column.
* The goal of this class being to group all conditions for a column in a SELECT.
*/
public interface Restriction
{
public boolean isOnToken();
public boolean isSlice();
public boolean isEQ();
public boolean isIN();
public boolean isContains();
public boolean isMultiColumn();
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException;
/**
* Returns <code>true</code> if one of the restrictions use the specified function.
*
* @param ksName the keyspace name
* @param functionName the function name
* @return <code>true</code> if one of the restrictions use the specified function, <code>false</code> otherwise.
*/
public boolean usesFunction(String ksName, String functionName);
/**
* Checks if the specified bound is set or not.
* @param b the bound type
* @return <code>true</code> if the specified bound is set, <code>false</code> otherwise
*/
public boolean hasBound(Bound b);
public List<ByteBuffer> bounds(Bound b, QueryOptions options) throws InvalidRequestException;
/**
* Checks if the specified bound is inclusive or not.
* @param b the bound type
* @return <code>true</code> if the specified bound is inclusive, <code>false</code> otherwise
*/
public boolean isInclusive(Bound b);
/**
* Merges this restriction with the specified one.
*
* @param otherRestriction the restriction to merge into this one
* @return the restriction resulting of the merge
* @throws InvalidRequestException if the restrictions cannot be merged
*/
public Restriction mergeWith(Restriction otherRestriction) throws InvalidRequestException;
/**
* Check if the restriction is on indexed columns.
*
* @param indexManager the index manager
* @return <code>true</code> if the restriction is on indexed columns, <code>false</code>
*/
public boolean hasSupportingIndex(SecondaryIndexManager indexManager);
/**
* Adds to the specified list the <code>IndexExpression</code>s corresponding to this <code>Restriction</code>.
*
* @param expressions the list to add the <code>IndexExpression</code>s to
* @param indexManager the secondary index manager
* @param options the query options
* @throws InvalidRequestException if this <code>Restriction</code> cannot be converted into
* <code>IndexExpression</code>s
*/
public void addIndexExpressionTo(List<IndexExpression> expressions,
SecondaryIndexManager indexManager,
QueryOptions options)
throws InvalidRequestException;
}
| 39.61 | 117 | 0.708659 |
efb614af5331ada7f5905d3bb283c0d915be79dc
| 3,482 |
package com.sparkpost.model;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.gson.Gson;
public class TemplateContentAttributesTest {
private String TEMPLATE_ATTRIBUTES_JSON = "{\n"
+ " \"email_rfc822\": \"RFC 822 Content\",\n"
+ " \"reply_to\": \"reply to\",\n"
+ " \"subject\": \"the subject\",\n"
+ " \"text\": \"some text\",\n"
+ " \"html\": \"html content\",\n"
+ " \"headers\": {\n"
+ " \"Content-Type\": \"text/plain\"\n"
+ " },"
+ " \"from\": {\n"
+ " \"email\" : \"someone@example.com\","
+ " \"name\" : \"First Last\""
+ " }"
+ "}";
@BeforeClass
public static void setUpClass() {
Configurator.setRootLevel(Level.DEBUG);
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
*
*/
@Test
public void testDecodeTemplateAttributes() {
Gson gson = new Gson();
TemplateContentAttributes templateAttributes = gson.fromJson(this.TEMPLATE_ATTRIBUTES_JSON, TemplateContentAttributes.class);
Assert.assertNotNull(templateAttributes);
Assert.assertEquals(templateAttributes.getEmailRFC822(), "RFC 822 Content");
Assert.assertEquals(templateAttributes.getReplyTo(), "reply to");
Assert.assertEquals(templateAttributes.getSubject(), "the subject");
Assert.assertEquals(templateAttributes.getText(), "some text");
Assert.assertEquals(templateAttributes.getHtml(), "html content");
Map<String, String> headers = templateAttributes.getHeaders();
Assert.assertNotNull(headers);
AddressAttributes from = templateAttributes.getFrom();
Assert.assertNotNull(from);
}
/**
*
*/
@Test
public void testTemplateAttributesRoundtrip() {
Gson gson = new Gson();
TemplateContentAttributes templateAttributes = gson.fromJson(this.TEMPLATE_ATTRIBUTES_JSON, TemplateContentAttributes.class);
Assert.assertNotNull(templateAttributes);
String templateAttributes_json = templateAttributes.toJson();
TemplateContentAttributes templateAttributes2 = gson.fromJson(templateAttributes_json, TemplateContentAttributes.class);
Assert.assertNotNull(templateAttributes2);
Assert.assertEquals(templateAttributes.getEmailRFC822(), templateAttributes2.getEmailRFC822());
Assert.assertEquals(templateAttributes.getReplyTo(), templateAttributes2.getReplyTo());
Assert.assertEquals(templateAttributes.getSubject(), templateAttributes2.getSubject());
Assert.assertEquals(templateAttributes.getText(), templateAttributes2.getText());
Assert.assertEquals(templateAttributes.getHtml(), templateAttributes2.getHtml());
Map<String, String> headers = templateAttributes2.getHeaders();
Assert.assertNotNull(headers);
AddressAttributes from = templateAttributes2.getFrom();
Assert.assertNotNull(from);
}
}
| 35.171717 | 133 | 0.63699 |
614db61b23b61f925f97b73502666b5024cc27cc
| 863 |
package fundamentos.constantesVariaveis;
import java.util.Scanner;
public class conversor {
public static void main(String [] args) {
Scanner inputMedida = new Scanner(System.in);
System.out.println("Qual a medida deseja converter fahrenheint[F] ou celsius [C]? ");
String medida = inputMedida.nextLine();
Scanner inputTemperatura = new Scanner(System.in);
System.out.println("Qual a temperatura atual? ");
Float temperatura = inputTemperatura.nextFloat();
if (medida == "F") {
Double conversor = (1.8*temperatura)+32;
System.out.println("A temperatura em Fahrenheint é de: " + conversor);
} else if (medida == "C") {
Double coversor = (temperatura-32)/1.8;
System.out.println("A temperatura em Celsius é de: " + coversor);
}
}
}
| 34.52 | 93 | 0.625724 |
e62b57ba1ba6304e3f6da59a0db6fb810f56a9ad
| 1,663 |
/*
* 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.dubbo.spring.boot.actuate.endpoint;
import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata;
import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import java.util.Map;
/**
* Dubbo Shutdown
*
* @since 2.7.0
*/
@Endpoint(id = "dubboshutdown")
public class DubboShutdownEndpoint extends AbstractDubboMetadata {
@Autowired
private DubboShutdownMetadata dubboShutdownMetadata;
@WriteOperation
public Map<String, Object> shutdown() throws Exception {
return dubboShutdownMetadata.shutdown();
}
}
| 36.955556 | 85 | 0.755262 |
73290b3aeedf41361756eb2aeb4f316a90ca28a6
| 2,150 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ozone.web.interfaces;
/**
* This in the accounting interface, Ozone Rest interface will call into this
* interface whenever a put or delete key happens.
* <p>
* TODO : Technically we need to report bucket creation and deletion too
* since the bucket names and metadata consume storage.
* <p>
* TODO : We should separate out reporting metadata & data --
* <p>
* In some cases end users will only want to account for the data they are
* storing since metadata is mostly a cost of business.
*/
public interface Accounting {
/**
* This call is made when ever a put key call is made.
* <p>
* In case of a Put which causes a over write of a key accounting system will
* see two calls, a removeByte call followed by an addByte call.
*
* @param owner - Volume Owner
* @param volume - Name of the Volume
* @param bucket - Name of the bucket
* @param bytes - How many bytes are put
*/
void addBytes(String owner, String volume, String bucket, int bytes);
/**
* This call is made whenever a delete call is made.
*
* @param owner - Volume Owner
* @param volume - Name of the Volume
* @param bucket - Name of the bucket
* @param bytes - How many bytes are deleted
*/
void removeBytes(String owner, String volume, String bucket, int bytes);
}
| 37.068966 | 79 | 0.711628 |
88de13e797287573ffc560303cafe769a48d7df1
| 1,865 |
// Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
/**
*
*/
package javax.servlet.sip;
import java.io.Serializable;
/**
* @author christophe
*/
public class SipApplicationRouterInfo {
String _NextApplicationName;
String _Route;
Serializable _StateInfo;
String _SubscriberURI;
SipApplicationRoutingRegion _SipApplicationRoutingRegion;
SipRouteModifier _SipRouterModifier;
public SipApplicationRouterInfo(String nextApplicationName,
String subscriberURI, String route, SipRouteModifier mod,SipApplicationRoutingRegion region,
Serializable stateIn) {
_NextApplicationName=nextApplicationName;
_SubscriberURI=subscriberURI;
_Route=route;
_SipRouterModifier=mod;
_SipApplicationRoutingRegion=region;
_StateInfo=stateIn;
}
public String getNextApplicationName() {
return _NextApplicationName;
}
public String getRoute() {
return _Route;
}
public Serializable getStateInfo() {
return _StateInfo;
}
public String getSubscriberURI() {
return _SubscriberURI;
}
public SipApplicationRoutingRegion getRoutingRegion() {
return _SipApplicationRoutingRegion;
}
public SipRouteModifier getRouteModifier() {
return _SipRouterModifier;
}
public String toString() {
StringBuffer buffer=new StringBuffer("RouterInfo:");
buffer.append(_NextApplicationName);
buffer.append(",");
buffer.append(_SubscriberURI);
buffer.append(",");
buffer.append(_SipRouterModifier);
buffer.append(",");
buffer.append(_SipApplicationRoutingRegion);
buffer.append(",");
buffer.append(_StateInfo);
return buffer.toString();
}
}
| 24.220779 | 104 | 0.678284 |
3ace5fec614853a08efbaff5d9f22aaa848f3cd4
| 2,228 |
package com.collegiate.ui.common;
import android.content.Intent;
import android.widget.Toast;
import com.collegiate.R;
import com.collegiate.util.ResourceUtils;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
* Created by gauravarora on 27/08/15.
*/
public abstract class BaseYoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, YouTubePlayer.OnFullscreenListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
private YouTubePlayerView mYoutubePlayerView;
protected void configureYoutubePlayer(YouTubePlayerView youTubePlayerView) {
mYoutubePlayerView = youTubePlayerView;
mYoutubePlayerView.initialize(getDeveloperKey(), this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.loadVideo(getVideoUrl());
} else {
player.play();
}
player.setOnFullscreenListener(this);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
getYouTubePlayerProvider().initialize(getDeveloperKey(), this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return mYoutubePlayerView;
}
protected abstract String getVideoUrl();
protected String getDeveloperKey() {
return ResourceUtils.getString(R.string.youtube_api_key);
}
}
| 33.757576 | 154 | 0.733393 |
9db1cf2fe5730e08d302ca956fe0162e55bdc194
| 3,829 |
package org.mj.bizserver.cmdhandler.club;
import io.netty.channel.ChannelHandlerContext;
import org.mj.bizserver.allmsg.ClubServerProtocol;
import org.mj.bizserver.allmsg.InternalServerMsg;
import org.mj.bizserver.foundation.BizResultWrapper;
import org.mj.bizserver.mod.club.membercenter.MemberCenterBizLogic;
import org.mj.bizserver.mod.club.membercenter.bizdata.MemberInfo;
import org.mj.comm.cmdhandler.ICmdHandler;
import org.mj.comm.util.OutParam;
import java.util.Collections;
import java.util.List;
/**
* 获取 ( 亲友圈 ) 成员信息列表指令处理器
*/
public class GetMemberInfoListCmdHandler implements ICmdHandler<ClubServerProtocol.GetMemberInfoListCmd> {
@Override
public void handle(
ChannelHandlerContext ctx,
int remoteSessionId,
int fromUserId,
ClubServerProtocol.GetMemberInfoListCmd cmdObj) {
if (null == ctx ||
remoteSessionId <= 0 ||
fromUserId <= 0 ||
null == cmdObj) {
return;
}
final OutParam<Integer> out_totalCount = new OutParam<>();
MemberCenterBizLogic.getInstance().getMemberInfoList_async(
fromUserId,
cmdObj.getClubId(),
cmdObj.getPageIndex(),
cmdObj.getPageSize(),
out_totalCount,
(resultX) -> buildResultMsgAndSend(
ctx, remoteSessionId, fromUserId, cmdObj.getClubId(), cmdObj.getPageIndex(), out_totalCount, resultX
)
);
}
/**
* 构建结果消息并发送
*
* @param ctx 客户端信道处理器上下文
* @param remoteSessionId 远程会话 Id
* @param fromUserId 来自用户 Id
* @param clubId 亲友圈 Id
* @param pageIndex 页面索引
* @param out_totalCount 亲友圈总人数
* @param resultX 业务结果
*/
static private void buildResultMsgAndSend(
ChannelHandlerContext ctx,
int remoteSessionId,
int fromUserId,
int clubId,
int pageIndex,
OutParam<Integer> out_totalCount,
BizResultWrapper<List<MemberInfo>> resultX) {
if (null == ctx ||
null == resultX) {
return;
}
InternalServerMsg newMsg = new InternalServerMsg();
newMsg.setRemoteSessionId(remoteSessionId);
newMsg.setFromUserId(fromUserId);
if (0 != newMsg.admitError(resultX)) {
ctx.writeAndFlush(newMsg);
return;
}
// 获取亲友圈成员列表
List<MemberInfo> memberInfoList = resultX.getFinalResult();
if (null == memberInfoList) {
memberInfoList = Collections.emptyList();
}
if (null == out_totalCount.getVal()) {
out_totalCount.setVal(0);
}
ClubServerProtocol.GetMemberInfoListResult.Builder b = ClubServerProtocol.GetMemberInfoListResult.newBuilder()
.setClubId(clubId)
.setPageIndex(pageIndex)
.setTotalCount(out_totalCount.getVal());
for (MemberInfo currMember : memberInfoList) {
if (null == currMember) {
continue;
}
b.addMemberInfo(
ClubServerProtocol.GetMemberInfoListResult.MemberInfo.newBuilder()
.setUserId(currMember.getUserId())
.setUserName(currMember.getUserName())
.setHeadImg(currMember.getHeadImg())
.setSex(currMember.getSex())
.setRole(currMember.getRoleIntVal())
.setJoinTime(currMember.getJoinTime())
.setLastLoginTime(currMember.getLastLoginTime())
.setCurrState(currMember.getCurrStateIntVal())
);
}
ClubServerProtocol.GetMemberInfoListResult r = b.build();
newMsg.putProtoMsg(r);
ctx.writeAndFlush(newMsg);
}
}
| 31.908333 | 118 | 0.608514 |
3a830e816d0b838b0eb2e7a3edd4f592b992eaf3
| 2,127 |
package com.tinkerpop.gremlin.process.graph.step.filter;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.graph.marker.Reversible;
import com.tinkerpop.gremlin.process.traverser.TraverserRequirement;
import com.tinkerpop.gremlin.process.util.TraversalHelper;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public final class RetainStep<S> extends FilterStep<S> implements Reversible {
private final String collectionSideEffectKey;
public RetainStep(final Traversal traversal, final String collectionSideEffectKey) {
super(traversal);
this.collectionSideEffectKey = collectionSideEffectKey;
this.setPredicate(traverser -> {
final Object retain = traverser.asAdmin().getSideEffects().exists(this.collectionSideEffectKey) ? traverser.sideEffects(this.collectionSideEffectKey) : traverser.path(this.collectionSideEffectKey);
return retain instanceof Collection ?
((Collection) retain).contains(traverser.get()) :
retain.equals(traverser.get());
});
}
public RetainStep(final Traversal traversal, final Collection<S> retainCollection) {
super(traversal);
this.collectionSideEffectKey = null;
this.setPredicate(traverser -> retainCollection.contains(traverser.get()));
}
public RetainStep(final Traversal traversal, final S retainObject) {
super(traversal);
this.collectionSideEffectKey = null;
this.setPredicate(traverser -> retainObject.equals(traverser.get()));
}
public String toString() {
return TraversalHelper.makeStepString(this, this.collectionSideEffectKey);
}
@Override
public Set<TraverserRequirement> getRequirements() {
return this.getTraversal().asAdmin().getSideEffects().exists(this.collectionSideEffectKey) ?
Collections.singleton(TraverserRequirement.SIDE_EFFECTS) :
Collections.singleton(TraverserRequirement.PATH_ACCESS);
}
}
| 39.388889 | 209 | 0.724024 |
9c27af1c73ea7afc0b521a35a8aba3e730262ca8
| 1,294 |
package com.yueyue.readhub.common.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import java.io.File;
/**
* author : yueyue on 2018/4/3 10:12
* desc :
*/
public class AppUtil {
private AppUtil() {
}
public static File getDiskCacheDir(Context context, String uniqueName) {
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
cachePath = context.getExternalCacheDir().getPath();
} else {
cachePath = context.getCacheDir().getPath();
}
return new File(cachePath + File.separator + uniqueName);
}
/**
* 只关注是否联网
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
}
| 28.130435 | 97 | 0.640649 |
5577ac2528759ff83b54caeedbc6cb9412558d63
| 303 |
package com.zan.tasks.service;
import java.util.List;
import com.zan.tasks.model.Board;
import com.zan.tasks.model.User;
public interface BoardService {
public void addBoard(Board board, User user);
public Board getBoard(Long id);
public List<Board> getBoards(User user);
}
| 17.823529 | 47 | 0.712871 |
b509dd1f6f5202486d965ae723d9250a3725af85
| 493 |
package com.careberos.Response;
import java.util.ArrayList;
import com.careberos.Model.Ticket;
public class TicketsResponse {
private int code;
private ArrayList<Ticket> tickets = new ArrayList<>();
public TicketsResponse() {
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public ArrayList<Ticket> getTickets() {
return tickets;
}
public void setTickets(ArrayList<Ticket> tickets) {
this.tickets = tickets;
}
}
| 14.5 | 55 | 0.703854 |
635b29fc54972ef3c2665062c0da0cc37b1d63db
| 2,709 |
package org.ovirt.engine.core.bll.network.vm;
import java.util.List;
import javax.inject.Inject;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.validator.VmNicFilterParameterValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.VmNicFilterParameterParameters;
import org.ovirt.engine.core.common.businessentities.network.VmNicFilterParameter;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.validation.group.UpdateEntity;
import org.ovirt.engine.core.dao.network.VmNicFilterParameterDao;
public class UpdateVmNicFilterParameterCommand<T extends VmNicFilterParameterParameters>
extends AbstractVmNicFilterParameterCommand<T> {
@Inject
private VmNicFilterParameterDao vmNicFilterParameterDao;
@Inject
private VmNicFilterParameterValidator validator;
public UpdateVmNicFilterParameterCommand(T parameters, CommandContext cmdContext) {
super(parameters, cmdContext);
}
@Override
protected void executeVmCommand() {
super.executeVmCommand();
vmNicFilterParameterDao.update(getParameters().getFilterParameter());
setSucceeded(true);
}
@Override
protected boolean validate() {
VmNicFilterParameter filterParameter = getParameters().getFilterParameter();
return super.validate()
&& validate(validator.parameterHavingIdExists(filterParameter.getId()))
&& validate(validator.vmInterfaceHavingIdExists(filterParameter.getVmInterfaceId()))
&& validate(validator.vmInterfaceHavingIdExistsOnVmHavingId(
filterParameter.getVmInterfaceId(), getVmId()));
}
@Override
protected List<Class<?>> getValidationGroups() {
addValidationGroup(UpdateEntity.class);
return super.getValidationGroups();
}
@Override
public AuditLogType getAuditLogTypeValue() {
addCustomValue("VmNicFilterParameterName", getParameters().getFilterParameter().getName());
addCustomValue("VmNicFilterParameterId", getParameters().getFilterParameter().getId().toString());
addCustomValue("VmInterfaceId", getParameters().getFilterParameter().getVmInterfaceId().toString());
addCustomValue("VmName", getVm().getName());
return getSucceeded() ? AuditLogType.NETWORK_UPDATE_NIC_FILTER_PARAMETER
: AuditLogType.NETWORK_UPDATE_NIC_FILTER_PARAMETER_FAILED;
}
@Override
protected void setActionMessageParameters() {
addValidationMessage(EngineMessage.VAR__ACTION__UPDATE);
super.setActionMessageParameters();
}
}
| 38.7 | 108 | 0.745663 |
fd3e9222ff06acfc51ccf796b096a44512dd3412
| 6,767 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing.querygraph;
import com.graphhopper.routing.ev.BooleanEncodedValue;
import com.graphhopper.routing.ev.DecimalEncodedValue;
import com.graphhopper.routing.ev.EnumEncodedValue;
import com.graphhopper.routing.ev.IntEncodedValue;
import com.graphhopper.routing.util.EdgeFilter;
import com.graphhopper.storage.IntsRef;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.FetchMode;
import com.graphhopper.util.PointList;
import java.util.List;
/**
* @author Peter Karich
*/
class VirtualEdgeIterator implements EdgeIterator {
private final EdgeFilter edgeFilter;
private List<EdgeIteratorState> edges;
private int current;
private transient EdgeIteratorState currentEdge = null;
VirtualEdgeIterator(EdgeFilter edgeFilter, List<EdgeIteratorState> edges) {
this.edgeFilter = edgeFilter;
reset(edges);
}
EdgeIterator reset(List<EdgeIteratorState> edges) {
this.edges = edges;
current = -1;
this.currentEdge = null;
return this;
}
@Override
public boolean next() {
final int s = edges.size();
do {
if (++current >= s) {
currentEdge = null;
return false;
}
} while (!edgeFilter.accept(currentEdge = edges.get(current)));
return true;
}
@Override
public EdgeIteratorState detach(boolean reverse) {
if (reverse)
throw new IllegalStateException("Not yet supported");
return currentEdge;
}
@Override
public int getEdge() {
return currentEdge.getEdge();
}
@Override
public int getEdgeKey() {
return currentEdge.getEdgeKey();
}
@Override
public int getBaseNode() {
return currentEdge.getBaseNode();
}
@Override
public int getAdjNode() {
return currentEdge.getAdjNode();
}
@Override
public PointList fetchWayGeometry(FetchMode mode) {
return currentEdge.fetchWayGeometry(mode);
}
@Override
public EdgeIteratorState setWayGeometry(PointList list) {
return currentEdge.setWayGeometry(list);
}
@Override
public double getDistance() {
return currentEdge.getDistance();
}
@Override
public EdgeIteratorState setDistance(double dist) {
return currentEdge.setDistance(dist);
}
@Override
public IntsRef getFlags() {
return currentEdge.getFlags();
}
@Override
public EdgeIteratorState setFlags(IntsRef flags) {
return currentEdge.setFlags(flags);
}
@Override
public EdgeIteratorState set(BooleanEncodedValue property, boolean value) {
currentEdge.set(property, value);
return this;
}
@Override
public boolean get(BooleanEncodedValue property) {
return currentEdge.get(property);
}
@Override
public EdgeIteratorState setReverse(BooleanEncodedValue property, boolean value) {
currentEdge.setReverse(property, value);
return this;
}
@Override
public boolean getReverse(BooleanEncodedValue property) {
return currentEdge.getReverse(property);
}
@Override
public EdgeIteratorState set(IntEncodedValue property, int value) {
currentEdge.set(property, value);
return this;
}
@Override
public int get(IntEncodedValue property) {
return currentEdge.get(property);
}
@Override
public EdgeIteratorState setReverse(IntEncodedValue property, int value) {
currentEdge.setReverse(property, value);
return this;
}
@Override
public int getReverse(IntEncodedValue property) {
return currentEdge.getReverse(property);
}
@Override
public EdgeIteratorState set(DecimalEncodedValue property, double value) {
currentEdge.set(property, value);
return this;
}
@Override
public double get(DecimalEncodedValue property) {
return currentEdge.get(property);
}
@Override
public EdgeIteratorState setReverse(DecimalEncodedValue property, double value) {
currentEdge.setReverse(property, value);
return this;
}
@Override
public double getReverse(DecimalEncodedValue property) {
return currentEdge.getReverse(property);
}
@Override
public <T extends Enum> EdgeIteratorState set(EnumEncodedValue<T> property, T value) {
currentEdge.set(property, value);
return this;
}
@Override
public <T extends Enum> T get(EnumEncodedValue<T> property) {
return currentEdge.get(property);
}
@Override
public <T extends Enum> EdgeIteratorState setReverse(EnumEncodedValue<T> property, T value) {
currentEdge.setReverse(property, value);
return this;
}
@Override
public <T extends Enum> T getReverse(EnumEncodedValue<T> property) {
return currentEdge.getReverse(property);
}
@Override
public String getName() {
return currentEdge.getName();
}
@Override
public EdgeIteratorState setName(String name) {
return currentEdge.setName(name);
}
@Override
public String toString() {
if (current >= 0 && current < edges.size()) {
return "virtual edge: " + currentEdge + ", all: " + edges.toString();
} else {
return "virtual edge: (invalid)" + ", all: " + edges.toString();
}
}
@Override
public EdgeIteratorState copyPropertiesFrom(EdgeIteratorState edge) {
return currentEdge.copyPropertiesFrom(edge);
}
@Override
public int getOrigEdgeFirst() {
return currentEdge.getOrigEdgeFirst();
}
@Override
public int getOrigEdgeLast() {
return currentEdge.getOrigEdgeLast();
}
public List<EdgeIteratorState> getEdges() {
return edges;
}
}
| 27.176707 | 97 | 0.670164 |
e7d81c259a60a5172b576501f2aca82a8a6e6547
| 538 |
package org.camunda.bpm.extension.mockito.query;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import javax.annotation.Generated;
@Generated(value="org.camunda.bpm.extension.mockito.generator.processor.GenerateQueryMocksProcessor", date="Tue Nov 08 16:00:04 CET 2016")
public class TaskQueryMock extends AbstractQueryMock<TaskQueryMock, TaskQuery, Task, TaskService> {
public TaskQueryMock() {
super(TaskQuery.class, TaskService.class);
}
}
| 33.625 | 138 | 0.799257 |
a31ba6f63c78320693e4b4bc9a0254be19e33a09
| 6,264 |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
import frc.robot.subsystems.DriveSubsystem;
import frc.robot.subsystems.IntakeSubsystem;
import frc.robot.subsystems.PneumaticsSubsystem;
import frc.robot.subsystems.SparkMaxClimberSubsystem;
//import frc.robot.subsystems.ColorSensor;
import frc.robot.subsystems.LauncherSubsystem;
import frc.robot.subsystems.FeederSubsystem;
//import frc.robot.commands.AutoDriveCommand;
import frc.robot.commands.DriveCommand;
import frc.robot.subsystems.IndexerSubsystem;
// import frc.robot.commands.auto.AutoDriveCommand;
// import frc.robot.commands.auto.AutoLaunchCommand;
import frc.robot.commands.auto.FinalAutoSequence;
//import frc.robot.commands.auto.auto_command_groups.sequence2.SecondAuto;
//import frc.robot.commands.launcher_commands.LauncherCommandGroup;
import frc.robot.commands.auto.auto_command_groups.sequence2.ToggleSolIntakeDriveParallelDeadline;
import frc.robot.commands.auto.base_auto_commands.DriveDistanceCommand;
import edu.wpi.first.cameraserver.CameraServer;
import edu.wpi.first.cscore.UsbCamera;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.CommandScheduler;
import frc.robot.commands.auto.base_auto_commands.SetEncoderTo0;
/**
* The VM is configured to automatically run this class, and to call the functions corresponding to
* each mode, as described in the TimedRobot documentation. If you change the name of this class or
* the package after creating this project, you must also update the build.gradle file in the
* project.
*/
public class Robot extends TimedRobot {
private static final String kDefaultAuto = "Default";
private static final String kCustomAuto = "My Auto";
private String m_autoSelected;
private final SendableChooser<String> m_chooser = new SendableChooser<>();
// Initializing subsystems:
public static DriveSubsystem DriveSubsystem = new DriveSubsystem();
public static IndexerSubsystem IndexerSubsystem = new IndexerSubsystem(); //added by will
public static IntakeSubsystem IntakeSubsystem = new IntakeSubsystem();
//public static ColorSensor ColorSensor = null;
public static LauncherSubsystem LauncherSubsystem = new LauncherSubsystem();
public static FeederSubsystem FeederSubsystem = new FeederSubsystem();
public static PneumaticsSubsystem PneumaticsSubsystem = null; // pneumatics is implemented in intake
public static SparkMaxClimberSubsystem SparkMaxClimberSubsystem = new SparkMaxClimberSubsystem();
// Initializing OI object
public static OI OI = new OI();
// Initializing commands
DriveCommand DriveCommand = new DriveCommand();
CommandScheduler commandScheduler = CommandScheduler.getInstance();
// UsbCamera camera1;
// UsbCamera camera2;
// NetworkTableEntry cameraSelection;
//IntakeCommand IntakeCommand = new IntakeCommand();
/**
* This function is run when the robot is first started up and should be used for any
* initialization code.
*/
@Override
public void robotInit() {
m_chooser.setDefaultOption("Default Auto", kDefaultAuto);
m_chooser.addOption("My Auto", kCustomAuto);
SmartDashboard.putData("Auto choices", m_chooser);
CameraServer.startAutomaticCapture();
}
/**
* This function is called every robot packet, no matter the mode. Use this for items like
* diagnostics that you want ran during disabled, autonomous, teleoperated and test.
*
* <p>This runs after the mode specific periodic functions, but before LiveWindow and
* SmartDashboard integrated updating.
*/
@Override
public void robotPeriodic() {}
/**
* This autonomous (along with the chooser code above) shows how to select between different
* autonomous modes using the dashboard. The sendable chooser code works with the Java
* SmartDashboard. If you prefer the LabVIEW Dashboard, remove all of the chooser code and
* uncomment the getString line to get the auto name from the text box below the Gyro
*
* <p>You can add additional auto modes by adding additional comparisons to the switch structure
* below with additional strings. If using the SendableChooser make sure to add them to the
* chooser code above as well.
*/
@Override
public void autonomousInit() {
m_autoSelected = m_chooser.getSelected();
// m_autoSelected = SmartDashboard.getString("Auto Selector", kDefaultAuto);
System.out.println("Auto selected: " + m_autoSelected);
switch (m_autoSelected) {
case kCustomAuto:
commandScheduler.schedule(new FinalAutoSequence());
break;
case kDefaultAuto:
default:
//DriveSubsystem.printEncoder();
commandScheduler.schedule(new FinalAutoSequence());
//commandScheduler.schedule(new SecondAuto());
// commandScheduler.schedule(new SetEncoderTo0());
// commandScheduler.schedule(new DriveDistanceCommand(-0.25, 100));
break;
}
}
/** This function is called periodically during autonomous. */
@Override
public void autonomousPeriodic() {
commandScheduler.run();//keepsrunning
}
/** This function is called once when teleop is enabled. */
@Override
public void teleopInit() {}
/** This function is called periodically during operator control. */
@Override
public void teleopPeriodic() {
// Start the CommandScheduler to schedule commands for each cycle
commandScheduler.run();
DriveCommand.schedule();
}
/** This function is called once when the robot is disabled. */
@Override
public void disabledInit() {}
/** This function is called periodically when disabled. */
@Override
public void disabledPeriodic() {}
/** This function is called once when test mode is enabled. */
@Override
public void testInit() {}
/** This function is called periodically during test mode. */
@Override
public void testPeriodic() {}
}
| 40.675325 | 102 | 0.762612 |
b2993b10a84d92349a30a763fb793917d788438c
| 2,864 |
/*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* 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 the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vlet.grid.voms;
import java.util.Hashtable;
import java.util.Map;
/**
* ---
* Gidon Moont
* Imperial College London
* Copyright (C) 2006
* ---
* This class will be able to translate the following OIDs
*
* - Certificate Distinguised Name parts...
*
* Country.
* Attribute name C
* OID 2.5.4.6
*
* Location.
* Attribute name L
* OID 2.5.4.7
*
* Common name.
* Attribute name CN
* OID 2.5.4.3
*
* Organization.
* Attribute name O
* OID 2.5.4.10
*
* Organizational Unit.
* Attribute name OU
* OID 2.5.6.5
*
* Email address
* Attribute name E
* OID 1.2.840.113549.1.9.1
*/
public class Translate_OID
{
private static Map<String,String> oid2string=null;
private static Map<String,String> string2oid=null;
static
{
oid2string=new Hashtable<String,String>();
string2oid=new Hashtable<String,String>();
// Oid -> String
oid2string.put("2.5.4.3", "CN");
oid2string.put("2.5.4.6", "C");
oid2string.put("2.5.4.7", "L");
oid2string.put("2.5.4.10", "O");
oid2string.put("2.5.4.11", "OU");
oid2string.put("1.2.840.113549.1.9.1", "E");
oid2string.put("1.2.840.113549.1.1.4", "MD5 with RSA encryption");
// String -> OID
string2oid.put("CN", "2.5.4.3");
string2oid.put("C", "2.5.4.6");
string2oid.put("L", "2.5.4.7");
string2oid.put("O", "2.5.4.10");
string2oid.put("OU", "2.5.4.11");
string2oid.put("E", "1.2.840.113549.1.9.1");
}
public static String getStringFromOID(String oid)
{
if (oid2string.containsKey(oid))
{
return oid2string.get(oid);
}
else
{
return new String("" + oid);
}
}
public static String getOIDFromString(String string)
{
if (string2oid.containsKey(string))
{
return string2oid.get(string);
}
else
{
return new String("" + string);
}
}
}
| 24.271186 | 92 | 0.607542 |
087e369e19b60f96d5da405f87373c5fd4fbbb25
| 7,640 |
package com.codeborne.selenide;
import com.codeborne.selenide.impl.ThreadLocalSelenideDriver;
import com.codeborne.selenide.impl.WebDriverContainer;
import com.codeborne.selenide.impl.WebDriverThreadLocalContainer;
import com.codeborne.selenide.proxy.SelenideProxyServer;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.WebDriverEventListener;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import static com.codeborne.selenide.Configuration.browser;
import static com.codeborne.selenide.Configuration.headless;
/**
* A static facade for accessing WebDriver instance for current threads
*/
@ParametersAreNonnullByDefault
public class WebDriverRunner implements Browsers {
public static WebDriverContainer webdriverContainer = new WebDriverThreadLocalContainer();
private static final SelenideDriver staticSelenideDriver = new ThreadLocalSelenideDriver();
/**
* Use this method BEFORE opening a browser to add custom event listeners to webdriver.
*
* @param listener your listener of webdriver events
*/
public static void addListener(WebDriverEventListener listener) {
webdriverContainer.addListener(listener);
}
/**
* Tell Selenide use your provided WebDriver instance.
* Use it if you need a custom logic for creating WebDriver.
* <p>
* It's recommended not to use implicit wait with this driver, because Selenide handles timing issues explicitly.
*
* <br>
* <p>
* NB! Be sure to call this method before calling <code>open(url)</code>.
* Otherwise Selenide will create its own WebDriver instance and would not close it.
*
* <p>
* NB! When using your custom webdriver, you are responsible for closing it.
* Selenide will not take care of it.
* </p>
*
* <p>
* NB! Webdriver instance should be created and used in the same thread.
* A typical error is to create webdriver instance in one thread and use it in another.
* Selenide does not support it.
* If you really need using multiple threads, please use #com.codeborne.selenide.WebDriverProvider
* </p>
*
* <p>
* P.S. Alternatively, you can run tests with system property
* <pre> -Dbrowser=com.my.WebDriverFactory</pre>
* <p>
* which should implement interface #com.codeborne.selenide.WebDriverProvider
* </p>
*/
public static void setWebDriver(WebDriver webDriver) {
webdriverContainer.setWebDriver(webDriver);
}
public static void setWebDriver(WebDriver webDriver, @Nullable SelenideProxyServer selenideProxy) {
webdriverContainer.setWebDriver(webDriver, selenideProxy);
}
public static void setWebDriver(WebDriver webDriver,
@Nullable SelenideProxyServer selenideProxy,
DownloadsFolder browserDownloadsFolder) {
webdriverContainer.setWebDriver(webDriver, selenideProxy, browserDownloadsFolder);
}
/**
* Get the underlying instance of Selenium WebDriver.
* This can be used for any operations directly with WebDriver.
*/
@CheckReturnValue
@Nonnull
public static WebDriver getWebDriver() {
return webdriverContainer.getWebDriver();
}
/**
* Sets Selenium Proxy instance
*/
public static void setProxy(Proxy webProxy) {
webdriverContainer.setProxy(webProxy);
}
/**
* Get the underlying instance of Selenium WebDriver, and assert that it's still alive.
*
* @return new instance of WebDriver if the previous one has been closed meanwhile.
*/
@CheckReturnValue
@Nonnull
public static WebDriver getAndCheckWebDriver() {
return webdriverContainer.getAndCheckWebDriver();
}
/**
* Get selenide proxy. It's activated only if Configuration.proxyEnabled == true
*
* @return null if proxy server is not started
*/
@CheckReturnValue
@Nullable
public static SelenideProxyServer getSelenideProxy() {
return webdriverContainer.getProxyServer();
}
@CheckReturnValue
@Nonnull
static SelenideDriver getSelenideDriver() {
return staticSelenideDriver;
}
@CheckReturnValue
@Nonnull
public static Driver driver() {
return getSelenideDriver().driver();
}
@CheckReturnValue
@Nonnull
public static DownloadsFolder getBrowserDownloadsFolder() {
return webdriverContainer.getBrowserDownloadsFolder();
}
/**
* Close the current window, quitting the browser if it's the last window currently open.
*
* @see WebDriver#close()
*/
public static void closeWindow() {
webdriverContainer.closeWindow();
}
/**
* <p>Close the browser if it's open.</p>
* <br>
* <p>NB! Method quits this driver, closing every associated window.</p>
*
* @see WebDriver#quit()
*/
public static void closeWebDriver() {
webdriverContainer.closeWebDriver();
}
/**
* @return true if instance of Selenium WebDriver is started in current thread
*/
@CheckReturnValue
public static boolean hasWebDriverStarted() {
return webdriverContainer.hasWebDriverStarted();
}
public static void using(WebDriver driver, Runnable lambda) {
if (hasWebDriverStarted()) {
WebDriver previous = getWebDriver();
try {
lambda.run();
}
finally {
setWebDriver(previous);
}
}
else {
setWebDriver(driver);
try {
lambda.run();
}
finally {
webdriverContainer.resetWebDriver();
}
}
}
@CheckReturnValue
@Nonnull
private static Browser browser() {
return new Browser(browser, headless);
}
/**
* Is Selenide configured to use Firefox browser
*/
@CheckReturnValue
public static boolean isFirefox() {
return browser().isFirefox();
}
/**
* Is Selenide configured to use legacy Firefox driver
*/
@CheckReturnValue
public static boolean isLegacyFirefox() {
return browser().isLegacyFirefox();
}
/**
* Is Selenide configured to use Chrome browser
*/
@CheckReturnValue
public static boolean isChrome() {
return browser().isChrome();
}
/**
* Is Selenide configured to use Internet Explorer browser
*/
@CheckReturnValue
public static boolean isIE() {
return browser().isIE();
}
/**
* Is Selenide configured to use Microsoft EDGE browser
*/
@CheckReturnValue
public static boolean isEdge() {
return browser().isEdge();
}
/**
* Is Selenide configured to use headless browser
*/
@CheckReturnValue
public static boolean isHeadless() {
return browser().isHeadless();
}
/**
* Does this browser support javascript
*/
@CheckReturnValue
public static boolean supportsJavascript() {
return driver().supportsJavascript();
}
/**
* Is Selenide configured to use Opera browser
*/
@CheckReturnValue
public static boolean isOpera() {
return browser().isOpera();
}
/**
* Delete all the browser cookies
*/
public static void clearBrowserCache() {
webdriverContainer.clearBrowserCache();
}
/**
* @return the source (HTML) of current page
*/
@CheckReturnValue
@Nonnull
public static String source() {
return webdriverContainer.getPageSource();
}
/**
* @return the URL of current page
*/
@CheckReturnValue
@Nonnull
public static String url() {
return webdriverContainer.getCurrentUrl();
}
/**
* @return the URL of current frame
*/
@CheckReturnValue
@Nonnull
public static String currentFrameUrl() {
return webdriverContainer.getCurrentFrameUrl();
}
}
| 26.344828 | 115 | 0.703141 |
559f6c77f1cdbc5712985c012db8374e5bbca3d1
| 4,883 |
import akka.stream.javadsl.Source;
import models.Pet;
import org.junit.*;
import play.libs.Json;
import play.libs.ws.WSClient;
import play.libs.ws.WSResponse;
import play.mvc.*;
import play.test.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import static play.test.Helpers.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.fluentlenium.core.filter.FilterConstructor.*;
public class IntegrationTest {
/**
* add your integration test here
* in this example we just check if the welcome page is being shown
*/
@Test
public void test() {
running(testServer(3333), HTMLUNIT, browser -> {
browser.goTo("http://localhost:3333");
assertThat(browser.pageSource(), containsString("Hello. Welcome to my pet shop!"));
});
}
@Test
public void testHomeServer() throws Exception {
TestServer server = testServer(3333);
running(server, () -> {
try {
WSClient ws = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage = ws.url("/").get();
WSResponse response = completionStage.toCompletableFuture().get();
ws.close();
assertEquals(OK, response.getStatus());
} catch (Exception e) {
System.out.println(e.getMessage());
}
});
}
@Test
public void testListPets() throws Exception {
TestServer server = testServer(3333);
running(server, () -> {
try {
WSClient ws = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage = ws.url("/list_pets").get();
WSResponse response = completionStage.toCompletableFuture().get();
ws.close();
assertEquals(OK, response.getStatus());
} catch (Exception e) {
System.out.println(e.getMessage());
}
});
}
@Test
public void testAddAndDeletePet() throws Exception {
TestServer server = testServer(3333);
running(server, () -> {
try {
WSClient ws = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage = ws.url("/add")
.setQueryParameter("name","test_pet")
.setQueryParameter("age","2")
.setQueryParameter("sex","male")
.put("");
WSResponse response = completionStage.toCompletableFuture().get();
ws.close();
assertEquals(CREATED, response.getStatus());
WSClient ws2 = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage2 = ws2.url("/delete/test_pet").delete();
WSResponse response2 = completionStage2.toCompletableFuture().get();
ws2.close();
assertEquals(OK, response2.getStatus());
} catch (Exception e) {
System.out.println(e.getMessage());
}
});
}
@Test
public void testAddUpdateAndDeletePet() throws Exception {
TestServer server = testServer(3333);
running(server, () -> {
try {
Map<String, String[]> data = new HashMap<>();
WSClient ws = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage = ws.url("/add")
.setQueryParameter("name","test_pet")
.setQueryParameter("age","2")
.setQueryParameter("sex","male")
.put("");
WSResponse response = completionStage.toCompletableFuture().get();
ws.close();
assertEquals(CREATED, response.getStatus());
WSClient ws2 = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage2 = ws2.url("/update")
.setContentType("application/x-www-form-urlencoded")
.post("name=test_pet&age=4&sex=male");
WSResponse response2 = completionStage2.toCompletableFuture().get();
ws2.close();
assertEquals(OK, response2.getStatus());
WSClient ws3 = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage3 = ws3.url("/delete/test_pet").delete();
WSResponse response3 = completionStage3.toCompletableFuture().get();
ws3.close();
assertEquals(OK, response3.getStatus());
} catch (Exception e) {
System.out.println(e.getMessage());
}
});
}
}
| 37.852713 | 100 | 0.557444 |
f7c4030d997294556acd77d5e3a66a0b3ec2d87e
| 186 |
package com.multi.thread.guide.design.pattern.chapter4;
/**
* @author dongzonglei
* @description
* @date 2019-02-16 11:14
*/
public interface Predicate {
boolean evaluate();
}
| 15.5 | 55 | 0.698925 |
100d7aa08ee0beb81214d56af7bb0afdba7d8a58
| 303 |
package softuni._02usersystem.services;
import softuni._02usersystem.models.entity.Country;
/**
* Created by IntelliJ IDEA.
* User: LAPD
* Date: 1.4.2018 г.
* Time: 12:59 ч.
*/
public interface CountryService {
Country getCountryById(Long id);
void registerCountry(Country country);
}
| 16.833333 | 51 | 0.719472 |
4bd8c872d4aaba3fd59ae40feab5f129878a4b7f
| 6,827 |
package uk.gov.hmcts.reform.divorce.orchestration.controller.ccdcase;
import com.github.tomakehurst.wiremock.matching.EqualToPattern;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator;
import uk.gov.hmcts.reform.ccd.client.CoreCaseDataApi;
import uk.gov.hmcts.reform.ccd.client.model.CaseDataContent;
import uk.gov.hmcts.reform.ccd.client.model.CaseDetails;
import uk.gov.hmcts.reform.ccd.client.model.Event;
import uk.gov.hmcts.reform.ccd.client.model.StartEventResponse;
import uk.gov.hmcts.reform.divorce.model.usersession.DivorceSession;
import uk.gov.hmcts.reform.divorce.orchestration.controller.MockedFunctionalTest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static org.mockito.Mockito.when;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.gov.hmcts.reform.divorce.orchestration.TestConstants.AUTH_TOKEN;
import static uk.gov.hmcts.reform.divorce.orchestration.TestConstants.BEARER_AUTH_TOKEN;
import static uk.gov.hmcts.reform.divorce.orchestration.TestConstants.TEST_EVENT_ID;
import static uk.gov.hmcts.reform.divorce.orchestration.TestConstants.TEST_SERVICE_TOKEN;
import static uk.gov.hmcts.reform.divorce.orchestration.TestConstants.TEST_TOKEN;
import static uk.gov.hmcts.reform.divorce.orchestration.TestConstants.TEST_USER_EMAIL;
import static uk.gov.hmcts.reform.divorce.orchestration.testutil.DataTransformationTestHelper.getTestDivorceSessionData;
import static uk.gov.hmcts.reform.divorce.orchestration.testutil.ObjectMapperTestUtil.convertObjectToJsonString;
public class PatchCaseTest extends MockedFunctionalTest {
private static final String IDAM_USER_DETAILS_CONTEXT_PATH = "/details";
private static final String PATCH_PATH = "/case";
private static final String USER_ID = "1";
private static final String CITIZEN_ROLE = "citizen";
private static final String CASE_ID = "123456789";
private static final String DIVORCE_CASE_PATCH_EVENT_SUMMARY = "Divorce case patch event";
private static final String DIVORCE_CASE_PATCH_EVENT_DESCRIPTION = "Patching Divorce Case";
private DivorceSession divorceSession;
@Value("${ccd.jurisdictionid}")
private String jurisdictionId;
@Value("${ccd.casetype}")
private String caseType;
@Value("${ccd.eventid.patch}")
private String patchEventId;
@Autowired
private MockMvc webClient;
@MockBean
private CoreCaseDataApi coreCaseDataApi;
@MockBean
private AuthTokenGenerator authTokenGenerator;
@Before
public void setUp() throws IOException {
divorceSession = getTestDivorceSessionData();
}
@Test
public void shouldPatchCase() throws Exception {
final Map<String, Object> caseData = new HashMap<>();
final String caseDataWithIdJson = "{\"id\": \"123456789\", \"data\": {}}";
final String userDetails = getUserDetailsForRole();
final CaseDetails caseDetails = CaseDetails.builder().build();
final StartEventResponse startEventResponse = createStartEventResponse();
final CaseDataContent caseDataContent = createCaseDataContent(caseData, startEventResponse);
stubUserDetailsEndpoint(userDetails);
when(authTokenGenerator.generate()).thenReturn(TEST_SERVICE_TOKEN);
when(coreCaseDataApi
.startEventForCitizen(
BEARER_AUTH_TOKEN,
TEST_SERVICE_TOKEN,
USER_ID,
jurisdictionId,
caseType,
CASE_ID,
patchEventId))
.thenReturn(startEventResponse);
when(coreCaseDataApi
.submitEventForCitizen(
BEARER_AUTH_TOKEN,
TEST_SERVICE_TOKEN,
USER_ID,
jurisdictionId,
caseType,
CASE_ID,
true,
caseDataContent))
.thenReturn(caseDetails);
webClient.perform(patch(PATCH_PATH)
.content(caseDataWithIdJson)
.header(AUTHORIZATION, AUTH_TOKEN)
.contentType(APPLICATION_JSON)
.accept(APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void shouldReturnBadRequestIfNoAuthenticationToken() throws Exception {
webClient.perform(patch(PATCH_PATH)
.content(convertObjectToJsonString(divorceSession))
.contentType(APPLICATION_JSON)
.accept(APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
private String getUserDetailsForRole() {
return "{\"id\":\"" + USER_ID
+ "\",\"email\":\"" + TEST_USER_EMAIL
+ "\",\"forename\":\"forename\",\"surname\":\"Surname\",\"roles\":[\"" + CITIZEN_ROLE + "\"]}";
}
private StartEventResponse createStartEventResponse() {
return StartEventResponse.builder()
.eventId(TEST_EVENT_ID)
.token(TEST_TOKEN)
.build();
}
private void stubUserDetailsEndpoint(final String message) {
idamServer.stubFor(get(IDAM_USER_DETAILS_CONTEXT_PATH)
.withHeader(AUTHORIZATION, new EqualToPattern(BEARER_AUTH_TOKEN))
.willReturn(aResponse()
.withStatus(OK.value())
.withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.withBody(message)));
}
private CaseDataContent createCaseDataContent(final Map<String, Object> caseData, final StartEventResponse startEventResponse) {
return CaseDataContent.builder()
.eventToken(startEventResponse.getToken())
.event(
Event.builder()
.id(startEventResponse.getEventId())
.summary(DIVORCE_CASE_PATCH_EVENT_SUMMARY)
.description(DIVORCE_CASE_PATCH_EVENT_DESCRIPTION)
.build()
).data(caseData)
.build();
}
}
| 40.88024 | 132 | 0.711 |
31cea5205f6fe542c87f3e96f0aa72eb491ec4ac
| 918 |
package edu.gemini.shared.util.immutable;
/**
* An association of three objects of type <code>T</code>, <code>U</code> and <code>V</code>.
*/
public interface Tuple3<T, U, V> {
/**
* The first (or left) object in the tuple.
*/
T _1();
/**
* The second (or middle) object in the tuple.
*/
U _2();
/**
* The second (or right) object in the tuple.
*/
V _3();
/**
* Creates a string representation of this tuple that is formed as in
* <pre>
* prefix + _1().toString() + sep + _2().toString() + sep + _3().toString() + suffix
* </pre>
*
* @param prefix string to prepend to the result
* @param sep separator string to place between two elements
* @param suffix string to append to the result
* @return string representation of the tuple
*/
String mkString(String prefix, String sep, String suffix);
}
| 26.228571 | 94 | 0.587146 |
ab745a0f4df3cb0acbd14fed4c58ce78f53ec250
| 1,152 |
package com.test.basic.chapter7;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by beigui on 2016/3/26.
* 功能:文件内容的写入 -- FileOutputStream
* 写入“Java 学习”到文件 d:/test/work.txt中
*/
public class FileWriteStreamDemo {
public static void main(String[] args) {
File file = new File("d:/test/", "work.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream out = null;
byte[] content = "Java 学习".getBytes();
try {
out = new FileOutputStream(file);
out.write(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| 26.181818 | 53 | 0.503472 |
acf5cb7a6db1421a746f848d69302c9d83cc8ef7
| 484 |
package com.exam.record;
import org.springblade.common.constant.CommonConstant;
import org.springblade.core.launch.BladeApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringCloudApplication
@EnableFeignClients(CommonConstant.BASE_PACKAGES)
public class RecordApplication {
public static void main(String[] args) {
BladeApplication.run("exam-record",RecordApplication.class,args);
}
}
| 32.266667 | 67 | 0.840909 |
b4c873a14d15db1044d3be0286e0dedb182d1311
| 1,037 |
package agh.cs.lab8;
import javax.imageio.IIOException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class ConstitutionReader {
public static void main(String[] args) {
if(args.length < 2){
System.out.println("Bład: Minimalna ilosc argumentów to 2");
}
else
{
Constitution constitution;
try {
constitution = ConstitutionParser.parseConstitution(args[0]);
List<Option> options=OptionParser.parseOptions(Arrays.copyOfRange(args,1,args.length));
for (Option option: options)
{
System.out.println(constitution.toString(option));
}
}
catch(IOException ex){
System.out.println("Bład odczytu pliku : " + ex.getMessage());
}
catch(IllegalArgumentException ex){
System.out.println("Bład argumentu : " + ex.getMessage());
}
}
}
}
| 30.5 | 103 | 0.559306 |
14237a1934edd3b56ed1631285f07215f7e22ba9
| 2,297 |
package com.dmd.weixin.app.media;
import com.dmd.weixin.app.AppWxClientFactory;
import com.dmd.weixin.app.base.AppSetting;
import com.dmd.weixin.app.base.WxEndpoint;
import com.dmd.weixin.common.WxClient;
import com.dmd.weixin.common.exception.WxRuntimeException;
import com.dmd.weixin.common.media.Media;
import com.dmd.weixin.common.media.MediaType;
import com.dmd.weixin.common.util.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.util.Map;
/**
* 临时素材管理
* @borball on 12/29/2016.
*/
public class Medias {
private static Logger logger = LoggerFactory.getLogger(Medias.class);
private WxClient wxClient;
public static Medias defaultMedias() {
return with(AppSetting.defaultSettings());
}
public static Medias with(AppSetting appSetting) {
Medias medias = new Medias();
medias.setWxClient(AppWxClientFactory.getInstance().with(appSetting));
return medias;
}
public void setWxClient(WxClient wxClient) {
this.wxClient = wxClient;
}
/**
* 上传临时图片
*
* @param type 临时素材类型:只能是 图片
* @param inputStream 临时素材流
* @param fileName 临时素材返回临时素材meta信息文件名
* @return
*/
public Media upload(MediaType type, InputStream inputStream, String fileName) {
if (type != MediaType.image) {
throw new WxRuntimeException(999, "unsupported media type: " + type.name());
}
String url = WxEndpoint.get("url.media.upload");
String response = wxClient.post(String.format(url, type.name()), inputStream, fileName);
logger.debug("upload media response: {}", response);
Map<String, Object> result = JsonMapper.defaultMapper().json2Map(response);
if (result.containsKey("media_id")) {
return JsonMapper.defaultMapper().fromJson(response, Media.class);
} else {
logger.warn("media upload failed: {}", response);
throw new WxRuntimeException(999, response);
}
}
/**
* 下载media
*
* @param mediaId media id
* @return 文件
*/
public File download(String mediaId) {
return wxClient.download(String.format(WxEndpoint.get("url.media.get"), mediaId));
}
}
| 29.448718 | 96 | 0.665651 |
9de1dc98c0629f6e942672a514e1880ac6cfef82
| 4,063 |
/*
* 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.aliyuncs.iot.transform.v20180120;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.iot.model.v20180120.ListOTAFirmwareResponse;
import com.aliyuncs.iot.model.v20180120.ListOTAFirmwareResponse.SimpleFirmwareInfo;
import com.aliyuncs.transform.UnmarshallerContext;
public class ListOTAFirmwareResponseUnmarshaller {
public static ListOTAFirmwareResponse unmarshall(ListOTAFirmwareResponse listOTAFirmwareResponse, UnmarshallerContext _ctx) {
listOTAFirmwareResponse.setRequestId(_ctx.stringValue("ListOTAFirmwareResponse.RequestId"));
listOTAFirmwareResponse.setSuccess(_ctx.booleanValue("ListOTAFirmwareResponse.Success"));
listOTAFirmwareResponse.setCode(_ctx.stringValue("ListOTAFirmwareResponse.Code"));
listOTAFirmwareResponse.setErrorMessage(_ctx.stringValue("ListOTAFirmwareResponse.ErrorMessage"));
listOTAFirmwareResponse.setTotal(_ctx.integerValue("ListOTAFirmwareResponse.Total"));
listOTAFirmwareResponse.setPageSize(_ctx.integerValue("ListOTAFirmwareResponse.PageSize"));
listOTAFirmwareResponse.setPageCount(_ctx.integerValue("ListOTAFirmwareResponse.PageCount"));
listOTAFirmwareResponse.setCurrentPage(_ctx.integerValue("ListOTAFirmwareResponse.CurrentPage"));
List<SimpleFirmwareInfo> firmwareInfo = new ArrayList<SimpleFirmwareInfo>();
for (int i = 0; i < _ctx.lengthValue("ListOTAFirmwareResponse.FirmwareInfo.Length"); i++) {
SimpleFirmwareInfo simpleFirmwareInfo = new SimpleFirmwareInfo();
simpleFirmwareInfo.setFirmwareName(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].FirmwareName"));
simpleFirmwareInfo.setFirmwareId(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].FirmwareId"));
simpleFirmwareInfo.setSrcVersion(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].SrcVersion"));
simpleFirmwareInfo.setDestVersion(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].DestVersion"));
simpleFirmwareInfo.setUtcCreate(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].UtcCreate"));
simpleFirmwareInfo.setUtcModified(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].UtcModified"));
simpleFirmwareInfo.setStatus(_ctx.integerValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].Status"));
simpleFirmwareInfo.setFirmwareDesc(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].FirmwareDesc"));
simpleFirmwareInfo.setFirmwareSign(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].FirmwareSign"));
simpleFirmwareInfo.setFirmwareSize(_ctx.integerValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].FirmwareSize"));
simpleFirmwareInfo.setFirmwareUrl(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].FirmwareUrl"));
simpleFirmwareInfo.setProductKey(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].ProductKey"));
simpleFirmwareInfo.setSignMethod(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].SignMethod"));
simpleFirmwareInfo.setProductName(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].ProductName"));
simpleFirmwareInfo.setType(_ctx.integerValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].Type"));
simpleFirmwareInfo.setModuleName(_ctx.stringValue("ListOTAFirmwareResponse.FirmwareInfo["+ i +"].ModuleName"));
firmwareInfo.add(simpleFirmwareInfo);
}
listOTAFirmwareResponse.setFirmwareInfo(firmwareInfo);
return listOTAFirmwareResponse;
}
}
| 63.484375 | 126 | 0.801378 |
2af93d8cf49fe541fa3f258ed9ecdf1094ba49db
| 281 |
package com.cantinho.cms.sqs.impl.result;
import java.util.List;
/**
* Created by samirtf on 13/04/17.
*/
public interface ICloudiaReceiptResult<T> {
String getRole();
void setRole(String role);
List<T> getReceipts();
void setReceipts(List<T> receipts);
}
| 14.789474 | 43 | 0.679715 |
2431ef60c64f1cf3d6678aec45a866e8567f086a
| 450 |
package io.onedev.commons.jsyntax.haskell;
import org.junit.Test;
import io.onedev.commons.jsyntax.AbstractTokenizerTest;
import io.onedev.commons.jsyntax.haskell.HaskellTokenizer;
public class HaskellTokenizerTest extends AbstractTokenizerTest {
@Test
public void test() {
verify(new HaskellTokenizer(), new String[] {"haskell/haskell.js"}, "test.hs");
verify(new HaskellTokenizer(), new String[] {"haskell/haskell.js"}, "test2.hs");
}
}
| 28.125 | 82 | 0.764444 |
0dbddccdbc9e00c3af0004f38b094b5b37fa5456
| 577 |
package com.sjani.usnationalparkguide.Data;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
@Dao
public interface AlertDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void save(AlertEntity alertEntity);
@Query("SELECT * FROM alerts")
LiveData<List<AlertEntity>> getAllAlerts();
@Query("DELETE FROM alerts")
void clearTable();
@Query("SELECT * FROM alerts")
List<AlertEntity> getAllAlerts2();
}
| 20.607143 | 52 | 0.741768 |
8e18ca023c6592c4ae63e16b2c3224a9242a07e8
| 4,018 |
package com.mrbysco.miab.entity.projectile;
import com.mrbysco.miab.init.MemeEntities;
import com.mrbysco.miab.init.MemeRegister;
import com.mrbysco.miab.memes.MemeRegistry;
import net.minecraft.entity.AreaEffectCloudEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.IRendersAsItem;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.projectile.ProjectileItemEntity;
import net.minecraft.item.Item;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.network.NetworkHooks;
@OnlyIn(
value = Dist.CLIENT,
_interface = IRendersAsItem.class
)
public class SplashMemeEntity extends ProjectileItemEntity implements IRendersAsItem {
@Override
protected Item getDefaultItem() {
return MemeRegister.SPLASH_MEME_IN_A_BOTTLE.get();
}
public SplashMemeEntity(EntityType<? extends SplashMemeEntity> entityType, World worldIn) {
super(entityType, worldIn);
}
public SplashMemeEntity(World worldIn, LivingEntity throwerIn) {
super(MemeEntities.SPLASH_MEME.get(), throwerIn, worldIn);
}
public SplashMemeEntity(World worldIn, double x, double y, double z) {
super(MemeEntities.SPLASH_MEME.get(), x, y, z, worldIn);
}
public SplashMemeEntity(FMLPlayMessages.SpawnEntity spawnEntity, World worldIn) {
this(MemeEntities.SPLASH_MEME.get(), worldIn);
}
@Override
public IPacket<?> createSpawnPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
@Override
public void handleStatusUpdate(byte id) {
if (id == 3) {
for (int i = 0; i < 8; ++i) {
this.world.addParticle(ParticleTypes.NOTE, this.getPosX(), this.getPosY(), this.getPosZ(), 0.0D, 0.0D, 0.0D);
}
}
}
@Override
protected float getGravityVelocity()
{
return 0.05F;
}
/**
* Called when this splash meme hits a block or entity.
*/
@Override
protected void onImpact(RayTraceResult result) {
if (!this.world.isRemote) {
if (this.isLingering()) {
if(!world.isRemote) {
this.makeAreaOfEffectCloud();
}
}
MemeRegistry.instance().triggerRandomMeme(world, this.getPosition(), world.getClosestPlayer(this, 100.0));
this.remove();
}
}
private void makeAreaOfEffectCloud() {
AreaEffectCloudEntity entityareaeffectcloud = new AreaEffectCloudEntity(this.world, this.getPosX(), this.getPosY(), this.getPosZ());
Entity entity = this.getShooter();
if (entity instanceof LivingEntity) {
entityareaeffectcloud.setOwner((LivingEntity)entity);
}
entityareaeffectcloud.setRadius(3.0F);
entityareaeffectcloud.setRadiusOnUse(-0.5F);
entityareaeffectcloud.setWaitTime(10);
entityareaeffectcloud.setRadiusPerTick(-entityareaeffectcloud.getRadius() / (float)entityareaeffectcloud.getDuration());
entityareaeffectcloud.setColor(13882323);
entityareaeffectcloud.setCustomName(new StringTextComponent("dankcloud"));
this.world.addEntity(entityareaeffectcloud);
}
@Override
public void readAdditional(CompoundNBT compound)
{
super.readAdditional(compound);
}
@Override
public void writeAdditional(CompoundNBT compound) {
super.writeAdditional(compound);
}
private boolean isLingering()
{
return this.getItem().getItem() == MemeRegister.LINGERING_MEME_IN_A_BOTTLE.get();
}
}
| 33.483333 | 140 | 0.693629 |
3395668fa7efe80818abfe1c3bf8c46fe26aadf3
| 1,176 |
package com.mimecast.robin.smtp.transaction;
import java.util.ArrayList;
import java.util.List;
/**
* Session transaction list.
*
* <p>This provides the implementation for session transactions.
*
* @see TransactionList
*/
public class SessionTransactionList extends TransactionList {
/**
* Gets last SMTP transaction of defined verb.
*
* @param verb Verb string.
* @return Transaction instance.
*/
public Transaction getLast(String verb) {
return !getTransactions(verb).isEmpty() ? getTransactions(verb).get((getTransactions(verb).size() - 1)) : null;
}
/**
* Session envelopes.
*/
private final List<EnvelopeTransactionList> envelopes = new ArrayList<>();
/**
* Adds envelope to list.
*
* @param envelopeTransactionList EnvelopeTransactionList instance.
*/
public void addEnvelope(EnvelopeTransactionList envelopeTransactionList) {
envelopes.add(envelopeTransactionList);
}
/**
* Gets envelopes.
*
* @return List of EnvelopeTransactionList.
*/
public List<EnvelopeTransactionList> getEnvelopes() {
return envelopes;
}
}
| 24.5 | 119 | 0.667517 |
cc40edff24070edce216a46f34bf6411b6ab5560
| 182 |
package behavior.state;
public class SleepState implements State {
@Override
public void exec(Human h) {
System.out.println(h + "睡觉");
h.setStateType(StateType.GETUP);
}
}
| 15.166667 | 42 | 0.714286 |
760548f1ac442c19f34812b57d4c0815f9f946fe
| 26,207 |
package com.project.convertedCode.globalNamespace.namespaces.Carbon.classes;
import com.runtimeconverter.runtime.references.ReferenceContainer;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.nativeClasses.Closure;
import com.runtimeconverter.runtime.interfaces.UpdateRuntimeScopeInterface;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import com.runtimeconverter.runtime.nativeFunctions.array.function_array_merge;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.interfaces.ContextConstants;
import com.runtimeconverter.runtime.nativeFunctions.runtime.function_call_user_func;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithInfo;
import com.runtimeconverter.runtime.references.BasicReferenceContainer;
import com.runtimeconverter.runtime.nativeFunctions.file.function_file_exists;
import com.runtimeconverter.runtime.includes.IncludeEventException;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.project.convertedCode.globalNamespace.namespaces.Symfony.namespaces.Component.namespaces.Translation.namespaces.Loader.classes.ArrayLoader;
import com.runtimeconverter.runtime.RuntimeStack;
import com.runtimeconverter.runtime.classes.NoConstructor;
import com.runtimeconverter.runtime.nativeFunctions.string.function_strlen;
import com.runtimeconverter.runtime.arrays.ArrayAction;
import com.project.convertedCode.globalNamespace.NamespaceGlobal;
import static com.runtimeconverter.runtime.ZVal.arrayActionR;
import static com.runtimeconverter.runtime.ZVal.toStringR;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/nesbot/carbon/src/Carbon/Translator.php
*/
public class Translator
extends com.project
.convertedCode
.globalNamespace
.namespaces
.Symfony
.namespaces
.Component
.namespaces
.Translation
.classes
.Translator {
public Translator(RuntimeEnv env, Object... args) {
super(env);
if (this.getClass() == Translator.class) {
this.__construct(env, args);
}
}
public Translator(NoConstructor n) {
super(n);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "locale")
@ConvertedParameter(
index = 1,
name = "formatter",
typeHint = "Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface",
defaultValue = "NULL",
defaultValueType = "constant"
)
@ConvertedParameter(
index = 2,
name = "cacheDir",
defaultValue = "NULL",
defaultValueType = "constant"
)
@ConvertedParameter(
index = 3,
name = "debug",
defaultValue = "false",
defaultValueType = "constant"
)
public Object __construct(RuntimeEnv env, Object... args) {
Object locale = assignParameter(args, 0, false);
Object formatter = assignParameter(args, 1, true);
if (null == formatter) {
formatter = ZVal.getNull();
}
Object cacheDir = assignParameter(args, 2, true);
if (null == cacheDir) {
cacheDir = ZVal.getNull();
}
Object debug = assignParameter(args, 3, true);
if (null == debug) {
debug = false;
}
env.callMethod(this, "addLoader", Translator.class, "array", new ArrayLoader(env));
super.__construct(env, locale, formatter, cacheDir, debug);
return null;
}
@ConvertedMethod
@ConvertedParameter(
index = 0,
name = "locale",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object resetMessages(RuntimeEnv env, Object... args) {
RuntimeStack stack = new RuntimeStack();
stack.setupGlobals(env);
Scope46 scope = new Scope46();
stack.pushScope(scope);
scope._thisVarAlias = this;
try {
ContextConstants runtimeConverterFunctionClassConstants =
new ContextConstants()
.setDir("/vendor/nesbot/carbon/src/Carbon")
.setFile("/vendor/nesbot/carbon/src/Carbon/Translator.php");
scope.locale = assignParameter(args, 0, true);
if (null == scope.locale) {
scope.locale = ZVal.getNull();
}
scope.filename = null;
if (ZVal.strictEqualityCheck(scope.locale, "===", ZVal.getNull())) {
env.getRequestStaticProperties(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class)
.messages =
ZVal.newArray();
throw new IncludeEventException(ZVal.assign(true));
}
if (function_file_exists
.f
.env(env)
.call(
scope.filename =
toStringR(
env.addRootFilesystemPrefix(
"/vendor/nesbot/carbon/src/Carbon"),
env)
+ "/Lang/"
+ toStringR(scope.locale, env)
+ ".php")
.getBool()) {
env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages")
.arrayAccess(env, scope.locale)
.set(
env.include(
toStringR(scope.filename, env),
stack,
runtimeConverterFunctionClassConstants,
true,
false));
env.callMethod(
scope._thisVarAlias,
"addResource",
Translator.class,
"array",
env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages")
.arrayGet(env, scope.locale),
scope.locale);
throw new IncludeEventException(ZVal.assign(true));
}
throw new IncludeEventException(ZVal.assign(false));
} catch (IncludeEventException runtimeConverterIncludeException) {
return runtimeConverterIncludeException.returnValue;
}
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "locale")
protected Object loadMessagesFromFile(RuntimeEnv env, Object... args) {
Object locale = assignParameter(args, 0, false);
if (arrayActionR(
ArrayAction.ISSET,
env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages"),
env,
locale)) {
return ZVal.assign(true);
}
return ZVal.assign(this.resetMessages(env, locale));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "locale")
@ConvertedParameter(index = 1, name = "messages")
public Object setMessages(RuntimeEnv env, Object... args) {
Object locale = assignParameter(args, 0, false);
Object messages = assignParameter(args, 1, false);
this.loadMessagesFromFile(env, locale);
env.callMethod(this, "addResource", Translator.class, "array", messages, locale);
env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages")
.arrayAccess(env, locale)
.set(
function_array_merge
.f
.env(env)
.call(
arrayActionR(
ArrayAction.ISSET,
env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages"),
env,
locale)
? env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages")
.arrayGet(env, locale)
: ZVal.newArray(),
messages)
.value());
return ZVal.assign(this);
}
@ConvertedMethod
@ConvertedParameter(
index = 0,
name = "locale",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object getMessages(RuntimeEnv env, Object... args) {
Object locale = assignParameter(args, 0, true);
if (null == locale) {
locale = ZVal.getNull();
}
return ZVal.assign(
ZVal.strictEqualityCheck(locale, "===", ZVal.getNull())
? env.getRequestStaticProperties(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class)
.messages
: env.getRequestStaticPropertiesReference(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class,
"messages")
.arrayGet(env, locale));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "locale")
public Object setLocale(RuntimeEnv env, Object... args) {
ContextConstants runtimeConverterFunctionClassConstants =
new ContextConstants()
.setDir("/vendor/nesbot/carbon/src/Carbon")
.setFile("/vendor/nesbot/carbon/src/Carbon/Translator.php");
Object locale = assignParameter(args, 0, false);
locale =
NamespaceGlobal.preg_replace_callback
.env(env)
.call(
"/[-_]([a-z]{2,})/",
new Closure(
env,
runtimeConverterFunctionClassConstants,
"Carbon",
this) {
@Override
@ConvertedMethod
@ConvertedParameter(index = 0, name = "matches")
public Object run(
RuntimeEnv env,
Object thisvar,
PassByReferenceArgs runtimePassByReferenceArgs,
Object... args) {
ReferenceContainer matches =
new BasicReferenceContainer(
assignParameter(args, 0, false));
return ZVal.assign(
"_"
+ toStringR(
function_call_user_func
.f
.env(env)
.addReferenceArgs(
new RuntimeArgsWithInfo(
args, this))
.call(
ZVal.isGreaterThan(
function_strlen
.f
.env(
env)
.call(
matches
.arrayGet(
env,
1))
.value(),
'>',
2)
? "ucfirst"
: "strtoupper",
matches.arrayGet(
env, 1))
.value(),
env));
}
},
NamespaceGlobal.strtolower.env(env).call(locale).value())
.value();
if (ZVal.isTrue(this.loadMessagesFromFile(env, locale))) {
super.setLocale(env, locale);
return ZVal.assign(true);
}
return ZVal.assign(false);
}
public static final Object CONST_class = "Carbon\\Translator";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion
extends com.project
.convertedCode
.globalNamespace
.namespaces
.Symfony
.namespaces
.Component
.namespaces
.Translation
.classes
.Translator
.RuntimeStaticCompanion {
private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup();
@ConvertedMethod
@ConvertedParameter(
index = 0,
name = "locale",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object get(RuntimeEnv env, Object... args) {
Object locale = assignParameter(args, 0, true);
if (null == locale) {
locale = ZVal.getNull();
}
Object ternaryExpressionTemp = null;
if (ZVal.strictEqualityCheck(
env.getRequestStaticProperties(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class)
.singleton,
"===",
ZVal.getNull())) {
env.getRequestStaticProperties(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class)
.singleton =
env.createNewWithLateStaticBindings(
this,
ZVal.isTrue(ternaryExpressionTemp = locale)
? ternaryExpressionTemp
: "en");
}
return ZVal.assign(
env.getRequestStaticProperties(
com.project
.convertedCode
.globalNamespace
.namespaces
.Carbon
.classes
.Translator
.RequestStaticProperties
.class)
.singleton);
}
}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
public static class RequestStaticProperties {
public Object singleton = null;
public Object messages = ZVal.newArray();
}
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("Carbon\\Translator")
.setLookup(
Translator.class,
MethodHandles.lookup(),
RuntimeStaticCompanion.staticCompanionLookup)
.setLocalProperties(
"cacheDir",
"catalogues",
"configCacheFactory",
"debug",
"fallbackLocales",
"formatter",
"loaders",
"locale",
"resources")
.setStaticPropertyNames("messages", "singleton")
.setFilename("vendor/nesbot/carbon/src/Carbon/Translator.php")
.addInterface("Symfony\\Component\\Translation\\TranslatorInterface")
.addInterface("Symfony\\Component\\Translation\\TranslatorBagInterface")
.addExtendsClass("Symfony\\Component\\Translation\\Translator")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
private static class Scope46 implements UpdateRuntimeScopeInterface {
Object filename;
Object _thisVarAlias;
Object locale;
public void updateStack(RuntimeStack stack) {
stack.setVariable("filename", this.filename);
stack.setVariable("this", this._thisVarAlias);
stack.setVariable("locale", this.locale);
}
public void updateScope(RuntimeStack stack) {
this.filename = stack.getVariable("filename");
this._thisVarAlias = stack.getVariable("this");
this.locale = stack.getVariable("locale");
}
}
}
| 47.390597 | 150 | 0.384439 |
d4c80cb1eb2cba646eb44719dd123b864e25a81e
| 611 |
package danieer.galvez.testrappi.viewmodel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import danieer.galvez.testrappi.model.MovieDetailResponse;
import danieer.galvez.testrappi.repository.DetailMovieRepository;
public class DetailMovieViewmodel extends ViewModel {
DetailMovieRepository detailMovieRepository;
public DetailMovieViewmodel() {
detailMovieRepository = new DetailMovieRepository();
}
public MutableLiveData<MovieDetailResponse> getMovieDetails(int movieId) {
return detailMovieRepository.getMovieDetails(movieId);
}
}
| 29.095238 | 78 | 0.806874 |
800fa5a648d44a0b237e9e959251bd574bd864c3
| 5,628 |
/**
* 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.apex.benchmark.hive;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.apex.benchmark.RandomMapOutput;
import org.apache.apex.malhar.hive.AbstractFSRollingOutputOperator;
import org.apache.apex.malhar.hive.HiveOperator;
import org.apache.apex.malhar.hive.HiveStore;
import org.apache.apex.malhar.lib.testbench.RandomEventGenerator;
import org.apache.hadoop.conf.Configuration;
import com.datatorrent.api.Context.PortContext;
import com.datatorrent.api.DAG;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.api.annotation.ApplicationAnnotation;
/**
* Application used to benchmark HIVE Map Insert operator
* The DAG consists of random Event generator operator that is
* connected to random map output operator that writes to a file in HDFS.
* The map output operator is connected to hive Map Insert output operator which writes
* the contents of HDFS file to hive tables.
* <p>
*
* @since 2.1.0
*/
@ApplicationAnnotation(name = "HiveMapInsertBenchmarkingApp")
public class HiveMapInsertBenchmarkingApp implements StreamingApplication
{
Logger LOG = LoggerFactory.getLogger(HiveMapInsertBenchmarkingApp.class);
@Override
public void populateDAG(DAG dag, Configuration conf)
{
HiveStore store = new HiveStore();
store.setDatabaseUrl(conf.get("dt.application.HiveMapInsertBenchmarkingApp.operator.HiveOperator.store.dbUrl"));
store.setConnectionProperties(conf.get(
"dt.application.HiveMapInsertBenchmarkingApp.operator.HiveOperator.store.connectionProperties"));
store.setFilepath(conf.get("dt.application.HiveMapInsertBenchmarkingApp.operator.HiveOperator.store.filepath"));
try {
hiveInitializeMapDatabase(store, conf.get(
"dt.application.HiveMapInsertBenchmarkingApp.operator.HiveOperator.tablename"), ":");
} catch (SQLException ex) {
LOG.debug(ex.getMessage());
}
dag.setAttribute(DAG.STREAMING_WINDOW_SIZE_MILLIS, 1000);
RandomEventGenerator eventGenerator = dag.addOperator("EventGenerator", RandomEventGenerator.class);
RandomMapOutput mapGenerator = dag.addOperator("MapGenerator", RandomMapOutput.class);
dag.setAttribute(eventGenerator, PortContext.QUEUE_CAPACITY, 10000);
dag.setAttribute(mapGenerator, PortContext.QUEUE_CAPACITY, 10000);
HiveOperator hiveInsert = dag.addOperator("HiveOperator", new HiveOperator());
hiveInsert.setStore(store);
FSRollingMapTestImpl rollingMapFsWriter = dag.addOperator("RollingFsMapWriter", new FSRollingMapTestImpl());
rollingMapFsWriter.setFilePath(store.filepath);
ArrayList<String> hivePartitionColumns = new ArrayList<String>();
hivePartitionColumns.add("dt");
hiveInsert.setHivePartitionColumns(hivePartitionColumns);
dag.addStream("EventGenerator2Map", eventGenerator.integer_data, mapGenerator.input);
dag.addStream("MapGenerator2HdfsOutput", mapGenerator.map_data, rollingMapFsWriter.input);
dag.addStream("FsWriter2Hive", rollingMapFsWriter.outputPort, hiveInsert.input);
}
/*
* User can create table and specify data columns and partition columns in this function.
*/
public static void hiveInitializeMapDatabase(
HiveStore hiveStore, String tablename, String delimiterMap) throws SQLException
{
hiveStore.connect();
Statement stmt = hiveStore.getConnection().createStatement();
stmt.execute("CREATE TABLE IF NOT EXISTS " + tablename
+ " (col1 map<string,int>) PARTITIONED BY(dt STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\n' \n"
+ "MAP KEYS TERMINATED BY '" + delimiterMap + "' \n"
+ "STORED AS TEXTFILE ");
hiveStore.disconnect();
}
public static class FSRollingMapTestImpl extends AbstractFSRollingOutputOperator<Map<String, Object>>
{
public String delimiter = ":";
public String getDelimiter()
{
return delimiter;
}
public void setDelimiter(String delimiter)
{
this.delimiter = delimiter;
}
@Override
public ArrayList<String> getHivePartition(Map<String, Object> tuple)
{
ArrayList<String> hivePartitions = new ArrayList<String>();
hivePartitions.add(tuple.toString());
return (hivePartitions);
}
@Override
protected byte[] getBytesForTuple(Map<String, Object> tuple)
{
Iterator<String> keyIter = tuple.keySet().iterator();
StringBuilder writeToHive = new StringBuilder("");
while (keyIter.hasNext()) {
String key = keyIter.next();
Object obj = tuple.get(key);
writeToHive.append(key).append(delimiter).append(obj).append("\n");
}
return writeToHive.toString().getBytes();
}
}
}
| 39.083333 | 116 | 0.749112 |
63c6d9f504b09dec4cd3e877b7eb722428f67fc4
| 3,777 |
/**
** Copyright 2016 General Electric Company
**
**
** 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.ge.research.semtk.edc.client;
import java.net.ConnectException;
import org.json.simple.JSONObject;
import com.ge.research.semtk.auth.ThreadAuthenticator;
import com.ge.research.semtk.ontologyTools.OntologyInfo;
import com.ge.research.semtk.resultSet.SimpleResultSet;
import com.ge.research.semtk.resultSet.Table;
import com.ge.research.semtk.resultSet.TableResultSet;
import com.ge.research.semtk.services.client.RestClient;
import com.ge.research.semtk.services.client.RestClientConfig;
import com.ge.research.semtk.sparqlX.SparqlConnection;
public class OntologyInfoClient extends RestClient {
public OntologyInfoClient(OntologyInfoClientConfig config) {
super ((RestClientConfig) config);
}
@Override
public void buildParametersJSON() throws Exception {
// performed by calls. Different params for different calls.
}
@Override
public void handleEmptyResponse() throws Exception {
throw new Exception("Received empty response");
}
/**
*
* @throws Exception
*/
public JSONObject execGetOntologyInfoJson(SparqlConnection sparqlConn) throws ConnectException, EndpointNotFoundException, Exception {
this.parametersJSON.put("jsonRenderedSparqlConnection", sparqlConn.toJson().toJSONString());
conf.setServiceEndpoint("ontologyinfo/getOntologyInfoJson");
try {
SimpleResultSet res = this.executeWithSimpleResultReturn();
res.throwExceptionIfUnsuccessful();
return res.getResultJSON("ontologyInfo");
} finally {
// reset conf and parametersJSON
this.parametersJSON.remove("jsonRenderedSparqlConnection");
conf.setServiceEndpoint(null);
}
}
/**
* Highest level: get oInfo from a SparqlConn
* Note that oInfo service has several optimizations including a cache.
* @param conn
* @return
* @throws ConnectException
* @throws EndpointNotFoundException
* @throws Exception
*/
public OntologyInfo getOntologyInfo(SparqlConnection conn) throws ConnectException, EndpointNotFoundException, Exception {
return new OntologyInfo(this.execGetOntologyInfoJson(conn));
}
public void uncacheChangedModel(SparqlConnection conn) throws ConnectException, EndpointNotFoundException, Exception {
this.parametersJSON.put("jsonRenderedSparqlConnection", conn.toJson().toJSONString());
conf.setServiceEndpoint("ontologyinfo/uncacheChangedModel");
try {
SimpleResultSet res = this.executeWithSimpleResultReturn();
res.throwExceptionIfUnsuccessful();
} finally {
// reset conf and parametersJSON
this.parametersJSON.remove("jsonRenderedSparqlConnection");
conf.setServiceEndpoint(null);
}
}
public void uncacheOntology(SparqlConnection conn) throws ConnectException, EndpointNotFoundException, Exception {
this.parametersJSON.put("jsonRenderedSparqlConnection", conn.toJson().toJSONString());
conf.setServiceEndpoint("ontologyinfo/uncacheOntology");
try {
SimpleResultSet res = this.executeWithSimpleResultReturn();
res.throwExceptionIfUnsuccessful();
} finally {
// reset conf and parametersJSON
this.parametersJSON.remove("jsonRenderedSparqlConnection");
conf.setServiceEndpoint(null);
}
}
}
| 32.282051 | 135 | 0.771247 |
5cec6d3c811927f594afce491e3b68c77324bbe4
| 320 |
package de.cuuky.cfw.configuration.placeholder.placeholder.util;
public class DateInfo {
public static final int YEAR = 0;
public static final int MONTH = 1;
public static final int DAY = 2;
public static final int HOUR = 3;
public static final int MINUTES = 4;
public static final int SECONDS = 5;
}
| 26.666667 | 65 | 0.721875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.