repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
GWTReact/gwt-react-examples | src/gwt/react/api_sanity_test/client/ComponentDidCatchBadComponent.java | 536 | package gwt.react.api_sanity_test.client;
import gwt.interop.utils.client.plainobjects.JsPlainObj;
import gwt.react.client.components.Component;
import gwt.react.client.elements.ReactElement;
import gwt.react.client.proptypes.BaseProps;
import jsinterop.annotations.JsType;
@JsType
public class ComponentDidCatchBadComponent extends Component<BaseProps, JsPlainObj> {
public ComponentDidCatchBadComponent(BaseProps props) {
super(props);
}
@Override
protected ReactElement render() {
throw new NullPointerException();
}
}
| mit |
pomortaz/azure-sdk-for-java | azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/ContainerServiceVMDiagnostics.java | 1382 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Profile for diagnostics on the container service VMs.
*/
public class ContainerServiceVMDiagnostics {
/**
* Whether the VM diagnostic agent is provisioned on the VM.
*/
@JsonProperty(required = true)
private boolean enabled;
/**
* The URI of the storage account where diagnostics are stored.
*/
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String storageUri;
/**
* Get the enabled value.
*
* @return the enabled value
*/
public boolean enabled() {
return this.enabled;
}
/**
* Set the enabled value.
*
* @param enabled the enabled value to set
* @return the ContainerServiceVMDiagnostics object itself.
*/
public ContainerServiceVMDiagnostics withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the storageUri value.
*
* @return the storageUri value
*/
public String storageUri() {
return this.storageUri;
}
}
| mit |
Azure/azure-sdk-for-java | sdk/advisor/azure-resourcemanager-advisor/src/main/java/com/azure/resourcemanager/advisor/implementation/RecommendationMetadatasClientImpl.java | 17190 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.advisor.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.advisor.fluent.RecommendationMetadatasClient;
import com.azure.resourcemanager.advisor.fluent.models.MetadataEntityInner;
import com.azure.resourcemanager.advisor.models.MetadataEntityListResult;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in RecommendationMetadatasClient. */
public final class RecommendationMetadatasClientImpl implements RecommendationMetadatasClient {
private final ClientLogger logger = new ClientLogger(RecommendationMetadatasClientImpl.class);
/** The proxy service used to perform REST calls. */
private final RecommendationMetadatasService service;
/** The service client containing this operation class. */
private final AdvisorManagementClientImpl client;
/**
* Initializes an instance of RecommendationMetadatasClientImpl.
*
* @param client the instance of the service client containing this operation class.
*/
RecommendationMetadatasClientImpl(AdvisorManagementClientImpl client) {
this.service =
RestProxy
.create(RecommendationMetadatasService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for AdvisorManagementClientRecommendationMetadatas to be used by the
* proxy service to perform REST calls.
*/
@Host("{$host}")
@ServiceInterface(name = "AdvisorManagementCli")
private interface RecommendationMetadatasService {
@Headers({"Content-Type: application/json"})
@Get("/providers/Microsoft.Advisor/metadata/{name}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<MetadataEntityInner>> get(
@HostParam("$host") String endpoint,
@PathParam("name") String name,
@QueryParam("api-version") String apiVersion,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get("/providers/Microsoft.Advisor/metadata")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<MetadataEntityListResult>> list(
@HostParam("$host") String endpoint,
@QueryParam("api-version") String apiVersion,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<MetadataEntityListResult>> listNext(
@PathParam(value = "nextLink", encoded = true) String nextLink,
@HostParam("$host") String endpoint,
@HeaderParam("Accept") String accept,
Context context);
}
/**
* Gets the metadata entity.
*
* @param name Name of metadata entity.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the metadata entity.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<MetadataEntityInner>> getWithResponseAsync(String name) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (name == null) {
return Mono.error(new IllegalArgumentException("Parameter name is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(
context -> service.get(this.client.getEndpoint(), name, this.client.getApiVersion(), accept, context))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Gets the metadata entity.
*
* @param name Name of metadata entity.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the metadata entity.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<MetadataEntityInner>> getWithResponseAsync(String name, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (name == null) {
return Mono.error(new IllegalArgumentException("Parameter name is required and cannot be null."));
}
final String accept = "application/json";
context = this.client.mergeContext(context);
return service.get(this.client.getEndpoint(), name, this.client.getApiVersion(), accept, context);
}
/**
* Gets the metadata entity.
*
* @param name Name of metadata entity.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the metadata entity.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<MetadataEntityInner> getAsync(String name) {
return getWithResponseAsync(name)
.flatMap(
(Response<MetadataEntityInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Gets the metadata entity.
*
* @param name Name of metadata entity.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the metadata entity.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public MetadataEntityInner get(String name) {
return getAsync(name).block();
}
/**
* Gets the metadata entity.
*
* @param name Name of metadata entity.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the metadata entity.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<MetadataEntityInner> getWithResponse(String name, Context context) {
return getWithResponseAsync(name, context).block();
}
/**
* Gets the list of metadata entities.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<MetadataEntityInner>> listSinglePageAsync() {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(
context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context))
.<PagedResponse<MetadataEntityInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Gets the list of metadata entities.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<MetadataEntityInner>> listSinglePageAsync(Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets the list of metadata entities.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<MetadataEntityInner> listAsync() {
return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Gets the list of metadata entities.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<MetadataEntityInner> listAsync(Context context) {
return new PagedFlux<>(
() -> listSinglePageAsync(context), nextLink -> listNextSinglePageAsync(nextLink, context));
}
/**
* Gets the list of metadata entities.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<MetadataEntityInner> list() {
return new PagedIterable<>(listAsync());
}
/**
* Gets the list of metadata entities.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<MetadataEntityInner> list(Context context) {
return new PagedIterable<>(listAsync(context));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<MetadataEntityInner>> listNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context))
.<PagedResponse<MetadataEntityInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the list of metadata entities.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<MetadataEntityInner>> listNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.listNext(nextLink, this.client.getEndpoint(), accept, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
}
| mit |
ah5/buynsell | src/main/com/buynsell/businessobjects/Product.java | 1394 | package com.buynsell.businessobjects;
import java.util.ArrayList;
public class Product {
protected String productid;
protected String catalogid;
protected String name;
protected String desc;
protected String cat;
protected String qty;
protected String wt;
public Product() {
}
public Product(ArrayList<?> raw) {
this.productid = (String) raw.get(0);
this.catalogid = (String) raw.get(1);
this.name = (String) raw.get(2);
this.desc = (String) raw.get(3);
this.cat = (String) raw.get(4);
this.qty = (String) raw.get(5);
this.wt = (String) raw.get(6);
}
public String getProductid() {
return this.productid;
}
public void setProductid(String productid) {
this.productid = productid;
}
public String getCatalogid() {
return this.catalogid;
}
public void setCatalogid(String catalogid) {
this.catalogid = catalogid;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return this.desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getCat() {
return this.cat;
}
public void setCat(String cat) {
this.cat = cat;
}
public String getQty() {
return this.qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getWt() {
return this.wt;
}
public void setWt(String wt) {
this.wt = wt;
}
} | mit |
Updownquark/Qommons | src/main/java/org/qommons/tree/DefaultTree.java | 1395 | package org.qommons.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class DefaultTree<V> implements Tree<V, DefaultTree<V>, List<DefaultTree<V>>> {
private V theValue;
private List<DefaultTree<V>> theChildren;
public DefaultTree() {
theChildren = new ArrayList<>();
}
public DefaultTree(V value) {
this();
theValue = value;
}
@Override
public V getValue() {
return theValue;
}
public DefaultTree<V> setValue(V value) {
theValue = value;
return this;
}
@Override
public List<DefaultTree<V>> getChildren() {
return theChildren;
}
public DefaultTree<V> replaceAll(Function<? super V, ? extends V> replacer) {
setValue(replacer.apply(getValue()));
for (DefaultTree<V> child : getChildren())
child.replaceAll(replacer);
return this;
}
@Override
public String toString() {
return String.valueOf(theValue);
}
public static <V> DefaultTree<V> treeOf(V root, Function<V, Iterable<V>> childFn) {
DefaultTree<V> ret = new DefaultTree<>(root);
for (V child : childFn.apply(root)) {
ret.getChildren().add(treeOf(child, childFn));
}
return ret;
}
public static <V> DefaultTree<V> treeOfArray(V root, Function<V, V[]> childFn) {
return treeOf(root, childFn.andThen(array -> Arrays.asList(array)));
}
}
| mit |
JsonSchema-JavaUI/sf-java-ui | src/main/java/io/asfjava/ui/core/schema/decorators/TextFieldSchemaDecorator.java | 1069 | package io.asfjava.ui.core.schema.decorators;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.types.StringSchema;
import io.asfjava.ui.core.form.TextField;
public class TextFieldSchemaDecorator implements SchemaDecorator {
@Override
public void customizeSchema(BeanProperty property, JsonSchema jsonschema) {
TextField annotation = property.getAnnotation(TextField.class);
if (annotation != null) {
if (annotation.title() != null) {
((StringSchema) jsonschema).setTitle(annotation.title());
}
if (annotation.pattern() != null) {
((StringSchema) jsonschema).setPattern(annotation.pattern());
}
if (annotation.minLenght() != 0) {
((StringSchema) jsonschema).setMinLength(annotation.minLenght());
}
if (annotation.maxLenght() != Integer.MAX_VALUE) {
((StringSchema) jsonschema).setMaxLength(annotation.maxLenght());
}
}
}
@Override
public String getAnnotation() {
return TextField.class.getName();
}
}
| mit |
JCThePants/NucleusFramework | src/com/jcwhatever/nucleus/internal/managed/items/floating/InternalFloatingItemManager.java | 4379 | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.internal.managed.items.floating;
import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.storage.DataPath;
import com.jcwhatever.nucleus.providers.storage.DataStorage;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.managed.items.floating.IFloatingItem;
import com.jcwhatever.nucleus.managed.items.floating.IFloatingItemManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import java.util.Collection;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
/**
* Manages floating items.
*/
public final class InternalFloatingItemManager implements IFloatingItemManager, Listener {
private final Map<Plugin, FloatingItemContext> _contexts = new WeakHashMap<>(25);
public InternalFloatingItemManager() {
Bukkit.getPluginManager().registerEvents(this, Nucleus.getPlugin());
}
@Override
@Nullable
public IFloatingItem add(Plugin plugin, String name, ItemStack itemStack) {
return add(plugin, name, itemStack, null);
}
@Override
@Nullable
public IFloatingItem add(Plugin plugin, String name, ItemStack itemStack,
@Nullable Location location) {
PreCon.notNull(plugin);
PreCon.notNullOrEmpty(name);
PreCon.notNull(itemStack);
return context(plugin).add(name, itemStack, location);
}
@Override
public boolean contains(Plugin plugin, String name) {
PreCon.notNull(plugin);
PreCon.notNullOrEmpty(name);
return context(plugin).contains(name);
}
@Nullable
@Override
public IFloatingItem get(Plugin plugin, String name) {
PreCon.notNull(name);
PreCon.notNullOrEmpty(name);
return context(plugin).get(name);
}
@Override
public Collection<IFloatingItem> getAll(Plugin plugin) {
PreCon.notNull(plugin);
return context(plugin).getAll();
}
@Override
public <T extends Collection<IFloatingItem>> T getAll(Plugin plugin, T output) {
PreCon.notNull(plugin);
PreCon.notNull(output);
// cast required for compiler
@SuppressWarnings("unchecked")
T result = (T)context(plugin).getAll(output);
return result;
}
@Override
public boolean remove(Plugin plugin, String name) {
PreCon.notNull(plugin);
PreCon.notNullOrEmpty(name);
FloatingItemContext context = _contexts.get(plugin);
return context != null && context.remove(name);
}
private FloatingItemContext context(Plugin plugin) {
FloatingItemContext context = _contexts.get(plugin);
if (context == null) {
IDataNode dataNode = DataStorage.get(plugin, new DataPath("nucleus.floating-items"));
dataNode.load();
context = new FloatingItemContext(plugin, dataNode);
_contexts.put(plugin, context);
}
return context;
}
}
| mit |
maxdemarzi/neo_loc_counter | src/main/java/com/maxdemarzi/RelationshipTypes.java | 144 | package com.maxdemarzi;
import org.neo4j.graphdb.RelationshipType;
public enum RelationshipTypes implements RelationshipType {
CALLS
}
| mit |
caizixian/algorithm_exercise | LeetCode/80.Remove Duplicates from Sorted Array II.java | 548 | public class Solution {
public int removeDuplicates(int[] nums) {
int w_ptr = 0;
int duplicate_counter = 0;
for (int r_ptr = 1; r_ptr < nums.length; r_ptr++) {
if (nums[r_ptr] == nums[r_ptr - 1]) {
//Duplicate
duplicate_counter++;
} else {
duplicate_counter = 0;
}
if (duplicate_counter <= 1) {
nums[w_ptr + 1] = nums[r_ptr];
w_ptr++;
}
}
return w_ptr + 1;
}
} | mit |
jglrxavpok/SBM | src/main/java/org/jglr/sbm/utils/StructuredModuleWriter.java | 324 | package org.jglr.sbm.utils;
import org.jglr.sbm.visitors.ModuleWriter;
/**
* Module writer using {@link StructuredCodeWriter} as its code writer
*/
public class StructuredModuleWriter extends ModuleWriter {
public StructuredModuleWriter() {
super();
codeWriter = new StructuredCodeWriter();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineScaleSetIpConfiguration.java | 12249 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.SubResource;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineScaleSetIpConfigurationProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Describes a virtual machine scale set network profile's IP configuration. */
@Fluent
public final class VirtualMachineScaleSetIpConfiguration extends SubResource {
/*
* The IP configuration name.
*/
@JsonProperty(value = "name", required = true)
private String name;
/*
* Describes a virtual machine scale set network profile's IP configuration
* properties.
*/
@JsonProperty(value = "properties")
private VirtualMachineScaleSetIpConfigurationProperties innerProperties;
/**
* Get the name property: The IP configuration name.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Set the name property: The IP configuration name.
*
* @param name the name value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withName(String name) {
this.name = name;
return this;
}
/**
* Get the innerProperties property: Describes a virtual machine scale set network profile's IP configuration
* properties.
*
* @return the innerProperties value.
*/
private VirtualMachineScaleSetIpConfigurationProperties innerProperties() {
return this.innerProperties;
}
/** {@inheritDoc} */
@Override
public VirtualMachineScaleSetIpConfiguration withId(String id) {
super.withId(id);
return this;
}
/**
* Get the subnet property: Specifies the identifier of the subnet.
*
* @return the subnet value.
*/
public ApiEntityReference subnet() {
return this.innerProperties() == null ? null : this.innerProperties().subnet();
}
/**
* Set the subnet property: Specifies the identifier of the subnet.
*
* @param subnet the subnet value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withSubnet(ApiEntityReference subnet) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withSubnet(subnet);
return this;
}
/**
* Get the primary property: Specifies the primary network interface in case the virtual machine has more than 1
* network interface.
*
* @return the primary value.
*/
public Boolean primary() {
return this.innerProperties() == null ? null : this.innerProperties().primary();
}
/**
* Set the primary property: Specifies the primary network interface in case the virtual machine has more than 1
* network interface.
*
* @param primary the primary value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withPrimary(Boolean primary) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withPrimary(primary);
return this;
}
/**
* Get the publicIpAddressConfiguration property: The publicIPAddressConfiguration.
*
* @return the publicIpAddressConfiguration value.
*/
public VirtualMachineScaleSetPublicIpAddressConfiguration publicIpAddressConfiguration() {
return this.innerProperties() == null ? null : this.innerProperties().publicIpAddressConfiguration();
}
/**
* Set the publicIpAddressConfiguration property: The publicIPAddressConfiguration.
*
* @param publicIpAddressConfiguration the publicIpAddressConfiguration value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withPublicIpAddressConfiguration(
VirtualMachineScaleSetPublicIpAddressConfiguration publicIpAddressConfiguration) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withPublicIpAddressConfiguration(publicIpAddressConfiguration);
return this;
}
/**
* Get the privateIpAddressVersion property: Available from Api-Version 2017-03-30 onwards, it represents whether
* the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'.
*
* @return the privateIpAddressVersion value.
*/
public IpVersion privateIpAddressVersion() {
return this.innerProperties() == null ? null : this.innerProperties().privateIpAddressVersion();
}
/**
* Set the privateIpAddressVersion property: Available from Api-Version 2017-03-30 onwards, it represents whether
* the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'.
*
* @param privateIpAddressVersion the privateIpAddressVersion value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withPrivateIpAddressVersion(IpVersion privateIpAddressVersion) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withPrivateIpAddressVersion(privateIpAddressVersion);
return this;
}
/**
* Get the applicationGatewayBackendAddressPools property: Specifies an array of references to backend address pools
* of application gateways. A scale set can reference backend address pools of multiple application gateways.
* Multiple scale sets cannot use the same application gateway.
*
* @return the applicationGatewayBackendAddressPools value.
*/
public List<SubResource> applicationGatewayBackendAddressPools() {
return this.innerProperties() == null ? null : this.innerProperties().applicationGatewayBackendAddressPools();
}
/**
* Set the applicationGatewayBackendAddressPools property: Specifies an array of references to backend address pools
* of application gateways. A scale set can reference backend address pools of multiple application gateways.
* Multiple scale sets cannot use the same application gateway.
*
* @param applicationGatewayBackendAddressPools the applicationGatewayBackendAddressPools value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withApplicationGatewayBackendAddressPools(
List<SubResource> applicationGatewayBackendAddressPools) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withApplicationGatewayBackendAddressPools(applicationGatewayBackendAddressPools);
return this;
}
/**
* Get the applicationSecurityGroups property: Specifies an array of references to application security group.
*
* @return the applicationSecurityGroups value.
*/
public List<SubResource> applicationSecurityGroups() {
return this.innerProperties() == null ? null : this.innerProperties().applicationSecurityGroups();
}
/**
* Set the applicationSecurityGroups property: Specifies an array of references to application security group.
*
* @param applicationSecurityGroups the applicationSecurityGroups value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withApplicationSecurityGroups(
List<SubResource> applicationSecurityGroups) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withApplicationSecurityGroups(applicationSecurityGroups);
return this;
}
/**
* Get the loadBalancerBackendAddressPools property: Specifies an array of references to backend address pools of
* load balancers. A scale set can reference backend address pools of one public and one internal load balancer.
* Multiple scale sets cannot use the same basic sku load balancer.
*
* @return the loadBalancerBackendAddressPools value.
*/
public List<SubResource> loadBalancerBackendAddressPools() {
return this.innerProperties() == null ? null : this.innerProperties().loadBalancerBackendAddressPools();
}
/**
* Set the loadBalancerBackendAddressPools property: Specifies an array of references to backend address pools of
* load balancers. A scale set can reference backend address pools of one public and one internal load balancer.
* Multiple scale sets cannot use the same basic sku load balancer.
*
* @param loadBalancerBackendAddressPools the loadBalancerBackendAddressPools value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withLoadBalancerBackendAddressPools(
List<SubResource> loadBalancerBackendAddressPools) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withLoadBalancerBackendAddressPools(loadBalancerBackendAddressPools);
return this;
}
/**
* Get the loadBalancerInboundNatPools property: Specifies an array of references to inbound Nat pools of the load
* balancers. A scale set can reference inbound nat pools of one public and one internal load balancer. Multiple
* scale sets cannot use the same basic sku load balancer.
*
* @return the loadBalancerInboundNatPools value.
*/
public List<SubResource> loadBalancerInboundNatPools() {
return this.innerProperties() == null ? null : this.innerProperties().loadBalancerInboundNatPools();
}
/**
* Set the loadBalancerInboundNatPools property: Specifies an array of references to inbound Nat pools of the load
* balancers. A scale set can reference inbound nat pools of one public and one internal load balancer. Multiple
* scale sets cannot use the same basic sku load balancer.
*
* @param loadBalancerInboundNatPools the loadBalancerInboundNatPools value to set.
* @return the VirtualMachineScaleSetIpConfiguration object itself.
*/
public VirtualMachineScaleSetIpConfiguration withLoadBalancerInboundNatPools(
List<SubResource> loadBalancerInboundNatPools) {
if (this.innerProperties() == null) {
this.innerProperties = new VirtualMachineScaleSetIpConfigurationProperties();
}
this.innerProperties().withLoadBalancerInboundNatPools(loadBalancerInboundNatPools);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (name() == null) {
throw LOGGER
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property name in model VirtualMachineScaleSetIpConfiguration"));
}
if (innerProperties() != null) {
innerProperties().validate();
}
}
private static final ClientLogger LOGGER = new ClientLogger(VirtualMachineScaleSetIpConfiguration.class);
}
| mit |
hagaeru3sei/embulk-input-kafka | src/main/java/org/embulk/input/kafka/data/column/ColumnType.java | 890 | package org.embulk.input.kafka.data.column;
import org.embulk.input.kafka.exception.ColumnTypeNotFoundException;
import java.util.HashMap;
import java.util.Map;
public enum ColumnType {
Boolean("boolean"),
Long("long"),
Double("double"),
String("string"),
Timestamp("timestamp");
private static final Map<String, ColumnType> types = new HashMap<String, ColumnType>();
static {
for (ColumnType type : ColumnType.values()) {
types.put(type.getName(), type);
}
}
private final String name;
ColumnType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static ColumnType get(String name) throws ColumnTypeNotFoundException {
ColumnType type = types.get(name);
if (type == null) {
throw new ColumnTypeNotFoundException("Column type not found. type: " + name);
}
return type;
}
}
| mit |
BraindeadCrew/java-websocket | src/main/java/fr/braindead/websocket/server/ServerStoppedException.java | 141 | package fr.braindead.websocket.server;
/**
*
* Created by leiko on 2/17/17.
*/
public class ServerStoppedException extends Exception {
}
| mit |
amverhagen/pulse-dodge | core/src/com/amverhagen/pulsedodge/tests/IndexedLineTester.java | 1317 | package com.amverhagen.pulsedodge.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import com.amverhagen.pulsedodge.lines.IndexedLine;
public class IndexedLineTester {
@Test
public void testMoveHorizontally() {
float initX = 0;
float xDifference = 30;
float xAfter = initX + xDifference;
for (int i = 1; i < 400; i++) {
IndexedLine iL = new IndexedLine(initX, 0f, i, 400);
iL.moveLineHorizontally(xDifference);
assertEquals((double) xAfter, (double) iL.getVectorAtIndex(i).x, .001d);
}
}
@Test
public void testMoveVertically() {
float initY = 0;
float yDifference = 30;
float yAfter = initY + yDifference;
for (int i = 1; i < 400; i++) {
IndexedLine iL = new IndexedLine(0f, 0f, i, 400);
iL.moveLineVertically(yDifference);
assertEquals((double) yAfter, (double) iL.getVectorAtIndex(i).y, .001d);
}
}
@Test
public void testDistancesBetweenPoints() {
float initX = 0;
float initY = 0;
int indices = 4;
for (int i = 0; i < 10000; i++) {
float distance = (float) i / (indices - 1);
IndexedLine iL = new IndexedLine(initX, initY, indices, i);
for (int j = 0; j < indices - 1; j++) {
float indiceDifference = iL.getVectorAtIndex(j + 1).x - iL.getVectorAtIndex(j).x;
assertEquals(distance, indiceDifference, .001);
}
}
}
}
| mit |
bysse/nobloat | jsonrpc-dispatch/src/test/java/se.slackers.nobloat.jsonrpc/MethodDispatcherImplTest.java | 5023 | package se.slackers.nobloat.jsonrpc;
import org.junit.Before;
import org.junit.Test;
import se.slackers.nobloat.jsonrpc.annotation.JsonRpc;
import se.slackers.nobloat.jsonrpc.annotation.JsonRpcNamespace;
import se.slackers.nobloat.jsonrpc.protocol.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.*;
public class MethodDispatcherImplTest {
private MethodDispatcherImpl dispatcher;
@Before
public void setup() {
MethodRegistry registry = new MethodRegistryImpl();
registry.register(new Api());
dispatcher = new MethodDispatcherImpl(registry);
}
@Test
public void testSimple() {
List<JsonRpcResponse> responses1 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.notification("api.test")));
assertTrue(responses1.isEmpty());
List<JsonRpcResponse> responses2 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.create(1L, "api.test", "A")));
assertEquals(1, responses2.size());
assertEquals(JsonRpcVersion.VERSION_2_0, responses2.get(0).getVersion());
assertEquals(1L, (long) responses2.get(0).getId());
assertEquals(null, responses2.get(0).getResult());
assertEquals(null, responses2.get(0).getError());
List<JsonRpcResponse> responses3 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.create(1L, "api.test", "A", "B")));
assertEquals(1, responses3.size());
assertEquals(JsonRpcVersion.VERSION_2_0, responses3.get(0).getVersion());
assertEquals(1L, (long) responses3.get(0).getId());
assertEquals("AB", responses3.get(0).getResult());
assertEquals(null, responses3.get(0).getError());
}
@Test
public void testFailingCall() {
List<JsonRpcResponse> responses1 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.create(1L, "api.failing")));
assertEquals(1, responses1.size());
JsonRpcResponse response1 = responses1.get(0);
assertEquals(JsonRpcVersion.VERSION_2_0, response1.getVersion());
assertEquals(1L, (long) response1.getId());
assertEquals(null, response1.getResult());
JsonRpcErrorResponse error1 = response1.getError();
assertNotNull(error1);
assertEquals(JsonRpcErrorCode.InternalError.getCode(), error1.getCode());
}
@Test
public void testNoSuchMethod() {
List<JsonRpcResponse> responses1 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.create(2L, "api.doesNotExist")));
assertEquals(1, responses1.size());
JsonRpcResponse response1 = responses1.get(0);
assertEquals(JsonRpcVersion.VERSION_2_0, response1.getVersion());
assertEquals(2L, (long) response1.getId());
assertEquals(null, response1.getResult());
JsonRpcErrorResponse error1 = response1.getError();
assertNotNull(error1);
assertEquals(JsonRpcErrorCode.MethodNotFound.getCode(), error1.getCode());
}
@Test
public void testFailingNotification() {
List<JsonRpcResponse> responses1 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.notification("api.failing")));
assertEquals(0, responses1.size());
}
@Test
public void testNoSuchMethodNotification() {
List<JsonRpcResponse> responses1 = dispatcher.dispatch(Collections.singletonList(JsonRpcRequest.notification("api.doesNotExist")));
assertEquals(0, responses1.size());
}
@Test
public void testBatches() {
List<JsonRpcRequest> requests = new ArrayList<>();
requests.add(JsonRpcRequest.create(1L, "api.test", "A", "B"));
requests.add(JsonRpcRequest.notification("api.doesNotExist"));
requests.add(JsonRpcRequest.create(2L, "api.doesNotExist", "A", "B"));
List<JsonRpcResponse> responses = dispatcher.dispatch(requests);
assertEquals(2, responses.size());
JsonRpcResponse ok = responses.get(0);
assertEquals(JsonRpcVersion.VERSION_2_0, ok.getVersion());
assertEquals(1L, (long) ok.getId());
assertEquals("AB", ok.getResult());
assertEquals(null, ok.getError());
JsonRpcResponse missing = responses.get(1);
assertEquals(JsonRpcVersion.VERSION_2_0, missing.getVersion());
assertEquals(2L, (long) missing.getId());
assertEquals(null, missing.getResult());
JsonRpcErrorResponse error1 = missing.getError();
assertNotNull(error1);
assertEquals(JsonRpcErrorCode.MethodNotFound.getCode(), error1.getCode());
}
@JsonRpcNamespace("api")
public static class Api {
@JsonRpc
public void test() {
}
@JsonRpc
public void test(String a) {
}
@JsonRpc
public String test(String a, String b) {
return a + b;
}
@JsonRpc
public void failing() {
throw new RuntimeException();
}
}
}
| mit |
motokito/jabref | src/test/java/net/sf/jabref/external/RegExpFileSearchTests.java | 6975 | /* Copyright (C) 2003-2015 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.external;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.sf.jabref.Globals;
import net.sf.jabref.logic.importer.ImportFormatPreferences;
import net.sf.jabref.logic.importer.ParserResult;
import net.sf.jabref.logic.importer.fileformat.BibtexParser;
import net.sf.jabref.logic.layout.format.NameFormatter;
import net.sf.jabref.model.database.BibDatabase;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.BibtexEntryTypes;
import net.sf.jabref.preferences.JabRefPreferences;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RegExpFileSearchTests {
private static final String filesDirectory = "src/test/resources/net/sf/jabref/imports/unlinkedFilesTestFolder";
private BibDatabase database;
private BibEntry entry;
@Before
public void setUp() throws IOException {
Globals.prefs = JabRefPreferences.getInstance();
StringReader reader = new StringReader(
"@ARTICLE{HipKro03," + "\n" + " author = {Eric von Hippel and Georg von Krogh}," + "\n"
+ " title = {Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science},"
+ "\n" + " journal = {Organization Science}," + "\n" + " year = {2003}," + "\n"
+ " volume = {14}," + "\n" + " pages = {209--223}," + "\n" + " number = {2}," + "\n"
+ " address = {Institute for Operations Research and the Management Sciences (INFORMS), Linthicum, Maryland, USA},"
+ "\n" + " doi = {http://dx.doi.org/10.1287/orsc.14.2.209.14992}," + "\n"
+ " issn = {1526-5455}," + "\n" + " publisher = {INFORMS}" + "\n" + "}");
BibtexParser parser = new BibtexParser(reader, ImportFormatPreferences.fromPreferences(Globals.prefs));
ParserResult result = null;
result = parser.parse();
database = result.getDatabase();
entry = database.getEntryByKey("HipKro03").get();
Assert.assertNotNull(database);
Assert.assertNotNull(entry);
}
@Test
public void testFindFiles() {
//given
List<BibEntry> entries = new ArrayList<>();
BibEntry localEntry = new BibEntry("123", BibtexEntryTypes.ARTICLE.getName());
localEntry.setCiteKey("pdfInDatabase");
localEntry.setField("year", "2001");
entries.add(localEntry);
List<String> extensions = Arrays.asList("pdf");
List<File> dirs = Arrays.asList(new File(filesDirectory));
//when
Map<BibEntry, java.util.List<File>> result = RegExpFileSearch.findFilesForSet(entries, extensions, dirs,
"**/[bibtexkey].*\\\\.[extension]");
//then
assertEquals(1, result.keySet().size());
}
@Test
public void testFieldAndFormat() {
assertEquals("Eric von Hippel and Georg von Krogh",
RegExpFileSearch.getFieldAndFormat("[author]", entry, database));
assertEquals("Eric von Hippel and Georg von Krogh",
RegExpFileSearch.getFieldAndFormat("author", entry, database));
assertEquals("", RegExpFileSearch.getFieldAndFormat("[unknownkey]", entry, database));
assertEquals("", RegExpFileSearch.getFieldAndFormat("[:]", entry, database));
assertEquals("", RegExpFileSearch.getFieldAndFormat("[:lower]", entry, database));
assertEquals("eric von hippel and georg von krogh",
RegExpFileSearch.getFieldAndFormat("[author:lower]", entry, database));
assertEquals("HipKro03", RegExpFileSearch.getFieldAndFormat("[bibtexkey]", entry, database));
assertEquals("HipKro03", RegExpFileSearch.getFieldAndFormat("[bibtexkey:]", entry, database));
}
@Test
@Ignore
public void testUserFieldAndFormat() {
List<String> names = Globals.prefs.getStringList(NameFormatter.NAME_FORMATER_KEY);
List<String> formats = Globals.prefs.getStringList(NameFormatter.NAME_FORMATTER_VALUE);
try {
List<String> f = new LinkedList<>(formats);
List<String> n = new LinkedList<>(names);
n.add("testMe123454321");
f.add("*@*@test");
Globals.prefs.putStringList(NameFormatter.NAME_FORMATER_KEY, n);
Globals.prefs.putStringList(NameFormatter.NAME_FORMATTER_VALUE, f);
assertEquals("testtest", RegExpFileSearch.getFieldAndFormat("[author:testMe123454321]", entry, database));
} finally {
Globals.prefs.putStringList(NameFormatter.NAME_FORMATER_KEY, names);
Globals.prefs.putStringList(NameFormatter.NAME_FORMATTER_VALUE, formats);
}
}
@Test
public void testExpandBrackets() {
assertEquals("", RegExpFileSearch.expandBrackets("", entry, database));
assertEquals("dropped", RegExpFileSearch.expandBrackets("drop[unknownkey]ped", entry, database));
assertEquals("Eric von Hippel and Georg von Krogh",
RegExpFileSearch.expandBrackets("[author]", entry, database));
assertEquals("Eric von Hippel and Georg von Krogh are two famous authors.",
RegExpFileSearch.expandBrackets("[author] are two famous authors.", entry, database));
assertEquals("Eric von Hippel and Georg von Krogh are two famous authors.",
RegExpFileSearch.expandBrackets("[author] are two famous authors.", entry, database));
assertEquals(
"Eric von Hippel and Georg von Krogh have published Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science in Organization Science.",
RegExpFileSearch.expandBrackets("[author] have published [title] in [journal].", entry, database));
}
@After
public void tearDown(){
Globals.prefs = null;
}
}
| mit |
archimatetool/archi | com.archimatetool.model/src/com/archimatetool/model/IStrategyElement.java | 560 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.model;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Strategy Element</b></em>'.
* <!-- end-user-doc -->
*
*
* @see com.archimatetool.model.IArchimatePackage#getStrategyElement()
* @model interface="true" abstract="true"
* @generated
*/
public interface IStrategyElement extends IArchimateElement {
} // IStrategyElement
| mit |
overleaf/writelatex-git-bridge | src/main/java/uk/ac/ic/wlgitbridge/data/filestore/RawFile.java | 1223 | package uk.ac.ic.wlgitbridge.data.filestore;
import uk.ac.ic.wlgitbridge.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
/**
* Created by Winston on 16/11/14.
*/
public abstract class RawFile {
public abstract String getPath();
public abstract byte[] getContents();
public abstract long size();
public final void writeToDisk(File directory) throws IOException {
writeToDiskWithName(directory, getPath());
}
public final void writeToDiskWithName(File directory, String name) throws IOException {
File file = new File(directory, name);
file.getParentFile().mkdirs();
file.createNewFile();
OutputStream out = new FileOutputStream(file);
out.write(getContents());
out.close();
Log.info("Wrote file: {}", file.getAbsolutePath());
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RawFile)) {
return false;
}
RawFile that = (RawFile) obj;
return getPath().equals(that.getPath())
&& Arrays.equals(getContents(), that.getContents());
}
}
| mit |
SullyJHF/learn-to-code | done/maze/src/maze/Maze.java | 1769 | package maze;
import javax.swing.JFrame;
public class Maze extends JFrame implements Runnable {
private Thread thread;
private Screen screen;
private boolean running = false;
private final int UPS = 30;
public Maze() {
super("Game Loop");
screen = new Screen();
add(screen);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public synchronized void start() {
if (running) return;
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
if (!running) return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
double secondsPerTick = 1.0 / UPS;
double nextTime = System.nanoTime() / 1000000000.0;
double maxTimeDiff = 0.5;
int skippedFrames = 1;
int maxSkippedFrames = 5;
while (running) {
double curTime = System.nanoTime() / 1000000000.0;
if ((curTime - nextTime) > maxTimeDiff) nextTime = curTime;
if (curTime >= nextTime) {
// do update code, this will get run UPS times a second
screen.tick();
nextTime += secondsPerTick;
if ((curTime < nextTime) || (skippedFrames > maxSkippedFrames)) {
// do rendering code
screen.render();
skippedFrames = 1;
} else {
++skippedFrames;
}
} else {
int sleepTime = (int) (1000.0 * (nextTime - curTime));
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
| mit |
vitrivr/cineast | cineast-api/src/main/java/org/vitrivr/cineast/api/rest/handlers/actions/feature/FindFeaturesByCategoryGetHandler.java | 2064 | package org.vitrivr.cineast.api.rest.handlers.actions.feature;
import static org.vitrivr.cineast.api.util.APIConstants.CATEGORY_NAME;
import io.javalin.http.Context;
import io.javalin.plugin.openapi.dsl.OpenApiBuilder;
import io.javalin.plugin.openapi.dsl.OpenApiDocumentation;
import java.util.Map;
import org.vitrivr.cineast.api.messages.lookup.IdList;
import org.vitrivr.cineast.api.messages.result.FeaturesByCategoryQueryResult;
import org.vitrivr.cineast.api.rest.OpenApiCompatHelper;
import org.vitrivr.cineast.api.rest.handlers.interfaces.ParsingPostRestHandler;
import org.vitrivr.cineast.api.util.QueryUtil;
/**
* Handler for the API call to retrieve all features for all objects for a given category.
*/
public class FindFeaturesByCategoryGetHandler implements ParsingPostRestHandler<IdList, FeaturesByCategoryQueryResult> {
public static final String ROUTE = "find/feature/all/by/category/{" + CATEGORY_NAME + "}";
@Override
public FeaturesByCategoryQueryResult performPost(IdList idList, Context ctx) {
final Map<String, String> parameters = ctx.pathParamMap();
// Category name from path params.
final String cat = parameters.get(CATEGORY_NAME);
return QueryUtil.retrieveFeaturesForCategory(cat, idList.getIdList());
}
@Override
public Class<IdList> inClass() {
return IdList.class;
}
@Override
public Class<FeaturesByCategoryQueryResult> outClass() {
return FeaturesByCategoryQueryResult.class;
}
@Override
public String route() {
return ROUTE;
}
@Override
public OpenApiDocumentation docs() {
return OpenApiBuilder.document()
.operation(op -> {
op.operationId("findFeaturesByCategory");
op.description("Find features for the given category for all (or specific) IDs");
op.summary("Find features for the given category for all (or specific) IDs");
op.addTagsItem(OpenApiCompatHelper.METADATA_OAS_TAG);
})
.pathParam(CATEGORY_NAME, String.class)
.body(inClass())
.json("200", outClass());
}
}
| mit |
dotwebstack/dotwebstack-framework | ext/ext-rml/src/main/java/org/dotwebstack/framework/ext/rml/mapping/Notation3RmlBodyMapper.java | 962 | package org.dotwebstack.framework.ext.rml.mapping;
import com.taxonic.carml.engine.rdf.RdfRmlMapper;
import com.taxonic.carml.model.TriplesMap;
import graphql.GraphQL;
import io.swagger.v3.oas.models.Operation;
import java.util.Map;
import java.util.Set;
import org.eclipse.rdf4j.model.Namespace;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
@Component
public class Notation3RmlBodyMapper extends AbstractRmlBodyMapper {
static final MediaType N3_MEDIA_TYPE = MediaType.parseMediaType("text/n3");
Notation3RmlBodyMapper(GraphQL graphQL, RdfRmlMapper rmlMapper, Map<Operation, Set<TriplesMap>> mappingsPerOperation,
Set<Namespace> namespaces) {
super(graphQL, rmlMapper, mappingsPerOperation, namespaces);
}
@Override
MediaType supportedMediaType() {
return N3_MEDIA_TYPE;
}
@Override
RDFFormat rdfFormat() {
return RDFFormat.N3;
}
}
| mit |
eXsio/clock | src/main/java/com/exsio/clock/service/i18n/SystemLocaleProviderFactory.java | 746 | package com.exsio.clock.service.i18n;
import com.exsio.clock.util.LocaleValidator;
import org.springframework.stereotype.Service;
import pl.exsio.jin.locale.provider.DefaultLocaleProviderImpl;
import pl.exsio.jin.locale.provider.LocaleProvider;
import pl.exsio.jin.locale.provider.factory.LocaleProviderFactory;
@Service
public class SystemLocaleProviderFactory implements LocaleProviderFactory {
private final LocaleProvider localeProvider;
public SystemLocaleProviderFactory() {
localeProvider = new DefaultLocaleProviderImpl(
LocaleValidator.validate(System.getProperty("user.language"))
);
}
@Override
public LocaleProvider getLocaleProvider() {
return localeProvider;
}
}
| mit |
PoJD/hawa | security/src/main/java/cz/pojd/security/event/SimpleStringTranslator.java | 1484 | package cz.pojd.security.event;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
/**
* Translates security events into a string. Might be simpler to use velocity, but seems like a waste of additional jars. The below should be simple
* enough to keep as a string here.
*
* @author Lubos Housa
* @since Nov 25, 2014 11:56:42 PM
*/
public class SimpleStringTranslator implements SecurityEventTranslator<String> {
private DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public String translate(SecurityEvent securityEvent) {
return "<html><body>" +
"<h3>Dear owner,</h3><br/>" +
"a security breach was detected at the house, see more details below: <br/><br/>" +
"<table><tbody>" +
(securityEvent.getType() != null ? "<tr><th>Type</th><td>" + securityEvent.getType().getName() + "</td>" : "") +
(securityEvent.getDetail() != null ? "<tr><th>Detail</th><td>" + securityEvent.getDetail() + "</td>" : "") +
(securityEvent.getSource() != null ? "<tr><th>Where</th><td>" + securityEvent.getSource().getName() + "</td>"
+ "<tr><th>Floor</th><td>" + securityEvent.getSource().getFloor() + "</td>" : "") +
(securityEvent.getFilePath() != null ? "<tr><th>File path</th><td>" + securityEvent.getFilePath() + "</td>" : "") +
(securityEvent.getAt() != null ? "<tr><th>When</th><td>" + formatter.print(securityEvent.getAt()) + "</td>" : "") +
"</tbody></table>" +
"</body></html>";
}
}
| mit |
noogotte/CWJ | src/main/java/fr/aumgn/cwj/i18n/Localization.java | 1719 | package fr.aumgn.cwj.i18n;
import static com.google.common.base.Preconditions.checkNotNull;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
/**
* A set of messages loaded with {@link I18n} for a given {@link Locale}.
*/
public class Localization {
private final Map<String, MessageFormat> map;
public Localization(ImmutableMap.Builder<String, MessageFormat> mapBuilder) {
this.map = checkNotNull(mapBuilder).build();
}
public boolean has(String key) {
return map.containsKey(checkNotNull(key));
}
public String get(String key, Object... arguments) {
String message = rawGet(key, arguments);
if (message == null) {
return keyNotFound(key);
}
return message;
}
public String get(String[] keys, Object... arguments) {
Preconditions.checkArgument(keys.length > 0, "Keys can't be empty");
for (String key : keys) {
String message = rawGet(key, arguments);
if (message != null) {
return message;
}
}
return keyNotFound(keys[keys.length - 1]);
}
private String keyNotFound(String key) {
return "## Missing message for key \"" + key + "\" ##";
}
private String rawGet(String key, Object... arguments) {
checkNotNull(key);
if (!map.containsKey(key)) {
return null;
}
MessageFormat message = map.get(key);
return message.format(arguments);
}
public Set<String> keys() {
return map.keySet();
}
}
| mit |
tckz916/BlastAdmin | src/main/java/com/github/tckz916/blastadmin/BlastAdmin.java | 2385 | package com.github.tckz916.blastadmin;
import com.github.tckz916.blastadmin.command.tabcomplete.GamemodeTabComplete;
import com.github.tckz916.blastadmin.command.tabcomplete.PrefixTabComple;
import com.github.tckz916.blastadmin.listener.PlayerListener;
import com.github.tckz916.blastadmin.message.Message;
import com.github.tckz916.blastadmin.message.MessageFormat;
import org.bukkit.command.TabCompleter;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Created by tckz916 on 2015/07/20.
*/
public class BlastAdmin extends JavaPlugin {
private static BlastAdmin instance = null;
private Message message = null;
private MessageFormat messageFormat = null;
@Override
public void onEnable() {
super.onEnable();
instance = this;
message = new Message();
messageFormat = new MessageFormat();
saveDefaultConfig();
reloadConfig();
registercommand("blastadmin");
registercommand("day");
registercommand("gamemode");
registercommand("iteminfo");
registercommand("night");
registercommand("mobhead");
registercommand("prefix");
registercommand("serverinfo");
registercommand("setspawn");
registercommand("spawn");
registercommand("tp");
registercommand("tpa");
registercommand("tphere");
registercommand("whois");
registercommand("tell");
registercommand("reply");
registertabcomplete("prefix", new PrefixTabComple());
registertabcomplete("gamemode", new GamemodeTabComplete());
registerlistener(new PlayerListener());
}
@Override
public void onDisable() {
super.onDisable();
}
private void registercommand(String cmd) {
getCommand(cmd).setExecutor(new BlastAdminCommandHandler());
}
private void registertabcomplete(String cmd, TabCompleter completer) {
getCommand(cmd).setTabCompleter(completer);
}
private void registerlistener(Listener listener) {
this.getServer().getPluginManager().registerEvents(listener, this);
}
public Message getMessage() {
return message;
}
public MessageFormat getMessageFormat() {
return messageFormat;
}
public static BlastAdmin getInstance() {
return instance;
}
}
| mit |
Nilbog21/EMRMS | src/test/java/edu/psu/sweng500/emrms/util/TestingUtilitiesTest.java | 221 | package edu.psu.sweng500.emrms.util;
import org.junit.Test;
public class TestingUtilitiesTest {
@Test
public void placeholderTest() {
TestingUtilities testingUtilities = new TestingUtilities();
}
} | mit |
RawLauncher/RawLauncher | app/src/main/java/com/sjcqs/rawlauncher/items/device_settings/DeviceSetting.java | 639 | package com.sjcqs.rawlauncher.items.device_settings;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import com.sjcqs.rawlauncher.items.Item;
/**
* Created by satyan on 8/27/17.
*/
class DeviceSetting extends Item {
private final String action;
public DeviceSetting(String action, String label, Drawable drawable, Intent intent) {
super(label,drawable,intent);
this.action = action;
}
@Override
public String getInput() {
return super.getInput();
}
@Override
public String toString() {
return super.toString() + "("+ action + ")";
}
}
| mit |
citeaux/JAHAP | src/main/java/org/jahap/business/acc/AccountInfo.java | 2624 | /*
* The MIT License
*
* Copyright 2014 Sebastian Russ <citeaux at https://github.com/citeaux/JAHAP>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jahap.business.acc;
import java.util.Date;
/**
*
* @author russ
*/
public class AccountInfo{
private String id;
private Date arrivaldate;
private Date departuredate;
private String name;
private Double balance;
public AccountInfo(String id, Date arrivaldate, Date departuredate, String Name,double balance) {
this.id = id;
this.arrivaldate = arrivaldate;
this.departuredate = departuredate;
this.name = Name;
this.balance=balance;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getArrivaldate() {
return arrivaldate;
}
public void setArrivaldate(Date arrivaldate) {
this.arrivaldate = arrivaldate;
}
public Date getDeparturedate() {
return departuredate;
}
public void setDeparturedate(Date departuredate) {
this.departuredate = departuredate;
}
public String getName() {
return name;
}
public void setName(String Name) {
this.name = Name;
}
public double getBalance() {
return balance;
}
public void setBalance(double Balance) {
this.balance = Balance;
}
} | mit |
getsandbox/jliquid-liqp | src/test/java/org/jliquid/liqp/filters/SortTest.java | 2268 | package org.jliquid.liqp.filters;
import java.util.HashMap;
import org.jliquid.liqp.Template;
import org.antlr.runtime.RecognitionException;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class SortTest {
@Test
public void applyTest() throws RecognitionException {
String json =
"{" +
" \"words\" : [\"2\", \"13\", \"1\"], " +
" \"numbers\" : [2, 13, 1] " +
"}";
String[][] tests = {
{"{{ x | sort }}", ""},
{"{{ words | sort }}", "1132"},
{"{{ numbers | sort }}", "1213"},
{"{{ numbers | sort | last }}", "13"},
{"{{ numbers | sort | first }}", "1"},
};
for (String[] test : tests) {
Template template = Template.parse(test[0]);
String rendered = String.valueOf(template.render(json));
assertThat(rendered, is(test[1]));
}
}
/*
* def test_sort
* assert_equal [1,2,3,4], @filters.sort([4,3,2,1])
* assert_equal [{"a" => 1}, {"a" => 2}, {"a" => 3}, {"a" => 4}], @filters.sort([{"a" => 4}, {"a" => 3}, {"a" => 1}, {"a" => 2}], "a")
* end
*/
@Test
public void applyOriginalTest() {
Filter filter = Filter.getFilter("sort");
assertThat(filter.apply(new Integer[]{4,3,2,1}), is((Object)new Integer[]{1,2,3,4}));
java.util.Map[] unsorted = new java.util.Map[]{
new HashMap<String, Integer>(){{ put("a", 4); }},
new HashMap<String, Integer>(){{ put("a", 3); }},
new HashMap<String, Integer>(){{ put("a", 2); }},
new HashMap<String, Integer>(){{ put("a", 1); }}
};
java.util.Map[] sorted = (Sort.SortableMap[])filter.apply(unsorted, "a");
java.util.Map[] expected = new java.util.Map[]{
new HashMap<String, Integer>(){{ put("a", 1); }},
new HashMap<String, Integer>(){{ put("a", 2); }},
new HashMap<String, Integer>(){{ put("a", 3); }},
new HashMap<String, Integer>(){{ put("a", 4); }}
};
assertThat(sorted, is(expected));
}
}
| mit |
eric-kansas/robolectric | robolectric/src/main/java/org/robolectric/RobolectricTestRunner.java | 24103 | package org.robolectric;
import android.app.Application;
import android.os.Build;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.internal.AssumptionViolatedException;
import org.junit.internal.runners.model.EachTestNotifier;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;
import org.robolectric.annotation.*;
import org.robolectric.internal.InstrumentingClassLoaderFactory;
import org.robolectric.internal.bytecode.*;
import org.robolectric.internal.dependency.CachedDependencyResolver;
import org.robolectric.internal.dependency.DependencyResolver;
import org.robolectric.internal.dependency.LocalDependencyResolver;
import org.robolectric.internal.dependency.MavenDependencyResolver;
import org.robolectric.internal.ParallelUniverse;
import org.robolectric.internal.ParallelUniverseInterface;
import org.robolectric.internal.SdkConfig;
import org.robolectric.internal.SdkEnvironment;
import org.robolectric.manifest.AndroidManifest;
import org.robolectric.res.Fs;
import org.robolectric.res.FsFile;
import org.robolectric.res.OverlayResourceLoader;
import org.robolectric.res.PackageResourceLoader;
import org.robolectric.res.ResourceLoader;
import org.robolectric.res.ResourcePath;
import org.robolectric.res.RoutingResourceLoader;
import org.robolectric.util.Logger;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.Pair;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.security.SecureRandom;
import java.util.*;
/**
* Installs a {@link org.robolectric.internal.bytecode.InstrumentingClassLoader} and
* {@link org.robolectric.res.ResourceLoader} in order to provide a simulation of the Android runtime environment.
*/
public class RobolectricTestRunner extends BlockJUnit4ClassRunner {
private static final String CONFIG_PROPERTIES = "robolectric.properties";
private static final Config DEFAULT_CONFIG = new Config.Implementation(defaultsFor(Config.class));
private static final Map<Pair<AndroidManifest, SdkConfig>, ResourceLoader> resourceLoadersByManifestAndConfig = new HashMap<>();
private static final Map<ManifestIdentifier, AndroidManifest> appManifestsByFile = new HashMap<>();
private static ShadowMap mainShadowMap;
private InstrumentingClassLoaderFactory instrumentingClassLoaderFactory;
private TestLifecycle<Application> testLifecycle;
private DependencyResolver dependencyResolver;
static {
new SecureRandom(); // this starts up the Poller SunPKCS11-Darwin thread early, outside of any Robolectric classloader
}
private final HashSet<Class<?>> loadedTestClasses = new HashSet<>();
/**
* Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file
* and res directory by default. Use the {@link Config} annotation to configure.
*
* @param testClass the test class to be run
* @throws InitializationError if junit says so
*/
public RobolectricTestRunner(final Class<?> testClass) throws InitializationError {
super(testClass);
}
@SuppressWarnings("unchecked")
private void assureTestLifecycle(SdkEnvironment sdkEnvironment) {
try {
ClassLoader robolectricClassLoader = sdkEnvironment.getRobolectricClassLoader();
testLifecycle = (TestLifecycle) robolectricClassLoader.loadClass(getTestLifecycleClass().getName()).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
protected DependencyResolver getJarResolver() {
if (dependencyResolver == null) {
if (Boolean.getBoolean("robolectric.offline")) {
String dependencyDir = System.getProperty("robolectric.dependency.dir", ".");
dependencyResolver = new LocalDependencyResolver(new File(dependencyDir));
} else {
File cacheDir = new File(new File(System.getProperty("java.io.tmpdir")), "robolectric");
cacheDir.mkdir();
if (cacheDir.exists()) {
Logger.info("Dependency cache location: %s", cacheDir.getAbsolutePath());
dependencyResolver = new CachedDependencyResolver(new MavenDependencyResolver(), cacheDir, 60 * 60 * 24 * 1000);
} else {
dependencyResolver = new MavenDependencyResolver();
}
}
}
return dependencyResolver;
}
protected ClassHandler createClassHandler(ShadowMap shadowMap, SdkConfig sdkConfig) {
return new ShadowWrangler(shadowMap);
}
protected AndroidManifest createAppManifest(FsFile manifestFile, FsFile resDir, FsFile assetDir, String packageName) {
if (!manifestFile.exists()) {
System.out.print("WARNING: No manifest file found at " + manifestFile.getPath() + ".");
System.out.println("Falling back to the Android OS resources only.");
System.out.println("To remove this warning, annotate your test class with @Config(manifest=Config.NONE).");
return null;
}
Logger.debug("Robolectric assets directory: " + assetDir.getPath());
Logger.debug(" Robolectric res directory: " + resDir.getPath());
Logger.debug(" Robolectric manifest path: " + manifestFile.getPath());
Logger.debug(" Robolectric package name: " + packageName);
return new AndroidManifest(manifestFile, resDir, assetDir, packageName);
}
public InstrumentationConfiguration createClassLoaderConfig() {
return InstrumentationConfiguration.newBuilder().build();
}
protected Class<? extends TestLifecycle> getTestLifecycleClass() {
return DefaultTestLifecycle.class;
}
public static void injectClassHandler(ClassLoader robolectricClassLoader, ClassHandler classHandler) {
String className = RobolectricInternals.class.getName();
Class<?> robolectricInternalsClass = ReflectionHelpers.loadClass(robolectricClassLoader, className);
ReflectionHelpers.setStaticField(robolectricInternalsClass, "classHandler", classHandler);
}
@Override
protected Statement classBlock(RunNotifier notifier) {
final Statement statement = childrenInvoker(notifier);
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
statement.evaluate();
for (Class<?> testClass : loadedTestClasses) {
invokeAfterClass(testClass);
}
} finally {
afterClass();
loadedTestClasses.clear();
}
}
};
}
private static void invokeAfterClass(final Class<?> clazz) throws Throwable {
final TestClass testClass = new TestClass(clazz);
final List<FrameworkMethod> afters = testClass.getAnnotatedMethods(AfterClass.class);
for (FrameworkMethod after : afters) {
after.invokeExplosively(null);
}
}
@Override
protected void runChild(FrameworkMethod method, RunNotifier notifier) {
Description description = describeChild(method);
EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
final Config config = getConfig(method.getMethod());
if (shouldIgnore(method, config)) {
eachNotifier.fireTestIgnored();
} else if(shouldRunApiVersion(config)) {
eachNotifier.fireTestStarted();
try {
AndroidManifest appManifest = getAppManifest(config);
if (instrumentingClassLoaderFactory == null) {
instrumentingClassLoaderFactory = new InstrumentingClassLoaderFactory(createClassLoaderConfig(), getJarResolver());
}
SdkEnvironment sdkEnvironment = instrumentingClassLoaderFactory.getSdkEnvironment(new SdkConfig(pickSdkVersion(config, appManifest)));
methodBlock(method, config, appManifest, sdkEnvironment).evaluate();
} catch (AssumptionViolatedException e) {
eachNotifier.addFailedAssumption(e);
} catch (Throwable e) {
eachNotifier.addFailure(e);
} finally {
eachNotifier.fireTestFinished();
}
}
}
protected boolean shouldRunApiVersion(Config config) {
return true;
}
protected boolean shouldIgnore(FrameworkMethod method, Config config) {
return method.getAnnotation(Ignore.class) != null;
}
private ParallelUniverseInterface parallelUniverseInterface;
private Statement methodBlock(final FrameworkMethod method, final Config config, final AndroidManifest appManifest, final SdkEnvironment sdkEnvironment) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
// Configure shadows *BEFORE* setting the ClassLoader. This is necessary because
// creating the ShadowMap loads all ShadowProviders via ServiceLoader and this is
// not available once we install the Robolectric class loader.
configureShadows(sdkEnvironment, config);
Thread.currentThread().setContextClassLoader(sdkEnvironment.getRobolectricClassLoader());
Class bootstrappedTestClass = sdkEnvironment.bootstrappedClass(getTestClass().getJavaClass());
HelperTestRunner helperTestRunner = getHelperTestRunner(bootstrappedTestClass);
final Method bootstrappedMethod;
try {
//noinspection unchecked
bootstrappedMethod = bootstrappedTestClass.getMethod(method.getName());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
parallelUniverseInterface = getHooksInterface(sdkEnvironment);
try {
try {
// Only invoke @BeforeClass once per class
if (!loadedTestClasses.contains(bootstrappedTestClass)) {
invokeBeforeClass(bootstrappedTestClass);
}
assureTestLifecycle(sdkEnvironment);
parallelUniverseInterface.resetStaticState(config);
parallelUniverseInterface.setSdkConfig(sdkEnvironment.getSdkConfig());
int sdkVersion = pickSdkVersion(config, appManifest);
ReflectionHelpers.setStaticField(sdkEnvironment.bootstrappedClass(Build.VERSION.class), "SDK_INT", sdkVersion);
ResourceLoader systemResourceLoader = sdkEnvironment.getSystemResourceLoader(getJarResolver());
setUpApplicationState(bootstrappedMethod, parallelUniverseInterface, systemResourceLoader, appManifest, config);
testLifecycle.beforeTest(bootstrappedMethod);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
final Statement statement = helperTestRunner.methodBlock(new FrameworkMethod(bootstrappedMethod));
// todo: this try/finally probably isn't right -- should mimic RunAfters? [xw]
try {
statement.evaluate();
} finally {
try {
parallelUniverseInterface.tearDownApplication();
} finally {
try {
internalAfterTest(bootstrappedMethod);
} finally {
parallelUniverseInterface.resetStaticState(config); // afterward too, so stuff doesn't hold on to classes?
// todo: is this really needed?
Thread.currentThread().setContextClassLoader(RobolectricTestRunner.class.getClassLoader());
}
}
}
} finally {
parallelUniverseInterface = null;
}
}
};
}
private void invokeBeforeClass(final Class clazz) throws Throwable {
if (!loadedTestClasses.contains(clazz)) {
loadedTestClasses.add(clazz);
final TestClass testClass = new TestClass(clazz);
final List<FrameworkMethod> befores = testClass.getAnnotatedMethods(BeforeClass.class);
for (FrameworkMethod before : befores) {
before.invokeExplosively(null);
}
}
}
protected HelperTestRunner getHelperTestRunner(Class bootstrappedTestClass) {
try {
return new HelperTestRunner(bootstrappedTestClass);
} catch (InitializationError initializationError) {
throw new RuntimeException(initializationError);
}
}
protected AndroidManifest getAppManifest(Config config) {
if (config.manifest().equals(Config.NONE)) {
return null;
}
String manifestProperty = System.getProperty("android.manifest");
String resourcesProperty = System.getProperty("android.resources");
String assetsProperty = System.getProperty("android.assets");
String packageName = System.getProperty("android.package");
FsFile baseDir;
FsFile manifestFile;
FsFile resDir;
FsFile assetDir;
boolean defaultManifest = config.manifest().equals(Config.DEFAULT);
if (defaultManifest && manifestProperty != null) {
manifestFile = Fs.fileFromPath(manifestProperty);
baseDir = manifestFile.getParent();
} else {
manifestFile = getBaseDir().join(defaultManifest ? AndroidManifest.DEFAULT_MANIFEST_NAME : config.manifest());
baseDir = manifestFile.getParent();
}
boolean defaultRes = Config.DEFAULT_RES_FOLDER.equals(config.resourceDir());
if (defaultRes && resourcesProperty != null) {
resDir = Fs.fileFromPath(resourcesProperty);
} else {
resDir = baseDir.join(config.resourceDir());
}
boolean defaultAssets = Config.DEFAULT_ASSET_FOLDER.equals(config.assetDir());
if (defaultAssets && assetsProperty != null) {
assetDir = Fs.fileFromPath(assetsProperty);
} else {
assetDir = baseDir.join(config.assetDir());
}
String configPackageName = config.packageName();
if (configPackageName != null && !configPackageName.isEmpty()) {
packageName = configPackageName;
}
List<FsFile> libraryDirs = null;
if (config.libraries().length > 0) {
libraryDirs = new ArrayList<>();
for (String libraryDirName : config.libraries()) {
libraryDirs.add(baseDir.join(libraryDirName));
}
}
ManifestIdentifier identifier = new ManifestIdentifier(manifestFile, resDir, assetDir, packageName, libraryDirs);
synchronized (appManifestsByFile) {
AndroidManifest appManifest;
appManifest = appManifestsByFile.get(identifier);
if (appManifest == null) {
appManifest = createAppManifest(manifestFile, resDir, assetDir, packageName);
if (libraryDirs != null) {
appManifest.setLibraryDirectories(libraryDirs);
}
appManifestsByFile.put(identifier, appManifest);
}
return appManifest;
}
}
protected FsFile getBaseDir() {
return Fs.currentDirectory();
}
public Config getConfig(Method method) {
Config config = DEFAULT_CONFIG;
Config globalConfig = Config.Implementation.fromProperties(getConfigProperties());
if (globalConfig != null) {
config = new Config.Implementation(config, globalConfig);
}
Config methodClassConfig = method.getDeclaringClass().getAnnotation(Config.class);
if (methodClassConfig != null) {
config = new Config.Implementation(config, methodClassConfig);
}
ArrayList<Class> testClassHierarchy = new ArrayList<>();
Class testClass = getTestClass().getJavaClass();
while (testClass != null) {
testClassHierarchy.add(0, testClass);
testClass = testClass.getSuperclass();
}
for (Class clazz : testClassHierarchy) {
Config classConfig = (Config) clazz.getAnnotation(Config.class);
if (classConfig != null) {
config = new Config.Implementation(config, classConfig);
}
}
Config methodConfig = method.getAnnotation(Config.class);
if (methodConfig != null) {
config = new Config.Implementation(config, methodConfig);
}
return config;
}
protected Properties getConfigProperties() {
ClassLoader classLoader = getClass().getClassLoader();
try (InputStream resourceAsStream = classLoader.getResourceAsStream(CONFIG_PROPERTIES)) {
if (resourceAsStream == null) return null;
Properties properties = new Properties();
properties.load(resourceAsStream);
return properties;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected void configureShadows(SdkEnvironment sdkEnvironment, Config config) {
ShadowMap shadowMap = createShadowMap();
if (config != null) {
Class<?>[] shadows = config.shadows();
if (shadows.length > 0) {
shadowMap = shadowMap.newBuilder().addShadowClasses(shadows).build();
}
}
ClassHandler classHandler = getClassHandler(sdkEnvironment, shadowMap);
injectClassHandler(sdkEnvironment.getRobolectricClassLoader(), classHandler);
}
private ClassHandler getClassHandler(SdkEnvironment sdkEnvironment, ShadowMap shadowMap) {
ClassHandler classHandler;
synchronized (sdkEnvironment) {
classHandler = sdkEnvironment.classHandlersByShadowMap.get(shadowMap);
if (classHandler == null) {
classHandler = createClassHandler(shadowMap, sdkEnvironment.getSdkConfig());
}
}
return classHandler;
}
protected void setUpApplicationState(Method method, ParallelUniverseInterface parallelUniverseInterface, ResourceLoader systemResourceLoader, AndroidManifest appManifest, Config config) {
parallelUniverseInterface.setUpApplicationState(method, testLifecycle, systemResourceLoader, appManifest, config);
}
protected int pickSdkVersion(Config config, AndroidManifest manifest) {
if (config != null && config.sdk().length > 1) {
throw new IllegalArgumentException("RobolectricTestRunner does not support multiple values for @Config.sdk");
} else if (config != null && config.sdk().length == 1) {
return config.sdk()[0];
} else if (manifest != null) {
return manifest.getTargetSdkVersion();
} else {
return SdkConfig.FALLBACK_SDK_VERSION;
}
}
private ParallelUniverseInterface getHooksInterface(SdkEnvironment sdkEnvironment) {
ClassLoader robolectricClassLoader = sdkEnvironment.getRobolectricClassLoader();
try {
Class<?> clazz = robolectricClassLoader.loadClass(ParallelUniverse.class.getName());
Class<? extends ParallelUniverseInterface> typedClazz = clazz.asSubclass(ParallelUniverseInterface.class);
Constructor<? extends ParallelUniverseInterface> constructor = typedClazz.getConstructor(RobolectricTestRunner.class);
return constructor.newInstance(this);
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public void internalAfterTest(final Method method) {
testLifecycle.afterTest(method);
}
private void afterClass() {
testLifecycle = null;
}
@TestOnly
boolean allStateIsCleared() {
return testLifecycle == null;
}
@Override
public Object createTest() throws Exception {
throw new UnsupportedOperationException("this should always be invoked on the HelperTestRunner!");
}
public final ResourceLoader getAppResourceLoader(SdkConfig sdkConfig, ResourceLoader systemResourceLoader, final AndroidManifest appManifest) {
Pair<AndroidManifest, SdkConfig> androidManifestSdkConfigPair = new Pair<>(appManifest, sdkConfig);
ResourceLoader resourceLoader = resourceLoadersByManifestAndConfig.get(androidManifestSdkConfigPair);
if (resourceLoader == null) {
resourceLoader = createAppResourceLoader(systemResourceLoader, appManifest);
resourceLoadersByManifestAndConfig.put(androidManifestSdkConfigPair, resourceLoader);
}
return resourceLoader;
}
protected ResourceLoader createAppResourceLoader(ResourceLoader systemResourceLoader, AndroidManifest appManifest) {
List<PackageResourceLoader> appAndLibraryResourceLoaders = new ArrayList<>();
for (ResourcePath resourcePath : appManifest.getIncludedResourcePaths()) {
appAndLibraryResourceLoaders.add(createResourceLoader(resourcePath));
}
OverlayResourceLoader overlayResourceLoader = new OverlayResourceLoader(appManifest.getPackageName(), appAndLibraryResourceLoaders);
Map<String, ResourceLoader> resourceLoaders = new HashMap<>();
resourceLoaders.put("android", systemResourceLoader);
resourceLoaders.put(appManifest.getPackageName(), overlayResourceLoader);
return new RoutingResourceLoader(resourceLoaders);
}
public PackageResourceLoader createResourceLoader(ResourcePath resourcePath) {
return new PackageResourceLoader(resourcePath);
}
protected ShadowMap createShadowMap() {
synchronized (RobolectricTestRunner.class) {
if (mainShadowMap != null) return mainShadowMap;
mainShadowMap = new ShadowMap.Builder().build();
return mainShadowMap;
}
}
public class HelperTestRunner extends BlockJUnit4ClassRunner {
public HelperTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
@Override protected Object createTest() throws Exception {
Object test = super.createTest();
testLifecycle.prepareTest(test);
return test;
}
@Override public Statement classBlock(RunNotifier notifier) {
return super.classBlock(notifier);
}
@Override public Statement methodBlock(FrameworkMethod method) {
return super.methodBlock(method);
}
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
final Statement invoker = super.methodInvoker(method, test);
return new Statement() {
@Override
public void evaluate() throws Throwable {
Thread orig = parallelUniverseInterface.getMainThread();
parallelUniverseInterface.setMainThread(Thread.currentThread());
try {
invoker.evaluate();
} finally {
parallelUniverseInterface.setMainThread(orig);
}
}
};
}
}
private static class ManifestIdentifier {
private final FsFile manifestFile;
private final FsFile resDir;
private final FsFile assetDir;
private final String packageName;
private final List<FsFile> libraryDirs;
public ManifestIdentifier(FsFile manifestFile, FsFile resDir, FsFile assetDir, String packageName,
List<FsFile> libraryDirs) {
this.manifestFile = manifestFile;
this.resDir = resDir;
this.assetDir = assetDir;
this.packageName = packageName;
this.libraryDirs = libraryDirs != null ? libraryDirs : Collections.<FsFile>emptyList();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ManifestIdentifier that = (ManifestIdentifier) o;
return assetDir.equals(that.assetDir)
&& libraryDirs.equals(that.libraryDirs)
&& manifestFile.equals(that.manifestFile)
&& resDir.equals(that.resDir)
&& ((packageName == null && that.packageName == null) || (packageName != null && packageName.equals(that.packageName)));
}
@Override
public int hashCode() {
int result = manifestFile.hashCode();
result = 31 * result + resDir.hashCode();
result = 31 * result + assetDir.hashCode();
result = 31 * result + (packageName == null ? 0 : packageName.hashCode());
result = 31 * result + libraryDirs.hashCode();
return result;
}
}
private static <A extends Annotation> A defaultsFor(Class<A> annotation) {
return annotation.cast(
Proxy.newProxyInstance(annotation.getClassLoader(), new Class[] { annotation },
new InvocationHandler() {
public Object invoke(Object proxy, @NotNull Method method, Object[] args)
throws Throwable {
return method.getDefaultValue();
}
}));
}
}
| mit |
nikolap/pdfmerger | src/np/pdf/Main.java | 485 | package np.pdf;
import java.io.IOException;
import np.pdf.gui.MainWindow;
import javafx.application.Application;
import javafx.stage.Stage;
/**
* @author Nikola Peric
*
*/
public class Main extends Application{
/**
* Launches the PDFMerger program.
* @param args
*/
public static void main(String[] args) throws IOException {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
MainWindow gui = new MainWindow();
gui.start(stage);
}
}
| mit |
hsqlu/coding-lab | java/coding-vampire/src/main/java/com/code/common/event/ThreadPoolEventDispatcher.java | 1145 | package com.code.common.event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
public class ThreadPoolEventDispatcher<EVENT_TYPE extends Enum<EVENT_TYPE>, EVENT>
extends AbstractEventDispatcher<EVENT_TYPE, EVENT> {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolEventDispatcher.class);
public ThreadPoolEventDispatcher(String name, int threadCount, int queueSize) {
super(name);
executor = new ThreadPoolExecutor(
threadCount, threadCount, 0L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(queueSize),
new ThreadFactory() {
int i = 0;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, name + "[" + (i++) + "]");
}
},
BLOCKING_POOL_POLICY);
}
@Override
protected void doHandler(IEventHandler<EVENT_TYPE, EVENT> handler, EVENT_TYPE eventType, EVENT event) {
executor.execute(() -> handler.handle(eventType, event));
}
}
| mit |
jazz-community/jazz-debug-environment | buildSrc/src/main/java/org/jazzcommunity/development/library/net/Credentials.java | 377 | package org.jazzcommunity.development.library.net;
public class Credentials {
private final String username;
private final char[] password;
public Credentials(String name, char[] password) {
this.username = name;
this.password = password;
}
public String getUsername() {
return username;
}
public char[] getPassword() {
return password;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/timeseriesinsights/mgmt-v2017_11_15/src/main/java/com/microsoft/azure/management/timeseriesinsights/v2017_11_15/implementation/EventSourcesImpl.java | 3061 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*
*/
package com.microsoft.azure.management.timeseriesinsights.v2017_11_15.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.timeseriesinsights.v2017_11_15.EventSources;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.management.timeseriesinsights.v2017_11_15.EventSourceListResponse;
import com.microsoft.azure.management.timeseriesinsights.v2017_11_15.EventSourceResource;
class EventSourcesImpl extends WrapperImpl<EventSourcesInner> implements EventSources {
private final TimeSeriesInsightsManager manager;
EventSourcesImpl(TimeSeriesInsightsManager manager) {
super(manager.inner().eventSources());
this.manager = manager;
}
public TimeSeriesInsightsManager manager() {
return this.manager;
}
@Override
public EventSourceResourceImpl define(String name) {
return wrapModel(name);
}
private EventSourceResourceImpl wrapModel(EventSourceResourceInner inner) {
return new EventSourceResourceImpl(inner, manager());
}
private EventSourceResourceImpl wrapModel(String name) {
return new EventSourceResourceImpl(name, this.manager());
}
@Override
public Observable<EventSourceListResponse> listByEnvironmentAsync(String resourceGroupName, String environmentName) {
EventSourcesInner client = this.inner();
return client.listByEnvironmentAsync(resourceGroupName, environmentName)
.map(new Func1<EventSourceListResponseInner, EventSourceListResponse>() {
@Override
public EventSourceListResponse call(EventSourceListResponseInner inner) {
return new EventSourceListResponseImpl(inner, manager());
}
});
}
@Override
public Observable<EventSourceResource> getAsync(String resourceGroupName, String environmentName, String eventSourceName) {
EventSourcesInner client = this.inner();
return client.getAsync(resourceGroupName, environmentName, eventSourceName)
.flatMap(new Func1<EventSourceResourceInner, Observable<EventSourceResource>>() {
@Override
public Observable<EventSourceResource> call(EventSourceResourceInner inner) {
if (inner == null) {
return Observable.empty();
} else {
return Observable.just((EventSourceResource)wrapModel(inner));
}
}
});
}
@Override
public Completable deleteAsync(String resourceGroupName, String environmentName, String eventSourceName) {
EventSourcesInner client = this.inner();
return client.deleteAsync(resourceGroupName, environmentName, eventSourceName).toCompletable();
}
}
| mit |
everKalle/ExperienceSamplingApplication | ExperienceSamplingApp/app/src/main/java/com/example/madiskar/experiencesamplingapp/interfaces/OnStudyTableChangedListener.java | 255 | package com.example.madiskar.experiencesamplingapp.interfaces;
/**
* Interface for updating My Studies list when changes to study list are made from outside the fragment
*/
public interface OnStudyTableChangedListener {
void onTableChanged();
}
| mit |
alrocar/apineitor | apineitor-meetup/src/main/java/com/apineitor/meetup/models/Rating.java | 4136 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Alberto Romeu
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.apineitor.meetup.models;
import javax.annotation.Generated;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.apineitor.models.APIResponse;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class Rating implements APIResponse {
@SerializedName("member_id")
@Expose
private Long memberId;
@SerializedName("event_id")
@Expose
private String eventId;
@SerializedName("time")
@Expose
private Long time;
@SerializedName("member_name")
@Expose
private String memberName;
@SerializedName("group_id")
@Expose
private Long groupId;
/**
* No args constructor for use in serialization
*
*/
public Rating() {
}
/**
*
* @param groupId
* @param time
* @param eventId
* @param memberId
* @param memberName
*/
public Rating(Long memberId, String eventId, Long time, String memberName,
Long groupId) {
this.memberId = memberId;
this.eventId = eventId;
this.time = time;
this.memberName = memberName;
this.groupId = groupId;
}
/**
*
* @return The memberId
*/
public Long getMemberId() {
return memberId;
}
/**
*
* @param memberId
* The member_id
*/
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
/**
*
* @return The eventId
*/
public String getEventId() {
return eventId;
}
/**
*
* @param eventId
* The event_id
*/
public void setEventId(String eventId) {
this.eventId = eventId;
}
/**
*
* @return The time
*/
public Long getTime() {
return time;
}
/**
*
* @param time
* The time
*/
public void setTime(Long time) {
this.time = time;
}
/**
*
* @return The memberName
*/
public String getMemberName() {
return memberName;
}
/**
*
* @param memberName
* The member_name
*/
public void setMemberName(String memberName) {
this.memberName = memberName;
}
/**
*
* @return The groupId
*/
public Long getGroupId() {
return groupId;
}
/**
*
* @param groupId
* The group_id
*/
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(memberId).append(eventId)
.append(time).append(memberName).append(groupId).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Rating) == false) {
return false;
}
Rating rhs = ((Rating) other);
return new EqualsBuilder().append(memberId, rhs.memberId)
.append(eventId, rhs.eventId).append(time, rhs.time)
.append(memberName, rhs.memberName)
.append(groupId, rhs.groupId).isEquals();
}
} | mit |
domax/gwt-dynamic-plugins | gwt-dynamic-main/gwt-dynamic-common/src/test/java/org/gwt/dynamic/common/shared/beans/BeanA.java | 1874 | /*
* Copyright 2014 Maxim Dominichenko
*
* Licensed under The MIT License (MIT) (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://github.com/domax/gwt-dynamic-plugins/blob/master/LICENSE
*
* 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.gwt.dynamic.common.shared.beans;
import java.util.Date;
import java.util.List;
public class BeanA {
public String name;
public Date ts;
public List<BeanB> values;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((ts == null) ? 0 : ts.hashCode());
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BeanA other = (BeanA) obj;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (ts == null) {
if (other.ts != null) return false;
} else if (!ts.equals(other.ts)) return false;
if (values == null) {
if (other.values != null) return false;
} else if (!values.equals(other.values)) return false;
return true;
}
@Override
public String toString() {
return new StringBuilder("BeanA")
.append(" {name=").append(name)
.append(", ts=").append(ts)
.append(", values=").append(values)
.append("}").toString();
}
}
| mit |
SquidDev-CC/CCTweaks | src/main/java/org/squiddev/cctweaks/core/Config.java | 8025 | package org.squiddev.cctweaks.core;
import net.minecraftforge.common.config.Configuration;
import org.squiddev.cctweaks.core.utils.DebugLogger;
import org.squiddev.configgen.*;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
/**
* The main config class
*/
@org.squiddev.configgen.Config(languagePrefix = "gui.config.cctweaks.")
public final class Config {
public static Configuration configuration;
public static Set<String> turtleDisabledActions;
public static void init(File file) {
org.squiddev.cctweaks.lua.ConfigForgeLoader.init(file);
org.squiddev.cctweaks.core.ConfigForgeLoader.init(org.squiddev.cctweaks.lua.ConfigForgeLoader.getConfiguration());
}
public static void sync() {
org.squiddev.cctweaks.core.ConfigForgeLoader.doSync();
org.squiddev.cctweaks.lua.ConfigForgeLoader.sync();
}
@OnSync
public static void onSync() {
configuration = org.squiddev.cctweaks.lua.ConfigForgeLoader.getConfiguration();
// Handle generation of HashSets, etc...
Set<String> disabledActions = turtleDisabledActions = new HashSet<String>();
for (String action : Turtle.disabledActions) {
disabledActions.add(action.toLowerCase());
}
Computer.computerUpgradeCrafting &= Computer.computerUpgradeEnabled;
Network.WirelessBridge.crafting &= Network.WirelessBridge.enabled;
Network.WirelessBridge.turtleEnabled &= Network.WirelessBridge.enabled;
if (Config.Computer.suspendInactive && !org.squiddev.cctweaks.lua.Config.Computer.MultiThreading.enabled) {
Config.Computer.suspendInactive = false;
DebugLogger.warn("Computer.suspendInactive requires multi-threading to be enabled. Falling back to default.");
}
}
/**
* Computer tweaks and items.
*/
public static final class Computer {
/**
* Enable upgrading computers.
*/
@DefaultBoolean(true)
public static boolean computerUpgradeEnabled;
/**
* Enable crafting the computer upgrade.
* Requires computerUpgradeEnabled.
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean computerUpgradeCrafting;
/**
* Enable using the debug wand.
*/
@DefaultBoolean(true)
public static boolean debugWandEnabled;
/**
* Suspend computers and turtles which timeout, rather than shutting them down.
*
* Requires multi-threading to be on, though threads can be set to 1.
*/
@DefaultBoolean(false)
@RequiresRestart
public static boolean suspendInactive;
/**
* Config options about creating custom ROMs.
*/
public static class CustomRom {
/**
* Whether custom ROMs are enabled.
*/
@DefaultBoolean(true)
public static boolean enabled;
/**
* Whether crafting of custom ROMs is enabled.
*/
@DefaultBoolean(true)
public static boolean crafting;
}
}
/**
* Turtle tweaks and items.
*/
public static final class Turtle {
/**
* Amount of RF/FE/Tesla required for one refuel point
* Set to 0 to disable.
*/
@DefaultInt(100)
@Range(min = 0)
public static int fluxRefuelAmount;
/**
* Amount of Eu required for one refuel point.
* Set to 0 to disable.
*/
@DefaultInt(25)
@Range(min = 0)
public static int euRefuelAmount;
/**
* Disabled turtle actions:
* (compare, compareTo, craft, detect, dig,
* drop, equip, inspect, move, place,
* refuel, select, suck, tool, turn).
*/
public static String[] disabledActions;
/**
* Various tool host options
*/
public static class ToolHost {
/**
* Enable the Tool Host
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean enabled;
/**
* Enable the Tool Manipulator
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean advanced;
/**
* Enable crafting the Tool Host
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean crafting;
/**
* Upgrade Id
*/
@DefaultInt(332)
@RequiresRestart
@Range(min = 0)
public static int upgradeId;
/**
* Upgrade Id for Tool Manipulator
*/
@DefaultInt(333)
@RequiresRestart
@Range(min = 0)
public static int advancedUpgradeId;
/**
* The dig speed factor for tool hosts.
* 20 is about normal player speed.
*/
@DefaultInt(10)
@Range(min = 1)
public static int digFactor;
}
}
/**
* Additional network functionality.
*/
public static final class Network {
/**
* The wireless bridge allows you to connect
* wired networks across dimensions.
*/
public static class WirelessBridge {
/**
* Enable the wireless bridge
*/
@DefaultBoolean(true)
@RequiresRestart(mc = false, world = true)
public static boolean enabled;
/**
* Enable the crafting of Wireless Bridges.
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean crafting;
/**
* Enable the Wireless Bridge upgrade for turtles.
*/
@DefaultBoolean(true)
@RequiresRestart(mc = false, world = true)
public static boolean turtleEnabled;
/**
* The turtle upgrade Id
*/
@DefaultInt(331)
@Range(min = 1)
@RequiresRestart
public static int turtleId;
/**
* Enable the Wireless Bridge upgrade for pocket computers.
*/
@DefaultBoolean(true)
@RequiresRestart(mc = false, world = true)
public static boolean pocketEnabled;
}
/**
* Various configuration options for network visualisation (provided by the debug wand).
*/
public static class Visualisation {
/**
* Whether network visualisation is enabled
*/
@DefaultBoolean(true)
public static boolean enabled;
/**
* The maximum distance for which the network is sent to the client.
* Further distances may be rendered on the client.
*/
@DefaultInt(3)
@Range(min = 1)
public static int renderDistance;
/**
* The cooldown between sending visualisation packets to the client.
*
* Prevents load on larget networks.
*/
@DefaultInt(5)
@Range(min = 0)
public static int cooldown;
}
/**
* Enable the crafting of full block modems.
*
* If you disable, existing ones will still function,
* and you can obtain them from creative.
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean fullBlockModemCrafting;
}
/**
* Integration with other mods.
*/
@RequiresRestart
public static final class Integration {
/**
* MC Multipart integration
*/
@DefaultBoolean(true)
@RequiresRestart
public static boolean mcMultipart;
}
/**
* Various tweaks that don't belong to anything
*/
public static final class Misc {
/**
* Render pocket computers like maps.
*
* This means the terminal is visible when you hold a pocket computer,
* and can be interacted with as a map.
*/
@DefaultBoolean(true)
public static boolean pocketMapRender;
/**
* Fun rendering overlay for various objects.
* Basically I'm slightly vain.
*/
@DefaultBoolean(true)
public static boolean funRender;
}
/**
* Controls over the packets sent between the server and client.
*/
public static final class Packets {
/**
* Only broadcast computer state to those in the current dimension and in range or to those interacting with it.
*/
@DefaultBoolean(true)
public static boolean updateLimiting;
/**
* Only broadcast terminal state to those in interacting with the computer.
*/
@DefaultBoolean(true)
public static boolean terminalLimiting;
}
/**
* Only used when testing and developing the mod.
* Nothing to see here, move along...
*/
public static final class Testing {
/**
* Enable debug blocks/items.
* Only use for testing.
*/
@DefaultBoolean(false)
public static boolean debugItems;
/**
* Controller validation occurs by default as a
* way of ensuring that your network has been
* correctly created.
*
* By enabling this it is easier to trace
* faults, though it willl slow things down
* slightly
*/
@DefaultBoolean(false)
public static boolean controllerValidation;
}
}
| mit |
pholser/jopt-simple | src/main/java/joptsimple/internal/Classes.java | 2815 | /*
The MIT License
Copyright (c) 2004-2016 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package joptsimple.internal;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class Classes {
private static final Map<Class<?>, Class<?>> WRAPPERS = new HashMap<>( 13 );
static {
WRAPPERS.put( boolean.class, Boolean.class );
WRAPPERS.put( byte.class, Byte.class );
WRAPPERS.put( char.class, Character.class );
WRAPPERS.put( double.class, Double.class );
WRAPPERS.put( float.class, Float.class );
WRAPPERS.put( int.class, Integer.class );
WRAPPERS.put( long.class, Long.class );
WRAPPERS.put( short.class, Short.class );
WRAPPERS.put( void.class, Void.class );
}
private Classes() {
throw new UnsupportedOperationException();
}
/**
* Gives the "short version" of the given class name. Somewhat naive to inner classes.
*
* @param className class name to chew on
* @return the short name of the class
*/
public static String shortNameOf( String className ) {
return className.substring( className.lastIndexOf( '.' ) + 1 );
}
/**
* Gives the primitive wrapper class for the given class. If the given class is not
* {@linkplain Class#isPrimitive() primitive}, returns the class itself.
*
* @param <T> generic class type
* @param clazz the class to check
* @return primitive wrapper type if {@code clazz} is primitive, otherwise {@code clazz}
*/
@SuppressWarnings( "unchecked" )
public static <T> Class<T> wrapperOf( Class<T> clazz ) {
return clazz.isPrimitive() ? (Class<T>) WRAPPERS.get( clazz ) : clazz;
}
}
| mit |
liulin2012/DailyExercise | DailyExerciseServer/src/dailyExercise/dao/impl/UserDao.java | 919 | package dailyExercise.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import dailyExercise.bean.User;
import dailyExercise.dao.IUserDao;
@Component("userDao")
public class UserDao implements IUserDao{
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public String save(User user) {
// TODO Auto-generated method stub
try{
return hibernateTemplate.save(user).toString();
}catch(Exception e){
return "fail";
}
}
@Override
public User findById(String userId){
return (User)hibernateTemplate.get(User.class, userId);
}
@Override
public boolean updateUser(User user) {
// TODO Auto-generated method stub
try{
hibernateTemplate.update(user);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
| mit |
zouabimourad/typescript-generator | typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DummyBean.java | 985 |
package cz.habarta.typescript.generator;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@SuppressWarnings("rawtypes")
public class DummyBean {
public String firstProperty;
public int intProperty;
public Integer integerProperty;
public boolean booleanProperty;
public Date dateProperty;
public LocalDate localDateProperty;
public String[] stringArrayProperty;
public List<String> stringListProperty;
public ArrayList<String> stringArrayListProperty;
public DummyEnum dummyEnumProperty;
public Map<String, String> stringMapProperty;
public List<List<Integer>> listOfListOfIntegerProperty;
public Map<String, DummyBean> mapOfDummyBeanProperty;
public List rawListProperty;
public Map rawMapProperty;
public List<DummyEnum> listOfDummyEnumProperty;
public Map<String, DummyEnum> mapOfDummyEnumProperty;
public Map<String, List<Map<String, DummyEnum>>> mapOfListOfMapOfDummyEnumProperty;
}
| mit |
openfact/openfact-pe | src/main/java/org/openfact/pe/ubl/ubl21/commons/TermsType.java | 1098 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.08.16 at 10:50:18 AM PET
//
package org.openfact.pe.ubl.ubl21.commons;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TermsType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TermsType">
* <simpleContent>
* <extension base="<urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2>TextType">
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TermsType")
public class TermsType
extends TextTypeUnqDat
{
}
| mit |
openfact/openfact | src/main/java/org/openfact/core/utils/finance/internal/languages/SlavonicPluralForms.java | 2143 | /*******************************************************************************
* Copyright 2016 Sistcoop, 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 org.openfact.core.utils.finance.internal.languages;
import com.google.common.collect.Range;
public class SlavonicPluralForms implements PluralForms {
private final String singularForm;
private final String pluralForm;
private final String genitivePluralForm;
private final GenderType genderType;
public SlavonicPluralForms(String singularForm, String pluralForm, String genitivePluralForm) {
this(singularForm, pluralForm, genitivePluralForm, GenderType.NON_APPLICABLE);
}
public SlavonicPluralForms(String singularForm, String pluralForm, String genitivePluralForm, GenderType genderType) {
this.singularForm = singularForm;
this.pluralForm = pluralForm;
this.genitivePluralForm = genitivePluralForm;
this.genderType = genderType;
}
@Override
public String formFor(Integer value) {
if (value == 1) {
return singularForm;
} else if (usePluralForm(value)) {
return pluralForm;
}
return genitivePluralForm;
}
private boolean usePluralForm(Integer value) {
return Range.closed(2, 4).contains(value % 10) && !Range.closed(12, 14).contains(value % 100);
}
@Override
public GenderType genderType() {
return genderType;
}
}
| mit |
thombergs/docx-stamper | src/main/java/org/wickedsource/docxstamper/api/EvaluationContextConfigurer.java | 681 | package org.wickedsource.docxstamper.api;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
* Allows for custom configuration of a spring expression language {@link org.springframework.expression.EvaluationContext}.
* This can for example be used to add custom {@link org.springframework.expression.PropertyAccessor}s and {@link org.springframework.expression.MethodResolver}s.
*/
public interface EvaluationContextConfigurer {
/**
* Configure the context before it's used by docxstamper.
*
* @param context the spel eval context, not null
*/
void configureEvaluationContext(StandardEvaluationContext context);
}
| mit |
Ginxo/becajava07 | BECA_EXAMPLES/src/main/java/com/everis/alicante/courses/becajava/examples/Escritor.java | 701 | package com.everis.alicante.courses.becajava.examples;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.everis.alicante.courses.becajava.garage.utils.TextFileUtils;
public class Escritor {
public static void escribirOutputStream(String data ,String path) throws IOException {
List<String> lista= new ArrayList<>();
lista.add(data);
TextFileUtils.saveFile(lista, path);
}
public static void main(String args[]){
Escritor escritor= new Escritor();
try {
escritor.escribirOutputStream("hola","output.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| mit |
Mikescher/absGDX | core/src/de/samdev/absgdx/example/topdowngame/entities/Slide_1.java | 3031 | package de.samdev.absgdx.example.topdowngame.entities;
import de.samdev.absgdx.example.Textures;
import de.samdev.absgdx.example.topdowngame.TopDownGameLayer;
import de.samdev.absgdx.framework.entities.Entity;
import de.samdev.absgdx.framework.entities.colliosiondetection.CollisionGeometryOwner;
import de.samdev.absgdx.framework.entities.colliosiondetection.geometries.CollisionGeometry;
import de.samdev.absgdx.framework.layer.GameLayer;
import de.samdev.absgdx.framework.math.align.AlignCorner4;
public class Slide_1 extends Entity {
public TopDownGameLayer owner;
public int tick = 0;
public float x, y;
public Entity other;
public CollisionGeometry t;
public Slide_1(Entity e) {
super(Textures.texSlideTile, 4, 4);
this.x = 10;
this.y = 38;
this.other = e;
}
@Override
public void onLayerAdd(GameLayer layer) {
setPosition(x, y);
t = addFullCollisionTriangle(AlignCorner4.TOPLEFT).geometry;
// t = addFullCollisionBox().geometry;
}
@Override
public void beforeUpdate(float delta) {
// System.out.println("x: " + other.collisionGeometries.get(0).geometry.getXTouchDistance(t));
// System.out.println("y: " + other.collisionGeometries.get(0).geometry.getYTouchDistance(t));
// System.out.println(this.getFirstHardCollider() != null);
// System.out.println("");
}
@Override
public void onActiveCollide(CollisionGeometryOwner passiveCollider, CollisionGeometry myGeo, CollisionGeometry otherGeo) {
// System.out.println("[COLLISION ACTIVE] " + this.getClass().getSimpleName() + " -> " + passiveCollider.getClass().getSimpleName() + "(" + Integer.toHexString(myGeo.hashCode()) + " | " + Integer.toHexString(otherGeo.hashCode()) + ")");
}
@Override
public void onPassiveCollide(CollisionGeometryOwner activeCollider, CollisionGeometry myGeo, CollisionGeometry otherGeo) {
// System.out.println("[COLLISION PASSIV] " + this.getClass().getSimpleName() + " -> " + activeCollider.getClass().getSimpleName() + "(" + Integer.toHexString(myGeo.hashCode()) + " | " + Integer.toHexString(otherGeo.hashCode()) + ")");
}
@Override
public void onActiveMovementCollide(CollisionGeometryOwner passiveCollider, CollisionGeometry myGeo, CollisionGeometry otherGeo) {
// System.out.println("[MOVE COLL ACTIVE] " + this.getClass().getSimpleName() + " -> " + passiveCollider.getClass().getSimpleName() + "(" + Integer.toHexString(myGeo.hashCode()) + " | " + Integer.toHexString(otherGeo.hashCode()) + ")");
}
@Override
public void onPassiveMovementCollide(CollisionGeometryOwner activeCollider, CollisionGeometry myGeo, CollisionGeometry otherGeo) {
// System.out.println("[MOVE COLL PASSIV] " + this.getClass().getSimpleName() + " -> " + activeCollider.getClass().getSimpleName() + "(" + Integer.toHexString(myGeo.hashCode()) + " | " + Integer.toHexString(otherGeo.hashCode()) + ")");
}
@Override
public boolean canCollideWith(CollisionGeometryOwner other) {
return true;
}
@Override
public boolean canMoveCollideWith(CollisionGeometryOwner other) {
return true;
}
}
| mit |
akkirilov/SoftUniProject | 07_OOP_Advanced/10_Reflection_ex/src/p03_05_BarracksWars/models/units/Archer.java | 259 | package p03_05_BarracksWars.models.units;
public class Archer extends AbstractUnit {
private static final int ARCHER_HEALHT = 25;
private static final int ARCHER_DAMAGE = 7;
public Archer() {
super(ARCHER_HEALHT, ARCHER_DAMAGE);
}
}
| mit |
atupal/oj | hackerrank/contests/algorithms/algorithmist/c.java | 1120 | import java.math.BigInteger;
import java.util.Scanner;
class Main {
public static void main(String args[]) {
BigInteger one = new BigInteger("1");
Scanner in = new Scanner(System.in);
int t = in.nextInt();
in.nextLine();
for (int c = 0; c < t; ++ c) {
String s = in.nextLine().trim();
String fact[] = s.split(" ");
String a[] = fact[0].split("/");
String b[] = fact[1].split("/");
BigInteger p1 = new BigInteger(a[0]);
BigInteger q1 = new BigInteger("1");
if (a.length == 2) {
q1 = new BigInteger(a[1]);
}
BigInteger p2 = new BigInteger(b[0]);
BigInteger q2 = new BigInteger("1");
if (b.length == 2) {
q2 = new BigInteger(b[1]);
}
BigInteger p = (p1.multiply(q2) ).add(p2.multiply(q1));
BigInteger q = q1.multiply(q2);
BigInteger gcd = p.gcd(q);
p = p.divide(gcd);
q = q.divide(gcd);
System.out.print(p);
if (q.compareTo(one) != 0) {
System.out.print("/");
System.out.println(q);
} else {
System.out.println();
}
}
}
}
| mit |
valery1707/test-sorm | src/main/java/name/valery1707/megatel/sorm/api/bro/smtp/BroSmtpDto.java | 2638 | package name.valery1707.megatel.sorm.api.bro.smtp;
import com.fasterxml.jackson.annotation.JsonInclude;
import name.valery1707.megatel.sorm.domain.BroSmtp;
import static name.valery1707.core.utils.DateUtils.bigDecimalToZonedDateTime;
import static name.valery1707.core.utils.DateUtils.formatDateTime;
@SuppressWarnings("unused")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BroSmtpDto {
private String ts;
private String idOrigHost;
private int idOrigPort;
private String idRespHost;
private int idRespPort;
private String from;
private String to;
private String subject;
private String userAgent;
private Boolean tls;
private String fuids;
private Boolean isWebmail;
public BroSmtpDto() {
}
public BroSmtpDto(BroSmtp src) {
this();
setTs(formatDateTime(bigDecimalToZonedDateTime(src.getTs())));
setIdOrigHost(src.getIdOrigHost());
setIdOrigPort(src.getIdOrigPort());
setIdRespHost(src.getIdRespHost());
setIdRespPort(src.getIdRespPort());
setFrom(src.getFrom());
setTo(src.getTo());
setSubject(src.getSubject());
setUserAgent(src.getUserAgent());
setTls(src.getTls());
setFuids(src.getFuids());
setWebmail(src.getWebmail());
}
public String getTs() {
return ts;
}
public void setTs(String ts) {
this.ts = ts;
}
public String getIdOrigHost() {
return idOrigHost;
}
public void setIdOrigHost(String idOrigHost) {
this.idOrigHost = idOrigHost;
}
public int getIdOrigPort() {
return idOrigPort;
}
public void setIdOrigPort(int idOrigPort) {
this.idOrigPort = idOrigPort;
}
public String getIdRespHost() {
return idRespHost;
}
public void setIdRespHost(String idRespHost) {
this.idRespHost = idRespHost;
}
public int getIdRespPort() {
return idRespPort;
}
public void setIdRespPort(int idRespPort) {
this.idRespPort = idRespPort;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public Boolean getTls() {
return tls;
}
public void setTls(Boolean tls) {
this.tls = tls;
}
public String getFuids() {
return fuids;
}
public void setFuids(String fuids) {
this.fuids = fuids;
}
public Boolean getWebmail() {
return isWebmail;
}
public void setWebmail(Boolean webmail) {
isWebmail = webmail;
}
}
| mit |
ferspanghero/UCI-INF225-SearchEngine | src/searchengine/core/crawling/DefaultCrawlControllerBuilder.java | 1150 | package searchengine.core.crawling;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* Represents a default builder of a pages crawling controller
*/
public class DefaultCrawlControllerBuilder implements ICrawlControllerBuilder {
@Override
public CrawlController build(CrawlParameters parameters) throws Exception {
if (parameters == null)
throw new IllegalArgumentException("Necessary parameters for crawling are missing");
String errorMessages = parameters.validate();
if (errorMessages != null && errorMessages.length() > 1)
throw new IllegalArgumentException(errorMessages);
PageFetcher pageFetcher = new PageFetcher(parameters.getConfig());
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(parameters.getConfig(), pageFetcher, robotstxtServer);
return controller;
}
}
| mit |
jangesz/java-action | tic-concurrent/tic-concurrent-collections/src/main/java/org/tic/concurrent/collections/MyLinkedHashMap.java | 22449 | package org.tic.concurrent.collections;
import java.io.IOException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
public class MyLinkedHashMap<K,V>
extends MyHashMap<K,V>
implements Map<K,V>
{
/*
* Implementation note. A previous version of this class was
* internally structured a little differently. Because superclass
* HashMap now uses trees for some of its nodes, class
* MyLinkedHashMap.Entry is now treated as intermediary node class
* that can also be converted to tree form. The name of this
* class, MyLinkedHashMap.Entry, is confusing in several ways in its
* current context, but cannot be changed. Otherwise, even though
* it is not exported outside this package, some existing source
* code is known to have relied on a symbol resolution corner case
* rule in calls to removeEldestEntry that suppressed compilation
* errors due to ambiguous usages. So, we keep the name to
* preserve unmodified compilability.
*
* The changes in node classes also require using two fields
* (head, tail) rather than a pointer to a header node to maintain
* the doubly-linked before/after list. This class also
* previously used a different style of callback methods upon
* access, insertion, and removal.
*/
/**
* MyHashMap.Node subclass for normal LinkedHashMap entries.
*/
static class Entry<K,V> extends MyHashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
private static final long serialVersionUID = 3801124242820219131L;
/**
* The head (eldest) of the doubly linked list.
*/
transient MyLinkedHashMap.Entry<K,V> head;
/**
* The tail (youngest) of the doubly linked list.
*/
transient MyLinkedHashMap.Entry<K,V> tail;
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
*
* @serial
*/
final boolean accessOrder;
// internal utilities
// link at the end of list
private void linkNodeLast(MyLinkedHashMap.Entry<K,V> p) {
MyLinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
// apply src's links to dst
private void transferLinks(MyLinkedHashMap.Entry<K,V> src,
MyLinkedHashMap.Entry<K,V> dst) {
MyLinkedHashMap.Entry<K,V> b = dst.before = src.before;
MyLinkedHashMap.Entry<K,V> a = dst.after = src.after;
if (b == null)
head = dst;
else
b.after = dst;
if (a == null)
tail = dst;
else
a.before = dst;
}
// overrides of HashMap hook methods
void reinitialize() {
super.reinitialize();
head = tail = null;
}
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
MyLinkedHashMap.Entry<K,V> p =
new MyLinkedHashMap.Entry<K,V>(hash, key, value, e);
linkNodeLast(p);
return p;
}
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
MyLinkedHashMap.Entry<K,V> q = (MyLinkedHashMap.Entry<K,V>)p;
MyLinkedHashMap.Entry<K,V> t =
new MyLinkedHashMap.Entry<K,V>(q.hash, q.key, q.value, next);
transferLinks(q, t);
return t;
}
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
linkNodeLast(p);
return p;
}
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
MyLinkedHashMap.Entry<K,V> q = (MyLinkedHashMap.Entry<K,V>)p;
TreeNode<K,V> t = new TreeNode<K,V>(q.hash, q.key, q.value, next);
transferLinks(q, t);
return t;
}
void afterNodeRemoval(Node<K,V> e) { // unlink
MyLinkedHashMap.Entry<K,V> p =
(MyLinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.before = p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a == null)
tail = b;
else
a.before = b;
}
void afterNodeInsertion(boolean evict) { // possibly remove eldest
MyLinkedHashMap.Entry<K,V> first;
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}
void afterNodeAccess(Node<K,V> e) { // move node to last
MyLinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
MyLinkedHashMap.Entry<K,V> p =
(MyLinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public MyLinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and a default load factor (0.75).
*
* @param initialCapacity the initial capacity
* @throws IllegalArgumentException if the initial capacity is negative
*/
public MyLinkedHashMap(int initialCapacity) {
super(initialCapacity);
accessOrder = false;
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the default initial capacity (16) and load factor (0.75).
*/
public MyLinkedHashMap() {
super();
accessOrder = false;
}
/**
* Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
* the same mappings as the specified map. The <tt>LinkedHashMap</tt>
* instance is created with a default load factor (0.75) and an initial
* capacity sufficient to hold the mappings in the specified map.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public MyLinkedHashMap(Map<? extends K, ? extends V> m) {
super();
accessOrder = false;
putMapEntries(m, false);
}
/**
* Constructs an empty <tt>LinkedHashMap</tt> instance with the
* specified initial capacity, load factor and ordering mode.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @param accessOrder the ordering mode - <tt>true</tt> for
* access-order, <tt>false</tt> for insertion-order
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public MyLinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
*/
public boolean containsValue(Object value) {
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) {
V v = e.value;
if (v == value || (value != null && value.equals(v)))
return true;
}
return false;
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*/
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
/**
* {@inheritDoc}
*/
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return defaultValue;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
/**
* {@inheritDoc}
*/
public void clear() {
super.clear();
head = tail = null;
}
/**
* Returns <tt>true</tt> if this map should remove its eldest entry.
* This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
* inserting a new entry into the map. It provides the implementor
* with the opportunity to remove the eldest entry each time a new one
* is added. This is useful if the map represents a cache: it allows
* the map to reduce memory consumption by deleting stale entries.
*
* <p>Sample use: this override will allow the map to grow up to 100
* entries and then delete the eldest entry each time a new entry is
* added, maintaining a steady state of 100 entries.
* <pre>
* private static final int MAX_ENTRIES = 100;
*
* protected boolean removeEldestEntry(Map.Entry eldest) {
* return size() > MAX_ENTRIES;
* }
* </pre>
*
* <p>This method typically does not modify the map in any way,
* instead allowing the map to modify itself as directed by its
* return value. It <i>is</i> permitted for this method to modify
* the map directly, but if it does so, it <i>must</i> return
* <tt>false</tt> (indicating that the map should not attempt any
* further modification). The effects of returning <tt>true</tt>
* after modifying the map from within this method are unspecified.
*
* <p>This implementation merely returns <tt>false</tt> (so that this
* map acts like a normal map - the eldest element is never removed).
*
* @param eldest The least recently inserted entry in the map, or if
* this is an access-ordered map, the least recently accessed
* entry. This is the entry that will be removed it this
* method returns <tt>true</tt>. If the map was empty prior
* to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
* in this invocation, this will be the entry that was just
* inserted; in other words, if the map contains a single
* entry, the eldest entry is also the newest.
* @return <tt>true</tt> if the eldest entry should be removed
* from the map; <tt>false</tt> if it should be retained.
*/
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
* Its {@link Spliterator} typically provides faster sequential
* performance but much poorer parallel performance than that of
* {@code HashMap}.
*
* @return a set view of the keys contained in this map
*/
public Set<K> keySet() {
Set<K> ks;
return (ks = keySet) == null ? (keySet = new MyLinkedHashMap.LinkedKeySet()) : ks;
}
final class LinkedKeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { MyLinkedHashMap.this.clear(); }
public final Iterator<K> iterator() {
return new MyLinkedHashMap.LinkedKeyIterator();
}
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return Spliterators.spliterator(this, Spliterator.SIZED |
Spliterator.ORDERED |
Spliterator.DISTINCT);
}
public final void forEach(Consumer<? super K> action) {
if (action == null)
throw new NullPointerException();
int mc = modCount;
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
action.accept(e.key);
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
* Its {@link Spliterator} typically provides faster sequential
* performance but much poorer parallel performance than that of
* {@code HashMap}.
*
* @return a view of the values contained in this map
*/
public Collection<V> values() {
Collection<V> vs;
return (vs = values) == null ? (values = new MyLinkedHashMap.LinkedValues()) : vs;
}
final class LinkedValues extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { MyLinkedHashMap.this.clear(); }
public final Iterator<V> iterator() {
return new MyLinkedHashMap.LinkedValueIterator();
}
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return Spliterators.spliterator(this, Spliterator.SIZED |
Spliterator.ORDERED);
}
public final void forEach(Consumer<? super V> action) {
if (action == null)
throw new NullPointerException();
int mc = modCount;
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
action.accept(e.value);
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation, or through the
* <tt>setValue</tt> operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
* <tt>clear</tt> operations. It does not support the
* <tt>add</tt> or <tt>addAll</tt> operations.
* Its {@link Spliterator} typically provides faster sequential
* performance but much poorer parallel performance than that of
* {@code HashMap}.
*
* @return a set view of the mappings contained in this map
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new MyLinkedHashMap.LinkedEntrySet()) : es;
}
final class LinkedEntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { MyLinkedHashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new MyLinkedHashMap.LinkedEntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return Spliterators.spliterator(this, Spliterator.SIZED |
Spliterator.ORDERED |
Spliterator.DISTINCT);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
if (action == null)
throw new NullPointerException();
int mc = modCount;
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
action.accept(e);
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
// Map overrides
public void forEach(BiConsumer<? super K, ? super V> action) {
if (action == null)
throw new NullPointerException();
int mc = modCount;
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
action.accept(e.key, e.value);
if (modCount != mc)
throw new ConcurrentModificationException();
}
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
if (function == null)
throw new NullPointerException();
int mc = modCount;
for (MyLinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
e.value = function.apply(e.key, e.value);
if (modCount != mc)
throw new ConcurrentModificationException();
}
// Iterators
abstract class LinkedHashIterator {
MyLinkedHashMap.Entry<K,V> next;
MyLinkedHashMap.Entry<K,V> current;
int expectedModCount;
LinkedHashIterator() {
next = head;
expectedModCount = modCount;
current = null;
}
public final boolean hasNext() {
return next != null;
}
final MyLinkedHashMap.Entry<K,V> nextNode() {
MyLinkedHashMap.Entry<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
current = e;
next = e.after;
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
final class LinkedKeyIterator extends MyLinkedHashMap.LinkedHashIterator
implements Iterator<K> {
public final K next() { return nextNode().getKey(); }
}
final class LinkedValueIterator extends MyLinkedHashMap.LinkedHashIterator
implements Iterator<V> {
public final V next() { return nextNode().value; }
}
final class LinkedEntryIterator extends MyLinkedHashMap.LinkedHashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
} | mit |
danydunk/Augusto | resources/test/rft/Refinement_buddi_crud_invalidHelper.java | 1419 | // DO NOT EDIT: This file is automatically generated.
//
// Only the associated template file should be edited directly.
// Helper class files are automatically regenerated from the template
// files at various times, including record actions and test object
// insertion actions. Any changes made directly to a helper class
// file will be lost when automatically updated.
package resources.test.rft;
import com.rational.test.ft.object.interfaces.*;
import com.rational.test.ft.object.interfaces.SAP.*;
import com.rational.test.ft.object.interfaces.WPF.*;
import com.rational.test.ft.object.interfaces.siebel.*;
import com.rational.test.ft.object.interfaces.flex.*;
import com.rational.test.ft.object.interfaces.dojo.*;
import com.rational.test.ft.object.interfaces.generichtmlsubdomain.*;
import com.rational.test.ft.script.*;
import com.rational.test.ft.vp.IFtVerificationPoint;
import com.ibm.rational.test.ft.object.interfaces.sapwebportal.*;
/**
* Script Name : <b>Refinement_buddi_crud_invalid</b><br>
* Generated : <b>2016/11/28 1:51:46 AM</b><br>
* Description : Helper class for script<br>
* Original Host : Windows 7 amd64 6.1 <br>
*
* @since November 28, 2016
* @author usi
*/
public abstract class Refinement_buddi_crud_invalidHelper extends RationalTestScript
{
protected Refinement_buddi_crud_invalidHelper()
{
setScriptName("test.rft.Refinement_buddi_crud_invalid");
}
}
| mit |
itwapp/itwapp-java | src/test/java/io/itwapp/rest/ApiRequestTest.java | 9691 | package io.itwapp.rest;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import io.itwapp.Itwapp;
import io.itwapp.exception.InvalidRequestError;
import io.itwapp.exception.ResourceNotFoundException;
import io.itwapp.exception.UnauthorizedException;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.junit.Assert.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ApiRequestTest {
private static String interviewId = null;
@BeforeClass
public static void setUpBeforeClass() {
Itwapp.apiKey = System.getenv("itwappApiKey");
Itwapp.secretKey = System.getenv("itwappApiSecret");
}
@Test
public void a_testSignRequestWithoutQueryStringParam() {
Method m = null;
try {
m = ApiRequest.class.getDeclaredMethod("sign", String.class, String.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
String result = null;
try {
result = (String) m.invoke(null, "GET", "/api/v1/test/");
} catch (IllegalAccessException | InvocationTargetException e) {
fail();
}
assertTrue(result.matches("/api/v1/test/\\?apiKey=.*×tamp=.*&signature=.*"));
}
@Test
public void b_testSignRequestWithQueryStringParam() {
Method m = null;
try {
m = ApiRequest.class.getDeclaredMethod("sign", String.class, String.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
String result = null;
try {
result = (String) m.invoke(null, "GET", "/api/v1/test/?foo=bar");
} catch (IllegalAccessException | InvocationTargetException e) {
fail();
}
assertTrue(result.matches("/api/v1/test/\\?foo=bar&apiKey=.*×tamp=.*&signature=.*"));
}
@Test(expected = UnauthorizedException.class)
public void c_testParseResultWithUnauthorizedException() throws Throwable {
Method m = null;
try {
m = ApiRequest.class.getDeclaredMethod("parseResult", Response.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Response r = null;
try {
Future<Response> f = asyncHttpClient.prepareGet(Itwapp.getApiBase() + "/api/v1/applicant/12").execute();
r = f.get();
} catch (InterruptedException | ExecutionException e) {
fail();
}
// Service should respond not authorized
assertEquals(401, r.getStatusCode());
invokeAndRaiseExceptionOrFail(m, r);
}
@Test(expected = ResourceNotFoundException.class)
public void c_testParseResultWithNotFoundException() throws Throwable {
Method m = null;
try {
m = ApiRequest.class.getDeclaredMethod("parseResult", Response.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Response r = null;
try {
Future<Response> f = asyncHttpClient.prepareGet(Itwapp.getApiBase() + "/api/v1/not_found_page").execute();
r = f.get();
} catch (InterruptedException | ExecutionException e) {
fail();
}
// Service should respond not authorized
assertEquals(404, r.getStatusCode());
invokeAndRaiseExceptionOrFail(m, r);
}
@Test(expected = InvalidRequestError.class)
public void c_testParseResultWithBadRequestException() throws Throwable {
Method m = null;
try {
m = ApiRequest.class.getDeclaredMethod("sign", String.class, String.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
String result = null;
try {
result = (String) m.invoke(null, "POST", "/api/v1/applicant/");
} catch (IllegalAccessException | InvocationTargetException e) {
fail();
}
assertTrue(result.matches("/api/v1/applicant/\\?apiKey=.*×tamp=.*&signature=.*"));
m = null;
try {
m = ApiRequest.class.getDeclaredMethod("parseResult", Response.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Response r = null;
try {
Future<Response> f = asyncHttpClient.preparePost(Itwapp.getApiBase() + result)
.setHeader("Content-Type", "application/json")
.execute();
r = f.get();
} catch (InterruptedException | ExecutionException e) {
fail();
}
// Service should respond not authorized
assertEquals(400, r.getStatusCode());
invokeAndRaiseExceptionOrFail(m, r);
}
@Test
public void d_testParseResultWithNormalResult() {
Method m = null;
try {
m = ApiRequest.class.getDeclaredMethod("sign", String.class, String.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
String result = null;
try {
result = (String) m.invoke(null, "GET", "/api/v1/interview/");
} catch (IllegalAccessException | InvocationTargetException e) {
fail();
}
assertTrue(result.matches("/api/v1/interview/\\?apiKey=.*×tamp=.*&signature=.*"));
m = null;
try {
m = ApiRequest.class.getDeclaredMethod("parseResult", Response.class);
} catch (NoSuchMethodException e) {
fail();
}
m.setAccessible(true);
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Response r = null;
try {
Future<Response> f = asyncHttpClient.prepareGet(Itwapp.getApiBase() + result).execute();
r = f.get();
} catch (InterruptedException | ExecutionException e) {
fail();
}
// Service should respond not authorized
assertEquals(200, r.getStatusCode());
try {
String json = (String) m.invoke(null, r);
JsonElement element = new JsonParser().parse(json);
assertTrue(element.isJsonArray());
} catch (IllegalAccessException | InvocationTargetException | JsonSyntaxException e) {
fail();
}
}
@Test
public void e_testGetRequest() {
String res = ApiRequest.get("/api/v1/interview/");
JsonElement element = new JsonParser().parse(res);
assertTrue(element.isJsonArray());
}
@Test
public void f_testPostRequest() {
Map<String, Object> param = new HashMap<>();
param.put("name", "interview 1");
param.put("video", "");
param.put("text", "");
Map<String, Object> question = new HashMap<>();
question.put("content", "question 1");
question.put("readingTime", 60);
question.put("answerTime", 60);
question.put("number", 1);
List<Map<String, Object>> questions = new ArrayList<>();
questions.add(question);
param.put("questions", questions);
String res = ApiRequest.post("/api/v1/interview/", param);
JsonElement element = new JsonParser().parse(res);
assertTrue(element.isJsonObject());
assertTrue(element.getAsJsonObject().has("_id"));
ApiRequestTest.interviewId = element.getAsJsonObject().get("_id").getAsString();
}
@Test
public void g_testPutRequest() {
assertNotNull(ApiRequestTest.interviewId);
Map<String, Object> param = new HashMap<>();
param.put("name", "interview 1");
param.put("video", "");
param.put("text", "");
Map<String, Object> question = new HashMap<>();
question.put("content", "question 1 - Updated");
question.put("readingTime", 60);
question.put("answerTime", 60);
question.put("number", 1);
List<Map<String, Object>> questions = new ArrayList<>();
questions.add(question);
param.put("questions", questions);
String res = ApiRequest.put("/api/v1/interview/" + ApiRequestTest.interviewId, param);
JsonElement element = new JsonParser().parse(res);
assertTrue(element.isJsonObject());
}
@Test
public void h_testDeleteRequest() {
assertNotNull(ApiRequestTest.interviewId);
String res = ApiRequest.delete("/api/v1/interview/" + ApiRequestTest.interviewId);
assertEquals("", res);
}
private void invokeAndRaiseExceptionOrFail(Method m, Response r) throws Throwable {
try {
m.invoke(null, r);
fail();
} catch (IllegalAccessException e) {
fail();
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
}
| mit |
cscfa/bartleby | library/logBack/logback-1.1.3/logback-core/src/test/java/ch/qos/logback/core/pattern/ExceptionalConverter.java | 831 | /**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.core.pattern;
import ch.qos.logback.core.pattern.DynamicConverter;
public class ExceptionalConverter extends DynamicConverter {
public String convert(Object event) {
if(!isStarted()) {
throw new IllegalStateException("this converter must be started before use");
}
return "";
}
}
| mit |
dualspiral/Hammer | HammerCore/src/main/java/uk/co/drnaylor/minecraft/hammer/core/commands/KickAllCommandCore.java | 6060 | /*
* This file is part of Hammer, licensed under the MIT License (MIT).
*
* Copyright (c) 2015 Daniel Naylor
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package uk.co.drnaylor.minecraft.hammer.core.commands;
import ninja.leaping.configurate.ConfigurationNode;
import uk.co.drnaylor.minecraft.hammer.core.HammerConstants;
import uk.co.drnaylor.minecraft.hammer.core.HammerCore;
import uk.co.drnaylor.minecraft.hammer.core.audit.ActionEnum;
import uk.co.drnaylor.minecraft.hammer.core.audit.AuditEntry;
import uk.co.drnaylor.minecraft.hammer.core.commands.enums.KickAllFlagEnum;
import uk.co.drnaylor.minecraft.hammer.core.commands.enums.KickFlagEnum;
import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.ArgumentMap;
import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.FlagParser;
import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.StringParser;
import uk.co.drnaylor.minecraft.hammer.core.exceptions.HammerException;
import uk.co.drnaylor.minecraft.hammer.core.handlers.DatabaseConnection;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerText;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextBuilder;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextColours;
import uk.co.drnaylor.minecraft.hammer.core.wrappers.WrappedCommandSource;
import java.text.MessageFormat;
import java.util.*;
public class KickAllCommandCore extends CommandCore {
public KickAllCommandCore(HammerCore core) {
super(core);
permissionNodes.add("hammer.kickall");
}
@Override
protected List<ParserEntry> createArgumentParserList() {
List<ParserEntry> entries = new ArrayList<>();
entries.add(new ParserEntry("kickall", new FlagParser<>(KickAllFlagEnum.class), true));
entries.add(new ParserEntry("reason", new StringParser(true), true));
return entries;
}
@Override
protected boolean requiresDatabase() {
return false;
}
/**
* Executes the specific routines in this command core with the specified source.
*
* @param source The {@link WrappedCommandSource} that is executing the command.
* @param arguments The arguments of the command
* @param conn If the command requires database access, holds a {@link DatabaseConnection} object. Otherwise, null.
* @return Whether the command succeeded
* @throws HammerException Thrown if an exception is thrown in the command core.
*/
@Override
protected boolean executeCommand(WrappedCommandSource source, ArgumentMap arguments, DatabaseConnection conn) throws HammerException {
Optional<List<KickAllFlagEnum>> flagOptional = arguments.<List<KickAllFlagEnum>>getArgument("kickall");
boolean whitelist = flagOptional.isPresent() && flagOptional.get().contains(KickAllFlagEnum.WHITELIST);
if (whitelist) {
if (source.hasPermission("hammer.whitelist")) {
core.getWrappedServer().setWhitelist(true);
sendTemplatedMessage(source, "hammer.kickall.whitelist", false, true);
} else {
sendTemplatedMessage(source, "hammer.kickall.nowhitelist", true, true);
return true;
}
}
Optional<String> reasonOptional = arguments.<String>getArgument("reason");
String reason = reasonOptional.isPresent() ? reasonOptional.get() : messageBundle.getString("hammer.kickall.defaultreason");
core.getWrappedServer().kickAllPlayers(source, reason);
sendTemplatedMessage(source, "hammer.kickall", false, true);
ConfigurationNode cn = core.getConfig().getConfig().getNode("audit");
if (cn.getNode("database").getBoolean() || cn.getNode("flatfile").getBoolean()) {
core.getWrappedServer().getScheduler().runAsyncNow(() -> createAuditEntry(source.getUUID(), reason, whitelist));
}
return true;
}
@Override
protected String commandName() {
return "kickall";
}
private void createAuditEntry(UUID actor, String reason, boolean isWhitelist) {
try {
DatabaseConnection conn = core.getDatabaseConnection();
String name;
if (actor.equals(HammerConstants.consoleUUID)) {
name = String.format("*%s*", messageBundle.getString("hammer.console"));
} else {
name = getName(actor, conn);
}
String r = MessageFormat.format(messageBundle.getString("hammer.audit.kickall"), name, reason);
if (isWhitelist) {
r += " " + messageBundle.getString("hammer.audit.whitelist");
}
insertAuditEntry(new AuditEntry(actor, null, core.getConfig().getConfig().getNode("server", "id").getInt(),
new Date(), ActionEnum.KICKALL, r), conn);
} catch (Exception e) {
core.getWrappedServer().getLogger().warn("Unable to add to audit log.");
e.printStackTrace();
}
}
}
| mit |
wolfogre/AndroidProgramming | KH5/kh5_5/src/test/java/wolfogre/kh5_5/ExampleUnitTest.java | 292 | package wolfogre.kh5_5;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
jorgebv/thesis_android | src/edu/arizona/jbv/thesis/main/MainActivity.java | 7026 | package edu.arizona.jbv.thesis.main;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import edu.arizona.jbv.thesis.crypto.AES256Encryptor;
import edu.arizona.jbv.thesis.crypto.CMSSignedDataEncryptor;
import edu.arizona.jbv.thesis.crypto.Encryptor;
import edu.arizona.jbv.thesis.data.IdentityToken;
import edu.arizona.jbv.thesis.networking.SSLClient;
import edu.arizona.jbv.thesis.utils.ThesisLog;
import edu.arizona.jbv.thesis.utils.ThesisTimer;
/**
* There is only one activity in the prototype app, and this is it. It has a
* dropdown for selecting which records will be requested, and three buttons to
* choose which trust server will be queried for the identity token. In this
* prototype, the client is known by all the trust servers, so querying any
* trust server results in an IdentityToken being returned. In a real
* application, only the trust server corresponding to the user's district would
* be likely to reply to identity token request.
*
* Asking for different health records results in different routes being taken
* when finding the trust server responsible for the correct health record
* server, but this goes on behind the scenes on the server.
*
* @author Jorge Vergara
*
*/
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new ButtonClick());
findViewById(R.id.button2).setOnClickListener(new ButtonClick());
findViewById(R.id.button3).setOnClickListener(new ButtonClick());
}
/**
* The NetworkThread makes the network requests to the trust server
*
* @author Jorge Vergara
*
*/
private class NetworkThread extends Thread {
private char server;
private String userID;
/**
* Sets up the NetworkThread. Start still needs to be called for any
* real work to be done.
*
* @param server
* The trust server to query. 'A', 'B', or 'C', currently.
* @param userID
* The userID to ask for. The userIDs are currently tied to
* the buttons
*/
public NetworkThread(char server, String userID) {
this.server = server;
this.userID = userID;
ThesisLog
.l("Asking TrustServer" + server + " for userID " + userID);
}
public void run() {
InputStream truststore = getResources().openRawResource(
R.raw.truststore);
InputStream clientstore = getResources().openRawResource(
R.raw.android);
SSLClient cli = new SSLClient(truststore, clientstore);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userID", userID));
String paramString = URLEncodedUtils
.format(postParameters, "utf-8");
HttpGet post = new HttpGet(
"https://dmft.cs.arizona.edu:8082/MobileTracker/Thesis/SSL/TrustServer"
+ server + "?" + paramString);
try {
ThesisLog.l("Requesting identity token. Starting timer");
ThesisTimer.startTimer();
HttpResponse resp = cli.execute(post);
long time = ThesisTimer.stopTimer();
ThesisLog.l("Finished. Total time was: " + time
+ " milliseconds");
InputStream is = resp.getEntity().getContent();
ObjectInputStream ois = new ObjectInputStream(is);
Object encodedCMSData = ois.readObject();
InputStream keystore = getResources().openRawResource(
R.raw.trustserverakeystore);
InputStream key = getResources().openRawResource(
R.raw.trustserverakey);
Encryptor enc = new CMSSignedDataEncryptor(keystore, key);
IdentityToken token = (IdentityToken) enc.byteToObject(enc
.decrypt(encodedCMSData));
HttpClient recordRequester = new DefaultHttpClient();
HttpPost post2 = new HttpPost(token.urlOfHealthRecordServer);
Encryptor aesEnc = new AES256Encryptor();
Object aesEncryptedCMSData = aesEnc.encrypt(encodedCMSData);
HttpEntity ent = new SerializableEntity(
(Serializable) aesEncryptedCMSData, false);
post2.setEntity(ent);
ThesisLog.l("Requesting health records. Starting timer");
ThesisTimer.startTimer();
HttpResponse resp2 = recordRequester.execute(post2);
time = ThesisTimer.stopTimer();
ThesisLog.l("Finished. Total time was: " + time
+ " milliseconds");
ObjectInputStream ois2 = new ObjectInputStream(resp2
.getEntity().getContent());
byte[] aesEncodedReply = (byte[]) ois2.readObject();
final String s2 = (String) aesEnc.byteToObject(aesEnc
.decrypt(aesEncodedReply));
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
"Request Completed: " + s2, Toast.LENGTH_SHORT)
.show();
}
});
ThesisLog.l(s2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
new AlertDialog.Builder(MainActivity.this).setTitle("Help")
.setMessage(getResources().getString(R.string.menu_text))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
;
}
}).show();
return true;
}
/**
* Listens to which trust server you are trying to query. Pulls the userID
* and send the request by starting up a NetworkThread.
*
* @author Jorge Vergara
*
*/
private class ButtonClick implements OnClickListener {
@Override
public void onClick(View arg0) {
Spinner spinner = (Spinner) findViewById(R.id.spinner);
String name = (String) spinner.getSelectedItem();
Button serverAButton = (Button) findViewById(R.id.button1);
Button serverBButton = (Button) findViewById(R.id.button2);
if (arg0 == serverAButton) {
new NetworkThread('A', name).start();
} else if (arg0 == serverBButton) {
new NetworkThread('B', name).start();
} else { // server C button
new NetworkThread('C', name).start();
}
}
}
}
| mit |
bignerdranch/expandable-recycler-view | expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/model/Parent.java | 653 | package com.bignerdranch.expandablerecyclerview.model;
import java.util.List;
/**
* Interface for implementing required methods in a parent.
*/
public interface Parent<C> {
/**
* Getter for the list of this parent's child items.
* <p>
* If list is empty, the parent has no children.
*
* @return A {@link List} of the children of this {@link Parent}
*/
List<C> getChildList();
/**
* Getter used to determine if this {@link Parent}'s
* {@link android.view.View} should show up initially as expanded.
*
* @return true if expanded, false if not
*/
boolean isInitiallyExpanded();
} | mit |
preslavc/SoftUni | Programing Basic/02.Simple Calculations/src/CircleAreaAndPerimeter.java | 377 |
import java.util.Scanner;
public class CircleAreaAndPerimeter {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double r = Double.parseDouble(console.nextLine());
double area = Math.PI * Math.pow(r, 2);
double perimeter = 2 * Math.PI * r;
console.close();
System.out.printf("Area = %s %nPerimeter = %s", area, perimeter);
}
}
| mit |
talandar/ProgressiveDifficulty | src/main/java/derpatiel/progressivediff/controls/FromSpawnerControl.java | 1460 | package derpatiel.progressivediff.controls;
import com.google.common.collect.Lists;
import derpatiel.progressivediff.api.DifficultyControl;
import derpatiel.progressivediff.SpawnEventDetails;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import java.util.List;
import java.util.function.Function;
/**
* Created by Jim on 5/1/2017.
*/
public class FromSpawnerControl extends DifficultyControl {
private static final String IDENTIFIER = "CONTROL_SPAWNER";
private int addedDifficulty;
public FromSpawnerControl(int addedDifficulty){
this.addedDifficulty = addedDifficulty;
}
@Override
public int getChangeForSpawn(SpawnEventDetails details) {
return details.fromSpawner ? addedDifficulty : 0;
}
@Override
public String getIdentifier() {
return IDENTIFIER;
}
public static Function<Configuration,List<DifficultyControl>> getFromConfig = config -> {
List<DifficultyControl> returns = Lists.newArrayList();
Property addedDifficultyFromSpawnerProp = config.get(IDENTIFIER,
"SpawnerAddedDifficulty", 10,"Difficulty added to a mob if it is from a spawner.");
int addedDifficultyIfSpawner = addedDifficultyFromSpawnerProp.getInt();
if(addedDifficultyIfSpawner!=0){
returns.add(new FromSpawnerControl(addedDifficultyIfSpawner));
}
return returns;
};
}
| mit |
rainu/jsimpleshell-rc | src/main/java/de/raysha/lib/jsimpleshell/rc/server/ServerSettings.java | 1117 | package de.raysha.lib.jsimpleshell.rc.server;
import java.net.ServerSocket;
import javax.crypto.SecretKey;
import de.raysha.lib.jsimpleshell.builder.ShellBuilder;
/**
* This class holds all informations for the {@link ShellServerBuilder}.
*
* @author rainu
*/
class ServerSettings {
private Integer port;
private ServerSocket socket;
private ShellBuilder shell;
private int connectionPoolSize;
private SecretKey secredKey;
public void setPort(Integer port) {
this.port = port;
}
public void setSocket(ServerSocket socket) {
this.socket = socket;
}
public void setShell(ShellBuilder shell) {
this.shell = shell;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public Integer getPort() {
return port;
}
public ServerSocket getSocket() {
return socket;
}
public ShellBuilder getShell() {
return shell;
}
public int getConnectionPoolSize() {
return connectionPoolSize;
}
public SecretKey getSecredKey() {
return secredKey;
}
public void setSecredKey(SecretKey secredKey) {
this.secredKey = secredKey;
}
}
| mit |
ewanld/fjdbc | src/main/java/com/github/fjdbc/op/CompositeOperation.java | 1936 | package com.github.fjdbc.op;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import com.github.fjdbc.ConnectionProvider;
import com.github.fjdbc.RuntimeSQLException;
/**
* Merge a sequence of {@link DbOperation} as a single {@link DbOperation}.
* <p>
* This allows the operations be executed in a single transaction.
*/
public class CompositeOperation implements DbOperation {
private final DbOperation[] operations;
private final ConnectionProvider cnxProvider;
/**
* @param connectionProvider
* The provider of {@link Connection} instances.
* @param operations
* The sequence of
*/
public CompositeOperation(ConnectionProvider connectionProvider, DbOperation... operations) {
this.cnxProvider = connectionProvider;
this.operations = operations;
}
public CompositeOperation(ConnectionProvider cnxProvider, Collection<? extends DbOperation> operations) {
this(cnxProvider, operations.toArray(new DbOperation[0]));
}
@Override
public int executeAndCommit() {
if (operations.length == 0) return 0;
Connection cnx = null;
try {
cnx = cnxProvider.borrow();
final int modifiedRows = execute(cnx);
cnxProvider.commit(cnx);
return modifiedRows;
} catch (final SQLException e) {
throw new RuntimeSQLException(e);
} finally {
// if the connection was already committed, roll back should be a no op.
cnxProvider.rollback(cnx);
cnxProvider.giveBack(cnx);
}
}
@Override
public int execute(Connection cnx) {
int modifiedRows = 0;
for (int i = 0; i < operations.length; i++) {
final DbOperation t = operations[i];
try {
modifiedRows += t.execute(cnx);
} catch (final SQLException e) {
throw new RuntimeSQLException(String.format("DB Operation %s/%s failed!", i + 1, operations.length),
e);
}
}
return modifiedRows;
}
} | mit |
atanasenev/ProgrammingBasics | FinalExam - PracticeProblems/src/p11_SpecialNumbers.java | 1310 | import java.util.Scanner;
/**
* Created by Atanas on 04/03/2017.
*/
public class p11_SpecialNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
for (int i = 1; i <= 9; i++) {
if (n % i == 0) {
num1 = i;
} else {
continue;
}
for (int j = 1; j <= 9; j++) {
if (n % j == 0) {
num2 = j;
} else {
continue;
}
for (int k = 1; k <= 9; k++) {
if (n % k == 0) {
num3 = k;
} else {
continue;
}
for (int l = 1; l <= 9; l++) {
if (n % l == 0) {
num4 = l;
System.out.printf("%d%d%d%d ", num1, num2, num3, num4);
} else {
continue;
}
}
}
}
}
}
}
| mit |
danielgimenes/SmashBrosTwitterAnalytics | SmashBrosTwitterStreamProcessor/src/br/com/dgimenes/smashbrostwitterstreamprocessor/util/SmashBrosTweetsFetcher.java | 3542 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Daniel Gimenes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package br.com.dgimenes.smashbrostwitterstreamprocessor.util;
import br.com.dgimenes.smashbrostwitterstreamprocessor.control.configuration.Configuration;
import br.com.dgimenes.smashbrostwitterstreamprocessor.exception.InvalidConfigurationFileException;
import br.com.dgimenes.smashbrostwitterstreamprocessor.persistence.model.TwitterAppAccount;
import twitter4j.Query;
import twitter4j.Query.ResultType;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class SmashBrosTweetsFetcher {
public static void main(String[] args) {
Configuration config;
if (args != null && args.length == 1) {
try {
config = Configuration.loadConfigFromFile(args[0]);
} catch (InvalidConfigurationFileException e) {
System.err.println("Invalid configuration file.\n");
printUsageMessage();
return;
}
} else {
printUsageMessage();
return;
}
TwitterAppAccount twitterAppAccount = config.getTwitterAppAccount();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(twitterAppAccount.getApiKey())
.setOAuthConsumerSecret(twitterAppAccount.getApiKeySecret())
.setOAuthAccessToken(twitterAppAccount.getAccessToken())
.setOAuthAccessTokenSecret(twitterAppAccount.getAccessTokenSecret());
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Query query = new Query();
query.setCount(5);
query.setQuery(config.getTweetTagsToTrack()[0]);
query.setResultType(ResultType.recent);
QueryResult result;
try {
result = twitter.search(query);
for (Status status : result.getTweets()) {
Logger.info("@" + status.getUser().getName() + " @" + status.getUser().getScreenName() + ":\n\t"
+ status.getText() + "\n", SmashBrosTweetsFetcher.class);
}
} catch (TwitterException e) {
e.printStackTrace();
}
}
private static void printUsageMessage() {
System.err
.println("Usage:\n\n\tjava -jar SmashBrosTwitterStreamProcessor.jar <configuration_file_path>\n\nConfiguration file should have the following data in Java Properties format:\n");
for (String configItemName : Configuration.getConfigurationItemNames()) {
System.err.println("\t" + configItemName);
}
System.err.println();
}
}
| mit |
UniversityOfBrightonComputing/iCirclesOriginal | src/main/java/icircles/recomposition/RecompositionStrategyType.java | 487 | package icircles.recomposition;
public enum RecompositionStrategyType {
NESTED("Recompose using zero-piercing (nesting)"),
SINGLY_PIERCED("Recompose using single piercings"),
DOUBLY_PIERCED("Recompose using double piercings"),
DOUBLY_PIERCED_EXTRA_ZONES("Recompose using dp with extra zones");
private String uiName;
public String getUiName() {
return uiName;
}
RecompositionStrategyType(String uiName) {
this.uiName = uiName;
}
}
| mit |
ShoukriKattan/ForgedUI-Eclipse | com.forgedui.editor/src/com/forgedui/editor/edit/command/PasteElementCommand.java | 4803 | package com.forgedui.editor.edit.command;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editparts.AbstractEditPart;
import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.jface.viewers.StructuredSelection;
import com.forgedui.editor.GUIEditor;
import com.forgedui.editor.GUIEditorPlugin;
import com.forgedui.model.Container;
import com.forgedui.model.Element;
import com.forgedui.model.titanium.ButtonBar;
import com.forgedui.model.titanium.Picker;
import com.forgedui.model.titanium.PickerColumn;
import com.forgedui.model.titanium.TabbedBar;
import com.forgedui.model.titanium.TitaniumUIBaseElement;
import com.forgedui.model.titanium.TitaniumUIBoundedElement;
import com.forgedui.model.titanium.TitaniumUIElement;
/**
*
* @author Zrieq
*
*/
public class PasteElementCommand extends Command {
private HashMap<Element, Element> list = new HashMap<Element, Element>();
private AbstractEditPart pasteTarget;
private List<EditPart> newTopLevelParts;
private GUIEditor guiEditor;
public PasteElementCommand(AbstractEditPart pasteTarget, GUIEditor guiEditor){
this.pasteTarget = pasteTarget;
this.guiEditor = guiEditor;
newTopLevelParts = new ArrayList<EditPart>();
}
@Override
public boolean canExecute() {
ArrayList<Element> bList = (ArrayList<Element>) Clipboard.getDefault()
.getContents();
if (bList == null || bList.isEmpty())
return false;
Iterator<Element> it = bList.iterator();
while (it.hasNext()) {
Element element = (Element) it.next();
if (isPastableElement(element)) {
list.put(element, null);
}else
return false;
}
return true;
}
@Override
public void execute() {
if (!canExecute())
return;
Iterator<Element> it = list.keySet().iterator();
while (it.hasNext()) {
Element element = (Element) it.next();
Element clone = cloneElement(element,(Container)pasteTarget.getModel());
list.put(element, clone);
newTopLevelParts.add(findEditPartForModel(pasteTarget,clone));
}
guiEditor.getGraphicalViewer().setSelection(new StructuredSelection(newTopLevelParts));
}
private EditPart findEditPartForModel(EditPart root,Element model) {
List<EditPart> children = root.getChildren();
for (EditPart editPart : children) {
if(editPart.getModel() == model)
return editPart;
else {
EditPart findEditPartForModel = findEditPartForModel(editPart,model);
if(findEditPartForModel != null)
return findEditPartForModel;
}
}
return null;
}
@Override
public void redo() {
Iterator<Element> it = list.values().iterator();
Container container = (Container)pasteTarget.getModel();
while (it.hasNext()) {
container.addChild(it.next());
}
}
@Override
public boolean canUndo() {
return !(list.isEmpty());
}
@Override
public void undo() {
Container container = (Container)pasteTarget.getModel();
for (Iterator<Element> iter = list.values().iterator(); iter.hasNext();)
container.removeChild(iter.next());
}
public boolean isPastableElement(Element element) {
if(element.getPlatform().compareTo(((Element)pasteTarget.getModel()).getPlatform()) != 0)
return false;
if(element instanceof Picker && !((Element)pasteTarget.getModel()).getPlatform().isAndroid())
return false;
return GUIEditorPlugin.getComponentValidator().validate(element, pasteTarget.getModel());
}
protected Element cloneElement(Element oldPart, Container newParent) {
Element newPart = null;
if (oldPart instanceof TitaniumUIBaseElement){
try {
newPart = ((TitaniumUIBaseElement)oldPart).getCopy();
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new IllegalStateException("Cant clone this: " + oldPart);
}
newParent.addChild(newPart);
if (oldPart instanceof Container) {
for (Element child : ((Container) oldPart).getChildren()) {
if(child != newPart && !GUIEditorPlugin.getComponentValidator().isAncestor(child,newPart))
cloneElement(child, (Container) newPart);
}
}
if (newPart instanceof TitaniumUIBoundedElement) {
TitaniumUIBoundedElement titNewPart = (TitaniumUIBoundedElement) newPart;
TitaniumUIBoundedElement titOldPart = (TitaniumUIBoundedElement) oldPart;
titNewPart.setWidth(titOldPart.getWidth());
titNewPart.setHeight(titOldPart.getHeight());
titNewPart.setLeft(titOldPart.getLeft());
titNewPart.setTop(titOldPart.getTop());
titNewPart.setRight(titOldPart.getRight());
titNewPart.setBottom(titOldPart.getBottom());
}
return newPart;
}
}
| mit |
feedeo/bingads-api | src/main/java/com/microsoft/bingads/v10/campaignmanagement/GetTargetsInfoFromLibraryRequest.java | 2331 | /**
* GetTargetsInfoFromLibraryRequest.java
* <p>
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.microsoft.bingads.v10.campaignmanagement;
public class GetTargetsInfoFromLibraryRequest implements java.io.Serializable {
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(GetTargetsInfoFromLibraryRequest.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v10", ">GetTargetsInfoFromLibraryRequest"));
}
private java.lang.Object __equalsCalc = null;
private boolean __hashCodeCalc = false;
public GetTargetsInfoFromLibraryRequest() {
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof GetTargetsInfoFromLibraryRequest)) return false;
GetTargetsInfoFromLibraryRequest other = (GetTargetsInfoFromLibraryRequest) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true;
__equalsCalc = null;
return _equals;
}
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
__hashCodeCalc = false;
return _hashCode;
}
}
| mit |
buj/boardgames | bgames/Bgames.java | 1483 | package bgames;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import bgames.other.ParseState;
public class Bgames {
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static void main(String[] args) {
if (args.length < 1) {
System.err.format("usage: java bgames.Bgames <input_file>\n");
return;
}
FileReader file = null;
try {
file = new FileReader(args[0]);
}
catch (FileNotFoundException exc) {
System.out.format("Specified file doesn't exist.\n");
return;
}
Scanner sc = new Scanner(file);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine()) {
builder.append(sc.nextLine());
builder.append("\n");
}
ParseState text = new ParseState(builder.toString());
World world = World.parse(text);
if (world != null) {
clearScreen();
System.out.format("%s\n", world.toString());
}
else {
System.out.format("Syntax error in specified file.\n");
return;
}
Scanner user = new Scanner(System.in);
while (user.hasNextLine()) {
String command = user.nextLine();
if (command.equals("")) {
World newWorld = world.next();
if (newWorld == world) {
break;
}
world = newWorld;
clearScreen();
System.out.format("%s\n", world.toString());
}
}
}
}
| mit |
sanelib/springils | core/src/main/java/org/sanelib/ils/core/commands/ProcessCommand.java | 190 | package org.sanelib.ils.core.commands;
import java.io.Serializable;
public interface ProcessCommand extends Serializable {
Class getRootEntityClass();
String getRootEntityName();
} | mit |
Mayo-WE01051879/mayosapp | Build/src/main/org/apache/tools/ant/util/regexp/JakartaRegexpRegexp.java | 3191 | /*
* 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.tools.ant.util.regexp;
import java.util.Vector;
import org.apache.regexp.RE;
import org.apache.tools.ant.BuildException;
/***
* Regular expression implementation using the Jakarta Regexp package
*/
public class JakartaRegexpRegexp extends JakartaRegexpMatcher
implements Regexp {
private static final int DECIMAL = 10;
/** Constructor for JakartaRegexpRegexp */
public JakartaRegexpRegexp() {
super();
}
/**
* Convert ant regexp substitution option to apache regex options.
*
* @param options the ant regexp options
* @return the apache regex substition options
*/
protected int getSubsOptions(int options) {
int subsOptions = RE.REPLACE_FIRSTONLY;
if (RegexpUtil.hasFlag(options, REPLACE_ALL)) {
subsOptions = RE.REPLACE_ALL;
}
return subsOptions;
}
/**
* Perform a substitution on the regular expression.
* @param input The string to substitute on
* @param argument The string which defines the substitution
* @param options The list of options for the match and replace.
* @return the result of the operation
* @throws BuildException on error
*/
public String substitute(String input, String argument, int options)
throws BuildException {
Vector v = getGroups(input, options);
// replace \1 with the corresponding group
StringBuffer result = new StringBuffer();
for (int i = 0; i < argument.length(); i++) {
char c = argument.charAt(i);
if (c == '\\') {
if (++i < argument.length()) {
c = argument.charAt(i);
int value = Character.digit(c, DECIMAL);
if (value > -1) {
result.append((String) v.elementAt(value));
} else {
result.append(c);
}
} else {
// TODO - should throw an exception instead?
result.append('\\');
}
} else {
result.append(c);
}
}
argument = result.toString();
RE reg = getCompiledPattern(options);
int sOptions = getSubsOptions(options);
return reg.subst(input, argument, sOptions);
}
}
| mit |
billhj/Etoile-java | Util/src/vib/core/util/environment/Root.java | 985 | /*
* This file is part of VIB (Virtual Interactive Behaviour).
*/
package vib.core.util.environment;
import vib.core.util.xml.XML;
import vib.core.util.xml.XMLTree;
/**
*
* @author Pierre Philippe
* @author Andre-Marie Pez
*/
public class Root extends TreeNode {
private Environment env = null;
public Root() {
}
Root(Environment env) {
this.env = env;
}
public Environment getEnvironment() {
return env;
}
@Override
protected String getXMLNodeName() {
return "environment";
}
@Override
protected XMLTree asXML(boolean doNonGuest, boolean doGest) {
XMLTree node = XML.createTree(getXMLNodeName());
for (Node child : getChildren()) {
if ((!child.isGuest() && doNonGuest) || (child.isGuest() && doGest)) {
node.addChild(child.asXML(doNonGuest, doGest));
}
}
return node;
}
}
| mit |
PlutoPowered/Nebula | src/main/java/com/gmail/socraticphoenix/nebula/lambda/many/Function69.java | 2531 | /*
* This file is an auto-generated element of the Nebula API, and retains the same license as listed in the license.txt
*/
package com.gmail.socraticphoenix.nebula.lambda.many;
public interface Function69<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P30, P31, P32, P33, P34, P35, P36, P37, P38, P39, P40, P41, P42, P43, P44, P45, P46, P47, P48, P49, P50, P51, P52, P53, P54, P55, P56, P57, P58, P59, P60, P61, P62, P63, P64, P65, P66, P67, P68, P69, R> extends Consumer69<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P30, P31, P32, P33, P34, P35, P36, P37, P38, P39, P40, P41, P42, P43, P44, P45, P46, P47, P48, P49, P50, P51, P52, P53, P54, P55, P56, P57, P58, P59, P60, P61, P62, P63, P64, P65, P66, P67, P68, P69> {
R invoke(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12, P13 p13, P14 p14, P15 p15, P16 p16, P17 p17, P18 p18, P19 p19, P20 p20, P21 p21, P22 p22, P23 p23, P24 p24, P25 p25, P26 p26, P27 p27, P28 p28, P29 p29, P30 p30, P31 p31, P32 p32, P33 p33, P34 p34, P35 p35, P36 p36, P37 p37, P38 p38, P39 p39, P40 p40, P41 p41, P42 p42, P43 p43, P44 p44, P45 p45, P46 p46, P47 p47, P48 p48, P49 p49, P50 p50, P51 p51, P52 p52, P53 p53, P54 p54, P55 p55, P56 p56, P57 p57, P58 p58, P59 p59, P60 p60, P61 p61, P62 p62, P63 p63, P64 p64, P65 p65, P66 p66, P67 p67, P68 p68, P69 p69);
@Override
default void call(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12, P13 p13, P14 p14, P15 p15, P16 p16, P17 p17, P18 p18, P19 p19, P20 p20, P21 p21, P22 p22, P23 p23, P24 p24, P25 p25, P26 p26, P27 p27, P28 p28, P29 p29, P30 p30, P31 p31, P32 p32, P33 p33, P34 p34, P35 p35, P36 p36, P37 p37, P38 p38, P39 p39, P40 p40, P41 p41, P42 p42, P43 p43, P44 p44, P45 p45, P46 p46, P47 p47, P48 p48, P49 p49, P50 p50, P51 p51, P52 p52, P53 p53, P54 p54, P55 p55, P56 p56, P57 p57, P58 p58, P59 p59, P60 p60, P61 p61, P62 p62, P63 p63, P64 p64, P65 p65, P66 p66, P67 p67, P68 p68, P69 p69) {
this.invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43, p44, p45, p46, p47, p48, p49, p50, p51, p52, p53, p54, p55, p56, p57, p58, p59, p60, p61, p62, p63, p64, p65, p66, p67, p68, p69);
}
}
| mit |
oleg-nenashev/remoting | src/main/java/org/jenkinsci/remoting/engine/JnlpProtocol1Handler.java | 6753 | /*
* The MIT License
*
* Copyright (c) 2004-2016, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.remoting.engine;
import hudson.remoting.Channel;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jenkinsci.remoting.nio.NioChannelHub;
import org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException;
/**
* Implementation of the JNLP-connect protocol.
*
* The slave sends the master the slave name it wants to register as and the
* computed HMAC of the slave name. If accepted the master will reply with a
* confirmation response.
*
* This was the first protocol supported by Jenkins. JNLP slaves will use this
* as a last resort when connecting to old versions of Jenkins masters.
*
* @since FIXME
*/
@Deprecated
public class JnlpProtocol1Handler extends LegacyJnlpProtocolHandler<LegacyJnlpConnectionState> {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(JnlpProtocol1Handler.class.getName());
/**
* Constructor.
*
* @param clientDatabase the client database to use or {@code null} if client connections will not be required.
* @param threadPool the {@link ExecutorService} to run tasks on.
* @param hub the {@link NioChannelHub} to use or {@code null} to use blocking I/O.
* @param preferNio {@code true} means that the protocol should attempt to use NIO if possible
*/
public JnlpProtocol1Handler(@Nullable JnlpClientDatabase clientDatabase, @Nonnull ExecutorService threadPool,
@Nullable NioChannelHub hub, boolean preferNio) {
super(clientDatabase, threadPool, hub, preferNio);
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "JNLP-connect";
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public LegacyJnlpConnectionState createConnectionState(@Nonnull Socket socket,
@Nonnull List<? extends JnlpConnectionStateListener> listeners)
throws IOException {
return new LegacyJnlpConnectionState(socket, listeners);
}
/**
* {@inheritDoc}
*/
@Override
void sendHandshake(@Nonnull LegacyJnlpConnectionState state, @Nonnull Map<String, String> headers)
throws IOException, ConnectionRefusalException {
String secretKey = headers.get(JnlpConnectionState.SECRET_KEY);
if (secretKey == null) {
throw new ConnectionRefusalException("Client headers missing " + JnlpConnectionState.SECRET_KEY);
}
String clientName = headers.get(JnlpConnectionState.CLIENT_NAME_KEY);
if (clientName == null) {
throw new ConnectionRefusalException("Client headers missing " + JnlpConnectionState.CLIENT_NAME_KEY);
}
// Initiate the handshake.
state.fireBeforeProperties();
DataOutputStream outputStream = state.getDataOutputStream();
outputStream.writeUTF(PROTOCOL_PREFIX + getName());
outputStream.writeUTF(secretKey);
outputStream.writeUTF(clientName);
outputStream.flush();
DataInputStream inputStream = state.getDataInputStream();
// Check if the server accepted.
String response = EngineUtil.readLine(inputStream);
if (!response.equals(GREETING_SUCCESS)) {
throw new ConnectionRefusalException("Server didn't accept the handshake: " + response);
}
// we don't get any headers from the server in JNLP-connect
state.fireAfterProperties(new HashMap<String, String>());
}
/**
* {@inheritDoc}
*/
@Override
void receiveHandshake(@Nonnull LegacyJnlpConnectionState state, @Nonnull Map<String, String> headers) throws IOException {
state.fireBeforeProperties();
final String secret = state.getDataInputStream().readUTF();
final String clientName = state.getDataInputStream().readUTF();
Map<String, String> properties = new HashMap<String, String>();
properties.put(JnlpConnectionState.CLIENT_NAME_KEY, clientName);
JnlpClientDatabase clientDatabase = getClientDatabase();
if (clientDatabase == null || !clientDatabase.exists(clientName)) {
throw new ConnectionRefusalException("Unknown client name: " + clientName);
}
String secretKey = clientDatabase.getSecretOf(clientName);
if (secretKey == null) {
throw new ConnectionRefusalException("Unknown client name: " + clientName);
}
if (!secretKey.equals(secret)) {
LOGGER.log(Level.WARNING, "An attempt was made to connect as {0} from {1} with an incorrect secret",
new Object[]{clientName, state.getSocket().getRemoteSocketAddress()});
throw new ConnectionRefusalException("Authorization failure");
}
state.fireAfterProperties(properties);
PrintWriter out = state.getPrintWriter();
out.println(GREETING_SUCCESS);
out.flush();
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
Channel buildChannel(@Nonnull LegacyJnlpConnectionState state) throws IOException {
return state.getChannelBuilder().build(state.getSocket());
}
}
| mit |
benjaminrclark/cate | src/main/java/org/cateproject/batch/convert/MapToStringConverter.java | 963 | package org.cateproject.batch.convert;
import java.util.Map;
import java.util.TreeSet;
import org.springframework.core.convert.converter.Converter;
public class MapToStringConverter implements Converter<Map<String,Object>,String>{
public String convert(Map<String,Object> map) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
boolean first = true;
for(String key : new TreeSet<String>(map.keySet())) {
if(!first) {
stringBuilder.append(",");
} else {
first = false;
}
Object value = map.get(key);
if(value instanceof Boolean) {
key = key + "_bool";
}
stringBuilder.append(key);
stringBuilder.append(":");
stringBuilder.append(value);
}
stringBuilder.append("]");
return stringBuilder.toString();
}
}
| mit |
SasPes/JavaSkop2017 | oauth2/src/test/java/com/saspes/oauth2/ApplicationTests.java | 3395 | package com.saspes.oauth2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class ApplicationTests {
@LocalServerPort
private int port;
private TestRestTemplate template = new TestRestTemplate();
@Test
public void homePageProtected() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String auth = response.getHeaders().getFirst("WWW-Authenticate");
assertTrue("Wrong header: " + auth, auth.startsWith("Bearer realm=\""));
}
@Test
public void userEndpointProtected() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/user", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String auth = response.getHeaders().getFirst("WWW-Authenticate");
assertTrue("Wrong header: " + auth, auth.startsWith("Bearer realm=\""));
}
@Test
public void authorizationRedirects() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/oauth/authorize", String.class);
assertEquals(HttpStatus.FOUND, response.getStatusCode());
String location = response.getHeaders().getFirst("Location");
assertTrue("Wrong header: " + location,
location.startsWith("http://localhost:" + port + "/uaa/login"));
}
@Test
public void loginSucceeds() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/login", String.class);
String csrf = getCsrf(response.getBody());
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("username", "test");
form.set("password", "test");
form.set("_csrf", csrf);
HttpHeaders headers = new HttpHeaders();
headers.put("COOKIE", response.getHeaders().get("Set-Cookie"));
RequestEntity<MultiValueMap<String, String>> request = new RequestEntity<MultiValueMap<String, String>>(
form, headers, HttpMethod.POST, URI.create("http://localhost:" + port
+ "/uaa/login"));
ResponseEntity<Void> location = template.exchange(request, Void.class);
assertEquals("http://localhost:" + port + "/uaa/",
location.getHeaders().getFirst("Location"));
}
private String getCsrf(String soup) {
Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*")
.matcher(soup);
if (matcher.matches()) {
return matcher.group(1);
}
return null;
}
}
| mit |
ajhalbleib/aicg | appinventor/appengine/src/com/google/appinventor/client/properties/json/ClientJsonBoolean.java | 905 | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package com.google.appinventor.client.properties.json;
import com.google.appinventor.shared.properties.json.JSONBoolean;
/**
* Implementation of {@link JSONBoolean} that uses the GWT JSON library.
*
* @author lizlooney@google.com (Liz Looney)
*/
final class ClientJsonBoolean extends ClientJsonValue implements JSONBoolean {
private final boolean value;
public ClientJsonBoolean(com.google.gwt.json.client.JSONBoolean value) {
this.value = value.booleanValue();
}
@Override
public boolean getBoolean() {
return value;
}
@Override
public String toJson() {
return Boolean.toString(value);
}
}
| mit |
alexwang3322/bs-android | example/src/main/java/com/bugsnag/android/example/ExampleActivity2.java | 3757 | package com.bugsnag.android.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.bugsnag.android.BeforeNotify;
import com.bugsnag.android.Bugsnag;
import com.bugsnag.android.MetaData;
import com.bugsnag.android.Severity;
import com.bugsnag.android.other.Other;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static android.widget.Toast.LENGTH_SHORT;
public class ExampleActivity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initBugSnag();
}
private void initBugSnag() {
// Initialize the Bugsnag client
Bugsnag.init(this);
Bugsnag.enableExceptionHandler();
// Execute some code before every bugsnag notification
Bugsnag.beforeNotify(new BeforeNotify() {
@Override
public boolean run(com.bugsnag.android.Error error) {
System.out.println(String.format("In beforeNotify - %s", error.getExceptionName()));
return true;
}
});
// Set the user information
Bugsnag.setUser("123456", "james@example.com", "James Smith");
Bugsnag.setProjectPackages("com.bugsnag.android.example", "com.bugsnag.android.other");
// Add some global metaData
Bugsnag.addToTab("user", "age", 31);
Bugsnag.addToTab("custom", "account", "something");
Bugsnag.leaveBreadcrumb("onCreate");
new Thread(new Runnable() {
public void run() {
try {
sleepSoundly();
} catch (java.lang.InterruptedException e) {
}
}
private void sleepSoundly() throws java.lang.InterruptedException {
Thread.sleep(100000);
}
}).start();
}
public void sendError(View view) {
actuallySendError();
}
private void actuallySendError() {
Bugsnag.notify(new RuntimeException("Non-fatal error"), Severity.ERROR);
Toast.makeText(this, "Sent error", LENGTH_SHORT).show();
}
public void sendWarning(View view) {
actuallySendWarning();
}
private void actuallySendWarning() {
Bugsnag.notify(new RuntimeException("Non-fatal warning"), Severity.WARNING);
Toast.makeText(this, "Sent warning", LENGTH_SHORT).show();
}
public void sendInfo(View view) {
Bugsnag.notify(new RuntimeException("Non-fatal info"), Severity.INFO);
Toast.makeText(this, "Sent info", LENGTH_SHORT).show();
}
/** no meta data */
public void sendErrorWithMetaData(View view) {
Map<String, String> nested = new HashMap<String, String>();
nested.put("normalkey", "normalvalue");
nested.put("password", "s3cr3t");
Collection list = new ArrayList();
list.add(nested);
MetaData metaData = new MetaData();
metaData.addToTab("user", "payingCustomer", true);
metaData.addToTab("user", "password", "p4ssw0rd");
metaData.addToTab("user", "credentials", nested);
metaData.addToTab("user", "more", list);
Bugsnag.notify(new RuntimeException("Non-fatal error with metaData"), Severity.ERROR, metaData);
Toast.makeText(this, "Sent error with metaData", LENGTH_SHORT).show();
}
public void withMyInformation(View view) {
MetaData metaData = new MetaData();
metaData.addToTab("user", "name", "alex");
Bugsnag.notify(null, metaData);
}
public void crash(View view) {
Other other = new Other();
other.meow();
}
}
| mit |
dineshvg/CADReader | src/de/tudarmstadt/dik/express/Constants.java | 1020 | /**
*
*/
package de.tudarmstadt.dik.express;
/**
* @author dinesh
*
*/
public class Constants {
public static final String DIR_PATH = "//home/dinesh/Semantic_Web_HiWi/express_file_dir";
public static final String MASTER_WORD = "REFERENCE";
public static final String LOGGER_PATH = "//home/dinesh/Semantic_Web_HiWi/express_file_dir/loggerData.txt";
public static final int TRUE_CASE = 0;
public static final String REFERENCE_FINDER = " ";
public static final String ISO_FINDER = "--";
public static final String ISO_REFACTOR = "-";
public static final String ENTITY_REFERENCE_FINDER = "REFERENCE FROM";
public static final String ENTITY_SEPERATOR = "ENTITYSEPERATOR";
public static final String ENTITY_END = ");";
public static final String ENTITY_START = "(";
public static final String ENTITY_COMMA_SEPERATOR = ",";
public static final String ENTITY_WORD_AS = "AS";
public static final String ENTITY_SEARCH_START = "ENTITY ";
public static final String ENTITY_SEARCH_END = "END_ENTITY;";
}
| mit |
jansoren/akka-persistence-java-example | mymicroservice-server/src/test/java/no/jansoren/mymicroservice/eventsourcing/ProjectionTest.java | 280 | package no.jansoren.mymicroservice.eventsourcing;
import no.jansoren.akka.persistence.eventsourcing.Projection;
import org.junit.Test;
public class ProjectionTest {
@Test
public void testProjectionNoMethods() {
Projection projection = new Projection();
}
}
| mit |
shikhar29111996/Java-programs | tictactoe.java | 1828 | import java.io.*;
class tictactoe
{
public static void main()throws IOException
{
BufferedReader dr=new BufferedReader(new InputStreamReader(System.in));
int i,j,a=2,r,c,s=0;
int g[][]=new int[3][3];
System.out.println(" WELCOME TO SHIKHAR'S TIC TAC TOE GAME ");
System.out.println("It's a two player game");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(a%2==0)
{
System.out.println("\nenter the numeral 1 in terms of row and column");
r=Integer.parseInt(dr.readLine());
c=Integer.parseInt(dr.readLine());
g[r-1][c-1]=1;
}
else
{
System.out.println("enter the numeral 0 in terms of row and column");
r=Integer.parseInt(dr.readLine());
c=Integer.parseInt(dr.readLine());
g[r-1][c-1]=0;
}
a++;
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(g[i][j]);
}
System.out.println();
}
// checking the condition of winning of one(1)//
{
for(i=0;i<3;i++)
{
s=0;
for(j=0;j<3;j++)
{
s=s+g[j][i];
}
if(s==3)
{
System.out.println("1 wins");
break;
}
}
for(i=0;i<3;i++)
{
s=0;
for(j=0;j<3;j++)
{
s=s+g[i][j];
}
if(s==3)
{
System.out.println("1-wins");
break;
}
}
s=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
s=s+g[i][j];
}
}
if(s==3)
{
System.out.println("1-wins");
}
s=0;
}
//checking the condition of winning zero(0)//
{
for(i=0;i<3;i++)
{
s=0;
for(j=0;j<3;j++)
{
s=s+g[j][i];
}
if(s==0)
{
System.out.println("0 wins");
break;
}
}
for(i=0;i<3;i++)
{
s=0;
for(j=0;j<3;j++)
{
s=s+g[i][j];
}
if(s==0)
{
System.out.println("0-wins");
break;
}
}
s=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
s=s+g[i][j];
}
}
if(s==0)
{
System.out.println("0-wins");
}
s=0;
}
//CHECKING FOR DRAW CONDITION//
{
if((s>0&&s!=3)||(s>3))
System.out.println("it's a draw");
}
}
} | mit |
vvision/R4D2 | tower/frameworks/ExampleBmp/java/com/android/utbm/lo52/libbmp/Example.java | 358 | package com.android.utbm.lo52.libbmp;
import android.util.Log;
public class Example {
static {
Log.d("pwet", "Loading....");
System.loadLibrary("bmpExample_jni");
}
public native int bpmFunction(String filename, int width, int height, int depth);
public Example() {
}
public static void main (){
bmpFunction("file", 50, 50, 32);
}
}
| mit |
sim642/shy | app/src/main/java/ee/shy/cli/command/remote/RemoveCommand.java | 1116 | package ee.shy.cli.command.remote;
import ee.shy.cli.Command;
import ee.shy.cli.HelptextBuilder;
import ee.shy.core.LocalRepository;
import ee.shy.core.Repository;
import java.io.IOException;
/**
* Command for removing remotes.
*/
public class RemoveCommand implements Command {
@Override
public void execute(String[] args) throws IOException {
if (args.length >= 1) {
Repository repository = LocalRepository.newExisting();
repository.getRemotes().remove(args[0]);
} else
System.err.println("Not enough parameters. See 'shy help remote'.");
}
@Override
public String getHelp() {
return new HelptextBuilder()
.addWithArgs("<name>", "Remove remote with given name")
.create();
}
@Override
public String getHelpBrief() {
return "Remove remotes";
}
@Override
public String[] getCompletion(String[] args) throws IOException {
Repository repository = LocalRepository.newExisting();
return repository.getRemotes().keySet().toArray(new String[0]);
}
}
| mit |
disis/disis-simulator-java | src/demo/Demo.java | 6294 | package demo;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.ClassNamesResourceConfig;
import core.configuration.ConfigurationLoader;
import core.configuration.LocalConfiguration;
import core.disis.DisisController;
import core.disis.RestSimulatorInfo;
import core.disis.SimulatorRestResource;
import core.disis.StaticContext;
import core.simulator.ScheduledEvent;
import core.simulator.SimulationModel;
import core.simulator.Simulator;
import demo.model.ticker.CounterEvent;
import demo.model.ticker.TickerModel;
import org.glassfish.grizzly.http.server.HttpServer;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is DISIS
* Authors: Jirka Penzes & Jan Voracek
* Date: 21. 6. 2014 8:07
*/
public class Demo {
public static void main(String[] args) throws IOException {
Map<String, Object> conf1 = new HashMap<>();
conf1.put("path", "src/demo/configuration/demo2/configuration-sample-1.json");
conf1.put("start-time", 0.0);
conf1.put("delay", 100l);
Map<String, Object> conf2 = new HashMap<>();
conf2.put("path", "src/demo/configuration/demo2/configuration-sample-2.json");
conf2.put("start-time", 1.0);
conf2.put("delay", 100l);
runSimulator(conf2);
System.in.read();
}
private static void runSimulator(Map<String, Object> conf) throws IOException {
String configurationPath = new File((String) conf.get("path")).getAbsolutePath();
LocalConfiguration configuration = ConfigurationLoader.load(configurationPath, LocalConfiguration.class);
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(configuration.getSimulatorFullAddress(), new ClassNamesResourceConfig(SimulatorRestResource.class));
httpServer.start();
Simulator simulator = new Simulator(new TickerModel(2, (Double) conf.get("start-time")), new SleepInvoker((Long) conf.get("delay")));
DisisController controller = new DisisController(configuration, simulator);
StaticContext.init(controller);
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(configuration.getDisisFullAddress()).path("connect");
RestSimulatorInfo clientInfo = new RestSimulatorInfo(
configuration.getTitle(),
configuration.getName(),
configuration.getDescription(),
configuration.getSimulatorFullAddress(),
configuration.getSurroundingSimulators());
Gson gson = new Gson();
resource.type(MediaType.APPLICATION_JSON).post(gson.toJson(clientInfo));
}
private static Client connectSimulator(LocalConfiguration configuration) throws IOException {
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(configuration.getSimulatorFullAddress(), new ClassNamesResourceConfig(SimulatorRestResource.class));
httpServer.start();
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(configuration.getDisisFullAddress()).path("connect");
RestSimulatorInfo clientInfo = new RestSimulatorInfo(
configuration.getTitle(),
configuration.getName(),
configuration.getDescription(),
configuration.getSimulatorFullAddress(),
configuration.getSurroundingSimulators());
Gson gson = new Gson();
resource.type(MediaType.APPLICATION_JSON).post(gson.toJson(clientInfo));
return client;
}
public static void demo1() throws IOException {
String configurationPath = new File("src/demo/configuration/demo1/configuration-sample.json").getAbsolutePath();
LocalConfiguration configuration = ConfigurationLoader.load(configurationPath, LocalConfiguration.class);
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(configuration.getSimulatorFullAddress(), new ClassNamesResourceConfig(SimulatorRestResource.class));
httpServer.start();
Simulator simulator = new Simulator(new TickerModel(1, 0.0), new SleepInvoker(100));
DisisController controller = new DisisController(configuration, simulator);
StaticContext.init(controller);
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(configuration.getDisisFullAddress()).path("connect");
RestSimulatorInfo clientInfo = new RestSimulatorInfo(
configuration.getTitle(),
configuration.getName(),
configuration.getDescription(),
configuration.getSimulatorFullAddress(),
configuration.getSurroundingSimulators());
Gson gson = new Gson();
resource.type(MediaType.APPLICATION_JSON).post(gson.toJson(clientInfo));
System.in.read();
}
private static void simulatorDemo() {
Simulator simulator = new Simulator(new SimulationModel() {
@Override
public void prepare() {
}
@Override
public Iterable<ScheduledEvent> getInitialEvents() {
List<ScheduledEvent> events = new ArrayList<>();
events.add(new ScheduledEvent(new CounterEvent(100), 0));
return events;
}
}, new SleepInvoker(1000));
simulator.simulate();
}
public static void restClient() {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource("http://localhost:8099/disis/test");
String response = resource.accept(MediaType.TEXT_PLAIN).post(String.class);
System.out.println(response);
}
}
| mit |
kushal-r/MyWorkspace | DS&Algorithms/src/com/g4g/algorithms/backtracking/NQueenProblem.java | 1698 | /**
* https://www.geeksforgeeks.org/backtracking-set-3-n-queen-problem/
*/
package com.g4g.algorithms.backtracking;
/**
* @author kushal
*
*/
public class NQueenProblem {
private static final int N = 4;
public static boolean isSafe(int[][] board, int row, int col) {
// Check the row till COL
for (int i = 0; i < col; i++) {
if (board[row][i] == 1)
return false;
}
// Check the upper left diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1)
return false;
}
// Check the lower left diagonal
for (int i = row, j = col; i < N && j >= 0; i++, j--) {
if (board[i][j] == 1)
return false;
}
return true;
}
public static boolean placeQueensHepler(int[][] board, int col) {
if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (placeQueensHepler(board, col + 1))
return true;
board[i][col] = 0;
}
}
return false;
}
public static boolean placeNQueens(int[][] board) {
if (placeQueensHepler(board, 0) == false) {
System.out.println("Solution does not exist");
return false;
}
printPositions(board);
return true;
}
public static void printPositions(int board[][]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(" " + board[i][j] + " ");
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
int board[][] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
placeNQueens(board);
}
}
| mit |
strayfluxinteractive/castrum | html/src/com/strayfluxinteractive/castrum/client/HtmlLauncher.java | 617 | package com.strayfluxinteractive.castrum.client;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.strayfluxinteractive.castrum.Castrum;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
return new GwtApplicationConfiguration(480, 320);
}
@Override
public ApplicationListener getApplicationListener () {
return new Castrum();
}
} | mit |
luiztrisoft/Sistema-web-para-eventos-academicos | eventos/src/main/java/br/com/trisoft/eventos/controller/RecuperarSenhaPorEmailMB.java | 1417 | package br.com.trisoft.eventos.controller;
import java.io.Serializable;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.outjected.email.api.MailMessage;
import br.com.trisoft.eventos.model.Usuario;
import br.com.trisoft.eventos.service.UsuarioService;
import br.com.trisoft.eventos.util.jsf.FacesUtil;
import br.com.trisoft.eventos.util.mail.Mailer;
@Named
@ViewScoped
public class RecuperarSenhaPorEmailMB implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Mailer mailer;
@Inject
private Usuario usuario;
@Inject
private UsuarioService service;
public void iniciar() {
if (usuario == null) {
limpar();
}
}
private void limpar() {
usuario = new Usuario();
}
public void senha() {
usuario = service.buscarPorEmail(usuario.getEmail().toLowerCase());
if (usuario != null) {
MailMessage message = mailer.novaMensagem();
message.to(this.usuario.getEmail()).subject("TriSoft Eventos")
.bodyHtml("<strong>senha: </strong> " + this.usuario.getSenha()).send();
FacesUtil.addInfoMessage("Confira seu e-mail para ter acesso a sua senha");
} else {
FacesUtil.addErrorMessage("Este e-mail não foi encontrado no sistema");
}
limpar();
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
| mit |
nikeshmhr/StudyBuddie | src/test/java/com/studybuddie/tests/UserCredentialTest.java | 1188 | package com.studybuddie.tests;
import com.studybuddie.config.DataConfig;
import com.studybuddie.config.RootConfig;
import com.studybuddie.config.WebConfig;
import com.studybuddie.data.UserCredential;
import com.studybuddie.data.UserCredentialRepo;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* @author Nikesh
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RootConfig.class})
public class UserCredentialTest {
@Autowired
private UserCredential jdbc;
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
@Test
public void hello() {
assertNotNull(jdbc);
assertNotNull(jdbc.getListOfFieldOfStudy());
System.out.println("List Size: " + jdbc.getListOfFieldOfStudy().size());
}
}
| mit |
pjoc-team/pjoc-pay | pjoc-event/src/main/java/pub/pjoc/pay/event/manager/impl/PayEventManagerImpl.java | 5782 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 pjoc.pub, blademainer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package pub.pjoc.pay.event.manager.impl;
import com.xiongyingqi.util.Assert;
import com.xiongyingqi.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pub.pjoc.common.entity.ReturnResult;
import pub.pjoc.pay.event.PayFailedListener;
import pub.pjoc.pay.event.PayRequestInterceptedListener;
import pub.pjoc.pay.event.PayRequestedListener;
import pub.pjoc.pay.event.PaySuccessListener;
import pub.pjoc.pay.event.manager.PayEventManager;
import pub.pjoc.pay.interceptor.InterceptResult;
import pub.pjoc.pay.threadpool.asynchronous.AsynchronousInvokerService;
import pub.pjoc.pay.vo.PayRequest;
import java.util.List;
/**
* Default implementation of pay event manager.
*
* @author blademainer
* @version 2016-08-31 21:57
*/
public class PayEventManagerImpl implements PayEventManager {
private static final Logger logger = LoggerFactory.getLogger(PayEventManagerImpl.class);
private List<PayRequestedListener> requestListeners;
private List<PayRequestInterceptedListener> interceptedListeners;
private List<PaySuccessListener> successListeners;
private List<PayFailedListener> failedListeners;
private AsynchronousInvokerService asynchronousInvokerService;
public PayEventManagerImpl(AsynchronousInvokerService asynchronousInvokerService) {
Assert.notNull(asynchronousInvokerService, "AsynchronousInvokerService must not be null!");
this.asynchronousInvokerService = asynchronousInvokerService;
}
@Override
public void notifyPayRequested(PayRequest request) {
if (asynchronousInvokerService == null || CollectionUtils.isEmpty(requestListeners)) {
return;
}
asynchronousInvokerService.submit(() -> {
requestListeners.forEach(x -> {
try {
x.payRequested(request);
} catch (Exception e) {
logger.error("A error occurred when notify to listener: " + x + " and error message: "
+ e.getMessage(), e);
}
});
return true;
});
}
@Override
public void notifyPayRequestSuccess(PayRequest request) {
if (asynchronousInvokerService == null || CollectionUtils.isEmpty(successListeners)) {
return;
}
asynchronousInvokerService.submit(() -> {
successListeners.forEach(x -> {
try {
x.payRequestSuccess(request);
} catch (Exception e) {
logger.error("A error occurred when notify to listener: " + x + " and error message: "
+ e.getMessage(), e);
}
});
return true;
});
}
@Override
public void notifyPayFailed(PayRequest request, ReturnResult failResult) {
if (asynchronousInvokerService == null || CollectionUtils.isEmpty(failedListeners)) {
return;
}
asynchronousInvokerService.submit(() -> {
failedListeners.forEach(x -> {
try {
x.payFailed(request, failResult);
} catch (Exception e) {
logger.error("A error occurred when notify to listener: " + x + " and error message: "
+ e.getMessage(), e);
}
});
return true;
});
}
@Override
public void notifyPayRequestIntercepted(PayRequest request, InterceptResult interceptResult) {
if (asynchronousInvokerService == null || CollectionUtils.isEmpty(interceptedListeners)) {
return;
}
asynchronousInvokerService.submit(() -> {
interceptedListeners.forEach(x -> {
try {
x.payRequestIntercepted(request, interceptResult);
} catch (Exception e) {
logger.error("A error occurred when notify to listener: " + x + " and error message: "
+ e.getMessage(), e);
}
});
return true;
});
}
public List<PayRequestedListener> getRequestListeners() {
return requestListeners;
}
public void setRequestListeners(List<PayRequestedListener> requestListeners) {
this.requestListeners = requestListeners;
}
public List<PayRequestInterceptedListener> getInterceptedListeners() {
return interceptedListeners;
}
public void setInterceptedListeners(List<PayRequestInterceptedListener> interceptedListeners) {
this.interceptedListeners = interceptedListeners;
}
public List<PaySuccessListener> getSuccessListeners() {
return successListeners;
}
public void setSuccessListeners(List<PaySuccessListener> successListeners) {
this.successListeners = successListeners;
}
public List<PayFailedListener> getFailedListeners() {
return failedListeners;
}
public void setFailedListeners(List<PayFailedListener> failedListeners) {
this.failedListeners = failedListeners;
}
}
| mit |
janisstreib/nan-hotline | webFrontend/src/me/streib/janis/nanhotline/web/pages/Page.java | 2349 | package me.streib.janis.nanhotline.web.pages;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.regex.Matcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import me.streib.janis.nanhotline.web.dbobjects.Supporter;
import org.cacert.gigi.output.template.Template;
public abstract class Page {
private Template defaultTemplate;
private String name;
public static final SimpleDateFormat DE_FROMAT_DATE = new SimpleDateFormat(
"dd.MM.yyyy HH:mm");
public Page(String name) {
this.name = name;
if (needsTemplate()) {
URL resource = getClass().getResource(
getClass().getSimpleName() + ".templ");
if (resource != null) {
defaultTemplate = new Template(resource);
}
}
}
/**
* By default, {@link #doGet()} is called.
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp,
Map<String, Object> vars, Matcher match) throws IOException,
SQLException {
doGet(req, resp, vars, match);
}
public void doPut(HttpServletRequest req, HttpServletResponse resp,
Map<String, Object> vars, Matcher match) throws IOException,
SQLException {
doGet(req, resp, vars, match);
}
public void doDelete(HttpServletRequest req, HttpServletResponse resp,
Map<String, Object> vars, Matcher match) throws IOException,
SQLException {
doGet(req, resp, vars, match);
}
public abstract void doGet(HttpServletRequest req,
HttpServletResponse resp, Map<String, Object> vars, Matcher match)
throws IOException, SQLException;
public String getName() {
return name;
}
public Template getDefaultTemplate() {
return defaultTemplate;
}
public abstract boolean needsLogin();
public abstract boolean needsTemplate();
public static boolean isLoggedIn(HttpServletRequest req) {
return req.getSession().getAttribute("user") != null;
}
public static Supporter getUser(HttpServletRequest req) {
return (Supporter) req.getSession().getAttribute("user");
}
}
| mit |
openpizza/openpizza-android | src/de/openpizza/android/views/ProductView.java | 2950 | package de.openpizza.android.views;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import de.openpizza.android.R;
import de.openpizza.android.ordermodul.OrderFacade;
import de.openpizza.android.service.data.Product;
public class ProductView extends ActionBarActivity {
private static Product product;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_view);
String productExtra = getIntent().getStringExtra("product");
product = new Gson().fromJson(productExtra, Product.class);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.product_view, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.finish_edit_button) {
saveItem();
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveItem() {
EditText quanEditText = (EditText) findViewById(R.id.product_count);
// TODO: Update product if it dose allready exist
Integer quantity = 0;
try {
quantity = Integer.parseInt(quanEditText.getText().toString());
} catch (Exception e) {
}
OrderFacade.addProduct(product, quantity);
finish();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_product_view,
container, false);
TextView nameView = (TextView) rootView
.findViewById(R.id.product_name);
nameView.setText(product.getName());
TextView descView = (TextView) rootView
.findViewById(R.id.product_desc);
descView.setText("");
List<Product> products = OrderFacade.getProductList();
for (Product p : products) {
if (p.getId() == product.getId()) {
TextView countView = (TextView) rootView
.findViewById(R.id.product_count);
countView.setText(product.getQuantity() + "");
}
}
return rootView;
}
}
}
| mit |
jimkyndemeyer/js-graphql-intellij-plugin | src/main/com/intellij/lang/jsgraphql/endpoint/JSGraphQLEndpointSpellcheckingStrategy.java | 1236 | /*
* Copyright (c) 2015-present, Jim Kynde Meyer
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.intellij.lang.jsgraphql.endpoint;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import com.intellij.spellchecker.inspections.IdentifierSplitter;
import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import com.intellij.spellchecker.tokenizer.TokenizerBase;
import org.jetbrains.annotations.NotNull;
public class JSGraphQLEndpointSpellcheckingStrategy extends SpellcheckingStrategy {
private static final TokenizerBase<PsiElement> IDENTIFIER_TOKENIZER = new TokenizerBase<>(IdentifierSplitter.getInstance());
@NotNull
@Override
public Tokenizer getTokenizer(PsiElement element) {
if (element.getParent() instanceof PsiNameIdentifierOwner) {
return EMPTY_TOKENIZER;
}
if (element.getNode().getElementType() == JSGraphQLEndpointTokenTypes.IDENTIFIER) {
return IDENTIFIER_TOKENIZER;
}
return super.getTokenizer(element);
}
}
| mit |
danimaniarqsoft/asterix-gen | asterix-modules/asterix-shell-core/src/main/java/org/springframework/shell/converters/StringConverter.java | 1555 | /*
* Copyright 2011-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.converters;
import java.util.List;
import org.springframework.shell.core.Completion;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.MethodTarget;
/**
* {@link Converter} for {@link String}.
*
* @author Ben Alex
* @since 1.0
*/
public class StringConverter implements Converter<String> {
public String convertFromText(final String value, final Class<?> requiredType, final String optionContext) {
return value;
}
public boolean getAllPossibleValues(final List<Completion> completions, final Class<?> requiredType, final String existingData, final String optionContext, final MethodTarget target) {
return false;
}
public boolean supports(final Class<?> requiredType, final String optionContext) {
return String.class.isAssignableFrom(requiredType) && (optionContext == null || !optionContext.contains("disable-string-converter"));
}
}
| mit |
homelinen/ld23-Tiny-World | core/src/main/java/com/calumgilchrist/ld23/tinyworld/core/Menu.java | 2458 | package com.calumgilchrist.ld23.tinyworld.core;
import static playn.core.PlayN.graphics;
import java.util.ArrayList;
import playn.core.CanvasLayer;
import playn.core.Font;
import playn.core.Layer;
import playn.core.TextFormat;
import playn.core.TextLayout;
public class Menu {
Font titleFont;
Font textFont;
int startY;
public TextLayout layout;
Layer layer;
String titleText;
ArrayList<String> menuItems;
public Menu(String titleText, int startY) {
titleFont = graphics().createFont("Courier", Font.Style.BOLD, 32);
textFont = graphics().createFont("Courier", Font.Style.BOLD, 24);
this.titleText = titleText;
this.startY = startY;
menuItems = new ArrayList<String>();
}
public void addMenuItem(String itemText) {
menuItems.add(itemText);
}
public void setTitleFont(Font font) {
titleFont = font;
}
public void setTextFont(Font font) {
textFont = font;
}
public Layer getTitle() {
String text = "Tiny World";
layout = graphics().layoutText(
text,
new TextFormat().withFont(titleFont)
.withWrapping(200, TextFormat.Alignment.CENTER)
.withEffect(TextFormat.Effect.shadow(0x33000000, 2, 2))
.withTextColor(0xFFFFFFFF));
layer = createTextLayer(layout);
layer.setTranslation((graphics().width() / 2) - (layout.width() / 2),
startY);
return layer;
}
public ArrayList<MenuItem> getMenuItems() {
ArrayList<MenuItem> returnItems = new ArrayList<MenuItem>();
for (int i = 0; i < menuItems.size(); i++) {
int posX, posY;
layout = graphics().layoutText(
menuItems.get(i),
new TextFormat()
.withFont(textFont)
.withWrapping(200, TextFormat.Alignment.CENTER)
.withEffect(
TextFormat.Effect.shadow(0x33000000, 2, 2))
.withTextColor(0xFFFFFFFF));
layer = createTextLayer(layout);
posX = (int) ((graphics().width() / 2) - (layout.width() / 2));
posY = startY + (100 * (((graphics().height() - 480)/480)+1) * (i+1));
layer.setTranslation(posX,posY);
MenuItem mi = new MenuItem(posX,posY,layout,layer,menuItems.get(i));
returnItems.add(mi);
}
Globals.numOfMenuItems = returnItems.size();
return returnItems;
}
protected Layer createTextLayer(TextLayout layout) {
@SuppressWarnings("deprecation")
CanvasLayer layer = graphics().createCanvasLayer(
(int) Math.ceil(layout.width()),
(int) Math.ceil(layout.height()));
layer.canvas().drawText(layout, 0, 0);
return layer;
}
} | mit |
Aloomaio/unlimited-kafka | src/main/java/com/alooma/unlimited_kafka/packer/s3/S3ManagerParams.java | 2031 | package com.alooma.unlimited_kafka.packer.s3;
import com.alooma.unlimited_kafka.packer.StorageManagerParams;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
public class S3ManagerParams implements StorageManagerParams {
private Long multipartUploadThreshold;
private Long minimumUploadPartSize;
private Integer threadPoolSize;
private String directoryNamePrefix;
private DateTimeFormatter dateTimeFormatter;
private boolean shouldUploadAsGzip = false;
public void setMultipartUploadThreshold(long multipartUploadThreshold) {
this.multipartUploadThreshold = multipartUploadThreshold;
}
public void setMinimumUploadPartSize(long minimumUploadPartSize) {
this.minimumUploadPartSize = minimumUploadPartSize;
}
public void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
public void setShouldUploadAsGzip(boolean shouldUploadAsGzip) {
this.shouldUploadAsGzip = shouldUploadAsGzip;
}
public boolean isShouldUploadAsGzip() {
return shouldUploadAsGzip;
}
public Optional<Integer> getOptionalOfThreadPoolSize(){
return Optional.ofNullable(threadPoolSize);
}
public Optional<Long> getOptionalOfMultipartUploadThreshold() {
return Optional.ofNullable(multipartUploadThreshold);
}
public Optional<Long> getOptionalOfMinimumUploadPartSize() {
return Optional.ofNullable(minimumUploadPartSize);
}
public Optional<String> getOptionalDirectoryNamePrefix() {
return Optional.ofNullable(directoryNamePrefix);
}
public void setDirectoryNamePrefix(String directoryNamePrefix) {
this.directoryNamePrefix = directoryNamePrefix;
}
public Optional<DateTimeFormatter> getOptionalDateTimeFormatter() {
return Optional.ofNullable(dateTimeFormatter);
}
public void setDateTimeFormatter(DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
}
| mit |
cowthan/Ayo2022 | ProjFringe/app-fringe/src/main/java/org/ayo/fringe/widget/photo/OnPhotoTapListener.java | 761 | package org.ayo.fringe.widget.photo;
import android.view.View;
/**
* Interface definition for a callback to be invoked when the Photo is tapped with a single
* tap.
*
* @author Chris Banes
*/
public interface OnPhotoTapListener {
/**
* A callback to receive where the user taps on a photo. You will only receive a callback if
* the user taps on the actual photo, tapping on 'whitespace' will be ignored.
*
* @param view - View the user tapped.
* @param x - where the user tapped from the of the Drawable, as percentage of the
* Drawable width.
* @param y - where the user tapped from the top of the Drawable, as percentage of the
* Drawable height.
*/
void onPhotoTap(View view, float x, float y);
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/ApplicationGatewayRewriteRule.java | 3691 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_11_01;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Rewrite rule of an application gateway.
*/
public class ApplicationGatewayRewriteRule {
/**
* Name of the rewrite rule that is unique within an Application Gateway.
*/
@JsonProperty(value = "name")
private String name;
/**
* Rule Sequence of the rewrite rule that determines the order of execution
* of a particular rule in a RewriteRuleSet.
*/
@JsonProperty(value = "ruleSequence")
private Integer ruleSequence;
/**
* Conditions based on which the action set execution will be evaluated.
*/
@JsonProperty(value = "conditions")
private List<ApplicationGatewayRewriteRuleCondition> conditions;
/**
* Set of actions to be done as part of the rewrite Rule.
*/
@JsonProperty(value = "actionSet")
private ApplicationGatewayRewriteRuleActionSet actionSet;
/**
* Get name of the rewrite rule that is unique within an Application Gateway.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set name of the rewrite rule that is unique within an Application Gateway.
*
* @param name the name value to set
* @return the ApplicationGatewayRewriteRule object itself.
*/
public ApplicationGatewayRewriteRule withName(String name) {
this.name = name;
return this;
}
/**
* Get rule Sequence of the rewrite rule that determines the order of execution of a particular rule in a RewriteRuleSet.
*
* @return the ruleSequence value
*/
public Integer ruleSequence() {
return this.ruleSequence;
}
/**
* Set rule Sequence of the rewrite rule that determines the order of execution of a particular rule in a RewriteRuleSet.
*
* @param ruleSequence the ruleSequence value to set
* @return the ApplicationGatewayRewriteRule object itself.
*/
public ApplicationGatewayRewriteRule withRuleSequence(Integer ruleSequence) {
this.ruleSequence = ruleSequence;
return this;
}
/**
* Get conditions based on which the action set execution will be evaluated.
*
* @return the conditions value
*/
public List<ApplicationGatewayRewriteRuleCondition> conditions() {
return this.conditions;
}
/**
* Set conditions based on which the action set execution will be evaluated.
*
* @param conditions the conditions value to set
* @return the ApplicationGatewayRewriteRule object itself.
*/
public ApplicationGatewayRewriteRule withConditions(List<ApplicationGatewayRewriteRuleCondition> conditions) {
this.conditions = conditions;
return this;
}
/**
* Get set of actions to be done as part of the rewrite Rule.
*
* @return the actionSet value
*/
public ApplicationGatewayRewriteRuleActionSet actionSet() {
return this.actionSet;
}
/**
* Set set of actions to be done as part of the rewrite Rule.
*
* @param actionSet the actionSet value to set
* @return the ApplicationGatewayRewriteRule object itself.
*/
public ApplicationGatewayRewriteRule withActionSet(ApplicationGatewayRewriteRuleActionSet actionSet) {
this.actionSet = actionSet;
return this;
}
}
| mit |
hypfvieh/java-utils | src/test/java/com/github/hypfvieh/util/FixUtilTest.java | 2725 | package com.github.hypfvieh.util;
import org.junit.jupiter.api.Test;
import com.github.hypfvieh.AbstractBaseUtilTest;
/**
*
* @author hypfvieh
*/
public class FixUtilTest extends AbstractBaseUtilTest {
private String sampleFixMsg = "8=FIX.4.2|9=65|35=0|49=TRIOMM|56=BAADER_UAT_AUC_DC|34=1992|52=20140714-21:29:29|10=149|";
public FixUtilTest() {
}
/**
* Test of getDelimiterFromFixMsgStr method, of class FixUtil.
*/
@Test
public void testGetDelimiterFromFixMsgStr() {
System.out.println("getDelimiterFromFixMsgStr");
String expResult = "|";
String result = FixUtil.getDelimiterFromFixMsgStr(sampleFixMsg);
assertEquals(expResult, result);
}
/**
* Test of setFixTagOnMsgStr method, of class FixUtil.
*/
@Test
public void testSetFixTagOnMsgStr() {
System.out.println("setFixTagOnMsgStr");
String expResult = "8=FIX.4.2|9=65|35=0|49=TRIOMM|56=BAADER_UAT_AUC_DC|34=1992|52=20140714-21:29:29|4711=FOOBAR|10=149|";
String result = FixUtil.setFixTagOnMsgStr(sampleFixMsg, 4711, "FOOBAR");
assertEquals(expResult, result);
}
/**
* Test of calculateFixBodyLength method, of class FixUtil.
*/
@Test
public void testCalculateFixBodyLength() {
System.out.println("calculateFixBodyLength");
String brokenMsg = sampleFixMsg;
FixUtil.setFixTagOnMsgStr(brokenMsg, 10, "815");
int expectValue = 65;
int calcValue = FixUtil.calculateFixBodyLength(brokenMsg);
assertEquals(expectValue, calcValue);
}
/**
* Test of calculateFixCheckSum method, of class FixUtil.
*/
@Test
public void testCalculateFixCheckSum() {
System.out.println("calculateFixCheckSum");
String expResult = "149";
String result = FixUtil.calculateFixCheckSum(sampleFixMsg, "|".charAt(0));
assertEquals(expResult, result);
}
/**
* Test of looksLikeFixMsg method, of class FixUtil.
*/
@Test
public void testLooksLikeFixMsg() {
System.out.println("looksLikeFixMsg");
boolean expResult = true;
boolean result = FixUtil.looksLikeFixMsg(sampleFixMsg);
assertEquals(expResult, result);
}
@Test
public void testSetValueCorrectOrder() {
System.out.println("setValue and correct order");
String testMsg = "9=65|49=TRIOMM|56=BAADER_UAT_AUC_DC|8=FIX.4.2|34=1992|52=20140714-21:29:29|35=0|4711=FOO|10=149|";
String expResult = "8=FIX.4.2|9=65|35=0|49=TRIOMM|56=BAADER_UAT_AUC_DC|34=1992|52=20140714-21:29:29|4711=FOOBAR|10=149|";
assertEquals(expResult, FixUtil.setFixTagOnMsgStr(testMsg, 4711, "FOOBAR"));
}
}
| mit |
jkpr/clueless | src/main/java/app/game/model/Dealer.java | 6294 | package app.game.model;
import app.exception.GameModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Created by james on 11/27/16.
*/
public class Dealer {
private static final Logger logger = LoggerFactory.getLogger(Dealer.class);
private Card msScarlet;
private Card colMustard;
private Card mrsWhite;
private Card mrGreen;
private Card mrsPeacock;
private Card profPlum;
private Card candlestick;
private Card knife;
private Card pipe;
private Card revolver;
private Card rope;
private Card wrench;
private Card kitchen;
private Card ballroom;
private Card conservatory;
private Card diningRoom;
private Card billiardRoom;
private Card library;
private Card lounge;
private Card hall;
private Card study;
public Dealer() {
try {
kitchen = new Card(BoardSpace.KITCHEN);
ballroom = new Card(BoardSpace.BALLROOM);
conservatory = new Card(BoardSpace.CONSERVATORY);
diningRoom = new Card(BoardSpace.DINING_ROOM);
billiardRoom = new Card(BoardSpace.BILLIARD_ROOM);
library = new Card(BoardSpace.LIBRARY);
lounge = new Card(BoardSpace.LOUNGE);
hall = new Card(BoardSpace.HALL);
study = new Card(BoardSpace.STUDY);
msScarlet = new Card(Character.MS_SCARLET);
colMustard = new Card(Character.COL_MUSTARD);
mrsWhite = new Card(Character.MRS_WHITE);
mrGreen = new Card(Character.MR_GREEN);
mrsPeacock = new Card(Character.MRS_PEACOCK);
profPlum = new Card(Character.PROF_PLUM);
candlestick = new Card(Weapon.CANDLESTICK);
knife = new Card(Weapon.KNIFE);
pipe = new Card(Weapon.PIPE);
revolver = new Card(Weapon.REVOLVER);
rope = new Card(Weapon.ROPE);
wrench = new Card(Weapon.WRENCH);
} catch (GameModelException e) {
logger.error("Error thrown while constructing Dealer. Should never happen...");
}
}
public DealResult deal(int nPlayer) {
// TODO ensure 3 <= nPlayer <= 6
DealResult result = new DealResult();
List<Card> characters = getCharactersList();
List<Card> weapons = getWeaponsList();
List<Card> rooms = getRoomsList();
Card murderCharacter = randomPop(characters);
Card murderWeapon = randomPop(weapons);
Card murderRoom = randomPop(rooms);
result.murder = new Murder(murderCharacter, murderWeapon, murderRoom);
List<Card> allRemaining = new LinkedList<>();
allRemaining.addAll(characters);
allRemaining.addAll(weapons);
allRemaining.addAll(rooms);
// shuffle in place
Collections.shuffle(allRemaining);
result.hands = new ArrayList<>(nPlayer);
for (int i = 0; i < nPlayer; i++) {
result.hands.add(new LinkedList<>());
}
// round-robin deal
for (int i = 0; i < allRemaining.size(); i++) {
Card next = allRemaining.get(i);
result.hands.get(i % nPlayer).add(next);
}
Collections.shuffle(result.hands);
return result;
}
private Card randomPop(List<Card> list) {
Random random = new Random();
int choice = random.nextInt(list.size());
Card chosen = list.remove(choice);
return chosen;
}
private List<Card> getRoomsList() {
List<Card> rooms = new LinkedList<>();
rooms.add(kitchen);
rooms.add(ballroom);
rooms.add(conservatory);
rooms.add(diningRoom);
rooms.add(billiardRoom);
rooms.add(library);
rooms.add(lounge);
rooms.add(hall);
rooms.add(study);
return rooms;
}
private List<Card> getCharactersList() {
List<Card> characters = new LinkedList<>();
characters.add(msScarlet);
characters.add(colMustard);
characters.add(mrsWhite);
characters.add(mrGreen);
characters.add(mrsPeacock);
characters.add(profPlum);
return characters;
}
private List<Card> getWeaponsList() {
List<Card> weapons = new LinkedList<>();
weapons.add(candlestick);
weapons.add(knife);
weapons.add(pipe);
weapons.add(revolver);
weapons.add(rope);
weapons.add(wrench);
return weapons;
}
public Card getCard(String name) throws GameModelException{
// TODO: return card just as in Board.getBoardSpace
switch(name){
case BoardSpace.KITCHEN:
return kitchen;
case BoardSpace.BALLROOM:
return ballroom;
case BoardSpace.CONSERVATORY:
return conservatory;
case BoardSpace.DINING_ROOM:
return diningRoom;
case BoardSpace.BILLIARD_ROOM:
return billiardRoom;
case BoardSpace.LIBRARY:
return library;
case BoardSpace.LOUNGE:
return lounge;
case BoardSpace.HALL:
return hall;
case BoardSpace.STUDY:
return study;
case Character.MS_SCARLET:
return msScarlet;
case Character.COL_MUSTARD:
return colMustard;
case Character.MRS_WHITE:
return mrsWhite;
case Character.MR_GREEN:
return mrGreen;
case Character.MRS_PEACOCK:
return mrsPeacock;
case Character.PROF_PLUM:
return profPlum;
case Weapon.CANDLESTICK:
return candlestick;
case Weapon.KNIFE:
return knife;
case Weapon.PIPE:
return pipe;
case Weapon.REVOLVER:
return revolver;
case Weapon.ROPE:
return rope;
case Weapon.WRENCH:
return wrench;
default:
throw new GameModelException(name);
}
}
class DealResult {
Murder murder;
List<List<Card>> hands;
}
}
| mit |
basking2/sdsai | sdsai-itrex/src/main/java/com/github/basking2/sdsai/itrex/functions/java/ClassOfFunction.java | 742 | /**
* Copyright (c) 2016-2021 Sam Baskinger
*/
package com.github.basking2.sdsai.itrex.functions.java;
import com.github.basking2.sdsai.itrex.EvaluationContext;
import com.github.basking2.sdsai.itrex.SExprRuntimeException;
import com.github.basking2.sdsai.itrex.functions.AbstractFunction1;
import java.util.Iterator;
public class ClassOfFunction extends AbstractFunction1<String, Class<?>> {
@Override
protected Class<?> applyImpl(final String className, final Iterator<?> rest, final EvaluationContext context) {
try {
return Class.forName(className);
}
catch (final ClassNotFoundException e) {
throw new SExprRuntimeException("Loading class "+className, e);
}
}
}
| mit |
tuxtor/fpjavademo | src/com/nabenik/functional/FunctionalSample.java | 2492 | package com.nabenik.functional;
/**
*
* @author tuxtor
*/
public class FunctionalSample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
FunctionalSample leSample = new FunctionalSample();
//The old way
leSample.doItWithOldFashion();
//The new Way
leSample.doItWithLambda();
}
public void doItWithOldFashion(){
MyFunctionalInterface myFunctionalObject = new MyFunctionalInterface() {
//Behaviour definition into anon inner class
@Override
public void doSomethingFunctional(String leText) {
System.out.println(leText);
}
};
myFunctionalObject.doSomethingFunctional("Invoking in the traditional way");
}
public void doItWithLambda(){
//Behaviour - lambda as anonymus function
MyFunctionalInterface myFunctionalObject = (x) -> System.out.println(x);
myFunctionalObject.doSomethingFunctional("I'm a basic lambda behaviour");
//Using lambda as a parameter in high order functions
MyFunctionalInterface behaviourAsParameter = (x) -> System.out.println("Simple behaviour ".concat(x));
MyFunctionalInterface anotherBehaviourAsParameter = (x) -> {
System.out.println("Complex behavior");
System.out.println("A very complex behaviour".concat(x));};
lambdaAsParameter(behaviourAsParameter);
lambdaAsParameter(anotherBehaviourAsParameter);
//Method references
//Static
MyFunctionalInterface staticMethodReference = System.out::println;
staticMethodReference.doSomethingFunctional("Print using references");
MyFunctionalInterface joeStaticMethodReference = FunctionalJoeClass::joeDoSomething;
joeStaticMethodReference.doSomethingFunctional("Joe static reference");
//Instance
FunctionalJoeClass joe = new FunctionalJoeClass();
MyFunctionalInterface instanceOfJoeMethodReference = joe::instanceOfJoeDoSomething;
instanceOfJoeMethodReference.doSomethingFunctional("Text printed by joe instance");
}
//High order function - Takes another function as a parameter
public void lambdaAsParameter(MyFunctionalInterface leParameter){
leParameter.doSomethingFunctional(" awesome while using high-order functions");
}
}
| mit |