hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9234c8e68247c025fbe7b0e3a3ba09d62e23a114 | 305 | java | Java | sistema-cadastro-springboot/src/main/java/com/eugenio/cadastro/dto/PessoaListagemCompletaDTO.java | eugenioarantes/sistema-cadastro | 3f9db946fd6e5ee8fdae8024473ef5dca79841a0 | [
"MIT"
] | null | null | null | sistema-cadastro-springboot/src/main/java/com/eugenio/cadastro/dto/PessoaListagemCompletaDTO.java | eugenioarantes/sistema-cadastro | 3f9db946fd6e5ee8fdae8024473ef5dca79841a0 | [
"MIT"
] | null | null | null | sistema-cadastro-springboot/src/main/java/com/eugenio/cadastro/dto/PessoaListagemCompletaDTO.java | eugenioarantes/sistema-cadastro | 3f9db946fd6e5ee8fdae8024473ef5dca79841a0 | [
"MIT"
] | null | null | null | 16.944444 | 40 | 0.806557 | 997,054 | package com.eugenio.cadastro.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class PessoaListagemCompletaDTO {
private Long Id;
private String nome;
private String email;
private String celular;
}
|
9234c8f8e5d15ee97b2e3cf591b30ded677ea5c1 | 32,124 | java | Java | src/main/java/walkingkooka/tree/select/parser/NodeSelectorParserToken.java | mP1/walkingkooka-tree | eda1c7f9ae88ed30b0d0be046ce909df7a7653f7 | [
"Apache-2.0"
] | 1 | 2022-02-19T14:29:35.000Z | 2022-02-19T14:29:35.000Z | src/main/java/walkingkooka/tree/select/parser/NodeSelectorParserToken.java | mP1/walkingkooka-tree | eda1c7f9ae88ed30b0d0be046ce909df7a7653f7 | [
"Apache-2.0"
] | 113 | 2019-10-29T00:29:30.000Z | 2022-02-02T09:31:45.000Z | src/main/java/walkingkooka/tree/select/parser/NodeSelectorParserToken.java | mP1/walkingkooka-tree | eda1c7f9ae88ed30b0d0be046ce909df7a7653f7 | [
"Apache-2.0"
] | null | null | null | 32.51417 | 131 | 0.700535 | 997,055 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.tree.select.parser;
import walkingkooka.Cast;
import walkingkooka.collect.list.Lists;
import walkingkooka.text.CharSequences;
import walkingkooka.text.Whitespace;
import walkingkooka.text.cursor.parser.ParserToken;
import walkingkooka.text.cursor.parser.ParserTokenVisitor;
import walkingkooka.tree.expression.ExpressionNumber;
import walkingkooka.visit.Visiting;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
/**
* Represents a token within the xpath query grammar.
*/
public abstract class NodeSelectorParserToken implements ParserToken {
/**
* {@see NodeSelectorAbsoluteParserToken}
*/
public static NodeSelectorAbsoluteParserToken absolute(final String value, final String text) {
return NodeSelectorAbsoluteParserToken.with(value, text);
}
/**
* {@see NodeSelectorAdditionParserToken}
*/
public static NodeSelectorAdditionParserToken addition(final List<ParserToken> value, final String text) {
return NodeSelectorAdditionParserToken.with(value, text);
}
/**
* {@see NodeSelectorAncestorParserToken}
*/
public static NodeSelectorAncestorParserToken ancestor(final String value, final String text) {
return NodeSelectorAncestorParserToken.with(value, text);
}
/**
* {@see NodeSelectorAncestorOrSelfParserToken}
*/
public static NodeSelectorAncestorOrSelfParserToken ancestorOrSelf(final String value, final String text) {
return NodeSelectorAncestorOrSelfParserToken.with(value, text);
}
/**
* {@see NodeSelectorAndParserToken}
*/
public static NodeSelectorAndParserToken and(final List<ParserToken> value, final String text) {
return NodeSelectorAndParserToken.with(value, text);
}
/**
* {@see NodeSelectorAndSymbolParserToken}
*/
public static NodeSelectorAndSymbolParserToken andSymbol(final String value, final String text) {
return NodeSelectorAndSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorAtSignSymbolParserToken}
*/
public static NodeSelectorAtSignSymbolParserToken atSignSymbol(final String value, final String text) {
return NodeSelectorAtSignSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorAttributeParserToken}
*/
public static NodeSelectorAttributeParserToken attribute(final List<ParserToken> value, final String text) {
return NodeSelectorAttributeParserToken.with(value, text);
}
/**
* {@see NodeSelectorAttributeNameParserToken}
*/
public static NodeSelectorAttributeNameParserToken attributeName(final NodeSelectorAttributeName value, final String text) {
return NodeSelectorAttributeNameParserToken.with(value, text);
}
/**
* {@see NodeSelectorBracketOpenSymbolParserToken}
*/
public static NodeSelectorBracketOpenSymbolParserToken bracketOpenSymbol(final String value, final String text) {
return NodeSelectorBracketOpenSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorBracketCloseSymbolParserToken}
*/
public static NodeSelectorBracketCloseSymbolParserToken bracketCloseSymbol(final String value, final String text) {
return NodeSelectorBracketCloseSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorChildParserToken}
*/
public static NodeSelectorChildParserToken child(final String value, final String text) {
return NodeSelectorChildParserToken.with(value, text);
}
/**
* {@see NodeSelectorDescendantParserToken}
*/
public static NodeSelectorDescendantParserToken descendant(final String value, final String text) {
return NodeSelectorDescendantParserToken.with(value, text);
}
/**
* {@see NodeSelectorDescendantOrSelfParserToken}
*/
public static NodeSelectorDescendantOrSelfParserToken descendantOrSelf(final String value, final String text) {
return NodeSelectorDescendantOrSelfParserToken.with(value, text);
}
/**
* {@see NodeSelectorDivideSymbolParserToken}
*/
public static NodeSelectorDivideSymbolParserToken divideSymbol(final String value, final String text) {
return NodeSelectorDivideSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorDivisionParserToken}
*/
public static NodeSelectorDivisionParserToken division(final List<ParserToken> value, final String text) {
return NodeSelectorDivisionParserToken.with(value, text);
}
/**
* {@see NodeSelectorEqualsParserToken}
*/
public static NodeSelectorEqualsParserToken equalsParserToken(final List<ParserToken> value, final String text) {
return NodeSelectorEqualsParserToken.with(value, text);
}
/**
* {@see NodeSelectorEqualsSymbolParserToken}
*/
public static NodeSelectorEqualsSymbolParserToken equalsSymbol(final String value, final String text) {
return NodeSelectorEqualsSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorExpressionParserToken}
*/
public static NodeSelectorExpressionParserToken expression(final List<ParserToken> value, final String text) {
return NodeSelectorExpressionParserToken.with(value, text);
}
/**
* {@see NodeSelectorExpressionNumberParserToken}
*/
public static NodeSelectorExpressionNumberParserToken expressionNumber(final ExpressionNumber value, final String text) {
return NodeSelectorExpressionNumberParserToken.with(value, text);
}
/**
* {@see NodeSelectorFirstChildParserToken}
*/
public static NodeSelectorFirstChildParserToken firstChild(final String value, final String text) {
return NodeSelectorFirstChildParserToken.with(value, text);
}
/**
* {@see NodeSelectorFollowingParserToken}
*/
public static NodeSelectorFollowingParserToken following(final String value, final String text) {
return NodeSelectorFollowingParserToken.with(value, text);
}
/**
* {@see NodeSelectorFollowingSiblingParserToken}
*/
public static NodeSelectorFollowingSiblingParserToken followingSibling(final String value, final String text) {
return NodeSelectorFollowingSiblingParserToken.with(value, text);
}
/**
* {@see NodeSelectorFunctionParserToken}
*/
public static NodeSelectorFunctionParserToken function(final List<ParserToken> value, final String text) {
return NodeSelectorFunctionParserToken.with(value, text);
}
/**
* {@see NodeSelectorFunctionNameParserToken}
*/
public static NodeSelectorFunctionNameParserToken functionName(final NodeSelectorFunctionName value, final String text) {
return NodeSelectorFunctionNameParserToken.with(value, text);
}
/**
* {@see NodeSelectorGreaterThanParserToken}
*/
public static NodeSelectorGreaterThanParserToken greaterThan(final List<ParserToken> value, final String text) {
return NodeSelectorGreaterThanParserToken.with(value, text);
}
/**
* {@see NodeSelectorGreaterThanSymbolParserToken}
*/
public static NodeSelectorGreaterThanSymbolParserToken greaterThanSymbol(final String value, final String text) {
return NodeSelectorGreaterThanSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorGreaterThanEqualsParserToken}
*/
public static NodeSelectorGreaterThanEqualsParserToken greaterThanEquals(final List<ParserToken> value, final String text) {
return NodeSelectorGreaterThanEqualsParserToken.with(value, text);
}
/**
* {@see NodeSelectorGreaterThanEqualsSymbolParserToken}
*/
public static NodeSelectorGreaterThanEqualsSymbolParserToken greaterThanEqualsSymbol(final String value, final String text) {
return NodeSelectorGreaterThanEqualsSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorGroupParserToken}
*/
public static NodeSelectorGroupParserToken group(final List<ParserToken> value, final String text) {
return NodeSelectorGroupParserToken.with(value, text);
}
/**
* {@see NodeSelectorLastChildParserToken}
*/
public static NodeSelectorLastChildParserToken lastChild(final String value, final String text) {
return NodeSelectorLastChildParserToken.with(value, text);
}
/**
* {@see NodeSelectorLessThanParserToken}
*/
public static NodeSelectorLessThanParserToken lessThan(final List<ParserToken> value, final String text) {
return NodeSelectorLessThanParserToken.with(value, text);
}
/**
* {@see NodeSelectorLessThanSymbolParserToken}
*/
public static NodeSelectorLessThanSymbolParserToken lessThanSymbol(final String value, final String text) {
return NodeSelectorLessThanSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorLessThanEqualsParserToken}
*/
public static NodeSelectorLessThanEqualsParserToken lessThanEquals(final List<ParserToken> value, final String text) {
return NodeSelectorLessThanEqualsParserToken.with(value, text);
}
/**
* {@see NodeSelectorLessThanEqualsSymbolParserToken}
*/
public static NodeSelectorLessThanEqualsSymbolParserToken lessThanEqualsSymbol(final String value, final String text) {
return NodeSelectorLessThanEqualsSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorMinusSymbolParserToken}
*/
public static NodeSelectorMinusSymbolParserToken minusSymbol(final String value, final String text) {
return NodeSelectorMinusSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorModuloParserToken}
*/
public static NodeSelectorModuloParserToken modulo(final List<ParserToken> value, final String text) {
return NodeSelectorModuloParserToken.with(value, text);
}
/**
* {@see NodeSelectorModuloSymbolParserToken}
*/
public static NodeSelectorModuloSymbolParserToken moduloSymbol(final String value, final String text) {
return NodeSelectorModuloSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorMultiplicationParserToken}
*/
public static NodeSelectorMultiplicationParserToken multiplication(final List<ParserToken> value, final String text) {
return NodeSelectorMultiplicationParserToken.with(value, text);
}
/**
* {@see NodeSelectorMultiplySymbolParserToken}
*/
public static NodeSelectorMultiplySymbolParserToken multiplySymbol(final String value, final String text) {
return NodeSelectorMultiplySymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorNegativeParserToken}
*/
public static NodeSelectorNegativeParserToken negative(final List<ParserToken> value, final String text) {
return NodeSelectorNegativeParserToken.with(value, text);
}
/**
* {@see NodeSelectorNodeNameParserToken}
*/
public static NodeSelectorNodeNameParserToken nodeName(final NodeSelectorNodeName value, final String text) {
return NodeSelectorNodeNameParserToken.with(value, text);
}
/**
* {@see NodeSelectorNotEqualsParserToken}
*/
public static NodeSelectorNotEqualsParserToken notEquals(final List<ParserToken> value, final String text) {
return NodeSelectorNotEqualsParserToken.with(value, text);
}
/**
* {@see NodeSelectorNotEqualsSymbolParserToken}
*/
public static NodeSelectorNotEqualsSymbolParserToken notEqualsSymbol(final String value, final String text) {
return NodeSelectorNotEqualsSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorOrParserToken}
*/
public static NodeSelectorOrParserToken or(final List<ParserToken> value, final String text) {
return NodeSelectorOrParserToken.with(value, text);
}
/**
* {@see NodeSelectorOrSymbolParserToken}
*/
public static NodeSelectorOrSymbolParserToken orSymbol(final String value, final String text) {
return NodeSelectorOrSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorParameterSeparatorSymbolParserToken}
*/
public static NodeSelectorParameterSeparatorSymbolParserToken parameterSeparatorSymbol(final String value, final String text) {
return NodeSelectorParameterSeparatorSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorParenthesisOpenSymbolParserToken}
*/
public static NodeSelectorParenthesisOpenSymbolParserToken parenthesisOpenSymbol(final String value, final String text) {
return NodeSelectorParenthesisOpenSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorParenthesisCloseSymbolParserToken}
*/
public static NodeSelectorParenthesisCloseSymbolParserToken parenthesisCloseSymbol(final String value, final String text) {
return NodeSelectorParenthesisCloseSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorParentOfParserToken}
*/
public static NodeSelectorParentOfParserToken parentOf(final String value, final String text) {
return NodeSelectorParentOfParserToken.with(value, text);
}
/**
* {@see NodeSelectorPlusSymbolParserToken}
*/
public static NodeSelectorPlusSymbolParserToken plusSymbol(final String value, final String text) {
return NodeSelectorPlusSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorPrecedingParserToken}
*/
public static NodeSelectorPrecedingParserToken preceding(final String value, final String text) {
return NodeSelectorPrecedingParserToken.with(value, text);
}
/**
* {@see NodeSelectorPrecedingSiblingParserToken}
*/
public static NodeSelectorPrecedingSiblingParserToken precedingSibling(final String value, final String text) {
return NodeSelectorPrecedingSiblingParserToken.with(value, text);
}
/**
* {@see NodeSelectorPredicateParserToken}
*/
public static NodeSelectorPredicateParserToken predicate(final List<ParserToken> value, final String text) {
return NodeSelectorPredicateParserToken.with(value, text);
}
/**
* {@see NodeSelectorQuotedTextParserToken}
*/
public static NodeSelectorQuotedTextParserToken quotedText(final String value, final String text) {
return NodeSelectorQuotedTextParserToken.with(value, text);
}
/**
* {@see NodeSelectorSelfParserToken}
*/
public static NodeSelectorSelfParserToken self(final String value, final String text) {
return NodeSelectorSelfParserToken.with(value, text);
}
/**
* {@see NodeSelectorSlashSeparatorSymbolParserToken}
*/
public static NodeSelectorSlashSeparatorSymbolParserToken slashSeparatorSymbol(final String value, final String text) {
return NodeSelectorSlashSeparatorSymbolParserToken.with(value, text);
}
/**
* {@see NodeSelectorSubtractionParserToken}
*/
public static NodeSelectorSubtractionParserToken subtraction(final List<ParserToken> value, final String text) {
return NodeSelectorSubtractionParserToken.with(value, text);
}
/**
* {@see NodeSelectorWhitespaceParserToken}
*/
public static NodeSelectorWhitespaceParserToken whitespace(final String value, final String text) {
return NodeSelectorWhitespaceParserToken.with(value, text);
}
/**
* {@see NodeSelectorWildcardParserToken}
*/
public static NodeSelectorWildcardParserToken wildcard(final String value, final String text) {
return NodeSelectorWildcardParserToken.with(value, text);
}
static List<ParserToken> copyAndCheckTokens(final List<ParserToken> tokens) {
Objects.requireNonNull(tokens, "tokens");
return Lists.immutable(tokens);
}
static void checkTextNullOrEmpty(final String text) {
CharSequences.failIfNullOrEmpty(text, "text");
}
static String checkTextNullOrWhitespace(final String text) {
Whitespace.failIfNullOrEmptyOrWhitespace(text, "text");
return text;
}
/**
* Package private ctor to limit sub classing.
*/
NodeSelectorParserToken(final String text) {
this.text = text;
}
@Override
public final String text() {
return this.text;
}
private final String text;
abstract Object value();
// isXXX............................................................................................................
/**
* Only {@link NodeSelectorAbsoluteParserToken} return true
*/
public final boolean isAbsolute() {
return this instanceof NodeSelectorAbsoluteParserToken;
}
/**
* Only {@link NodeSelectorAdditionParserToken} return true
*/
public final boolean isAddition() {
return this instanceof NodeSelectorAdditionParserToken;
}
/**
* Only {@link NodeSelectorAncestorParserToken} return true
*/
public final boolean isAncestor() {
return this instanceof NodeSelectorAncestorParserToken;
}
/**
* Only {@link NodeSelectorAncestorOrSelfParserToken} return true
*/
public final boolean isAncestorOrSelf() {
return this instanceof NodeSelectorAncestorOrSelfParserToken;
}
/**
* Only {@link NodeSelectorAndParserToken} return true
*/
public final boolean isAnd() {
return this instanceof NodeSelectorAndParserToken;
}
/**
* Only {@link NodeSelectorAndSymbolParserToken} return true
*/
public final boolean isAndSymbol() {
return this instanceof NodeSelectorAndSymbolParserToken;
}
/**
* Only {@link NodeSelectorAtSignSymbolParserToken} return true
*/
public final boolean isAtSignSymbol() {
return this instanceof NodeSelectorAtSignSymbolParserToken;
}
/**
* Only {@link NodeSelectorAttributeParserToken} return true
*/
public final boolean isAttribute() {
return this instanceof NodeSelectorAttributeParserToken;
}
/**
* Only {@link NodeSelectorAttributeNameParserToken} return true
*/
public final boolean isAttributeName() {
return this instanceof NodeSelectorAttributeNameParserToken;
}
/**
* Only {@link NodeSelectorBracketOpenSymbolParserToken} return true
*/
public final boolean isBracketOpenSymbol() {
return this instanceof NodeSelectorBracketOpenSymbolParserToken;
}
/**
* Only {@link NodeSelectorBracketCloseSymbolParserToken} return true
*/
public final boolean isBracketCloseSymbol() {
return this instanceof NodeSelectorBracketCloseSymbolParserToken;
}
/**
* Only {@link NodeSelectorChildParserToken} return true
*/
public final boolean isChild() {
return this instanceof NodeSelectorChildParserToken;
}
/**
* Only {@link NodeSelectorDescendantParserToken} return true
*/
public final boolean isDescendant() {
return this instanceof NodeSelectorDescendantParserToken;
}
/**
* Only {@link NodeSelectorDescendantOrSelfParserToken} return true
*/
public final boolean isDescendantOrSelf() {
return this instanceof NodeSelectorDescendantOrSelfParserToken;
}
/**
* Only {@link NodeSelectorDivideSymbolParserToken} return true
*/
public final boolean isDivideSymbol() {
return this instanceof NodeSelectorDivideSymbolParserToken;
}
/**
* Only {@link NodeSelectorDivisionParserToken} return true
*/
public final boolean isDivision() {
return this instanceof NodeSelectorDivisionParserToken;
}
/**
* Only {@link NodeSelectorEqualsParserToken} return true
*/
public final boolean isEquals() {
return this instanceof NodeSelectorEqualsParserToken;
}
/**
* Only {@link NodeSelectorEqualsSymbolParserToken} return true
*/
public final boolean isEqualsSymbol() {
return this instanceof NodeSelectorEqualsSymbolParserToken;
}
/**
* Only {@link NodeSelectorExpressionParserToken} return true
*/
public final boolean isExpression() {
return this instanceof NodeSelectorExpressionParserToken;
}
/**
* Only {@link NodeSelectorExpressionNumberParserToken} return true
*/
public final boolean isExpressionNumber() {
return this instanceof NodeSelectorExpressionNumberParserToken;
}
/**
* Only {@link NodeSelectorFirstChildParserToken} return true
*/
public final boolean isFirstChild() {
return this instanceof NodeSelectorFirstChildParserToken;
}
/**
* Only {@link NodeSelectorFollowingParserToken} return true
*/
public final boolean isFollowing() {
return this instanceof NodeSelectorFollowingParserToken;
}
/**
* Only {@link NodeSelectorFollowingSiblingParserToken} return true
*/
public final boolean isFollowingSibling() {
return this instanceof NodeSelectorFollowingSiblingParserToken;
}
/**
* Only {@link NodeSelectorFunctionParserToken} return true
*/
public final boolean isFunction() {
return this instanceof NodeSelectorFunctionParserToken;
}
/**
* Only {@link NodeSelectorFunctionNameParserToken} return true
*/
public final boolean isFunctionName() {
return this instanceof NodeSelectorFunctionNameParserToken;
}
/**
* Only {@link NodeSelectorGreaterThanParserToken} return true
*/
public final boolean isGreaterThan() {
return this instanceof NodeSelectorGreaterThanParserToken;
}
/**
* Only {@link NodeSelectorGreaterThanSymbolParserToken} return true
*/
public final boolean isGreaterThanSymbol() {
return this instanceof NodeSelectorGreaterThanSymbolParserToken;
}
/**
* Only {@link NodeSelectorGreaterThanEqualsParserToken} return true
*/
public final boolean isGreaterThanEquals() {
return this instanceof NodeSelectorGreaterThanEqualsParserToken;
}
/**
* Only {@link NodeSelectorGreaterThanEqualsSymbolParserToken} return true
*/
public final boolean isGreaterThanEqualsSymbol() {
return this instanceof NodeSelectorGreaterThanEqualsSymbolParserToken;
}
/**
* Only {@link NodeSelectorGroupParserToken} return true
*/
public final boolean isGroup() {
return this instanceof NodeSelectorGroupParserToken;
}
/**
* Only {@link NodeSelectorLastChildParserToken} return true
*/
public final boolean isLastChild() {
return this instanceof NodeSelectorLastChildParserToken;
}
/**
* Only {@link NodeSelectorLessThanParserToken} return true
*/
public final boolean isLessThan() {
return this instanceof NodeSelectorLessThanParserToken;
}
/**
* Only {@link NodeSelectorLessThanSymbolParserToken} return true
*/
public final boolean isLessThanSymbol() {
return this instanceof NodeSelectorLessThanSymbolParserToken;
}
/**
* Only {@link NodeSelectorLessThanEqualsParserToken} return true
*/
public final boolean isLessThanEquals() {
return this instanceof NodeSelectorLessThanEqualsParserToken;
}
/**
* Only {@link NodeSelectorLessThanEqualsSymbolParserToken} return true
*/
public final boolean isLessThanEqualsSymbol() {
return this instanceof NodeSelectorLessThanEqualsSymbolParserToken;
}
/**
* Only {@link NodeSelectorMinusSymbolParserToken} return true
*/
public final boolean isMinusSymbol() {
return this instanceof NodeSelectorMinusSymbolParserToken;
}
/**
* Only {@link NodeSelectorModuloParserToken} return true
*/
public final boolean isModulo() {
return this instanceof NodeSelectorModuloParserToken;
}
/**
* Only {@link NodeSelectorModuloSymbolParserToken} return true
*/
public final boolean isModuloSymbol() {
return this instanceof NodeSelectorModuloSymbolParserToken;
}
/**
* Only {@link NodeSelectorMultiplicationParserToken} return true
*/
public final boolean isMultiplication() {
return this instanceof NodeSelectorMultiplicationParserToken;
}
/**
* Only {@link NodeSelectorMultiplySymbolParserToken} return true
*/
public final boolean isMultiplySymbol() {
return this instanceof NodeSelectorMultiplySymbolParserToken;
}
/**
* Only {@link NodeSelectorNegativeParserToken} return true
*/
public final boolean isNegative() {
return this instanceof NodeSelectorNegativeParserToken;
}
/**
* Only {@link NodeSelectorNodeNameParserToken} return true
*/
public final boolean isNodeName() {
return this instanceof NodeSelectorNodeNameParserToken;
}
/**
* Only {@link NodeSelectorNotEqualsParserToken} return true
*/
public final boolean isNotEquals() {
return this instanceof NodeSelectorNotEqualsParserToken;
}
/**
* Only {@link NodeSelectorNotEqualsSymbolParserToken} return true
*/
public final boolean isNotEqualsSymbol() {
return this instanceof NodeSelectorNotEqualsSymbolParserToken;
}
/**
* Only {@link NodeSelectorOrParserToken} return true
*/
public final boolean isOr() {
return this instanceof NodeSelectorOrParserToken;
}
/**
* Only {@link NodeSelectorOrSymbolParserToken} return true
*/
public final boolean isOrSymbol() {
return this instanceof NodeSelectorOrSymbolParserToken;
}
/**
* Only {@link NodeSelectorParameterSeparatorSymbolParserToken} return true
*/
public final boolean isParameterSeparatorSymbol() {
return this instanceof NodeSelectorParameterSeparatorSymbolParserToken;
}
/**
* Only {@link NodeSelectorParenthesisOpenSymbolParserToken} return true
*/
public final boolean isParenthesisOpenSymbol() {
return this instanceof NodeSelectorParenthesisOpenSymbolParserToken;
}
/**
* Only {@link NodeSelectorParenthesisCloseSymbolParserToken} return true
*/
public final boolean isParenthesisCloseSymbol() {
return this instanceof NodeSelectorParenthesisCloseSymbolParserToken;
}
/**
* Only {@link NodeSelectorParentOfParserToken} return true
*/
public final boolean isParentOf() {
return this instanceof NodeSelectorParentOfParserToken;
}
/**
* Only {@link NodeSelectorPlusSymbolParserToken} return true
*/
public final boolean isPlusSymbol() {
return this instanceof NodeSelectorPlusSymbolParserToken;
}
/**
* Only {@link NodeSelectorPrecedingParserToken} return true
*/
public final boolean isPreceding() {
return this instanceof NodeSelectorPrecedingParserToken;
}
/**
* Only {@link NodeSelectorPrecedingSiblingParserToken} return true
*/
public final boolean isPrecedingSibling() {
return this instanceof NodeSelectorPrecedingSiblingParserToken;
}
/**
* Only {@link NodeSelectorPredicateParserToken} return true
*/
public final boolean isPredicate() {
return this instanceof NodeSelectorPredicateParserToken;
}
/**
* Only {@link NodeSelectorQuotedTextParserToken} return true
*/
public final boolean isQuotedText() {
return this instanceof NodeSelectorQuotedTextParserToken;
}
/**
* Only {@link NodeSelectorSelfParserToken} return true
*/
public final boolean isSelf() {
return this instanceof NodeSelectorSelfParserToken;
}
/**
* Only {@link NodeSelectorSlashSeparatorSymbolParserToken} return true
*/
public final boolean isSlashSeparatorSymbol() {
return this instanceof NodeSelectorSlashSeparatorSymbolParserToken;
}
/**
* Only {@link NodeSelectorSubtractionParserToken} return true
*/
public final boolean isSubtraction() {
return this instanceof NodeSelectorSubtractionParserToken;
}
/**
* Only {@link NodeSelectorSymbolParserToken} return true
*/
public final boolean isSymbol() {
return this instanceof NodeSelectorSymbolParserToken;
}
/**
* Only {@link NodeSelectorWhitespaceParserToken} return true
*/
public final boolean isWhitespace() {
return this instanceof NodeSelectorWhitespaceParserToken;
}
/**
* Only {@link NodeSelectorWildcardParserToken} return true
*/
public final boolean isWildcard() {
return this instanceof NodeSelectorWildcardParserToken;
}
/**
* The priority of this token, tokens with a value of zero are left in their original position.
*/
abstract int operatorPriority();
final static int IGNORED = 0;
final static int LOWEST_PRIORITY = IGNORED + 1;
final static int OR_PRIORITY = LOWEST_PRIORITY + 1;
final static int AND_PRIORITY = OR_PRIORITY + 1;
final static int EQUALS_NOT_EQUALS_PRIORITY = AND_PRIORITY + 1;
final static int LESS_GREATER_PRIORITY = EQUALS_NOT_EQUALS_PRIORITY + 1;
final static int ADDITION_SUBTRACTION_PRIORITY = LESS_GREATER_PRIORITY + 1;
final static int MULTIPLY_DIVISION_PRIORITY = ADDITION_SUBTRACTION_PRIORITY + 1;
final static int MOD_PRIORITY = MULTIPLY_DIVISION_PRIORITY + 1;
final static int HIGHEST_PRIORITY = MOD_PRIORITY;
/**
* Factory that creates the {@link NodeSelectorBinaryParserToken} sub class using the provided tokens and text.
*/
abstract NodeSelectorBinaryParserToken binaryOperand(final List<ParserToken> tokens, final String text);
// Visitor ......................................................................................................
/**
* Begins the visiting process.
*/
@Override
public final void accept(final ParserTokenVisitor visitor) {
if (visitor instanceof NodeSelectorParserTokenVisitor) {
final NodeSelectorParserTokenVisitor visitor2 = Cast.to(visitor);
if (Visiting.CONTINUE == visitor2.startVisit(this)) {
this.accept(visitor2);
}
visitor2.endVisit(this);
}
}
abstract void accept(final NodeSelectorParserTokenVisitor visitor);
// Object ...........................................................................................................
@Override
public final int hashCode() {
return Objects.hash(this.text, this.value());
}
@Override
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
public final boolean equals(final Object other) {
return this == other ||
this.canBeEqual(other) &&
this.equals0((NodeSelectorParserToken) other);
}
abstract boolean canBeEqual(final Object other);
private boolean equals0(final NodeSelectorParserToken other) {
return this.text.equals(other.text) &&
this.value().equals(other.value());
}
@Override
public final String toString() {
return this.text();
}
}
|
9234c9fd4cb8a1544de77a32a1ac96b47ba0a651 | 551 | java | Java | Java/Loops.java | mhkarazeybek/Android_Java-Kotlin | dd798407768afd4e27125b506f6763aaae7cce20 | [
"MIT"
] | 5 | 2019-10-12T20:29:05.000Z | 2021-03-02T19:41:57.000Z | Java/Loops.java | mhkarazeybek/Android_Java-Kotlin | dd798407768afd4e27125b506f6763aaae7cce20 | [
"MIT"
] | null | null | null | Java/Loops.java | mhkarazeybek/Android_Java-Kotlin | dd798407768afd4e27125b506f6763aaae7cce20 | [
"MIT"
] | null | null | null | 20.407407 | 45 | 0.522686 | 997,056 | package com.mhkarazeybek.javalearning;
/**
* Created by samsung on 20.1.2018.
*/
public class Loops {
public static void main(String[] args) {
int[] myNumbers ={12,15,18,21,24};
int x =myNumbers[0]/3*5;
System.out.println(x+"\nfor loop");
// for loop
for(int i=0;i<myNumbers.length ;i++){
int y=myNumbers[i]/3*5;
System.out.println(y);
}
for(int number:myNumbers){
int z=number/3*5;
System.out.println(z);
}
//While
}
}
|
9234ca4d3f70c748dd8c41cc76b498d457f8c5af | 1,558 | java | Java | yoti-sdk-api/src/main/java/com/yoti/api/client/YotiClient.java | TiENChain/yoti-java-sdk | df765a895a39695e02ff6cc84dbb6b57f6b84eef | [
"MIT"
] | null | null | null | yoti-sdk-api/src/main/java/com/yoti/api/client/YotiClient.java | TiENChain/yoti-java-sdk | df765a895a39695e02ff6cc84dbb6b57f6b84eef | [
"MIT"
] | null | null | null | yoti-sdk-api/src/main/java/com/yoti/api/client/YotiClient.java | TiENChain/yoti-java-sdk | df765a895a39695e02ff6cc84dbb6b57f6b84eef | [
"MIT"
] | 1 | 2018-10-07T19:46:31.000Z | 2018-10-07T19:46:31.000Z | 34.622222 | 144 | 0.682927 | 997,057 | package com.yoti.api.client;
import com.yoti.api.client.aml.AmlProfile;
import com.yoti.api.client.aml.AmlResult;
/**
* <p>
* Entry point to interact with the Yoti Connect API.
* </p>
* <p>
* It can be safely cached and shared even by multiple threads.
* </p>
* a
*/
public interface YotiClient {
/**
* Get the activity details for a token. Amongst others contains the user profile with the user's attributes you
* have selected in your application configuration on Yoti Portal.
*
* <b>Note: encrypted tokens should only be used once. You should not invoke this method multiple times with the same token.</b>
*
* @param encryptedYotiToken
* encrypted Yoti token (can be only decrypted with your application's private key). Note that this token must only be used once.
* @return an {@link ActivityDetails} instance holding the user's attributes
*
* @throws ProfileException
* aggregate exception signalling issues during the call
*/
ActivityDetails getActivityDetails(String encryptedYotiToken) throws ProfileException;
/**
* Request an AML check for the given profile.
*
* @param amlProfile
* Details of the profile to search for when performing the AML check
* @return an {@link AmlProfile} with the results of the check
*
* @throws AmlException
* aggregate exception signalling issues during the call
*/
AmlResult performAmlCheck(AmlProfile amlProfile) throws AmlException;
}
|
9234cac4b92e711e94e0735805b6703cfdd1a604 | 7,867 | java | Java | main/plugins/org.talend.model/src/main/java/org/talend/designer/core/model/utils/emf/component/impl/FORMATTypeImpl.java | dmytro-sylaiev/tcommon-studio-se | b75fadfb9bd1a42897073fe2984f1d4fb42555bd | [
"Apache-2.0"
] | 75 | 2015-01-29T03:23:32.000Z | 2022-02-26T07:05:40.000Z | main/plugins/org.talend.model/src/main/java/org/talend/designer/core/model/utils/emf/component/impl/FORMATTypeImpl.java | dmytro-sylaiev/tcommon-studio-se | b75fadfb9bd1a42897073fe2984f1d4fb42555bd | [
"Apache-2.0"
] | 813 | 2015-01-21T09:36:31.000Z | 2022-03-30T01:15:29.000Z | main/plugins/org.talend.model/src/main/java/org/talend/designer/core/model/utils/emf/component/impl/FORMATTypeImpl.java | dmytro-sylaiev/tcommon-studio-se | b75fadfb9bd1a42897073fe2984f1d4fb42555bd | [
"Apache-2.0"
] | 272 | 2015-01-08T06:47:46.000Z | 2022-02-09T23:22:27.000Z | 29.575188 | 137 | 0.544807 | 997,058 | /**
*/
package org.talend.designer.core.model.utils.emf.component.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.talend.designer.core.model.utils.emf.component.ComponentPackage;
import org.talend.designer.core.model.utils.emf.component.FORMATType;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>FORMAT Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.talend.designer.core.model.utils.emf.component.impl.FORMATTypeImpl#getCONNECTION <em>CONNECTION</em>}</li>
* <li>{@link org.talend.designer.core.model.utils.emf.component.impl.FORMATTypeImpl#getHINT <em>HINT</em>}</li>
* <li>{@link org.talend.designer.core.model.utils.emf.component.impl.FORMATTypeImpl#getLABEL <em>LABEL</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class FORMATTypeImpl extends EObjectImpl implements FORMATType {
/**
* The default value of the '{@link #getCONNECTION() <em>CONNECTION</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCONNECTION()
* @generated
* @ordered
*/
protected static final String CONNECTION_EDEFAULT = null;
/**
* The cached value of the '{@link #getCONNECTION() <em>CONNECTION</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCONNECTION()
* @generated
* @ordered
*/
protected String cONNECTION = CONNECTION_EDEFAULT;
/**
* The default value of the '{@link #getHINT() <em>HINT</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHINT()
* @generated
* @ordered
*/
protected static final String HINT_EDEFAULT = null;
/**
* The cached value of the '{@link #getHINT() <em>HINT</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHINT()
* @generated
* @ordered
*/
protected String hINT = HINT_EDEFAULT;
/**
* The default value of the '{@link #getLABEL() <em>LABEL</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLABEL()
* @generated
* @ordered
*/
protected static final String LABEL_EDEFAULT = null;
/**
* The cached value of the '{@link #getLABEL() <em>LABEL</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLABEL()
* @generated
* @ordered
*/
protected String lABEL = LABEL_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected FORMATTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return ComponentPackage.Literals.FORMAT_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getCONNECTION() {
return cONNECTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCONNECTION(String newCONNECTION) {
String oldCONNECTION = cONNECTION;
cONNECTION = newCONNECTION;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ComponentPackage.FORMAT_TYPE__CONNECTION, oldCONNECTION, cONNECTION));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getHINT() {
return hINT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setHINT(String newHINT) {
String oldHINT = hINT;
hINT = newHINT;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ComponentPackage.FORMAT_TYPE__HINT, oldHINT, hINT));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLABEL() {
return lABEL;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLABEL(String newLABEL) {
String oldLABEL = lABEL;
lABEL = newLABEL;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ComponentPackage.FORMAT_TYPE__LABEL, oldLABEL, lABEL));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ComponentPackage.FORMAT_TYPE__CONNECTION:
return getCONNECTION();
case ComponentPackage.FORMAT_TYPE__HINT:
return getHINT();
case ComponentPackage.FORMAT_TYPE__LABEL:
return getLABEL();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ComponentPackage.FORMAT_TYPE__CONNECTION:
setCONNECTION((String)newValue);
return;
case ComponentPackage.FORMAT_TYPE__HINT:
setHINT((String)newValue);
return;
case ComponentPackage.FORMAT_TYPE__LABEL:
setLABEL((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case ComponentPackage.FORMAT_TYPE__CONNECTION:
setCONNECTION(CONNECTION_EDEFAULT);
return;
case ComponentPackage.FORMAT_TYPE__HINT:
setHINT(HINT_EDEFAULT);
return;
case ComponentPackage.FORMAT_TYPE__LABEL:
setLABEL(LABEL_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case ComponentPackage.FORMAT_TYPE__CONNECTION:
return CONNECTION_EDEFAULT == null ? cONNECTION != null : !CONNECTION_EDEFAULT.equals(cONNECTION);
case ComponentPackage.FORMAT_TYPE__HINT:
return HINT_EDEFAULT == null ? hINT != null : !HINT_EDEFAULT.equals(hINT);
case ComponentPackage.FORMAT_TYPE__LABEL:
return LABEL_EDEFAULT == null ? lABEL != null : !LABEL_EDEFAULT.equals(lABEL);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (cONNECTION: ");
result.append(cONNECTION);
result.append(", hINT: ");
result.append(hINT);
result.append(", lABEL: ");
result.append(lABEL);
result.append(')');
return result.toString();
}
} //FORMATTypeImpl
|
9234cb697b030dec087cd92b674bb06704b65898 | 3,684 | java | Java | server/src/main/java/org/engineer365/common/error/GenericError.java | zlmkenan001/cloud-native-micro-service-engineering | 1d4020a9fabc00103734d38b85292e5cba4e1d50 | [
"MIT"
] | 1 | 2020-11-30T03:29:36.000Z | 2020-11-30T03:29:36.000Z | server/src/main/java/org/engineer365/common/error/GenericError.java | zlmkenan001/cloud-native-micro-service-engineering | 1d4020a9fabc00103734d38b85292e5cba4e1d50 | [
"MIT"
] | null | null | null | server/src/main/java/org/engineer365/common/error/GenericError.java | zlmkenan001/cloud-native-micro-service-engineering | 1d4020a9fabc00103734d38b85292e5cba4e1d50 | [
"MIT"
] | null | null | null | 26.12766 | 99 | 0.696254 | 997,059 | /*
* MIT License
*
* Copyright (c) 2020 engineer365.org
*
* 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.engineer365.common.error;
import java.util.Map;
import org.springframework.http.HttpStatus;
/**
* 所有异常类的基类。
* 一般不直接使用,一般直接使用它的某个子类。
*/
@lombok.Getter
public class GenericError extends RuntimeException {
private static final long serialVersionUID = -6956880450354038826L;
/**
* 错误代码。
*/
HttpStatus status;
/**
* 错误消息的参数
*/
Object[] params;
/**
* 无级联异常时抛出的异常,可以定义消息格式和消息参数
*
* @param status 错误代码
* @param messageFormat 消息格式,用于String.format(messageFormat, params
* @param params 消息参数,用于String.format(messageFormat, params
*/
public GenericError(HttpStatus status, String messageFormat, Object... params) {
super(String.format(messageFormat, params));
this.status = status;
this.params = params;
}
/**
* 无级联异常时抛出的异常,只可以传递简单消息文字
*
* @param status 错误代码
* @param message 肩带消息文字
*/
public GenericError(HttpStatus status, String message) {
super(message);
this.status = status;
this.params = new Object[0];
}
/**
* 无级联异常时抛出的异常,不用传递简单消息文字,消息文字直接使用错误代码所表示的错误消息
*
* @param status 错误代码
*/
public GenericError(HttpStatus status) {
this(status, status.getReasonPhrase());
}
/**
* 带有级联异常时抛出的异常,可以定义消息格式和消息参数
*
* @param cause 级联异常
* @param status 错误代码
* @param messageFormat 消息格式,用于String.format(messageFormat, params
* @param params 消息参数,用于String.format(messageFormat, params
*/
public GenericError(Throwable cause, HttpStatus status, String messageFormat, Object... params) {
super(String.format(messageFormat, params), cause);
this.status = status;
this.params = params;
}
/**
* 带有级联异常时抛出的异常,只可以传递简单消息文字
*
* @param cause 级联异常
* @param status 错误代码
* @param message 肩带消息文字
*/
public GenericError(Throwable cause, HttpStatus status, String message) {
super(message, cause);
this.status = status;
this.params = new Object[0];
}
/**
* 带有级联异常时抛出的异常,不用传递简单消息文字,消息文字直接使用错误代码所表示的错误消息
*
* @param cause 级联异常
* @param status 错误代码
*/
public GenericError(Throwable cause, HttpStatus status) {
this(status, status.getReasonPhrase(), cause);
}
/**
* 导出成Map。不包括级联异常。对于RESTful API,这个map就是HTTP response body
* @return
*/
public Map<String, Object> toMap() {
return toMap(this.status, this.params, getMessage());
}
public static Map<String, Object> toMap(HttpStatus status, Object[] params, String note) {
return Map.of(
"status", status.name(),
"params", params,
"note", note
);
}
}
|
9234ccfb82bfd284fc5122eac220e4a1e98404ae | 941 | java | Java | app/src/main/java/bjfu/it/haofanfang/androidquiz/MyDBHelper.java | Supremesir/AndroidQuiz | 4bb8aa8454793662c73a65c76f46dfaac13da507 | [
"MIT"
] | null | null | null | app/src/main/java/bjfu/it/haofanfang/androidquiz/MyDBHelper.java | Supremesir/AndroidQuiz | 4bb8aa8454793662c73a65c76f46dfaac13da507 | [
"MIT"
] | null | null | null | app/src/main/java/bjfu/it/haofanfang/androidquiz/MyDBHelper.java | Supremesir/AndroidQuiz | 4bb8aa8454793662c73a65c76f46dfaac13da507 | [
"MIT"
] | null | null | null | 24.128205 | 79 | 0.652497 | 997,060 | package bjfu.it.haofanfang.androidquiz;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
/**
* @author HaoFan Fang
* @date 2020-01-01 22:57
*/
public class MyDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME="AndroidQuiz.db";
private static final int DB_VERSION=1;
public MyDBHelper(@Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RECORD(_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "SNO TEXT,"
+ "SECOND INTEGER,"
+ "ANW1 TEXT,"
+ "ANW2 TEXT,"
+ "ANW3 TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
9234cd8681b693561b21fdd00f265316817a6944 | 8,265 | java | Java | src/main/java/com/ucm/tfg/fragments/FilmFragment.java | DanielCalle/TFG-Android | fe8d6346b0c0ea13a7d99b044ab446384d7ed712 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ucm/tfg/fragments/FilmFragment.java | DanielCalle/TFG-Android | fe8d6346b0c0ea13a7d99b044ab446384d7ed712 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ucm/tfg/fragments/FilmFragment.java | DanielCalle/TFG-Android | fe8d6346b0c0ea13a7d99b044ab446384d7ed712 | [
"Apache-2.0"
] | null | null | null | 34.873418 | 111 | 0.619843 | 997,061 | package com.ucm.tfg.fragments;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.SearchView;
import android.widget.Toast;
import com.ucm.tfg.R;
import com.ucm.tfg.Session;
import com.ucm.tfg.Utils;
import com.ucm.tfg.activities.FilmActivity;
import com.ucm.tfg.adapters.FilmAdapter;
import com.ucm.tfg.entities.Film;
import com.ucm.tfg.requests.FilmRequest;
import com.ucm.tfg.requests.Request;
import com.ucm.tfg.requests.UserRequest;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link FilmFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FilmFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FilmFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private FilmAdapter filmAdapter;
private SearchView searchView;
private Toolbar toolbar;
private SwipeRefreshLayout swipeRefreshLayout;
public FilmFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment PlanFragment.
*/
// TODO: Rename and change types and number of parameters
public static FilmFragment newInstance(String param1, String param2) {
FilmFragment fragment = new FilmFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_film, container, false);
GridView gridView = (GridView) view.findViewById(R.id.films);
// Creating the adapter for each film
filmAdapter = new FilmAdapter(getActivity());
// When click on a film, redirects to the film activity
filmAdapter.addFilmOnClickListener((Film film, View v) -> {
// this is used for an animation effect when changing interfaces
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat
.makeSceneTransitionAnimation(
getActivity(),
Pair.create(v, "film_poster")
);
Intent i = new Intent(getActivity(), FilmActivity.class);
i.putExtra("film", film);
startActivity(i, optionsCompat.toBundle());
});
gridView.setAdapter(filmAdapter);
// Swipe down action -> refresh data
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
swipeRefreshLayout.setOnRefreshListener(() -> {
updateFilms();
});
toolbar = getActivity().findViewById(R.id.toolbar);
updateFilms();
return view;
}
@Override
public void onResume(){
super.onResume();
updateFilms();
}
@Override
// Determines if the fragment is visible to the user
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if (toolbar != null) {
// Clearing toolbar and changes the menu for this fragment
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_films);
toolbar.setTitle(R.string.action_films);
// Action search
searchView = (SearchView) toolbar.getMenu().findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
if (!Utils.isNullOrEmpty(s)) {
searchFilms(s);
}
return false;
}
});
searchView.setOnCloseListener(() -> {
updateFilms();
return false;
});
}
}
}
private void updateFilms() {
long userId = getActivity().getSharedPreferences(Session.SESSION_FILE, 0).getLong(Session.USER, 0);
if (userId != 0) {
swipeRefreshLayout.setRefreshing(true);
UserRequest.getUserFilmsById(getActivity(), userId, new Request.ClientResponse<ArrayList<Film>>() {
@Override
public void onSuccess(ArrayList<Film> result) {
filmAdapter.setData(result);
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onError(String error) {
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
}
private void searchFilms(String name) {
if (!Utils.isNullOrEmpty(name)) {
swipeRefreshLayout.setRefreshing(true);
FilmRequest.searchFilmsByName(getActivity(), name, new Request.ClientResponse<ArrayList<Film>>() {
@Override
public void onSuccess(ArrayList<Film> result) {
filmAdapter.setData(result);
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onError(String error) {
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentLoaded();
}
}
|
9234cddcbe787c2751f46f1ebaac5668e309a316 | 2,501 | java | Java | src/main/java/com/alipay/api/domain/ZhimaCustomerEpIdentificationInitializeModel.java | 10088/alipay-sdk-java-all | 64dfba5e687e39aa7a735a711bd6f1392f63c69d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/domain/ZhimaCustomerEpIdentificationInitializeModel.java | 10088/alipay-sdk-java-all | 64dfba5e687e39aa7a735a711bd6f1392f63c69d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/domain/ZhimaCustomerEpIdentificationInitializeModel.java | 10088/alipay-sdk-java-all | 64dfba5e687e39aa7a735a711bd6f1392f63c69d | [
"Apache-2.0"
] | null | null | null | 25.01 | 381 | 0.721711 | 997,062 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 企业认证V2初始化
*
* @author auto create
* @since 1.0, 2022-04-15 12:02:23
*/
public class ZhimaCustomerEpIdentificationInitializeModel extends AlipayObject {
private static final long serialVersionUID = 4492226236442844522L;
/**
* 认证模式。
枚举值:法人认证——EP_LEGAL_PERSON_CERTIFY。
*/
@ApiField("certify_mode")
private String certifyMode;
/**
* 值为json串,必须指定身份类型identity_type,不同的身份类型对应的身份信息不同。 当前支持的identity_type=EP_CERT_INFO ,身份信息为法人证件三要素与企业证件三要素,如 {"identity_type": "EP_CERT_INFO", "legal_person_cert_type": "IDENTITY_CARD", "legal_person_cert_name": "收委", "legal_person_cert_no":"260104197909275964", "ep_cert_type": "NATIONAL_LEGAL_MERGE", "ep_cert_name": "xxx有限公司", "ep_cert_no":"91330000327827106L"}。
备注:(1)目前法人证件类型仅支持IDENTITY_CARD(身份证),企业证件类型仅支持 NATIONAL_LEGAL(工商注册号)和 NATIONAL_LEGAL_MERGE ( 社会统一信用代码)。
(2)企业信息可以不填,但是填的话必须填入企业名、企业证件号、企业证件类型。
*/
@ApiField("identity_param")
private String identityParam;
/**
* 认证结束后的商户回调地址。
*/
@ApiField("merchant_url")
private String merchantUrl;
/**
* 产品码,直接使用[示例]给出的值。
*/
@ApiField("product_code")
private String productCode;
/**
* 场景码,表示商户在什么场景使用企业认证产品。
*/
@ApiField("scene_code")
private String sceneCode;
/**
* 商户请求的唯一标志,商户要保证其唯一性。值为32位长度的字母数字下划线组合。建议:前面几位字符是商户自定义的简称,中间可以使用一段日期,结尾可以使用一个序列号。
*/
@ApiField("transaction_id")
private String transactionId;
public String getCertifyMode() {
return this.certifyMode;
}
public void setCertifyMode(String certifyMode) {
this.certifyMode = certifyMode;
}
public String getIdentityParam() {
return this.identityParam;
}
public void setIdentityParam(String identityParam) {
this.identityParam = identityParam;
}
public String getMerchantUrl() {
return this.merchantUrl;
}
public void setMerchantUrl(String merchantUrl) {
this.merchantUrl = merchantUrl;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getSceneCode() {
return this.sceneCode;
}
public void setSceneCode(String sceneCode) {
this.sceneCode = sceneCode;
}
public String getTransactionId() {
return this.transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
|
9234cec6e51254edf0c337329b38e4e22cd61190 | 14,289 | java | Java | netreflected/src/net461/system.net_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/net/sockets/UdpSingleSourceMulticastClient.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 35 | 2020-08-30T03:19:42.000Z | 2022-03-12T09:22:23.000Z | netreflected/src/net461/system.net_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/net/sockets/UdpSingleSourceMulticastClient.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 50 | 2020-06-22T17:03:18.000Z | 2022-03-30T21:19:05.000Z | netreflected/src/net461/system.net_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/net/sockets/UdpSingleSourceMulticastClient.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 12 | 2020-08-30T03:19:45.000Z | 2022-03-05T02:22:37.000Z | 44.514019 | 333 | 0.679334 | 997,063 | /*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.net.sockets;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.net.IPAddress;
import system.IAsyncResult;
import system.IAsyncResultImplementation;
import system.AsyncCallback;
/**
* The base .NET class managing System.Net.Sockets.UdpSingleSourceMulticastClient, System.Net, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Net.Sockets.UdpSingleSourceMulticastClient" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Net.Sockets.UdpSingleSourceMulticastClient</a>
*/
public class UdpSingleSourceMulticastClient extends NetObject implements AutoCloseable {
/**
* Fully assembly qualified name: System.Net, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "System.Net, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: System.Net
*/
public static final String assemblyShortName = "System.Net";
/**
* Qualified class name: System.Net.Sockets.UdpSingleSourceMulticastClient
*/
public static final String className = "System.Net.Sockets.UdpSingleSourceMulticastClient";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public UdpSingleSourceMulticastClient(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link UdpSingleSourceMulticastClient}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link UdpSingleSourceMulticastClient} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static UdpSingleSourceMulticastClient cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new UdpSingleSourceMulticastClient(from.getJCOInstance());
}
// Constructors section
public UdpSingleSourceMulticastClient() throws Throwable {
}
public UdpSingleSourceMulticastClient(IPAddress sourceAddress, IPAddress groupAddress, int localPort) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(sourceAddress == null ? null : sourceAddress.getJCOInstance(), groupAddress == null ? null : groupAddress.getJCOInstance(), localPort));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
public int EndReceiveFromSource(IAsyncResult result, JCORefOut<java.util.concurrent.atomic.AtomicInteger> sourcePort) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArgumentException, system.net.sockets.SocketException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Invoke("EndReceiveFromSource", result == null ? null : result.getJCOInstance(), sourcePort.getJCRefOut());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IAsyncResult BeginJoinGroup(AsyncCallback callback, NetObject state) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArgumentException, system.net.sockets.SocketException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objBeginJoinGroup = (JCObject)classInstance.Invoke("BeginJoinGroup", callback, state == null ? null : state.getJCOInstance());
return new IAsyncResultImplementation(objBeginJoinGroup);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IAsyncResult BeginReceiveFromSource(byte[] buffer, int offset, int count, AsyncCallback callback, NetObject state) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArgumentException, system.net.sockets.SocketException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objBeginReceiveFromSource = (JCObject)classInstance.Invoke("BeginReceiveFromSource", buffer, offset, count, callback, state == null ? null : state.getJCOInstance());
return new IAsyncResultImplementation(objBeginReceiveFromSource);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IAsyncResult BeginReceiveFromSource(JCORefOut dupParam0, int dupParam1, int dupParam2, AsyncCallback dupParam3, NetObject dupParam4) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArgumentException, system.net.sockets.SocketException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objBeginReceiveFromSource = (JCObject)classInstance.Invoke("BeginReceiveFromSource", dupParam0.getJCRefOut(), dupParam1, dupParam2, dupParam3, dupParam4 == null ? null : dupParam4.getJCOInstance());
return new IAsyncResultImplementation(objBeginReceiveFromSource);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IAsyncResult BeginSendToSource(byte[] buffer, int offset, int count, int remotePort, AsyncCallback callback, NetObject state) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArgumentException, system.net.sockets.SocketException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objBeginSendToSource = (JCObject)classInstance.Invoke("BeginSendToSource", buffer, offset, count, remotePort, callback, state == null ? null : state.getJCOInstance());
return new IAsyncResultImplementation(objBeginSendToSource);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IAsyncResult BeginSendToSource(JCORefOut dupParam0, int dupParam1, int dupParam2, int dupParam3, AsyncCallback dupParam4, NetObject dupParam5) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArgumentException, system.net.sockets.SocketException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objBeginSendToSource = (JCObject)classInstance.Invoke("BeginSendToSource", dupParam0.getJCRefOut(), dupParam1, dupParam2, dupParam3, dupParam4, dupParam5 == null ? null : dupParam5.getJCOInstance());
return new IAsyncResultImplementation(objBeginSendToSource);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Dispose() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Dispose");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void EndJoinGroup(IAsyncResult result) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("EndJoinGroup", result == null ? null : result.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void EndSendToSource(IAsyncResult result) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("EndSendToSource", result == null ? null : result.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void close() throws Exception {
try {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Dispose");
}
catch (JCNativeException jcne) {
throw translateException(jcne);
}
} catch (Throwable t) {
throw new Exception(t);
}
}
// Properties section
public int getReceiveBufferSize() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Get("ReceiveBufferSize");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setReceiveBufferSize(int ReceiveBufferSize) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("ReceiveBufferSize", ReceiveBufferSize);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public int getSendBufferSize() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Get("SendBufferSize");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setSendBufferSize(int SendBufferSize) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("SendBufferSize", SendBufferSize);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
} |
9234d06d49c56f7616db33493c3245b46c43d02d | 220 | java | Java | java-puzzlers/src/test/java/com/markruler/puzzler/fixture/Counter.java | xpdojo/java | 66985d884439a85f963274b55b3e895e31552594 | [
"Apache-2.0"
] | null | null | null | java-puzzlers/src/test/java/com/markruler/puzzler/fixture/Counter.java | xpdojo/java | 66985d884439a85f963274b55b3e895e31552594 | [
"Apache-2.0"
] | 18 | 2021-12-11T10:48:56.000Z | 2022-03-29T01:04:08.000Z | java-puzzlers/src/test/java/com/markruler/puzzler/fixture/Counter.java | xpdojo/java | 66985d884439a85f963274b55b3e895e31552594 | [
"Apache-2.0"
] | null | null | null | 15.714286 | 38 | 0.618182 | 997,064 | package com.markruler.puzzler.fixture;
public class Counter {
private static int count;
public static void increment() {
count++;
}
public static int getCount() {
return count;
}
}
|
9234d127f974c4989fc86daff41cfb42ee7ebd75 | 2,591 | java | Java | src/main/java/me/coley/puredds/sub/SampleImpl.java | chesapeaketechnology/PureDDS | eb56e81bc4beb7940e4b955186f49db3652061ba | [
"MIT"
] | 6 | 2020-06-15T15:13:17.000Z | 2022-01-04T06:11:36.000Z | src/main/java/me/coley/puredds/sub/SampleImpl.java | yourfrienddhruv/PureDDS | eb56e81bc4beb7940e4b955186f49db3652061ba | [
"MIT"
] | null | null | null | src/main/java/me/coley/puredds/sub/SampleImpl.java | yourfrienddhruv/PureDDS | eb56e81bc4beb7940e4b955186f49db3652061ba | [
"MIT"
] | 1 | 2021-04-15T17:48:19.000Z | 2021-04-15T17:48:19.000Z | 20.242188 | 83 | 0.743728 | 997,065 | package me.coley.puredds.sub;
import org.omg.dds.core.ModifiableInstanceHandle;
import org.omg.dds.core.ServiceEnvironment;
import org.omg.dds.core.Time;
import org.omg.dds.sub.InstanceState;
import org.omg.dds.sub.Sample;
import org.omg.dds.sub.SampleState;
import org.omg.dds.sub.ViewState;
/**
* Sample impl.
*
* @param <T>
* Topic data type.
*
* @author Matt Coley
*/
public class SampleImpl<T> implements Sample<T> {
private final ServiceEnvironment environment;
private final SampleState sampleState;
private final ViewState viewState;
private final InstanceState instanceState;
private final Time srcTime;
private final ModifiableInstanceHandle handle;
private final ModifiableInstanceHandle publicationHandle;
private final int numDisposed;
private final int numNoWrters;
private final int sampleRank;
private final int generationRank;
private final int absGenerationRank;
private final T data;
/**
* Create a sample.
*
* @param environment
* Environment context.
*/
public SampleImpl(ServiceEnvironment environment) {
this.environment = environment;
// TODO: How to collect this info and pass it effectively?
// - This will require laying out how the topic data types (T) are actually read
sampleState = null;
viewState = null;
instanceState = null;
srcTime = null;
handle = null;
publicationHandle = null;
numDisposed = 0;
numNoWrters = 0;
sampleRank = 0;
generationRank = 0;
absGenerationRank = 0;
data = null;
}
@Override
public T getData() {
return data;
}
@Override
public SampleState getSampleState() {
return sampleState;
}
@Override
public ViewState getViewState() {
return viewState;
}
@Override
public InstanceState getInstanceState() {
return instanceState;
}
@Override
public Time getSourceTimestamp() {
return srcTime;
}
@Override
public ModifiableInstanceHandle getInstanceHandle() {
return handle;
}
@Override
public ModifiableInstanceHandle getPublicationHandle() {
return publicationHandle;
}
@Override
public int getDisposedGenerationCount() {
return numDisposed;
}
@Override
public int getNoWritersGenerationCount() {
return numNoWrters;
}
@Override
public int getSampleRank() {
return sampleRank;
}
@Override
public int getGenerationRank() {
return generationRank;
}
@Override
public int getAbsoluteGenerationRank() {
return absGenerationRank;
}
@Override
public Sample<T> clone() {
return new SampleImpl<>(getEnvironment());
}
@Override
public ServiceEnvironment getEnvironment() {
return environment;
}
}
|
9234d22db0fcfcccaa1222d19fdb38c2df7b32a7 | 972 | java | Java | server/src/main/java/org/eclipse/lsp/cobol/core/messages/MessageService.java | VitGottwald/che-che4z-lsp-for-cobol | 6e93fa7d413ef474d45811f965d710a368dba2be | [
"Apache-2.0"
] | null | null | null | server/src/main/java/org/eclipse/lsp/cobol/core/messages/MessageService.java | VitGottwald/che-che4z-lsp-for-cobol | 6e93fa7d413ef474d45811f965d710a368dba2be | [
"Apache-2.0"
] | 1 | 2021-03-18T13:02:33.000Z | 2021-03-18T13:02:33.000Z | server/src/main/java/org/eclipse/lsp/cobol/core/messages/MessageService.java | isabella232/che-che4z-lsp-for-cobol | 32623e8364c1701436d75bdcc4ffc231337c6507 | [
"Apache-2.0"
] | 1 | 2021-06-24T11:15:30.000Z | 2021-06-24T11:15:30.000Z | 32.4 | 97 | 0.716049 | 997,066 | /*
* Copyright (c) 2020 Broadcom.
* The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*
*/
package org.eclipse.lsp.cobol.core.messages;
/** This class sets the basic contract for any externalized message service to be implemented. */
public interface MessageService {
/**
* This method return an {@link String} based on passes key and params.
*
* @param key Unique ID for each message in externalized message file.
* @param parameters Arguments referenced by the format specifiers in the format * string in
* externalized message file.
* @return {@link String}
*/
String getMessage(String key, Object... parameters);
}
|
9234d24befdc78cd4649397fbfb8ff60ca795f6c | 3,612 | java | Java | src/textgen/MyLinkedList.java | Alexzi666/text_generator | a710bb0a0a370e8b91ac0611d4a157df4aaf2114 | [
"BSD-2-Clause"
] | 1 | 2021-05-30T07:21:29.000Z | 2021-05-30T07:21:29.000Z | src/textgen/MyLinkedList.java | Alexzi666/text_generator | a710bb0a0a370e8b91ac0611d4a157df4aaf2114 | [
"BSD-2-Clause"
] | null | null | null | src/textgen/MyLinkedList.java | Alexzi666/text_generator | a710bb0a0a370e8b91ac0611d4a157df4aaf2114 | [
"BSD-2-Clause"
] | null | null | null | 20.64 | 80 | 0.627353 | 997,067 | package textgen;
import java.util.AbstractList;
/** A class that implements a doubly linked list
*
* @author UC San Diego Intermediate Programming MOOC team
*
* @param <E> The type of the elements stored in the list
*/
public class MyLinkedList<E> extends AbstractList<E> {
LLNode<E> head;
LLNode<E> tail;
int size;
/** Create a new empty LinkedList */
public MyLinkedList() {
head = new LLNode<E>(null);
tail = new LLNode<E>(null);
size = 0;
head.next = tail;
tail.prev = head;
// TODO: Implement this method
}
/**
* Appends an element to the end of the list
* @param element The element to add
*/
public boolean add(E element )
{
if(element == null) {
throw new NullPointerException();
}
LLNode<E> n = new LLNode<E>(element);
tail.prev.next = n;
n.next = tail;
n.prev = tail.prev;
tail.prev = n;
size++;
// TODO: Implement this method
return true;
}
/** Get the element at position index
* @throws IndexOutOfBoundsException if the index is out of bounds. */
public E get(int index)
{
if(index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
LLNode<E> n = head;
for(int i = 0; i <= index; i++) {
n = n.next;
}
// TODO: Implement this method.
return n.data;
}
/**
* Add an element to the list at the specified index
* @param The index where the element should be added
* @param element The element to add
*/
public void add(int index, E element )
{
if(element == null) {
throw new NullPointerException();
}
if((index < 0 || index >= size) && size != 0) {
// System.out.println("I am here" + index + element + " i failed");
throw new IndexOutOfBoundsException();
}
LLNode<E> prev = head;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
LLNode<E> node = new LLNode<E>(element);
node.next = prev.next;
prev.next = node;
node.next.prev = node;
node.prev = prev;
size++;
// TODO: Implement this method
}
/** Return the size of the list */
public int size()
{
// TODO: Implement this method
return size;
}
/** Remove a node at the specified index and return its data element.
* @param index The index of the element to remove
* @return The data element removed
* @throws IndexOutOfBoundsException If index is outside the bounds of the list
*
*/
public E remove(int index)
{
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
LLNode<E> n = head;
for (int i = 0; i <= index; i++) {
n = n.next;
}
n.prev.next = n.next;
n.next.prev = n.prev;
size--;
return n.data;
// TODO: Implement this method
}
/**
* Set an index position in the list to a new element
* @param index The index of the element to change
* @param element The new element
* @return The element that was replaced
* @throws IndexOutOfBoundsException if the index is out of bounds.
*/
public E set(int index, E element)
{
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
if (element == null) {
throw new NullPointerException();
}
LLNode<E> n = head;
for (int i = 0; i <= index; i++) {
n = n.next;
}
n.data = element;
return element;
// TODO: Implement this method
}
}
class LLNode<E>
{
LLNode<E> prev;
LLNode<E> next;
E data;
// TODO: Add any other methods you think are useful here
// E.g. you might want to add another constructor
public LLNode()
{
this.data = null;
this.prev = null;
this.next = null;
}
public LLNode(E e)
{
this.data = e;
this.prev = null;
this.next = null;
}
}
|
9234d31594ef51e02a79575d26730beeb3cd34cc | 1,558 | java | Java | src/com/haxademic/core/draw/textures/SimplexNoiseTexture.java | cacheflowe/haxademic | 9873996e1553c7b5d9807801581c82abf1895f27 | [
"MIT"
] | 142 | 2015-01-04T05:24:37.000Z | 2022-02-07T15:05:28.000Z | src/com/haxademic/core/draw/textures/SimplexNoiseTexture.java | cacheflowe/haxademic | 9873996e1553c7b5d9807801581c82abf1895f27 | [
"MIT"
] | 5 | 2015-04-19T00:36:40.000Z | 2022-02-02T20:02:04.000Z | src/com/haxademic/core/draw/textures/SimplexNoiseTexture.java | cacheflowe/haxademic | 9873996e1553c7b5d9807801581c82abf1895f27 | [
"MIT"
] | 27 | 2015-01-04T05:24:41.000Z | 2021-06-25T20:36:34.000Z | 25.129032 | 79 | 0.725289 | 997,068 | package com.haxademic.core.draw.textures;
import com.haxademic.core.draw.context.PG;
import com.haxademic.core.draw.textures.pshader.TextureShader;
import processing.core.PGraphics;
import processing.core.PVector;
public class SimplexNoiseTexture {
protected TextureShader noiseTexture;
protected PGraphics noiseBuffer;
protected float zoom = 1;
protected float rotation = 0;
protected PVector offset = new PVector();
public SimplexNoiseTexture(int w, int h) {
this(w, h, false);
}
public SimplexNoiseTexture(int w, int h, boolean is32bit) {
noiseTexture = new TextureShader(TextureShader.noise_simplex_2d_iq);
noiseBuffer = (is32bit) ? PG.newPG32(w, h, false, false) : PG.newPG(w, h);
}
public PGraphics texture() {
return noiseBuffer;
}
public void zoom(float zoom) {
this.update(zoom, rotation, offset.x, offset.y);
}
public void rotation(float rotation) {
this.update(zoom, rotation, offset.x, offset.y);
}
public void offsetX(float offsetX) {
this.update(zoom, rotation, offsetX, offset.y);
}
public void offsetY(float offsetY) {
this.update(zoom, rotation, offset.x, offsetY);
}
public void update(float zoom, float rotation, float offsetX, float offsetY) {
this.zoom = zoom;
this.rotation = rotation;
this.offset.set(offsetX, offsetY);
this.update();
}
public void update() {
noiseTexture.shader().set("offset", offset.x, offset.y);
noiseTexture.shader().set("rotation", rotation);
noiseTexture.shader().set("zoom", zoom);
noiseBuffer.filter(noiseTexture.shader());
}
}
|
9234d31c7e7fa6ac841e7b71e0669f96657ab71c | 23,160 | java | Java | Benchmarks_with_Functional_Bugs/Java/DataflowJavaSDK-c06125d/src/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java | kupl/starlab-benchmarks | 1efc9efffad1b797f6a795da7e032041e230d900 | [
"MIT"
] | null | null | null | Benchmarks_with_Functional_Bugs/Java/DataflowJavaSDK-c06125d/src/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java | kupl/starlab-benchmarks | 1efc9efffad1b797f6a795da7e032041e230d900 | [
"MIT"
] | null | null | null | Benchmarks_with_Functional_Bugs/Java/DataflowJavaSDK-c06125d/src/sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/StreamingDataflowWorker.java | kupl/starlab-benchmarks | 1efc9efffad1b797f6a795da7e032041e230d900 | [
"MIT"
] | 2 | 2020-11-26T13:27:14.000Z | 2022-03-20T02:12:55.000Z | 36.074766 | 100 | 0.670121 | 997,069 | /*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.dataflow.sdk.runners.worker;
import com.google.api.services.dataflow.model.MapTask;
import com.google.api.services.dataflow.model.MetricUpdate;
import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.runners.worker.windmill.Windmill;
import com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServerStub;
import com.google.cloud.dataflow.sdk.util.BoundedQueueExecutor;
import com.google.cloud.dataflow.sdk.util.CloudCounterUtils;
import com.google.cloud.dataflow.sdk.util.StateFetcher;
import com.google.cloud.dataflow.sdk.util.StreamingModeExecutionContext;
import com.google.cloud.dataflow.sdk.util.Transport;
import com.google.cloud.dataflow.sdk.util.UserCodeException;
import com.google.cloud.dataflow.sdk.util.Values;
import com.google.cloud.dataflow.sdk.util.common.Counter;
import com.google.cloud.dataflow.sdk.util.common.CounterSet;
import com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Implements a Streaming Dataflow worker.
*/
public class StreamingDataflowWorker {
private static final Logger LOG = Logger.getLogger(StreamingDataflowWorker.class.getName());
static final int MAX_THREAD_POOL_SIZE = 100;
static final long THREAD_EXPIRATION_TIME_SEC = 60;
static final int MAX_THREAD_POOL_QUEUE_SIZE = 100;
static final long MAX_COMMIT_BYTES = 32 << 20;
static final int DEFAULT_STATUS_PORT = 8081;
// Memory threshold under which no new work will be processed. Set to 0 to disable pushback.
static final double PUSHBACK_THRESHOLD = 0.1;
static final String WINDMILL_SERVER_CLASS_NAME =
"com.google.cloud.dataflow.sdk.runners.worker.windmill.WindmillServer";
/**
* Indicates that the key token was invalid when data was attempted to be fetched.
*/
public static class KeyTokenInvalidException extends RuntimeException {
public KeyTokenInvalidException(String key) {
super("Unable to fetch data due to token mismatch for key " + key);
}
}
static MapTask parseMapTask(String input) throws IOException {
return Transport.getJsonFactory()
.fromString(input, MapTask.class);
}
public static void main(String[] args) throws Exception {
LOG.setLevel(Level.INFO);
String hostport = System.getProperty("windmill.hostport");
if (hostport == null) {
throw new Exception("-Dwindmill.hostport must be set to the location of the windmill server");
}
int statusPort = DEFAULT_STATUS_PORT;
if (System.getProperties().containsKey("status_port")) {
statusPort = Integer.parseInt(System.getProperty("status_port"));
}
ArrayList<MapTask> mapTasks = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
mapTasks.add(parseMapTask(args[i]));
}
WindmillServerStub windmillServer =
(WindmillServerStub) Class.forName(WINDMILL_SERVER_CLASS_NAME)
.getDeclaredConstructor(String.class).newInstance(hostport);
StreamingDataflowWorker worker =
new StreamingDataflowWorker(mapTasks, windmillServer);
worker.start();
worker.runStatusServer(statusPort);
}
private ConcurrentMap<String, MapTask> instructionMap;
private ConcurrentMap<String, ConcurrentLinkedQueue<Windmill.WorkItemCommitRequest>> outputMap;
private ConcurrentMap<String, ConcurrentLinkedQueue<WorkerAndContext>> mapTaskExecutors;
private ThreadFactory threadFactory;
private BoundedQueueExecutor executor;
private WindmillServerStub windmillServer;
private Thread dispatchThread;
private Thread commitThread;
private AtomicBoolean running;
private StateFetcher stateFetcher;
private DataflowPipelineOptions options;
private long clientId;
private Server statusServer;
private AtomicReference<Throwable> lastException;
/** Regular constructor. */
public StreamingDataflowWorker(
List<MapTask> mapTasks, WindmillServerStub server) {
initialize(mapTasks, server);
options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
options.setAppName("StreamingWorkerHarness");
options.setStreaming(true);
if (System.getProperties().containsKey("path_validator_class")) {
try {
options.setPathValidatorClass((Class) Class.forName(
System.getProperty("path_validator_class")));
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to find validator class", e);
}
}
if (System.getProperties().containsKey("credential_factory_class")) {
try {
options.setCredentialFactoryClass((Class) Class.forName(
System.getProperty("credential_factory_class")));
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to find credential factory class", e);
}
}
}
/** The constructor that takes PipelineOptions. Should be used only by unit tests. */
StreamingDataflowWorker(
List<MapTask> mapTasks, WindmillServerStub server, DataflowPipelineOptions options) {
initialize(mapTasks, server);
this.options = options;
}
public void start() {
running.set(true);
dispatchThread = threadFactory.newThread(new Runnable() {
public void run() {
dispatchLoop();
}
});
dispatchThread.setPriority(Thread.MIN_PRIORITY);
dispatchThread.setName("DispatchThread");
dispatchThread.start();
commitThread = threadFactory.newThread(new Runnable() {
public void run() {
commitLoop();
}
});
commitThread.setPriority(Thread.MAX_PRIORITY);
commitThread.setName("CommitThread");
commitThread.start();
}
public void stop() {
try {
if (statusServer != null) {
statusServer.stop();
}
running.set(false);
dispatchThread.join();
executor.shutdown();
if (!executor.awaitTermination(5, TimeUnit.MINUTES)) {
throw new RuntimeException("Process did not terminate within 5 minutes");
}
for (ConcurrentLinkedQueue<WorkerAndContext> queue : mapTaskExecutors.values()) {
WorkerAndContext workerAndContext;
while ((workerAndContext = queue.poll()) != null) {
workerAndContext.getWorker().close();
}
}
commitThread.join();
} catch (Exception e) {
LOG.warning("Exception while shutting down: " + e);
e.printStackTrace();
}
}
/** Initializes the execution harness. */
private void initialize(List<MapTask> mapTasks, WindmillServerStub server) {
this.instructionMap = new ConcurrentHashMap<>();
this.outputMap = new ConcurrentHashMap<>();
this.mapTaskExecutors = new ConcurrentHashMap<>();
for (MapTask mapTask : mapTasks) {
addComputation(mapTask);
}
this.threadFactory = new ThreadFactory() {
private final Thread.UncaughtExceptionHandler handler =
new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable e) {
LOG.severe("Uncaught exception: " + e);
e.printStackTrace();
System.exit(1);
}
};
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(handler);
t.setDaemon(true);
return t;
}
};
this.executor = new BoundedQueueExecutor(
MAX_THREAD_POOL_SIZE, THREAD_EXPIRATION_TIME_SEC, TimeUnit.SECONDS,
MAX_THREAD_POOL_QUEUE_SIZE, threadFactory);
this.windmillServer = server;
this.running = new AtomicBoolean();
this.stateFetcher = new StateFetcher(server);
this.clientId = new Random().nextLong();
this.lastException = new AtomicReference<>();
}
public void runStatusServer(int statusPort) {
statusServer = new Server(statusPort);
statusServer.setHandler(new StatusHandler());
try {
statusServer.start();
LOG.info("Status server started on port " + statusPort);
statusServer.join();
} catch (Exception e) {
LOG.warning("Status server failed to start: " + e);
}
}
private void addComputation(MapTask mapTask) {
String computation = mapTask.getSystemName();
if (!instructionMap.containsKey(computation)) {
LOG.info("Adding config for " + computation + ": " + mapTask);
outputMap.put(computation, new ConcurrentLinkedQueue<Windmill.WorkItemCommitRequest>());
instructionMap.put(computation, mapTask);
mapTaskExecutors.put(
computation,
new ConcurrentLinkedQueue<WorkerAndContext>());
}
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// NOLINT
}
}
private void dispatchLoop() {
LOG.info("Dispatch starting");
Runtime rt = Runtime.getRuntime();
long lastPushbackLog = 0;
while (running.get()) {
// If free memory is less than a percentage of total memory, block
// until current work drains and memory is released.
// Also force a GC to try to get under the memory threshold if possible.
while (rt.freeMemory() < rt.totalMemory() * PUSHBACK_THRESHOLD) {
if (lastPushbackLog < (lastPushbackLog = System.currentTimeMillis()) - 60 * 1000) {
LOG.warning("In pushback, not accepting new work. Free Memory: "
+ rt.freeMemory() + "MB / " + rt.totalMemory() + "MB");
System.gc();
}
sleep(10);
}
int backoff = 1;
Windmill.GetWorkResponse workResponse;
do {
workResponse = getWork();
if (workResponse.getWorkCount() > 0) {
break;
}
sleep(backoff);
backoff = Math.min(1000, backoff * 2);
} while (running.get());
for (final Windmill.ComputationWorkItems computationWork : workResponse.getWorkList()) {
for (final Windmill.WorkItem work : computationWork.getWorkList()) {
final String computation = computationWork.getComputationId();
if (!instructionMap.containsKey(computation)) {
getConfig(computation);
}
executor.execute(new Runnable() {
public void run() {
process(computation, work);
}
});
}
}
}
LOG.info("Dispatch done");
}
private void process(
final String computation, final Windmill.WorkItem work) {
LOG.log(Level.FINE, "Starting processing for " + computation + ":\n{0}", work);
MapTask mapTask = instructionMap.get(computation);
if (mapTask == null) {
LOG.info("Received work for unknown computation: " + computation
+ ". Known computations are " + instructionMap.keySet());
return;
}
Windmill.WorkItemCommitRequest.Builder outputBuilder =
Windmill.WorkItemCommitRequest.newBuilder()
.setKey(work.getKey())
.setWorkToken(work.getWorkToken());
StreamingModeExecutionContext context = null;
MapTaskExecutor worker = null;
try {
WorkerAndContext workerAndContext = mapTaskExecutors.get(computation).poll();
if (workerAndContext == null) {
context = new StreamingModeExecutionContext(computation, stateFetcher);
worker = MapTaskExecutorFactory.create(options, mapTask, context);
} else {
worker = workerAndContext.getWorker();
context = workerAndContext.getContext();
}
context.start(work, outputBuilder);
// Blocks while executing work.
worker.execute();
buildCounters(worker.getOutputCounters(), outputBuilder);
context.flushState();
mapTaskExecutors.get(computation).offer(new WorkerAndContext(worker, context));
worker = null;
context = null;
} catch (Throwable t) {
if (worker != null) {
try {
worker.close();
} catch (Exception e) {
LOG.warning("Failed to close worker: " + e.getMessage());
e.printStackTrace();
}
}
t = t instanceof UserCodeException ? t.getCause() : t;
if (t instanceof KeyTokenInvalidException) {
LOG.fine("Execution of work for " + computation + " for key " + work.getKey().toStringUtf8()
+ " failed due to token expiration, will not retry locally.");
} else {
LOG.warning("Execution of work for " + computation + " for key "
+ work.getKey().toStringUtf8() + " failed, retrying."
+ "\nError: " + t.getMessage());
t.printStackTrace();
lastException.set(t);
LOG.fine("Failed work: " + work);
reportFailure(computation, work, t);
// Try again, but go to the end of the queue to avoid a tight loop.
sleep(60000);
executor.forceExecute(new Runnable() {
public void run() {
process(computation, work);
}
});
}
return;
}
Windmill.WorkItemCommitRequest output = outputBuilder.build();
outputMap.get(computation).add(output);
LOG.fine("Processing done for work token: " + work.getWorkToken());
}
private void commitLoop() {
while (running.get()) {
Windmill.CommitWorkRequest.Builder commitRequestBuilder =
Windmill.CommitWorkRequest.newBuilder();
long remainingCommitBytes = MAX_COMMIT_BYTES;
for (Map.Entry<String, ConcurrentLinkedQueue<Windmill.WorkItemCommitRequest>> entry :
outputMap.entrySet()) {
Windmill.ComputationCommitWorkRequest.Builder computationRequestBuilder =
Windmill.ComputationCommitWorkRequest.newBuilder();
ConcurrentLinkedQueue<Windmill.WorkItemCommitRequest> queue = entry.getValue();
while (remainingCommitBytes > 0) {
Windmill.WorkItemCommitRequest request = queue.poll();
if (request == null) {
break;
}
remainingCommitBytes -= request.getSerializedSize();
computationRequestBuilder.addRequests(request);
}
if (computationRequestBuilder.getRequestsCount() > 0) {
computationRequestBuilder.setComputationId(entry.getKey());
commitRequestBuilder.addRequests(computationRequestBuilder);
}
}
if (commitRequestBuilder.getRequestsCount() > 0) {
Windmill.CommitWorkRequest commitRequest = commitRequestBuilder.build();
LOG.log(Level.FINE, "Commit: {0}", commitRequest);
commitWork(commitRequest);
}
if (remainingCommitBytes > 0) {
sleep(100);
}
}
}
private Windmill.GetWorkResponse getWork() {
return windmillServer.getWork(
Windmill.GetWorkRequest.newBuilder()
.setClientId(clientId)
.setMaxItems(100)
.build());
}
private void commitWork(Windmill.CommitWorkRequest request) {
windmillServer.commitWork(request);
}
private void getConfig(String computation) {
Windmill.GetConfigRequest request =
Windmill.GetConfigRequest.newBuilder().addComputations(computation).build();
for (String serializedMapTask : windmillServer.getConfig(request).getCloudWorksList()) {
try {
addComputation(parseMapTask(serializedMapTask));
} catch (IOException e) {
LOG.warning("Parsing MapTask failed: " + serializedMapTask);
e.printStackTrace();
}
}
}
private void buildCounters(CounterSet counterSet,
Windmill.WorkItemCommitRequest.Builder builder) {
for (MetricUpdate metricUpdate :
CloudCounterUtils.extractCounters(counterSet, true /* delta */)) {
Windmill.Counter.Kind kind;
String cloudKind = metricUpdate.getKind();
if (cloudKind.equals(Counter.AggregationKind.SUM.name())) {
kind = Windmill.Counter.Kind.SUM;
} else if (cloudKind.equals(Counter.AggregationKind.MEAN.name())) {
kind = Windmill.Counter.Kind.MEAN;
} else if (cloudKind.equals(Counter.AggregationKind.MAX.name())) {
kind = Windmill.Counter.Kind.MAX;
} else if (cloudKind.equals(Counter.AggregationKind.MIN.name())) {
kind = Windmill.Counter.Kind.MIN;
} else {
LOG.log(Level.FINE, "Unhandled counter type: " + metricUpdate.getKind());
return;
}
Windmill.Counter.Builder counterBuilder = builder.addCounterUpdatesBuilder();
counterBuilder.setName(metricUpdate.getName().getName()).setKind(kind);
Object element = null;
if (kind == Windmill.Counter.Kind.MEAN) {
Object meanCount = metricUpdate.getMeanCount();
if (meanCount != null) {
try {
Long longValue = Values.asLong(meanCount);
if (longValue != 0) {
counterBuilder.setMeanCount(longValue);
}
} catch (ClassCastException e) {
// Nothing to do.
}
}
element = metricUpdate.getMeanSum();
} else {
element = metricUpdate.getScalar();
}
if (element != null) {
try {
Double doubleValue = Values.asDouble(element);
if (doubleValue != 0) {
counterBuilder.setDoubleScalar(doubleValue);
}
} catch (ClassCastException e) {
// Nothing to do.
}
try {
Long longValue = Values.asLong(element);
if (longValue != 0) {
counterBuilder.setIntScalar(longValue);
}
} catch (ClassCastException e) {
// Nothing to do.
}
}
}
}
private Windmill.Exception buildExceptionReport(Throwable t) {
Windmill.Exception.Builder builder = Windmill.Exception.newBuilder();
builder.addStackFrames(t.toString());
for (StackTraceElement frame : t.getStackTrace()) {
builder.addStackFrames(frame.toString());
}
if (t.getCause() != null) {
builder.setCause(buildExceptionReport(t.getCause()));
}
return builder.build();
}
private void reportFailure(String computation, Windmill.WorkItem work, Throwable t) {
windmillServer.reportStats(Windmill.ReportStatsRequest.newBuilder()
.setComputationId(computation)
.setKey(work.getKey())
.setWorkToken(work.getWorkToken())
.addExceptions(buildExceptionReport(t))
.build());
}
private static class WorkerAndContext {
public MapTaskExecutor worker;
public StreamingModeExecutionContext context;
public WorkerAndContext(MapTaskExecutor worker, StreamingModeExecutionContext context) {
this.worker = worker;
this.context = context;
}
public MapTaskExecutor getWorker() {
return worker;
}
public StreamingModeExecutionContext getContext() {
return context;
}
}
private class StatusHandler extends AbstractHandler {
@Override
public void handle(
String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
PrintWriter responseWriter = response.getWriter();
responseWriter.println("<html><body>");
printHeader(responseWriter);
printMetrics(responseWriter);
printResources(responseWriter);
printLastException(responseWriter);
printSpecs(responseWriter);
responseWriter.println("</body></html>");
}
}
private void printHeader(PrintWriter response) {
response.println("<h1>Streaming Worker Harness</h1>");
response.println("Running: " + running.get() + "<br>");
response.println("ID: " + clientId + "<br>");
}
private void printMetrics(PrintWriter response) {
response.println("<h2>Metrics</h2>");
response.println("Worker Threads: " + executor.getPoolSize()
+ "/" + MAX_THREAD_POOL_QUEUE_SIZE + "<br>");
response.println("Active Threads: " + executor.getActiveCount() + "<br>");
response.println("Work Queue Size: " + executor.getQueue().size() + "<br>");
response.println("Commit Queues: <ul>");
for (Map.Entry<String, ConcurrentLinkedQueue<Windmill.WorkItemCommitRequest>> entry
: outputMap.entrySet()) {
response.print("<li>");
response.print(entry.getKey());
response.print(": ");
response.print(entry.getValue().size());
response.println("</li>");
}
response.println("</ul>");
}
private void printResources(PrintWriter response) {
Runtime rt = Runtime.getRuntime();
int mb = 1024 * 1024;
response.append("<h2>Resources</h2>\n");
response.append("Total Memory: " + rt.totalMemory() / mb + "MB<br>\n");
response.append("Used Memory: " + (rt.totalMemory() - rt.freeMemory()) / mb + "MB<br>\n");
response.append("Max Memory: " + rt.maxMemory() / mb + "MB<br>\n");
}
private void printSpecs(PrintWriter response) {
response.append("<h2>Specs</h2>\n");
for (Map.Entry<String, MapTask> entry : instructionMap.entrySet()) {
response.println("<h3>" + entry.getKey() + "</h3>");
response.print("<script>document.write(JSON.stringify(");
response.print(entry.getValue().toString());
response.println(", null, \"  \").replace(/\\n/g, \"<br>\"))</script>");
}
}
private void printLastException(PrintWriter response) {
Throwable t = lastException.get();
if (t != null) {
response.println("<h2>Last Exception</h2>");
StringWriter writer = new StringWriter();
t.printStackTrace(new PrintWriter(writer));
response.println(writer.toString().replace("\t", "  ").replace("\n", "<br>"));
}
}
}
|
9234d3387212b20d0ff9b07b09c05ba370219a06 | 6,219 | java | Java | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/internal/LinearOpModeCamera.java | JaradAPCS/wiredcats-ftc_app-master-old | bd428664becdd1a21f3eb4d94a9f0b72adb2abec | [
"MIT"
] | null | null | null | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/internal/LinearOpModeCamera.java | JaradAPCS/wiredcats-ftc_app-master-old | bd428664becdd1a21f3eb4d94a9f0b72adb2abec | [
"MIT"
] | null | null | null | FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/internal/LinearOpModeCamera.java | JaradAPCS/wiredcats-ftc_app-master-old | bd428664becdd1a21f3eb4d94a9f0b72adb2abec | [
"MIT"
] | 4 | 2016-11-17T23:05:39.000Z | 2016-12-02T13:55:04.000Z | 28.39726 | 137 | 0.585303 | 997,070 | package org.firstinspires.ftc.robotcontroller.internal;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.util.Log;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import java.io.ByteArrayOutputStream;
import java.util.List;
/**
* TeleOp Mode
* <p/>
* Enables control of the robot via the gamepad
*/
public class LinearOpModeCamera extends LinearOpMode {
public Camera camera;
public CameraPreview preview;
public int width;
public int height;
public YuvImage yuvImage = null;
volatile private boolean imageReady = false;
private int looped = 0;
private String data;
private int ds = 1; // downsampling parameter
@Override
// should be overwritten by extension class
public void runOpMode() throws InterruptedException {
}
public Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
try {
Camera.Parameters parameters = camera.getParameters();
width = parameters.getPreviewSize().width;
height = parameters.getPreviewSize().height;
yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null);
imageReady = true;
looped += 1;
} catch (Exception e) {
}
}
};
public void setCameraDownsampling(int downSampling) {
ds = downSampling;
}
public boolean imageReady() {
return imageReady;
}
public boolean isCameraAvailable() {
int cameraId = -1;
Camera cam = null;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { //change to back // Camera.CameraInfo.CAMERA_FACING_FRONT or BACK
cameraId = i;
break;
}
}
try {
cam = Camera.open(cameraId);
} catch (Exception e) {
Log.e("Error", "Camera Not Available!");
return false;
}
cam.release();
cam = null;
return true;
}
public Camera openCamera(int cameraInfoType) {
int cameraId = -1;
Camera cam = null;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == cameraInfoType) { // Camera.CameraInfo.CAMERA_FACING_FRONT or BACK
cameraId = i;
break;
}
}
try {
cam = Camera.open(cameraId);
} catch (Exception e) {
Log.e("Error", "Can't Open Camera");
}
return cam;
}
public int red(int pixel) {
return (pixel >> 16) & 0xff;
}
public int green(int pixel) {
return (pixel >> 8) & 0xff;
}
public int blue(int pixel) {
return pixel & 0xff;
}
public int gray(int pixel) {
return (red(pixel) + green(pixel) + blue(pixel));
}
public int highestColor(int red, int green, int blue) {
int[] color = {red, green, blue};
int value = 0;
for (int i = 1; i < 3; i++) {
if (color[value] < color[i]) {
value = i;
}
}
return value;
}
public Bitmap convertYuvImageToRgb(YuvImage yuvImage, int width, int height, int downSample) {
Bitmap rgbImage;
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 0, out);
byte[] imageBytes = out.toByteArray();
BitmapFactory.Options opt;
opt = new BitmapFactory.Options();
opt.inSampleSize = downSample;
rgbImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, opt);
return rgbImage;
}
public void startCamera() {
camera = openCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); //change to back
camera.setPreviewCallback(previewCallback);
Camera.Parameters parameters = camera.getParameters();
//width = parameters.getPreviewSize().width / ds;
//height = parameters.getPreviewSize().height / ds;
//parameters.setPreviewSize(width, height);
//
//parameters.setPreviewSize(width, height);
//change
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Camera.Size cs = sizes.get(0);
parameters.setPreviewSize(cs.width, cs.height);
//end
camera.setParameters(parameters);
data = parameters.flatten();
if (preview == null) {
((FtcRobotControllerActivity) hardwareMap.appContext).initPreviewLinear(camera, this, previewCallback);
}
}
public void stopCameraInSecs(int duration) {
Thread cameraKillThread = new Thread(new CameraKillThread(duration));
cameraKillThread.start();
}
public class CameraKillThread implements Runnable {
int dur;
public CameraKillThread(int duration) {
dur=duration;
}
public void run() {
try {
Thread.sleep(dur * 1000, 0);
} catch(InterruptedException ex) {
}
stopCamera();
imageReady=false;
}
}
public void stopCamera() {
if (camera != null) {
if (preview != null) {
((FtcRobotControllerActivity) hardwareMap.appContext).removePreviewLinear(this);
preview = null;
}
camera.stopPreview();
camera.setPreviewCallback(null);
if(camera != null) {
camera.release();
}
camera = null;
}
}
}
|
9234d4458f23ee7d74fe79f3bc2322e7164c2b33 | 11,478 | java | Java | characteristic/u2afa/src/androidTest/java/org/im97mori/ble/characteristic/u2afa/GenericLevelAndroidTest.java | im97mori-github/AndroidBLEUtil | f032d360b2393e1a3291b5e551c67ad3ebb9b5eb | [
"MIT"
] | 2 | 2021-12-16T01:34:55.000Z | 2021-12-17T02:19:48.000Z | characteristic/u2afa/src/androidTest/java/org/im97mori/ble/characteristic/u2afa/GenericLevelAndroidTest.java | im97mori-github/AndroidBLEUtil | f032d360b2393e1a3291b5e551c67ad3ebb9b5eb | [
"MIT"
] | null | null | null | characteristic/u2afa/src/androidTest/java/org/im97mori/ble/characteristic/u2afa/GenericLevelAndroidTest.java | im97mori-github/AndroidBLEUtil | f032d360b2393e1a3291b5e551c67ad3ebb9b5eb | [
"MIT"
] | 2 | 2020-11-03T02:19:25.000Z | 2021-12-16T01:35:06.000Z | 39.308219 | 115 | 0.665621 | 997,071 | package org.im97mori.ble.characteristic.u2afa;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.Parcel;
import org.im97mori.ble.BLEUtils;
import org.junit.Test;
import static org.im97mori.ble.BLEUtils.BASE_UUID;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GenericLevelAndroidTest {
@Test
public void test_constructor_00001() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = 0x01;
data[ 1] = 0x02;
data[ 2] = 0x03;
data[ 3] = 0x04;
data[ 4] = 0x05;
data[ 5] = 0x06;
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
assertEquals(BLEUtils.createUInt48(data, 0), result.getGlobalTradeItemNumber());
}
@Test
public void test_constructor_00002() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912343L;
data[ 1] = (byte) (12345678912343L >> 8);
data[ 2] = (byte) (12345678912343L >> 16);
data[ 3] = (byte) (12345678912343L >> 24);
data[ 4] = (byte) (12345678912343L >> 32);
data[ 5] = (byte) (12345678912343L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
assertEquals(BLEUtils.createUInt48(data, 0), result.getGlobalTradeItemNumber());
assertTrue(result.isValid());
}
@Test
public void test_constructor_00003() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912344L;
data[ 1] = (byte) (12345678912344L >> 8);
data[ 2] = (byte) (12345678912344L >> 16);
data[ 3] = (byte) (12345678912344L >> 24);
data[ 4] = (byte) (12345678912344L >> 32);
data[ 5] = (byte) (12345678912344L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
assertEquals(BLEUtils.createUInt48(data, 0), result.getGlobalTradeItemNumber());
assertFalse(result.isValid());
}
@Test
public void test_constructor_00101() {
long globalTradeItemNumber = 1;
GlobalTradeItemNumberAndroid result = new GlobalTradeItemNumberAndroid(globalTradeItemNumber);
assertEquals(globalTradeItemNumber, result.getGlobalTradeItemNumber());
}
@Test
public void test_constructor_00102() {
long globalTradeItemNumber = 12345678912343L;
GlobalTradeItemNumberAndroid result = new GlobalTradeItemNumberAndroid(globalTradeItemNumber);
assertEquals(globalTradeItemNumber, result.getGlobalTradeItemNumber());
assertTrue(result.isValid());
}
@Test
public void test_constructor_00103() {
long globalTradeItemNumber = 12345678912344L;
GlobalTradeItemNumberAndroid result = new GlobalTradeItemNumberAndroid(globalTradeItemNumber);
assertEquals(globalTradeItemNumber, result.getGlobalTradeItemNumber());
assertFalse(result.isValid());
}
@Test
public void test_parcelable_00001() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = 0x01;
data[ 1] = 0x02;
data[ 2] = 0x03;
data[ 3] = 0x04;
data[ 4] = 0x05;
data[ 5] = 0x06;
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
Parcel parcel = Parcel.obtain();
result1.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
GlobalTradeItemNumberAndroid result2 = GlobalTradeItemNumberAndroid.CREATOR.createFromParcel(parcel);
assertEquals(result2.getGlobalTradeItemNumber(), result1.getGlobalTradeItemNumber());
}
@Test
public void test_parcelable_00002() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912343L;
data[ 1] = (byte) (12345678912343L >> 8);
data[ 2] = (byte) (12345678912343L >> 16);
data[ 3] = (byte) (12345678912343L >> 24);
data[ 4] = (byte) (12345678912343L >> 32);
data[ 5] = (byte) (12345678912343L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
Parcel parcel = Parcel.obtain();
result1.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
GlobalTradeItemNumberAndroid result2 = GlobalTradeItemNumberAndroid.CREATOR.createFromParcel(parcel);
assertEquals(result2.getGlobalTradeItemNumber(), result1.getGlobalTradeItemNumber());
}
@Test
public void test_parcelable_00003() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912344L;
data[ 1] = (byte) (12345678912344L >> 8);
data[ 2] = (byte) (12345678912344L >> 16);
data[ 3] = (byte) (12345678912344L >> 24);
data[ 4] = (byte) (12345678912344L >> 32);
data[ 5] = (byte) (12345678912344L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
Parcel parcel = Parcel.obtain();
result1.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
GlobalTradeItemNumberAndroid result2 = GlobalTradeItemNumberAndroid.CREATOR.createFromParcel(parcel);
assertEquals(result2.getGlobalTradeItemNumber(), result1.getGlobalTradeItemNumber());
}
@Test
public void test_parcelable_00101() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = 0x01;
data[ 1] = 0x02;
data[ 2] = 0x03;
data[ 3] = 0x04;
data[ 4] = 0x05;
data[ 5] = 0x06;
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
assertArrayEquals(data, result1.getBytes());
}
@Test
public void test_parcelable_00102() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912343L;
data[ 1] = (byte) (12345678912343L >> 8);
data[ 2] = (byte) (12345678912343L >> 16);
data[ 3] = (byte) (12345678912343L >> 24);
data[ 4] = (byte) (12345678912343L >> 32);
data[ 5] = (byte) (12345678912343L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
assertArrayEquals(data, result1.getBytes());
}
@Test
public void test_parcelable_00103() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912344L;
data[ 1] = (byte) (12345678912344L >> 8);
data[ 2] = (byte) (12345678912344L >> 16);
data[ 3] = (byte) (12345678912344L >> 24);
data[ 4] = (byte) (12345678912344L >> 32);
data[ 5] = (byte) (12345678912344L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
assertArrayEquals(data, result1.getBytes());
}
@Test
public void test_parcelable_00201() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = 0x01;
data[ 1] = 0x02;
data[ 2] = 0x03;
data[ 3] = 0x04;
data[ 4] = 0x05;
data[ 5] = 0x06;
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
GlobalTradeItemNumberAndroid result2 = GlobalTradeItemNumberAndroid.CREATOR.createFromByteArray(data);
assertArrayEquals(result1.getBytes(), result2.getBytes());
}
@Test
public void test_parcelable_00202() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912343L;
data[ 1] = (byte) (12345678912343L >> 8);
data[ 2] = (byte) (12345678912343L >> 16);
data[ 3] = (byte) (12345678912343L >> 24);
data[ 4] = (byte) (12345678912343L >> 32);
data[ 5] = (byte) (12345678912343L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
GlobalTradeItemNumberAndroid result2 = GlobalTradeItemNumberAndroid.CREATOR.createFromByteArray(data);
assertArrayEquals(result1.getBytes(), result2.getBytes());
}
@Test
public void test_parcelable_00203() {
//@formatter:off
byte[] data = new byte[6];
data[ 0] = (byte) 12345678912344L;
data[ 1] = (byte) (12345678912344L >> 8);
data[ 2] = (byte) (12345678912344L >> 16);
data[ 3] = (byte) (12345678912344L >> 24);
data[ 4] = (byte) (12345678912344L >> 32);
data[ 5] = (byte) (12345678912344L >> 40);
//@formatter:on
BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(BASE_UUID, 0, 0);
bluetoothGattCharacteristic.setValue(data);
GlobalTradeItemNumberAndroid result1 = new GlobalTradeItemNumberAndroid(bluetoothGattCharacteristic);
GlobalTradeItemNumberAndroid result2 = GlobalTradeItemNumberAndroid.CREATOR.createFromByteArray(data);
assertArrayEquals(result1.getBytes(), result2.getBytes());
}
}
|
9234d46aa1b99d80bfd2b5d3f3132efff9b3852f | 1,053 | java | Java | ExtractedJars/RT_News_com.rt.mobile.english/javafiles/android/support/v7/app/MediaRouteControllerDialog$1.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 3 | 2019-05-01T09:22:08.000Z | 2019-07-06T22:21:59.000Z | ExtractedJars/RT_News_com.rt.mobile.english/javafiles/android/support/v7/app/MediaRouteControllerDialog$1.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | null | null | null | ExtractedJars/RT_News_com.rt.mobile.english/javafiles/android/support/v7/app/MediaRouteControllerDialog$1.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 1 | 2020-11-26T12:22:02.000Z | 2020-11-26T12:22:02.000Z | 27.710526 | 107 | 0.642925 | 997,072 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v7.app;
// Referenced classes of package android.support.v7.app:
// MediaRouteControllerDialog
class MediaRouteControllerDialog$1
implements Runnable
{
public void run()
{
startGroupListFadeInAnimation();
// 0 0:aload_0
// 1 1:getfield #14 <Field MediaRouteControllerDialog this$0>
// 2 4:invokevirtual #22 <Method void MediaRouteControllerDialog.startGroupListFadeInAnimation()>
// 3 7:return
}
final MediaRouteControllerDialog this$0;
MediaRouteControllerDialog$1()
{
this$0 = MediaRouteControllerDialog.this;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #14 <Field MediaRouteControllerDialog this$0>
super();
// 3 5:aload_0
// 4 6:invokespecial #17 <Method void Object()>
// 5 9:return
}
}
|
9234d656967b55315ac0637943af08726271d76a | 1,085 | java | Java | src/main/java/com/qut/routeOptimizerApplication/service/opta/common/domain/PersistableIdComparator.java | pskpretty/routeOptimizerApplication | b061e5376d55c64553e4bebe3f0fe21464d711cb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/qut/routeOptimizerApplication/service/opta/common/domain/PersistableIdComparator.java | pskpretty/routeOptimizerApplication | b061e5376d55c64553e4bebe3f0fe21464d711cb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/qut/routeOptimizerApplication/service/opta/common/domain/PersistableIdComparator.java | pskpretty/routeOptimizerApplication | b061e5376d55c64553e4bebe3f0fe21464d711cb | [
"Apache-2.0"
] | 1 | 2019-02-21T09:48:43.000Z | 2019-02-21T09:48:43.000Z | 33.90625 | 95 | 0.754839 | 997,073 | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qut.routeOptimizerApplication.service.opta.common.domain;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.lang3.builder.CompareToBuilder;
public class PersistableIdComparator implements Comparator<AbstractPersistable>, Serializable {
@Override
public int compare(AbstractPersistable a, AbstractPersistable b) {
return new CompareToBuilder().append(a.getId(), b.getId()).toComparison();
}
}
|
9234d71ed5e3a411ee3c80b967f5da40a0b9aa0a | 590 | java | Java | platforms/android/app/src/main/java/com/xzl/jicu/extend/WXDictionaryModule.java | SimonOsaka/way-app | d97b817bc0ffa1a018f457e42bb0a5faaefa065a | [
"MIT"
] | null | null | null | platforms/android/app/src/main/java/com/xzl/jicu/extend/WXDictionaryModule.java | SimonOsaka/way-app | d97b817bc0ffa1a018f457e42bb0a5faaefa065a | [
"MIT"
] | 3 | 2021-03-11T06:56:50.000Z | 2022-02-19T06:58:19.000Z | platforms/android/app/src/main/java/com/xzl/jicu/extend/WXDictionaryModule.java | SimonOsaka/way-app | d97b817bc0ffa1a018f457e42bb0a5faaefa065a | [
"MIT"
] | null | null | null | 25.652174 | 64 | 0.716949 | 997,074 | package com.xzl.jicu.extend;
import android.util.Log;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
import com.xzl.jicu.util.Constants;
import com.xzl.jicu.util.SpUtils;
public class WXDictionaryModule extends WXModule {
private static final String TAG = "WXDictionaryModule";
@JSMethod(uiThread = false)
public Object getDict(String key) {
String value = SpUtils.get(key, Constants.STRING_EMPTY);
Log.d(TAG, "字典key:" + key + ",value:" + value);
return value;
}
}
|
9234d7968dcb2e6088a5d3594c57e1e8ad126399 | 3,330 | java | Java | src/main/java/gloridifice/watersource/common/recipe/type/SoulWaterBottleRecipe.java | Lyaiya/WaterSource | 447f1f2ea2d332b8d1c97b132b61fc1eb990918f | [
"BSD-3-Clause"
] | 6 | 2020-10-18T11:24:53.000Z | 2022-03-22T10:35:31.000Z | src/main/java/gloridifice/watersource/common/recipe/type/SoulWaterBottleRecipe.java | Lyaiya/WaterSource | 447f1f2ea2d332b8d1c97b132b61fc1eb990918f | [
"BSD-3-Clause"
] | 51 | 2020-06-30T13:27:01.000Z | 2022-03-22T12:19:33.000Z | src/main/java/gloridifice/watersource/common/recipe/type/SoulWaterBottleRecipe.java | Lyaiya/WaterSource | 447f1f2ea2d332b8d1c97b132b61fc1eb990918f | [
"BSD-3-Clause"
] | 9 | 2020-05-24T02:39:57.000Z | 2021-09-19T23:49:04.000Z | 38.275862 | 197 | 0.686486 | 997,075 | package gloridifice.watersource.common.recipe.type;
import gloridifice.watersource.WaterSource;
import gloridifice.watersource.common.item.StrainerBlockItem;
import gloridifice.watersource.registry.ItemRegistry;
import gloridifice.watersource.registry.RecipeSerializersRegistry;
import net.minecraft.block.Block;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.item.crafting.SpecialRecipe;
import net.minecraft.potion.PotionUtils;
import net.minecraft.potion.Potions;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.ITag;
import net.minecraft.tags.ItemTags;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.List;
public class SoulWaterBottleRecipe extends SpecialRecipe {
public SoulWaterBottleRecipe(ResourceLocation idIn) {
super(idIn);
}
@Override
public boolean matches(CraftingInventory inv, World worldIn) {
ITag<Block> tag = BlockTags.getCollection().get(new ResourceLocation(WaterSource.MODID, "soul_strainers"));
List<ItemStack> list = new ArrayList<>();
boolean hasStrainer = false, hasPotion = false;
for (int j = 0; j < inv.getSizeInventory(); ++j) {
ItemStack itemstack = inv.getStackInSlot(j);
if (!itemstack.isEmpty()) {
if (tag != null && tag.contains(Block.getBlockFromItem(itemstack.getItem()))) {
list.add(itemstack);
hasStrainer = true;
}
if (itemstack.isItemEqual(new ItemStack(Items.POTION)) && ItemStack.areItemStackTagsEqual(PotionUtils.addPotionToItemStack(new ItemStack(Items.POTION), Potions.WATER), itemstack)) {
list.add(itemstack);
hasPotion = true;
}
}
}
return hasPotion && hasStrainer && list.size() == 2;
}
@Override
public ItemStack getCraftingResult(CraftingInventory inv) {
return new ItemStack(ItemRegistry.itemSoulWaterBottle);
}
@Override
public NonNullList<ItemStack> getRemainingItems(CraftingInventory inv) {
NonNullList<ItemStack> nonnulllist = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY);
for (int j = 0; j < inv.getSizeInventory(); ++j) {
ItemStack itemstack = inv.getStackInSlot(j);
ITag<Item> tag = ItemTags.getCollection().get(new ResourceLocation(WaterSource.MODID, "soul_strainers"));
if (!itemstack.isEmpty() && tag != null && tag.contains(itemstack.getItem())) {
ItemStack i = StrainerBlockItem.damageItem(itemstack.copy(), 1);
nonnulllist.set(j, i);
}
}
return nonnulllist;
}
@Override
public boolean canFit(int width, int height) {
return false;
}
@Override
public IRecipeSerializer<?> getSerializer() {
return RecipeSerializersRegistry.CRAFTING_SOUL_WATER_BOTTLE.get();
}
@Override
public ItemStack getRecipeOutput() {
return new ItemStack(ItemRegistry.itemSoulWaterBottle);
}
}
|
9234d7a56e08a4037f271b625c1b8faac295032f | 2,989 | java | Java | core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/OneToOneMapsIdJoinColumnTest.java | deveshub/high-performance-java-persistence | 4e259ebc7150dc639fb8c7f35f7c3ecacf6c49d3 | [
"Apache-2.0"
] | 963 | 2015-10-16T04:36:10.000Z | 2022-03-27T22:24:56.000Z | core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/OneToOneMapsIdJoinColumnTest.java | deveshub/high-performance-java-persistence | 4e259ebc7150dc639fb8c7f35f7c3ecacf6c49d3 | [
"Apache-2.0"
] | 58 | 2015-10-15T12:48:53.000Z | 2022-02-16T00:55:15.000Z | core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/OneToOneMapsIdJoinColumnTest.java | deveshub/high-performance-java-persistence | 4e259ebc7150dc639fb8c7f35f7c3ecacf6c49d3 | [
"Apache-2.0"
] | 432 | 2015-10-15T06:01:37.000Z | 2022-03-27T22:24:57.000Z | 21.977941 | 86 | 0.542322 | 997,076 | package com.vladmihalcea.book.hpjp.hibernate.association;
import com.vladmihalcea.book.hpjp.util.AbstractTest;
import com.vladmihalcea.book.hpjp.util.providers.Database;
import org.junit.Test;
import javax.persistence.*;
import java.util.Date;
import static org.junit.Assert.assertNotNull;
/**
* @author Vlad Mihalcea
*/
public class OneToOneMapsIdJoinColumnTest extends AbstractTest {
@Override
protected Class<?>[] entities() {
return new Class<?>[] {
Post.class,
PostDetails.class,
};
}
@Override
protected Database database() {
return Database.MYSQL;
}
@Test
public void testLifecycle() {
doInJPA(entityManager -> {
Post post = new Post("First post");
entityManager.persist(post);
});
doInJPA(entityManager -> {
Post post = entityManager.find(Post.class, 1L);
PostDetails details = new PostDetails("John Doe");
details.setPost(post);
entityManager.persist(details);
});
doInJPA(entityManager -> {
Post post = entityManager.find(Post.class, 1L);
PostDetails details = entityManager.find(PostDetails.class, post.getId());
assertNotNull(details);
entityManager.flush();
details.setPost(null);
});
}
@Entity(name = "Post")
@Table(name = "post")
public static class Post {
@Id
@GeneratedValue
private Long id;
private String title;
public Post() {}
public Post(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@Entity(name = "PostDetails")
@Table(name = "post_details")
public static class PostDetails {
@Id
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id")
private Post post;
public PostDetails() {}
public PostDetails(String createdBy) {
createdOn = new Date();
this.createdBy = createdBy;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreatedOn() {
return createdOn;
}
public String getCreatedBy() {
return createdBy;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
}
}
|
9234d805775211c8135a7d35767d2ac1c39d5cca | 5,185 | java | Java | Source/Plugins/Core/com.equella.core/src/com/tle/web/workflow/tasks/ModerationService.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 14 | 2019-10-09T23:59:32.000Z | 2022-03-01T08:34:56.000Z | Source/Plugins/Core/com.equella.core/src/com/tle/web/workflow/tasks/ModerationService.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 1,549 | 2019-08-16T01:07:16.000Z | 2022-03-31T23:57:34.000Z | Source/Plugins/Core/com.equella.core/src/com/tle/web/workflow/tasks/ModerationService.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 24 | 2019-09-05T00:09:35.000Z | 2021-10-19T05:10:39.000Z | 37.846715 | 98 | 0.762777 | 997,077 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.workflow.tasks;
import com.google.inject.Provider;
import com.tle.beans.item.ItemTaskId;
import com.tle.beans.workflow.WorkflowStatus;
import com.tle.beans.workflow.WorkflowStep;
import com.tle.core.guice.Bind;
import com.tle.core.item.service.ItemService;
import com.tle.core.item.standard.operations.workflow.StatusOperation;
import com.tle.core.plugins.PluginService;
import com.tle.core.plugins.PluginTracker;
import com.tle.core.workflow.service.WorkflowService;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.equella.annotation.PluginResourceHandler;
import com.tle.web.sections.generic.AbstractSectionFilter;
import com.tle.web.sections.registry.TreeRegistry;
import javax.inject.Inject;
import javax.inject.Singleton;
@SuppressWarnings("nls")
@Bind
@Singleton
public class ModerationService extends AbstractSectionFilter {
static {
PluginResourceHandler.init(ModerationService.class);
}
public static final String VIEW_METADATA = "metadata";
public static final String VIEW_SUMMARY = "summary";
public static final String VIEW_PROGRESS = "progress";
private static final String TREE_NAME = "$CURRENTTASK$"; // $NON-NLS-1$
@Inject private TreeRegistry treeRegistry;
@Inject private ItemService itemService;
@Inject private WorkflowService workflowService;
@Inject private Provider<StatusOperation> statusOpFactpry;
private PluginTracker<ModerationView> tracker;
@Override
protected SectionTree getFilterTree() {
return treeRegistry.getTreeForPath(TREE_NAME);
}
public TaskListState refreshCurrentTask(SectionInfo info, TaskListState state) {
StatusOperation statusOp = statusOpFactpry.get();
ItemTaskId taskId = state.getItemTaskId();
itemService.operation(taskId, statusOp);
WorkflowStatus status = statusOp.getStatus();
state.setWorkflowStatus(
status, status.getStepForId(taskId.getTaskId()), workflowService.getMessageCount(taskId));
return state;
}
public void moderate(
SectionInfo info, String viewType, ItemTaskId taskId, int index, int listSize) {
StatusOperation statusOp = statusOpFactpry.get();
itemService.operation(taskId, statusOp);
WorkflowStatus status = statusOp.getStatus();
TaskListState state = new TaskListState(taskId, index, listSize);
WorkflowStep currentStep = status.getStepForId(taskId.getTaskId());
if (currentStep == null) {
throw new NotModeratingStepException("Moderating task no longer exists: " + taskId);
}
state.setWorkflowStatus(status, currentStep, workflowService.getMessageCount(taskId));
forwardToView(info, state, viewType);
}
private void forwardToView(SectionInfo info, TaskListState state, String viewer) {
ModerationView modViewer = tracker.getBeanByExtension(tracker.getExtension(viewer));
SectionInfo forward = modViewer.getViewForward(info, state.getItemTaskId(), viewer);
CurrentTaskSection taskSection = forward.lookupSection(CurrentTaskSection.class);
taskSection.setupState(forward, state);
info.forwardAsBookmark(forward);
}
@Inject
public void setPluginService(PluginService pluginService) {
tracker =
new PluginTracker<ModerationView>(
pluginService, "com.tle.web.workflow", "moderationView", "id")
.setBeanKey("bean");
}
public void setEditing(SectionInfo info, boolean editing) {
TaskListState state = getCurrentTaskState(info);
if (state != null) {
state.setEditing(editing);
}
}
public boolean isModerating(SectionInfo info) {
CurrentTaskSection currentTask = info.lookupSection(CurrentTaskSection.class);
return currentTask != null && currentTask.getCurrentState(info) != null;
}
private TaskListState getCurrentTaskState(SectionInfo info) {
CurrentTaskSection taskSection = info.lookupSection(CurrentTaskSection.class);
if (taskSection == null) {
return null;
}
return taskSection.getCurrentState(info);
}
public void viewSummary(SectionInfo info) {
forwardToView(info, getCurrentTaskState(info), VIEW_SUMMARY);
}
public void viewMetadata(SectionInfo info) {
forwardToView(info, getCurrentTaskState(info), VIEW_METADATA);
}
public ItemTaskId getCurrentTaskId(SectionInfo info) {
return getCurrentTaskState(info).getItemTaskId();
}
}
|
9234d83ca56a05353c93bc6fa179a7ab8006c68e | 16,209 | java | Java | src/slogo_team12/Display.java | SummerSmith/slogo | bf784362bf54d760128b51865e170a1fd530e11f | [
"MIT"
] | null | null | null | src/slogo_team12/Display.java | SummerSmith/slogo | bf784362bf54d760128b51865e170a1fd530e11f | [
"MIT"
] | null | null | null | src/slogo_team12/Display.java | SummerSmith/slogo | bf784362bf54d760128b51865e170a1fd530e11f | [
"MIT"
] | null | null | null | 34.858065 | 139 | 0.720402 | 997,078 | package slogo_team12;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;
import javafx.util.Duration;
import nodes.Node;
import parser.BackEndManager;
import parser.ConstructNodes;
import parser.ProcessString;
import parser.TurtleManager;
import turtle.CreateTurtle;
import turtle.Turtle;
import user_data.UserCommands;
import user_data.UserController;
import user_data.UserHistory;
import user_data.UserVariables;
import windows.CommandWindow;
import windows.TurtleWindow;
import windows.UserCommandsWindow;
import windows.UserHistoryWindow;
import windows.UserVariablesWindow;
import windows.Windows;
import point.Point;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import gui_elements.buttons.ClearButton;
import gui_elements.buttons.RunButton;
import gui_elements.buttons.UndoButton;
import gui_elements.buttons.EditVariablesButton;
import gui_elements.buttons.RedoButton;
import gui_elements.buttons.UserAPIButton;
import gui_elements.combo_boxes.BackgroundColorComboBox;
import gui_elements.combo_boxes.ComboBoxes;
import gui_elements.combo_boxes.LanguageComboBox;
import gui_elements.combo_boxes.PenColorComboBox;
import gui_elements.combo_boxes.SavedCommandFilesComboBox;
import gui_elements.combo_boxes.TurtleImageComboBox;
import gui_elements.labels.BackgroundColorLabel;
import gui_elements.labels.CommandWindowLabel;
import gui_elements.labels.ErrorLabel;
import gui_elements.labels.LanguageLabel;
import gui_elements.labels.SavedCommandFilesLabel;
import gui_elements.labels.TurtleDisplayLabel;
import gui_elements.labels.user_api_labels.UserAPILabel;
import gui_elements.labels.user_windows_labels.UserCommandsLabel;
import gui_elements.labels.user_windows_labels.UserHistoryLabel;
import gui_elements.labels.user_windows_labels.UserVariablesLabel;
import image_classes.ImageClass;
import image_classes.SLogoImageClass;
import image_classes.TurtleImageClass;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Line;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* This class displays the main GUI for "SLogo." Here, the user can enter commands into the
* command window, save methods and commands, define variables, choose GUI settings from
* lists of selections, and get access to API methods. The "Display" class contains different
* windows to manage the GUI, including a WindowElements interface and specific Window
* classes that implement this interface (TurtleWindow, CommandWindow, UserVariablesWindow,
* UserCommandsWindow, and UserHistoryWindow). This class has a main method, so this is the
* program to run.
*
* @author Aditya Sridhar
*/
public class Display extends Application {
private final Paint BACKGROUND = Color.BLACK;
private final String PROPERTY_FILENAME = "data/display.properties";
private final String TITLE_PROPERTY = "title";
private final String WIDTH_PROPERTY = "width";
private final String HEIGHT_PROPERTY = "height";
// private final String IMAGE_PROPERTY = "image";
// private final String IMAGE_WIDTH_PROPERTY = "imgWidth";
// private final String IMAGE_HEIGHT_PROPERTY = "imgHeight";
// private final String IMAGE_XLOC_PROPERTY = "imgXLoc";
// private final String IMAGE_YLOC_PROPERTY = "imgYLoc";
private static String myLanguage = "English";
private static String errorString = "";
private String title;
private final int FRAMES_PER_SECOND = 2;
private final int INITIAL_TIME_DELAY = 1000 / FRAMES_PER_SECOND;
private int screen_width, screen_height;
// private int image_width, image_height, image_xloc, image_yloc;
// private int time_delay = INITIAL_TIME_DELAY;
private static boolean runButtonPressed;
// private boolean setIntroLabels = true;
private Stage stage;
private Properties menu_properties;
private InputStream input;
private CommandWindow command_window;
private static TurtleWindow turtle_window;
private SavedCommandFilesLabel pen_color_label;
private BackgroundColorLabel background_color_label;
private LanguageLabel language_label;
private TurtleDisplayLabel turtle_display_label;
private CommandWindowLabel command_window_label;
private UserVariablesLabel user_variables_label;
private UserCommandsLabel user_commands_label;
private UserHistoryLabel user_history_label;
private UserAPILabel user_api_label;
private static ErrorLabel error_label;
private ClearButton clear_button;
private RunButton run_button;
private UserAPIButton user_api_button;
private EditVariablesButton edit_variables_button;
private UndoButton undo_button;
private RedoButton redo_button;
private BackgroundColorComboBox background_color_combobox;
private SavedCommandFilesComboBox saved_command_files_combobox;
private LanguageComboBox language_combobox;
private ImageClass slogo_image_object;
private Timeline animation;
// Additional setup for the display
private static Scene myScene;
private static Group root;
/**
* Initializes the stage for the display.
*/
@Override
public void start(Stage stage) {
this.stage = stage;
initialize();
}
/**
* Sets the scene and initializes the screen properties.
*/
private void initialize() {
root = new Group();
// initializeStructures();
getProperties();
setScene();
setStage();
setImages();
setGUIComponents();
setRunButtonPressed(false);
new UserController(command_window);
new CreateTurtle(root);
startAnimation();
}
private void setScene() {
myScene = new Scene(root, screen_width, screen_height, BACKGROUND);
}
private void startAnimation(){
KeyFrame frame = new KeyFrame(Duration.millis(INITIAL_TIME_DELAY),
e -> step());
Timeline animation = new Timeline();
animation.setCycleCount(Timeline.INDEFINITE);
animation.getKeyFrames().add(frame);
this.animation = animation;
animation.play();
}
private void step(){
if(runButtonPressed) {
if(root.getChildren().contains(error_label.getLabel())) {
root.getChildren().remove(error_label.getLabel());
setErrorString("");
error_label.getLabel().setText(errorString);
}
String text = CommandWindow.getText();
try {
BackEndManager back_end_manager = new BackEndManager(text, myLanguage);
back_end_manager.parse();
for(Turtle turtle : TurtleManager.getActiveTurtles()) {
// System.out.println(turtle.getNextPoints().size() + "......................");
// if(turtle.getNextPoints().size() != 0) {
moveImageView(turtle);
drawLine(turtle);
// }
}
checkErrorLabel(text);
CommandWindow.clearWindow();
if(errorString.length() != 0) {
//System.out.println("front end catch errors! " + errorString);
if(root.getChildren().contains(error_label)) {
root.getChildren().remove(error_label.getLabel());
}
else {
error_label.getLabel().setText(errorString);
root.getChildren().remove(error_label.getLabel());
root.getChildren().add(error_label.getLabel());
}
}
else {
//System.out.println("front end uncatch errors! ");
root.getChildren().remove(error_label.getLabel());
}
runButtonPressed = false;
} catch (Exception e) {
System.err.println("After button was pressed, the nodes were not able to be constructed.");
e.printStackTrace();
}
}
}
private void checkErrorLabel(String text) {
if(!errorString.equals("")) {
error_label.getLabel().setText(errorString);
root.getChildren().add(error_label.getLabel());
}
else {
updateUserHistoryWindow(text);
}
}
private void updateUserHistoryWindow(String text) {
UserController.updateUserHistoryWindow(text);
}
private void drawLine(Turtle turtle) {
List<Point> nextPoints = turtle.getNextPoints();
ImageView imageView = turtle.getImageView();
List<Line> lines = new ArrayList<Line>();
for(int i = 0; i < nextPoints.size() - 1; i++) {
Point curr_point = nextPoints.get(i);
Point next_point = nextPoints.get(i + 1);
double x_offset = TurtleWindow.getInitialTurtleX() + imageView.getFitWidth() / 2;
double y_offset = TurtleWindow.getInitialTurtleY() + imageView.getFitHeight() / 2;
Line line = new Line(curr_point.getX() + x_offset,
curr_point.getY() + y_offset,
next_point.getX() + x_offset,
next_point.getY() + y_offset);
line.setStyle(turtle.getPenColor());
line.setStrokeWidth(turtle.getPenThickness());
if(turtle.getPenDown()) {
TurtleWindow.getPaneRoot().getChildren().add(line);
}
lines.add(line);
}
if(lines.size() != 0) {
addValuesToTurtlePropertiesHistory(turtle);
addLinesToLineHistory(lines);
}
}
private void addLinesToLineHistory(List<Line> lines) {
HashMap<Integer, ArrayList<Line>> line_history = UserHistory.getLineHistory();
UserHistory.setLHPointer(UserHistory.getLHPointer() + 1);
line_history.put(UserHistory.getLHPointer(), (ArrayList<Line>) lines);
}
private void addValuesToTurtlePropertiesHistory(Turtle turtle) {
HashMap<Integer, HashMap<Turtle, Double[]>> turtle_properties_history = UserHistory.getTurtlePropertiesHistory();
double initialX = (double) TurtleWindow.getInitialTurtleX();
double initialY = (double) TurtleWindow.getInitialTurtleY();
if(UserHistory.getTPHPointer() == -1) {
UserHistory.setTPHPointer(UserHistory.getTPHPointer() + 1);
HashMap<Turtle, Double[]> initial_turtle_properties_map = new HashMap<Turtle, Double[]>();
initial_turtle_properties_map.put(turtle, new Double[]{initialX, initialY, 0.0});
turtle_properties_history.put(0, initial_turtle_properties_map);
}
UserHistory.setTPHPointer(UserHistory.getTPHPointer() + 1);
HashMap<Turtle, Double[]> turtle_properties_map = new HashMap<Turtle, Double[]>();
turtle_properties_map.put(turtle, new Double[]{turtle.getXLocation() + initialX, turtle.getYLocation() + initialY, turtle.getHeading()});
turtle_properties_history.put(UserHistory.getTPHPointer(), turtle_properties_map);
}
public void moveImageView(Turtle turtle) {
ImageView imageView = turtle.getImageView();
imageView.setLayoutX(TurtleWindow.getInitialTurtleX() + turtle.getXLocation());
imageView.setLayoutY(TurtleWindow.getInitialTurtleY() + turtle.getYLocation());
imageView.setRotate(turtle.getHeading());
Group paneRoot = TurtleWindow.getPaneRoot();
if(turtle.getTurtleIsShowing() && !paneRoot.getChildren().contains(imageView)) {
TurtleWindow.getPaneRoot().getChildren().set(0, imageView);
}
else if(!turtle.getTurtleIsShowing() && paneRoot.getChildren().contains(imageView)) {
TurtleWindow.getPaneRoot().getChildren().set(0, new ImageView());
}
}
/**
* Reads in properties from a property file and gets the
* screen properties.
*/
private void getProperties() {
menu_properties = new Properties();
input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
menu_properties.load(input);
title = menu_properties.getProperty(TITLE_PROPERTY);
screen_width = Integer.parseInt(menu_properties.getProperty(WIDTH_PROPERTY));
screen_height = Integer.parseInt(menu_properties.getProperty(HEIGHT_PROPERTY));
} catch (IOException ex) {
System.err.println("Display file input does not exist!");
} catch (Exception ey) {
System.err.println("The properties for the display could not be retrieved completely.");
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.err.println("Display file input cannot close!");
}
}
}
}
/**
* Calls methods to add the individual
* GUI components to the screen.
*/
private void setGUIComponents() {
setWindows();
setLabels();
setButtons();
setComboBoxes();
}
/*
* Sets up screen windows.
*/
private void setWindows() {
command_window = new CommandWindow(root);
turtle_window = new TurtleWindow(root);
}
/*
* Sets up screen labels.
*/
private void setLabels() {
pen_color_label = new SavedCommandFilesLabel(new Label(), root);
background_color_label = new BackgroundColorLabel(new Label(), root);
language_label = new LanguageLabel(new Label(), root);
turtle_display_label = new TurtleDisplayLabel(new Label(), root);
command_window_label = new CommandWindowLabel(new Label(), root);
user_variables_label = new UserVariablesLabel(new Label(), root);
user_commands_label = new UserCommandsLabel(new Label(), root);
user_history_label = new UserHistoryLabel(new Label(), root);
user_api_label = new UserAPILabel(new Label(), root);
error_label = new ErrorLabel(new Label(), root);
}
/*
* Sets up screen buttons.
*/
private void setButtons() {
clear_button = new ClearButton(new Button(), root);
run_button = new RunButton(new Button(), root);
edit_variables_button = new EditVariablesButton(new Button(), root);
user_api_button = new UserAPIButton(new Button(), root);
undo_button = new UndoButton(new Button(), root);
redo_button = new RedoButton(new Button(), root);
}
/*
* Sets up screen comboBoxes.
*/
private void setComboBoxes() {
background_color_combobox = new BackgroundColorComboBox(new ComboBox(), root);
language_combobox = new LanguageComboBox(new ComboBox(), root);
saved_command_files_combobox = new SavedCommandFilesComboBox(new ComboBox(), root);
}
/**
* Sets the stage for the display.
*/
private void setStage() {
stage.setScene(myScene);
stage.setTitle(title);
stage.show();
stage.setResizable(false);
}
/**
* Sets the images for the display.
*/
private void setImages() {
new SLogoImageClass(root);
}
/**
* Returns the width of the display screen.
*/
public int getScreenWidth() {
return screen_width;
}
/**
* Returns the height of the display screen.
*/
public int getScreenHeight() {
return screen_height;
}
public static void setRunButtonPressed(boolean buttonPressedState) {
runButtonPressed = buttonPressedState;
}
public static void setLanguage(String language) {
myLanguage = language;
}
public static Group getRoot() {
return root;
}
public static void setErrorString(String string) {
errorString = string;
}
public static Label getErrorLabel() {
return error_label.getLabel();
}
public static Scene getScene() {
return myScene;
}
/**
* Starts the program.
*/
public static void main(String[] args) {
launch(args);
}
public static TurtleWindow getTurtleWindow() {
return turtle_window;
}
}
|
9234d8474fc9ef8c17e6e667bcb3e185e64f060a | 1,469 | java | Java | json-smart/src/test/java/be/atbash/json/testclasses/Price.java | atbashEE/atbash-json-smart | c2b9ce63dfc31891d23e3f72fe07c32173a8e021 | [
"Apache-2.0"
] | null | null | null | json-smart/src/test/java/be/atbash/json/testclasses/Price.java | atbashEE/atbash-json-smart | c2b9ce63dfc31891d23e3f72fe07c32173a8e021 | [
"Apache-2.0"
] | 3 | 2018-05-10T16:40:04.000Z | 2019-01-09T07:02:17.000Z | json-smart/src/test/java/be/atbash/json/testclasses/Price.java | atbashEE/atbash-json-smart | c2b9ce63dfc31891d23e3f72fe07c32173a8e021 | [
"Apache-2.0"
] | null | null | null | 24.898305 | 75 | 0.676651 | 997,079 | /*
* Copyright 2017-2018 Rudy De Busscher (https://www.atbash.be)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package be.atbash.json.testclasses;
import be.atbash.json.JSONAware;
import be.atbash.json.parser.MappedBy;
/**
*
*/
@MappedBy(encoder = PriceJSONEncoder.class)
public class Price implements JSONAware {
private double value;
private Currency currency;
public Price() {
}
public Price(double value, Currency currency) {
this.value = value;
this.currency = currency;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
@Override
public String toJSONString() {
return String.format("\"%s%s\"", value, currency.toJSONString());
}
}
|
9234d85c2156836cdacbc02dbe628bac1ed49dbb | 2,323 | java | Java | src/main/java/org/ncgr/xgboost/TesterTrainer.java | sammyjava/pangenomics | 6720b4e6ceccfa79954d24a56fad47bd5fcd198a | [
"MIT"
] | null | null | null | src/main/java/org/ncgr/xgboost/TesterTrainer.java | sammyjava/pangenomics | 6720b4e6ceccfa79954d24a56fad47bd5fcd198a | [
"MIT"
] | null | null | null | src/main/java/org/ncgr/xgboost/TesterTrainer.java | sammyjava/pangenomics | 6720b4e6ceccfa79954d24a56fad47bd5fcd198a | [
"MIT"
] | null | null | null | 24.712766 | 127 | 0.619458 | 997,080 | package org.ncgr.xgboost;
import java.util.Map;
import java.util.HashMap;
import ml.dmlc.xgboost4j.java.Booster;
import ml.dmlc.xgboost4j.java.DMatrix;
import ml.dmlc.xgboost4j.java.XGBoost;
import ml.dmlc.xgboost4j.java.XGBoostError;
/**
* Test/train from a couple of SVM format files.
*
* @author Sam Hokin
*/
public class TesterTrainer {
public static void main(String[] args) throws XGBoostError {
DMatrix trainMat = new DMatrix("pathfrs.train.svm");
DMatrix testMat = new DMatrix("pathfrs.test.svm");
// JSON-ish parameters
Map<String,Object> params = new HashMap<String,Object>() {
{
put("eta", 1.0);
put("max_depth", 2);
put("objective", "binary:logistic");
put("eval_metric", "logloss");
}
};
// Specify a watch list to see model accuracy on data sets
Map<String,DMatrix> watches = new HashMap<String, DMatrix>() {
{
put("train", trainMat);
put("test", testMat);
}
};
int nround = 2;
Booster booster = XGBoost.train(trainMat, params, nround, watches, null, null);
// save a model
// booster.saveModel("model.bin");
// load a model
// Booster booster = XGBoost.loadModel("model.bin");
// predict
float[][] predicts = booster.predict(testMat);
// predict leaf
float[][] leafPredicts = booster.predictLeaf(testMat, 0);
// spit out the results
int TP = 0;
int FP = 0;
int TN = 0;
int FN = 0;
for (int i=0; i<predicts.length; i++) {
boolean isCase = testMat.getLabel()[i]>0.5;
for (int j=0; j<predicts[i].length; j++) {
double predict = predicts[i][j];
if (predict>0.5) {
// positive call
if (isCase) {
TP++;
} else {
FP++;
}
} else {
// negative call
if (isCase) {
FN++;
} else {
TN++;
}
}
}
}
// stats
int totCase = TP + FN;
int totCtrl = FP + TN;
int correct = TP + TN;
int total = totCase + totCtrl;
double accuracy = (double)correct / (double)total;
double TPR = (double)TP / (double)totCase;
double FPR = (double)FP / (double)totCtrl;
double MCC = ((double)(TP*TN) - (double)(FP*FN)) / Math.sqrt((double)(TP+FP)*(double)(TP+FN)*(double)(TN+FP)*(double)(TN+FN));
System.out.println("TP\tFP\tTN\tFN\tAcc\tTPR\tFPR\tMCC");
System.out.println(TP+"\t"+FP+"\t"+TN+"\t"+FN+"\t"+accuracy+"\t"+TPR+"\t"+FPR+"\t"+MCC);
}
}
|
9234d8fc6f2f7582bbf440de784ba8e349a56607 | 1,655 | java | Java | jNoRightTurns/norightturns/src/main/java/com/ken/norightturns/export/MinimizedSegment.java | kenkawakenkenke/no-right-turns | 01ddb0e803e3d09c1c755fe6ea9d880f3d5d6cfb | [
"MIT"
] | 1 | 2022-02-09T07:40:33.000Z | 2022-02-09T07:40:33.000Z | jNoRightTurns/norightturns/src/main/java/com/ken/norightturns/export/MinimizedSegment.java | kenkawakenkenke/no-right-turns | 01ddb0e803e3d09c1c755fe6ea9d880f3d5d6cfb | [
"MIT"
] | 2 | 2021-04-13T05:33:56.000Z | 2021-04-13T08:09:50.000Z | jNoRightTurns/norightturns/src/main/java/com/ken/norightturns/export/MinimizedSegment.java | kenkawakenkenke/no-right-turns | 01ddb0e803e3d09c1c755fe6ea9d880f3d5d6cfb | [
"MIT"
] | null | null | null | 31.826923 | 134 | 0.760725 | 997,081 | package com.ken.norightturns.export;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.ken.norightturns.export.GridMap.CellID;
import com.ken.norightturns.segment.Segment;
import com.ken.norightturns.segment.SegmentConnection;
import model.Coordinate;
public class MinimizedSegment implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8467996270884743307L;
// A cell where you can get corresponding details from.
public final CellID cellID;
public final double distance;
public final Collection<SegmentConnection> connections;
public MinimizedSegment(CellID cellID, double distance, Collection<SegmentConnection> connections) {
this.cellID = cellID;
this.distance = distance;
this.connections = connections;
}
public Map toJSONMap() {
Map<String, Object> map =new HashMap<>();
map.put("c", cellID.toString());
map.put("d", distance);
map.put("cs", connections.stream().map(con -> con.toJSONMap()).collect(ImmutableList.toImmutableList()));
return map;
}
public static List<MinimizedSegment> toMinimizedSegments(GridMap gridMap, Map<Long, Coordinate> coordForID, List<Segment> segments) {
return segments.stream()
.map(segment -> {
Coordinate headCoord = coordForID.get(segment.nodes[0]);
CellID cellID = gridMap.cellIDFor(headCoord);
return new MinimizedSegment(cellID, segment.distancesToEnd[0], segment.connections());
})
.collect(ImmutableList.toImmutableList());
}
}
|
9234dab28a441f37e75daae7f47196596c6e29a6 | 2,676 | java | Java | FuelClubWeb/src/br/com/fuelclub/entity/Tipo_Pagamento.java | lucasgrittem/AppsCwb | d082cc84ab4fcb71a0f9903bd8479b2747f8a95a | [
"Apache-2.0"
] | null | null | null | FuelClubWeb/src/br/com/fuelclub/entity/Tipo_Pagamento.java | lucasgrittem/AppsCwb | d082cc84ab4fcb71a0f9903bd8479b2747f8a95a | [
"Apache-2.0"
] | null | null | null | FuelClubWeb/src/br/com/fuelclub/entity/Tipo_Pagamento.java | lucasgrittem/AppsCwb | d082cc84ab4fcb71a0f9903bd8479b2747f8a95a | [
"Apache-2.0"
] | null | null | null | 28.774194 | 112 | 0.743274 | 997,082 | package br.com.fuelclub.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table (name = "Tipo_pagamento")
public class Tipo_Pagamento {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long tipo_pagamento_id;
@ManyToMany
private List<PostoCombustivel> postos;
private String tipo_pagamento_descricao;
public Long getTipo_pagamento_id() {
return tipo_pagamento_id;
}
public void setTipo_pagamento_id(Long tipo_pagamento_id) {
this.tipo_pagamento_id = tipo_pagamento_id;
}
public List<PostoCombustivel> getPostos() {
return postos;
}
public void setPostos(List<PostoCombustivel> postos) {
this.postos = postos;
}
public String getTipo_pagamento_descricao() {
return tipo_pagamento_descricao;
}
public void setTipo_pagamento_descricao(String tipo_pagamento_descricao) {
this.tipo_pagamento_descricao = tipo_pagamento_descricao;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((postos == null) ? 0 : postos.hashCode());
result = prime * result + ((tipo_pagamento_descricao == null) ? 0 : tipo_pagamento_descricao.hashCode());
result = prime * result + ((tipo_pagamento_id == null) ? 0 : tipo_pagamento_id.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;
Tipo_Pagamento other = (Tipo_Pagamento) obj;
if (postos == null) {
if (other.postos != null)
return false;
} else if (!postos.equals(other.postos))
return false;
if (tipo_pagamento_descricao == null) {
if (other.tipo_pagamento_descricao != null)
return false;
} else if (!tipo_pagamento_descricao.equals(other.tipo_pagamento_descricao))
return false;
if (tipo_pagamento_id == null) {
if (other.tipo_pagamento_id != null)
return false;
} else if (!tipo_pagamento_id.equals(other.tipo_pagamento_id))
return false;
return true;
}
@Override
public String toString() {
return "Tipo_Pagamento [tipo_pagamento_descricao=" + tipo_pagamento_descricao + "]";
}
public Tipo_Pagamento(Long tipo_pagamento_id, List<PostoCombustivel> postos, String tipo_pagamento_descricao) {
super();
this.tipo_pagamento_id = tipo_pagamento_id;
this.postos = postos;
this.tipo_pagamento_descricao = tipo_pagamento_descricao;
}
public Tipo_Pagamento() {
super();
// TODO Auto-generated constructor stub
}
}
|
9234dbdc1656dbfece89096dc3726067025bb33e | 922 | java | Java | src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/PetitionerSolicitorApplicationSubmittedEmailTask.java | uk-gov-mirror/hmcts.div-case-orchestration-service | a43c5d0b44f470eecea18d0f5f56b152d4230be3 | [
"MIT"
] | 7 | 2018-10-03T10:16:08.000Z | 2021-12-10T16:19:21.000Z | src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/PetitionerSolicitorApplicationSubmittedEmailTask.java | uk-gov-mirror/hmcts.div-case-orchestration-service | a43c5d0b44f470eecea18d0f5f56b152d4230be3 | [
"MIT"
] | 975 | 2018-08-28T09:35:17.000Z | 2022-03-31T17:39:57.000Z | src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/PetitionerSolicitorApplicationSubmittedEmailTask.java | uk-gov-mirror/hmcts.div-case-orchestration-service | a43c5d0b44f470eecea18d0f5f56b152d4230be3 | [
"MIT"
] | 3 | 2018-10-10T09:44:57.000Z | 2021-04-10T22:35:46.000Z | 36.88 | 130 | 0.835141 | 997,083 | package uk.gov.hmcts.reform.divorce.orchestration.tasks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import uk.gov.hmcts.reform.divorce.orchestration.domain.model.email.EmailTemplateNames;
import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.generics.PetitionerSolicitorSendEmailTask;
import uk.gov.hmcts.reform.divorce.orchestration.service.EmailService;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.email.EmailTemplateNames.SOL_APPLICANT_APPLICATION_SUBMITTED;
@Component
@Slf4j
public class PetitionerSolicitorApplicationSubmittedEmailTask extends PetitionerSolicitorSendEmailTask {
public PetitionerSolicitorApplicationSubmittedEmailTask(EmailService emailService) {
super(emailService);
}
@Override
protected EmailTemplateNames getTemplate() {
return SOL_APPLICANT_APPLICATION_SUBMITTED;
}
}
|
9234dc94944e9b8571d279f39992ec138286d62e | 4,380 | java | Java | src/main/java/org/myshelf/fxencoder/components/Footer.java | MoBlaa/FXSecGen | 3ff48c7b8d9e5d6ffe88a26d3c8e5e121161abb6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/myshelf/fxencoder/components/Footer.java | MoBlaa/FXSecGen | 3ff48c7b8d9e5d6ffe88a26d3c8e5e121161abb6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/myshelf/fxencoder/components/Footer.java | MoBlaa/FXSecGen | 3ff48c7b8d9e5d6ffe88a26d3c8e5e121161abb6 | [
"Apache-2.0"
] | null | null | null | 30.416667 | 116 | 0.684932 | 997,084 | package org.myshelf.fxencoder.components;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
public class Footer extends BorderPane {
private static EventHandler<ActionEvent> getProxy(@NotNull ObjectProperty<EventHandler<ActionEvent>> property) {
return (event) -> {
if (property.isNotNull().get()) {
property.get().handle(event);
}
};
}
@FXML private Button btnPrevious;
@FXML private Button btnNext;
@FXML private Button btnRefresh;
private ObjectProperty<EventHandler<ActionEvent>> propertyOnRefreshAction;
private ObjectProperty<EventHandler<ActionEvent>> propertyOnNextAction;
private ObjectProperty<EventHandler<ActionEvent>> propertyOnPreviousAction;
public Footer() {
this.propertyOnNextAction = new SimpleObjectProperty<>();
this.propertyOnPreviousAction = new SimpleObjectProperty<>();
this.propertyOnRefreshAction = new SimpleObjectProperty<>();
FXMLLoader fxmlLoader = new FXMLLoader(Footer.class.getResource("Footer.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@FXML
public void initialize() {
btnNext.setOnAction(getProxy(onNextActionProperty()));
btnPrevious.setOnAction(getProxy(onPreviousActionProperty()));
btnRefresh.setOnAction(getProxy(onRefreshActionProperty()));
Platform.runLater(btnNext::requestFocus);
}
// ========== Refresh Action =========
public EventHandler<ActionEvent> getOnRefreshAction() {
return propertyOnRefreshAction.get();
}
public ObjectProperty<EventHandler<ActionEvent>> onRefreshActionProperty() {
return propertyOnRefreshAction;
}
public void setOnRefreshAction(EventHandler<ActionEvent> propertyOnRefreshAction) {
this.propertyOnRefreshAction.set(propertyOnRefreshAction);
}
// =========== Next Action ==========
public EventHandler<ActionEvent> getOnNextAction() {
return propertyOnNextAction.get();
}
public ObjectProperty<EventHandler<ActionEvent>> onNextActionProperty() {
return propertyOnNextAction;
}
public void setOnNextAction(EventHandler<ActionEvent> propertyOnNextAction) {
this.propertyOnNextAction.set(propertyOnNextAction);
}
// ========== Previous Action =========
public EventHandler<ActionEvent> getOnPreviousAction() {
return propertyOnPreviousAction.get();
}
public ObjectProperty<EventHandler<ActionEvent>> onPreviousActionProperty() {
return propertyOnPreviousAction;
}
public void setOnPreviousAction(EventHandler<ActionEvent> propertyOnPreviousAction) {
this.propertyOnPreviousAction.set(propertyOnPreviousAction);
}
// ========== Can Refresh ==========
public Boolean getCanRefresh() {
return !this.btnRefresh.disableProperty().get();
}
public BooleanProperty canRefreshProperty() {
return this.btnRefresh.disableProperty();
}
public void setCanRefresh(Boolean value) {
this.btnRefresh.disableProperty().set(!value);
}
// ========== Has Previous Step ==========
public Boolean getHasPrevious() {
return !this.btnPrevious.disableProperty().get();
}
public BooleanProperty hasPreviousProperty() {
return this.btnPrevious.disableProperty();
}
public void setHasPrevious(Boolean value) {
this.btnPrevious.disableProperty().set(!value);
}
// ========== Has Next Step ==========
public Boolean getHasNext() {
return !this.btnNext.disableProperty().get();
}
public BooleanProperty hasNextProperty() {
return this.btnNext.disableProperty();
}
public void setHasNext(Boolean value) {
this.btnNext.disableProperty().set(!value);
}
}
|
9234ddd2fff2c8dda0806e5032bc95e6351f33b6 | 6,228 | java | Java | src/LevelChooser.java | plotfi/LegoLemmings | 71635396e4ebd4e3302dddf2cb9ecb1fa0c8a875 | [
"MIT"
] | null | null | null | src/LevelChooser.java | plotfi/LegoLemmings | 71635396e4ebd4e3302dddf2cb9ecb1fa0c8a875 | [
"MIT"
] | null | null | null | src/LevelChooser.java | plotfi/LegoLemmings | 71635396e4ebd4e3302dddf2cb9ecb1fa0c8a875 | [
"MIT"
] | null | null | null | 32.778947 | 99 | 0.505941 | 997,085 | import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
/**
* get level statistics. This class reads from the file levelChooser.txt and uses the info therein
* to get data on each of the levels, in order.
*
* <p>(instructions on the format of the file can be found in the sample)
*/
public class LevelChooser {
/** The List of levels */
private Stack levels;
/**
* This function reads in and interprets the data. This function reads in and interprets the data
* from the file.
*/
public LevelChooser() {
levels = new Stack();
File levelText;
FileReader in;
BufferedReader readFrom = null;
try {
levelText = new File("levelChooser.txt");
in = new FileReader(levelText);
readFrom = new BufferedReader(in);
int c;
while (-1 != (c = readFrom.read())) {
String levelName = "";
int lems = 0;
int rate = 0;
int goal = 0;
int time = 0;
int x = 0;
int y = 0;
Point start;
if ('#' == c) {
readFrom.readLine();
continue;
}
c = (char) readFrom.read();
if ('|' != c) {
c = (char) readFrom.read(); // second | after level number
} // add another if we support 100+ levels
/*file name*/ c = (char) readFrom.read(); // second |
while ('|' != (char) (c = (char) readFrom.read())) {
levelName = levelName.concat(Character.toString((char) c));
}
/*num released*/ c = (char) readFrom.read(); // second |
lems = Character.getNumericValue((char) (readFrom.read()));
lems *= 10;
lems += Character.getNumericValue((char) (readFrom.read()));
c = (char) readFrom.read();
if ('|' != (char) c) {
lems *= 10;
lems += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
/*release rate*/ c = (char) readFrom.read(); // second |
rate = Character.getNumericValue((char) (readFrom.read()));
c = (char) readFrom.read();
if ('|' != (char) c) {
rate *= 10;
rate += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
/*goal number*/ c = (char) readFrom.read(); // second |
goal = Character.getNumericValue((char) (readFrom.read()));
c = (char) readFrom.read();
if ('|' != (char) c) {
goal *= 10;
goal += Character.getNumericValue((char) c);
c = (char) readFrom.read();
if ('|' != (char) c) {
goal *= 10;
goal += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
}
/*time*/ c = (char) readFrom.read(); // second |
time = Character.getNumericValue((char) (readFrom.read()));
c = (char) readFrom.read();
if ('|' != (char) c) {
time *= 10;
time += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
/*x start*/ c = (char) readFrom.read(); // second |
x = Character.getNumericValue((char) (readFrom.read()));
c = (char) readFrom.read();
if (',' != (char) c) {
x *= 10;
x += Character.getNumericValue((char) c);
c = (char) readFrom.read();
if (',' != (char) c) {
x *= 10;
x += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
}
/*y start*/ y = Character.getNumericValue((char) (readFrom.read()));
c = (char) readFrom.read();
if ('\n' != (char) c) {
y *= 10;
y += Character.getNumericValue((char) c);
c = (char) readFrom.read();
if ('\n' != (char) c) {
y *= 10;
y += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
}
/*abilities:*/ Stack abilities = new Stack();
int temp;
for (int lq = 0; lq < 7; lq++) {
c = (char) readFrom.read();
if ('-' == (char) c) {
temp = -1;
c = (char) readFrom.read();
c = (char) readFrom.read();
} else {
temp = Character.getNumericValue((char) c);
c = (char) readFrom.read();
if ('|' != (char) c) {
temp *= 10;
temp += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
}
abilities.add(new Integer(temp));
c = (char) readFrom.read(); // second |
} // loop
c = (char) readFrom.read();
if ('-' == (char) c) {
temp = -1;
c = (char) readFrom.read();
c = (char) readFrom.read();
} else {
temp = Character.getNumericValue((char) c);
c = (char) readFrom.read();
if ('\n' != (char) c) {
temp *= 10;
temp += Character.getNumericValue((char) c);
c = (char) readFrom.read();
}
}
abilities.add(new Integer(temp));
Stack tempStack = new Stack();
for (int i = 7; i >= 0; i--) {
tempStack.push(abilities.elementAt(i));
}
start = new Point(x, y);
levels.addElement(new LevelData(levelName, lems, rate, goal, time, start, tempStack));
}
readFrom.close();
} catch (IOException e) {
System.err.println("Error reading from file");
System.err.println("Please replace levelChooser.txt");
System.exit(-1);
}
}
/**
* This function gets the data for the selected level. This function gets the data for the
* selected level.
*
* @param i the level to get data for.
* @return the data for the selected level.
*/
public LevelData getLevelData(int i) {
return (LevelData) levels.elementAt(i);
}
/**
* This function returns the number of levels available. This function returns the number of
* levels available.
*
* @return number of levels available.
*/
public int getLevelCount() {
return levels.size();
}
}
|
9234dde356ca944e598e0f0227425bc8a3591c65 | 365 | java | Java | study/src/main/java/com/myzuji/study/java/lang/RunTimeStudy.java | mestarshine/myzuji | a7ccca932f4b9794adbb6b345eb19ce04f319890 | [
"MIT"
] | null | null | null | study/src/main/java/com/myzuji/study/java/lang/RunTimeStudy.java | mestarshine/myzuji | a7ccca932f4b9794adbb6b345eb19ce04f319890 | [
"MIT"
] | null | null | null | study/src/main/java/com/myzuji/study/java/lang/RunTimeStudy.java | mestarshine/myzuji | a7ccca932f4b9794adbb6b345eb19ce04f319890 | [
"MIT"
] | null | null | null | 18.25 | 77 | 0.542466 | 997,086 | package com.myzuji.study.java.lang;
/**
* 说明
*
* @author shine
* @date 2020/02/01
*/
public class RunTimeStudy {
public static void main(String[] args) {
try {
ProcessBuilder p = new ProcessBuilder("notepad.exe", "testfile");
p.start();
} catch (Exception e) {
System.out.println(e);
}
}
}
|
9234df189cef0f183b0464ed6498d21119e20f09 | 3,160 | java | Java | openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/Embeddable.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 104 | 2015-01-31T01:11:05.000Z | 2022-03-20T05:28:58.000Z | openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/Embeddable.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 56 | 2016-09-30T14:04:31.000Z | 2022-02-21T11:23:53.000Z | openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/Embeddable.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 127 | 2015-01-11T14:18:46.000Z | 2022-03-23T13:46:58.000Z | 36.744186 | 77 | 0.722152 | 997,087 | /*
* 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.openjpa.jdbc.meta;
import java.sql.SQLException;
import org.apache.openjpa.jdbc.kernel.JDBCFetchConfiguration;
import org.apache.openjpa.jdbc.kernel.JDBCStore;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.schema.ColumnIO;
import org.apache.openjpa.jdbc.sql.Result;
import org.apache.openjpa.kernel.OpenJPAStateManager;
/**
* Interface for field strategies that can managed fields of
* embedded-element, embedded-key, and embedded-value objects. Fields of
* directly embedded objects do not have to implement this interface.
*
* @author Abe White
* @since 0.4.0
*/
public interface Embeddable {
Object UNSUPPORTED = new Object();
/**
* Return the columns used by this strategy.
*/
Column[] getColumns();
/**
* Return column I/O information for this mapping.
*/
ColumnIO getColumnIO();
/**
* Return the arguments needed to extract datastore values via
* {@link Result#getObject} for each column.
*/
Object[] getResultArguments();
/**
* Convert the given Java value to its datastore equivalent. If this
* mapping occupies multiple columns, return an object array with one
* element per column. For relation id columns, return the state manager
* the column depends on.
*/
Object toEmbeddedDataStoreValue(Object val, JDBCStore store);
/**
* Convert the given datastore value to its Java equivalent.
* If {@link #getColumns} returns multiple columns, the given datastore
* value will be an object array of the corresponding length. This method
* must only be supported by mappings of embedded id objects. In other
* cases {@link #loadEmbedded} will be used instead. Return
* {@link #UNSUPPORTED} if this mapping cannot support this method.
*/
Object toEmbeddedObjectValue(Object val);
/**
* Load this strategy's field by transforming the given datastore value.
* If {@link #getColumns} returns multiple columns, the given datastore
* value will be an object array of the corresponding length. The value
* does not have to be loaded immediately; it may be stored as impl data.
*/
void loadEmbedded(OpenJPAStateManager sm, JDBCStore store,
JDBCFetchConfiguration fetch, Object val)
throws SQLException;
}
|
9234e192a9017c32dc16a576fc215730469aa471 | 3,942 | java | Java | jOOQ/src/main/java/org/jooq/impl/BitXor.java | grachevko/jOOQ | 33a29b5afe3812fa4f79cfcd2f1cff5c7d2f2031 | [
"Apache-2.0"
] | null | null | null | jOOQ/src/main/java/org/jooq/impl/BitXor.java | grachevko/jOOQ | 33a29b5afe3812fa4f79cfcd2f1cff5c7d2f2031 | [
"Apache-2.0"
] | null | null | null | jOOQ/src/main/java/org/jooq/impl/BitXor.java | grachevko/jOOQ | 33a29b5afe3812fa4f79cfcd2f1cff5c7d2f2031 | [
"Apache-2.0"
] | null | null | null | 24.6375 | 118 | 0.518519 | 997,088 | /*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq.impl;
import static org.jooq.impl.DSL.*;
import static org.jooq.impl.Internal.*;
import static org.jooq.impl.Keywords.*;
import static org.jooq.impl.Names.*;
import static org.jooq.impl.SQLDataType.*;
import static org.jooq.impl.Tools.*;
import static org.jooq.impl.Tools.BooleanDataKey.*;
import static org.jooq.impl.Tools.DataExtendedKey.*;
import static org.jooq.impl.Tools.DataKey.*;
import static org.jooq.SQLDialect.*;
import org.jooq.*;
import org.jooq.Record;
import org.jooq.conf.*;
import org.jooq.impl.*;
import org.jooq.tools.*;
import java.util.*;
/**
* The <code>BIT XOR</code> statement.
*/
@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
final class BitXor<T extends Number>
extends
AbstractField<T>
{
final Field<T> arg1;
final Field<T> arg2;
BitXor(
Field<T> arg1,
Field<T> arg2
) {
super(
N_BIT_XOR,
allNotNull((DataType) dataType(INTEGER, arg1, false), arg1, arg2)
);
this.arg1 = nullSafeNotNull(arg1, INTEGER);
this.arg2 = nullSafeNotNull(arg2, INTEGER);
}
// -------------------------------------------------------------------------
// XXX: QueryPart API
// -------------------------------------------------------------------------
@Override
public final void accept(Context<?> ctx) {
switch (ctx.family()) {
case H2:
case HSQLDB:
ctx.visit(function(N_BITXOR, getDataType(), arg1, arg2));
break;
case FIREBIRD:
ctx.visit(function(N_BIN_OR, getDataType(), arg1, arg2));
break;
case SQLITE:
ctx.visit(// ~(a & b) & (a | b)
DSL.bitAnd(
DSL.bitNot(DSL.bitAnd((Field<Number>) arg1, (Field<Number>) arg2)),
DSL.bitOr((Field<Number>) arg1, (Field<Number>) arg2)
));
break;
default:
ctx.sql('(');
SQL op = Expression.HASH_OP_FOR_BIT_XOR.contains(ctx.dialect()) ? Operators.OP_NUM : Operators.OP_HAT;
Expression.<Field<T>, BitXor<T>>acceptAssociative(
ctx,
this,
q -> new Expression.Expr<>(q.arg1, op, q.arg2),
c -> c.sql(' ')
);
ctx.sql(')');
break;
}
}
// -------------------------------------------------------------------------
// The Object API
// -------------------------------------------------------------------------
@Override
public boolean equals(Object that) {
if (that instanceof BitXor) {
return
StringUtils.equals(arg1, ((BitXor) that).arg1) &&
StringUtils.equals(arg2, ((BitXor) that).arg2)
;
}
else
return super.equals(that);
}
}
|
9234e44a512b393bfef0d0ef43e13133315ee930 | 598 | java | Java | di-service/src/main/java/com/softline/service/MysqlService.java | dongjuntao/data-integration-backend | 71453b5a6353a45b2ae4e7612ec5097710a762a6 | [
"Apache-2.0"
] | 3 | 2021-04-21T07:24:27.000Z | 2021-10-15T02:31:41.000Z | di-service/src/main/java/com/softline/service/MysqlService.java | dongjuntao/data-integration-backend | 71453b5a6353a45b2ae4e7612ec5097710a762a6 | [
"Apache-2.0"
] | 1 | 2022-01-17T06:27:56.000Z | 2022-01-17T06:27:56.000Z | di-service/src/main/java/com/softline/service/MysqlService.java | dongjuntao/data-integration-backend | 71453b5a6353a45b2ae4e7612ec5097710a762a6 | [
"Apache-2.0"
] | 2 | 2021-11-15T13:59:57.000Z | 2021-11-19T05:56:02.000Z | 27.181818 | 112 | 0.801003 | 997,089 | package com.softline.service;
import com.softline.database.common.DatabaseParam;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* Created by dong ON 2020/11/26
*/
public interface MysqlService {
Map<String, Object> getTableNamesAndFieldsByDataByDBName(DatabaseParam databaseParam) throws Exception;
List<String> getTableNameList(DatabaseParam databaseParam) throws SQLException;
Map<String, Object> getFieldsByTableName(String tableName, DatabaseParam databaseParam) throws SQLException;
boolean isConnected(DatabaseParam databaseParam);
}
|
9234e5f2ce2a04f49be4b782d08b95e69a772e32 | 7,975 | java | Java | src/test/java/TauSSA/DepartureEventTest.java | imperial-qore/jline | 96969c95f3a853dc115dc809fbd25225a5d89fcf | [
"BSD-3-Clause"
] | null | null | null | src/test/java/TauSSA/DepartureEventTest.java | imperial-qore/jline | 96969c95f3a853dc115dc809fbd25225a5d89fcf | [
"BSD-3-Clause"
] | null | null | null | src/test/java/TauSSA/DepartureEventTest.java | imperial-qore/jline | 96969c95f3a853dc115dc809fbd25225a5d89fcf | [
"BSD-3-Clause"
] | 2 | 2021-11-24T12:28:00.000Z | 2022-02-16T11:21:18.000Z | 46.637427 | 93 | 0.691285 | 997,090 | package TauSSA;
import SimUtil.Exp;
import StochLib.*;
import StochLib.Queue;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.*;
class DepartureEventTest {
private DepartureEvent departureEvent1;
private DepartureEvent departureEvent2;
private DepartureEvent departureEvent3;
private DepartureEvent departureEvent4;
private DepartureEvent departureEvent5;
private DepartureEvent departureEvent6;
private StateMatrix stateMatrix;
private EventStack eventStack;
private Queue queue1;
private Queue queue2;
private Queue queue3;
private Network network;
private JobClass jobClass1;
private JobClass jobClass2;
private Timeline timeline;
@org.junit.jupiter.api.BeforeEach
void setUp() {
int[][] capacityMatrix = new int[3][3];
int[] nodeCapacities = new int[3];
int[] servers = new int[3];
capacityMatrix[0][0] = 10;
capacityMatrix[0][1] = 9;
capacityMatrix[0][2] = 8;
capacityMatrix[1][0] = 9;
capacityMatrix[1][1] = 8;
capacityMatrix[1][2] = 7;
capacityMatrix[2][0] = 8;
capacityMatrix[2][1] = 7;
capacityMatrix[2][2] = 6;
nodeCapacities[0] = 13;
nodeCapacities[1] = 12;
nodeCapacities[2] = 1;
servers[0] = 3;
servers[1] = 5;
servers[2] = 1;
SchedStrategy[] schedStrategies = new SchedStrategy[3];
schedStrategies[0] = SchedStrategy.FCFS;
schedStrategies[1] = SchedStrategy.LCFS;
schedStrategies[2] = SchedStrategy.LCFS;
NetworkStruct networkStruct = new NetworkStruct();
networkStruct.nStateful = 3;
networkStruct.nClasses = 3;
networkStruct.schedStrategies = schedStrategies;
networkStruct.capacities = capacityMatrix;
networkStruct.nodeCapacity = nodeCapacities;
networkStruct.numberOfServers = servers;
this.stateMatrix = new StateMatrix(networkStruct);
this.timeline = new Timeline(networkStruct,CutoffStrategy.None);
this.eventStack = new EventStack();
this.network = new Network("Test Network");
this.jobClass1 = new OpenClass(this.network, "Job Class", 1);
this.jobClass2 = new OpenClass(this.network, "Job Class 2", 2);
this.queue1 = new Queue(this.network, "Queue 1", SchedStrategy.FCFS);
this.queue1.setService(this.jobClass1,new Exp(3));
this.queue1.setService(this.jobClass2,new Exp(4));
this.queue1.setNumberOfServers(3);
this.queue2 = new Queue(this.network, "Queue 2", SchedStrategy.LCFS);
this.queue2.setService(this.jobClass1,new Exp(5));
this.queue2.setService(this.jobClass2,new Exp(4));
this.queue2.setNumberOfServers(5);
this.queue3 = new Queue(this.network, "Queue 3", SchedStrategy.LCFS);
this.queue3.setService(this.jobClass1,new Exp(6));
this.queue3.setService(this.jobClass2,new Exp(7));
this.network.link(this.network.serialRouting(this.queue1, this.queue2, this.queue3));
this.departureEvent1 = new DepartureEvent(this.queue1, this.jobClass1);
this.departureEvent2 = new DepartureEvent(this.queue2, this.jobClass1);
this.departureEvent3 = new DepartureEvent(this.queue3, this.jobClass1);
this.departureEvent4 = new DepartureEvent(this.queue1, this.jobClass2);
this.departureEvent5 = new DepartureEvent(this.queue2, this.jobClass2);
this.departureEvent6 = new DepartureEvent(this.queue3, this.jobClass2);
}
@org.junit.jupiter.api.Test
void testGetRate() {
assertEquals(this.departureEvent1.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.setState(0,0,1);
this.stateMatrix.addToBuffer(0,0,1);
assertEquals(this.departureEvent1.getRate(this.stateMatrix), 3);
assertEquals(this.departureEvent4.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.setState(0,0,2);
this.stateMatrix.addToBuffer(0,0,1);
assertEquals(this.departureEvent1.getRate(this.stateMatrix), 6);
assertEquals(this.departureEvent4.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.setState(0,0,3);
this.stateMatrix.addToBuffer(0,0,1);
assertEquals(this.departureEvent1.getRate(this.stateMatrix), 9);
assertEquals(this.departureEvent4.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.setState(0,0,4);
this.stateMatrix.addToBuffer(0,0,1);
assertEquals(this.departureEvent1.getRate(this.stateMatrix), 9);
assertEquals(this.departureEvent4.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.setState(0,1,1);
this.stateMatrix.addToBuffer(0,1,1);
assertEquals(this.departureEvent1.getRate(this.stateMatrix), 9);
assertEquals(this.departureEvent4.getRate(this.stateMatrix), Double.NaN);
assertEquals(this.departureEvent2.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.incrementState(1,0);
this.stateMatrix.addToBuffer(1,0,1);
assertEquals(this.departureEvent3.getRate(this.stateMatrix), Double.NaN);
assertEquals(this.departureEvent2.getRate(this.stateMatrix), 5);
assertEquals(this.departureEvent5.getRate(this.stateMatrix), Double.NaN);
this.stateMatrix.incrementState(1,1);
this.stateMatrix.addToBuffer(1,1,1);
assertEquals(this.departureEvent3.getRate(this.stateMatrix), Double.NaN);
assertEquals(this.departureEvent2.getRate(this.stateMatrix), 5);
assertEquals(this.departureEvent5.getRate(this.stateMatrix), 4);
this.stateMatrix.incrementState(1,1);
this.stateMatrix.addToBuffer(1,1,1);
assertEquals(this.departureEvent3.getRate(this.stateMatrix), Double.NaN);
assertEquals(this.departureEvent2.getRate(this.stateMatrix), 5);
assertEquals(this.departureEvent5.getRate(this.stateMatrix), 8);
this.stateMatrix.incrementState(1,1);
this.stateMatrix.addToBuffer(1,1,1);
assertEquals(this.departureEvent3.getRate(this.stateMatrix), Double.NaN);
assertEquals(this.departureEvent2.getRate(this.stateMatrix), 5);
assertEquals(this.departureEvent5.getRate(this.stateMatrix), 12);
this.stateMatrix.incrementState(1,1);
this.stateMatrix.addToBuffer(1,1,1);
assertEquals(this.departureEvent3.getRate(this.stateMatrix), Double.NaN);
assertEquals(this.departureEvent2.getRate(this.stateMatrix), 5);
assertEquals(this.departureEvent5.getRate(this.stateMatrix), 16);
}
@org.junit.jupiter.api.Test
void testStateUpdate() {
Random random = new Random();
this.stateMatrix.setState(0,0,5);
this.stateMatrix.addToBuffer(0,0,5);
this.departureEvent1.stateUpdate(this.stateMatrix, random, this.timeline);
assertEquals(this.stateMatrix.getState(0,0),4);
assertEquals(this.stateMatrix.getState(1,0),1);
this.departureEvent1.stateUpdate(this.stateMatrix, random, this.timeline);
assertEquals(this.stateMatrix.getState(0,0),3);
assertEquals(this.stateMatrix.getState(1,0),2);
this.departureEvent1.stateUpdate(this.stateMatrix, random, this.timeline);
assertEquals(this.stateMatrix.getState(0,0),2);
assertEquals(this.stateMatrix.getState(1,0),3);
this.departureEvent1.stateUpdate(this.stateMatrix, random, this.timeline);
assertEquals(this.stateMatrix.getState(0,0),1);
assertEquals(this.stateMatrix.getState(1,0),4);
}
@org.junit.jupiter.api.Test
void testStateUpdateN() {
Random random = new Random();
this.stateMatrix.setState(0,0,5);
this.stateMatrix.addToBuffer(0,0,5);
this.departureEvent1.stateUpdateN(2,this.stateMatrix, random, this.timeline);
assertEquals(this.stateMatrix.getState(0,0),3);
assertEquals(this.stateMatrix.getState(1,0),2);
}
} |
9234e6123dbc421284d21274018feed2af5f505b | 616 | java | Java | app/src/main/java/com/grzegorzbaczek/twitchstreamertools/dagger/ApplicationComponent.java | GrzegorzBaczek93/TwitchStreamerTools | 40b9dfd96e6db85a2c9ebf0b07ec40219510f04f | [
"Apache-2.0"
] | 1 | 2018-08-14T13:47:35.000Z | 2018-08-14T13:47:35.000Z | app/src/main/java/com/grzegorzbaczek/twitchstreamertools/dagger/ApplicationComponent.java | GrzegorzBaczek93/TwitchStreamerTools | 40b9dfd96e6db85a2c9ebf0b07ec40219510f04f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/grzegorzbaczek/twitchstreamertools/dagger/ApplicationComponent.java | GrzegorzBaczek93/TwitchStreamerTools | 40b9dfd96e6db85a2c9ebf0b07ec40219510f04f | [
"Apache-2.0"
] | null | null | null | 30.8 | 84 | 0.847403 | 997,091 | package com.grzegorzbaczek.twitchstreamertools.dagger;
import com.grzegorzbaczek.twitchstreamertools.data.repository.SocialMediaRepository;
import com.grzegorzbaczek.twitchstreamertools.ui.account.AddAccountViewModel;
import com.grzegorzbaczek.twitchstreamertools.ui.list.ListViewModel;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
void inject(SocialMediaRepository socialMediaRepository);
void inject(ListViewModel listViewModel);
void inject(AddAccountViewModel addAccountViewModel);
}
|
9234e62ce5676d025693ee763feb994f56d086db | 5,908 | java | Java | gatherer/src/pandas/gatherer/core/Worker.java | nla/pandas4 | 2cee9b8fae88cf5bee46472b305fa91e1f3d2976 | [
"Apache-2.0"
] | 1 | 2022-01-03T16:51:53.000Z | 2022-01-03T16:51:53.000Z | gatherer/src/pandas/gatherer/core/Worker.java | nla/pandas4 | 2cee9b8fae88cf5bee46472b305fa91e1f3d2976 | [
"Apache-2.0"
] | 22 | 2021-02-22T14:36:01.000Z | 2022-02-20T12:07:44.000Z | gatherer/src/pandas/gatherer/core/Worker.java | nla/pandas4 | 2cee9b8fae88cf5bee46472b305fa91e1f3d2976 | [
"Apache-2.0"
] | 2 | 2021-06-10T09:13:31.000Z | 2021-11-18T19:15:12.000Z | 35.806061 | 203 | 0.688727 | 997,092 | package pandas.gatherer.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pandas.gather.*;
import java.io.IOException;
import java.time.Instant;
class Worker implements Runnable {
private static final Logger log = LoggerFactory.getLogger(Worker.class);
private final GatherManager gatherManager;
private final WorkingArea workingArea;
private final Backend backend;
private final InstanceService instanceService;
private final InstanceGatherRepository instanceGatherRepository;
private final ThumbnailGenerator thumbnailGenerator;
Worker(GatherManager gatherManager, InstanceService instanceService, InstanceGatherRepository instanceGatherRepository, WorkingArea workingArea, Backend backend, ThumbnailGenerator thumbnailGenerator) {
this.gatherManager = gatherManager;
this.instanceService = instanceService;
this.workingArea = workingArea;
this.backend = backend;
this.instanceGatherRepository = instanceGatherRepository;
this.thumbnailGenerator = thumbnailGenerator;
}
/**
* Main loop of the gatherer. Pick up a new title to be gathered from the GatherManager and start
* gathering it. If there are no titles currently available, wait a minute or so and try again.
*/
public void run() {
long pollDelay = 1000;
try {
while (!gatherManager.isShutdown()) {
Instance instance = gatherManager.nextInstance(backend.getGatherMethod(), Thread.currentThread().getName());
if (instance == null) {
Thread.sleep(pollDelay);
continue;
}
try {
processInstance(instance);
} finally {
gatherManager.gathererFinished(Thread.currentThread().getName());
}
}
} catch (Exception e2) {
log.info(Thread.currentThread().getName() + " " + e2 + " in Gatherer " + Thread.currentThread().getName());
e2.printStackTrace();
}
log.debug("Shutdown");
}
/**
* Peform a gather operation.
*
* Gathering consists of 4 stages, intialisation, pre-processing, gathering,
* and post-processing. Not all gather types may implement all four stages.
*/
private void processInstance(Instance instance) {
gatherManager.addGatherInstanceThreadWithId(Thread.currentThread().getName(), instance.getId());
loop:
while (!gatherManager.isShutdown()) {
instance = instanceService.refresh(instance);
log.info("{} {}", instance.getState().getName(), instance.getHumanId());
try {
String nextState;
switch (instance.getState().getName()) {
case State.CREATION:
nameThread("C", instance);
log.info("mkdir {}", workingArea.getInstanceDir(instance.getTitle().getPi(), instance.getDateString()));
workingArea.createInstance(instance.getTitle().getPi(), instance.getDateString());
if (backend.getGatherMethod().equals(GatherMethod.UPLOAD)) {
// upload instances are special and stay in the creation state
// not ideal but I don't want to rework the design now.
break loop;
}
nextState = State.GATHERING;
break;
case State.GATHERING:
nameThread("G", instance);
Instant startTime = Instant.now();
thumbnailGenerator.generateLiveThumbnail(instance);
backend.gather(instance);
nextState = State.GATHER_PROCESS;
saveGatherStatistics(instance, startTime);
break;
case State.GATHER_PROCESS:
nameThread("P", instance);
backend.postprocess(instance);
nextState = State.GATHERED;
break;
case State.ARCHIVING:
nameThread("A", instance);
backend.archive(instance);
instanceService.publishInstanceImmediatelyIfNecessary(instance.getId());
nextState = State.ARCHIVED;
break;
case State.DELETING:
nameThread("D", instance);
backend.delete(instance);
nextState = State.DELETED;
break;
default:
break loop; // nothing more to do
}
/*
* Only move to the state if its unchanged. It might have been updated in the background
* by a user pausing or stopping an instance.
*/
if (instance.getState().getName().equals(instanceService.refresh(instance).getState().getName()) && !gatherManager.isShutdown()) {
instanceService.updateState(instance, nextState);
}
} catch (Exception e) {
log.error("{} {}", instance.getState().getName(), instance.getHumanId(), e);
// we try try hard not to crash as the worker will be permanently dead if we do
// there might be an intermittent problem with the database so these
// could fail.
try {
instanceService.recordFailure(instance, "Failed " + instance.getState().getName(), e.getMessage(), Thread.currentThread().getName());
} catch (Exception e2) {
log.error("Error logging exception to db", e2);
}
} finally {
clearThreadName();
}
}
}
private void clearThreadName() {
Thread thread = Thread.currentThread();
String name = thread.getName();
int i = name.indexOf(" ");
if (i >= 0) {
thread.setName(name.substring(0, i));
}
}
private void nameThread(String stateCode, Instance instance) {
Thread thread = Thread.currentThread();
thread.setName(thread.getName() + " " + stateCode + instance.getTitle().getPi());
}
private void saveGatherStatistics(Instance instance, Instant startTime) {
try {
instanceService.finishGather(instance.getId(), startTime);
if (!instance.getGatherMethodName().equals(GatherMethod.HERITRIX)) {
FileStats stats = workingArea.instanceStats(instance.getTitle().getPi(), instance.getDateString(), gatherManager::isShutdown);
if (gatherManager.isShutdown()) {
return;
}
instanceService.updateGatherStats(instance.getId(), stats.fileCount(), stats.size());
}
} catch (IOException e) {
log.warn("Unable to save gather stats for " + instance.getHumanId(), e);
}
}
}
|
9234e6beabb35c61481df5e57056cfc64bcbea55 | 2,255 | java | Java | src/test/java/org/mandfer/tools/system/ArchiverServiceTest.java | marcandreuf/ToolBox | 94c1a927af956b1049b08bfe4ff98b75771bef7b | [
"MIT"
] | null | null | null | src/test/java/org/mandfer/tools/system/ArchiverServiceTest.java | marcandreuf/ToolBox | 94c1a927af956b1049b08bfe4ff98b75771bef7b | [
"MIT"
] | 2 | 2021-03-20T07:30:01.000Z | 2021-11-03T06:02:20.000Z | src/test/java/org/mandfer/tools/system/ArchiverServiceTest.java | marcandreuf/ToolBox | 94c1a927af956b1049b08bfe4ff98b75771bef7b | [
"MIT"
] | null | null | null | 32.214286 | 99 | 0.745898 | 997,093 | package org.mandfer.tools.system;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import static org.mockito.Mockito.*;
/**
* Created by marc on 21/08/16.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({Path.class, DateTime.class})
public class ArchiverServiceTest {
private Path mock_path, mock_destPath, mock_failed, mock_relPath, mock_fullPath;
private DateTime mock_creationDate;
private OS mock_Os;
private MediaService mock_mediaService;
private ArchiverService archiverService;
@Before
public void setUP() throws FileNotFoundException {
mock_path = mock(Path.class);
mock_destPath = mock(Path.class);
mock_failed = mock(Path.class);
mock_relPath = mock(Path.class);
mock_fullPath = mock(Path.class);
mock_creationDate = PowerMockito.mock(DateTime.class);
mock_Os = mock(OS.class);
mock_mediaService = mock(MediaService.class);
archiverService = new ArchiverService(mock_Os, mock_mediaService);
}
@Test
public void testArchiveFile() throws Exception {
when(mock_mediaService.findCreationDate(mock_path)).thenReturn(mock_creationDate);
when(mock_Os.calcDateRelPath(mock_path, mock_creationDate)).thenReturn(mock_relPath);
when(mock_destPath.resolve(mock_relPath)).thenReturn(mock_fullPath);
archiverService.archive(mock_path, mock_destPath, mock_failed);
verify(mock_mediaService).findCreationDate(mock_path);
verify(mock_Os).calcDateRelPath(mock_path, mock_creationDate);
verify(mock_Os).moveFileTo(mock_path, mock_fullPath);
}
@Test
public void moveFileToBackupFolderIfThereIsAnyException() throws Exception {
when(mock_mediaService.findCreationDate(mock_path)).thenThrow(FileNotFoundException.class);
archiverService.archive(mock_path, mock_destPath, mock_failed);
verify(mock_Os).moveFileTo(mock_path, mock_failed);
}
}
|
9234e9673526abf06a20335267d52340b1c9a5b6 | 1,512 | java | Java | src/main/java/org/rogmann/jsmud/source/StatementIf.java | srogmann/jsmud-analysis | a5a1dd82a41a3bfba60e161dd79a48023c0fa45f | [
"Apache-2.0"
] | 1 | 2022-03-12T10:40:00.000Z | 2022-03-12T10:40:00.000Z | src/main/java/org/rogmann/jsmud/source/StatementIf.java | srogmann/jsmud-analysis | a5a1dd82a41a3bfba60e161dd79a48023c0fa45f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rogmann/jsmud/source/StatementIf.java | srogmann/jsmud-analysis | a5a1dd82a41a3bfba60e161dd79a48023c0fa45f | [
"Apache-2.0"
] | null | null | null | 22.235294 | 127 | 0.685847 | 997,094 | package org.rogmann.jsmud.source;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.JumpInsnNode;
/**
* if-Statement.
*/
public class StatementIf extends StatementInstr<JumpInsnNode> {
/** destination label */
protected final Label labelDest;
/** display-name of label */
private final String labelName;
/** condition-expression */
private final ExpressionBase<?> exprCond;
/**
* Constructor
* @param insn jump-instruction, e.g. IF_ICMPLE
* @param exprCond conditional-expression
* @param labelDest destination label
* @param labelName display-name of label
*/
public StatementIf(final JumpInsnNode insn, final ExpressionBase<?> exprCond, final Label labelDest, final String labelName) {
super(insn);
this.exprCond = exprCond;
this.labelDest = labelDest;
this.labelName = labelName;
}
/**
* Gets the conditional expression.
* @return condition
*/
public ExpressionBase<?> getExprCond() {
return exprCond;
}
/**
* Gets the name of the destination-label.
* @return label-name
*/
public String getLabelName() {
return labelName;
}
/** {@inheritDoc} */
@Override
public void render(StringBuilder sb) {
sb.append("if").append(' ').append('(');
exprCond.render(sb);
sb.append(')').append(' ');
sb.append("goto").append(' ').append(labelName);
sb.append(';');
}
/** {@inheritDoc} */
@Override
public String toString() {
return String.format("%s(if (%s) goto %s);",
getClass().getSimpleName(), exprCond, labelName);
}
}
|
9234ea8c1c25ada5514f6b13aaa4ebb5170bfda7 | 3,314 | java | Java | google-ads/src/main/java/com/google/ads/googleads/v3/enums/AdTypeProto.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | 3 | 2020-12-20T18:56:52.000Z | 2021-07-29T12:12:02.000Z | google-ads/src/main/java/com/google/ads/googleads/v3/enums/AdTypeProto.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v3/enums/AdTypeProto.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | 1 | 2021-02-15T04:54:10.000Z | 2021-02-15T04:54:10.000Z | 48.028986 | 96 | 0.7414 | 997,095 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v3/enums/ad_type.proto
package com.google.ads.googleads.v3.enums;
public final class AdTypeProto {
private AdTypeProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v3_enums_AdTypeEnum_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v3_enums_AdTypeEnum_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n+google/ads/googleads/v3/enums/ad_type." +
"proto\022\035google.ads.googleads.v3.enums\032\034go" +
"ogle/api/annotations.proto\"\357\003\n\nAdTypeEnu" +
"m\"\340\003\n\006AdType\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN" +
"\020\001\022\013\n\007TEXT_AD\020\002\022\024\n\020EXPANDED_TEXT_AD\020\003\022\020\n" +
"\014CALL_ONLY_AD\020\006\022\036\n\032EXPANDED_DYNAMIC_SEAR" +
"CH_AD\020\007\022\014\n\010HOTEL_AD\020\010\022\025\n\021SHOPPING_SMART_" +
"AD\020\t\022\027\n\023SHOPPING_PRODUCT_AD\020\n\022\014\n\010VIDEO_A" +
"D\020\014\022\014\n\010GMAIL_AD\020\r\022\014\n\010IMAGE_AD\020\016\022\030\n\024RESPO" +
"NSIVE_SEARCH_AD\020\017\022 \n\034LEGACY_RESPONSIVE_D" +
"ISPLAY_AD\020\020\022\n\n\006APP_AD\020\021\022\031\n\025LEGACY_APP_IN" +
"STALL_AD\020\022\022\031\n\025RESPONSIVE_DISPLAY_AD\020\023\022\023\n" +
"\017HTML5_UPLOAD_AD\020\025\022\024\n\020DYNAMIC_HTML5_AD\020\026" +
"\022\025\n\021APP_ENGAGEMENT_AD\020\027\022\"\n\036SHOPPING_COMP" +
"ARISON_LISTING_AD\020\030\022\027\n\023VIDEO_RESPONSIVE_" +
"AD\020\036B\340\001\n!com.google.ads.googleads.v3.enu" +
"msB\013AdTypeProtoP\001ZBgoogle.golang.org/gen" +
"proto/googleapis/ads/googleads/v3/enums;" +
"enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V3.En" +
"ums\312\002\035Google\\Ads\\GoogleAds\\V3\\Enums\352\002!Go" +
"ogle::Ads::GoogleAds::V3::Enumsb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_ads_googleads_v3_enums_AdTypeEnum_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v3_enums_AdTypeEnum_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v3_enums_AdTypeEnum_descriptor,
new java.lang.String[] { });
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
9234eb30360c86ed420abdd0f77f68642fc6275e | 1,448 | java | Java | src/main/java/com/corp/concepts/audio/handler/AudioHandler.java | selcuksert/jsaudio | ff1ba668db8c027cc9a0d12059c83f00c8ebcd5e | [
"MIT"
] | null | null | null | src/main/java/com/corp/concepts/audio/handler/AudioHandler.java | selcuksert/jsaudio | ff1ba668db8c027cc9a0d12059c83f00c8ebcd5e | [
"MIT"
] | null | null | null | src/main/java/com/corp/concepts/audio/handler/AudioHandler.java | selcuksert/jsaudio | ff1ba668db8c027cc9a0d12059c83f00c8ebcd5e | [
"MIT"
] | null | null | null | 30.808511 | 108 | 0.800414 | 997,096 | package com.corp.concepts.audio.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import com.corp.concepts.audio.service.AudioConverterService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class AudioHandler {
private static final Logger logger = LoggerFactory.getLogger(AudioHandler.class);
private AudioConverterService audioConverterService;
public AudioHandler(AudioConverterService audioConverterService) {
this.audioConverterService = audioConverterService;
}
public Mono<ServerResponse> audio(ServerRequest serverRequest) {
float sampleRate = 48000;
int sampleSizeInBits = 16;
int channels = 2;
try {
Flux<byte[]> stream = audioConverterService.generateAudioStream("test.wav", sampleRate, sampleSizeInBits,
channels);
return ServerResponse.ok().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
.body(stream, byte[].class);
} catch (Exception e) {
logger.error("Error:", e);
}
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Flux.empty(), byte[].class);
}
}
|
9234ed694b9db7301cacf111cd55a711a66cefc4 | 1,780 | java | Java | Homework5/src/Product.java | helenajae/javaHomework | d10357e22d74143415b8939b12212d6bdd8c6e70 | [
"MIT"
] | null | null | null | Homework5/src/Product.java | helenajae/javaHomework | d10357e22d74143415b8939b12212d6bdd8c6e70 | [
"MIT"
] | null | null | null | Homework5/src/Product.java | helenajae/javaHomework | d10357e22d74143415b8939b12212d6bdd8c6e70 | [
"MIT"
] | null | null | null | 24.054054 | 98 | 0.611798 | 997,097 | public class Product {
private int productNumber;
private String productName;
private int unitsInStock;
private double productPrice;
private Vendor vendor;
public Product(int productNumber, String productName, int unitsInStock, double productPrice) {
this.productNumber = productNumber;
this.productName = productName;
this.unitsInStock = unitsInStock;
this.productPrice = productPrice;
}
public Product(Vendor vendor) {
}
public double totalInventoryValue(){
return unitsInStock * productPrice;
}
public int getProductNumber() {
return productNumber;
}
public String getProductName() {
return productName;
}
public int getUnitsInStock() {
return unitsInStock;
}
public double getProductPrice() {
return productPrice;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setUnitsInStock(int unitsInStock) {
this.unitsInStock = unitsInStock;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public Vendor getVendor() {
return vendor;
}
public void setVendor(Vendor vendor) {
this.vendor = vendor;
}
@Override
public String toString() {
return "Product{" +
"productNumber=" + productNumber +
", productName='" + productName + '\'' +
", unitsInStock=" + unitsInStock +
", productPrice=" + productPrice +
", vendor=" + vendor +
'}';
}
} |
9234edf814929e01697b48869ab1bbb90d4b6ec3 | 757 | java | Java | core/src/main/java/ru/smartapp/core/common/dto/incoming/RunAppDto.java | FedorSergeev/smartapp | 08c2f8baade18bf5203325144e4cefc22fa84087 | [
"MIT"
] | 1 | 2021-09-09T18:25:06.000Z | 2021-09-09T18:25:06.000Z | core/src/main/java/ru/smartapp/core/common/dto/incoming/RunAppDto.java | FedorSergeev/smartapp | 08c2f8baade18bf5203325144e4cefc22fa84087 | [
"MIT"
] | 3 | 2021-10-12T12:41:12.000Z | 2021-10-17T18:51:32.000Z | core/src/main/java/ru/smartapp/core/common/dto/incoming/RunAppDto.java | FedorSergeev/smartapp | 08c2f8baade18bf5203325144e4cefc22fa84087 | [
"MIT"
] | null | null | null | 25.233333 | 81 | 0.752972 | 997,098 | package ru.smartapp.core.common.dto.incoming;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.Nullable;
import ru.smartapp.core.common.dto.CharacterDto;
import ru.smartapp.core.common.dto.DeviceDto;
/**
* Сообщает о запуске смартапа. Приходит в бэкенд смартапа при передаче сообщения
*/
@Getter
@Setter
public class RunAppDto extends AbstractIncomingMessage<RunAppPayloadDto> {
@JsonProperty("payload")
private RunAppPayloadDto payload;
@Override
public @Nullable DeviceDto getDeviceDto() {
return payload.getDevice();
}
@Nullable
@Override
public CharacterDto getCharacterDto() {
return payload.getCharacter();
}
}
|
9234ee757e54d1ad466d9151e6db299282715098 | 1,585 | java | Java | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/NoOpClassFileTransformer.java | rovarga/byte-buddy | dd921d374977a642a6d8fa4654560dad6a683079 | [
"Apache-2.0"
] | 1 | 2020-10-17T08:53:44.000Z | 2020-10-17T08:53:44.000Z | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/NoOpClassFileTransformer.java | rovarga/byte-buddy | dd921d374977a642a6d8fa4654560dad6a683079 | [
"Apache-2.0"
] | null | null | null | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/NoOpClassFileTransformer.java | rovarga/byte-buddy | dd921d374977a642a6d8fa4654560dad6a683079 | [
"Apache-2.0"
] | null | null | null | 31.7 | 98 | 0.676972 | 997,099 | /*
* Copyright 2014 - 2020 Rafael Winterhalter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bytebuddy.dynamic.loading;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;
/**
* A class file transformer that does not apply a transformation.
*/
public enum NoOpClassFileTransformer implements ClassFileTransformer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* Indicates that no transformation is to applied.
*/
private static final byte[] NO_TRANSFORMATION = null;
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Array is guaranteed to be null")
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
return NO_TRANSFORMATION;
}
}
|
9234ef61c23071ceb6c1e3df1a5ef47b62a5fc54 | 2,322 | java | Java | Fatec_Saude/app/src/main/java/com/example/natanael/fatec_saude/ConnectionHosp.java | nata27junior/Projeto-Dispositivos-Movel-v2 | adaec6968e3f2249ea6a39a6613f4d794e1770c1 | [
"Apache-2.0"
] | null | null | null | Fatec_Saude/app/src/main/java/com/example/natanael/fatec_saude/ConnectionHosp.java | nata27junior/Projeto-Dispositivos-Movel-v2 | adaec6968e3f2249ea6a39a6613f4d794e1770c1 | [
"Apache-2.0"
] | null | null | null | Fatec_Saude/app/src/main/java/com/example/natanael/fatec_saude/ConnectionHosp.java | nata27junior/Projeto-Dispositivos-Movel-v2 | adaec6968e3f2249ea6a39a6613f4d794e1770c1 | [
"Apache-2.0"
] | null | null | null | 25.516484 | 99 | 0.555125 | 997,100 | package com.example.natanael.fatec_saude;
import android.os.StrictMode;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.io.InputStreamReader;
import java.util.LinkedList;
import org.json.JSONObject;
public class ConnectionHosp {
public List<Marker> getData() throws JSONException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final StringBuilder result = new StringBuilder();
URL url;
HttpURLConnection urlConnection = null;
try {
//hospital particular
url = new URL("https://api.myjson.com/bins/vn9q7");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
result.append(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(result);
List<Marker> finalResult = generateJSON(new JSONArray(result.toString()));
return finalResult;
}
public List<Marker> generateJSON(JSONArray json){
List<Marker> found = new LinkedList<Marker>();
try {
for (int i = 0; i < json.length(); i++) {
//
JSONObject obj = json.getJSONObject(i);
found.add(new Marker(obj.getDouble("lat"),obj.getDouble("lng"),
obj.getString("nome"),
obj.getString("morada1"),
obj.getString("morada2"),
obj.getString("codPostal"),
obj.getString("imagem")));
}
} catch (JSONException e) {
// handle exception
}
return found;
}
} |
9234ef96b428aaa8d63a09a1d1928506a82bc490 | 22,409 | java | Java | aws-java-sdk-cloud9/src/main/java/com/amazonaws/services/cloud9/model/DescribeEnvironmentMembershipsRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-cloud9/src/main/java/com/amazonaws/services/cloud9/model/DescribeEnvironmentMembershipsRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-cloud9/src/main/java/com/amazonaws/services/cloud9/model/DescribeEnvironmentMembershipsRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 35.068858 | 133 | 0.585747 | 997,101 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloud9.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloud9-2017-09-23/DescribeEnvironmentMemberships"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeEnvironmentMembershipsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value is
* specified, information about all environment members are returned.
* </p>
*/
private String userArn;
/**
* <p>
* The ID of the environment to get environment member information about.
* </p>
*/
private String environmentId;
/**
* <p>
* The type of environment member permissions to get information about. Available values include:
* </p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* </p>
*/
private java.util.List<String> permissions;
/**
* <p>
* During a previous call, if there are more than 25 items in the list, only the first 25 items are returned, along
* with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation
* again, adding the next token to the call. To get all of the items in the list, keep calling this operation with
* each subsequent next token that is returned, until no more next tokens are returned.
* </p>
*/
private String nextToken;
/**
* <p>
* The maximum number of environment members to get information about.
* </p>
*/
private Integer maxResults;
/**
* <p>
* The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value is
* specified, information about all environment members are returned.
* </p>
*
* @param userArn
* The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value
* is specified, information about all environment members are returned.
*/
public void setUserArn(String userArn) {
this.userArn = userArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value is
* specified, information about all environment members are returned.
* </p>
*
* @return The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value
* is specified, information about all environment members are returned.
*/
public String getUserArn() {
return this.userArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value is
* specified, information about all environment members are returned.
* </p>
*
* @param userArn
* The Amazon Resource Name (ARN) of an individual environment member to get information about. If no value
* is specified, information about all environment members are returned.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeEnvironmentMembershipsRequest withUserArn(String userArn) {
setUserArn(userArn);
return this;
}
/**
* <p>
* The ID of the environment to get environment member information about.
* </p>
*
* @param environmentId
* The ID of the environment to get environment member information about.
*/
public void setEnvironmentId(String environmentId) {
this.environmentId = environmentId;
}
/**
* <p>
* The ID of the environment to get environment member information about.
* </p>
*
* @return The ID of the environment to get environment member information about.
*/
public String getEnvironmentId() {
return this.environmentId;
}
/**
* <p>
* The ID of the environment to get environment member information about.
* </p>
*
* @param environmentId
* The ID of the environment to get environment member information about.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeEnvironmentMembershipsRequest withEnvironmentId(String environmentId) {
setEnvironmentId(environmentId);
return this;
}
/**
* <p>
* The type of environment member permissions to get information about. Available values include:
* </p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* </p>
*
* @return The type of environment member permissions to get information about. Available values include:</p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* @see Permissions
*/
public java.util.List<String> getPermissions() {
return permissions;
}
/**
* <p>
* The type of environment member permissions to get information about. Available values include:
* </p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* </p>
*
* @param permissions
* The type of environment member permissions to get information about. Available values include:</p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* @see Permissions
*/
public void setPermissions(java.util.Collection<String> permissions) {
if (permissions == null) {
this.permissions = null;
return;
}
this.permissions = new java.util.ArrayList<String>(permissions);
}
/**
* <p>
* The type of environment member permissions to get information about. Available values include:
* </p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setPermissions(java.util.Collection)} or {@link #withPermissions(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param permissions
* The type of environment member permissions to get information about. Available values include:</p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Permissions
*/
public DescribeEnvironmentMembershipsRequest withPermissions(String... permissions) {
if (this.permissions == null) {
setPermissions(new java.util.ArrayList<String>(permissions.length));
}
for (String ele : permissions) {
this.permissions.add(ele);
}
return this;
}
/**
* <p>
* The type of environment member permissions to get information about. Available values include:
* </p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* </p>
*
* @param permissions
* The type of environment member permissions to get information about. Available values include:</p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Permissions
*/
public DescribeEnvironmentMembershipsRequest withPermissions(java.util.Collection<String> permissions) {
setPermissions(permissions);
return this;
}
/**
* <p>
* The type of environment member permissions to get information about. Available values include:
* </p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* </p>
*
* @param permissions
* The type of environment member permissions to get information about. Available values include:</p>
* <ul>
* <li>
* <p>
* <code>owner</code>: Owns the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-only</code>: Has read-only access to the environment.
* </p>
* </li>
* <li>
* <p>
* <code>read-write</code>: Has read-write access to the environment.
* </p>
* </li>
* </ul>
* <p>
* If no value is specified, information about all environment members are returned.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Permissions
*/
public DescribeEnvironmentMembershipsRequest withPermissions(Permissions... permissions) {
java.util.ArrayList<String> permissionsCopy = new java.util.ArrayList<String>(permissions.length);
for (Permissions value : permissions) {
permissionsCopy.add(value.toString());
}
if (getPermissions() == null) {
setPermissions(permissionsCopy);
} else {
getPermissions().addAll(permissionsCopy);
}
return this;
}
/**
* <p>
* During a previous call, if there are more than 25 items in the list, only the first 25 items are returned, along
* with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation
* again, adding the next token to the call. To get all of the items in the list, keep calling this operation with
* each subsequent next token that is returned, until no more next tokens are returned.
* </p>
*
* @param nextToken
* During a previous call, if there are more than 25 items in the list, only the first 25 items are returned,
* along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call
* this operation again, adding the next token to the call. To get all of the items in the list, keep calling
* this operation with each subsequent next token that is returned, until no more next tokens are returned.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* During a previous call, if there are more than 25 items in the list, only the first 25 items are returned, along
* with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation
* again, adding the next token to the call. To get all of the items in the list, keep calling this operation with
* each subsequent next token that is returned, until no more next tokens are returned.
* </p>
*
* @return During a previous call, if there are more than 25 items in the list, only the first 25 items are
* returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the
* list, call this operation again, adding the next token to the call. To get all of the items in the list,
* keep calling this operation with each subsequent next token that is returned, until no more next tokens
* are returned.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* During a previous call, if there are more than 25 items in the list, only the first 25 items are returned, along
* with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation
* again, adding the next token to the call. To get all of the items in the list, keep calling this operation with
* each subsequent next token that is returned, until no more next tokens are returned.
* </p>
*
* @param nextToken
* During a previous call, if there are more than 25 items in the list, only the first 25 items are returned,
* along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call
* this operation again, adding the next token to the call. To get all of the items in the list, keep calling
* this operation with each subsequent next token that is returned, until no more next tokens are returned.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeEnvironmentMembershipsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* The maximum number of environment members to get information about.
* </p>
*
* @param maxResults
* The maximum number of environment members to get information about.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* The maximum number of environment members to get information about.
* </p>
*
* @return The maximum number of environment members to get information about.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* The maximum number of environment members to get information about.
* </p>
*
* @param maxResults
* The maximum number of environment members to get information about.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeEnvironmentMembershipsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getUserArn() != null)
sb.append("UserArn: ").append(getUserArn()).append(",");
if (getEnvironmentId() != null)
sb.append("EnvironmentId: ").append(getEnvironmentId()).append(",");
if (getPermissions() != null)
sb.append("Permissions: ").append(getPermissions()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeEnvironmentMembershipsRequest == false)
return false;
DescribeEnvironmentMembershipsRequest other = (DescribeEnvironmentMembershipsRequest) obj;
if (other.getUserArn() == null ^ this.getUserArn() == null)
return false;
if (other.getUserArn() != null && other.getUserArn().equals(this.getUserArn()) == false)
return false;
if (other.getEnvironmentId() == null ^ this.getEnvironmentId() == null)
return false;
if (other.getEnvironmentId() != null && other.getEnvironmentId().equals(this.getEnvironmentId()) == false)
return false;
if (other.getPermissions() == null ^ this.getPermissions() == null)
return false;
if (other.getPermissions() != null && other.getPermissions().equals(this.getPermissions()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getUserArn() == null) ? 0 : getUserArn().hashCode());
hashCode = prime * hashCode + ((getEnvironmentId() == null) ? 0 : getEnvironmentId().hashCode());
hashCode = prime * hashCode + ((getPermissions() == null) ? 0 : getPermissions().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
return hashCode;
}
@Override
public DescribeEnvironmentMembershipsRequest clone() {
return (DescribeEnvironmentMembershipsRequest) super.clone();
}
}
|
9234efa82d6cb75c747be37ff0b2d23dccccfc12 | 789 | java | Java | gen/edu/clemson/resolve/jetbrains/psi/ResTypeReprDecl.java | Welchd1/resolve-intellij-plugin-v4 | 282bbd7e5c4fb5533a48536e2dbaae989e3efce3 | [
"BSD-3-Clause"
] | 1 | 2020-01-17T00:28:12.000Z | 2020-01-17T00:28:12.000Z | gen/edu/clemson/resolve/jetbrains/psi/ResTypeReprDecl.java | Welchd1/resolve-intellij-plugin-v4 | 282bbd7e5c4fb5533a48536e2dbaae989e3efce3 | [
"BSD-3-Clause"
] | 6 | 2016-03-20T21:19:11.000Z | 2017-03-16T23:29:23.000Z | gen/edu/clemson/resolve/jetbrains/psi/ResTypeReprDecl.java | Welchd1/resolve-intellij-plugin-v4 | 282bbd7e5c4fb5533a48536e2dbaae989e3efce3 | [
"BSD-3-Clause"
] | 4 | 2016-01-07T19:23:53.000Z | 2020-09-22T02:41:32.000Z | 18.785714 | 62 | 0.773131 | 997,102 | // This is a generated file. Not intended for manual editing.
package edu.clemson.resolve.jetbrains.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.ResolveState;
public interface ResTypeReprDecl extends ResTypeLikeNodeDecl {
@Nullable
ResConventionsClause getConventionsClause();
@Nullable
ResCorrespondenceClause getCorrespondenceClause();
@Nullable
ResExemplarDecl getExemplarDecl();
@Nullable
ResType getType();
@Nullable
ResTypeImplInit getTypeImplInit();
@NotNull
PsiElement getFamilyType();
@Nullable
PsiElement getSemicolon();
@NotNull
PsiElement getIdentifier();
@Nullable
PsiElement getIs();
@Nullable
ResType getResTypeInner(ResolveState context);
}
|
9234f07fd741c4f6717fc9424108e378317c5acc | 1,330 | java | Java | ctm-serializer/src/test/java/Test.java | bb/ctm-writer | 9fb0cff2dc56f8ae5e7667667557a062f7b69191 | [
"Apache-2.0"
] | null | null | null | ctm-serializer/src/test/java/Test.java | bb/ctm-writer | 9fb0cff2dc56f8ae5e7667667557a062f7b69191 | [
"Apache-2.0"
] | null | null | null | ctm-serializer/src/test/java/Test.java | bb/ctm-writer | 9fb0cff2dc56f8ae5e7667667557a062f7b69191 | [
"Apache-2.0"
] | null | null | null | 35 | 103 | 0.633835 | 997,103 | import java.io.File;
import junit.framework.TestCase;
import org.tmapi.core.TopicMap;
import org.tmapi.core.TopicMapSystemFactory;
import org.tmapix.io.CTMTopicMapReader;
/*******************************************************************************
* Copyright 2010, Topic Map Lab ( http://www.topicmapslab.de )
*
* 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.
******************************************************************************/
/**
* @author Sven Krosse
*
*/
public class Test extends TestCase {
public void test() throws Exception{
TopicMap tm = TopicMapSystemFactory.newInstance().newTopicMapSystem().createTopicMap("http://lala");
CTMTopicMapReader reader = new CTMTopicMapReader(tm, new File("src/test/resources/ex.ctm"));
reader.read();
}
}
|
9234f248393590888c36d0b06c9d0583bc82609f | 7,971 | java | Java | xml/impl/src/com/intellij/psi/formatter/xml/AbstractSyntheticBlock.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | xml/impl/src/com/intellij/psi/formatter/xml/AbstractSyntheticBlock.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | null | null | null | xml/impl/src/com/intellij/psi/formatter/xml/AbstractSyntheticBlock.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:06.000Z | 2018-10-03T12:35:06.000Z | 32.668033 | 133 | 0.72814 | 997,104 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.formatter.xml;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTokenType;
import java.util.List;
public abstract class AbstractSyntheticBlock implements Block {
protected final Indent myIndent;
protected final XmlFormattingPolicy myXmlFormattingPolicy;
protected final ASTNode myEndTreeNode;
protected final ASTNode myStartTreeNode;
private final XmlTag myTag;
public AbstractSyntheticBlock(List<Block> subBlocks, Block parent, XmlFormattingPolicy policy, Indent indent) {
myEndTreeNode = getLastNode(subBlocks);
myStartTreeNode = getFirstNode(subBlocks);
myIndent = indent;
myXmlFormattingPolicy = policy;
if (parent instanceof AbstractXmlBlock) {
myTag = ((AbstractXmlBlock)parent).getTag();
}
else if (parent instanceof AbstractSyntheticBlock) {
myTag = ((AbstractSyntheticBlock)parent).getTag();
} else {
throw new IllegalStateException("Parent should be AbstractXmlBlock or AbstractSyntheticBlock, but it is " + parent.getClass());
}
}
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.xml.AbstractSyntheticBlock");
public boolean shouldKeepWhiteSpacesInside() {
return myTag != null && myXmlFormattingPolicy.keepWhiteSpacesInsideTag(myTag);
}
private ASTNode getFirstNode(final List<Block> subBlocks) {
LOG.assertTrue(!subBlocks.isEmpty());
final Block firstBlock = subBlocks.get(0);
if (firstBlock instanceof AbstractBlock) {
return ((AbstractBlock)firstBlock).getNode();
}
else {
return getFirstNode(firstBlock.getSubBlocks());
}
}
private ASTNode getLastNode(final List<Block> subBlocks) {
LOG.assertTrue(!subBlocks.isEmpty());
final Block lastBlock = subBlocks.get(subBlocks.size() - 1);
if (lastBlock instanceof AbstractBlock) {
return ((AbstractBlock)lastBlock).getNode();
}
else {
return getLastNode(lastBlock.getSubBlocks());
}
}
private boolean isEndOfTag() {
return myEndTreeNode.getElementType() == XmlTokenType.XML_TAG_END;
}
@Override
public Wrap getWrap() {
return null;
}
@Override
public Indent getIndent() {
return myIndent;
}
@Override
public Alignment getAlignment() {
return null;
}
protected static boolean isXmlTagName(final IElementType type1, final IElementType type2) {
if ((type1 == XmlTokenType.XML_NAME || type1 == XmlTokenType.XML_TAG_NAME) && (type2 == XmlTokenType.XML_TAG_END)) return true;
if ((type1 == XmlTokenType.XML_NAME || type1 == XmlTokenType.XML_TAG_NAME) && (type2 == XmlTokenType.XML_EMPTY_ELEMENT_END)) {
return true;
}
if (type1 == XmlElementType.XML_ATTRIBUTE && type2 == XmlTokenType.XML_EMPTY_ELEMENT_END) return true;
return type1 == XmlElementType.XML_ATTRIBUTE && type2 == XmlTokenType.XML_TAG_END;
}
public boolean endsWithText() {
return myEndTreeNode.getElementType() == XmlElementType.XML_TEXT ||
myEndTreeNode.getElementType() == XmlTokenType.XML_DATA_CHARACTERS ||
myEndTreeNode.getElementType() == XmlTokenType.XML_CHAR_ENTITY_REF ||
myEndTreeNode.getElementType() == XmlElementType.XML_ENTITY_REF;
}
public boolean isTagDescription() {
final ASTNode startTreeNode = myStartTreeNode;
return isTagDescription(startTreeNode);
}
private static boolean isTagDescription(final ASTNode startTreeNode) {
return startTreeNode.getElementType() == XmlTokenType.XML_START_TAG_START ||
startTreeNode.getElementType() == XmlTokenType.XML_END_TAG_START;
}
public boolean startsWithText() {
return myStartTreeNode.getElementType() == XmlElementType.XML_TEXT ||
myStartTreeNode.getElementType() == XmlTokenType.XML_DATA_CHARACTERS ||
myStartTreeNode.getElementType() == XmlTokenType.XML_CHAR_ENTITY_REF ||
myStartTreeNode.getElementType() == XmlElementType.XML_ENTITY_REF;
}
public boolean endsWithTextElement() {
if (endsWithText()) return true;
if (isEndOfTag() && myXmlFormattingPolicy.isTextElement(getTag())) return true;
return isTextTag(myEndTreeNode);
}
protected XmlTag getTag() {
return myTag;
}
public boolean startsWithTextElement() {
if (startsWithText()) return true;
if (isStartOfTag() && myXmlFormattingPolicy.isTextElement(getTag())) return true;
return isTextTag(myStartTreeNode);
}
private boolean isTextTag(final ASTNode treeNode) {
return isXmlTag(treeNode) && myXmlFormattingPolicy.isTextElement((XmlTag)SourceTreeToPsiMap.treeElementToPsi(treeNode));
}
private boolean isXmlTag(final ASTNode treeNode) {
return (treeNode.getPsi() instanceof XmlTag);
}
private boolean isStartOfTag() {
return isTagDescription(myStartTreeNode);
}
protected static TextRange calculateTextRange(final List<Block> subBlocks) {
return new TextRange(subBlocks.get(0).getTextRange().getStartOffset(),
subBlocks.get(subBlocks.size() - 1).getTextRange().getEndOffset());
}
@Override
public boolean isIncomplete() {
return getSubBlocks().get(getSubBlocks().size() - 1).isIncomplete();
}
public boolean startsWithTag() {
return isXmlTag(myStartTreeNode);
}
public XmlTag getStartTag() {
return (XmlTag)myStartTreeNode.getPsi();
}
public boolean endsWithTag() {
return isXmlTag(myEndTreeNode);
}
public boolean isJspTextBlock() {
return false;
}
public boolean isJspxTextBlock() {
return false;
}
/**
* Checks if the block contains a single node which belongs to the outer (template) language.
*
* @return True if it does, False otherwise.
*/
public boolean isOuterLanguageBlock() {
return (myStartTreeNode == myEndTreeNode) && (myStartTreeNode instanceof OuterLanguageElement);
}
@Override
public boolean isLeaf() {
return false;
}
public boolean startsWithCDATA() {
return isCDATA(myStartTreeNode.getFirstChildNode());
}
private boolean isCDATA(final ASTNode node) {
return node != null && node.getElementType() == XmlElementType.XML_CDATA;
}
public boolean containsCDATA() {
return myStartTreeNode.getElementType() == XmlTokenType.XML_CDATA_START &&
myEndTreeNode.getElementType() == XmlTokenType.XML_CDATA_END;
}
public boolean endsWithCDATA() {
return isCDATA(myStartTreeNode.getLastChildNode());
}
public boolean insertLineFeedAfter() {
final List<Block> subBlocks = getSubBlocks();
final Block lastBlock = subBlocks.get(subBlocks.size() - 1);
if (lastBlock instanceof XmlTagBlock) {
return insertLineFeedAfter(((XmlTagBlock)lastBlock).getTag());
}
if (endsWithText()) {
return insertLineFeedAfter(myTag);
}
return false;
}
protected boolean insertLineFeedAfter(final XmlTag tag) {
return myXmlFormattingPolicy.getWrappingTypeForTagBegin(tag) == WrapType.ALWAYS;
}
}
|
9234f36a6e2c40744f74369f97d3ef06c4cd13b5 | 3,424 | java | Java | elt/src/main/java/com/leidoslabs/holeshot/elt/gpuimage/HistogramType.java | LeidosLabs/holeshot | b3aa04a84059e3a4c07d42ff9a46cc37f443eb3d | [
"Apache-2.0"
] | 2 | 2020-03-25T00:51:06.000Z | 2020-04-29T08:37:22.000Z | elt/src/main/java/com/leidoslabs/holeshot/elt/gpuimage/HistogramType.java | LeidosLabs/holeshot | b3aa04a84059e3a4c07d42ff9a46cc37f443eb3d | [
"Apache-2.0"
] | 10 | 2020-02-13T21:54:56.000Z | 2021-12-18T18:26:09.000Z | elt/src/main/java/com/leidoslabs/holeshot/elt/gpuimage/HistogramType.java | LeidosLabs/holeshot | b3aa04a84059e3a4c07d42ff9a46cc37f443eb3d | [
"Apache-2.0"
] | 2 | 2020-02-17T11:46:38.000Z | 2021-01-06T21:26:53.000Z | 49.623188 | 107 | 0.775409 | 997,105 | /*
* Licensed to Leidos, Inc. under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information regarding copyright ownership.
* Leidos, Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.leidoslabs.holeshot.elt.gpuimage;
import java.util.Arrays;
import java.util.List;
/**
* Enum for histogram type, includes compatible vertex shaders
*/
public enum HistogramType {
RED(Arrays.asList(Shaders.RED_SAMPLING_SHADER)),
GREEN(Arrays.asList(Shaders.GREEN_SAMPLING_SHADER)),
BLUE(Arrays.asList(Shaders.BLUE_SAMPLING_SHADER)),
// LUMINANCE(Arrays.asList(Shaders.LUMINANCE_SAMPLING_SHADER)),
RGB(Arrays.asList(Shaders.RED_SAMPLING_SHADER,
Shaders.GREEN_SAMPLING_SHADER,
Shaders.BLUE_SAMPLING_SHADER));
private List<String> vertexShaders;
private HistogramType(List<String> vertexShaders) {
this.vertexShaders = vertexShaders;
}
public List<String> getVertexShaders() {
return vertexShaders;
}
public static class Shaders {
// Names of the shader files, without extensions
public static final String PASSTHROUGH_VERTEX_SHADER = "PassthroughVertexShader.vp";
public static final String PASSTHROUGH_ZORDER_VERTEX_SHADER = "PassthroughZOrderVertexShader.vp";
public static final String ALL_FOR_ONE_SHADER = "AllForOneShader.vp";
public static final String EFIRST_SHADER = "eFirstShader.fp";
public static final String EMIN_SHADER = "eMinShader.fp";
public static final String EMAX_SHADER = "eMaxShader.fp";
public static final String ELAST_SHADER = "eLastShader.fp";
public static final String CONSTANT_SHADER = "ConstantShader.fp";
public static final String RED_SAMPLING_SHADER = "HistogramRedSampling.vp";
public static final String GREEN_SAMPLING_SHADER = "HistogramGreenSampling.vp";
public static final String BLUE_SAMPLING_SHADER = "HistogramBlueSampling.vp";
public static final String HISTOGRAM_ACCUMULATION_SHADER = "HistogramAccumulation_GL.fp";
public static final String CUMULATIVE_HISTOGRAM_SHADER = "CumulativeHistogramShader.fp";
public static final String SUMMED_AREA_HORIZONTAL_PHASE_SHADER = "SummedAreaHorizontalPhase.fp";
public static final String SUMMED_AREA_VERTICAL_PHASE_SHADER = "SummedAreaVerticalPhase.fp";
public static final String EQUALIZATION_SHADER = "EqualizationShader.fp";
public static final String DRA_PARAMETERS_SHADER = "DRAParametersShader.fp";
public static final String TTC_SHADER = "ToneTransferCurveShader.fp";
public static final String MOSAIC_FRAGMENT_SHADER = "MosaicShader.fp";
public static final String MOSAIC_VERTEX_SHADER = "MosaicShader.vp";
public static final String INTERPOLATED_FRAGMENT_SHADER = "InterpolatedShader.fp";
public static final String INTERPOLATED_VERTEX_SHADER = "InterpolatedShader.vp";
}
}; |
9234f48f18522be25fec49625b04854ec6ba067d | 1,673 | java | Java | src/net/alastairwyse/aspectjdemo/ConfigurationSettings.java | alastairwyse/AspectJDemo | 0f5b03eacacc9576f9701f1066ed0be287596238 | [
"Apache-2.0"
] | null | null | null | src/net/alastairwyse/aspectjdemo/ConfigurationSettings.java | alastairwyse/AspectJDemo | 0f5b03eacacc9576f9701f1066ed0be287596238 | [
"Apache-2.0"
] | null | null | null | src/net/alastairwyse/aspectjdemo/ConfigurationSettings.java | alastairwyse/AspectJDemo | 0f5b03eacacc9576f9701f1066ed0be287596238 | [
"Apache-2.0"
] | 1 | 2021-03-13T04:17:12.000Z | 2021-03-13T04:17:12.000Z | 37.177778 | 134 | 0.729827 | 997,106 | /*
* Copyright 2015 Alastair Wyse (http://www.oraclepermissiongenerator.net/aspectjdemo/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.alastairwyse.aspectjdemo;
/**
* Container class holding configuration settings for the aspectjdemo program.
* @author Alastair Wyse
*/
public class ConfigurationSettings {
/**
* Initialises a new instance of the ConfigurationSettings class.
* @param metricLogFilePath The full path to the configuration file for the application.
* @param metricEventWriteFrequency The frequency in which metric events should be written to the metric log file in milliseonds.
*/
public ConfigurationSettings(String metricLogFilePath, int metricEventWriteFrequency) {
MetricLogFilePath = metricLogFilePath;
MetricEventWriteFrequency = metricEventWriteFrequency;
}
/**
* The full path to the configuration file for the application.
*/
public String MetricLogFilePath;
/**
* The frequency in which metric events should be written to the metric log file in milliseonds.
*/
public int MetricEventWriteFrequency;
}
|
9234f53dc01e3aa53337c7db7eaa2be3fbf28543 | 1,255 | java | Java | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/network/cluster/function/NetworkClusterToAttachNetworkToVdsGroupParameterTransformer.java | UranusBlockStack/ovirt-engine | fe3c90ed3e74e6af9497c826c82e653382946ae1 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/network/cluster/function/NetworkClusterToAttachNetworkToVdsGroupParameterTransformer.java | UranusBlockStack/ovirt-engine | fe3c90ed3e74e6af9497c826c82e653382946ae1 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/network/cluster/function/NetworkClusterToAttachNetworkToVdsGroupParameterTransformer.java | UranusBlockStack/ovirt-engine | fe3c90ed3e74e6af9497c826c82e653382946ae1 | [
"Apache-2.0"
] | null | null | null | 35.857143 | 92 | 0.8 | 997,107 | package org.ovirt.engine.core.bll.network.cluster.function;
import java.util.Objects;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.ovirt.engine.core.common.action.AttachNetworkToVdsGroupParameter;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.dao.network.NetworkDao;
import org.ovirt.engine.core.utils.linq.Function;
@Singleton
@Named
final class NetworkClusterToAttachNetworkToVdsGroupParameterTransformer
implements Function<NetworkCluster, AttachNetworkToVdsGroupParameter> {
private final NetworkDao networkDao;
@Inject
NetworkClusterToAttachNetworkToVdsGroupParameterTransformer(NetworkDao networkDao) {
Objects.requireNonNull(networkDao, "networkDao cannot be null");
this.networkDao = networkDao;
}
@Override
public AttachNetworkToVdsGroupParameter eval(NetworkCluster networkCluster) {
final Network network = networkDao.get(networkCluster.getNetworkId());
network.setCluster(networkCluster);
return new AttachNetworkToVdsGroupParameter(networkCluster.getClusterId(), network);
}
}
|
9234f5d14d4fa820f76f405d9cef6191b84178b3 | 2,673 | java | Java | Thoth/src/controllers/MainViewLogisticController.java | mjochab/PZ_2019_Lab3_Gr7 | d4d3fdb665b66a26322fe32f7b046ab69ce272f9 | [
"MIT"
] | null | null | null | Thoth/src/controllers/MainViewLogisticController.java | mjochab/PZ_2019_Lab3_Gr7 | d4d3fdb665b66a26322fe32f7b046ab69ce272f9 | [
"MIT"
] | 29 | 2019-03-23T18:06:20.000Z | 2019-05-27T23:18:59.000Z | Thoth/src/controllers/MainViewLogisticController.java | mjochab/PZ_2019_Lab3_Gr7 | d4d3fdb665b66a26322fe32f7b046ab69ce272f9 | [
"MIT"
] | 2 | 2019-03-10T22:22:34.000Z | 2019-03-23T16:34:44.000Z | 37.125 | 226 | 0.697344 | 997,108 | package controllers;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;
import log.ThothLoggerConfigurator;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import static controllers.MainWindowController.sessionContext;
/**
* Kontroler głównego widoku logistyka
*/
public class MainViewLogisticController implements Initializable {
private static final Logger logger = Logger.getLogger(MainViewLogisticController.class);
@FXML
MenuItem logout, back;
@FXML
Parent root;
@FXML
private Label sessionInfo;
/**
* Metoda obsługijąca prycik powrotu i wylogowywania.
* Wczytuje odpowiedni widok w zależności w któryym oknie się znajdujemy.
*
* @param actionEvent pozwala zlokalizować z jakiego okna wywołano metodę
* @throws IOException występuje przy odczycie/zapisie pliku
*/
public void menuItemAction(ActionEvent actionEvent) throws IOException { //wylogowanie na MENU ITEM
Stage stage = (Stage) root.getScene().getWindow();
if (actionEvent.getSource() == logout) {
root = FXMLLoader.load(getClass().getResource("/fxmlfiles/MainWindow.fxml"));
} else {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxmlfiles/choose_employee.fxml"));
root = loader.load();
MainWindowController mainController = loader.getController();
mainController.setComboList();
}
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
logger.addAppender(ThothLoggerConfigurator.getFileAppender());
if (sessionContext.getCurrentLoggedUser().getUserId() == 1) {
if (back != null) {
back.setVisible(true);
} else {
logger.warn("BACK is null");
}
}
logger.warn("Aktualnie zaloogwany User: " + sessionContext.getCurrentLoggedUser());
logger.warn("Obiekt zalogowanego User'a: " + sessionContext.getCurrentLoggedShop());
logger.warn("Hello from MainController");
sessionInfo.setText(" Zalogowano jako: "+sessionContext.getCurrentLoggedUser().getFirstName()+" "+sessionContext.getCurrentLoggedUser().getLastName()+" / Lokalizacja: "+sessionContext.getCurrentLoggedShop().getCity());
}
}
|
9234f79cabfe917b2bf8921319adf992f4133f37 | 197 | java | Java | chapter_004/src/main/java/ru/job4j/generic/UserStore.java | YuryMatskevich/ymatskevich | 12b9c26a12712308bc53350961168506dae5c52c | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/generic/UserStore.java | YuryMatskevich/ymatskevich | 12b9c26a12712308bc53350961168506dae5c52c | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/generic/UserStore.java | YuryMatskevich/ymatskevich | 12b9c26a12712308bc53350961168506dae5c52c | [
"Apache-2.0"
] | 1 | 2020-03-23T18:12:28.000Z | 2020-03-23T18:12:28.000Z | 16.416667 | 52 | 0.654822 | 997,109 | package ru.job4j.generic;
/**
* @author Yury Matskevich
* @since 0.1
*/
public class UserStore extends AbstractStore<User> {
public UserStore(int maxSize) {
super(maxSize);
}
}
|
9234f8e5bd99fc62f8953519ee8de30545b72088 | 1,139 | java | Java | src/oose2015/items/Armor.java | KasperHdL/Arena | be210bd325e602d9ae9de7bd1c64b9facfe6e2b0 | [
"MIT"
] | 1 | 2015-04-18T10:56:14.000Z | 2015-04-18T10:56:14.000Z | src/oose2015/items/Armor.java | KasperHdL/OOSE2015 | be210bd325e602d9ae9de7bd1c64b9facfe6e2b0 | [
"MIT"
] | 45 | 2015-03-12T09:46:10.000Z | 2015-07-02T22:59:12.000Z | src/oose2015/items/Armor.java | KasperHdL/Arena | be210bd325e602d9ae9de7bd1c64b9facfe6e2b0 | [
"MIT"
] | 1 | 2015-03-11T09:10:21.000Z | 2015-03-11T09:10:21.000Z | 20.709091 | 58 | 0.542581 | 997,110 | package oose2015.items;
/**
* @author itai.yavin
* <p/>
* Description:
* Child of item class.
* Armor class item.
* <p/>
*/
public class Armor extends Item{
public float speedReduction, damageReduction;
/**
* Armor constructor
* Sets armor variables
* @param level - level of armor
*/
public Armor(int level){
this.level = level;
if(level < 10)
speedReduction = level * 0.03f;
else if(level <= 20)
speedReduction = .30f + (level - 10) * 0.02f;
else if(level > 20)
speedReduction = 0.50f;
if(level < 10)
damageReduction = level * 0.02f;
else if(level <= 20)
damageReduction = .20f + (level - 10) * 0.01f;
else if(level > 20)
damageReduction = 0.30f;
}
/**
* Modifies speedReduction variable
* @return
*/
public float getSpeedModifier(){
return 1f - speedReduction;
}
/**
* Modifies damageReduction variable
* @return
*/
public float getDamageModifier(){
return 1f - damageReduction;
}
}
|
9234f904dd5b80e69b8126d8e44e0e32ba7261f2 | 1,160 | java | Java | web-server-impl/src/main/java/com/intellij/javaee/web/WebModel.java | consulo/consulo-jakartaee | c5f7b05abfc15965e4fa0fb69eaa723579fd5cee | [
"Apache-2.0"
] | 3 | 2017-08-26T17:21:49.000Z | 2021-08-05T03:18:23.000Z | web-server-impl/src/main/java/com/intellij/javaee/web/WebModel.java | consulo/consulo-javaee | fc9ba10b6a05d9add6f7f44168b7260f83962e9b | [
"Apache-2.0"
] | 34 | 2016-08-13T11:54:50.000Z | 2021-10-22T03:09:28.000Z | web-server-impl/src/main/java/com/intellij/javaee/web/WebModel.java | consulo/consulo-jakartaee | c5f7b05abfc15965e4fa0fb69eaa723579fd5cee | [
"Apache-2.0"
] | 1 | 2019-10-05T10:31:52.000Z | 2019-10-05T10:31:52.000Z | 27.619048 | 76 | 0.747414 | 997,111 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.javaee.web;
import com.intellij.javaee.model.CommonListener;
import javax.annotation.Nonnull;
import java.util.List;
/**
* @author Dmitry Avdeev
* @see com.intellij.javaee.web.facet.WebFacet#getWebModel()
*/
public interface WebModel {
List<CommonServlet> getServlets();
CommonServlet findServlet(@Nonnull String name);
CommonFilter findFilter(@Nonnull String name);
List<CommonServletMapping<CommonServlet>> getServletMappings();
List<CommonFilter> getFilters();
List<CommonListener> getListeners();
}
|
9234f908a8b0339421225f13b44702aebfb21d6a | 18,453 | java | Java | BaseLibrary/src/main/java/come/haolin_android/mvp/baselibrary/imagepicker/ImagePicker.java | ntub-109205/MemeMaker2.0 | f2e7be3d4497068d36a76b1923c0a3ecff2d7fc1 | [
"MIT"
] | null | null | null | BaseLibrary/src/main/java/come/haolin_android/mvp/baselibrary/imagepicker/ImagePicker.java | ntub-109205/MemeMaker2.0 | f2e7be3d4497068d36a76b1923c0a3ecff2d7fc1 | [
"MIT"
] | null | null | null | BaseLibrary/src/main/java/come/haolin_android/mvp/baselibrary/imagepicker/ImagePicker.java | ntub-109205/MemeMaker2.0 | f2e7be3d4497068d36a76b1923c0a3ecff2d7fc1 | [
"MIT"
] | null | null | null | 34.882798 | 181 | 0.664933 | 997,112 | package come.haolin_android.mvp.baselibrary.imagepicker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.FileProvider;
import androidx.core.util.Pair;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import come.haolin_android.mvp.baselibrary.R;
import come.haolin_android.mvp.baselibrary.bean.ImageFolder;
import come.haolin_android.mvp.baselibrary.bean.ImageItem;
import come.haolin_android.mvp.baselibrary.imagepicker.loader.ImageLoader;
import come.haolin_android.mvp.baselibrary.imagepicker.ui.ImageGridActivity;
import come.haolin_android.mvp.baselibrary.imagepicker.ui.ImageViewerActivity;
import come.haolin_android.mvp.baselibrary.imagepicker.util.ProviderUtil;
import come.haolin_android.mvp.baselibrary.imagepicker.util.Utils;
import come.haolin_android.mvp.baselibrary.imagepicker.view.CropImageView;
public class ImagePicker {
public static final String TAG = ImagePicker.class.getSimpleName();
public static final int REQUEST_CODE_TAKE = 1001;
public static final int REQUEST_CODE_CROP = 1002;
public static final int REQUEST_CODE_PREVIEW = 1003;
public static final int RESULT_CODE_ITEMS = 1004;
public static final int RESULT_CODE_BACK = 1005;
public static final String EXTRA_RESULT_ITEMS = "extra_result_items";
public static final String EXTRA_SELECTED_IMAGE_POSITION = "selected_image_position";
public static final String EXTRA_IMAGE_ITEMS = "extra_image_items";
public static final String EXTRA_FROM_ITEMS = "extra_from_items";
public static final String EXTRA_EXIT_POSITION = "extra_exit_position";
private static ImagePicker mInstance;
private boolean multiMode = true; //图片选择模式
private int selectLimit = 9; //最大选择图片数量
private boolean crop = true; //裁剪
private boolean showCamera = true; //显示相机
private boolean isSaveRectangle = false; //裁剪后的图片是否是矩形,否者跟随裁剪框的形状
private int outPutX = 800; //裁剪保存宽度
private int outPutY = 800; //裁剪保存高度
private int focusWidth = 280; //焦点框的宽度
private int focusHeight = 280; //焦点框的高度
private ImageLoader imageLoader; //图片加载器
private CropImageView.Style style = CropImageView.Style.RECTANGLE; //裁剪框的形状
private File cropCacheFolder;
private File takeImageFile;
private ArrayList<ImageItem> mSelectedImages = new ArrayList<>(); //选中的图片集合
private List<ImageFolder> mImageFolders; //所有的图片文件夹
private int mCurrentImageFolderPosition = 0; //当前选中的文件夹位置 0表示所有图片
private List<OnPictureSelectedListener> mImageSelectedListeners; // 图片选中的监听回调
private OnSelectedListener onImageSelectedListener;
private boolean shareView = true;
private MediaType loadType = MediaType.IMAGE;
private List<String> viewerItem;
private ImagePicker() {
}
public static ImagePicker getInstance() {
if (mInstance == null) {
synchronized (ImagePicker.class) {
if (mInstance == null) {
mInstance = new ImagePicker();
}
}
}
return mInstance;
}
/**
* 根据系统时间、前缀、后缀产生一个文件
*/
public static File createFile(File folder, String prefix, String suffix) {
if (!folder.exists() || !folder.isDirectory()) folder.mkdirs();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.TAIWAN);
String filename = prefix + dateFormat.format(new Date(System.currentTimeMillis())) + suffix;
return new File(folder, filename);
}
/**
* 扫描图片
*/
public static void galleryAddPic(Context context, File file) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
public void shareView(boolean shareView) {
this.shareView = shareView;
}
public boolean isShareView() {
return shareView;
}
public boolean isMultiMode() {
return multiMode;
}
public ImagePicker multiMode(boolean multiMode) {
this.multiMode = multiMode;
return this;
}
public int getSelectLimit() {
return selectLimit;
}
public ImagePicker selectLimit(int selectLimit) {
this.selectLimit = selectLimit;
return this;
}
public boolean isCrop() {
return crop;
}
public ImagePicker crop(boolean crop) {
this.crop = crop;
return this;
}
public ImagePicker loadType(MediaType loadType) {
this.loadType = loadType;
return this;
}
public boolean isShowCamera() {
return showCamera;
}
public ImagePicker showCamera(boolean showCamera) {
this.showCamera = showCamera;
return this;
}
public boolean isSaveRectangle() {
return isSaveRectangle;
}
public ImagePicker saveRectangle(boolean isSaveRectangle) {
this.isSaveRectangle = isSaveRectangle;
return this;
}
public int getOutPutX() {
return outPutX;
}
public ImagePicker outPutX(int outPutX) {
this.outPutX = outPutX;
return this;
}
public int getOutPutY() {
return outPutY;
}
public ImagePicker outPutY(int outPutY) {
this.outPutY = outPutY;
return this;
}
public int getFocusWidth() {
return focusWidth;
}
public ImagePicker focusWidth(int focusWidth) {
this.focusWidth = focusWidth;
return this;
}
public int getFocusHeight() {
return focusHeight;
}
public ImagePicker focusHeight(int focusHeight) {
this.focusHeight = focusHeight;
return this;
}
public File getTakeImageFile() {
return takeImageFile;
}
public File getCropCacheFolder(Context context) {
if (cropCacheFolder == null) {
cropCacheFolder = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + context.getPackageName() + "/ImagePicker/cropTemp/");
cropCacheFolder.mkdirs();
}
return cropCacheFolder;
}
public ImagePicker cropCacheFolder(File cropCacheFolder) {
this.cropCacheFolder = cropCacheFolder;
return this;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
public ImagePicker imageLoader(ImageLoader imageLoader) {
this.imageLoader = imageLoader;
return this;
}
public CropImageView.Style getStyle() {
return style;
}
public ImagePicker style(CropImageView.Style style) {
this.style = style;
return this;
}
public List<ImageFolder> getImageFolders() {
return mImageFolders;
}
public ImagePicker imageFolders(List<ImageFolder> imageFolders) {
mImageFolders = imageFolders;
return this;
}
public int getCurrentImageFolderPosition() {
return mCurrentImageFolderPosition;
}
public ImagePicker currentImageFolderPosition(int mCurrentSelectedImageSetPosition) {
mCurrentImageFolderPosition = mCurrentSelectedImageSetPosition;
return this;
}
public ArrayList<ImageItem> getCurrentImageFolderItems() {
return mImageFolders.get(mCurrentImageFolderPosition).images;
}
public boolean isSelect(ImageItem item) {
return mSelectedImages.contains(item);
}
public int getSelectImageCount() {
if (mSelectedImages == null) {
return 0;
}
return mSelectedImages.size();
}
public ArrayList<ImageItem> getSelectedImages() {
return mSelectedImages;
}
public ImagePicker selectedImages(ArrayList<ImageItem> selectedImages) {
if (selectedImages == null) {
return null;
}
this.mSelectedImages = selectedImages;
return this;
}
public void clearSelectedImages() {
if (mSelectedImages != null) mSelectedImages.clear();
}
public void clear() {
if (mImageSelectedListeners != null) {
mImageSelectedListeners.clear();
mImageSelectedListeners = null;
}
if (mImageFolders != null) {
mImageFolders.clear();
mImageFolders = null;
}
if (mSelectedImages != null) {
mSelectedImages.clear();
}
mCurrentImageFolderPosition = 0;
}
/**
* 拍照的方法
*/
@Deprecated
public void takePicture(Activity activity, int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
if (Utils.existSDCard())
takeImageFile = new File(Environment.getExternalStorageDirectory(), "/DCIM/camera/");
else takeImageFile = Environment.getDataDirectory();
takeImageFile = createFile(takeImageFile, "IMG_", ".jpg");
if (takeImageFile != null) {
// 默认情况下,即不需要指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
// 照相机有自己默认的存储路径,拍摄的照片将返回一个缩略图。如果想访问原始图片,
// 可以通过dat extra能够得到原始图片位置。即,如果指定了目标uri,data就没有数据,
// 如果没有指定uri,则data就返回有数据!
Uri uri;
if (VERSION.SDK_INT <= VERSION_CODES.M) {
uri = Uri.fromFile(takeImageFile);
} else {
/**
* 7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider
* 并且这样可以解决MIUI系统上拍照返回size为0的情况
*/
uri = FileProvider.getUriForFile(activity, ProviderUtil.getFileProviderName(activity), takeImageFile);
//加入uri权限 要不三星手机不能拍照
List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
activity.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
Log.e("nanchen", ProviderUtil.getFileProviderName(activity));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
}
activity.startActivityForResult(takePictureIntent, requestCode);
}
public void addOnPictureSelectedListener(OnPictureSelectedListener l) {
if (mImageSelectedListeners == null) mImageSelectedListeners = new ArrayList<>();
mImageSelectedListeners.add(l);
}
public void removeOnPictureSelectedListener(OnPictureSelectedListener l) {
if (mImageSelectedListeners == null) return;
mImageSelectedListeners.remove(l);
}
public void addSelectedImageItem(int position, ImageItem item, boolean isAdd) {
if (isAdd) mSelectedImages.add(item);
else mSelectedImages.remove(item);
notifyImageSelectedChanged(position, item, isAdd);
}
private void notifyImageSelectedChanged(int position, ImageItem item, boolean isAdd) {
if (mImageSelectedListeners == null) return;
for (OnPictureSelectedListener l : mImageSelectedListeners) {
l.onImageSelected(position, item, isAdd);
}
}
/**
* 用于手机内存不足,进程被系统回收,重启时的状态恢复
*/
public void restoreInstanceState(Bundle savedInstanceState) {
cropCacheFolder = (File) savedInstanceState.getSerializable("cropCacheFolder");
takeImageFile = (File) savedInstanceState.getSerializable("takeImageFile");
imageLoader = savedInstanceState.getParcelable("imageLoader");
style = (CropImageView.Style) savedInstanceState.getSerializable("style");
multiMode = savedInstanceState.getBoolean("multiMode");
crop = savedInstanceState.getBoolean("crop");
showCamera = savedInstanceState.getBoolean("showCamera");
isSaveRectangle = savedInstanceState.getBoolean("isSaveRectangle");
selectLimit = savedInstanceState.getInt("selectLimit");
outPutX = savedInstanceState.getInt("outPutX");
outPutY = savedInstanceState.getInt("outPutY");
focusWidth = savedInstanceState.getInt("focusWidth");
focusHeight = savedInstanceState.getInt("focusHeight");
}
/**
* 用于手机内存不足,进程被系统回收时的状态保存
*/
public void saveInstanceState(Bundle outState) {
outState.putSerializable("cropCacheFolder", cropCacheFolder);
outState.putSerializable("takeImageFile", takeImageFile);
outState.putSerializable("style", style);
outState.putBoolean("multiMode", multiMode);
outState.putBoolean("crop", crop);
outState.putBoolean("showCamera", showCamera);
outState.putBoolean("isSaveRectangle", isSaveRectangle);
outState.putInt("selectLimit", selectLimit);
outState.putInt("outPutX", outPutX);
outState.putInt("outPutY", outPutY);
outState.putInt("focusWidth", focusWidth);
outState.putInt("focusHeight", focusHeight);
}
public ImagePicker selectedListener(OnSelectedListener listener) {
onImageSelectedListener = listener;
return this;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
if (data != null && requestCode == 100) {
ArrayList<ImageItem> images = data.getParcelableArrayListExtra(ImagePicker.EXTRA_RESULT_ITEMS);
if (onImageSelectedListener != null) {
onImageSelectedListener.onImageSelected(images);
}
} else {
if (onImageSelectedListener != null) {
onImageSelectedListener.onImageSelected(null);
}
}
Log.v("TAG", "onActivityResult");
onImageSelectedListener = null;
}
}
public void startPhotoPicker(Activity activity, Class<?> clazz) {
if (onImageSelectedListener == null) {
Log.e(TAG, "\n\n\nOnImageSelectedListener is null , will not return any data\n\n\n");
}
multiMode(false);
ImagePicker.getInstance().selectLimit(1);
Intent intent = new Intent(activity, clazz);
intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
activity.startActivityForResult(intent, 100);
}
public void startPhotoPicker(Activity activity) {
startPhotoPicker(activity, ImageGridActivity.class);
}
public void startImagePicker(Activity activity, Class<?> clazz, ArrayList<ImageItem> images) {
if (onImageSelectedListener == null) {
Log.e(TAG, "\n\n\nOnImageSelectedListener is null , will not return any data\n\n\n");
}
Intent intent = new Intent(activity, clazz);
if (images != null) {
intent.putParcelableArrayListExtra(ImageGridActivity.EXTRAS_IMAGES, images);
ImagePicker.getInstance().selectedImages(images);
}
loadType(MediaType.VIDEO);
activity.startActivityForResult(intent, 100);
}
public void startImagePicker(Activity activity, ArrayList<ImageItem> images) {
startImagePicker(activity, ImageGridActivity.class, images);
}
public void startImagePicker(Activity activity) {
startImagePicker(activity, null);
}
public void startVideoPicker(Activity activity, Class<?> clazz) {
if (onImageSelectedListener == null) {
Log.e(TAG, "\n\n\nOnImageSelectedListener is null , will not return any data\n\n\n");
}
crop(false);
showCamera(false);
selectLimit(1);
multiMode(false);
loadType(MediaType.VIDEO);
Intent intent = new Intent(activity, clazz);
activity.startActivityForResult(intent, 100);
}
public void startVideoPicker(Activity activity) {
startVideoPicker(activity, ImageGridActivity.class);
}
public void startImageViewer(Activity activity, List<String> images, View view, int position) {
if (images == null || images.size() == 0)
return;
ImagePicker.getInstance().viewerItem(images);
Intent intent = new Intent(activity, ImageViewerActivity.class);
intent.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && ImagePicker.getInstance().isShareView() && view != null) {
ActivityOptionsCompat option = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, Pair.create(view, activity.getString(R.string.share_view_photo) + position));
ActivityCompat.startActivity(activity, intent, option.toBundle());
} else {
activity.startActivity(intent);
}
}
public void startImageViewer(Activity activity, List<String> images, int position) {
startImageViewer(activity, images, null, position);
}
public void startImageViewer(Activity activity, List<String> images) {
startImageViewer(activity, images, null, 0);
}
public List<String> getViewerItem() {
return viewerItem;
}
public void viewerItem(List<String> data) {
viewerItem = data;
}
public MediaType getLoadType() {
return loadType;
}
public interface OnPictureSelectedListener {
void onImageSelected(int position, ImageItem item, boolean isAdd);
}
public interface OnSelectedListener {
void onImageSelected(List<ImageItem> items);
}
}
|
9234f93b6b84114a900f1c6d444d1cb26e1bab48 | 14,807 | java | Java | src/org/sosy_lab/cpachecker/cpa/smg/graphs/SMG.java | mutilin/cpachecker-ldv | e57bec78f72d408abb4a6812044972324df298d4 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2017-03-10T07:42:29.000Z | 2017-03-10T07:42:29.000Z | src/org/sosy_lab/cpachecker/cpa/smg/graphs/SMG.java | mutilin/cpachecker-ldv | e57bec78f72d408abb4a6812044972324df298d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/org/sosy_lab/cpachecker/cpa/smg/graphs/SMG.java | mutilin/cpachecker-ldv | e57bec78f72d408abb4a6812044972324df298d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 27.780488 | 116 | 0.670494 | 997,113 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.smg.graphs;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.sosy_lab.cpachecker.cfa.types.MachineModel;
import org.sosy_lab.cpachecker.cfa.types.c.CType;
import org.sosy_lab.cpachecker.cpa.smg.SMGEdgeHasValue;
import org.sosy_lab.cpachecker.cpa.smg.SMGEdgeHasValueFilter;
import org.sosy_lab.cpachecker.cpa.smg.SMGEdgePointsTo;
import org.sosy_lab.cpachecker.cpa.smg.objects.SMGObject;
import com.google.common.annotations.VisibleForTesting;
public class SMG {
final private Set<SMGObject> objects = new HashSet<>();
final private Set<Integer> values = new HashSet<>();
final private Set<SMGEdgeHasValue> hv_edges = new HashSet<>();
final private Map<Integer, SMGEdgePointsTo> pt_edges = new HashMap<>();
final private Map<SMGObject, Boolean> object_validity = new HashMap<>();
final private NeqRelation neq = new NeqRelation();
final private MachineModel machine_model;
/**
* A special object representing NULL
*/
final private static SMGObject nullObject = SMGObject.getNullObject();
/**
* An address of the special object representing null
*/
final private static int nullAddress = 0;
/**
* Constructor.
*
* Consistent after call: yes.
*
* @param pMachineModel A machine model this SMG uses.
*
*/
public SMG(final MachineModel pMachineModel) {
SMGEdgePointsTo nullPointer = new SMGEdgePointsTo(nullAddress, nullObject, 0);
addObject(nullObject);
object_validity.put(nullObject, false);
addValue(nullAddress);
addPointsToEdge(nullPointer);
machine_model = pMachineModel;
}
/**
* Copy constructor.
*
* Consistent after call: yes if pHeap is consistent, no otherwise.
*
* @param pHeap Original SMG.
*/
public SMG(final SMG pHeap) {
machine_model = pHeap.machine_model;
hv_edges.addAll(pHeap.hv_edges);
neq.putAll(pHeap.neq);
object_validity.putAll(pHeap.object_validity);
objects.addAll(pHeap.objects);
pt_edges.putAll(pHeap.pt_edges);
values.addAll(pHeap.values);
}
@Override
public int hashCode() {
return Objects.hash(
machine_model,
hv_edges,
neq,
object_validity,
objects,
pt_edges,
values);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SMG other = (SMG) obj;
return machine_model == other.machine_model
&& Objects.equals(hv_edges, other.hv_edges)
&& Objects.equals(neq, other.neq)
&& Objects.equals(object_validity,other.object_validity)
&& Objects.equals(objects, other.objects)
&& Objects.equals(pt_edges, other.pt_edges)
&& Objects.equals(values, other.values);
}
/**
* Add an object to the SMG.
*
* Keeps consistency: no.
*
* @param pObj object to add.
*
*/
final public void addObject(final SMGObject pObj) {
addObject(pObj, true);
}
/**
* Remove pValue from the SMG. This method does not remove
* any edges leading from/to the removed value.
*
* Keeps consistency: no
*
* @param pValue Value to remove
*/
final public void removeValue(final Integer pValue) {
values.remove(pValue);
neq.removeValue(pValue);
}
/**
* Remove pObj from the SMG. This method does not remove
* any edges leading from/to the removed object.
*
* Keeps consistency: no
*
* @param pObj Object to remove
*/
@VisibleForTesting
final public void removeObject(final SMGObject pObj) {
objects.remove(pObj);
object_validity.remove(pObj);
}
/**
* Remove pObj and all edges leading from/to it from the SMG
*
* Keeps consistency: no
*
* @param pObj Object to remove
*/
final public void removeObjectAndEdges(final SMGObject pObj) {
removeObject(pObj);
Iterator<SMGEdgeHasValue> hv_iter = hv_edges.iterator();
Iterator<SMGEdgePointsTo> pt_iter = pt_edges.values().iterator();
while (hv_iter.hasNext()) {
if (hv_iter.next().getObject() == pObj) {
hv_iter.remove();
}
}
while (pt_iter.hasNext()) {
if (pt_iter.next().getObject() == pObj) {
pt_iter.remove();
}
}
}
/**
* Add pObj object to the SMG, with validity set to pValidity.
*
* Keeps consistency: no.
*
* @param pObj Object to add
* @param pValidity Validity of the newly added object.
*
*/
final public void addObject(final SMGObject pObj, final boolean pValidity) {
objects.add(pObj);
object_validity.put(pObj, pValidity);
}
/**
* Add pValue value to the SMG.
*
* Keeps consistency: no.
*
* @param pValue Value to add.
*/
final public void addValue(Integer pValue) {
values.add(pValue);
}
/**
* Add pEdge Points-To edge to the SMG.
*
* Keeps consistency: no.
*
* @param pEdge Points-To edge to add.
*/
final public void addPointsToEdge(SMGEdgePointsTo pEdge) {
pt_edges.put(pEdge.getValue(), pEdge);
}
/**
* Add pEdge Has-Value edge to the SMG.
*
* Keeps consistency: no
*
* @param pEdge Has-Value edge to add
*/
final public void addHasValueEdge(SMGEdgeHasValue pEdge) {
hv_edges.add(pEdge);
}
/**
* Remove pEdge Has-Value edge from the SMG.
*
* Keeps consistency: no
*
* @param pEdge Has-Value edge to remove
*/
final public void removeHasValueEdge(SMGEdgeHasValue pEdge) {
hv_edges.remove(pEdge);
}
/**
* Remove the Points-To edge from the SMG with the value pValue as Source.
*
* Keeps consistency: no
*
* @param pValue the Source of the Points-To edge to be removed
*/
final public void removePointsToEdge(int pValue) {
pt_edges.remove(pValue);
}
/**
* Sets the validity of the object pObject to pValidity.
* Throws {@link IllegalArgumentException} if pObject is
* not present in SMG.
*
* Keeps consistency: no
*
* @param pObject An object.
* @param pValidity Validity to set.
*/
public void setValidity(SMGObject pObject, boolean pValidity) {
if (! objects.contains(pObject)) {
throw new IllegalArgumentException("Object [" + pObject + "] not in SMG");
}
object_validity.put(pObject, pValidity);
}
/**
* Replaces whole HasValue edge set with new set.
* @param pNewHV
*
* Keeps consistency: no
*/
public void replaceHVSet(Set<SMGEdgeHasValue> pNewHV) {
hv_edges.clear();
hv_edges.addAll(pNewHV);
}
/**
* Adds a neq relation between two values to the SMG
* Keeps consistency: no
*/
public void addNeqRelation(Integer pV1, Integer pV2) {
neq.add_relation(pV1, pV2);
}
/* ********************************************* */
/* Non-modifying functions: getters and the like */
/* ********************************************* */
/**
* Getter for obtaining designated NULL object. Constant.
* @return An object guaranteed to be the only NULL object in the SMG
*/
final public SMGObject getNullObject() {
return SMG.nullObject;
}
/**
* Getter for obtaining designated zero value. Constant.
* @return A value guaranteed to be the only zero value in the SMG
*/
final public int getNullValue() {
return SMG.nullAddress;
}
/**
* Getter for obtaining string representation of values set. Constant.
* @return String representation of values set
*/
final public String valuesToString() {
return "values=" + values.toString();
}
/**
* Getter for obtaining string representation of has-value edges set. Constant.
* @return String representation of has-value edges set
*/
final public String hvToString() {
return "hasValue=" + hv_edges.toString();
}
/**
* Getter for obtaining string representation of points-to edges set. Constant.
* @return String representation of points-to edges set
*/
final public String ptToString() {
return "pointsTo=" + pt_edges.toString();
}
/**
* Getter for obtaining unmodifiable view on values set. Constant.
* @return Unmodifiable view on values set.
*/
final public Set<Integer> getValues() {
return Collections.unmodifiableSet(values);
}
/**
* Getter for obtaining unmodifiable view on objects set. Constant.
* @return Unmodifiable view on objects set.
*/
final public Set<SMGObject> getObjects() {
return Collections.unmodifiableSet(objects);
}
/**
* Getter for obtaining unmodifiable view on Has-Value edges set. Constant.
* @return Unmodifiable view on Has-Value edges set.
*/
final public Set<SMGEdgeHasValue> getHVEdges() {
return Collections.unmodifiableSet(hv_edges);
}
/**
* Getter for obtaining unmodifiable view on Has-Value edges set, filtered by
* a certain set of criteria.
* @param pFilter Filtering object
* @return A set of Has-Value edges for which the criteria in p hold
*/
final public Set<SMGEdgeHasValue> getHVEdges(SMGEdgeHasValueFilter pFilter) {
return Collections.unmodifiableSet(pFilter.filterSet(hv_edges));
}
/**
* Getter for obtaining unmodifiable view on Points-To edges set. Constant.
* @return Unmodifiable view on Points-To edges set.
*/
final public Map<Integer, SMGEdgePointsTo> getPTEdges() {
return Collections.unmodifiableMap(pt_edges );
}
/**
* Getter for obtaining an object, pointed by a value pValue. Constant.
*
* @param pValue An origin value.
* @return The object pointed by the value pValue, if such exists.
* Null, if pValue does not point to any
* object.
*
* Throws {@link IllegalArgumentException} if pValue is
* not present in the SMG.
*
* TODO: Test
* TODO: Consistency check: no value can point to more objects
*/
final public SMGObject getObjectPointedBy(Integer pValue) {
if ( ! values.contains(pValue)) {
throw new IllegalArgumentException("Value [" + pValue + "] not in SMG");
}
if (pt_edges.containsKey(pValue)) {
return pt_edges.get(pValue).getObject();
} else {
return null;
}
}
/**
* Getter for determining if the object pObject is valid. Constant.
* Throws {@link IllegalArgumentException} if pObject is
* not present in the SMG.
*
* @param pObject An object.
* @return True if Object is valid, False if it is invalid.
*/
final public boolean isObjectValid(SMGObject pObject) {
if ( ! objects.contains(pObject)) {
throw new IllegalArgumentException("Object [" + pObject + "] not in SMG");
}
return object_validity.get(pObject);
}
/**
* Getter for obtaining SMG machine model. Constant.
* @return SMG machine model
*/
final public MachineModel getMachineModel() {
return machine_model;
}
/**
* Obtains a bitset signifying where the object bytes are nullified.
*
* Constant.
*
* @param pObj SMGObject for which the information is to be obtained
* @return A bitset. A bit has 1 value if the appropriate byte is guaranteed
* to be NULL (is covered by a HasValue edge leading from an object to null value,
* 0 otherwise.
*/
public BitSet getNullBytesForObject(SMGObject pObj) {
BitSet bs = new BitSet(pObj.getSize());
bs.clear();
SMGEdgeHasValueFilter objectFilter = SMGEdgeHasValueFilter.objectFilter(pObj).filterHavingValue(getNullValue());
for (SMGEdgeHasValue edge : getHVEdges(objectFilter)) {
bs.set(edge.getOffset(), edge.getOffset() + edge.getSizeInBytes(machine_model));
}
return bs;
}
/**
* Checks, whether a {@link SMGEdgePointsTo} edge exists with the
* given value as source.
*
*
* @param value the source of the {@link SMGEdgePointsTo} edge.
* @return true, if the {@link SMGEdgePointsTo} edge with the source
* value exists, otherwise false.
*/
public boolean isPointer(Integer value) {
return pt_edges.containsKey(value);
}
/**
* Returns the {@link SMGEdgePointsTo} edge with the
* given value as source.
*
* @param value the source of the {@link SMGEdgePointsTo} edge.
* @return the {@link SMGEdgePointsTo} edge with the
* value as source.
*/
public SMGEdgePointsTo getPointer(Integer value) {
return pt_edges.get(value);
}
public boolean isCoveredByNullifiedBlocks(SMGEdgeHasValue pEdge) {
return isCoveredByNullifiedBlocks(pEdge.getObject(), pEdge.getOffset(), pEdge.getSizeInBytes(machine_model));
}
public boolean isCoveredByNullifiedBlocks(SMGObject pObject, int pOffset, CType pType ) {
return isCoveredByNullifiedBlocks(pObject, pOffset, machine_model.getSizeof(pType));
}
private boolean isCoveredByNullifiedBlocks(SMGObject pObject, int pOffset, int size) {
BitSet objectNullBytes = getNullBytesForObject(pObject);
int expectedMinClear = pOffset + size;
return (objectNullBytes.nextClearBit(pOffset) >= expectedMinClear);
}
public void mergeValues(int pV1, int pV2) {
if (pV1 == pV2) {
return;
}
if (pV2 == nullAddress) {
int tmp = pV1;
pV1 = pV2;
pV2 = tmp;
}
neq.mergeValues(pV1, pV2);
removeValue(pV2);
Set<SMGEdgeHasValue> new_hv_edges = new HashSet<>();
for (SMGEdgeHasValue hv : hv_edges) {
if (hv.getValue() != pV2) {
new_hv_edges.add(hv);
} else {
new_hv_edges.add(new SMGEdgeHasValue(hv.getType(), hv.getOffset(), hv.getObject(), pV1));
}
}
hv_edges.clear();
hv_edges.addAll(new_hv_edges);
// TODO: Handle PT Edges: I'm not entirely sure how they should be handled
}
public boolean haveNeqRelation(Integer pV1, Integer pV2) {
return neq.neq_exists(pV1, pV2);
}
public Set<Integer> getNeqsForValue(Integer pV) {
return neq.getNeqsForValue(pV);
}
}
|
9234f944487b97a41c920b0ea87cdc354855ed49 | 430 | java | Java | tools-core/src/test/java/com/tools/core/convert/PrimitiveConvertTest.java | ghj1040110333/tools | 60f9343790f891700d0ebe5f8a77b226313e72b9 | [
"MulanPSL-1.0"
] | null | null | null | tools-core/src/test/java/com/tools/core/convert/PrimitiveConvertTest.java | ghj1040110333/tools | 60f9343790f891700d0ebe5f8a77b226313e72b9 | [
"MulanPSL-1.0"
] | null | null | null | tools-core/src/test/java/com/tools/core/convert/PrimitiveConvertTest.java | ghj1040110333/tools | 60f9343790f891700d0ebe5f8a77b226313e72b9 | [
"MulanPSL-1.0"
] | null | null | null | 21.5 | 57 | 0.746512 | 997,114 | package com.tools.core.convert;
import com.tools.core.convert.Convert;
import org.junit.Assert;
import org.junit.Test;
public class PrimitiveConvertTest {
@Test
public void toIntTest(){
final int convert = Convert.convert(int.class, "123");
Assert.assertEquals(123, convert);
}
@Test(expected = NumberFormatException.class)
public void toIntErrorTest(){
final int convert = Convert.convert(int.class, "aaaa");
}
}
|
9234f9e95e261ce528b0a04ad4e5f1faea37d93b | 3,828 | java | Java | ParserGenerator/src/GrammarTransformer.java | olegggatttor/MT | 8b3638e63b03b1d16c6e0a53037376220309b998 | [
"MIT"
] | null | null | null | ParserGenerator/src/GrammarTransformer.java | olegggatttor/MT | 8b3638e63b03b1d16c6e0a53037376220309b998 | [
"MIT"
] | null | null | null | ParserGenerator/src/GrammarTransformer.java | olegggatttor/MT | 8b3638e63b03b1d16c6e0a53037376220309b998 | [
"MIT"
] | null | null | null | 31.9 | 111 | 0.572362 | 997,115 | import org.antlr.v4.runtime.tree.ParseTree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class GrammarTransformer extends GrammarBaseListener {
Grammar grammar = new Grammar();
@Override
public void exitStart(GrammarParser.StartContext ctx) {
super.exitStart(ctx);
grammar.startRule = ctx.getChild(1).getText();
}
@Override
public void exitSynth(GrammarParser.SynthContext ctx) {
super.exitSynth(ctx);
grammar.synthAttrs = ctx.fields().getText().split(",");
}
@Override
public void exitSkip(GrammarParser.SkipContext ctx) {
super.exitSkip(ctx);
grammar.skipRegexs.add(ctx.getChild(0).getText().substring(1, ctx.getChild(0).getText().length() - 1));
}
@Override
public void exitTerminal(GrammarParser.TerminalContext ctx) {
super.exitTerminal(ctx);
final TerminalRule rule = new TerminalRule(ctx.getChild(0).getText());
if (ctx.getChild(1).getText().equals("[")) {
rule.fields.addAll(Arrays.asList(ctx.getChild(2).getText().split(",")));
rule.term = ctx.getChild(5).getText().substring(1, ctx.getChild(5).getText().length() - 1);
if (!ctx.getChild(6).getText().equals(";")) {
rule.code = ctx.getChild(6).getText();
}
} else {
rule.term = ctx.getChild(2).getText().substring(1, ctx.getChild(2).getText().length() - 1);
if (!ctx.getChild(3).getText().equals(";")) {
rule.code = ctx.getChild(3).getText();
}
}
grammar.rules.add(rule);
}
@Override
public void exitNonTerminal(GrammarParser.NonTerminalContext ctx) {
super.exitNonTerminal(ctx);
NonTerminalRule rule = new NonTerminalRule(ctx.getChild(0).getText());
ArrayList<String> fields = new ArrayList<>();
for (var ch : ctx.children) {
if (ch instanceof GrammarParser.FieldsContext) {
for (var f : ((GrammarParser.FieldsContext) ch).children) {
if (f instanceof GrammarParser.FieldContext) {
fields.add(f.getText());
}
}
}
if (ch instanceof GrammarParser.GrammarRuleContext) {
if (ch.getChild(0) instanceof GrammarParser.CodeContext) {
rule.code = ch.getText();
continue;
}
rule.rightPart.add(new Pair(ch.getChild(0).getText(),
((GrammarParser.GrammarRuleContext) ch).children.stream()
.filter(x -> x instanceof GrammarParser.ArgContext)
.map(ParseTree::getText)
.collect(Collectors.joining(", "))));
}
if (ch.getText().equals("|") || ch.getText().equals(";")) {
rule.fields = fields;
grammar.rules.add(rule);
rule = new NonTerminalRule(ctx.getChild(0).getText());
}
}
}
}
class Grammar {
String startRule;
ArrayList<GrammarRule> rules = new ArrayList<>();
String[] synthAttrs;
ArrayList<String> skipRegexs = new ArrayList<>();
}
class GrammarRule {
String name;
String code;
ArrayList<String> fields = new ArrayList<>();
}
class Pair {
String fst;
String snd;
Pair(String a, String b) {
fst = a;
snd = b;
}
}
class TerminalRule extends GrammarRule {
String term;
TerminalRule(final String name) {
this.name = name;
}
}
class NonTerminalRule extends GrammarRule {
ArrayList<Pair> rightPart = new ArrayList<>();
NonTerminalRule(final String name) {
this.name = name;
}
}
|
9234fa538f1f79e38bee1ebbda32d8d4e0dda987 | 1,349 | java | Java | src/main/java/me/hqm/privatereserve/command/LockModeCommand.java | HmmmQuestionMark/PrivateReserve | e449ce02c9f05adaef54bf4ecedfafd9c7269eb9 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/me/hqm/privatereserve/command/LockModeCommand.java | HmmmQuestionMark/PrivateReserve | e449ce02c9f05adaef54bf4ecedfafd9c7269eb9 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/me/hqm/privatereserve/command/LockModeCommand.java | HmmmQuestionMark/PrivateReserve | e449ce02c9f05adaef54bf4ecedfafd9c7269eb9 | [
"BSD-3-Clause"
] | null | null | null | 32.119048 | 93 | 0.680504 | 997,116 | package me.hqm.privatereserve.command;
import com.demigodsrpg.command.BaseCommand;
import com.demigodsrpg.command.CommandResult;
import me.hqm.privatereserve.PrivateReserve;
import org.bukkit.ChatColor;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import java.util.UUID;
public class LockModeCommand extends BaseCommand {
@Override
protected CommandResult onCommand(CommandSender sender, Command command, String[] args) {
if (sender instanceof ConsoleCommandSender) {
return CommandResult.PLAYER_ONLY;
}
UUID playerId = ((Player) sender).getUniqueId();
if (PrivateReserve.PLAYER_R.isVisitorOrExpelled(playerId)) {
return CommandResult.NO_PERMISSIONS;
}
if (toggleLockMode(playerId.toString())) {
sender.sendMessage(ChatColor.YELLOW + "Locking is now enabled.");
} else {
sender.sendMessage(ChatColor.YELLOW + "Locking is now disabled.");
}
return CommandResult.SUCCESS;
}
boolean toggleLockMode(String playerId) {
if (PrivateReserve.RELATIONAL_R.contains(playerId, "NO-LOCK")) {
PrivateReserve.RELATIONAL_R.remove(playerId, "NO-LOCK");
return true;
}
PrivateReserve.RELATIONAL_R.put(playerId, "NO-LOCK", true);
return false;
}
}
|
9234fad6d5e5e31cd3f92af22e9c8c885090f341 | 2,487 | java | Java | My_LMS/src/main/java/com/yildirimbayrakci/util/PasswordGenerator.java | yildirim2189/Library_Management_System-Java_Swing | 28e8da2cb4034c68b2f6e80924e8d7e39d8aa0e8 | [
"MIT"
] | 1 | 2019-12-14T23:23:37.000Z | 2019-12-14T23:23:37.000Z | My_LMS/src/main/java/com/yildirimbayrakci/util/PasswordGenerator.java | yildirim2189/Library_Management_System-Java_Swing | 28e8da2cb4034c68b2f6e80924e8d7e39d8aa0e8 | [
"MIT"
] | null | null | null | My_LMS/src/main/java/com/yildirimbayrakci/util/PasswordGenerator.java | yildirim2189/Library_Management_System-Java_Swing | 28e8da2cb4034c68b2f6e80924e8d7e39d8aa0e8 | [
"MIT"
] | null | null | null | 31.884615 | 109 | 0.609168 | 997,117 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.yildirimbayrakci.util;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author yildi
*/
public class PasswordGenerator {
private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
private static final String NUMBER = "0123456789";
private static final String OTHER_CHAR = "!@#$%&*()_+-=[]?";
private static final String PASSWORD_ALLOW_BASE = CHAR_LOWER + CHAR_UPPER + NUMBER ; // + OTHER_CHAR;
// optional, make it more random
private static final String PASSWORD_ALLOW_BASE_SHUFFLE = shuffleString(PASSWORD_ALLOW_BASE);
private static final String PASSWORD_ALLOW = PASSWORD_ALLOW_BASE_SHUFFLE;
private static SecureRandom random = new SecureRandom();
/*
public static void main(String[] args) {
System.out.format("String for password \t\t\t: %s%n", PASSWORD_ALLOW_BASE);
System.out.format("String for password (shuffle) \t: %s%n%n", PASSWORD_ALLOW);
// generate 5 random password
for (int i = 0; i < 5; i++) {
System.out.println("password : " + generateRandomPassword(8));
System.out.println("\n");
}
}
*/
public static String generateRandomPassword(int length) {
if (length < 1) {
throw new IllegalArgumentException();
}
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int rndCharAt = random.nextInt(PASSWORD_ALLOW.length());
char rndChar = PASSWORD_ALLOW.charAt(rndCharAt);
// debug
System.out.format("%d\t:\t%c%n", rndCharAt, rndChar);
sb.append(rndChar);
}
return sb.toString();
}
// shuffle
public static String shuffleString(String string) {
List<String> letters = Arrays.asList(string.split(""));
Collections.shuffle(letters);
return letters.stream().collect(Collectors.joining());
}
}
|
9234faea5b7bfb386ff5208ac1def26fd26a5af8 | 988 | java | Java | src/main/java/de/team33/libs/provision/vX/LazySupplyB.java | akk-team33/lib-provision | 543a9e2abc95307d108277cdde4a564b3e6f9174 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/team33/libs/provision/vX/LazySupplyB.java | akk-team33/lib-provision | 543a9e2abc95307d108277cdde4a564b3e6f9174 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/team33/libs/provision/vX/LazySupplyB.java | akk-team33/lib-provision | 543a9e2abc95307d108277cdde4a564b3e6f9174 | [
"Apache-2.0"
] | null | null | null | 25.333333 | 68 | 0.6083 | 997,118 | package de.team33.libs.provision.vX;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class LazySupplyB<C> extends LazySupply<C> {
@SuppressWarnings("rawtypes")
private final Map<Key, Result> map = new ConcurrentHashMap<>(0);
private static final class Result<R> {
private final R result;
private Result(final R result) {
this.result = result;
}
}
public LazySupplyB(final C context) {
super(context);
}
@Override
public final <R> R get(final Key<? super C, R> key) {
//noinspection unchecked
return (R) map.computeIfAbsent(key, this::test).result;
}
private <R> Result<R> test(final Key<C, R> key) {
try {
return new Result<>(key.init(context));
} catch (final RuntimeException caught) {
throw caught;
} catch (final Exception caught) {
throw new EnvelopeException(caught);
}
}
}
|
9234fcd30925dfa6e74b8b16d535f5e179b161e6 | 1,888 | java | Java | bdm-mysql/src/main/java/com/liaierto/dao/TDeleteMysqlPugin.java | liaierto/bdm | 81964045b1570d76c914953ee6a2079179620044 | [
"Apache-2.0"
] | 2 | 2016-10-27T02:45:40.000Z | 2017-06-29T01:28:09.000Z | bdm-mysql/src/main/java/com/liaierto/dao/TDeleteMysqlPugin.java | liaierto/bdm | 81964045b1570d76c914953ee6a2079179620044 | [
"Apache-2.0"
] | null | null | null | bdm-mysql/src/main/java/com/liaierto/dao/TDeleteMysqlPugin.java | liaierto/bdm | 81964045b1570d76c914953ee6a2079179620044 | [
"Apache-2.0"
] | null | null | null | 29.5 | 86 | 0.57786 | 997,119 | package com.liaierto.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
public class TDeleteMysqlPugin {
private static Log log = LogFactory.getLog(TDeleteMysqlPugin.class);
public boolean delete(Map<String,Object> item, String content) throws Exception {
JSONObject filter = null;
PreparedStatement statement = null;
String[] valus = null;
try {
Connection con = (Connection) item.get("connection");
JSONObject cont = JSONObject.parseObject(content);
filter = JSONObject.parseObject(cont.getString("filter"));
String value = filter.getString("value");
String fileterKey = item.get("filter").toString();//过滤参数
if(!"".equals(value)){
valus = value.split(",");
}
StringBuffer sql = new StringBuffer();
sql.append("delete from " + item.get("tableName"));
sql.append(" where 1=1 ");
if(!"".equals(fileterKey)){
sql.append(" and ");
sql.append(fileterKey);
}
statement = con.prepareStatement(sql.toString());
for(int i=0;i<valus.length;i++){
statement.setObject(i+1,valus[i]);
}
int pResult = statement.executeUpdate();
if(pResult>=1){
return true;
}else{
return false;
}
} catch (SQLException e) {
log.error(e);
return false;
}finally{
if(statement!=null)statement.close();
}
}
public static TDeleteMysqlPugin getInstance(){
return new TDeleteMysqlPugin();
}
}
|
9234fe409dde0f01d3c8c026ecd83e9ba4792f2d | 9,080 | java | Java | src/main/java/us/jcedeno/cookie/listener/CookieClickedListener.java | InfinityZ25/OpenSquid | 2e33febb44ba3d869c91d0367bb58c0fe13959fd | [
"MIT"
] | null | null | null | src/main/java/us/jcedeno/cookie/listener/CookieClickedListener.java | InfinityZ25/OpenSquid | 2e33febb44ba3d869c91d0367bb58c0fe13959fd | [
"MIT"
] | null | null | null | src/main/java/us/jcedeno/cookie/listener/CookieClickedListener.java | InfinityZ25/OpenSquid | 2e33febb44ba3d869c91d0367bb58c0fe13959fd | [
"MIT"
] | null | null | null | 38.151261 | 119 | 0.533921 | 997,120 | package us.jcedeno.cookie.listener;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.SoundCategory;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.MapMeta;
import org.bukkit.map.MapCanvas;
import me.aleiv.core.paper.map.packet.WrapperPlayServerMap;
import us.jcedeno.cookie.CookieManager;
import us.jcedeno.cookie.events.PlayerClickedCookieEvent;
import us.jcedeno.cookie.events.PlayerPaintedCookieEvent;
/**
* Listener for interactions with item frames.
*
* @author jcedeno
*/
public class CookieClickedListener implements Listener {
private CookieManager cookieManager;
public CookieClickedListener(CookieManager cookieManager) {
this.cookieManager = cookieManager;
}
/**
* Event called when a player click on an item frame which contains a full map.
* Only the player who created the map (or a permission) should be able to
* interact with it.
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInteractAtEntity(final PlayerInteractAtEntityEvent e) {
if (!CookieManager.EDIT)
return;
final var entity = e.getRightClicked();
if (entity != null && entity instanceof ItemFrame frame) {
ItemStack itemInFrame = frame.getItem();
if (itemInFrame != null && itemInFrame.getType() == Material.FILLED_MAP
&& itemInFrame.getItemMeta() instanceof MapMeta map) {
var entry = cookieManager.getFrameMap().get(entity.getLocation().getBlock());
if (entry != null) {
var interactionPoint = entity.getLocation().add(e.getClickedPosition());
Bukkit.getPluginManager().callEvent(new PlayerClickedCookieEvent(interactionPoint,
e.getPlayer(), frame, !Bukkit.isPrimaryThread()));
}
}
}
}
/**
* Event called when a player clicks on a block which contains a map on an item
* frame above of it.
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerInteractAtItemFramesBlock(final PlayerInteractEvent e) {
if (!CookieManager.EDIT || e.getAction() != Action.RIGHT_CLICK_BLOCK || e.getBlockFace() != BlockFace.UP)
return;
var block = e.getClickedBlock().getRelative(BlockFace.UP);
var map = cookieManager.getFrameMap().get(block);
if (map != null) {
var interaction = e.getInteractionPoint();
if (interaction != null) {
// Normalize the vector and reduce it by one vector unit for accuracy.
var vec = interaction.toVector().clone();
var normie = e.getPlayer().getEyeLocation().toVector().subtract(vec).normalize();
var l = interaction.toVector().clone().add(normie.multiply(0.05)).toLocation(block.getWorld());
// Call the Event and handle everything else there.
Bukkit.getPluginManager()
.callEvent(new PlayerClickedCookieEvent(l, e.getPlayer(), map, !Bukkit.isPrimaryThread()));
}
}
}
@EventHandler
public void onPlayerClickedCookie(final PlayerClickedCookieEvent e) {
// TODO Ensure that players can only edit a cookie if it belongs to them.
if (CookieManager.EDIT) {
var player = e.getPlayer();
var frame = e.getItemFrame();
var position = e.getInteractionPoint();
var bX = frame.getLocation().getBlockX();
var bZ = frame.getLocation().getBlockZ();
var relativeX = position.getX() - bX;
var relativeZ = position.getZ() - bZ;
// Send relative to player
// player.sendMessage("rotation: " + frame.getRotation() + ", " + relativeX + ",
// " + relativeZ);
var cookieMap = cookieManager.getCookieMaps().get(player.getUniqueId());
// Null safety
if (cookieMap == null)
return;
byte x = 0;
byte z = 0;
WrapperPlayServerMap packet = null;
// Handle all the cases based on rotation; improve this later.
switch (frame.getRotation()) {
case NONE:
case FLIPPED: {
x = (byte) (relativeX * 128);
// Add 1 - z to adjust for rotation.
z = (byte) ((relativeZ) * 128);
packet = cookieMap.paintPixel(Math.min(127, x), Math.min(127, z), CookieManager.getPaintColor());
break;
}
case CLOCKWISE_45:
case FLIPPED_45:
z = (byte) Math.ceil((position.getX()) * 128);
x = (byte) Math.ceil((position.getZ()) * 128);
packet = cookieMap.paintPixel(Math.min(x, 127), Math.min(128 - z, 127),
CookieManager.getPaintColor());
break;
case COUNTER_CLOCKWISE:
case CLOCKWISE:
x = (byte) Math.ceil((position.getX()) * 128);
z = (byte) Math.ceil((position.getZ()) * 128);
packet = cookieMap.paintPixel(Math.min(128 - x, 127), Math.min(128 - z, 127),
CookieManager.getPaintColor());
break;
case COUNTER_CLOCKWISE_45:
case CLOCKWISE_135:
z = (byte) Math.ceil((position.getX()) * 128);
x = (byte) Math.ceil((position.getZ()) * 128);
packet = cookieMap.paintPixel(Math.min(128 - x, 127), Math.min(127, z),
CookieManager.getPaintColor());
break;
}
if (packet != null) {
packet.broadcastPacket();
// Call the Event
var canvas = cookieMap.getMapRenderer().getCanvas();
if (canvas != null)
Bukkit.getPluginManager()
.callEvent(PlayerPaintedCookieEvent.of(cookieMap, player, x, z,
canvas.getPixel(x, z)));
}
}
}
@EventHandler
public void onPlayerPaintedMap(final PlayerPaintedCookieEvent e) {
/*
* TODO Detection
* Color que clickear = -93
* Safe zone = -96
* error = -94
* ignore/outside = -95
*/
var px = e.getPixel();
/**
* Pixel count color -93:
*
* Creeper = 968 pixeles
* Eye = 864 pixeles
* Squid = 1040 pixeles
* Rodolfo = 1176 pixeles
*/
if (px.color() == -93) {
// Correct clicked
e.getCookieMap().increaseCorrectPixels();
e.getPlayer().playSound(e.getPlayer().getLocation(), "squid:sfx.right", SoundCategory.AMBIENT, 0.25f,
0.0f);
} else if (px.color() == -94) {
// incorrect clicked
e.getCookieMap().increaseIncorrectPixels();
// Play error sound
e.getPlayer().playSound(e.getPlayer().getLocation(), "squid:sfx.wrong", SoundCategory.AMBIENT, 1.0f, 0.0f);
}
}
void countPixelColorsOfMap(MapCanvas canvas, Player player) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
if (canvas != null) {
// Double for loop from 0 to 127
for (int x = 0; x < 128; x++) {
for (int z = 0; z < 128; z++) {
// If the pixel is the same color as the one clicked
var pixel = canvas.getPixel(x, z);
switch (pixel) {
case -93:
a += (1);
break;
case -94:
b += (1);
break;
case -95:
c += (1);
break;
case -96:
d += (1);
break;
}
}
}
}
// Send the message to the player
player.sendMessage("There are " + a + " pixels of color " + -93 + ".");
player.sendMessage("There are " + b + " pixels of color " + -94 + ".");
player.sendMessage("There are " + c + " pixels of color " + -95 + ".");
player.sendMessage("There are " + d + " pixels of color " + -96 + ".");
}
}
|
923500d6870c19302b7f65dd11fceb1a233a854e | 1,913 | java | Java | src/main/java/com/whirvis/jraknet/identifier/package-info.java | misselvexu/JRakNet | da93370c3257351b5aa17dcc0f96eb8aa73f8140 | [
"MIT"
] | null | null | null | src/main/java/com/whirvis/jraknet/identifier/package-info.java | misselvexu/JRakNet | da93370c3257351b5aa17dcc0f96eb8aa73f8140 | [
"MIT"
] | null | null | null | src/main/java/com/whirvis/jraknet/identifier/package-info.java | misselvexu/JRakNet | da93370c3257351b5aa17dcc0f96eb8aa73f8140 | [
"MIT"
] | null | null | null | 50.342105 | 150 | 0.619969 | 997,121 | /*
* __ ______ ______ __ __ __ __ ______ ______
* /\ \ /\ == \ /\ __ \ /\ \/ / /\ "-.\ \ /\ ___\ /\__ _\
* _\_\ \ \ \ __< \ \ __ \ \ \ _"-. \ \ \-. \ \ \ __\ \/_/\ \/
* /\_____\ \ \_\ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\\"\_\ \ \_____\ \ \_\
* \/_____/ \/_/ /_/ \/_/\/_/ \/_/\/_/ \/_/ \/_/ \/_____/ \/_/
*
* the MIT License (MIT)
*
* Copyright (c) 2016-2019 Trent "Whirvis" Summerlin
*
* 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.
*/
/**
* Classes used to create identifiers that describe servers or parse identifiers
* to get their information.
*
* @author Trent "Whirvis" Summerlin
* @since JRakNet v1.0.0
* @see com.whirvis.jraknet.identifier.Identifier Identifier
*/
package com.whirvis.jraknet.identifier; |
92350234ac8c07b4bdad53c212418b3983adb171 | 603 | java | Java | sample/webservice/eBayDemoApp/src/com/ebay/trading/api/GetStoreCustomPageResponseType.java | 4everalone/nano | 71779b1ad546663ee90a29f1c2d4236a6948a621 | [
"Apache-2.0"
] | 3 | 2016-01-27T20:05:27.000Z | 2018-01-16T13:11:38.000Z | sample/hello-ebay-trading/src/main/java/com/ebay/trading/api/GetStoreCustomPageResponseType.java | maxep/NanoKit | 7bb39fdd456f9af4f2d2dad937d482620c797a4e | [
"Apache-2.0"
] | null | null | null | sample/hello-ebay-trading/src/main/java/com/ebay/trading/api/GetStoreCustomPageResponseType.java | maxep/NanoKit | 7bb39fdd456f9af4f2d2dad937d482620c797a4e | [
"Apache-2.0"
] | 1 | 2015-09-02T02:40:36.000Z | 2015-09-02T02:40:36.000Z | 26.217391 | 98 | 0.762852 | 997,122 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
/**
*
* Contains the custom page or pages for the user's Store.
*
*/
@RootElement(name = "GetStoreCustomPageResponse", namespace = "urn:ebay:apis:eBLBaseComponents")
public class GetStoreCustomPageResponseType extends AbstractResponseType implements Serializable {
private static final long serialVersionUID = -1L;
@Element(name = "CustomPageArray")
@Order(value=0)
public StoreCustomPageArrayType customPageArray;
} |
923502a41ee80936b62ea8b93d87e8544e40275b | 2,596 | java | Java | src/main/java/refinedstorage/block/BlockGrid.java | TheSeven/refinedstorage | 647b5ea163feceb54989d78c7cd555f5b92d5394 | [
"MIT"
] | 1 | 2021-10-30T00:17:14.000Z | 2021-10-30T00:17:14.000Z | src/main/java/refinedstorage/block/BlockGrid.java | TheSeven/refinedstorage | 647b5ea163feceb54989d78c7cd555f5b92d5394 | [
"MIT"
] | null | null | null | src/main/java/refinedstorage/block/BlockGrid.java | TheSeven/refinedstorage | 647b5ea163feceb54989d78c7cd555f5b92d5394 | [
"MIT"
] | 1 | 2021-10-30T00:17:20.000Z | 2021-10-30T00:17:20.000Z | 32.860759 | 192 | 0.703005 | 997,123 | package refinedstorage.block;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import refinedstorage.RefinedStorage;
import refinedstorage.RefinedStorageGui;
import refinedstorage.item.ItemBlockBase;
import refinedstorage.tile.grid.TileGrid;
import java.util.List;
public class BlockGrid extends BlockNode {
public static final PropertyEnum TYPE = PropertyEnum.create("type", EnumGridType.class);
public BlockGrid() {
super("grid");
}
@Override
public TileEntity createTileEntity(World world, IBlockState state) {
return new TileGrid();
}
@Override
public void getSubBlocks(Item item, CreativeTabs tab, List<ItemStack> subItems) {
for (int i = 0; i <= 3; i++) {
subItems.add(new ItemStack(item, 1, i));
}
}
@Override
protected BlockStateContainer createBlockState() {
return createBlockStateBuilder()
.add(TYPE)
.build();
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty(TYPE, meta == 0 ? EnumGridType.NORMAL : (meta == 1 ? EnumGridType.CRAFTING : (meta == 2 ? EnumGridType.PATTERN : EnumGridType.FLUID)));
}
@Override
public int getMetaFromState(IBlockState state) {
return state.getValue(TYPE) == EnumGridType.NORMAL ? 0 : (state.getValue(TYPE) == EnumGridType.CRAFTING ? 1 : (state.getValue(TYPE) == EnumGridType.PATTERN ? 2 : 3));
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
player.openGui(RefinedStorage.INSTANCE, RefinedStorageGui.GRID, world, pos.getX(), pos.getY(), pos.getZ());
((TileGrid) world.getTileEntity(pos)).onGridOpened(player);
}
return true;
}
@Override
public boolean hasConnectivityState() {
return true;
}
@Override
public Item createItem() {
return new ItemBlockBase(this, getPlacementType(), true);
}
}
|
923502ea61058e61afbb39bb6b3ab854e0a901ad | 1,417 | java | Java | problems/src/main/java/prob676/implement/magic/dictionary/MagicDictionary.java | yangyangv2/leet-code | 6419661bba796e896017faa30575747d136685f7 | [
"MIT"
] | null | null | null | problems/src/main/java/prob676/implement/magic/dictionary/MagicDictionary.java | yangyangv2/leet-code | 6419661bba796e896017faa30575747d136685f7 | [
"MIT"
] | null | null | null | problems/src/main/java/prob676/implement/magic/dictionary/MagicDictionary.java | yangyangv2/leet-code | 6419661bba796e896017faa30575747d136685f7 | [
"MIT"
] | null | null | null | 27.784314 | 119 | 0.523641 | 997,124 | package prob676.implement.magic.dictionary;
import java.util.HashSet;
import java.util.Set;
/**
* Created by yanya04 on 5/24/2018.
*/
public class MagicDictionary {
private Set<String> set;
/** Initialize your data structure here. */
public MagicDictionary() {
set = new HashSet<>();
}
/** Build a dictionary through a list of words */
public void buildDict(String[] dict) {
String word = null;
for(int i = 0; i < dict.length; i ++){
for(int j = 0; j < dict[i].length(); j ++){
for(int k = 0; k <= 26; k ++){
if((char) (k + 'a') == dict[i].charAt(j))
continue;
if(j == 0)
word = (char)(k + 'a') + dict[i].substring(1);
else
word = dict[i].substring(0, j) + (char)(k + 'a') + dict[i].substring(j + 1, dict[i].length());
set.add(word);
}
}
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
public boolean search(String word) {
return set.contains(word);
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* boolean param_2 = obj.search(word);
*/
|
92350584fdadbcb616618a7923aa241e719f57fe | 494 | java | Java | mark59-selenium-sample-dsl/src/main/java/com/mark59/seleniumDSL/pageElements/OptionButton.java | mark-5-9/mark59-wip | df97f1bbb24816bd82b036317961346c7d4bbbc4 | [
"Apache-2.0"
] | 1 | 2021-09-16T05:45:40.000Z | 2021-09-16T05:45:40.000Z | mark59-selenium-sample-dsl/src/main/java/com/mark59/seleniumDSL/pageElements/OptionButton.java | mark-5-9/mark59-wip | df97f1bbb24816bd82b036317961346c7d4bbbc4 | [
"Apache-2.0"
] | 35 | 2020-08-11T05:42:56.000Z | 2022-01-17T04:33:06.000Z | mark59-selenium-sample-dsl/src/main/java/com/mark59/seleniumDSL/pageElements/OptionButton.java | mark-5-9/mark59 | b513f10a1fedd882f51380c3dbfc63bc36f6c6b9 | [
"Apache-2.0"
] | 1 | 2022-02-22T04:30:11.000Z | 2022-02-22T04:30:11.000Z | 23.52381 | 90 | 0.793522 | 997,125 | package com.mark59.seleniumDSL.pageElements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import com.mark59.seleniumDSL.core.Elemental;
import com.mark59.seleniumDSL.core.FluentWaitFactory;
public class OptionButton extends Elemental {
public OptionButton(WebDriver driver, String id) {
this(driver, By.id(id));
}
public OptionButton(WebDriver driver, By by) {
super(driver, by, FluentWaitFactory.DEFAULT_TIMEOUT, FluentWaitFactory.DEFAULT_POLLING);
}
}
|
923505b65b78b3ad00eb2f222b851c79511fb98d | 622 | java | Java | casacodigo/casacodigo/src/main/java/com/br/zup/casacodigo/pais/estado/Estado.java | CaioNovoaAntunes/orange-talents-06-template-casa-do-codigo | 21b7b5ff5797637c977d94b7d377f73b6f06774f | [
"Apache-2.0"
] | null | null | null | casacodigo/casacodigo/src/main/java/com/br/zup/casacodigo/pais/estado/Estado.java | CaioNovoaAntunes/orange-talents-06-template-casa-do-codigo | 21b7b5ff5797637c977d94b7d377f73b6f06774f | [
"Apache-2.0"
] | null | null | null | casacodigo/casacodigo/src/main/java/com/br/zup/casacodigo/pais/estado/Estado.java | CaioNovoaAntunes/orange-talents-06-template-casa-do-codigo | 21b7b5ff5797637c977d94b7d377f73b6f06774f | [
"Apache-2.0"
] | null | null | null | 15.948718 | 55 | 0.604502 | 997,126 | package com.br.zup.casacodigo.pais.estado;
import com.br.zup.casacodigo.pais.Pais;
import javax.persistence.*;
@Entity
public class Estado {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String nome;
@ManyToOne
private Pais pais;
public Estado(){
}
public Estado(String nome, Pais pais) {
this.nome = nome;
this.pais = pais;
}
public String getNome(){
return nome;
}
public Long getId() {
return id;
}
public Pais getPais() {
return pais;
}
}
|
9235062d2c648825208842ce2d87debc6920bb98 | 458 | java | Java | tartar/tartar.job_repairComputation/src/main/java/kn/uni/sen/joblibrary/tartar/convert/uppaaltrace/model/VariableVector.java | sen-uni-kn/tartar | 5148f8737ab39c09aa0ca4907b1af7c44cf8b8a0 | [
"MIT"
] | null | null | null | tartar/tartar.job_repairComputation/src/main/java/kn/uni/sen/joblibrary/tartar/convert/uppaaltrace/model/VariableVector.java | sen-uni-kn/tartar | 5148f8737ab39c09aa0ca4907b1af7c44cf8b8a0 | [
"MIT"
] | null | null | null | tartar/tartar.job_repairComputation/src/main/java/kn/uni/sen/joblibrary/tartar/convert/uppaaltrace/model/VariableVector.java | sen-uni-kn/tartar | 5148f8737ab39c09aa0ca4907b1af7c44cf8b8a0 | [
"MIT"
] | null | null | null | 14.774194 | 63 | 0.722707 | 997,127 | package kn.uni.sen.joblibrary.tartar.convert.uppaaltrace.model;
import java.util.ArrayList;
import java.util.List;
public class VariableVector
{
String id;
List<VariableState> varList = new ArrayList<>();
public VariableVector(String id)
{
this.id = id;
}
public String getID()
{
return id;
}
public void addVariableState(VariableState var)
{
varList.add(var);
}
public List<VariableState> getVariableList()
{
return varList;
}
}
|
92350721eca5fc4a4ed54160e5a09865fe74cd7a | 2,778 | java | Java | convert/src/main/java/org/bdgenomics/convert/bdgenomics/VariantAnnotationMessageToString.java | bigdatagenomics/convert | 7aac8af982269df87e8f79f34f94b3a44cc5854e | [
"Apache-2.0"
] | null | null | null | convert/src/main/java/org/bdgenomics/convert/bdgenomics/VariantAnnotationMessageToString.java | bigdatagenomics/convert | 7aac8af982269df87e8f79f34f94b3a44cc5854e | [
"Apache-2.0"
] | 28 | 2017-09-26T18:31:36.000Z | 2021-08-12T22:19:42.000Z | convert/src/main/java/org/bdgenomics/convert/bdgenomics/VariantAnnotationMessageToString.java | heuermh/bdg-convert | 9a7df4e237373de5e31f088af1e0dbc18135dd42 | [
"Apache-2.0"
] | 1 | 2018-07-27T12:32:05.000Z | 2018-07-27T12:32:05.000Z | 36.552632 | 106 | 0.667387 | 997,128 | /**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG 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.bdgenomics.convert.bdgenomics;
import org.bdgenomics.convert.AbstractConverter;
import org.bdgenomics.convert.ConversionException;
import org.bdgenomics.convert.ConversionStringency;
import org.bdgenomics.formats.avro.VariantAnnotationMessage;
import org.slf4j.Logger;
/**
* Convert VariantAnnotationMessage to String.
*/
final class VariantAnnotationMessageToString extends AbstractConverter<VariantAnnotationMessage, String> {
/**
* Package private constructor.
*/
VariantAnnotationMessageToString() {
super(VariantAnnotationMessage.class, String.class);
}
@Override
public String convert(final VariantAnnotationMessage variantAnnotationMessage,
final ConversionStringency stringency,
final Logger logger) throws ConversionException {
if (variantAnnotationMessage == null) {
warnOrThrow(variantAnnotationMessage, "must not be null", null, stringency, logger);
return null;
}
// use message code if available
switch (variantAnnotationMessage) {
case ERROR_CHROMOSOME_NOT_FOUND:
return "E1";
case ERROR_OUT_OF_CHROMOSOME_RANGE:
return "E2";
case WARNING_REF_DOES_NOT_MATCH_GENOME:
return "W1";
case WARNING_SEQUENCE_NOT_AVAILABLE:
return "W2";
case WARNING_TRANSCRIPT_INCOMPLETE:
return "W3";
case WARNING_TRANSCRIPT_MULTIPLE_STOP_CODONS:
return "W4";
case WARNING_TRANSCRIPT_NO_START_CODON:
return "W5";
case INFO_REALIGN_3_PRIME:
return "I1";
case INFO_COMPOUND_ANNOTATION:
return "I2";
case INFO_NON_REFERENCE_ANNOTATION:
return "I3";
default:
return variantAnnotationMessage.toString();
}
}
}
|
923507a1e4bdf3e978606febd13685c9b561c5f1 | 4,331 | java | Java | uikit/src/main/java/cn/wildfire/chat/kit/voip/conference/ConferenceInviteActivity.java | android-xiao-jun/android-chat | c2539c3655c0c1f6886cdb431f6c55cda2a109aa | [
"ICU",
"MIT"
] | 2 | 2020-12-17T06:21:00.000Z | 2021-08-18T06:46:16.000Z | uikit/src/main/java/cn/wildfire/chat/kit/voip/conference/ConferenceInviteActivity.java | android-xiao-jun/android-chat | c2539c3655c0c1f6886cdb431f6c55cda2a109aa | [
"ICU",
"MIT"
] | null | null | null | uikit/src/main/java/cn/wildfire/chat/kit/voip/conference/ConferenceInviteActivity.java | android-xiao-jun/android-chat | c2539c3655c0c1f6886cdb431f6c55cda2a109aa | [
"ICU",
"MIT"
] | 1 | 2021-11-05T19:21:47.000Z | 2021-11-05T19:21:47.000Z | 43.31 | 157 | 0.636804 | 997,129 | /*
* Copyright (c) 2020 WildFireChat. All rights reserved.
*/
package cn.wildfire.chat.kit.voip.conference;
import android.text.TextUtils;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import cn.wildfire.chat.kit.conversation.forward.ForwardPromptView;
import cn.wildfire.chat.kit.conversation.pick.PickOrCreateConversationActivity;
import cn.wildfire.chat.kit.group.GroupViewModel;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfire.chat.kit.viewmodel.MessageViewModel;
import cn.wildfirechat.message.ConferenceInviteMessageContent;
import cn.wildfirechat.message.Message;
import cn.wildfirechat.message.TextMessageContent;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.UserInfo;
public class ConferenceInviteActivity extends PickOrCreateConversationActivity {
private ConferenceInviteMessageContent inviteMessage;
private MessageViewModel messageViewModel;
private UserViewModel userViewModel;
private GroupViewModel groupViewModel;
@Override
protected void afterViews() {
super.afterViews();
inviteMessage = getIntent().getParcelableExtra("inviteMessage");
messageViewModel = ViewModelProviders.of(this).get(MessageViewModel.class);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
}
@Override
protected void onPickOrCreateConversation(Conversation conversation) {
invite(conversation);
}
public void invite(Conversation conversation) {
switch (conversation.type) {
case Single:
UserInfo userInfo = userViewModel.getUserInfo(conversation.target, false);
invite(userInfo.displayName, userInfo.portrait, conversation);
break;
case Group:
GroupInfo groupInfo = groupViewModel.getGroupInfo(conversation.target, false);
invite(groupInfo.name, groupInfo.portrait, conversation);
break;
default:
break;
}
}
private void invite(String targetName, String targetPortrait, Conversation targetConversation) {
ForwardPromptView view = new ForwardPromptView(this);
view.bind(targetName, targetPortrait, "会议邀请");
MaterialDialog dialog = new MaterialDialog.Builder(this)
.customView(view, false)
.negativeText("取消")
.positiveText("发送")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
Message extraMsg = null;
if (!TextUtils.isEmpty(view.getEditText())) {
TextMessageContent content = new TextMessageContent(view.getEditText());
extraMsg = new Message();
extraMsg.content = content;
}
messageViewModel.sendMessage(targetConversation, inviteMessage);
Toast.makeText(ConferenceInviteActivity.this, "邀请成功", Toast.LENGTH_SHORT).show();
finish();
// .observe(ConferenceInviteActivity.this, new Observer<OperateResult<Integer>>() {
// @Override
// public void onChanged(@Nullable OperateResult<Integer> integerOperateResult) {
// if (integerOperateResult.isSuccess()) {
// Toast.makeText(ConferenceInviteActivity.this, "邀请成功", Toast.LENGTH_SHORT).show();
// finish();
// } else {
// Toast.makeText(ConferenceInviteActivity.this, "邀请失败" + integerOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
// }
// }
// });
}
})
.build();
dialog.show();
}
}
|
923508f2fc1a2675eac9dfc07a98d87624cf444b | 539 | java | Java | acm-module-dc2/src/main/java/com/wisdom/acm/dc2/form/DailyChangeVersionAddForm.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-module-dc2/src/main/java/com/wisdom/acm/dc2/form/DailyChangeVersionAddForm.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-module-dc2/src/main/java/com/wisdom/acm/dc2/form/DailyChangeVersionAddForm.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | 16.333333 | 55 | 0.664193 | 997,130 | package com.wisdom.acm.dc2.form;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.wisdom.base.common.aspect.LogParam;
import com.wisdom.base.common.form.BaseForm;
import lombok.Data;
import java.util.Date;
@Data
public class DailyChangeVersionAddForm extends BaseForm
{
/**
* 模块记录的id
*/
private String moudleRecordId;
/**
*模块名称
*/
private String moudleName;
/**
*模块修改备注
*/
private String modifyRemark;
/**
*修改内容
*/
private String modifyContent;
}
|
9235092d8dfd5026693cc43f34018f7027a39e49 | 42,627 | java | Java | src/main/java/org/openstreetmap/atlas/geography/PolyLine.java | Huyuntj/atlas | bb1545ed2da7a1d51f133a4bb686c064c63892eb | [
"BSD-3-Clause"
] | 188 | 2017-08-08T17:26:54.000Z | 2022-03-29T07:59:30.000Z | src/main/java/org/openstreetmap/atlas/geography/PolyLine.java | Huyuntj/atlas | bb1545ed2da7a1d51f133a4bb686c064c63892eb | [
"BSD-3-Clause"
] | 403 | 2017-08-09T16:15:25.000Z | 2022-02-16T19:33:42.000Z | src/main/java/org/openstreetmap/atlas/geography/PolyLine.java | Huyuntj/atlas | bb1545ed2da7a1d51f133a4bb686c064c63892eb | [
"BSD-3-Clause"
] | 79 | 2017-08-08T17:55:01.000Z | 2021-11-10T20:51:57.000Z | 33.25039 | 138 | 0.586835 | 997,131 | package org.openstreetmap.atlas.geography;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.locationtech.jts.geom.prep.PreparedGeometry;
import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
import org.openstreetmap.atlas.exception.CoreException;
import org.openstreetmap.atlas.geography.Snapper.SnappedLocation;
import org.openstreetmap.atlas.geography.clipping.Clip;
import org.openstreetmap.atlas.geography.clipping.Clip.ClipType;
import org.openstreetmap.atlas.geography.converters.WkbLocationConverter;
import org.openstreetmap.atlas.geography.converters.WkbPolyLineConverter;
import org.openstreetmap.atlas.geography.converters.WktLocationConverter;
import org.openstreetmap.atlas.geography.converters.WktPolyLineConverter;
import org.openstreetmap.atlas.geography.converters.jts.JtsMultiPolygonToMultiPolygonConverter;
import org.openstreetmap.atlas.geography.converters.jts.JtsPointConverter;
import org.openstreetmap.atlas.geography.converters.jts.JtsPolyLineConverter;
import org.openstreetmap.atlas.geography.converters.jts.JtsPolygonConverter;
import org.openstreetmap.atlas.geography.geojson.GeoJsonBuilder;
import org.openstreetmap.atlas.geography.geojson.GeoJsonBuilder.LocationIterableProperties;
import org.openstreetmap.atlas.geography.geojson.GeoJsonGeometry;
import org.openstreetmap.atlas.geography.geojson.GeoJsonObject;
import org.openstreetmap.atlas.geography.geojson.GeoJsonType;
import org.openstreetmap.atlas.geography.geojson.GeoJsonUtils;
import org.openstreetmap.atlas.geography.matching.PolyLineMatch;
import org.openstreetmap.atlas.streaming.resource.WritableResource;
import org.openstreetmap.atlas.streaming.writers.JsonWriter;
import org.openstreetmap.atlas.utilities.collections.Iterables;
import org.openstreetmap.atlas.utilities.collections.MultiIterable;
import org.openstreetmap.atlas.utilities.collections.StringList;
import org.openstreetmap.atlas.utilities.scalars.Angle;
import org.openstreetmap.atlas.utilities.scalars.Distance;
import org.openstreetmap.atlas.utilities.scalars.Ratio;
import org.openstreetmap.atlas.utilities.tuples.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
/**
* A PolyLine is a set of {@link Location}s in a specific order
*
* @author matthieun
* @author mgostintsev
* @author Sid
*/
public class PolyLine implements Collection<Location>, Located, Serializable, GeometryPrintable,
GeoJsonGeometry, GeometricObject
{
public static final PolyLine TEST_POLYLINE = new PolyLine(Location.TEST_3, Location.TEST_7,
Location.TEST_4, Location.TEST_1, Location.TEST_5);
public static final PolyLine TEST_POLYLINE_2 = new PolyLine(Location.TEST_1, Location.TEST_5,
Location.TEST_4, Location.TEST_3, Location.TEST_7);
public static final PolyLine CENTER = new PolyLine(Location.CENTER);
public static final PolyLine SIMPLE_POLYLINE = new PolyLine(Location.forString("1,1"),
Location.forString("2,2"));
public static final String SEPARATOR = ":";
protected static final int SIMPLE_STRING_LENGTH = 200;
private static final JtsMultiPolygonToMultiPolygonConverter JTS_MULTIPOLYGON_CONVERTER = new JtsMultiPolygonToMultiPolygonConverter();
private static final JtsPolygonConverter JTS_POLYGON_CONVERTER = new JtsPolygonConverter();
private static final JtsPointConverter JTS_POINT_CONVERTER = new JtsPointConverter();
private static final JtsPolyLineConverter JTS_POLYLINE_CONVERTER = new JtsPolyLineConverter();
private static final long serialVersionUID = -3291779878869865427L;
private static final Logger logger = LoggerFactory.getLogger(PolyLine.class);
private static final String IMMUTABLE_POLYLINE = "A polyline is immutable";
private final List<Location> points;
private transient PreparedGeometry prepared;
public static GeoJsonObject asGeoJson(final Iterable<? extends Iterable<Location>> geometries)
{
return new GeoJsonBuilder().create(Iterables.translate(geometries,
geometry -> new LocationIterableProperties(geometry, new HashMap<>())));
}
/**
* Generate a random {@link PolyLine} within bounds.
*
* @param numberPoints
* The number of points in the {@link PolyLine}
* @param bounds
* The bounds for the points to be in
* @return The random {@link PolyLine}
*/
public static PolyLine random(final int numberPoints, final Rectangle bounds)
{
final List<Location> locations = new ArrayList<>();
IntStream.range(0, numberPoints).forEach(index -> locations.add(Location.random(bounds)));
return new PolyLine(locations);
}
public static void saveAsGeoJson(final Iterable<? extends Iterable<Location>> geometries,
final WritableResource resource)
{
try (JsonWriter writer = new JsonWriter(resource))
{
writer.write(asGeoJson(geometries).jsonObject());
}
}
/**
* Create a {@link PolyLine} from Well Known Binary
*
* @param wkb
* The Well Known Binary
* @return The {@link PolyLine}
*/
public static PolyLine wkb(final byte[] wkb)
{
return new WkbPolyLineConverter().backwardConvert(wkb);
}
/**
* Create a {@link PolyLine} from Well Known Text
*
* @param wkt
* The Well Known Text
* @return The {@link PolyLine}
*/
public static PolyLine wkt(final String wkt)
{
return new WktPolyLineConverter().backwardConvert(wkt);
}
public PolyLine(final Iterable<? extends Location> points)
{
this(Iterables.asList(points));
}
public PolyLine(final List<? extends Location> points)
{
if (points.isEmpty())
{
throw new CoreException("Cannot have an empty PolyLine or Polygon.");
}
this.points = new ArrayList<>(points);
}
public PolyLine(final Location... points)
{
this(Iterables.iterable(points));
}
@Override
public boolean add(final Location e)
{
throw new IllegalAccessError("Cannot add a Location to a PolyLine.");
}
@Override
public boolean addAll(final Collection<? extends Location> collection)
{
throw new IllegalAccessError("Cannot add Locations to a PolyLine.");
}
/**
* Return a {@link List} of {@link Tuple} that contains the Angle {@link Angle} and
* {@link Location} of all {@link Angle}s that are greater than or equal to the target
* {@link Angle}.
*
* @param target
* The threshold {@link Angle} used for comparison.
* @return The {@link List} of {@link Tuple} that contains the {@link Angle} and
* {@link Location} of all results
*/
public List<Tuple<Angle, Location>> anglesGreaterThanOrEqualTo(final Angle target)
{
final List<Tuple<Angle, Location>> result = new ArrayList<>();
final List<Segment> segments = segments();
if (segments.isEmpty() || segments.size() == 1)
{
return result;
}
for (int i = 1; i < segments.size(); i++)
{
final Segment first = segments.get(i - 1);
final Segment second = segments.get(i);
final Optional<Heading> firstHeading = first.heading();
final Optional<Heading> secondHeading = second.heading();
if (firstHeading.isPresent() && secondHeading.isPresent())
{
final Angle candidate = firstHeading.get().difference(secondHeading.get());
if (candidate.isGreaterThanOrEqualTo(target))
{
final Tuple<Angle, Location> tuple = Tuple.createTuple(candidate, first.end());
result.add(tuple);
}
}
}
return result;
}
/**
* Return a {@link List} of {@link Tuple} that contains the {@link Angle} and {@link Location}
* of all {@link Angle}s that are less than or equal to the target {@link Angle}.
*
* @param target
* The threshold {@link Angle} used for comparison.
* @return The {@link List} of {@link Tuple} that contains the {@link Angle} and
* {@link Location} of all results
*/
public List<Tuple<Angle, Location>> anglesLessThanOrEqualTo(final Angle target)
{
final List<Tuple<Angle, Location>> result = new ArrayList<>();
final List<Segment> segments = segments();
if (segments.isEmpty() || segments.size() == 1)
{
return result;
}
for (int i = 1; i < segments.size(); i++)
{
final Segment first = segments.get(i - 1);
final Segment second = segments.get(i);
final Optional<Heading> firstHeading = first.heading();
final Optional<Heading> secondHeading = second.heading();
if (firstHeading.isPresent() && secondHeading.isPresent())
{
final Angle candidate = firstHeading.get().difference(secondHeading.get());
if (candidate.isLessThanOrEqualTo(target))
{
final Tuple<Angle, Location> tuple = Tuple.createTuple(candidate, first.end());
result.add(tuple);
}
}
}
return result;
}
/**
* Append the given {@link PolyLine} to this one, if possible.
*
* @param other
* The {@link PolyLine} to append
* @return the new, combined {@link PolyLine}
*/
public PolyLine append(final PolyLine other)
{
if (this.last().equals(other.first()))
{
return new PolyLine(new MultiIterable<>(this, other.truncate(1, 0)));
}
else
{
throw new CoreException(
"Cannot append {} to {} - the end and start points do not match.",
other.toWkt(), this.toWkt());
}
}
@Override
public JsonObject asGeoJsonGeometry()
{
return GeoJsonUtils.geometry(GeoJsonType.LINESTRING,
GeoJsonUtils.locationsToCoordinates(this.points));
}
/**
* Return the average distance from this {@link PolyLine}'s shape points to the other shape, and
* the other shape's shape points to this polyline.
*
* @param other
* The other shape to compare to
* @return The two way cost distance to the other {@link PolyLine}
*/
public Distance averageDistanceTo(final PolyLine other)
{
return averageOneWayDistanceTo(other).add(other.averageOneWayDistanceTo(this))
.scaleBy(Ratio.HALF);
}
/**
* Return the average distance from this {@link PolyLine}'s shape points to the other shape,
* using a one-way snapping.
*
* @param other
* The other shape to compare to
* @return The one way cost distance to the other {@link PolyLine}
*/
public Distance averageOneWayDistanceTo(final PolyLine other)
{
Distance costDistance = Distance.ZERO;
for (final Location shapePoint : this)
{
costDistance = costDistance.add(shapePoint.snapTo(other).getDistance());
}
return costDistance.scaleBy(1.0 / this.size());
}
/**
* Return a sub-{@link PolyLine} of this {@link PolyLine}
*
* @param start
* The start location to include
* @param startOccurrence
* The occurrence index starting from 0 for the end location, in case of self
* intersecting or ring polylines.
* @param end
* The end location to include
* @param endOccurrence
* The occurrence index starting from 0 for the end location, in case of self
* intersecting or ring polylines.
* @return The sub-{@link PolyLine} including start and end
*/
public PolyLine between(final Location start, final int startOccurrence, final Location end,
final int endOccurrence)
{
final List<Location> result = new ArrayList<>();
boolean started = false;
int startIndex = 0;
int endIndex = 0;
for (final Location location : this)
{
if (location.equals(start) && startOccurrence == startIndex++)
{
started = true;
}
if (location.equals(end) && endOccurrence == endIndex++)
{
if (!started)
{
throw new CoreException(
"Found end first! {}(occurrence {}) and {}(occurrence {}) are not in order with respect to {}",
start, startOccurrence, end, endOccurrence, this.toWkt());
}
started = false;
result.add(location);
// Break here to avoid confusion with self-intersecting polylines.
break;
}
if (started)
{
result.add(location);
}
}
if (started)
{
throw new CoreException("(Start was {}) End {} is not in polyLine {}", start, end,
this);
}
return new PolyLine(result);
}
@Override
public Rectangle bounds()
{
return Rectangle.forLocations(this);
}
@Override
public void clear()
{
throw new IllegalAccessError(IMMUTABLE_POLYLINE);
}
/**
* Clip this feature on a {@link MultiPolygon}
*
* @param clipping
* The {@link MultiPolygon} to clip to
* @param clipType
* The clip type (AND, OR, XOR or NOT).
* @return The clip object containing the clipped features.
*/
public Clip clip(final MultiPolygon clipping, final ClipType clipType)
{
return new Clip(clipType, this, clipping);
}
/**
* Clip this feature on a {@link Polygon}
*
* @param clipping
* The {@link Polygon} to clip to
* @param clipType
* The clip type (AND, OR, XOR or NOT).
* @return The clip object containing the clipped features.
*/
public Clip clip(final Polygon clipping, final ClipType clipType)
{
return new Clip(clipType, this, clipping);
}
/**
* @param location
* The {@link Location} to test
* @return True if one of the vertices of this {@link PolyLine} is the provided {@link Location}
*/
public boolean contains(final Location location)
{
for (final Location thisLocation : this)
{
if (thisLocation.equals(location))
{
return true;
}
}
return false;
}
@Override
public final boolean contains(final Object object)
{
if (object instanceof Location)
{
return contains((Location) object);
}
if (object instanceof Segment)
{
return contains((Segment) object);
}
throw new IllegalAccessError(
"A polyline can contain a Segment or Location only. Maybe you meant \"covers\"?");
}
/**
* @param segment
* The {@link Segment} to test
* @return True if one of the segments of this {@link PolyLine} is the provided {@link Segment}
*/
public boolean contains(final Segment segment)
{
final List<Segment> segments = this.segments();
for (final Segment thisSegment : segments)
{
if (thisSegment.equals(segment))
{
return true;
}
}
return false;
}
@Override
public boolean containsAll(final Collection<?> collection)
{
throw new IllegalAccessError();
}
/**
* Get the cost {@link Distance} to the set of {@link Segment}s that are connected and that
* provide a new {@link PolyLine} that is the closest in shape to this {@link PolyLine}
*
* @param candidates
* The candidate {@link PolyLine}s to match to this {@link PolyLine}
* @return The best reconstructed match from this PolyLine.
*/
public PolyLineMatch costDistanceToOneWay(final Iterable<PolyLine> candidates)
{
return new PolyLineMatch(this, Iterables.asList(candidates));
}
@Override
public boolean equals(final Object other)
{
if (other instanceof PolyLine)
{
final PolyLine that = (PolyLine) other;
return Iterables.equals(this, that);
}
return false;
}
/**
* Tests if this {@link PolyLine} has the same shape as another {@link PolyLine}. This is
* different from equals as some {@link PolyLine}s that are different can still have the same
* shape, by being reversed or by self intersecting in the same point for example.
*
* @param other
* The other {@link PolyLine} to compare to
* @return True if they both have the same shape
*/
public boolean equalsShape(final PolyLine other)
{
return this.overlapsShapeOf(other) && other.overlapsShapeOf(this);
}
/**
* @return the final {@link Heading} for this {@link PolyLine}, based on the {@link Heading} of
* the last {@link Segment}.
*/
public Optional<Heading> finalHeading()
{
final List<Segment> segments = this.segments();
return segments.size() > 0 ? segments.get(segments.size() - 1).heading() : Optional.empty();
}
/**
* @return The first {@link Location} of this {@link PolyLine}
*/
public Location first()
{
return size() > 0 ? get(0) : null;
}
/**
* @param index
* The index to query
* @return The {@link Location} at the index provided in this {@link PolyLine}
*/
public Location get(final int index)
{
if (index < 0 || index >= size())
{
throw new CoreException("Cannot get a Location with index " + index
+ ", which is not between 0 and " + size());
}
return this.points.get(index);
}
@Override
public GeoJsonType getGeoJsonType()
{
return GeoJsonType.LINESTRING;
}
@Override
public int hashCode()
{
int result = 0;
for (final Location location : this)
{
result += location.hashCode();
}
return result;
}
/**
* @return The difference, if available, between the last {@link Segment}'s {@link Heading} and
* the first {@link Segment}'s {@link Heading}
*/
public Optional<Angle> headingDifference()
{
if (this.size() <= 1)
{
return Optional.empty();
}
if (this.size() == 2)
{
return Optional.of(Angle.NONE);
}
else
{
final List<Segment> segments = this.segments();
final Segment first = segments.get(0);
final Segment last = segments.get(segments.size() - 1);
final Optional<Heading> heading1 = first.heading();
if (!heading1.isPresent())
{
return Optional.empty();
}
final Optional<Heading> heading2 = last.heading();
if (!heading2.isPresent())
{
return Optional.empty();
}
return Optional.of(heading2.get().subtract(heading1.get()));
}
}
/**
* @return the initial {@link Heading} for this {@link PolyLine}, based on the {@link Heading}
* of the first {@link Segment}.
*/
public Optional<Heading> initialHeading()
{
final List<Segment> segments = this.segments();
return segments.size() > 0 ? segments.get(0).heading() : Optional.empty();
}
/**
* @return All the locations in this {@link PolyLine} except the first and last.
*/
public Iterable<Location> innerLocations()
{
return this.truncate(1, 1);
}
public Set<Location> intersections(final PolyLine candidate)
{
final Set<Location> result = new HashSet<>();
if (this instanceof Segment)
{
result.addAll(candidate.intersections((Segment) this));
}
else
{
final List<Segment> segments = this.segments();
segments.forEach(segment ->
{
final Set<Location> intersections = segment.intersections(candidate);
result.addAll(intersections);
});
}
return result;
}
public Set<Location> intersections(final Segment candidate)
{
final Set<Location> result = new HashSet<>();
final List<Segment> segments = this.segments();
segments.forEach(segment ->
{
final Location intersection = segment.intersection(candidate);
if (intersection != null)
{
result.add(intersection);
}
});
return result;
}
/**
* Test if two {@link PolyLine}s intersect.
*
* @param other
* The other {@link PolyLine}
* @return True if this {@link PolyLine} intersects the other at least once.
*/
@Override
public boolean intersects(final PolyLine other)
{
if (this.prepared == null)
{
this.prepared = PreparedGeometryFactory.prepare(JTS_POLYLINE_CONVERTER.convert(this));
}
return this.prepared.intersects(JTS_POLYLINE_CONVERTER.convert(other));
}
public boolean isClosed()
{
return JTS_POLYLINE_CONVERTER.convert(this).isClosed();
}
@Override
public final boolean isEmpty()
{
return this.points.isEmpty();
}
/**
* @return True if this {@link PolyLine} is a single point, i.e. all the points are the same.
*/
public boolean isPoint()
{
Location firstPoint = null;
for (final Location point : this.points)
{
if (firstPoint == null)
{
firstPoint = point;
continue;
}
if (!point.equals(firstPoint))
{
return false;
}
}
return true;
}
public boolean isSimple()
{
if (this.prepared == null)
{
this.prepared = PreparedGeometryFactory.prepare(JTS_POLYLINE_CONVERTER.convert(this));
}
return this.prepared.getGeometry().isSimple();
}
@Override
public Iterator<Location> iterator()
{
return this.points.iterator();
}
public Location last()
{
return this.points.size() > 0 ? get(size() - 1) : null;
}
public Distance length()
{
Distance result = Distance.ZERO;
final List<Segment> segments = this.segments();
for (final Segment segment : segments)
{
result = result.add(segment.length());
}
return result;
}
/**
* @return The biggest Angle in this {@link PolyLine}
*/
public Angle maximumAngle()
{
final List<Segment> segments = segments();
if (segments.isEmpty())
{
return null;
}
if (segments.size() == 1)
{
return Angle.NONE;
}
Angle maximum = Angle.NONE;
for (int i = 1; i < segments.size(); i++)
{
final Segment first = segments.get(i - 1);
final Segment second = segments.get(i);
final Optional<Heading> firstHeading = first.heading();
final Optional<Heading> secondHeading = second.heading();
if (firstHeading.isPresent() && secondHeading.isPresent())
{
final Angle candidate = firstHeading.get().difference(secondHeading.get());
if (candidate.isGreaterThan(maximum))
{
maximum = candidate;
}
}
}
return maximum;
}
/**
* @return The location of the biggest Angle in this {@link PolyLine}
*/
public Optional<Location> maximumAngleLocation()
{
final List<Segment> segments = segments();
if (segments.isEmpty() || segments.size() == 1)
{
return Optional.empty();
}
Angle maximum = Angle.NONE;
Location maximumAngleLocation = null;
for (int i = 1; i < segments.size(); i++)
{
final Segment first = segments.get(i - 1);
final Segment second = segments.get(i);
final Optional<Heading> firstHeading = first.heading();
final Optional<Heading> secondHeading = second.heading();
if (firstHeading.isPresent() && secondHeading.isPresent())
{
final Angle candidate = firstHeading.get().difference(secondHeading.get());
if (candidate.isGreaterThan(maximum) || maximumAngleLocation == null)
{
maximum = candidate;
maximumAngleLocation = first.end();
}
}
}
return Optional.ofNullable(maximumAngleLocation);
}
public Location middle()
{
return offsetFromStart(Ratio.HALF);
}
/**
* Get the number of times a location appears in this {@link PolyLine}. Most useful for self
* intersecting or ring {@link PolyLine}s.
*
* @param node
* The location to test
* @return The number of occurrences in this {@link PolyLine}. 0 if it never shows up.
*/
public int occurrences(final Location node)
{
int result = 0;
for (final Location location : this)
{
if (location.equals(node))
{
result++;
}
}
return result;
}
/**
* Get the offset from the start of the node's location
*
* @param node
* The location to test
* @param occurrenceIndex
* In case of a self intersecting polyline (one or more locations appear more than
* once), indicate the index at which this method should return the location. 0 would
* be first occurrence, 1 second, etc.
* @return The offset ratio from the start of the {@link PolyLine}
*/
public Ratio offsetFromStart(final Location node, final int occurrenceIndex)
{
final Distance max = this.length();
Distance candidate = Distance.ZERO;
Location previous = this.first();
int index = 0;
for (final Location location : this)
{
candidate = candidate.add(previous.distanceTo(location));
if (location.equals(node) && occurrenceIndex == index++)
{
return Ratio.ratio(candidate.asMeters() / max.asMeters());
}
previous = location;
}
throw new CoreException("The location {} is not a node of the PolyLine", node);
}
public Location offsetFromStart(final Ratio ratio)
{
final Distance length = length();
final Distance stop = length.scaleBy(ratio);
Distance accumulated = Distance.ZERO;
final List<Segment> segments = this.segments();
for (final Segment segment : segments)
{
if (accumulated.add(segment.length()).isGreaterThan(stop))
{
// This is the proper segment
final Ratio segmentRatio = Ratio.ratio(
stop.substract(accumulated).asMeters() / segment.length().asMeters());
return segment.offsetFromStart(segmentRatio);
}
if (accumulated.add(segment.length()).equals(stop))
{
return segment.end();
}
accumulated = accumulated.add(segment.length());
}
throw new CoreException("This exception should never be thrown.");
}
/**
* @return The overall heading of the {@link PolyLine}: the heading between the start point and
* the end point.
*/
public Optional<Heading> overallHeading()
{
if (this.isPoint())
{
logger.warn("Cannot compute a PolyLine's heading when it has zero length : {}", this);
return Optional.empty();
}
if (this.first().equals(this.last()))
{
if (logger.isWarnEnabled())
{
logger.warn("Cannot compute overall heading when the polyline has "
+ "same start and end locations : {}", this.first().toWkt());
}
return Optional.empty();
}
return Optional.ofNullable(this.first().headingTo(this.last()));
}
/**
* Tests if this {@link PolyLine} has at least the same shape as another {@link PolyLine}. If
* this {@link PolyLine} is made up of {@link Segment}s ABC and the given {@link PolyLine} is
* made up of BC, this would return true, despite the excess {@link Segment}.
*
* @param other
* The other {@link PolyLine} to compare to
* @return True if this {@link PolyLine} has at least the same shape as the other (but possibly
* more)
*/
public boolean overlapsShapeOf(final PolyLine other)
{
final Set<Segment> thisSegments = new HashSet<>();
final List<Segment> segments = this.segments();
segments.forEach(segment ->
{
thisSegments.add(segment);
thisSegments.add(segment.reversed());
});
final List<Segment> otherSegments = other.segments();
for (final Segment otherSegment : otherSegments)
{
if (!thisSegments.contains(otherSegment))
{
return false;
}
}
return true;
}
/**
* Prepends the given {@link PolyLine} to this one, if possible.
*
* @param other
* The {@link PolyLine} to prepend
* @return the new, combined {@link PolyLine}
*/
public PolyLine prepend(final PolyLine other)
{
if (this.first().equals(other.last()))
{
return new PolyLine(new MultiIterable<>(other, this.truncate(1, 0)));
}
else
{
throw new CoreException(
"Cannot prepend {} to {} - the end and start points do not match.",
other.toWkt(), this.toWkt());
}
}
@Override
public boolean remove(final Object object)
{
throw new IllegalAccessError(IMMUTABLE_POLYLINE);
}
@Override
public boolean removeAll(final Collection<?> collection)
{
throw new IllegalAccessError(IMMUTABLE_POLYLINE);
}
@Override
public boolean retainAll(final Collection<?> collection)
{
throw new IllegalAccessError(IMMUTABLE_POLYLINE);
}
public PolyLine reversed()
{
final List<Location> reversed = new ArrayList<>();
for (int i = this.size() - 1; i >= 0; i--)
{
reversed.add(this.get(i));
}
return new PolyLine(reversed);
}
public void saveAsGeoJson(final WritableResource resource)
{
final List<Iterable<Location>> geometries = new ArrayList<>();
geometries.add(this);
saveAsGeoJson(geometries, resource);
}
/**
* @return All the {@link Segment}s that represent this {@link PolyLine}. If the
* {@link PolyLine} is empty, then the {@link Segment} list is empty. If the
* {@link PolyLine} has only one item, the {@link Segment} list contains only one
* {@link Segment} made of twice the same {@link Location}. If the {@link PolyLine} has
* more than one {@link Location}, then the result is a list of {@link Segment}s. Note:
* This method should be used carefully. Each call to it will cause a rebuild of the
* {@link List}, which can be very inefficient for long {@link PolyLine}s. To avoid
* this, the caller can call segments once and cache the results.
*/
public List<Segment> segments()
{
final List<Segment> result = new ArrayList<>(this.size());
if (size() == 1)
{
result.add(new Segment(get(0), get(0)));
}
else if (this instanceof Segment)
{
result.add((Segment) this);
}
else
{
Location previous = null;
for (final Location location : this)
{
if (previous == null)
{
previous = location;
continue;
}
result.add(new Segment(previous, location));
previous = location;
}
}
return result;
}
/**
* Returns a Set of {@link Location} for all self-intersections, other than shape points for
* this {@link PolyLine}. Separated from selfIntersects() to avoid degrading its performance.
*
* @return the set of locations
*/
public Set<Location> selfIntersections()
{
Set<Location> intersections = null;
final boolean isPolygon = this instanceof Polygon;
if (this.isSimple() && !isPolygon)
{
if (this.isClosed())
{
intersections = new HashSet<>();
intersections.add(this.first());
return intersections;
}
return Collections.emptySet();
}
// Exclude point-segments, so we know which segments are actually consecutive
final List<Segment> segments = this.segments().stream()
.filter(segment -> !segment.isPoint()).collect(Collectors.toList());
// Consecutive segments should not be considered (they always have common point)
for (int i = 0; i < segments.size() - 2; i++)
{
// For Polygons the last segment is consecutive to the first
final int limit = isPolygon && i == 0 ? segments.size() - 1 : segments.size();
// Only consider 'higher' segments.
// No need to do a reverse check with the 'lower' segments again.
for (int j = i + 2; j < limit; j++)
{
final Location intersection = segments.get(i).intersection(segments.get(j));
if (intersection != null)
{
// Self-intersection is a low probability event.
// Only allocate if needed
if (intersections == null)
{
intersections = new HashSet<>();
}
intersections.add(intersection);
}
}
}
return intersections == null ? Collections.emptySet() : intersections;
}
/**
* @return True if the {@link PolyLine} self intersects at locations other than shape points.
*/
public boolean selfIntersects()
{
// See comments on algorithm in selfIntersections()
final boolean isPolygon = this instanceof Polygon;
final List<Segment> segments = this.segments().stream()
.filter(segment -> !segment.isPoint()).collect(Collectors.toList());
for (int i = 0; i < segments.size() - 2; i++)
{
final int limit = isPolygon && i == 0 ? segments.size() - 1 : segments.size();
for (int j = i + 2; j < limit; j++)
{
if (segments.get(i).intersection(segments.get(j)) != null)
{
return true;
}
}
}
return false;
}
public PolyLine shiftFirstAlongGreatCircle(final Heading initialHeading,
final Distance distance)
{
return new PolyLine(new MultiIterable<>(
Iterables.from(this.first().shiftAlongGreatCircle(initialHeading, distance)),
this.truncate(1, 0)));
}
public PolyLine shiftLastAlongGreatCircle(final Heading initialHeading, final Distance distance)
{
return new PolyLine(new MultiIterable<>(this.truncate(0, 1),
Iterables.from(this.last().shiftAlongGreatCircle(initialHeading, distance))));
}
/**
* Return the smaller one between the shortest distance from this {@link PolyLine}'s shape
* points to the other shape, and the other shape's shape points to this polyline.
*
* @param other
* The other shape to compare to
* @return The two way shortest distance to the other {@link PolyLine}
*/
public Distance shortestDistanceTo(final PolyLine other)
{
final Distance one = shortestOneWayDistanceTo(other);
final Distance two = other.shortestOneWayDistanceTo(this);
return one.isLessThan(two) ? one : two;
}
/**
* Return the shortest distance from this {@link PolyLine}'s shape points to the other shape,
* using a one-way snapping.
*
* @param other
* The other shape to compare to
* @return The shortest one way cost distance to the other {@link PolyLine}
*/
public Distance shortestOneWayDistanceTo(final PolyLine other)
{
Distance shortest = Distance.MAXIMUM;
for (final Location shapePoint : this)
{
final Distance current = shapePoint.snapTo(other).getDistance();
shortest = current.isLessThan(shortest) ? current : shortest;
}
return shortest;
}
@Override
public int size()
{
return this.points.size();
}
/**
* Snap an origin {@link Location} to this {@link PolyLine} using a {@link Snapper}
*
* @param origin
* The origin {@link Location} to snap
* @return The corresponding {@link SnappedLocation}
*/
public SnappedLocation snapFrom(final Location origin)
{
return new Snapper().snap(origin, this);
}
@Override
public Object[] toArray()
{
return this.points.toArray();
}
@Override
public <T> T[] toArray(final T[] array)
{
return this.points.toArray(array);
}
public String toCompactString()
{
final StringList stringList = new StringList();
this.forEach(location ->
{
stringList.add(location.toCompactString());
});
return stringList.join(SEPARATOR);
}
public String toSimpleString()
{
final String string = toCompactString();
if (string.length() > SIMPLE_STRING_LENGTH + 1)
{
return string.substring(0, SIMPLE_STRING_LENGTH / 2) + "..."
+ string.substring(string.length() - SIMPLE_STRING_LENGTH / 2);
}
return string;
}
@Override
public String toString()
{
return toWkt();
}
/**
* @return This {@link PolyLine} as Well Known Binary
*/
@Override
public byte[] toWkb()
{
if (this.size() == 1)
{
// Handle a single location polyLine
return new WkbLocationConverter().convert(this.first());
}
return new WkbPolyLineConverter().convert(this);
}
/**
* @return This {@link PolyLine} as Well Known Text
*/
@Override
public String toWkt()
{
if (this.size() == 1)
{
// Handle a single location polyLine
return new WktLocationConverter().convert(this.first());
}
return new WktPolyLineConverter().convert(this);
}
/**
* Truncates this {@link PolyLine} at the given start and end index. If the provided indices are
* invalid, an empty Iterable will be returned.
*
* @param indexFromStart
* The index before which to truncate from the start
* @param indexFromEnd
* The index after which to truncate from the end
* @return all the locations in this {@link PolyLine} after truncation.
*/
public Iterable<Location> truncate(final int indexFromStart, final int indexFromEnd)
{
if (indexFromStart < 0 || indexFromEnd < 0 || indexFromStart >= this.size()
|| indexFromEnd >= this.size() || indexFromStart + indexFromEnd >= this.size())
{
logger.debug("Invalid start index {} or end index {} supplied.", indexFromStart,
indexFromEnd);
return Collections.emptyList();
}
return Iterables.stream(this).truncate(indexFromStart, indexFromEnd);
}
@Override
public boolean within(final GeometricSurface surface)
{
return surface.fullyGeometricallyEncloses(this);
}
/**
* @return This {@link PolyLine} without duplicate consecutive shape points. Non-consecutive
* shape points will remain unchanged.
*/
public PolyLine withoutDuplicateConsecutiveShapePoints()
{
final List<Location> shapePoints = new ArrayList<>();
boolean hasDuplicates = false;
final Iterator<Location> locationIterator = this.iterator();
// PolyLines are only valid if at least one point exists, so it is safe to call next() once.
Location previousLocation = locationIterator.next();
shapePoints.add(previousLocation);
while (locationIterator.hasNext())
{
final Location currentLocation = locationIterator.next();
if (!currentLocation.equals(previousLocation))
{
shapePoints.add(currentLocation);
}
else
{
hasDuplicates = true;
}
previousLocation = currentLocation;
}
return hasDuplicates ? new PolyLine(shapePoints) : this;
}
protected final List<Location> getPoints()
{
return this.points;
}
}
|
92350a4369df11cd7516474aa35a4b91daa4e643 | 4,408 | java | Java | chrome/browser/password_edit_dialog/android/java/src/org/chromium/chrome/browser/password_edit_dialog/PasswordEditDialogView.java | sunlongbo/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/password_edit_dialog/android/java/src/org/chromium/chrome/browser/password_edit_dialog/PasswordEditDialogView.java | sunlongbo/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/password_edit_dialog/android/java/src/org/chromium/chrome/browser/password_edit_dialog/PasswordEditDialogView.java | sunlongbo/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | 41.196262 | 100 | 0.727541 | 997,132 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.password_edit_dialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import org.chromium.base.Callback;
import org.chromium.ui.modelutil.PropertyKey;
import org.chromium.ui.modelutil.PropertyModel;
import java.util.List;
/**
* The custom view for password edit modal dialog.
*/
public class PasswordEditDialogView extends LinearLayout implements OnItemSelectedListener {
private Spinner mUsernamesSpinner;
private TextView mPasswordView;
private TextView mFooterView;
private Callback<Integer> mUsernameSelectedCallback;
/**
* The view binder method to propagate parameters from model to view
*/
public static void bind(
PropertyModel model, PasswordEditDialogView dialogView, PropertyKey propertyKey) {
if (propertyKey == PasswordEditDialogProperties.USERNAMES) {
// Propagation of USERNAMES property triggers passing both USERNAMES and
// SELECTED_USERNAME_INDEX properties to the view. This is safe because both properties
// are set through property model builder and available by the time the property model
// is bound to the view. The SELECTED_USERNAME_INDEX property is writable since it
// maintains username index of the user, currently selected in UI. Updating the property
// by itself doesn't get propagated to the view as the value originates in the view and
// gets routed to coordinator through USERNAME_SELECTED_CALLBACK.
dialogView.setUsernames(model.get(PasswordEditDialogProperties.USERNAMES),
model.get(PasswordEditDialogProperties.SELECTED_USERNAME_INDEX));
} else if (propertyKey == PasswordEditDialogProperties.PASSWORD) {
dialogView.setPassword(model.get(PasswordEditDialogProperties.PASSWORD));
} else if (propertyKey == PasswordEditDialogProperties.FOOTER) {
dialogView.setFooter(model.get(PasswordEditDialogProperties.FOOTER));
} else if (propertyKey == PasswordEditDialogProperties.USERNAME_SELECTED_CALLBACK) {
dialogView.setUsernameSelectedCallback(
model.get(PasswordEditDialogProperties.USERNAME_SELECTED_CALLBACK));
}
}
public PasswordEditDialogView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Stores references to the dialog fields after dialog inflation.
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mUsernamesSpinner = findViewById(R.id.usernames_spinner);
mUsernamesSpinner.setOnItemSelectedListener(this);
mPasswordView = findViewById(R.id.password);
mFooterView = findViewById(R.id.footer);
}
void setUsernames(List<String> usernames, int selectedUsernameIndex) {
ArrayAdapter<String> usernamesAdapter =
new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item);
usernamesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
usernamesAdapter.addAll(usernames);
mUsernamesSpinner.setAdapter(usernamesAdapter);
mUsernamesSpinner.setSelection(selectedUsernameIndex);
}
void setPassword(String password) {
mPasswordView.setText(password);
}
void setFooter(String footer) {
mFooterView.setVisibility(!TextUtils.isEmpty(footer) ? View.VISIBLE : View.GONE);
mFooterView.setText(footer);
}
void setUsernameSelectedCallback(Callback<Integer> callback) {
mUsernameSelectedCallback = callback;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mUsernameSelectedCallback != null) {
mUsernameSelectedCallback.onResult(position);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
}
|
92350ac85005560f835808067dc2d78304d969f9 | 633 | java | Java | src/main/java/uk/co/gmescouts/stmarys/beddingplants/data/OrderRepository.java | ChrisSamo632/bedding-plants | c27e3a6b5f1d555d9d649dabf3e59604a511f9c8 | [
"MIT"
] | null | null | null | src/main/java/uk/co/gmescouts/stmarys/beddingplants/data/OrderRepository.java | ChrisSamo632/bedding-plants | c27e3a6b5f1d555d9d649dabf3e59604a511f9c8 | [
"MIT"
] | 1 | 2022-02-12T09:51:29.000Z | 2022-02-12T09:51:29.000Z | src/main/java/uk/co/gmescouts/stmarys/beddingplants/data/OrderRepository.java | ChrisSamo632/bedding-plants | c27e3a6b5f1d555d9d649dabf3e59604a511f9c8 | [
"MIT"
] | null | null | null | 37.235294 | 95 | 0.837283 | 997,133 | package uk.co.gmescouts.stmarys.beddingplants.data;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import uk.co.gmescouts.stmarys.beddingplants.data.model.Order;
import uk.co.gmescouts.stmarys.beddingplants.data.model.OrderType;
import java.util.Set;
public interface OrderRepository extends JpaRepository<Order, Long> {
Order findByNumAndCustomerSaleYear(Integer num, Integer customerSaleYear);
Set<Order> findByTypeAndCustomerSaleYear(OrderType type, Integer customerSaleYear, Sort sort);
Set<Order> findByCustomerSaleYear(Integer customerSaleYear, Sort sort);
}
|
92350bc658b9128a8c921320e94d56b5d9f60d82 | 2,288 | java | Java | mysql-connector-java-8.0.23/src/main/core-api/java/com/mysql/cj/exceptions/UnableToConnectException.java | Imobiliario-MrBelly/LP2 | d2310dac8f9c151828ac09f2fea2985e7ade662a | [
"MIT"
] | 8 | 2020-10-30T19:46:43.000Z | 2022-01-11T16:39:06.000Z | SistemaHotel/biblioteca/mysql-connector-java-8.0.25/src/main/core-api/java/com/mysql/cj/exceptions/UnableToConnectException.java | darlanaraujo/SistemaHotel | f2026c4e91610c840499f999c0195a2c303494c6 | [
"MIT"
] | 25 | 2021-03-30T14:33:26.000Z | 2021-05-10T17:37:14.000Z | SistemaHotel/biblioteca/mysql-connector-java-8.0.25/src/main/core-api/java/com/mysql/cj/exceptions/UnableToConnectException.java | darlanaraujo/SistemaHotel | f2026c4e91610c840499f999c0195a2c303494c6 | [
"MIT"
] | 5 | 2020-10-29T18:22:12.000Z | 2021-12-09T21:48:00.000Z | 37.508197 | 125 | 0.731643 | 997,134 | /*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 2.0, as published by the
* Free Software Foundation.
*
* This program is also distributed with certain software (including but not
* limited to OpenSSL) that is licensed under separate terms, as designated in a
* particular file or component or in included license documentation. The
* authors of MySQL hereby grant you an additional permission to link the
* program and your derivative works with the separately licensed software that
* they have included with MySQL.
*
* Without limiting anything contained in the foregoing, this file, which is
* part of MySQL Connector/J, is also subject to the Universal FOSS Exception,
* version 1.0, a copy of which can be found at
* http://oss.oracle.com/licenses/universal-foss-exception.
*
* 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, version 2.0,
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.cj.exceptions;
public class UnableToConnectException extends CJException {
private static final long serialVersionUID = 6824175447292574109L;
public UnableToConnectException() {
super();
setSQLState("08001");
}
public UnableToConnectException(String message) {
super(message);
setSQLState("08001");
}
public UnableToConnectException(String message, Throwable cause) {
super(message, cause);
setSQLState("08001");
}
public UnableToConnectException(Throwable cause) {
super(cause);
setSQLState("08001");
}
public UnableToConnectException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
setSQLState("08001");
}
}
|
92350d0ad3cea02acfc500f01f3a0d25d753faef | 3,214 | java | Java | src/main/java/org/apache/flink/state/benchmark/ValueStateBenchmark.java | Aitozi/flink-benchmarks | 0f8d2e35f4915fbc7898672266f8af59009e06e1 | [
"Apache-2.0"
] | 84 | 2020-04-20T10:09:36.000Z | 2022-03-26T14:47:17.000Z | src/main/java/org/apache/flink/state/benchmark/ValueStateBenchmark.java | Aitozi/flink-benchmarks | 0f8d2e35f4915fbc7898672266f8af59009e06e1 | [
"Apache-2.0"
] | 23 | 2020-08-21T08:31:14.000Z | 2022-02-11T06:34:55.000Z | src/main/java/org/apache/flink/state/benchmark/ValueStateBenchmark.java | Aitozi/flink-benchmarks | 0f8d2e35f4915fbc7898672266f8af59009e06e1 | [
"Apache-2.0"
] | 40 | 2020-06-05T10:02:05.000Z | 2022-03-24T04:28:18.000Z | 38.722892 | 116 | 0.726198 | 997,135 | /*
* 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.flink.state.benchmark;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.flink.contrib.streaming.state.benchmark.StateBackendBenchmarkUtils.createKeyedStateBackend;
import static org.apache.flink.contrib.streaming.state.benchmark.StateBackendBenchmarkUtils.getValueState;
import static org.apache.flink.state.benchmark.StateBenchmarkConstants.setupKeyCount;
/** Implementation for listValue state benchmark testing. */
public class ValueStateBenchmark extends StateBenchmarkBase {
private ValueState<Long> valueState;
public static void main(String[] args) throws RunnerException {
Options opt =
new OptionsBuilder()
.verbosity(VerboseMode.NORMAL)
.include(".*" + ValueStateBenchmark.class.getCanonicalName() + ".*")
.build();
new Runner(opt).run();
}
@Setup
public void setUp() throws Exception {
keyedStateBackend = createKeyedStateBackend(backendType);
valueState =
getValueState(keyedStateBackend, new ValueStateDescriptor<>("kvState", Long.class));
for (int i = 0; i < setupKeyCount; ++i) {
keyedStateBackend.setCurrentKey((long) i);
valueState.update(random.nextLong());
}
keyIndex = new AtomicInteger();
}
@Benchmark
public void valueUpdate(KeyValue keyValue) throws IOException {
keyedStateBackend.setCurrentKey(keyValue.setUpKey);
valueState.update(keyValue.value);
}
@Benchmark
public void valueAdd(KeyValue keyValue) throws IOException {
keyedStateBackend.setCurrentKey(keyValue.newKey);
valueState.update(keyValue.value);
}
@Benchmark
public Long valueGet(KeyValue keyValue) throws IOException {
keyedStateBackend.setCurrentKey(keyValue.setUpKey);
return valueState.value();
}
}
|
92350e5cb00a27f3e9a6c8e9514978202e0d9270 | 1,510 | java | Java | src/test/java/de/codecentric/reedelk/scheduler/internal/scheduler/SchedulingStrategySchedulerCronTest.java | codecentric/reedelk-module-scheduler | 85459d90d62870de35a1400c503f9ac6860e4f95 | [
"Apache-2.0"
] | 6 | 2020-04-18T08:44:26.000Z | 2020-07-17T07:22:08.000Z | src/test/java/de/codecentric/reedelk/scheduler/internal/scheduler/SchedulingStrategySchedulerCronTest.java | codecentric/reedelk-module-scheduler | 85459d90d62870de35a1400c503f9ac6860e4f95 | [
"Apache-2.0"
] | 1 | 2021-12-16T13:18:44.000Z | 2021-12-16T13:18:55.000Z | src/test/java/de/codecentric/reedelk/scheduler/internal/scheduler/SchedulingStrategySchedulerCronTest.java | AlexRogalskiy/reedelk-module-scheduler | 85459d90d62870de35a1400c503f9ac6860e4f95 | [
"Apache-2.0"
] | 1 | 2021-12-16T13:18:37.000Z | 2021-12-16T13:18:37.000Z | 35.116279 | 122 | 0.755629 | 997,136 | package de.codecentric.reedelk.scheduler.internal.scheduler;
import de.codecentric.reedelk.runtime.api.component.InboundEventListener;
import de.codecentric.reedelk.scheduler.component.CronConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SchedulingStrategySchedulerCronTest {
@Mock
private InboundEventListener listener;
@Test
void shouldCorrectlyScheduleJob() {
// Given
CronConfiguration configuration = new CronConfiguration();
configuration.setExpression("* * * ? * *");
SchedulingStrategySchedulerCron strategy = strategyWith(configuration);
// When
strategy.schedule(listener);
// Then
verify(strategy).scheduleJob(any(InboundEventListener.class), any(JobDetail.class), any(Trigger.class));
}
private SchedulingStrategySchedulerCron strategyWith(CronConfiguration configuration) {
SchedulingStrategySchedulerCron strategy =
Mockito.spy(new SchedulingStrategySchedulerCron(configuration));
doNothing().when(strategy).scheduleJob(any(InboundEventListener.class), any(JobDetail.class), any(Trigger.class));
return strategy;
}
}
|
92350e79aebb9c1219dc74ee89c7e330829bbfb2 | 1,077 | java | Java | code/src/linreg/LinRegData.java | Luke-Skynet/MLDS-in-Java | 066791c9b293cedb2a346c1ea62efa2ba5cdaed3 | [
"MIT"
] | 1 | 2021-12-18T18:55:58.000Z | 2021-12-18T18:55:58.000Z | code/src/linreg/LinRegData.java | Luke-Skynet/MLDS-in-Java | 066791c9b293cedb2a346c1ea62efa2ba5cdaed3 | [
"MIT"
] | null | null | null | code/src/linreg/LinRegData.java | Luke-Skynet/MLDS-in-Java | 066791c9b293cedb2a346c1ea62efa2ba5cdaed3 | [
"MIT"
] | null | null | null | 18.568966 | 72 | 0.634169 | 997,137 | package linreg;
import math.Vector;
public class LinRegData {
private final Vector data;
private final float label;
public LinRegData(Vector data, float label) {
this.data = data;
this.label = label;
}
Vector getData() {
return data;
}
public int getDim() {
return data.getLength();
}
public float getDataValue(int i) {
return data.getValue(i);
}
public float getLabel(){
return label;
}
public static LinRegData[] format(float[][] xValues, float[] yValues) {
Vector[] vectors = new Vector[xValues.length];
for (int i = 0; i < xValues.length; i++) {
vectors[i] = new Vector(xValues[i]);
}
LinRegData[] data = new LinRegData[vectors.length];
for (int i = 0; i < data.length; i++) {
data[i] = new LinRegData(vectors[i], yValues[i]);
}
return data;
}
public static LinRegData[] format(Vector[] vectors, float[] labels) {
LinRegData[] data = new LinRegData[vectors.length];
for (int i = 0; i < data.length; i++) {
data[i] = new LinRegData(vectors[i], labels[i]);
}
return data;
}
} |
92350ed3d72bf26a8f8cb67008393f1f4f92ce10 | 181 | java | Java | src/main/java/render/clients/RenderClient.java | jschwartz73/micronaut-freemarker-aws-example | 1138400f8ac2e42e3c33719126a441f1f0c44b70 | [
"MIT"
] | 2 | 2019-05-14T21:37:42.000Z | 2021-02-13T19:48:59.000Z | src/main/java/render/clients/RenderClient.java | jschwartz73/micronaut-freemarker-aws-example | 1138400f8ac2e42e3c33719126a441f1f0c44b70 | [
"MIT"
] | null | null | null | src/main/java/render/clients/RenderClient.java | jschwartz73/micronaut-freemarker-aws-example | 1138400f8ac2e42e3c33719126a441f1f0c44b70 | [
"MIT"
] | null | null | null | 22.625 | 51 | 0.812155 | 997,138 | package render.clients;
import io.micronaut.http.client.annotation.Client;
import render.IOperations;
@Client(id="my-client")
public interface RenderClient extends IOperations {
} |
92350f86f490e715ca2394a5572c1efb9fc7f07d | 8,150 | java | Java | lib/lib-search/src/test/java/org/sagebionetworks/search/SearchDaoImplTest.java | txk1452/Synapse-Repository-Services | e530afb283e6afa0ba6df090138a0f76101370ed | [
"Apache-2.0"
] | null | null | null | lib/lib-search/src/test/java/org/sagebionetworks/search/SearchDaoImplTest.java | txk1452/Synapse-Repository-Services | e530afb283e6afa0ba6df090138a0f76101370ed | [
"Apache-2.0"
] | null | null | null | lib/lib-search/src/test/java/org/sagebionetworks/search/SearchDaoImplTest.java | txk1452/Synapse-Repository-Services | e530afb283e6afa0ba6df090138a0f76101370ed | [
"Apache-2.0"
] | null | null | null | 33.677686 | 105 | 0.730675 | 997,139 | package org.sagebionetworks.search;
import static org.junit.Assert.*;
import com.amazonaws.services.cloudsearchdomain.model.Hit;
import com.amazonaws.services.cloudsearchdomain.model.Hits;
import com.amazonaws.services.cloudsearchdomain.model.SearchRequest;
import com.amazonaws.services.cloudsearchdomain.model.SearchResult;
import com.google.common.collect.Sets;
import org.apache.commons.collections.ArrayStack;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.never;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.sagebionetworks.repo.model.search.Document;
import org.sagebionetworks.repo.model.search.DocumentTypeNames;
import org.sagebionetworks.repo.model.search.SearchResults;
import org.springframework.test.util.ReflectionTestUtils;
import com.amazonaws.services.cloudsearchv2.AmazonCloudSearch;
import com.amazonaws.services.cloudsearchv2.model.DomainStatus;
import org.sagebionetworks.repo.web.ServiceUnavailableException;
import javax.print.Doc;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Unit test for the search dao.
*
* @author jmhill
*
*/
@RunWith(MockitoJUnitRunner.class)
public class SearchDaoImplTest {
@Mock
private CloudSearchClientProvider mockCloudSearchClientProvider;
@Mock
private CloudsSearchDomainClientAdapter mockCloudSearchDomainClient;
@Spy
private SearchDaoImpl dao = new SearchDaoImpl(); //variable must be initialized here for Spy to work
private SearchResult searchResult;
private ArgumentCaptor<SearchRequest> requestArgumentCaptor;
@Before
public void setUp(){
ReflectionTestUtils.setField(dao, "cloudSearchClientProvider", mockCloudSearchClientProvider);
when(mockCloudSearchClientProvider.getCloudSearchClient()).thenReturn(mockCloudSearchDomainClient);
requestArgumentCaptor = ArgumentCaptor.forClass(SearchRequest.class);
searchResult = new SearchResult();
when(mockCloudSearchDomainClient.rawSearch(requestArgumentCaptor.capture())).thenReturn(searchResult);
}
///////////////////////////
// deleteDocuments() tests
///////////////////////////
@Test(expected = IllegalArgumentException.class)
public void testDeleteDocumentsNullDocIds(){
dao.deleteDocuments(null);
}
@Test
public void testDeleteDocumentsEmptyIdSet(){
dao.deleteDocuments(new HashSet<>());
verify(mockCloudSearchClientProvider, never()).getCloudSearchClient();
verify(mockCloudSearchDomainClient, never()).sendDocuments(any());
}
@Test
public void testDeleteDocumentsMultipleIds(){
String id1 = "syn123";
String id2 = "syn456";
//Expected documents
Document expectedDoc1 = new Document();
expectedDoc1.setId(id1);
expectedDoc1.setType(DocumentTypeNames.delete);
Document expectedDoc2 = new Document();
expectedDoc2.setId(id2);
expectedDoc2.setType(DocumentTypeNames.delete);
//method under test
dao.deleteDocuments(new LinkedHashSet<>(Arrays.asList(id1, id2)));
verify(dao, times(1)).createOrUpdateSearchDocument(Arrays.asList(expectedDoc1, expectedDoc2));
}
/////////////////////////////////////////
// createOrUpdateSearchDocument() tests
/////////////////////////////////////////
@Test (expected = IllegalArgumentException.class)
public void testCreateOrUpdateSearchDocumentNullDocument(){
dao.createOrUpdateSearchDocument((Document) null);
}
@Test
public void testCreateOrUpdateSearchDocumentSingleDocument(){
Document doc = new Document();
dao.createOrUpdateSearchDocument(doc);
verify(dao, times(1)).createOrUpdateSearchDocument(Collections.singletonList(doc));
}
@Test
public void testCreateOrUpdateSearchDocumentUsingList(){
List<Document> docList = new LinkedList<>();
dao.createOrUpdateSearchDocument(docList);
verify(mockCloudSearchClientProvider,times(1)).getCloudSearchClient();
verify(mockCloudSearchDomainClient, times(1)).sendDocuments(docList);
}
/////////////////////////
// executeSearch() tests
/////////////////////////
@Test
public void testExecuteSearch() {
SearchRequest searchRequest = new SearchRequest();
SearchResult result = dao.executeSearch(searchRequest);
assertEquals(result, searchResult);
verify(mockCloudSearchClientProvider,times(1)).getCloudSearchClient();
verify(mockCloudSearchDomainClient, times(1)).rawSearch(new SearchRequest());
}
///////////////////////
// doesDocumentExist()
///////////////////////
@Test(expected = IllegalArgumentException.class)
public void testDoesDocumentExistNullId() {
dao.doesDocumentExist(null, "etag");
}
@Test
public void testDoesDocumentExistReturnsTrue(){
helperTestDoesDocumentExist(1L, true);
}
@Test
public void testDoesDocumentExistReturnsFalse(){
helperTestDoesDocumentExist(0L, false);
}
private void helperTestDoesDocumentExist(long numFoundHits, boolean expectedBooleanResult){
searchResult.withHits(new Hits().withFound(numFoundHits));
boolean result = dao.doesDocumentExist("syn123", "etagerino");
assertEquals(expectedBooleanResult, result);
SearchRequest capturedRequest = requestArgumentCaptor.getValue();
verify(dao,times(1)).executeSearch(capturedRequest);
assertEquals("(and _id:'syn123' etag:'etagerino')", capturedRequest.getQuery());
}
//////////////////////////////
// listSearchDocuments() test
//////////////////////////////
@Test
public void testListSearchDocuments() {
long limit = 42;
long offset = 420;
SearchResult result = dao.listSearchDocuments(limit, offset);
assertEquals(searchResult, result);
SearchRequest capturedRequest = requestArgumentCaptor.getValue();
verify(dao, times(1)).executeSearch(capturedRequest);
assertEquals("matchall", capturedRequest.getQuery());
assertEquals((Long) limit, capturedRequest.getSize());
assertEquals((Long) offset, capturedRequest.getStart());
}
////////////////////////////
// deleteAllDocuments() test
////////////////////////////
@Test
public void testDeleteAllDocuments() throws InterruptedException {
String hitId1 = "syn123";
String hitId2 = "syn456";
//because deleteAllDocuments will stop only once no more documents are found,
// we must provide different SearchResult on each call to listSearchDocuments()
doAnswer(new Answer() {
private Iterator<SearchResult> searchResultIterator = Arrays.asList(
//first result w/ 2 hits
new SearchResult().withHits(new Hits().withFound(2L)
.withHit(new Hit().withId(hitId1), new Hit().withId(hitId2))),
//second result w/ 0 hits
new SearchResult().withHits(new Hits().withFound(0L))
).iterator();
@Override
public SearchResult answer(InvocationOnMock invocationOnMock) throws Throwable {
return searchResultIterator.next();
}
}).when(dao).listSearchDocuments(anyLong(), anyLong());
ArgumentCaptor<Set> idSetCaptor = ArgumentCaptor.forClass(Set.class);
doNothing().when(dao).deleteDocuments(idSetCaptor.capture());
dao.deleteAllDocuments();
verify(dao, times(2)).listSearchDocuments(1000,0);
Set<String> capturedIdSet = idSetCaptor.getValue();
verify(dao, times(1)).deleteDocuments(capturedIdSet);
assertEquals(Sets.newHashSet(hitId1, hitId2), capturedIdSet);
}
}
|
92350fd8919a09253e6578d3904f92b4341f6000 | 1,000 | java | Java | addons/web-support/api/src/main/java/org/jboss/windup/web/addons/websupport/rest/MigrationIssuesEndpoint.java | jonathanvila/windup-web | 559f6dd4295ae1bfd3f8279955182fdf17abec3d | [
"Unlicense"
] | null | null | null | addons/web-support/api/src/main/java/org/jboss/windup/web/addons/websupport/rest/MigrationIssuesEndpoint.java | jonathanvila/windup-web | 559f6dd4295ae1bfd3f8279955182fdf17abec3d | [
"Unlicense"
] | null | null | null | addons/web-support/api/src/main/java/org/jboss/windup/web/addons/websupport/rest/MigrationIssuesEndpoint.java | jonathanvila/windup-web | 559f6dd4295ae1bfd3f8279955182fdf17abec3d | [
"Unlicense"
] | null | null | null | 28.714286 | 135 | 0.722388 | 997,140 | package org.jboss.windup.web.addons.websupport.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.Map;
/**
* Gets a list of Migration issues from the server.
*
* @author <a href="mailto:envkt@example.com">David Klingenberg</a>
*/
@Path("reports/{executionId}/migrationIssues")
@Consumes("application/json")
@Produces("application/json")
public interface MigrationIssuesEndpoint extends FurnaceRESTGraphAPI
{
/**
* Returns a high level summary of all issues.
*/
@POST
@Path("aggregatedIssues")
Object getAggregatedIssues(@PathParam("executionId") Long executionId, Map<String, Object> filter);
/**
* Returns the specific files associated with a particular issue.
*/
@POST
@Path("{issueId}/files")
Object getIssueFiles(@PathParam("executionId") Long executionId, @PathParam("issueId") String issueId, Map<String, Object> filter);
}
|
9235103a8284a6cafecbd95e958a420c380be28d | 1,738 | java | Java | server/data/data-jmap/src/main/java/org/apache/james/jmap/api/upload/UploadRepository.java | sergeByishimo/james-project | e7e2c912d9ca59c6f4cc6c8b75ce4994038c08f7 | [
"Apache-2.0"
] | 634 | 2015-12-21T20:24:06.000Z | 2022-03-24T09:57:48.000Z | server/data/data-jmap/src/main/java/org/apache/james/jmap/api/upload/UploadRepository.java | sergeByishimo/james-project | e7e2c912d9ca59c6f4cc6c8b75ce4994038c08f7 | [
"Apache-2.0"
] | 4,148 | 2015-09-14T15:59:06.000Z | 2022-03-31T10:29:10.000Z | server/data/data-jmap/src/main/java/org/apache/james/jmap/api/upload/UploadRepository.java | sergeByishimo/james-project | e7e2c912d9ca59c6f4cc6c8b75ce4994038c08f7 | [
"Apache-2.0"
] | 392 | 2015-07-16T07:04:59.000Z | 2022-03-28T09:37:53.000Z | 46.972973 | 95 | 0.604143 | 997,141 | /****************************************************************
* 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.james.jmap.api.upload;
import java.io.InputStream;
import org.apache.james.core.Username;
import org.apache.james.jmap.api.model.Upload;
import org.apache.james.jmap.api.model.UploadId;
import org.apache.james.jmap.api.model.UploadMetaData;
import org.apache.james.mailbox.model.ContentType;
import org.reactivestreams.Publisher;
public interface UploadRepository {
Publisher<UploadMetaData> upload(InputStream data, ContentType contentType, Username user);
Publisher<Upload> retrieve(UploadId id, Username user);
}
|
923510706fafedf0af1a2350482280c9fad0de57 | 6,570 | java | Java | opensrp-web/src/test/java/org/opensrp/web/controller/DataExportControllerTest.java | proshantokuet/data-coorection | 88f5653d606b06001776a0530be0c6c62c9f805f | [
"Apache-2.0"
] | null | null | null | opensrp-web/src/test/java/org/opensrp/web/controller/DataExportControllerTest.java | proshantokuet/data-coorection | 88f5653d606b06001776a0530be0c6c62c9f805f | [
"Apache-2.0"
] | null | null | null | opensrp-web/src/test/java/org/opensrp/web/controller/DataExportControllerTest.java | proshantokuet/data-coorection | 88f5653d606b06001776a0530be0c6c62c9f805f | [
"Apache-2.0"
] | null | null | null | 28.942731 | 106 | 0.571081 | 997,142 | package org.opensrp.web.controller;
import static org.mockito.MockitoAnnotations.initMocks;
import java.io.FileWriter;
import java.io.IOException;
import org.ektorp.ViewResult;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.opensrp.register.mcare.repository.AllHouseHolds;
import org.opensrp.register.mcare.service.DataExportService;
import org.springframework.mock.web.MockHttpServletResponse;
public class DataExportControllerTest {
@Mock
private DataExportController controller;
@Mock
private DataExportService dataExportService;
@Mock
private AllHouseHolds allHouseHolds;
@Before
public void setUp() throws Exception {
initMocks(this);
this.controller = new DataExportController();
}
@Ignore@Test
public void test() throws JSONException{
String multimediaDirPath = "/opt/multimedia";
String reportName = "BD";
System.out.println("Path:..............:"+multimediaDirPath);
MockHttpServletResponse response = new MockHttpServletResponse();
response.setContentType("text/csv");
response.setHeader("Content-disposition",
"attachment; " + "filename=" + reportName);
ViewResult hhs=allHouseHolds.allHHsCreatedBetween2Date("HouseHold",1451584800000L, 1485799200000L,"FWA");
FileWriter writer;
try {
writer = new FileWriter(multimediaDirPath +"/export/" + reportName);
writer.append("FWA WORKER ID");
writer.append(',');
writer.append("today_newhh_FW");
writer.append(',');
writer.append("start_newhh_FW");
writer.append(',');
writer.append("end_newhh_FW");
writer.append(',');
writer.append("FWNHREGDATE");
writer.append(',');
writer.append("FWGOBHHID");
writer.append(',');
writer.append("FWJIVHHID");
writer.append(',');
writer.append("FWUNION");
writer.append(',');
writer.append("FWWARD");
writer.append(',');
writer.append("FWSUBUNIT");
writer.append(','); //10
writer.append("FWMAUZA_PARA");
writer.append(',');
writer.append("FWHOHFNAME");
writer.append(',');
writer.append("FWHOHBIRTHDATE");
writer.append(',');
writer.append("FWHOHGENDER");
writer.append(',');
writer.append("FWNHHMBRNUMB");
writer.append(',');
writer.append("FWNHHMWRA");
writer.append(',');
writer.append("REGDATE");
writer.append(',');
writer.append("FWWOMFNAME");
writer.append(',');
writer.append("FWBIRTHDATE");
writer.append(',');
writer.append("FWWOMAGE");
writer.append(','); //20
writer.append("FWCWOMSTRMEN");
writer.append(',');
writer.append("FWCWOMHUSLIV");
writer.append(',');
writer.append("FWCWOMHUSALV");
writer.append(',');
writer.append("FWCWOMHUSSTR");
writer.append(',');
writer.append("FWELIGIBLE");
writer.append(',');
writer.append("FWWOMANYID");
writer.append(',');
writer.append("FWWOMNID");
writer.append(',');
writer.append("FWWOMBID");
writer.append(',');
writer.append("FWHUSNAME");
writer.append(',');
writer.append("Latitude");
writer.append(','); //30
writer.append("Longitude");
writer.append(',');
writer.append("ELCO");
writer.append(',');
writer.append("RECEIVED TIME AT SERVER");
writer.append(',');
writer.append("FD WORKER ID");
writer.append(',');
writer.append("INSTANCE ID");
writer.append(',');
writer.append("ENTITY ID");
writer.append('\n'); //36
int count =hhs.getSize();
System.out.println("count: "+count);
for (int i = 0; i <count; i++) {
if(hhs.getRows().get(i).getValue().equalsIgnoreCase("")){
System.err.println("Error.........................");
}
String[] s=hhs.getRows().get(i).getValue().split(",");
int elco = 0;
String temp = s[0].replace("\"", "").replace("[", "");
//System.out.println("Loop val: "+ temp);
if(temp != null && !temp.isEmpty() && !temp.equalsIgnoreCase(""))
elco = Integer.parseInt(temp);
//String jsonArray = vr.getRows().get(i).getValue().trim();
//System.out.println(hhs.getRows().get(i).getValue());
for(int y=1;y<=16;y++){
if(s[y] != null && !s[y].isEmpty() && !s[y].equalsIgnoreCase("")){
writer.append(s[y]);
writer.append(',');
}
else {
writer.append("");
writer.append(',');
}
}
if(elco>0){
for(int y=21;y<=30;y++){
if(s[y] != null && !s[y].isEmpty() && !s[y].equalsIgnoreCase("")){
writer.append(s[y]);
writer.append(',');
}
else {
writer.append("");
writer.append(',');
}
}
writer.append(String.valueOf(s[31]));
writer.append(',');
writer.append(String.valueOf(s[32]));
writer.append(',');
writer.append(s[33]);
String gps = s[34];
if(gps != null && !gps.isEmpty() && !gps.equalsIgnoreCase("")){
String[] location = gps.split(" ");
if (location.length > 1 ) {
System.out.println("Location: "+ location[0].replace("\"", "") + " " + location[1]);
writer.append(',');
writer.append(location[0].replace("\"", ""));
writer.append(',');
writer.append(location[1].replace("\"", ""));
}
else if (location.length > 0 ) {
writer.append(',');
writer.append(location[0].replace("\"", ""));
writer.append(',');
writer.append("");
}
else{
writer.append(',');
writer.append("");
writer.append(',');
writer.append("");
}
}else{
writer.append(',');
writer.append("");
writer.append(',');
writer.append("");
}
}
else{
for(int y=1;y<=15;y++){
writer.append(',');
writer.append("");
}
}
writer.append(',');
writer.append(String.valueOf(elco));
writer.append(',');
writer.append(s[17]);
writer.append(',');
writer.append(s[18]);
writer.append(',');
writer.append(s[19]);
writer.append(',');
writer.append(s[20]);
writer.append('\n');
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println("Loop time end:"+ System.currentTimeMillis());
}
}
}
|
9235108b13f9372ab01dde96f962879be9fcd36b | 484 | java | Java | src/main/java/com/ferreusveritas/dynamictrees/api/worldgen/IPoissonDiscProvider.java | Charles445/DynamicTrees | cffa54a08957e525a708712ec38c2c7d081988c2 | [
"MIT"
] | 143 | 2017-12-04T20:49:00.000Z | 2022-01-08T10:11:07.000Z | src/main/java/com/ferreusveritas/dynamictrees/api/worldgen/IPoissonDiscProvider.java | Charles445/DynamicTrees | cffa54a08957e525a708712ec38c2c7d081988c2 | [
"MIT"
] | 611 | 2017-10-27T22:17:49.000Z | 2022-01-12T16:34:26.000Z | src/main/java/com/ferreusveritas/dynamictrees/api/worldgen/IPoissonDiscProvider.java | Charles445/DynamicTrees | cffa54a08957e525a708712ec38c2c7d081988c2 | [
"MIT"
] | 90 | 2017-12-29T05:16:00.000Z | 2022-01-01T08:04:31.000Z | 26.888889 | 81 | 0.801653 | 997,143 | package com.ferreusveritas.dynamictrees.api.worldgen;
import com.ferreusveritas.dynamictrees.systems.poissondisc.PoissonDisc;
import java.util.List;
public interface IPoissonDiscProvider {
List<PoissonDisc> getPoissonDiscs(int chunkX, int chunkY, int chunkZ);
byte[] getChunkPoissonData(int chunkX, int chunkY, int chunkZ);
void setChunkPoissonData(int chunkX, int chunkY, int chunkZ, byte[] circleData);
void unloadChunkPoissonData(int chunkX, int chunkY, int chunkZ);
}
|
9235109207f3b5723af27c8b894fb96ee2a77d38 | 3,242 | java | Java | app/src/main/java/com/ru/devit/mediateka/domain/cinemausecases/GetCinemaByQuery.java | Devit951/Mediateka | 917df3c0b86daef73a67a3a6e73401860d073114 | [
"Apache-2.0",
"CC-BY-4.0"
] | 40 | 2018-05-11T17:47:42.000Z | 2021-11-11T08:56:19.000Z | app/src/main/java/com/ru/devit/mediateka/domain/cinemausecases/GetCinemaByQuery.java | Devit951/Mediateka | 917df3c0b86daef73a67a3a6e73401860d073114 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2 | 2018-05-20T11:36:12.000Z | 2018-08-06T11:17:30.000Z | app/src/main/java/com/ru/devit/mediateka/domain/cinemausecases/GetCinemaByQuery.java | Devit951/Mediateka | 917df3c0b86daef73a67a3a6e73401860d073114 | [
"Apache-2.0",
"CC-BY-4.0"
] | 3 | 2018-05-21T17:28:11.000Z | 2020-04-19T22:29:39.000Z | 36.840909 | 129 | 0.563233 | 997,144 | package com.ru.devit.mediateka.domain.cinemausecases;
import com.ru.devit.mediateka.domain.Actions;
import com.ru.devit.mediateka.domain.CinemaRepository;
import com.ru.devit.mediateka.domain.UseCase;
import com.ru.devit.mediateka.models.model.Cinema;
import com.ru.devit.mediateka.utils.FormatterUtils;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.functions.Action;
import io.reactivex.processors.FlowableProcessor;
import io.reactivex.processors.PublishProcessor;
import static com.ru.devit.mediateka.utils.FormatterUtils.DEFAULT_VALUE;
public class GetCinemaByQuery extends UseCase<List<Cinema>> {
private Actions actions;
private boolean isDataLoaded = false;
private final CinemaRepository repository;
private final FlowableProcessor<String> processor = PublishProcessor.create();
@Inject public GetCinemaByQuery(Scheduler executorThread ,
Scheduler uiThread ,
CinemaRepository repository) {
super(executorThread, uiThread);
this.repository = repository;
}
public void onNextQuery(String query) {
processor.onNext(query);
}
public void setActions(Actions actions){
this.actions = actions;
}
public void removeActions() {
actions.removeActions();
}
public void sortByDate(List<Cinema> cinemas){
Collections.sort(cinemas, (cinema, cinema2) -> {
if (cinema.getReleaseDate().equals(FormatterUtils.DEFAULT_VALUE) || cinema2.getReleaseDate().equals(DEFAULT_VALUE)){
return cinema.getReleaseDate().compareTo(cinema2.getReleaseDate());
}
int releaseDate1 = Integer.valueOf(cinema.getReleaseDate());
int releaseDate2 = Integer.valueOf(cinema2.getReleaseDate());
return Integer.compare(releaseDate2 , releaseDate1);
});
}
@Override
protected Flowable<List<Cinema>> createUseCase() {
return processor
.flatMap(s -> {
if (!isDataLoaded){
return Flowable.just(s)
.doOnNext(s1 -> {
if (s1.isEmpty()) actions.onDataLoaded();
else actions.onNext();
});
} else {
actions.onDataLoaded();
return Flowable.just(s)
.doOnComplete(() -> {
actions.onClearAdapter();
isDataLoaded = false;
});
}
})
.debounce(800 , TimeUnit.MILLISECONDS)
.filter(q -> !q.isEmpty())
.distinctUntilChanged()
.switchMap(s -> {
isDataLoaded = true;
return repository.searchCinemas(s);
});
}
}
|
923510fd53befc8dda343d5fe150302daa561ce1 | 539 | java | Java | src/main/java/com/marcus8448/mods/marcus8448mod/utils/Constants.java | marcus8448/marcus8448-Mod | 3e1c38b4594adfe64a89e1e3eaee6e1d4c18209a | [
"MIT"
] | 5 | 2018-03-31T00:26:31.000Z | 2018-11-18T06:50:31.000Z | src/main/java/com/marcus8448/mods/marcus8448mod/utils/Constants.java | marcus8448/marcus8448-Mod | 3e1c38b4594adfe64a89e1e3eaee6e1d4c18209a | [
"MIT"
] | 6 | 2018-05-20T23:26:31.000Z | 2018-09-21T01:20:40.000Z | src/main/java/com/marcus8448/mods/marcus8448mod/utils/Constants.java | marcus8448/marcus8448-Mod | 3e1c38b4594adfe64a89e1e3eaee6e1d4c18209a | [
"MIT"
] | 2 | 2018-06-23T05:48:22.000Z | 2018-06-23T15:03:52.000Z | 35.933333 | 100 | 0.734694 | 997,145 | package com.marcus8448.mods.marcus8448mod.utils;
/**
* @author marcus8448
*
*/
public class Constants {
public static final String MODID = "marcus8448mod";
public static final String NAME = "marcus8448's Mod";
public static final String VERSION = "1.12.2-1.1.0.0_alpha";
public static final String MCV = "1.12.2";
public static final String CLIENT_PROXY = "com.marcus8448.mods.marcus8448mod.proxy.ClientProxy";
public static final String COMMON_PROXY = "com.marcus8448.mods.marcus8448mod.proxy.CommonProxy";
}
|
92351104cfb45c8d3a04af9bd4b1d6ddfb428a1f | 692 | java | Java | src/test/java/me/soshin/dao/PlayerDAOTest.java | AlexeySoshin/Elo | 517e41200878fa76207f10a5d2106aedac3f719f | [
"MIT"
] | null | null | null | src/test/java/me/soshin/dao/PlayerDAOTest.java | AlexeySoshin/Elo | 517e41200878fa76207f10a5d2106aedac3f719f | [
"MIT"
] | null | null | null | src/test/java/me/soshin/dao/PlayerDAOTest.java | AlexeySoshin/Elo | 517e41200878fa76207f10a5d2106aedac3f719f | [
"MIT"
] | null | null | null | 22.322581 | 71 | 0.738439 | 997,146 | package me.soshin.dao;
import me.soshin.model.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class PlayerDAOTest {
@Resource
PlayerDAO playerDAO;
@Test
public void testRanking() {
List<Player> ranked = this.playerDAO.getPlayersRanked();
assertEquals(36, (int) ranked.get(0).getId());
assertEquals(7, (int) ranked.get(39).getId());
}
} |
923512b3d3489b18e273b75b4e73ea11a4ecdea8 | 6,068 | java | Java | lib.ApkParser/src/net/dongliu/apk/parser/struct/ResValue.java | BugLai/ApkToolPlus | 719f5c207812052af0b21ae7ab13338bd250de27 | [
"Apache-2.0"
] | 911 | 2016-05-01T16:59:21.000Z | 2022-03-30T11:09:41.000Z | lib.ApkParser/src/net/dongliu/apk/parser/struct/ResValue.java | 1104436107/ApkToolPlus | 2d75d3ec95ed0aa0b81f71ec472deeb5729ddc4a | [
"Apache-2.0"
] | 24 | 2016-04-26T15:19:58.000Z | 2021-06-03T07:57:09.000Z | lib.ApkParser/src/net/dongliu/apk/parser/struct/ResValue.java | 1104436107/ApkToolPlus | 2d75d3ec95ed0aa0b81f71ec472deeb5729ddc4a | [
"Apache-2.0"
] | 253 | 2016-12-22T05:10:33.000Z | 2022-03-29T07:09:20.000Z | 35.694118 | 95 | 0.620962 | 997,147 | package net.dongliu.apk.parser.struct;
/**
* apk res value struct.
*
* @author dongliu
*/
public class ResValue {
// Number of bytes in this structure. uint16; always 8
private int size;
// Always set to 0. uint8
private short res0;
// Type of the data value. uint8
private short dataType;
// The data for this item; as interpreted according to dataType. unit32
/*
* The data field is a fixed size 32-bit integer.
* How it is interpreted depends upon the value of the type field.
* Some of the possible interpretations are as
* a boolean value
* a float value
* an integer value
* an index into the Table chunk’s StringPool
* a composite value
*/
/**
* the real data repesented by string
*/
private ResourceEntity data;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public short getRes0() {
return res0;
}
public void setRes0(short res0) {
this.res0 = res0;
}
public short getDataType() {
return dataType;
}
public void setDataType(short dataType) {
this.dataType = dataType;
}
public ResourceEntity getData() {
return data;
}
public void setData(ResourceEntity data) {
this.data = data;
}
@Override
public String toString() {
return "ResValue{" +
"size=" + size +
", res0=" + res0 +
", dataType=" + dataType +
", data=" + data +
'}';
}
public static class ResType {
// Contains no data.
public static final short NULL = 0x00;
// The 'data' holds a ResTable_ref; a reference to another resource
// table entry.
public static final short REFERENCE = 0x01;
// The 'data' holds an attribute resource identifier.
public static final short ATTRIBUTE = 0x02;
// The 'data' holds an index into the containing resource table's
// global value string pool.
public static final short STRING = 0x03;
// The 'data' holds a single-precision floating point number.
public static final short FLOAT = 0x04;
// The 'data' holds a complex number encoding a dimension value;
// such as "100in".
public static final short DIMENSION = 0x05;
// The 'data' holds a complex number encoding a fraction of a
// container.
public static final short FRACTION = 0x06;
// Beginning of integer flavors...
public static final short FIRST_INT = 0x10;
// The 'data' is a raw integer value of the form n..n.
public static final short INT_DEC = 0x10;
// The 'data' is a raw integer value of the form 0xn..n.
public static final short INT_HEX = 0x11;
// The 'data' is either 0 or 1; for input "false" or "true" respectively.
public static final short INT_BOOLEAN = 0x12;
// Beginning of color integer flavors...
public static final short FIRST_COLOR_INT = 0x1c;
// The 'data' is a raw integer value of the form #aarrggbb.
public static final short INT_COLOR_ARGB8 = 0x1c;
// The 'data' is a raw integer value of the form #rrggbb.
public static final short INT_COLOR_RGB8 = 0x1d;
// The 'data' is a raw integer value of the form #argb.
public static final short INT_COLOR_ARGB4 = 0x1e;
// The 'data' is a raw integer value of the form #rgb.
public static final short INT_COLOR_RGB4 = 0x1f;
// ...end of integer flavors.
public static final short LAST_COLOR_INT = 0x1f;
// ...end of integer flavors.
public static final short LAST_INT = 0x1f;
}
// A number of constants used when the data is interpreted as a composite value are defined
// by the following anonymous C++ enum
public static class ResDataCOMPLEX {
// Where the unit type information is. This gives us 16 possible
// types; as defined below.
public static final short UNIT_SHIFT = 0;
public static final short UNIT_MASK = 0xf;
// TYPE_DIMENSION: Value is raw pixels.
public static final short UNIT_PX = 0;
// TYPE_DIMENSION: Value is Device Independent Pixels.
public static final short UNIT_DIP = 1;
// TYPE_DIMENSION: Value is a Scaled device independent Pixels.
public static final short UNIT_SP = 2;
// TYPE_DIMENSION: Value is in points.
public static final short UNIT_PT = 3;
// TYPE_DIMENSION: Value is in inches.
public static final short UNIT_IN = 4;
// TYPE_DIMENSION: Value is in millimeters.
public static final short UNIT_MM = 5;
// TYPE_FRACTION: A basic fraction of the overall size.
public static final short UNIT_FRACTION = 0;
// TYPE_FRACTION: A fraction of the parent size.
public static final short UNIT_FRACTION_PARENT = 1;
// Where the radix information is; telling where the decimal place
// appears in the mantissa. This give us 4 possible fixed point
// representations as defined below.
public static final short RADIX_SHIFT = 4;
public static final short RADIX_MASK = 0x3;
// The mantissa is an integral number -- i.e.; 0xnnnnnn.0
public static final short RADIX_23p0 = 0;
// The mantissa magnitude is 16 bits -- i.e; 0xnnnn.nn
public static final short RADIX_16p7 = 1;
// The mantissa magnitude is 8 bits -- i.e; 0xnn.nnnn
public static final short RADIX_8p15 = 2;
// The mantissa magnitude is 0 bits -- i.e; 0x0.nnnnnn
public static final short RADIX_0p23 = 3;
// Where the actual value is. This gives us 23 bits of
// precision. The top bit is the sign.
public static final short MANTISSA_SHIFT = 8;
public static final int MANTISSA_MASK = 0xffffff;
}
}
|
9235135672528adfb16ae574e3f207b391883d5f | 6,014 | java | Java | export/parser/org/eclipse/cdt/internal/core/dom/parser/CStringValue.java | seemoo-lab/polypyus_pdom | c08d06d3268578566978697d0560c34f3b224b55 | [
"Apache-2.0"
] | null | null | null | export/parser/org/eclipse/cdt/internal/core/dom/parser/CStringValue.java | seemoo-lab/polypyus_pdom | c08d06d3268578566978697d0560c34f3b224b55 | [
"Apache-2.0"
] | null | null | null | export/parser/org/eclipse/cdt/internal/core/dom/parser/CStringValue.java | seemoo-lab/polypyus_pdom | c08d06d3268578566978697d0560c34f3b224b55 | [
"Apache-2.0"
] | null | null | null | 24.647541 | 96 | 0.654972 | 997,148 | /*******************************************************************************
* Copyright (c) 2016 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory;
import org.eclipse.cdt.core.dom.ast.IValue;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPBasicType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPEvaluation;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.EvalFixed;
import org.eclipse.core.runtime.CoreException;
public final class CStringValue implements IValue {
private static final Map<Character, Character> escapeSequences;
static {
Map<Character, Character> map = new HashMap<Character, Character>();
map.put('\'', '\'');
map.put('"', '"');
map.put('?', '?');
map.put('\\', '\\');
map.put('a', '\007');
map.put('b', '\b');
map.put('f', '\f');
map.put('n', '\n');
map.put('r', '\r');
map.put('t', '\t');
map.put('v', '\013');
escapeSequences = Collections.unmodifiableMap(map);
}
private final char[] fFixedValue;
private String fParsedValue;
private CStringValue(char[] fixedValue) {
fFixedValue = fixedValue;
}
public static IValue create(char[] fixedValue) {
return new CStringValue(fixedValue);
}
public String cStringValue() {
if (fParsedValue == null) {
fParsedValue = parseString();
}
return fParsedValue;
}
private int indexOfStartQuote() {
final int len = fFixedValue.length;
int i = 0;
while (i < len && fFixedValue[i] != '"') {
++i;
}
if (i >= len) {
return -1;
} else {
return i;
}
}
private int indexOfEndQuote() {
int i = fFixedValue.length - 1;
while (i >= 0 && fFixedValue[i] != '"') {
--i;
}
if (i < 0) {
return -1;
} else {
return i;
}
}
private boolean isRawStringLiteral() {
for (int i = 0; i < indexOfStartQuote(); ++i) {
if (fFixedValue[i] == 'R') {
return true;
}
}
return false;
}
private int getDelimiterLength() {
if (isRawStringLiteral()) {
int i = indexOfStartQuote();
int len = 0;
while (i < fFixedValue.length && fFixedValue[i] != '(') {
++i;
++len;
}
return len;
}
return 0;
}
private int getStart() {
return indexOfStartQuote() + getDelimiterLength() + 1;
}
private int getEnd() {
return indexOfEndQuote() - getDelimiterLength() - 1;
}
private String parseString() {
// TODO: Reuse code between this and CPPASTLiteralExpression.computeStringLiteralSize().
boolean isRaw = isRawStringLiteral();
int end = getEnd();
StringBuilder builder = new StringBuilder();
for (int i = getStart(); i <= end; ++i) {
if (!isRaw && fFixedValue[i] == '\\' && i < end) {
++i;
//C-Strings are null-terminated. Therefore, a '\0' character
//denotes the end of the string, even if the literal contains
//more characters after that
if (fFixedValue[i] == '0') {
break;
} else {
i = parseEscapeSequence(i, builder);
}
} else {
builder.append(fFixedValue[i]);
}
}
return builder.toString();
}
private int parseEscapeSequence(int i, StringBuilder builder) {
char c = fFixedValue[i];
Character escapeSequence = escapeSequences.get(c);
if (escapeSequence != null) {
builder.append(escapeSequence);
} else if (c == 'u' && i + 4 <= getEnd()) {
StringBuilder hexStr = new StringBuilder();
++i;
for (int end = i + 4; i < end; ++i) {
hexStr.append(fFixedValue[i]);
}
int codePoint = Integer.parseInt(hexStr.toString(), 16);
builder.append(Character.toChars(codePoint));
}
return i;
}
@Override
public Number numberValue() {
return null;
}
@Override
public int numberOfSubValues() {
String str = cStringValue();
return str.length();
}
@Override
public ICPPEvaluation getSubValue(int index) {
String str = cStringValue();
Character c = null;
if (index >= 0 && index < str.length()) {
c = str.charAt(index);
} else if (index == str.length()) {
c = '\0';
}
if (c != null) {
IValue val = IntegralValue.create(c);
return new EvalFixed(CPPBasicType.CHAR, ValueCategory.PRVALUE, val);
}
return EvalFixed.INCOMPLETE;
}
@Override
public ICPPEvaluation[] getAllSubValues() {
return null;
}
@Override
public ICPPEvaluation getEvaluation() {
return null;
}
@Override
public char[] getSignature() {
return fFixedValue;
}
@Override
public int hashCode() {
return CharArrayUtils.hash(getSignature());
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CStringValue)) {
return false;
}
final CStringValue rhs = (CStringValue) obj;
if (fFixedValue != null)
return CharArrayUtils.equals(fFixedValue, rhs.fFixedValue);
return CharArrayUtils.equals(getSignature(), rhs.getSignature());
}
@Override
public void setSubValue(int position, ICPPEvaluation newValue) {
}
@Override
public IValue clone() {
char[] newFixedValue = Arrays.copyOf(fFixedValue, fFixedValue.length);
return new CStringValue(newFixedValue);
}
@Override
public void marshal(ITypeMarshalBuffer buf) throws CoreException {
buf.putShort(ITypeMarshalBuffer.C_STRING_VALUE);
buf.putCharArray(fFixedValue);
}
public static IValue unmarshal(short firstBytes, ITypeMarshalBuffer buf) throws CoreException {
return new CStringValue(buf.getCharArray());
}
/**
* For debugging only.
*/
@Override
public String toString() {
return new String(fFixedValue);
}
} |
923513858fb328322a0fe5e143832fc49b0af443 | 821 | java | Java | src/main/java/org/amurzeau/allocation/services/UserService.java | amurzeau/allocation-server | aa832ec6be5b412eb2822628da8e04be761de502 | [
"MIT"
] | null | null | null | src/main/java/org/amurzeau/allocation/services/UserService.java | amurzeau/allocation-server | aa832ec6be5b412eb2822628da8e04be761de502 | [
"MIT"
] | null | null | null | src/main/java/org/amurzeau/allocation/services/UserService.java | amurzeau/allocation-server | aa832ec6be5b412eb2822628da8e04be761de502 | [
"MIT"
] | null | null | null | 27.366667 | 97 | 0.727162 | 997,149 | package org.amurzeau.allocation.services;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import org.amurzeau.allocation.rest.SchemaVersion;
import org.jboss.logging.Logger;
import io.quarkus.runtime.StartupEvent;
@ApplicationScoped
public class UserService {
private static final Logger LOGGER = Logger.getLogger(UserService.class);
public void onStart(@Observes StartupEvent ev) {
LOGGER.info("The application is starting...");
SchemaVersion item = SchemaVersion.<SchemaVersion>find("order by id DESC").firstResult();
if (item == null)
return;
migrateDatabase(item.version);
}
public void migrateDatabase(long fromVersion) {
LOGGER.infov("Migrating database from version {0}", fromVersion);
}
}
|
9235138fbe3e505d2fe5717bbfcd2e0163e2c3f3 | 2,246 | java | Java | drools-repository/src/main/java/org/drools/repository/StateItem.java | pymma/drools47jdk8 | b532d45ac47806bef8c3a6cf1ac671c73ed4ea09 | [
"Apache-2.0"
] | 13 | 2016-05-08T12:40:40.000Z | 2017-01-09T05:02:36.000Z | drools-repository/src/main/java/org/drools/repository/StateItem.java | rapidan/drools | 62a0a5907ca1f4505cea2f4c55302da846b1cc75 | [
"Apache-2.0"
] | 7 | 2020-06-30T23:18:02.000Z | 2022-02-01T01:05:08.000Z | drools-repository/src/main/java/org/drools/repository/StateItem.java | rapidan/drools | 62a0a5907ca1f4505cea2f4c55302da846b1cc75 | [
"Apache-2.0"
] | 6 | 2015-12-04T06:09:37.000Z | 2019-07-19T07:20:44.000Z | 31.194444 | 176 | 0.5935 | 997,150 | package org.drools.repository;
import javax.jcr.Node;
import org.apache.log4j.Logger;
/**
* The StateItem represents the status of an asset.
* An asset can only be in 1 state at a time. Kind of for workflow.
*
*
* @author btruitt
*/
public class StateItem extends Item {
private Logger log = Logger.getLogger(StateItem.class);
/**
* All assets when created, or a new version saved, have a status of Draft.
*/
public static String DRAFT_STATE_NAME = "Draft";
/**
* The name of the state node type
*/
public static final String STATE_NODE_TYPE_NAME = "drools:stateNodeType";
/**
* Constructs an object of type StateItem corresponding the specified node
*
* @param rulesRepository the rulesRepository that instantiated this object
* @param node the node to which this object corresponds
* @throws RulesRepositoryException
*/
public StateItem(RulesRepository rulesRepository, Node node) throws RulesRepositoryException {
super(rulesRepository, node);
try {
//make sure this node is a state node
if(!(this.node.getPrimaryNodeType().getName().equals(STATE_NODE_TYPE_NAME))) {
String message = this.node.getName() + " is not a node of type " + STATE_NODE_TYPE_NAME + ". It is a node of type: " + this.node.getPrimaryNodeType().getName();
log.error(message);
throw new RulesRepositoryException(message);
}
}
catch(Exception e) {
log.error("Caught exception: " + e);
throw new RulesRepositoryException(e);
}
}
public boolean equals(Object in) {
if (!(in instanceof StateItem)) {
return false;
} else if (in == this) {
return true;
} else if (in == null) {
return false;
} else {
StateItem other = (StateItem) in;
return this.getName().equals( other.getName() );
}
}
public String toString() {
return "Current status: [" + getName() + "] (" + super.toString() + ")";
}
public int hashCode() {
return getName().hashCode();
}
} |
923513ae64ab5986dad6cab08ede259f8fe002bc | 7,178 | java | Java | src/test/java/org/swisspush/reststorage/util/HttpRequestHeaderTest.java | gedestroy/vertx-rest-storage | 1550c94db83256c28084b938641a5e9c28e5ff4a | [
"Apache-2.0"
] | 19 | 2015-09-16T01:16:29.000Z | 2020-06-27T12:15:21.000Z | src/test/java/org/swisspush/reststorage/util/HttpRequestHeaderTest.java | gedestroy/vertx-rest-storage | 1550c94db83256c28084b938641a5e9c28e5ff4a | [
"Apache-2.0"
] | 55 | 2015-10-29T11:46:53.000Z | 2022-01-25T02:03:36.000Z | src/test/java/org/swisspush/reststorage/util/HttpRequestHeaderTest.java | gedestroy/vertx-rest-storage | 1550c94db83256c28084b938641a5e9c28e5ff4a | [
"Apache-2.0"
] | 10 | 2016-04-28T09:40:42.000Z | 2020-09-17T09:35:17.000Z | 38.180851 | 95 | 0.713151 | 997,151 | package org.swisspush.reststorage.util;
import io.vertx.core.MultiMap;
import io.vertx.core.http.CaseInsensitiveHeaders;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.swisspush.reststorage.util.HttpRequestHeader.*;
/**
* <p>
* Tests for the {@link HttpRequestHeader} class
* </p>
*
* @author https://github.com/mcweba [Marc-Andre Weber]
*/
@RunWith(VertxUnitRunner.class)
public class HttpRequestHeaderTest {
MultiMap headers;
@Before
public void setUp() {
headers = new CaseInsensitiveHeaders();
}
@Test
public void testContainsHeader(TestContext context){
context.assertFalse(containsHeader(null, LOCK_HEADER));
context.assertFalse(containsHeader(headers, ETAG_HEADER));
headers.set("x-expire-after", "99");
context.assertTrue(containsHeader(headers, EXPIRE_AFTER_HEADER));
headers.clear();
headers.set("X-EXPIRE-AFTER", "99");
context.assertTrue(containsHeader(headers, EXPIRE_AFTER_HEADER));
headers.clear();
headers.set("x-Expire-After", "99");
context.assertTrue(containsHeader(headers, EXPIRE_AFTER_HEADER));
headers.clear();
headers.set("xexpireafter", "99");
context.assertFalse(containsHeader(headers, EXPIRE_AFTER_HEADER));
}
@Test
public void testGetInteger(TestContext context){
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "99");
context.assertEquals(99, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "444");
context.assertEquals(444, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "0");
context.assertEquals(0, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "9999999999999999999");
context.assertNull(getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "");
context.assertNull(getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "xyz");
context.assertNull(getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.clear();
context.assertNull(getInteger(headers, LOCK_EXPIRE_AFTER_HEADER));
context.assertNull(getInteger(null, LOCK_EXPIRE_AFTER_HEADER));
}
@Test
public void testGetIntegerWithDefaultValue(TestContext context){
Integer defaultValue = 1;
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "99");
context.assertEquals(99, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "444");
context.assertEquals(444, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "0");
context.assertEquals(0, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "9999999999999999999");
context.assertEquals(1, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "");
context.assertEquals(1, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "xyz");
context.assertEquals(1, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.clear();
context.assertEquals(1, getInteger(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
context.assertEquals(1, getInteger(null, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
}
@Test
public void testGetLong(TestContext context){
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "99");
context.assertEquals(99L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "444");
context.assertEquals(444L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "0");
context.assertEquals(0L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "9999999999999999999");
context.assertNull(getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "");
context.assertNull(getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "xyz");
context.assertNull(getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
headers.clear();
context.assertNull(getLong(headers, LOCK_EXPIRE_AFTER_HEADER));
context.assertNull(getLong(null, LOCK_EXPIRE_AFTER_HEADER));
}
@Test
public void testGetLongWithDefaultValue(TestContext context){
Long defaultValue = 1L;
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "99");
context.assertEquals(99L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "444");
context.assertEquals(444L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "0");
context.assertEquals(0L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "9999999999999999999");
context.assertEquals(1L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "");
context.assertEquals(1L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.set(LOCK_EXPIRE_AFTER_HEADER.getName(), "xyz");
context.assertEquals(1L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
headers.clear();
context.assertEquals(1L, getLong(headers, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
context.assertEquals(1L, getLong(null, LOCK_EXPIRE_AFTER_HEADER, defaultValue));
}
@Test
public void testGetString(TestContext context){
headers.set(ETAG_HEADER.getName(), "99");
context.assertEquals("99", getString(headers, ETAG_HEADER));
headers.set(ETAG_HEADER.getName(), "444");
context.assertEquals("444", getString(headers, ETAG_HEADER));
headers.set(ETAG_HEADER.getName(), "0");
context.assertEquals("0", getString(headers, ETAG_HEADER));
headers.set(ETAG_HEADER.getName(), "9999999999999999999");
context.assertEquals("9999999999999999999", getString(headers, ETAG_HEADER));
headers.set(ETAG_HEADER.getName(), "");
context.assertEquals("", getString(headers, ETAG_HEADER));
headers.set(ETAG_HEADER.getName(), "xyz");
context.assertEquals("xyz", getString(headers, ETAG_HEADER));
headers.clear();
context.assertNull(getString(headers, ETAG_HEADER));
context.assertNull(getString(null, ETAG_HEADER));
}
}
|
923514e7a6e6ad17840159bc440f9d3132151b9f | 2,762 | java | Java | Client App/src/client/app/ClientApp.java | mlegy/Simple-Chatting-APP | ca475f157e637afd5b7ac04cfe1152848e246492 | [
"Apache-2.0"
] | 1 | 2018-02-12T00:51:59.000Z | 2018-02-12T00:51:59.000Z | Client App/src/client/app/ClientApp.java | mlegy/Simple-Chatting-APP | ca475f157e637afd5b7ac04cfe1152848e246492 | [
"Apache-2.0"
] | null | null | null | Client App/src/client/app/ClientApp.java | mlegy/Simple-Chatting-APP | ca475f157e637afd5b7ac04cfe1152848e246492 | [
"Apache-2.0"
] | null | null | null | 35.410256 | 91 | 0.589066 | 997,152 | package client.app;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
public class ClientApp {
private static final String LOGIN_PREFIX = "LOGIN ";
private static final String LOGOUT_PREFIX = "LOGOUT ";
public static final String MESSAGE_PREFIX = "MSG ";
private static DataOutputStream dataOutputStream;
public static String nickname;
public static void main(String[] args) throws Exception {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (Exception e) {
}
// show the nickname dialog
nickname = JOptionPane.showInputDialog("Enter nickname");
if (nickname == null) {
return;
}
String ip = JOptionPane.showInputDialog("Enter ip","localhost");
if (ip == null) {
return;
}
try {
// establish a connection to the server
Socket socket = new Socket(ip, 1234);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
// send login command
send(LOGIN_PREFIX + nickname);
// show main frame
MainFrame mainFrame = new MainFrame();
mainFrame.setVisible(true);
mainFrame.onUserLogined(nickname);
// wait for all incoming messags from the server
while (true) {
String command = dataInputStream.readUTF();
if (command.startsWith(LOGIN_PREFIX)) { // login command
String nicknamesString = command.substring(LOGIN_PREFIX.length());
String[] nicknames = nicknamesString.split(",");
for (String name : nicknames) {
mainFrame.onUserLogined(name);
}
} else if (command.startsWith(MESSAGE_PREFIX)) { // login command
String newMessage = command.substring(MESSAGE_PREFIX.length());
mainFrame.onMessageRecieved(newMessage);
} else if (command.startsWith(LOGOUT_PREFIX)) { // logout command
String nickname = command.substring(LOGOUT_PREFIX.length());
mainFrame.onUserLoggedOut(nickname);
}
}
} catch (Exception e) {
}
}
public static void send(String command) {
try {
dataOutputStream.writeUTF(command);
dataOutputStream.flush();
} catch (Exception e) {
}
}
} |
923515b6efe7e75044a2a0abfd23ef5de0af987e | 9,701 | java | Java | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/InnerNodeImpl.java | yellowflash/hadoop | aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 14,425 | 2015-01-01T15:34:43.000Z | 2022-03-31T15:28:37.000Z | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/InnerNodeImpl.java | yellowflash/hadoop | aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 3,805 | 2015-03-20T15:58:53.000Z | 2022-03-31T23:58:37.000Z | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/InnerNodeImpl.java | yellowflash/hadoop | aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 9,521 | 2015-01-01T19:12:52.000Z | 2022-03-31T03:07:51.000Z | 31.092949 | 78 | 0.61839 | 997,153 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.net;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** InnerNode represents a switch/router of a data center or rack.
* Different from a leaf node, it has non-null children.
*/
public class InnerNodeImpl extends NodeBase implements InnerNode {
protected static class Factory implements InnerNode.Factory<InnerNodeImpl> {
protected Factory() {}
@Override
public InnerNodeImpl newInnerNode(String path) {
return new InnerNodeImpl(path);
}
}
static final Factory FACTORY = new Factory();
protected final List<Node> children = new ArrayList<>();
protected final Map<String, Node> childrenMap = new HashMap<>();
protected int numOfLeaves;
/** Construct an InnerNode from a path-like string. */
protected InnerNodeImpl(String path) {
super(path);
}
/** Construct an InnerNode
* from its name, its network location, its parent, and its level. */
protected InnerNodeImpl(String name, String location,
InnerNode parent, int level) {
super(name, location, parent, level);
}
@Override
public List<Node> getChildren() {
return children;
}
/** @return the number of children this node has. */
@Override
public int getNumOfChildren() {
return children.size();
}
/** Judge if this node represents a rack.
* @return true if it has no child or its children are not InnerNodes
*/
public boolean isRack() {
if (children.isEmpty()) {
return true;
}
Node firstChild = children.get(0);
if (firstChild instanceof InnerNode) {
return false;
}
return true;
}
/** Judge if this node is an ancestor of node <i>n</i>.
*
* @param n a node
* @return true if this node is an ancestor of <i>n</i>
*/
public boolean isAncestor(Node n) {
return getPath(this).equals(NodeBase.PATH_SEPARATOR_STR) ||
(n.getNetworkLocation()+NodeBase.PATH_SEPARATOR_STR).
startsWith(getPath(this)+NodeBase.PATH_SEPARATOR_STR);
}
/** Judge if this node is the parent of node <i>n</i>.
*
* @param n a node
* @return true if this node is the parent of <i>n</i>
*/
public boolean isParent(Node n) {
return n.getNetworkLocation().equals(getPath(this));
}
/* Return a child name of this node who is an ancestor of node <i>n</i> */
public String getNextAncestorName(Node n) {
if (!isAncestor(n)) {
throw new IllegalArgumentException(
this + "is not an ancestor of " + n);
}
String name = n.getNetworkLocation().substring(getPath(this).length());
if (name.charAt(0) == PATH_SEPARATOR) {
name = name.substring(1);
}
int index=name.indexOf(PATH_SEPARATOR);
if (index != -1) {
name = name.substring(0, index);
}
return name;
}
@Override
public boolean add(Node n) {
if (!isAncestor(n)) {
throw new IllegalArgumentException(n.getName()
+ ", which is located at " + n.getNetworkLocation()
+ ", is not a descendant of " + getPath(this));
}
if (isParent(n)) {
// this node is the parent of n; add n directly
n.setParent(this);
n.setLevel(this.level+1);
Node prev = childrenMap.put(n.getName(), n);
if (prev != null) {
for(int i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(n.getName())) {
children.set(i, n);
return false;
}
}
}
children.add(n);
numOfLeaves++;
return true;
} else {
// find the next ancestor node
String parentName = getNextAncestorName(n);
InnerNode parentNode = (InnerNode)childrenMap.get(parentName);
if (parentNode == null) {
// create a new InnerNode
parentNode = createParentNode(parentName);
children.add(parentNode);
childrenMap.put(parentNode.getName(), parentNode);
}
// add n to the subtree of the next ancestor node
if (parentNode.add(n)) {
numOfLeaves++;
return true;
} else {
return false;
}
}
}
/**
* Creates a parent node to be added to the list of children.
* Creates a node using the InnerNode four argument constructor specifying
* the name, location, parent, and level of this node.
*
* <p>To be overridden in subclasses for specific InnerNode implementations,
* as alternative to overriding the full {@link #add(Node)} method.
*
* @param parentName The name of the parent node
* @return A new inner node
* @see InnerNodeImpl(String, String, InnerNode, int)
*/
private InnerNodeImpl createParentNode(String parentName) {
return new InnerNodeImpl(parentName,
getPath(this), this, this.getLevel() + 1);
}
@Override
public boolean remove(Node n) {
if (!isAncestor(n)) {
throw new IllegalArgumentException(n.getName()
+ ", which is located at " + n.getNetworkLocation()
+ ", is not a descendant of " + getPath(this));
}
if (isParent(n)) {
// this node is the parent of n; remove n directly
if (childrenMap.containsKey(n.getName())) {
for (int i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(n.getName())) {
children.remove(i);
childrenMap.remove(n.getName());
numOfLeaves--;
n.setParent(null);
return true;
}
}
}
return false;
} else {
// find the next ancestor node: the parent node
String parentName = getNextAncestorName(n);
InnerNodeImpl parentNode = (InnerNodeImpl)childrenMap.get(parentName);
if (parentNode == null) {
return false;
}
// remove n from the parent node
boolean isRemoved = parentNode.remove(n);
// if the parent node has no children, remove the parent node too
if (isRemoved) {
if (parentNode.getNumOfChildren() == 0) {
for(int i=0; i < children.size(); i++) {
if (children.get(i).getName().equals(parentName)) {
children.remove(i);
childrenMap.remove(parentName);
break;
}
}
}
numOfLeaves--;
}
return isRemoved;
}
} // end of remove
@Override
public Node getLoc(String loc) {
if (loc == null || loc.length() == 0) {
return this;
}
String[] path = loc.split(PATH_SEPARATOR_STR, 2);
Node childNode = childrenMap.get(path[0]);
if (childNode == null || path.length == 1) {
return childNode;
} else if (childNode instanceof InnerNode) {
return ((InnerNode)childNode).getLoc(path[1]);
} else {
return null;
}
}
@Override
public Node getLeaf(int leafIndex, Node excludedNode) {
int count=0;
// check if the excluded node a leaf
boolean isLeaf = !(excludedNode instanceof InnerNode);
// calculate the total number of excluded leaf nodes
int numOfExcludedLeaves =
isLeaf ? 1 : ((InnerNode)excludedNode).getNumOfLeaves();
if (isLeafParent()) { // children are leaves
if (isLeaf) { // excluded node is a leaf node
if (excludedNode != null &&
childrenMap.containsKey(excludedNode.getName())) {
int excludedIndex = children.indexOf(excludedNode);
if (excludedIndex != -1 && leafIndex >= 0) {
// excluded node is one of the children so adjust the leaf index
leafIndex = leafIndex>=excludedIndex ? leafIndex+1 : leafIndex;
}
}
}
// range check
if (leafIndex<0 || leafIndex>=this.getNumOfChildren()) {
return null;
}
return children.get(leafIndex);
} else {
for(int i=0; i<children.size(); i++) {
InnerNodeImpl child = (InnerNodeImpl)children.get(i);
if (excludedNode == null || excludedNode != child) {
// not the excludedNode
int numOfLeaves = child.getNumOfLeaves();
if (excludedNode != null && child.isAncestor(excludedNode)) {
numOfLeaves -= numOfExcludedLeaves;
}
if (count+numOfLeaves > leafIndex) {
// the leaf is in the child subtree
return child.getLeaf(leafIndex-count, excludedNode);
} else {
// go to the next child
count = count+numOfLeaves;
}
} else { // it is the excluededNode
// skip it and set the excludedNode to be null
excludedNode = null;
}
}
return null;
}
}
private boolean isLeafParent() {
return isRack();
}
@Override
public int getNumOfLeaves() {
return numOfLeaves;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object to) {
return super.equals(to);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.