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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e19cce36518b2489e21c7c569d8fab1d32a83c3 | 1,188 | java | Java | cloud-storage/googledrive/api/src/java/org/sakaiproject/googledrive/model/GoogleDriveItemComparator.java | dsp-testing/sakai | 220c13b3a8dc8d7d7838508b2c85bef56e40d95b | [
"ECL-2.0"
] | 1 | 2016-08-12T21:11:32.000Z | 2016-08-12T21:11:32.000Z | cloud-storage/googledrive/api/src/java/org/sakaiproject/googledrive/model/GoogleDriveItemComparator.java | Bobmaintain/sakai | eff276d940e373469ff93e8062ae40b95689068f | [
"ECL-2.0"
] | null | null | null | cloud-storage/googledrive/api/src/java/org/sakaiproject/googledrive/model/GoogleDriveItemComparator.java | Bobmaintain/sakai | eff276d940e373469ff93e8062ae40b95689068f | [
"ECL-2.0"
] | 2 | 2017-06-24T09:07:26.000Z | 2017-06-26T09:07:26.000Z | 34.941176 | 81 | 0.692761 | 10,940 | /**
* Copyright (c) 2003-2019 The Apereo Foundation
*
* Licensed under the Educational Community 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://opensource.org/licenses/ecl2
*
* 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.sakaiproject.googledrive.model;
import java.util.Comparator;
public class GoogleDriveItemComparator implements Comparator<GoogleDriveItem> {
@Override
public int compare(GoogleDriveItem o1, GoogleDriveItem o2) {
String o1Name = o1.getGoogleDriveItemId();
String o2Name = o2.getGoogleDriveItemId();
if(!o1.isFolder()){
o1Name = o1.getParentId() + o1Name;
}
if(!o2.isFolder()){
o2Name = o2.getParentId() + o2Name;
}
return o1Name.compareTo(o2Name);
}
}
|
3e19cd7cd3a0bc1174ad424b8a543f9c00b76318 | 572 | java | Java | lion-gateway-server/src/main/java/com/zhaoguhong/lion/gateway/config/HandlerChainConfig.java | zhaoguhong/lion-gateway | c5d5ce9d248f399f6485379e2e2a77a1ef66266a | [
"Apache-2.0"
] | null | null | null | lion-gateway-server/src/main/java/com/zhaoguhong/lion/gateway/config/HandlerChainConfig.java | zhaoguhong/lion-gateway | c5d5ce9d248f399f6485379e2e2a77a1ef66266a | [
"Apache-2.0"
] | null | null | null | lion-gateway-server/src/main/java/com/zhaoguhong/lion/gateway/config/HandlerChainConfig.java | zhaoguhong/lion-gateway | c5d5ce9d248f399f6485379e2e2a77a1ef66266a | [
"Apache-2.0"
] | null | null | null | 26 | 86 | 0.809441 | 10,941 | package com.zhaoguhong.lion.gateway.config;
import com.zhaoguhong.lion.gateway.plugin.handler.DefaultHandlerChain;
import com.zhaoguhong.lion.gateway.plugin.handler.PluginHandler;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author zhaoguhong
* @date 2021/11/26
*/
@Configuration
public class HandlerChainConfig {
@Bean
public DefaultHandlerChain DefaultHandlerChain(List<PluginHandler> pluginHandlers) {
return new DefaultHandlerChain(pluginHandlers);
}
}
|
3e19cde4e90f483ace05da971333cd2efca39e07 | 1,245 | java | Java | src/cz/vutbr/web/csskit/TermURIImpl.java | chrimm/cordovastudio | 199233198db410a9f2d7c8d8c103b85220912dae | [
"Apache-2.0"
] | 2 | 2017-07-02T13:39:06.000Z | 2021-12-22T08:09:27.000Z | src/cz/vutbr/web/csskit/TermURIImpl.java | chrimm/cordovastudio | 199233198db410a9f2d7c8d8c103b85220912dae | [
"Apache-2.0"
] | null | null | null | src/cz/vutbr/web/csskit/TermURIImpl.java | chrimm/cordovastudio | 199233198db410a9f2d7c8d8c103b85220912dae | [
"Apache-2.0"
] | null | null | null | 21.101695 | 84 | 0.545382 | 10,942 | package cz.vutbr.web.csskit;
import java.net.URL;
import cz.vutbr.web.css.TermURI;
/**
* TermURIImpl
* @author kapy
* @author Jan Svercl, VUT Brno, 2008
*/
public class TermURIImpl extends TermImpl<String> implements TermURI {
protected URL base;
protected TermURIImpl() {
}
@Override
public TermURI setValue(String uri) {
if(uri == null)
throw new IllegalArgumentException("Invalid uri for TermURI(null)");
/* this shlould be done by parser
uri = uri.replaceAll("^url\\(", "")
.replaceAll("\\)$", "")
.replaceAll("^'", "")
.replaceAll("^\"", "")
.replaceAll("'$", "")
.replaceAll("\"$", "");
*/
this.value = uri;
return this;
}
public TermURI setBase(URL base)
{
this.base = base;
return this;
}
public URL getBase()
{
return base;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(operator!=null) sb.append(operator.value());
sb.append(OutputUtil.URL_OPENING).append(value).append(OutputUtil.URL_CLOSING);
return sb.toString();
}
}
|
3e19ce5a3a3e0b9955f0f31e009a7ea30fcced3c | 2,381 | java | Java | sqlg-core/src/main/java/org/umlg/sqlg/util/SqlgTraversalUtil.java | wiltonlazary/sqlg | 3a1b31133a55b74816b6ae02f4095a88616c17cf | [
"MIT"
] | null | null | null | sqlg-core/src/main/java/org/umlg/sqlg/util/SqlgTraversalUtil.java | wiltonlazary/sqlg | 3a1b31133a55b74816b6ae02f4095a88616c17cf | [
"MIT"
] | 2 | 2022-01-21T23:27:09.000Z | 2022-02-16T01:05:52.000Z | sqlg-core/src/main/java/org/umlg/sqlg/util/SqlgTraversalUtil.java | wiltonlazary/sqlg | 3a1b31133a55b74816b6ae02f4095a88616c17cf | [
"MIT"
] | null | null | null | 37.793651 | 120 | 0.659807 | 10,943 | package org.umlg.sqlg.util;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import java.util.List;
import java.util.function.Predicate;
/**
* @author Pieter Martin (https://github.com/pietermartin)
* Date: 2017/04/29
*/
public class SqlgTraversalUtil {
public static final <S, E> boolean test(final Traverser.Admin<S> traverser, final Traversal.Admin<S, E> traversal) {
final Traverser.Admin<S> split = traverser.split();
split.setSideEffects(traversal.getSideEffects());
split.setBulk(1l);
// traversal.reset();
traversal.addStart(split);
return traversal.hasNext(); // filter
}
public static boolean hasOneBulkRequirement(Traversal.Admin<?, ?> traversal) {
List<Step> steps = TraversalHelper.getStepsOfAssignableClassRecursively(Step.class, traversal);
for (Step step : steps) {
if (step.getRequirements().contains(TraverserRequirement.ONE_BULK)) {
return true;
}
}
return false;
}
public static boolean anyStepRecursively(final Predicate<Step> predicate, final Traversal.Admin<?, ?> traversal) {
for (final Step<?, ?> step : traversal.getSteps()) {
if (predicate.test(step)) {
return true;
}
if (step instanceof TraversalParent) {
if (anyStepRecursively(predicate, ((TraversalParent) step))) {
return true;
}
}
}
return false;
}
public static boolean anyStepRecursively(final Predicate<Step> predicate, final TraversalParent step) {
for (final Traversal.Admin<?, ?> localChild : step.getLocalChildren()) {
if (anyStepRecursively(predicate, localChild)) return true;
}
for (final Traversal.Admin<?, ?> globalChild : step.getGlobalChildren()) {
if (anyStepRecursively(predicate, globalChild)) return true;
}
return false;
}
}
|
3e19cebb7cd3a03b1e1b5a91253fa819d17d08d9 | 19,871 | java | Java | antlr-src/org/antlr/v4/runtime/misc/IntervalSet.java | MegaApuTurkUltra/Scratch-ApuC | f5525ec9939d0dd2e3cc6365c87091d76effe360 | [
"Apache-2.0"
] | 10 | 2015-02-17T19:02:26.000Z | 2020-03-23T14:12:18.000Z | runtime/Java/src/org/antlr/v4/runtime/misc/IntervalSet.java | Acidburn0zzz/antlr4 | 561383c34c5973e129ed77d33a1d850ed4273cc3 | [
"BSD-3-Clause"
] | 1 | 2019-12-14T18:53:15.000Z | 2020-12-13T15:06:14.000Z | runtime/Java/src/org/antlr/v4/runtime/misc/IntervalSet.java | Acidburn0zzz/antlr4 | 561383c34c5973e129ed77d33a1d850ed4273cc3 | [
"BSD-3-Clause"
] | 1 | 2016-01-09T07:21:02.000Z | 2016-01-09T07:21:02.000Z | 27.947961 | 112 | 0.615923 | 10,944 | /*
* [The "BSD license"]
* Copyright (c) 2012 Terence Parr
* Copyright (c) 2012 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.v4.runtime.misc;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Token;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
/**
* This class implements the {@link IntSet} backed by a sorted array of
* non-overlapping intervals. It is particularly efficient for representing
* large collections of numbers, where the majority of elements appear as part
* of a sequential range of numbers that are all part of the set. For example,
* the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.
*
* <p>
* This class is able to represent sets containing any combination of values in
* the range {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE}
* (inclusive).</p>
*/
public class IntervalSet implements IntSet {
public static final IntervalSet COMPLETE_CHAR_SET = IntervalSet.of(Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE);
static {
COMPLETE_CHAR_SET.setReadonly(true);
}
public static final IntervalSet EMPTY_SET = new IntervalSet();
static {
EMPTY_SET.setReadonly(true);
}
/** The list of sorted, disjoint intervals. */
protected List<Interval> intervals;
protected boolean readonly;
public IntervalSet(List<Interval> intervals) {
this.intervals = intervals;
}
public IntervalSet(IntervalSet set) {
this();
addAll(set);
}
public IntervalSet(int... els) {
if ( els==null ) {
intervals = new ArrayList<Interval>(2); // most sets are 1 or 2 elements
}
else {
intervals = new ArrayList<Interval>(els.length);
for (int e : els) add(e);
}
}
/** Create a set with a single element, el. */
@NotNull
public static IntervalSet of(int a) {
IntervalSet s = new IntervalSet();
s.add(a);
return s;
}
/** Create a set with all ints within range [a..b] (inclusive) */
public static IntervalSet of(int a, int b) {
IntervalSet s = new IntervalSet();
s.add(a,b);
return s;
}
public void clear() {
if ( readonly ) throw new IllegalStateException("can't alter readonly IntervalSet");
intervals.clear();
}
/** Add a single element to the set. An isolated element is stored
* as a range el..el.
*/
@Override
public void add(int el) {
if ( readonly ) throw new IllegalStateException("can't alter readonly IntervalSet");
add(el,el);
}
/** Add interval; i.e., add all integers from a to b to set.
* If b<a, do nothing.
* Keep list in sorted order (by left range value).
* If overlap, combine ranges. For example,
* If this is {1..5, 10..20}, adding 6..7 yields
* {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}.
*/
public void add(int a, int b) {
add(Interval.of(a, b));
}
// copy on write so we can cache a..a intervals and sets of that
protected void add(Interval addition) {
if ( readonly ) throw new IllegalStateException("can't alter readonly IntervalSet");
//System.out.println("add "+addition+" to "+intervals.toString());
if ( addition.b<addition.a ) {
return;
}
// find position in list
// Use iterators as we modify list in place
for (ListIterator<Interval> iter = intervals.listIterator(); iter.hasNext();) {
Interval r = iter.next();
if ( addition.equals(r) ) {
return;
}
if ( addition.adjacent(r) || !addition.disjoint(r) ) {
// next to each other, make a single larger interval
Interval bigger = addition.union(r);
iter.set(bigger);
// make sure we didn't just create an interval that
// should be merged with next interval in list
while ( iter.hasNext() ) {
Interval next = iter.next();
if ( !bigger.adjacent(next) && bigger.disjoint(next) ) {
break;
}
// if we bump up against or overlap next, merge
iter.remove(); // remove this one
iter.previous(); // move backwards to what we just set
iter.set(bigger.union(next)); // set to 3 merged ones
iter.next(); // first call to next after previous duplicates the result
}
return;
}
if ( addition.startsBeforeDisjoint(r) ) {
// insert before r
iter.previous();
iter.add(addition);
return;
}
// if disjoint and after r, a future iteration will handle it
}
// ok, must be after last interval (and disjoint from last interval)
// just add it
intervals.add(addition);
}
/** combine all sets in the array returned the or'd value */
public static IntervalSet or(IntervalSet[] sets) {
IntervalSet r = new IntervalSet();
for (IntervalSet s : sets) r.addAll(s);
return r;
}
@Override
public IntervalSet addAll(IntSet set) {
if ( set==null ) {
return this;
}
if (set instanceof IntervalSet) {
IntervalSet other = (IntervalSet)set;
// walk set and add each interval
int n = other.intervals.size();
for (int i = 0; i < n; i++) {
Interval I = other.intervals.get(i);
this.add(I.a,I.b);
}
}
else {
for (int value : set.toList()) {
add(value);
}
}
return this;
}
public IntervalSet complement(int minElement, int maxElement) {
return this.complement(IntervalSet.of(minElement,maxElement));
}
/** {@inheritDoc} */
@Override
public IntervalSet complement(IntSet vocabulary) {
if ( vocabulary==null || vocabulary.isNil() ) {
return null; // nothing in common with null set
}
IntervalSet vocabularyIS;
if (vocabulary instanceof IntervalSet) {
vocabularyIS = (IntervalSet)vocabulary;
}
else {
vocabularyIS = new IntervalSet();
vocabularyIS.addAll(vocabulary);
}
return vocabularyIS.subtract(this);
}
@Override
public IntervalSet subtract(IntSet a) {
if (a == null || a.isNil()) {
return new IntervalSet(this);
}
if (a instanceof IntervalSet) {
return subtract(this, (IntervalSet)a);
}
IntervalSet other = new IntervalSet();
other.addAll(a);
return subtract(this, other);
}
/**
* Compute the set difference between two interval sets. The specific
* operation is {@code left - right}. If either of the input sets is
* {@code null}, it is treated as though it was an empty set.
*/
@NotNull
public static IntervalSet subtract(@Nullable IntervalSet left, @Nullable IntervalSet right) {
if (left == null || left.isNil()) {
return new IntervalSet();
}
IntervalSet result = new IntervalSet(left);
if (right == null || right.isNil()) {
// right set has no elements; just return the copy of the current set
return result;
}
int resultI = 0;
int rightI = 0;
while (resultI < result.intervals.size() && rightI < right.intervals.size()) {
Interval resultInterval = result.intervals.get(resultI);
Interval rightInterval = right.intervals.get(rightI);
// operation: (resultInterval - rightInterval) and update indexes
if (rightInterval.b < resultInterval.a) {
rightI++;
continue;
}
if (rightInterval.a > resultInterval.b) {
resultI++;
continue;
}
Interval beforeCurrent = null;
Interval afterCurrent = null;
if (rightInterval.a > resultInterval.a) {
beforeCurrent = new Interval(resultInterval.a, rightInterval.a - 1);
}
if (rightInterval.b < resultInterval.b) {
afterCurrent = new Interval(rightInterval.b + 1, resultInterval.b);
}
if (beforeCurrent != null) {
if (afterCurrent != null) {
// split the current interval into two
result.intervals.set(resultI, beforeCurrent);
result.intervals.add(resultI + 1, afterCurrent);
resultI++;
rightI++;
continue;
}
else {
// replace the current interval
result.intervals.set(resultI, beforeCurrent);
resultI++;
continue;
}
}
else {
if (afterCurrent != null) {
// replace the current interval
result.intervals.set(resultI, afterCurrent);
rightI++;
continue;
}
else {
// remove the current interval (thus no need to increment resultI)
result.intervals.remove(resultI);
continue;
}
}
}
// If rightI reached right.intervals.size(), no more intervals to subtract from result.
// If resultI reached result.intervals.size(), we would be subtracting from an empty set.
// Either way, we are done.
return result;
}
@Override
public IntervalSet or(IntSet a) {
IntervalSet o = new IntervalSet();
o.addAll(this);
o.addAll(a);
return o;
}
/** {@inheritDoc} */
@Override
public IntervalSet and(IntSet other) {
if ( other==null ) { //|| !(other instanceof IntervalSet) ) {
return null; // nothing in common with null set
}
List<Interval> myIntervals = this.intervals;
List<Interval> theirIntervals = ((IntervalSet)other).intervals;
IntervalSet intersection = null;
int mySize = myIntervals.size();
int theirSize = theirIntervals.size();
int i = 0;
int j = 0;
// iterate down both interval lists looking for nondisjoint intervals
while ( i<mySize && j<theirSize ) {
Interval mine = myIntervals.get(i);
Interval theirs = theirIntervals.get(j);
//System.out.println("mine="+mine+" and theirs="+theirs);
if ( mine.startsBeforeDisjoint(theirs) ) {
// move this iterator looking for interval that might overlap
i++;
}
else if ( theirs.startsBeforeDisjoint(mine) ) {
// move other iterator looking for interval that might overlap
j++;
}
else if ( mine.properlyContains(theirs) ) {
// overlap, add intersection, get next theirs
if ( intersection==null ) {
intersection = new IntervalSet();
}
intersection.add(mine.intersection(theirs));
j++;
}
else if ( theirs.properlyContains(mine) ) {
// overlap, add intersection, get next mine
if ( intersection==null ) {
intersection = new IntervalSet();
}
intersection.add(mine.intersection(theirs));
i++;
}
else if ( !mine.disjoint(theirs) ) {
// overlap, add intersection
if ( intersection==null ) {
intersection = new IntervalSet();
}
intersection.add(mine.intersection(theirs));
// Move the iterator of lower range [a..b], but not
// the upper range as it may contain elements that will collide
// with the next iterator. So, if mine=[0..115] and
// theirs=[115..200], then intersection is 115 and move mine
// but not theirs as theirs may collide with the next range
// in thisIter.
// move both iterators to next ranges
if ( mine.startsAfterNonDisjoint(theirs) ) {
j++;
}
else if ( theirs.startsAfterNonDisjoint(mine) ) {
i++;
}
}
}
if ( intersection==null ) {
return new IntervalSet();
}
return intersection;
}
/** {@inheritDoc} */
@Override
public boolean contains(int el) {
int n = intervals.size();
for (int i = 0; i < n; i++) {
Interval I = intervals.get(i);
int a = I.a;
int b = I.b;
if ( el<a ) {
break; // list is sorted and el is before this interval; not here
}
if ( el>=a && el<=b ) {
return true; // found in this interval
}
}
return false;
/*
for (ListIterator iter = intervals.listIterator(); iter.hasNext();) {
Interval I = (Interval) iter.next();
if ( el<I.a ) {
break; // list is sorted and el is before this interval; not here
}
if ( el>=I.a && el<=I.b ) {
return true; // found in this interval
}
}
return false;
*/
}
/** {@inheritDoc} */
@Override
public boolean isNil() {
return intervals==null || intervals.isEmpty();
}
/** {@inheritDoc} */
@Override
public int getSingleElement() {
if ( intervals!=null && intervals.size()==1 ) {
Interval I = intervals.get(0);
if ( I.a == I.b ) {
return I.a;
}
}
return Token.INVALID_TYPE;
}
/**
* Returns the maximum value contained in the set.
*
* @return the maximum value contained in the set. If the set is empty, this
* method returns {@link Token#INVALID_TYPE}.
*/
public int getMaxElement() {
if ( isNil() ) {
return Token.INVALID_TYPE;
}
Interval last = intervals.get(intervals.size()-1);
return last.b;
}
/**
* Returns the minimum value contained in the set.
*
* @return the minimum value contained in the set. If the set is empty, this
* method returns {@link Token#INVALID_TYPE}.
*/
public int getMinElement() {
if ( isNil() ) {
return Token.INVALID_TYPE;
}
return intervals.get(0).a;
}
/** Return a list of Interval objects. */
public List<Interval> getIntervals() {
return intervals;
}
@Override
public int hashCode() {
int hash = MurmurHash.initialize();
for (Interval I : intervals) {
hash = MurmurHash.update(hash, I.a);
hash = MurmurHash.update(hash, I.b);
}
hash = MurmurHash.finish(hash, intervals.size() * 2);
return hash;
}
/** Are two IntervalSets equal? Because all intervals are sorted
* and disjoint, equals is a simple linear walk over both lists
* to make sure they are the same. Interval.equals() is used
* by the List.equals() method to check the ranges.
*/
@Override
public boolean equals(Object obj) {
if ( obj==null || !(obj instanceof IntervalSet) ) {
return false;
}
IntervalSet other = (IntervalSet)obj;
return this.intervals.equals(other.intervals);
}
@Override
public String toString() { return toString(false); }
public String toString(boolean elemAreChar) {
StringBuilder buf = new StringBuilder();
if ( this.intervals==null || this.intervals.isEmpty() ) {
return "{}";
}
if ( this.size()>1 ) {
buf.append("{");
}
Iterator<Interval> iter = this.intervals.iterator();
while (iter.hasNext()) {
Interval I = iter.next();
int a = I.a;
int b = I.b;
if ( a==b ) {
if ( a==Token.EOF ) buf.append("<EOF>");
else if ( elemAreChar ) buf.append("'").append((char)a).append("'");
else buf.append(a);
}
else {
if ( elemAreChar ) buf.append("'").append((char)a).append("'..'").append((char)b).append("'");
else buf.append(a).append("..").append(b);
}
if ( iter.hasNext() ) {
buf.append(", ");
}
}
if ( this.size()>1 ) {
buf.append("}");
}
return buf.toString();
}
public String toString(String[] tokenNames) {
StringBuilder buf = new StringBuilder();
if ( this.intervals==null || this.intervals.isEmpty() ) {
return "{}";
}
if ( this.size()>1 ) {
buf.append("{");
}
Iterator<Interval> iter = this.intervals.iterator();
while (iter.hasNext()) {
Interval I = iter.next();
int a = I.a;
int b = I.b;
if ( a==b ) {
buf.append(elementName(tokenNames, a));
}
else {
for (int i=a; i<=b; i++) {
if ( i>a ) buf.append(", ");
buf.append(elementName(tokenNames, i));
}
}
if ( iter.hasNext() ) {
buf.append(", ");
}
}
if ( this.size()>1 ) {
buf.append("}");
}
return buf.toString();
}
protected String elementName(String[] tokenNames, int a) {
if ( a==Token.EOF ) return "<EOF>";
else if ( a==Token.EPSILON ) return "<EPSILON>";
else return tokenNames[a];
}
@Override
public int size() {
int n = 0;
int numIntervals = intervals.size();
if ( numIntervals==1 ) {
Interval firstInterval = this.intervals.get(0);
return firstInterval.b-firstInterval.a+1;
}
for (int i = 0; i < numIntervals; i++) {
Interval I = intervals.get(i);
n += (I.b-I.a+1);
}
return n;
}
public IntegerList toIntegerList() {
IntegerList values = new IntegerList(size());
int n = intervals.size();
for (int i = 0; i < n; i++) {
Interval I = intervals.get(i);
int a = I.a;
int b = I.b;
for (int v=a; v<=b; v++) {
values.add(v);
}
}
return values;
}
@Override
public List<Integer> toList() {
List<Integer> values = new ArrayList<Integer>();
int n = intervals.size();
for (int i = 0; i < n; i++) {
Interval I = intervals.get(i);
int a = I.a;
int b = I.b;
for (int v=a; v<=b; v++) {
values.add(v);
}
}
return values;
}
public Set<Integer> toSet() {
Set<Integer> s = new HashSet<Integer>();
for (Interval I : intervals) {
int a = I.a;
int b = I.b;
for (int v=a; v<=b; v++) {
s.add(v);
}
}
return s;
}
/** Get the ith element of ordered set. Used only by RandomPhrase so
* don't bother to implement if you're not doing that for a new
* ANTLR code gen target.
*/
public int get(int i) {
int n = intervals.size();
int index = 0;
for (int j = 0; j < n; j++) {
Interval I = intervals.get(j);
int a = I.a;
int b = I.b;
for (int v=a; v<=b; v++) {
if ( index==i ) {
return v;
}
index++;
}
}
return -1;
}
public int[] toArray() {
return toIntegerList().toArray();
}
@Override
public void remove(int el) {
if ( readonly ) throw new IllegalStateException("can't alter readonly IntervalSet");
int n = intervals.size();
for (int i = 0; i < n; i++) {
Interval I = intervals.get(i);
int a = I.a;
int b = I.b;
if ( el<a ) {
break; // list is sorted and el is before this interval; not here
}
// if whole interval x..x, rm
if ( el==a && el==b ) {
intervals.remove(i);
break;
}
// if on left edge x..b, adjust left
if ( el==a ) {
I.a++;
break;
}
// if on right edge a..x, adjust right
if ( el==b ) {
I.b--;
break;
}
// if in middle a..x..b, split interval
if ( el>a && el<b ) { // found in this interval
int oldb = I.b;
I.b = el-1; // [a..x-1]
add(el+1, oldb); // add [x+1..b]
}
}
}
public boolean isReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
if ( this.readonly && !readonly ) throw new IllegalStateException("can't alter readonly IntervalSet");
this.readonly = readonly;
}
}
|
3e19cef1856b6d747cd740a6b9dd16f25525e7d5 | 1,596 | java | Java | rule-engine/src/main/java/bigdata/hermesfuxi/eagle/rules/service/realtime/UserActionCountQueryServiceStateImpl.java | Hermesfuxi/eagle | 640c1ece5e09b2b5d7558555f8209e8fc524b228 | [
"Apache-2.0"
] | 10 | 2021-04-27T12:07:38.000Z | 2022-03-25T14:38:29.000Z | rule-engine/src/main/java/bigdata/hermesfuxi/eagle/rules/service/realtime/UserActionCountQueryServiceStateImpl.java | Hermesfuxi/eagle | 640c1ece5e09b2b5d7558555f8209e8fc524b228 | [
"Apache-2.0"
] | null | null | null | rule-engine/src/main/java/bigdata/hermesfuxi/eagle/rules/service/realtime/UserActionCountQueryServiceStateImpl.java | Hermesfuxi/eagle | 640c1ece5e09b2b5d7558555f8209e8fc524b228 | [
"Apache-2.0"
] | 1 | 2021-12-30T07:16:20.000Z | 2021-12-30T07:16:20.000Z | 33.25 | 112 | 0.659148 | 10,945 | package bigdata.hermesfuxi.eagle.rules.service.realtime;
import bigdata.hermesfuxi.eagle.rules.pojo.LogBean;
import bigdata.hermesfuxi.eagle.rules.pojo.AtomicRuleParam;
import bigdata.hermesfuxi.eagle.rules.pojo.RuleParam;
import bigdata.hermesfuxi.eagle.rules.utils.RuleCalculateUtils;
import java.util.List;
/**
* @author hermesfuxi
* desc 用户行为次数类条件查询服务实现:在flink的state中统计行为次数
*/
public class UserActionCountQueryServiceStateImpl implements RealTimeRuleQueryCalculateService {
/**
* 查询规则参数对象中,要求的用户行为次数类条件是否满足
* 同时,将查询到的真实次数,set回 规则参数对象中
*
* @param logBeans 用户事件明细
* @param ruleParam 规则整体参数对象
* @return 条件是否满足
*/
@Override
public Boolean ruleQueryCalculate(Iterable<LogBean> logBeans, RuleParam ruleParam) throws Exception {
// 判断行为次数条件: B(p1=v1) >= 1次 且 D(p2=v3)>=1
List<AtomicRuleParam> userActionCountParams = ruleParam.getUserActionCountParams();
for (AtomicRuleParam userActionCountParam : userActionCountParams) {
// B(p1=v1) >= 1次 且 D(p2=v3)>=1
// 内循环,遍历每一个历史明细事件,看看能否找到与当前条件匹配的事件
int count = userActionCountParam.getRealCnts();
for (LogBean logBean : logBeans) {
boolean flag = RuleCalculateUtils.eventBeanMatchEventParam(logBean, userActionCountParam, true);
if(flag){
count++;
}
}
userActionCountParam.setRealCnts(count);
if(count < userActionCountParam.getCnts()){
return false;
}
}
return true;
}
}
|
3e19cf52e8d6a4ef54aeca2e4ed8616d1b4be2cd | 1,310 | java | Java | transpiler-core/src/main/java/com/scheible/simplistictranspiler/transpiler/resolver/IdentifierScoper.java | janScheible/simplistic-transpiler | 4602aee1b5f1f7b38ba2ce234ee684d8822008ef | [
"MIT"
] | 1 | 2021-05-18T17:17:23.000Z | 2021-05-18T17:17:23.000Z | transpiler-core/src/main/java/com/scheible/simplistictranspiler/transpiler/resolver/IdentifierScoper.java | janScheible/simplistic-transpiler | 4602aee1b5f1f7b38ba2ce234ee684d8822008ef | [
"MIT"
] | null | null | null | transpiler-core/src/main/java/com/scheible/simplistictranspiler/transpiler/resolver/IdentifierScoper.java | janScheible/simplistic-transpiler | 4602aee1b5f1f7b38ba2ce234ee684d8822008ef | [
"MIT"
] | null | null | null | 34.473684 | 149 | 0.739695 | 10,946 | package com.scheible.simplistictranspiler.transpiler.resolver;
import com.scheible.simplistictranspiler.transpiler.helper.AnnotationProvider;
import com.scheible.simplistictranspiler.transpiler.jdkinternal.JdkInternalHelper;
import com.sun.source.tree.IdentifierTree;
import java.util.Map;
import java.util.function.Function;
import jsinterop.annotations.JsType;
/**
*
* @author sj
*/
public class IdentifierScoper {
//
// customization of scope classes names (e.g. '@JsType(isNative = true, name = "custom")')
//
final static Function<Map.Entry<String, AnnotationProvider>, String> JS_TYPE_NAME_TRANSFORMATOR = (Map.Entry<String, AnnotationProvider> entry) -> {
return entry.getValue().get(JsType.class)
.map(annotation -> "<auto>".equals(annotation.name()) ? entry.getKey() : annotation.name()).orElse(entry.getKey());
};
String getScope(final IdentifierTree node) {
final String name = node.getName().toString();
String scope = "";
if (!JdkInternalHelper.isTopLevelClass(node)) {
if (JdkInternalHelper.isStatic(node)) {
scope = JdkInternalHelper.getOwnerTopLevelRelativeName(node, JS_TYPE_NAME_TRANSFORMATOR) + ".";
} else if (JdkInternalHelper.isMemberVariable(node) && !"this".equals(name) && !"super".equals(name)) {
scope = "this.";
}
}
return scope;
}
}
|
3e19cf8a40f3720b3699ff8b2e59e64282f505e9 | 12,427 | java | Java | interfacemodules/xml/src/test/java/org/treetank/service/xml/xpath/filter/FilterTest.java | sebastiangraf/treetank | 9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60 | [
"BSD-3-Clause"
] | 5 | 2015-11-05T06:52:43.000Z | 2020-09-15T09:34:15.000Z | interfacemodules/xml/src/test/java/org/treetank/service/xml/xpath/filter/FilterTest.java | sebastiangraf/treetank | 9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60 | [
"BSD-3-Clause"
] | null | null | null | interfacemodules/xml/src/test/java/org/treetank/service/xml/xpath/filter/FilterTest.java | sebastiangraf/treetank | 9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60 | [
"BSD-3-Clause"
] | 1 | 2018-12-29T08:38:20.000Z | 2018-12-29T08:38:20.000Z | 31.864103 | 84 | 0.683995 | 10,947 | /**
* Copyright (c) 2011, University of Konstanz, Distributed Systems Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Konstanz nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.treetank.service.xml.xpath.filter;
import static org.testng.AssertJUnit.assertEquals;
import static org.treetank.data.IConstants.ROOT_NODE;
import java.util.Properties;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import org.treetank.access.conf.ResourceConfiguration;
import org.treetank.access.conf.ResourceConfiguration.IResourceConfigurationFactory;
import org.treetank.access.conf.StandardSettings;
import org.treetank.api.INodeReadTrx;
import org.treetank.axis.AbsAxis;
import org.treetank.axis.filter.AbsFilter;
import org.treetank.axis.filter.AttributeFilter;
import org.treetank.axis.filter.ElementFilter;
import org.treetank.axis.filter.ItemFilter;
import org.treetank.axis.filter.NameFilter;
import org.treetank.axis.filter.NestedFilter;
import org.treetank.axis.filter.NodeFilter;
import org.treetank.axis.filter.TextFilter;
import org.treetank.axis.filter.TypeFilter;
import org.treetank.axis.filter.WildcardFilter;
import org.treetank.exception.TTByteHandleException;
import org.treetank.exception.TTException;
import org.treetank.exception.TTIOException;
import org.treetank.exception.TTXPathException;
import org.treetank.service.xml.xpath.AxisTest;
import org.treetank.service.xml.xpath.XPathAxis;
import org.treetank.testutil.CoreTestHelper;
import org.treetank.testutil.Holder;
import org.treetank.testutil.ModuleFactory;
import org.treetank.testutil.NodeElementTestHelper;
import com.google.inject.Inject;
/**
* Test Cases for all AbsAxis-implementations
*
* @author Sebastian Graf, University of Konstanz
*
*/
@Guice(moduleFactory = ModuleFactory.class)
public class FilterTest {
private Holder holder;
@Inject
private IResourceConfigurationFactory mResourceConfig;
private ResourceConfiguration mResource;
@BeforeClass
public void setUp() throws TTException {
CoreTestHelper.deleteEverything();
CoreTestHelper.Holder holder = CoreTestHelper.Holder.generateStorage();
Properties props = StandardSettings.getProps(CoreTestHelper.PATHS.PATH1
.getFile().getAbsolutePath(), CoreTestHelper.RESOURCENAME);
mResource = mResourceConfig.create(props);
NodeElementTestHelper.createTestDocument(mResource);
this.holder = Holder.generateRtx(holder, mResource);
}
@AfterClass
public void tearDown() throws TTException {
holder.close();
CoreTestHelper.deleteEverything();
}
@Test(dataProvider = "instantiateFilter")
public void testFilter(Class<IFilterChecker> pFilterCheckerClass,
IFilterChecker[] pFilterChecker) throws Exception {
for (int i = 0; i < pFilterChecker.length; i++) {
pFilterChecker[i].checkFilter(holder.getNRtx());
}
}
@DataProvider(name = "instantiateFilter")
public Object[][] instantiateFilter() throws TTByteHandleException {
Object[][] returnVal = { { IFilterChecker.class, new IFilterChecker[] {
// DocumentNode Filter
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTXPathException, TTIOException {
pRtx.moveTo(1L);
AxisTest.testIAxisConventions(
new DocumentNodeAxis(pRtx),
new long[] { ROOT_NODE });
pRtx.moveTo(5L);
AxisTest.testIAxisConventions(
new DocumentNodeAxis(pRtx),
new long[] { ROOT_NODE });
pRtx.moveTo(9L);
AxisTest.testIAxisConventions(
new DocumentNodeAxis(pRtx),
new long[] { ROOT_NODE });
pRtx.moveTo(9L);
pRtx.moveToAttribute(0);
AxisTest.testIAxisConventions(
new DocumentNodeAxis(pRtx),
new long[] { ROOT_NODE });
pRtx.moveTo(13L);
AxisTest.testIAxisConventions(
new DocumentNodeAxis(pRtx),
new long[] { ROOT_NODE });
}
}, // DubFilter Test
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTXPathException, TTIOException {
pRtx.moveTo(1L);
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"child::node()/parent::node()"),
new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"b/following-sibling::node()"), new long[] {
8L, 9L, 13L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"b/preceding::node()"), new long[] { 4L, 8L,
7L, 6L, 5L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"//c/ancestor::node()"), new long[] { 5L, 1L,
9L });
}
}, // ItemFilter Test
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTXPathException, TTIOException {
pRtx.moveTo(9L);
testFilterConventions(new ItemFilter(pRtx), true);
pRtx.moveTo(3L);
testFilterConventions(new ItemFilter(pRtx), true);
pRtx.moveTo(2L);
pRtx.moveToAttribute(0);
testFilterConventions(new ItemFilter(pRtx), true);
}
}, // Nested Filter Test
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTXPathException, TTIOException {
pRtx.moveTo(9L);
testFilterConventions(new NestedFilter(pRtx,
new ItemFilter(holder.getNRtx()),
new ElementFilter(pRtx), new NameFilter(pRtx,
"b")), true);
testFilterConventions(new NestedFilter(pRtx,
new ItemFilter(pRtx),
new AttributeFilter(pRtx), new NameFilter(pRtx,
"b")), false);
pRtx.moveTo(4L);
testFilterConventions(new NestedFilter(pRtx,
new NodeFilter(holder.getNRtx()),
new ElementFilter(pRtx)), false);
testFilterConventions(new NestedFilter(pRtx,
new NodeFilter(holder.getNRtx()),
new TextFilter(pRtx)), true);
pRtx.moveTo(1L);
pRtx.moveToAttribute(0);
testFilterConventions(new NestedFilter(pRtx,
new AttributeFilter(holder.getNRtx()),
new NameFilter(pRtx, "i")), true);
}
}, // Predicate Filter Test
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTXPathException, TTIOException {
// Find descendants starting from nodeKey 0L (root).
pRtx.moveTo(ROOT_NODE);
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"/p:a[@i]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a/b[@p:x]"), new long[] { 9L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[text()]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[element()]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[node()/text()]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[./node()]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[./node()/node()/node()]"), new long[] {});
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[//element()]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[/text()]"), new long[] {});
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[3<4]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[13>=4]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[13.0>=4]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[4 = 4]"), new long[] { 1L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[3=4]"), new long[] {});
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"p:a[3.2 = 3.22]"), new long[] {});
pRtx.moveTo(1L);
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"child::b[child::c]"), new long[] { 5L, 9L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"child::*[text() or c]"), new long[] { 5l, 9L });
AxisTest.testIAxisConventions(new XPathAxis(pRtx,
"child::*[text() or c], /node(), //c"),
new long[] { 5l, 9L, 1L, 7L, 11L });
}
}, // Type Filter Test
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTIOException, TTXPathException {
final AbsAxis axis = new XPathAxis(pRtx, "a");
axis.moveTo(9L);
testFilterConventions(
new TypeFilter(pRtx, "xs:untyped"), true);
testFilterConventions(new TypeFilter(pRtx, "xs:long"),
false);
pRtx.moveTo(4L);
testFilterConventions(
new TypeFilter(pRtx, "xs:untyped"), true);
testFilterConventions(
new TypeFilter(pRtx, "xs:double"), false);
pRtx.moveTo(1L);
pRtx.moveToAttribute(0);
testFilterConventions(
new TypeFilter(pRtx, "xs:untyped"), true);
testFilterConventions(
new TypeFilter(pRtx, "xs:anyType"), false);
}
}, // Wildcard Filter
new IFilterChecker() {
@Override
public void checkFilter(INodeReadTrx pRtx)
throws TTIOException {
pRtx.moveTo(9L);
FilterTest.testFilterConventions(new WildcardFilter(
pRtx, "b", true), true);
pRtx.moveToAttribute(0);
try {
testFilterConventions(new WildcardFilter(pRtx, "p",
false), true);
Assert.fail("Expected an Exception, because attributes are not supported.");
} catch (IllegalStateException e) {
assertEquals(e.getMessage(),
"Wildcards are not supported in attribute names yet.");
}
// IFilterTest.testIFilterConventions(new
// WildcardFilter(holder.getRtx(), "b",
// true), true);
// holder.getRtx().moveTo(3L);
// IFilterTest.testIFilterConventions(new
// ItemFilter(holder.getRtx()),
// true);
pRtx.moveTo(1L);
testFilterConventions(new WildcardFilter(pRtx, "p",
false), true);
testFilterConventions(new WildcardFilter(pRtx, "a",
true), true);
testFilterConventions(new WildcardFilter(pRtx, "c",
true), false);
testFilterConventions(new WildcardFilter(pRtx, "b",
false), false);
}
} } } };
return returnVal;
}
private static void testFilterConventions(final AbsFilter filter,
final boolean expected) {
// IFilter Convention 1.
final long startKey = filter.getNode().getDataKey();
assertEquals(expected, filter.filter());
// IAxis Convention 2.
assertEquals(startKey, filter.getNode().getDataKey());
}
/**
* Interface to check axis.
*
* @author Sebastian Graf, University of Konstanz
*
*/
interface IFilterChecker {
void checkFilter(INodeReadTrx pRtx) throws TTXPathException,
TTIOException;
}
}
|
3e19d02c9203d382aace2378096593cbac108b43 | 410 | java | Java | src/test/java/com/github/xuqplus/hi/leetcode/q0400/q0415/ATest.java | xuqplus/hi-leetcode | c1c6ce860393ff2179ccd23ddfb13901881d61de | [
"Apache-2.0"
] | null | null | null | src/test/java/com/github/xuqplus/hi/leetcode/q0400/q0415/ATest.java | xuqplus/hi-leetcode | c1c6ce860393ff2179ccd23ddfb13901881d61de | [
"Apache-2.0"
] | null | null | null | src/test/java/com/github/xuqplus/hi/leetcode/q0400/q0415/ATest.java | xuqplus/hi-leetcode | c1c6ce860393ff2179ccd23ddfb13901881d61de | [
"Apache-2.0"
] | null | null | null | 15.769231 | 51 | 0.612195 | 10,948 | package com.github.xuqplus.hi.leetcode.q0400.q0415;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
/**
* 字符串相加
* easy
* https://leetcode-cn.com/problems/add-strings/
*/
@Slf4j
public class ATest {
@Test
void a() {
Solution solution = new Solution();
log.info("{}", solution.run());
}
}
class Solution {
public int run() {
return 0;
}
}
|
3e19d02d6b48552ae9836d83244efe9f001b050d | 9,972 | java | Java | oxygen-sdk-workspace/sdkExtensions/oxygen-gim-extensions/src/main/java/com/oxygenxml/gim/operations/AddBusinessRuleOperation.java | nakohdo/dim | 8f4abd4a75ed8f8fc2ec4c90f721b65dabe8e8d9 | [
"Apache-2.0"
] | 28 | 2015-02-13T09:40:07.000Z | 2021-08-04T23:24:56.000Z | oxygen-sdk-workspace/sdkExtensions/oxygen-gim-extensions/src/main/java/com/oxygenxml/gim/operations/AddBusinessRuleOperation.java | nakohdo/dim | 8f4abd4a75ed8f8fc2ec4c90f721b65dabe8e8d9 | [
"Apache-2.0"
] | 13 | 2015-01-24T22:20:18.000Z | 2017-07-21T10:46:24.000Z | oxygen-sdk-workspace/sdkExtensions/oxygen-gim-extensions/src/main/java/com/oxygenxml/gim/operations/AddBusinessRuleOperation.java | nakohdo/dim | 8f4abd4a75ed8f8fc2ec4c90f721b65dabe8e8d9 | [
"Apache-2.0"
] | 17 | 2015-02-19T11:51:12.000Z | 2020-11-10T03:06:09.000Z | 41.55 | 146 | 0.661552 | 10,949 | package com.oxygenxml.gim.operations;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.text.BadLocationException;
import javax.xml.bind.JAXBException;
import javax.xml.transform.TransformerException;
import org.apache.log4j.Logger;
import org.eclipse.swt.widgets.Shell;
import ro.sync.ecss.extensions.api.ArgumentDescriptor;
import ro.sync.ecss.extensions.api.ArgumentsMap;
import ro.sync.ecss.extensions.api.AuthorAccess;
import ro.sync.ecss.extensions.api.AuthorConstants;
import ro.sync.ecss.extensions.api.AuthorDocumentController;
import ro.sync.ecss.extensions.api.AuthorOperation;
import ro.sync.ecss.extensions.api.AuthorOperationException;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import ro.sync.ecss.extensions.api.node.AuthorNodeUtil;
import ro.sync.util.URLUtil;
import com.oxygenxml.gim.BusinessRule;
import com.oxygenxml.gim.BusinessRuleLibrary;
import com.oxygenxml.gim.BusinessRuleParam;
import com.oxygenxml.gim.BusinessRuleRepository;
import com.oxygenxml.gim.ui.ec.ECBusinessRuleSelectDialog;
import com.oxygenxml.gim.ui.sa.SABusinessRuleSelectDialog;
/**
* An operation that adds a new business rule into the document.
*/
public class AddBusinessRuleOperation implements AuthorOperation {
/**
* Logger for logging.
*/
private static final Logger logger = Logger.getLogger(AddBusinessRuleOperation.class.getName());
/**
* The location where all the library rules are located.
*/
private static final String LIBRARY_LOCATION = "libraryLocation";
/**
* A string representation of an XML fragment. The moved node will be wrapped
* in this string before moving it in the destination.
*/
private static final String ARGUMENT_SURROUND_FRAGMENT_LOCATION = "surroundFragment";
/**
* The insert location argument.
* The value is <code>insertLocation</code>.
*/
public static final String ARGUMENT_XPATH_LOCATION = "insertLocation";
/**
* The insert position argument.
* The value is <code>insertPosition</code>.
*/
public static final String ARGUMENT_RELATIVE_LOCATION = "insertPosition";
/**
* The arguments for this operation.
*/
private ArgumentDescriptor[] arguments;
public AddBusinessRuleOperation() {
arguments = new ArgumentDescriptor[] {
new ArgumentDescriptor(
LIBRARY_LOCATION,
ArgumentDescriptor.TYPE_STRING,
"The location of the abstract rules library."),
new ArgumentDescriptor(
ARGUMENT_SURROUND_FRAGMENT_LOCATION,
ArgumentDescriptor.TYPE_FRAGMENT,
"A string representation of an XML fragment. The rule fragment will be wrapped "
+ "in this string before putting it in the destination."),
new ArgumentDescriptor(
ARGUMENT_XPATH_LOCATION,
ArgumentDescriptor.TYPE_XPATH_EXPRESSION,
"An XPath expression indicating the insert location for the fragment.\n" +
"Note: If it is not defined then the insert location will be at the caret."),
// Argument defining the relative position to the node obtained from the XPath location.
new ArgumentDescriptor(
ARGUMENT_RELATIVE_LOCATION,
ArgumentDescriptor.TYPE_CONSTANT_LIST,
"The insert position relative to the node determined by the XPath expression.\n" +
"Can be: "
+ AuthorConstants.POSITION_BEFORE + ", " +
AuthorConstants.POSITION_INSIDE_FIRST + ", " +
AuthorConstants.POSITION_INSIDE_LAST + " or " +
AuthorConstants.POSITION_AFTER + ".\n" +
"Note: If the XPath expression is not defined this argument is ignored",
new String[] {
AuthorConstants.POSITION_BEFORE,
AuthorConstants.POSITION_INSIDE_FIRST,
AuthorConstants.POSITION_INSIDE_LAST,
AuthorConstants.POSITION_AFTER,
},
AuthorConstants.POSITION_INSIDE_FIRST)
};
}
@Override
public String getDescription() {
return "Operation that parses a given library of rules and offser an UI in which the user can select a rule and give values for each parameter";
}
@Override
public void doOperation(AuthorAccess authorAccess, ArgumentsMap args)
throws IllegalArgumentException, AuthorOperationException {
// TODO How this operation works
// If we are inside a section with rules, just add it at the caret location.
// If we are somewhere else in the document, but we have a rules section, add it at the end of that.
// Otherwise, create a rules section and add it there.
// TODO Could this cases be expressed in more operations at the action level? And just give some
// arguments to the operation? like insertLocation and wrapper string?
String libraryLocationArg = (String) args.getArgumentValue(LIBRARY_LOCATION);
System.out.println("libraryLocationArg " + libraryLocationArg);
if (libraryLocationArg != null) {
String expandedLibraryLocation = authorAccess.getUtilAccess().expandEditorVariables(libraryLocationArg, null);
URL library = null;
try {
library = new URL(expandedLibraryLocation);
} catch (MalformedURLException e1) {
// Maybe is not an URL. Try to parse it as a File.
try {
library = URLUtil.correct(new File(expandedLibraryLocation));
} catch (MalformedURLException e) {
throw new AuthorOperationException("Unable to build an URL from the given library: " + libraryLocationArg);
}
}
try {
BusinessRuleLibrary rulesLibrary = BusinessRuleRepository.getInstance().loadLibrary(
authorAccess.getXMLUtilAccess(),
library);
BusinessRuleSelector businessRuleSelector = null;
// TODO make an interface BusinessRuleSelector, selectRule(rulesLibrary)
if (authorAccess.getWorkspaceAccess().isStandalone()) {
businessRuleSelector = new SABusinessRuleSelectDialog(
(JFrame) authorAccess.getWorkspaceAccess().getParentFrame());
} else {
//
businessRuleSelector = new ECBusinessRuleSelectDialog(
(Shell) authorAccess.getWorkspaceAccess().getParentFrame());
}
BusinessRule selectedRule = businessRuleSelector.selectRule(rulesLibrary);
if (selectedRule != null) {
Object xpathLocation = args.getArgumentValue(ARGUMENT_XPATH_LOCATION);
Object relativeLocation = args.getArgumentValue(ARGUMENT_RELATIVE_LOCATION);
int insertionOffset = authorAccess.getEditorAccess().getCaretOffset();
if (xpathLocation != null && ((String)xpathLocation).trim().length() > 0) {
// Evaluate the expression and obtain the offset of the first node from the result
insertionOffset =
authorAccess.getDocumentController().getXPathLocationOffset(
(String) xpathLocation, (String) relativeLocation);
}
String fragment = (String) args.getArgumentValue(ARGUMENT_SURROUND_FRAGMENT_LOCATION);
AuthorDocumentController ctrl = authorAccess.getDocumentController();
if (fragment != null) {
// 1. The fragment is optional. Insert the fragment, if any.
AuthorDocumentFragment xmlFragment = ctrl.createNewDocumentFragmentInContext(fragment, insertionOffset);
ctrl.insertFragment(insertionOffset, xmlFragment);
// 1.2 Relocated the insertion offset inside the first leaf of the fragment.
AuthorNode firstLeaf = AuthorNodeUtil.getFirstLeaf(xmlFragment);
if (firstLeaf != null) {
insertionOffset += firstLeaf.getStartOffset() + 1;
}
}
StringBuilder xmlFragment = new StringBuilder();
xmlFragment.append(
"<dl>\n" +
" <dlhead>\n" +
" <dthd>Rule</dthd>\n" +
" <ddhd>");
xmlFragment.append(selectedRule.getRuleName());
xmlFragment.append("</ddhd>" +
" </dlhead>\n");
List<BusinessRuleParam> params = selectedRule.getParams();
for (BusinessRuleParam param : params) {
xmlFragment.append(
" <dlentry>\n" +
" <dt>");
xmlFragment.append(param.getName());
xmlFragment.append("</dt>\n" +
" <dd></dd>\n" +
" </dlentry>\n");
}
xmlFragment.append("</dl>");
ctrl.insertXMLFragment(xmlFragment.toString(), insertionOffset);
// Move the caret in the first value that the user have to insert.
try {
AuthorNode dlNode = ctrl.getNodeAtOffset(insertionOffset + 1);
AuthorNode[] findNodes = ctrl.findNodesByXPath("dlentry[1]/dd", dlNode, true, true, true, false);
if (findNodes != null && findNodes.length > 0) {
authorAccess.getEditorAccess().setCaretPosition(findNodes[0].getStartOffset() + 1);
}
} catch (BadLocationException e) {
logger.error(e, e);
}
}
} catch (TransformerException e) {
e.printStackTrace();
throw new AuthorOperationException("Loading the library failed.", e);
} catch (JAXBException e) {
e.printStackTrace();
throw new AuthorOperationException("Loading the library failed.", e);
}
} else {
throw new AuthorOperationException("The library location was not specified.");
}
}
@Override
public ArgumentDescriptor[] getArguments() {
return arguments;
}
}
|
3e19d1dc7b7612fbc083d2318f897bab493233a6 | 2,472 | java | Java | src/GoBackDriver.java | arshiahsn/GoBackN | 8c02eecf8b5877d803683be7a53bc57fdc0c8219 | [
"MIT",
"Unlicense"
] | null | null | null | src/GoBackDriver.java | arshiahsn/GoBackN | 8c02eecf8b5877d803683be7a53bc57fdc0c8219 | [
"MIT",
"Unlicense"
] | null | null | null | src/GoBackDriver.java | arshiahsn/GoBackN | 8c02eecf8b5877d803683be7a53bc57fdc0c8219 | [
"MIT",
"Unlicense"
] | null | null | null | 28.413793 | 112 | 0.652913 | 10,950 |
/**
* A simple driver for GoBackFtp class
*
* CPSC 441
* Assignment 5
*
* @author Majid Ghaderi
* @version 2021
*
*/
import java.io.*;
import java.util.*;
import java.util.logging.*;
public class GoBackDriver {
private static final Logger logger = Logger.getLogger("GoBackFtp"); // global logger
/**
* main
*/
public static void main(String[] args) {
// input file name is required
if (args.length == 0) {
System.out.println("incorrect usage, input file name is required");
System.out.println("try again");
System.exit(0);
}
// parse command line args
HashMap<String, String> params = parseCommandLine(args);
// set the parameters
// may through illegal argumenrt exception
// if inputs do not have proper format/type/value
String fileName = params.getOrDefault("-i", args[0]); // name of the file to be sent to the server
String serverName = params.getOrDefault("-s", "localhost"); // server name
int serverPort = Integer.parseInt( params.getOrDefault("-p", "2025") ); // server port number
int windowSize = Integer.parseInt( params.getOrDefault("-w", "10") ); // window size
int timeoutInterval = Integer.parseInt( params.getOrDefault("-t", "50") ); // duraiton of tim-out timer
Level logLevel = Level.parse( params.getOrDefault("-v", "all").toUpperCase() ); // log levels: all, info, off
// set log level
setLogLevel(logLevel);
try {
// send the file
GoBackFtp ftp = new GoBackFtp(windowSize, timeoutInterval);
System.out.printf("sending file \'%s\' to the server...\n", fileName);
ftp.send(serverName, serverPort, fileName);
System.out.println("send completed.");
} catch (FtpException e) {
System.out.println(e.getMessage());
}
}
// parse command line arguments
private static HashMap<String, String> parseCommandLine(String[] args) {
HashMap<String, String> params = new HashMap<String, String>();
int i = 0;
while ((i + 1) < args.length) {
params.put(args[i], args[i+1]);
i += 2;
}
return params;
}
// set the global log level and format
private static void setLogLevel(Level level) {
System.setProperty("java.util.logging.SimpleFormatter.format", "%5$s %n");
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(level);
logger.addHandler(handler);
logger.setLevel(level);
logger.setUseParentHandlers(false);
}
}
|
3e19d2040ea8bcddd4d18b42c5bf15ea6df9972f | 211 | java | Java | AsyncSockets/src/main/java/com/asyncsockets/DataEvent.java | Otaka/KOSBuild | 92ae30bc906867c329059865036a4e1621b25175 | [
"MIT"
] | null | null | null | AsyncSockets/src/main/java/com/asyncsockets/DataEvent.java | Otaka/KOSBuild | 92ae30bc906867c329059865036a4e1621b25175 | [
"MIT"
] | null | null | null | AsyncSockets/src/main/java/com/asyncsockets/DataEvent.java | Otaka/KOSBuild | 92ae30bc906867c329059865036a4e1621b25175 | [
"MIT"
] | null | null | null | 19.181818 | 95 | 0.763033 | 10,951 | package com.asyncsockets;
import java.io.IOException;
/**
* @author sad
*/
public abstract class DataEvent {
public abstract void dataArrived(SocketHandler socket, Request request) throws IOException;
}
|
3e19d314090a9c49990a99985444ebb3120001da | 10,130 | java | Java | app/src/main/java/com/erikboesen/arbolwp/activity/MainActivity.java | ErikBoesen/arbo_lwp | a28c2d8bd99eb9b8975e87f961768732842bfcf4 | [
"MIT"
] | null | null | null | app/src/main/java/com/erikboesen/arbolwp/activity/MainActivity.java | ErikBoesen/arbo_lwp | a28c2d8bd99eb9b8975e87f961768732842bfcf4 | [
"MIT"
] | null | null | null | app/src/main/java/com/erikboesen/arbolwp/activity/MainActivity.java | ErikBoesen/arbo_lwp | a28c2d8bd99eb9b8975e87f961768732842bfcf4 | [
"MIT"
] | null | null | null | 27.013333 | 97 | 0.712833 | 10,952 | package com.erikboesen.arbolwp.activity;
import com.erikboesen.arbolwp.app.ArboApp;
import com.erikboesen.arbolwp.database.Theme;
import com.erikboesen.arbolwp.graphics.BitmapLoader;
import com.erikboesen.arbolwp.widget.ThemesView;
import com.erikboesen.arbolwp.R;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import org.json.JSONException;
public class MainActivity extends AppCompatActivity {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static final int FULL_SCREEN_FLAGS =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
private static final int SELECT_LAST = -1;
private ThemesView themesView;
private MenuItem setThemeMenuItem;
private View mainLayout;
private View progressView;
private View decorView;
private boolean leanBack = false;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_main);
themesView = (ThemesView) findViewById(R.id.themes);
themesView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// devices with hardware buttons do not automatically
// leave lean back mode so show the system UI manually
// if it's hidden
if (!setSystemUiVisibility(leanBack)) {
PreviewActivity.show(v.getContext(),
ArboApp.db.getTheme(
themesView.getSelectedThemeId()));
}
}
});
final String title = getString(R.string.themes);
themesView.setOnChangeListener(new ThemesView.OnChangeListener() {
@Override
public void onChange(int index, long id) {
setTitle(String.format(title, index + 1,
themesView.getCount()));
updateThemeMenuItem(id);
}
});
mainLayout = findViewById(R.id.main_layout);
findViewById(R.id.edit_theme).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
EditorActivity.class);
intent.putExtra(EditorActivity.THEME_ID,
themesView.getSelectedThemeId());
startActivity(intent);
}
});
progressView = findViewById(R.id.progress_view);
initDecorView();
handleSendIntents(getIntent());
}
@Override
public void onResume() {
super.onResume();
queryThemesAsync();
}
@Override
public void onPause() {
super.onPause();
themesView.closeCursor();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
setThemeMenuItem = menu.findItem(R.id.set_theme);
updateThemeMenuItem();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
long id = themesView.getSelectedThemeId();
switch (item.getItemId()) {
case R.id.set_theme:
setAsWallpaper(id, item);
return true;
case R.id.add_theme:
addTheme();
return true;
case R.id.delete_theme:
askDeleteTheme(id);
return true;
case R.id.duplicate_theme:
duplicateTheme(id);
return true;
case R.id.share_theme:
shareTheme(id);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void queryThemesAsync() {
queryThemesAsync(themesView.getSelectedIndex());
}
// this AsyncTask is running for a short and finite time only
// and it's perfectly okay to delay garbage collection of the
// parent instance until this task has ended
@SuppressLint("StaticFieldLeak")
private void queryThemesAsync(final int index) {
if (progressView.getVisibility() == View.VISIBLE) {
return;
}
progressView.setVisibility(View.VISIBLE);
new AsyncTask<Void, Void, Cursor>() {
@Override
protected Cursor doInBackground(Void... nothings) {
return ArboApp.db.queryThemes();
}
@Override
protected void onPostExecute(Cursor cursor) {
if (isFinishing()) {
return;
}
progressView.setVisibility(View.GONE);
if (cursor != null) {
themesView.setThemes(cursor, index == SELECT_LAST ?
cursor.getCount() : index);
}
}
}.execute();
}
private void updateThemeMenuItem() {
updateThemeMenuItem(themesView.getSelectedThemeId());
}
private void updateThemeMenuItem(long id) {
if (setThemeMenuItem != null) {
setThemeMenuItem.setIcon(
ArboApp.preferences.getTheme() == id ?
R.drawable.ic_wallpaper_set :
R.drawable.ic_wallpaper_unset);
}
}
private void addTheme() {
addTheme(new Theme());
}
private void duplicateTheme(long id) {
addTheme(ArboApp.db.getTheme(id));
}
private void addTheme(Theme theme) {
ArboApp.db.insertTheme(theme);
queryThemesAsync(SELECT_LAST);
}
private void shareTheme(long id) {
Intent intent = new Intent();
intent.setType("application/json");
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,
ArboApp.db.getTheme(id).toJson());
startActivity(Intent.createChooser(intent,
getString(R.string.share_theme)));
}
private void askDeleteTheme(final long id) {
new AlertDialog.Builder(this)
.setTitle(R.string.delete_theme)
.setMessage(R.string.sure_to_delete_theme)
.setPositiveButton(
android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int whichButton) {
deleteTheme(id);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void deleteTheme(long id) {
if (themesView.getCount() < 2) {
return;
}
ArboApp.db.deleteTheme(id);
queryThemesAsync();
if (ArboApp.preferences.getTheme() == id) {
ArboApp.preferences.setTheme(
ArboApp.db.getFirstThemeId());
updateThemeMenuItem();
}
}
private void setAsWallpaper(long id, MenuItem item) {
ArboApp.preferences.setTheme(id);
item.setIcon(R.drawable.ic_wallpaper_set);
Toast.makeText(this, R.string.set_as_wallpaper,
Toast.LENGTH_SHORT).show();
}
private void handleSendIntents(Intent intent) {
if (!Intent.ACTION_SEND.equals(intent.getAction())) {
return;
}
String type = intent.getType();
if (type == null) {
return;
} else if (type.startsWith("image/")) {
addThemeFromImageUriAsync(this,
(Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
} else if ("application/json".equals(type)) {
String json = intent.getStringExtra(Intent.EXTRA_TEXT);
try {
addTheme(Theme.clamp(new Theme(json)));
} catch (JSONException e) {
Toast.makeText(this, R.string.error_invalid_json,
Toast.LENGTH_SHORT).show();
}
}
}
// this AsyncTask is running for a short and finite time only
// and it's perfectly okay to delay garbage collection of the
// parent instance until this task has ended
@SuppressLint("StaticFieldLeak")
private void addThemeFromImageUriAsync(final Context context,
final Uri uri) {
if (uri == null || progressView.getVisibility() == View.VISIBLE) {
return;
}
progressView.setVisibility(View.VISIBLE);
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... nothings) {
return BitmapLoader.getBitmapFromUri(context, uri, 512);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
progressView.setVisibility(View.GONE);
if (bitmap == null) {
return;
}
addThemeFromBitmap(bitmap);
}
}.execute();
}
private void addThemeFromBitmap(Bitmap bitmap) {
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette p) {
int defaultColor = 0xff000000;
addThemeWithColors(new int[]{
p.getLightVibrantColor(
p.getLightMutedColor(defaultColor)),
p.getVibrantColor(
p.getMutedColor(defaultColor)),
p.getDarkVibrantColor(
p.getDarkMutedColor(defaultColor))
});
}
});
}
private void addThemeWithColors(int[] colors) {
addTheme(new Theme(
Math.random() > .5f,
Math.random() > .5f,
Math.random() > .5f,
colors.length,
1 + (int) Math.round(Math.random() * 5),
.02f + Math.round(Math.random() * .13f),
.5f + Math.round(Math.random() * 1.5f),
0,
colors
));
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initDecorView() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return;
}
decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(FULL_SCREEN_FLAGS);
setToolBarVisibility(true);
mainLayout.setVisibility(View.VISIBLE);
leanBack = false;
} else {
setToolBarVisibility(false);
mainLayout.setVisibility(View.INVISIBLE);
leanBack = true;
}
}
});
decorView.setSystemUiVisibility(FULL_SCREEN_FLAGS);
}
private void setToolBarVisibility(boolean visible) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
if (visible) {
actionBar.show();
} else {
actionBar.hide();
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean setSystemUiVisibility(boolean visible) {
if (decorView == null ||
Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return false;
}
int flags = FULL_SCREEN_FLAGS;
if (!visible) {
flags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN;
}
decorView.setSystemUiVisibility(flags);
return true;
}
}
|
3e19d3851a839840efe3403ad53be081c4629b7f | 9,742 | java | Java | MojiList/build/generated/source/r/debug/android/support/v4/R.java | priyankaharmale/EmojiApp | f126a2cf58addccc379bd278dde4eeb39e46990e | [
"Apache-2.0"
] | null | null | null | MojiList/build/generated/source/r/debug/android/support/v4/R.java | priyankaharmale/EmojiApp | f126a2cf58addccc379bd278dde4eeb39e46990e | [
"Apache-2.0"
] | null | null | null | MojiList/build/generated/source/r/debug/android/support/v4/R.java | priyankaharmale/EmojiApp | f126a2cf58addccc379bd278dde4eeb39e46990e | [
"Apache-2.0"
] | null | null | null | 62.050955 | 126 | 0.754363 | 10,953 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.v4;
public final class R {
public static final class attr {
public static final int font = 0x7f0300a5;
public static final int fontProviderAuthority = 0x7f0300a7;
public static final int fontProviderCerts = 0x7f0300a8;
public static final int fontProviderFetchStrategy = 0x7f0300a9;
public static final int fontProviderFetchTimeout = 0x7f0300aa;
public static final int fontProviderPackage = 0x7f0300ab;
public static final int fontProviderQuery = 0x7f0300ac;
public static final int fontStyle = 0x7f0300ad;
public static final int fontWeight = 0x7f0300ae;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f040000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f05005f;
public static final int notification_icon_bg_color = 0x7f050060;
public static final int notification_material_background_media_default_color = 0x7f050061;
public static final int primary_text_default_material_dark = 0x7f050066;
public static final int ripple_material_light = 0x7f05006b;
public static final int secondary_text_default_material_dark = 0x7f05006c;
public static final int secondary_text_default_material_light = 0x7f05006d;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f06004e;
public static final int compat_button_inset_vertical_material = 0x7f06004f;
public static final int compat_button_padding_horizontal_material = 0x7f060050;
public static final int compat_button_padding_vertical_material = 0x7f060051;
public static final int compat_control_corner_material = 0x7f060052;
public static final int notification_action_icon_size = 0x7f060094;
public static final int notification_action_text_size = 0x7f060095;
public static final int notification_big_circle_margin = 0x7f060096;
public static final int notification_content_margin_start = 0x7f060097;
public static final int notification_large_icon_height = 0x7f060098;
public static final int notification_large_icon_width = 0x7f060099;
public static final int notification_main_column_padding_top = 0x7f06009a;
public static final int notification_media_narrow_margin = 0x7f06009b;
public static final int notification_right_icon_size = 0x7f06009c;
public static final int notification_right_side_padding_top = 0x7f06009d;
public static final int notification_small_icon_background_padding = 0x7f06009e;
public static final int notification_small_icon_size_as_large = 0x7f06009f;
public static final int notification_subtext_size = 0x7f0600a0;
public static final int notification_top_pad = 0x7f0600a1;
public static final int notification_top_pad_large_text = 0x7f0600a2;
}
public static final class drawable {
public static final int notification_action_background = 0x7f0700a4;
public static final int notification_bg = 0x7f0700a5;
public static final int notification_bg_low = 0x7f0700a6;
public static final int notification_bg_low_normal = 0x7f0700a7;
public static final int notification_bg_low_pressed = 0x7f0700a8;
public static final int notification_bg_normal = 0x7f0700a9;
public static final int notification_bg_normal_pressed = 0x7f0700aa;
public static final int notification_icon_background = 0x7f0700ab;
public static final int notification_template_icon_bg = 0x7f0700ac;
public static final int notification_template_icon_low_bg = 0x7f0700ad;
public static final int notification_tile_bg = 0x7f0700ae;
public static final int notify_panel_notification_icon_bg = 0x7f0700af;
}
public static final class id {
public static final int action0 = 0x7f080036;
public static final int action_container = 0x7f080040;
public static final int action_divider = 0x7f080043;
public static final int action_image = 0x7f080045;
public static final int action_text = 0x7f080050;
public static final int actions = 0x7f080052;
public static final int async = 0x7f080059;
public static final int blocking = 0x7f08005c;
public static final int cancel_action = 0x7f080069;
public static final int chronometer = 0x7f08006e;
public static final int end_padder = 0x7f080083;
public static final int forever = 0x7f08008d;
public static final int icon = 0x7f080097;
public static final int icon_group = 0x7f080098;
public static final int info = 0x7f08009e;
public static final int italic = 0x7f08009f;
public static final int line1 = 0x7f0800be;
public static final int line3 = 0x7f0800bf;
public static final int media_actions = 0x7f0800c6;
public static final int normal = 0x7f0800d1;
public static final int notification_background = 0x7f0800d2;
public static final int notification_main_column = 0x7f0800d3;
public static final int notification_main_column_container = 0x7f0800d4;
public static final int right_icon = 0x7f0800e7;
public static final int right_side = 0x7f0800e8;
public static final int status_bar_latest_event_content = 0x7f080113;
public static final int tag_transition_group = 0x7f080119;
public static final int text = 0x7f08011a;
public static final int text2 = 0x7f08011b;
public static final int time = 0x7f080123;
public static final int title = 0x7f080124;
}
public static final class integer {
public static final int cancel_button_image_alpha = 0x7f09000a;
public static final int status_bar_notification_info_maxnum = 0x7f090014;
}
public static final class layout {
public static final int notification_action = 0x7f0a0061;
public static final int notification_action_tombstone = 0x7f0a0062;
public static final int notification_media_action = 0x7f0a0063;
public static final int notification_media_cancel_action = 0x7f0a0064;
public static final int notification_template_big_media = 0x7f0a0065;
public static final int notification_template_big_media_custom = 0x7f0a0066;
public static final int notification_template_big_media_narrow = 0x7f0a0067;
public static final int notification_template_big_media_narrow_custom = 0x7f0a0068;
public static final int notification_template_custom_big = 0x7f0a0069;
public static final int notification_template_icon_group = 0x7f0a006a;
public static final int notification_template_lines_media = 0x7f0a006b;
public static final int notification_template_media = 0x7f0a006c;
public static final int notification_template_media_custom = 0x7f0a006d;
public static final int notification_template_part_chronometer = 0x7f0a006e;
public static final int notification_template_part_time = 0x7f0a006f;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0d0060;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0e0108;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0e0109;
public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0e010a;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0e010b;
public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0e010c;
public static final int TextAppearance_Compat_Notification_Media = 0x7f0e010d;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0e010e;
public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0e010f;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0e0110;
public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0e0111;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0e0187;
public static final int Widget_Compat_NotificationActionText = 0x7f0e0188;
}
public static final class styleable {
public static final int[] FontFamily = { 0x7f0300a7, 0x7f0300a8, 0x7f0300a9, 0x7f0300aa, 0x7f0300ab, 0x7f0300ac };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f0300a5, 0x7f0300ad, 0x7f0300ae };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
}
}
|
3e19d3a054228b11405c96cb9278cf9161563855 | 59 | java | Java | src/se/lexicon/model/Flight1.java | sohrabag/FlightBase | 4654d8e3f14b07bb65626e643b34ca289bb783f5 | [
"MIT"
] | null | null | null | src/se/lexicon/model/Flight1.java | sohrabag/FlightBase | 4654d8e3f14b07bb65626e643b34ca289bb783f5 | [
"MIT"
] | null | null | null | src/se/lexicon/model/Flight1.java | sohrabag/FlightBase | 4654d8e3f14b07bb65626e643b34ca289bb783f5 | [
"MIT"
] | null | null | null | 8.428571 | 26 | 0.728814 | 10,954 | package se.lexicon.model;
public interface Flight1 {
}
|
3e19d3ce490d338d74ba36a3186a0d9f5891b6a7 | 528 | java | Java | amzKit/src/main/java/amz/kit/service/impl/DefaultSchedulerAssigner.java | AmzDevelopmentTeam/amzkit4j | 36be70d6ec56362ae04eaa8a49fa87dc9ab22c19 | [
"Apache-2.0"
] | null | null | null | amzKit/src/main/java/amz/kit/service/impl/DefaultSchedulerAssigner.java | AmzDevelopmentTeam/amzkit4j | 36be70d6ec56362ae04eaa8a49fa87dc9ab22c19 | [
"Apache-2.0"
] | null | null | null | amzKit/src/main/java/amz/kit/service/impl/DefaultSchedulerAssigner.java | AmzDevelopmentTeam/amzkit4j | 36be70d6ec56362ae04eaa8a49fa87dc9ab22c19 | [
"Apache-2.0"
] | 1 | 2021-08-06T20:47:20.000Z | 2021-08-06T20:47:20.000Z | 27.789474 | 74 | 0.74053 | 10,955 | package amz.kit.service.impl;
import amz.kit.util.SchedulerAssigner;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
public final class DefaultSchedulerAssigner implements SchedulerAssigner {
@Override
public <T> Single<T> assignSchedulers(Single<T> source) {
return source.subscribeOn(Schedulers.io());
}
@Override
public <T> Observable<T> assignSchedulers(Observable<T> source) {
return source.subscribeOn(Schedulers.io());
}
}
|
3e19d42bf8fde2c45c8e5021ecaabd76416b5fed | 3,921 | java | Java | protege-editor-core/src/main/java/org/protege/editor/core/ui/view/ViewComponentPluginJPFImpl.java | Rena-Yang-cell/protege | 093b336088e323afea9108eb7361dbcf4d8384c0 | [
"BSD-2-Clause"
] | 746 | 2015-01-09T14:51:00.000Z | 2022-03-30T06:33:55.000Z | protege-editor-core/src/main/java/org/protege/editor/core/ui/view/ViewComponentPluginJPFImpl.java | Rena-Yang-cell/protege | 093b336088e323afea9108eb7361dbcf4d8384c0 | [
"BSD-2-Clause"
] | 941 | 2015-01-06T16:02:28.000Z | 2022-03-28T09:58:34.000Z | protege-editor-core/src/main/java/org/protege/editor/core/ui/view/ViewComponentPluginJPFImpl.java | Rena-Yang-cell/protege | 093b336088e323afea9108eb7361dbcf4d8384c0 | [
"BSD-2-Clause"
] | 213 | 2015-01-10T17:56:43.000Z | 2022-03-23T15:03:06.000Z | 27.87234 | 118 | 0.696438 | 10,956 | package org.protege.editor.core.ui.view;
import org.eclipse.core.runtime.IExtension;
import org.protege.editor.core.PropertyUtil;
import org.protege.editor.core.plugin.ExtensionInstantiator;
import org.protege.editor.core.plugin.JPFUtil;
import org.protege.editor.core.plugin.PluginProperties;
import org.protege.editor.core.ui.workspace.Workspace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.awt.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import java.util.Set;
/*
* Copyright (C) 2007, University of Manchester
*
*
*/
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Medical Informatics Group<br>
* Date: Mar 29, 2006<br><br>
* dycjh@example.com.uk<br>
* www.cs.man.ac.uk/~horridgm<br><br>
*/
public class ViewComponentPluginJPFImpl implements ViewComponentPlugin {
private static final Logger logger = LoggerFactory.getLogger(ViewComponentPluginJPFImpl.class);
public static final String ID = "ViewComponent";
public static final String LABEL_PARAM = "label";
public static final String LOCATION_PARAM = "location";
public static final String WORKSPACE_TAB_ID_PARAM = "workspaceTabId";
public static final String HEADER_COLOR_PARAM = "headerColor";
public static final String USER_CREATABLE_PARAM = "userCreatable";
public static final String CATEGORY = "category";
public static final String NAVIGATES = "navigates";
private IExtension extension;
private Workspace workspace;
private static final Color DEFAULT_COLOR = Color.LIGHT_GRAY;
public ViewComponentPluginJPFImpl(Workspace workspace, IExtension extension) {
this.extension = extension;
this.workspace = workspace;
}
public String getId() {
return extension.getUniqueIdentifier();
}
public Workspace getWorkspace() {
return workspace;
}
public String getDocumentation() {
return JPFUtil.getDocumentation(extension);
}
public String getLabel() {
return PluginProperties.getParameterValue(extension, LABEL_PARAM, "<Error! No label defined>");
}
public boolean isUserCreatable() {
return PluginProperties.getBooleanParameterValue(extension, USER_CREATABLE_PARAM, true);
}
public Color getBackgroundColor() {
String val = PluginProperties.getParameterValue(extension, HEADER_COLOR_PARAM, null);
if (val != null) {
return PropertyUtil.getColor(val, DEFAULT_COLOR);
}
return DEFAULT_COLOR;
}
public Set<String> getCategorisations() {
return PluginProperties.getParameterValues(extension, CATEGORY);
}
public Set<String> getNavigates() {
return PluginProperties.getParameterValues(extension, NAVIGATES);
}
@Nonnull
@Override
public Optional<URI> getHelpLink() {
return Optional.ofNullable(
PluginProperties.getParameterValue(extension, "help", null)
).flatMap(u -> {
try {
return Optional.of(new URI(u));
} catch (URISyntaxException e) {
logger.warn("Malformed help URL ({}): {}", u, e.getMessage());
return Optional.empty();
}
});
}
/**
* Creates an instance of the plugin. It is expected that
* this instance will be "setup", but the instance's
* initialise method will not have been called in the instantiation
* process.
*/
public ViewComponent newInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
ExtensionInstantiator<ViewComponent> instantiator = new ExtensionInstantiator<>(extension);
ViewComponent viewComponent = instantiator.instantiate();
viewComponent.setup(this);
return viewComponent;
}
}
|
3e19d54efc324eef305c14475d383dcb25b9d994 | 463 | java | Java | spring-boot-caching/src/main/java/no/njm/spring/cache/Application.java | njmittet/spring-examples | 39bfa463c10c3fe0568b28788512a2fd1ec30d70 | [
"MIT"
] | null | null | null | spring-boot-caching/src/main/java/no/njm/spring/cache/Application.java | njmittet/spring-examples | 39bfa463c10c3fe0568b28788512a2fd1ec30d70 | [
"MIT"
] | null | null | null | spring-boot-caching/src/main/java/no/njm/spring/cache/Application.java | njmittet/spring-examples | 39bfa463c10c3fe0568b28788512a2fd1ec30d70 | [
"MIT"
] | null | null | null | 28.9375 | 68 | 0.820734 | 10,957 | package no.njm.spring.cache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
} |
3e19d60c105bfdfd42c6d9cf7c6a3d197cd3afeb | 1,567 | java | Java | repository/postgres/src/main/java/com/expediagroup/streamplatform/streamregistry/repository/postgres/data/keys/ProducerDataKey.java | sullis/stream-registry | 15b61c5f96baf3381a94a974da2402da7b5af87f | [
"Apache-2.0"
] | null | null | null | repository/postgres/src/main/java/com/expediagroup/streamplatform/streamregistry/repository/postgres/data/keys/ProducerDataKey.java | sullis/stream-registry | 15b61c5f96baf3381a94a974da2402da7b5af87f | [
"Apache-2.0"
] | null | null | null | repository/postgres/src/main/java/com/expediagroup/streamplatform/streamregistry/repository/postgres/data/keys/ProducerDataKey.java | sullis/stream-registry | 15b61c5f96baf3381a94a974da2402da7b5af87f | [
"Apache-2.0"
] | null | null | null | 27.982143 | 85 | 0.763242 | 10,958 | /**
* Copyright (C) 2018-2020 Expedia, 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.expediagroup.streamplatform.streamregistry.repository.postgres.data.keys;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Embeddable
public class ProducerDataKey implements Serializable {
@Column(length = 100)
private String streamDomain;
@Column(length = 100)
private String streamName;
@Column(length = 100)
private Integer streamVersion;
@Column(length = 100)
private String zone;
@Column(length = 100)
private String name;
public StreamDataKey getStreamDataKey() {
return new StreamDataKey(streamDomain, streamName, streamVersion);
}
public InfrastructureDataKey getInfrastructureDataKey() {
return new InfrastructureDataKey(zone, name);
}
public ZoneDataKey getZoneDataKey() {
return new ZoneDataKey(zone);
}
}
|
3e19d64a4119d4fe3a48324a1c78715440da4ed3 | 2,273 | java | Java | src/main/java/br/com/pedront/hackerrank/crackingthecodinginterview/hashtables/RansomNote.java | pedront/hackerrank | f5be16a635f2f522351f34e595eca7d0dfce0b6d | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/pedront/hackerrank/crackingthecodinginterview/hashtables/RansomNote.java | pedront/hackerrank | f5be16a635f2f522351f34e595eca7d0dfce0b6d | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/pedront/hackerrank/crackingthecodinginterview/hashtables/RansomNote.java | pedront/hackerrank | f5be16a635f2f522351f34e595eca7d0dfce0b6d | [
"Apache-2.0"
] | null | null | null | 30.716216 | 98 | 0.524417 | 10,959 | package br.com.pedront.hackerrank.crackingthecodinginterview.hashtables;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Scanner;
/**
* @author pnakano
* @version $Revision: $<br/>
* $Id: $
* @since 02/01/18 13:45
*/
public class RansomNote {
public static void solve(String[] magazine, String[] ransom) {
HashMap<String, Integer> magazineSet = new HashMap<>();
for (String magazineWord : magazine) {
Integer count = magazineSet.get(magazineWord);
if (count == null) {
count = 0;
}
count++;
magazineSet.put(magazineWord, count);
}
for (String ransomWord : ransom) {
Integer count = magazineSet.get(ransomWord);
if (count == null || count == 0) {
System.out.println("No");
return;
} else {
count--;
magazineSet.put(ransomWord, count);
}
}
System.out.println("Yes");
}
public static void main(String[] args) throws IOException {
try (InputStream inStream = new FileInputStream(
new File("src/main/resources/br/com/pedront/hackerrank/crackingthecodinginterview"
+ "/hashtables/TestCase13"))) {
Scanner in = new Scanner(inStream);
int m = in.nextInt();
int n = in.nextInt();
String magazine[] = new String[m];
for (int magazine_i = 0; magazine_i < m; magazine_i++) {
magazine[magazine_i] = in.next();
}
String ransom[] = new String[n];
for (int ransom_i = 0; ransom_i < n; ransom_i++) {
ransom[ransom_i] = in.next();
}
solve(magazine, ransom);
}
// String magazine[] = { "give", "me", "one", "grand", "today", "night" };
// String ransom[] = { "give", "one", "grand", "today" };
// String magazine[] = { "two", "times", "three", "is", "not", "four" };
// String ransom[] = { "two", "times", "two", "is", "four" };
// solve(magazine, ransom);
}
}
|
3e19d722c9f7bbb5be2d3202e843e574095643cb | 964 | java | Java | amico_im_service/amico_im_service_netty/src/main/java/com/amico/service/im/net/req/dto/map/IMReqModelMap.java | 13802410684/IM_AMICO_SERVICE | 8abe99b5d17727565dad5b4fa687f6f38a651fb5 | [
"Apache-2.0"
] | null | null | null | amico_im_service/amico_im_service_netty/src/main/java/com/amico/service/im/net/req/dto/map/IMReqModelMap.java | 13802410684/IM_AMICO_SERVICE | 8abe99b5d17727565dad5b4fa687f6f38a651fb5 | [
"Apache-2.0"
] | null | null | null | amico_im_service/amico_im_service_netty/src/main/java/com/amico/service/im/net/req/dto/map/IMReqModelMap.java | 13802410684/IM_AMICO_SERVICE | 8abe99b5d17727565dad5b4fa687f6f38a651fb5 | [
"Apache-2.0"
] | null | null | null | 27.542857 | 90 | 0.761411 | 10,960 | package com.amico.service.im.net.req.dto.map;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.amico.service.im.net.req.dto.AddFriendDto;
import com.amico.service.im.net.req.dto.GroupChatDto;
import com.amico.service.im.net.req.dto.GuestChatDto;
import com.amico.service.im.net.req.dto.LoginDto;
import com.amico.service.im.net.req.dto.SingleChatDto;
import io.jboot.utils.StrUtils;
public class IMReqModelMap {
private static final Map<String, Class> dictMap = new ConcurrentHashMap<String, Class>();
static {
dictMap.put("AddFriendDto", AddFriendDto.class);
dictMap.put("GroupChatDto", GroupChatDto.class);
dictMap.put("GuestChatDto", GuestChatDto.class);
dictMap.put("SingleChatDto", SingleChatDto.class);
dictMap.put("LoginDto", LoginDto.class);
}
public static Class getClassByName(String clsName) {
if (StrUtils.isNotEmpty(clsName)) {
return dictMap.get(clsName);
} else {
return null;
}
}
}
|
3e19d8366f72528202d23f50f331212dfc7efc8f | 727 | java | Java | resume-online-frontend/resume-online-jfx-core/src/main/java/resumeonline/jfx/core/FileChooserProvider.java | jbrasileiro/resume-online | 4cdd3a2d27182d7dd6fa1263ddb3dafffc00afba | [
"Apache-2.0"
] | null | null | null | resume-online-frontend/resume-online-jfx-core/src/main/java/resumeonline/jfx/core/FileChooserProvider.java | jbrasileiro/resume-online | 4cdd3a2d27182d7dd6fa1263ddb3dafffc00afba | [
"Apache-2.0"
] | 2 | 2019-05-30T21:52:48.000Z | 2022-01-21T23:10:36.000Z | resume-online-frontend/resume-online-jfx-core/src/main/java/resumeonline/jfx/core/FileChooserProvider.java | jbrasileiro/resume-online | 4cdd3a2d27182d7dd6fa1263ddb3dafffc00afba | [
"Apache-2.0"
] | null | null | null | 30.291667 | 78 | 0.711142 | 10,961 | package resumeonline.jfx.core;
import javafx.stage.FileChooser;
import resumeonline.commons.exeception.NoNewInstanceAllowed;
import resumeonline.commons.io.file.Directory;
public final class FileChooserProvider {
private FileChooserProvider() {
super();
throw new NoNewInstanceAllowed(getClass());
}
public static FileChooser create(
final Directory directory) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter
= new FileChooser.ExtensionFilter("Arquivo PDF (*.pdf)", "*.pdf");
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.setInitialDirectory(directory);
return fileChooser;
}
}
|
3e19d8999c1921edbfcbbe49943baef4a2faa16a | 2,097 | java | Java | src/main/java/nu/nerd/df/DragonFight.java | kadenscott/DragonFight | 7cc69f340b367ba748167815f8da4aa121a2c480 | [
"MIT"
] | 1 | 2022-03-08T07:53:38.000Z | 2022-03-08T07:53:38.000Z | src/main/java/nu/nerd/df/DragonFight.java | kadenscott/DragonFight | 7cc69f340b367ba748167815f8da4aa121a2c480 | [
"MIT"
] | 4 | 2020-12-11T06:19:57.000Z | 2021-09-24T06:53:30.000Z | src/main/java/nu/nerd/df/DragonFight.java | kadenscott/DragonFight | 7cc69f340b367ba748167815f8da4aa121a2c480 | [
"MIT"
] | 6 | 2021-08-04T03:15:53.000Z | 2021-09-06T04:57:57.000Z | 29.125 | 79 | 0.531235 | 10,962 | package nu.nerd.df;
import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
import nu.nerd.beastmaster.commands.ExecutorBase;
import nu.nerd.df.commands.DFExecutor;
import nu.nerd.df.commands.DragonExecutor;
import nu.nerd.df.commands.DragonFightExecutor;
// ----------------------------------------------------------------------------
/**
* Main plugin class.
*/
public class DragonFight extends JavaPlugin {
// ------------------------------------------------------------------------
/**
* The plugin as a singleton.
*/
public static DragonFight PLUGIN;
/**
* Configuration as singleton.
*/
public static Configuration CONFIG = new Configuration();
/**
* Current fight as singleton.
*/
public static FightState FIGHT = new FightState();
// ------------------------------------------------------------------------
/**
* @see org.bukkit.plugin.java.JavaPlugin#onEnable()
*/
@Override
public void onEnable() {
PLUGIN = this;
saveDefaultConfig();
CONFIG.reload();
addCommandExecutor(new DFExecutor());
addCommandExecutor(new DragonExecutor());
addCommandExecutor(new DragonFightExecutor());
Bukkit.getPluginManager().registerEvents(FIGHT, this);
FIGHT.onEnable();
}
// ------------------------------------------------------------------------
/**
* @see org.bukkit.plugin.java.JavaPlugin#onDisable()
*/
@Override
public void onDisable() {
FIGHT.onDisable();
CONFIG.save();
}
// ------------------------------------------------------------------------
/**
* Add the specified CommandExecutor and set it as its own TabCompleter.
*
* @param executor the CommandExecutor.
*/
protected void addCommandExecutor(ExecutorBase executor) {
PluginCommand command = getCommand(executor.getName());
command.setExecutor(executor);
command.setTabCompleter(executor);
}
} // class DragonFight |
3e19d90efafd071182137e8a4905eb6ce914f9e5 | 2,138 | java | Java | Setembro/3-9-2019/SistemaDeLogin/src/dao/UsuarioDAO.java | jjeanjacques10/AulasPOO-FIAP | 47713ebebf0b78a30da18648fe488108dc7bd757 | [
"MIT"
] | 1 | 2020-03-31T12:51:34.000Z | 2020-03-31T12:51:34.000Z | Setembro/3-9-2019/SistemaDeLogin/src/dao/UsuarioDAO.java | jjeanjacques10/FIAP-aulas-POO | 47713ebebf0b78a30da18648fe488108dc7bd757 | [
"MIT"
] | null | null | null | Setembro/3-9-2019/SistemaDeLogin/src/dao/UsuarioDAO.java | jjeanjacques10/FIAP-aulas-POO | 47713ebebf0b78a30da18648fe488108dc7bd757 | [
"MIT"
] | null | null | null | 22.270833 | 90 | 0.669785 | 10,963 | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import connection.Conexao;
import model.Usuario;
public class UsuarioDAO {
private Connection connection;
private String sql;
private PreparedStatement ps;
private ResultSet rs;
public UsuarioDAO() {
connection = Conexao.getConnection();
}
public ArrayList<Usuario> listar() {
ArrayList<Usuario> lista = new ArrayList<Usuario>();
sql = "SELECT * FROM JAVA_USUARIO";
try {
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
lista.add(new Usuario(rs.getInt("ID"), rs.getString("EMAIL"), rs.getString("SENHA")));
}
} catch (SQLException e) {
System.out.println("Erro ao selecionar os valores\n" + e);
}
return lista;
}
public String inserir(Usuario usuario) {
sql = "INSERT INTO JAVA_USUARIO values(?, ?, ?)";
try {
ps = connection.prepareStatement(sql);
ps.setInt(1, usuario.getId());
ps.setString(2, usuario.getEmail());
ps.setString(3, usuario.getSenha());
ps.execute();
} catch (SQLException e) {
System.out.println("Erro ao inserir no banco\n" + e);
e.printStackTrace();
}
return "Usuario Cadastrado";
}
public boolean verificarRm(int id) {
if (pesquisa(id)) {
return true;
} else {
return false;
}
}
public boolean pesquisa(int id) {
boolean retorno = false;
sql = "select * from JAVA_USUARIO WHERE ID = ?";
try {
ps = connection.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
retorno = rs.next();
} catch (SQLException e) {
System.out.println("Erro ao pesquisar no banco\n" + e);
e.printStackTrace();
}
return retorno;
}
public boolean logar(String email, String senha) {
boolean retorno = false;
ArrayList<Usuario> lista = new ArrayList<Usuario>();
lista = listar();
for (Usuario usuario : lista) {
if (usuario.getEmail().equals(email) && usuario.getSenha().equals(senha)) {
retorno = true;
}
}
return retorno;
}
}
|
3e19d97c3735349e1a7880701dc99b4e0b0127a2 | 1,274 | java | Java | src/openjava/ptree/CastExpression.java | Abhiroopks/MuJava-Project | beb55bb18ef80de55c301878e9fe3830dfbfb886 | [
"Apache-2.0"
] | null | null | null | src/openjava/ptree/CastExpression.java | Abhiroopks/MuJava-Project | beb55bb18ef80de55c301878e9fe3830dfbfb886 | [
"Apache-2.0"
] | null | null | null | src/openjava/ptree/CastExpression.java | Abhiroopks/MuJava-Project | beb55bb18ef80de55c301878e9fe3830dfbfb886 | [
"Apache-2.0"
] | null | null | null | 25.48 | 104 | 0.681319 | 10,964 | //
// Decompiled by Procyon v0.5.36
//
package openjava.ptree;
import openjava.mop.Environment;
import openjava.ptree.util.ParseTreeVisitor;
import openjava.mop.OJClass;
public class CastExpression extends NonLeaf implements Expression
{
public CastExpression(final TypeName p2, final Expression p3) {
this.set(p2, p3);
}
public CastExpression(final OJClass ojClass, final Expression expression) {
this(TypeName.forOJClass(ojClass), expression);
}
CastExpression() {
}
public TypeName getTypeSpecifier() {
return (TypeName)this.elementAt(0);
}
public void setTypeSpecifier(final TypeName p) {
this.setElementAt(p, 0);
}
public Expression getExpression() {
return (Expression)this.elementAt(1);
}
public void setExpression(final Expression p) {
this.setElementAt(p, 1);
}
@Override
public void accept(final ParseTreeVisitor parseTreeVisitor) throws ParseTreeException {
parseTreeVisitor.visit(this);
}
@Override
public OJClass getType(final Environment environment) throws Exception {
return environment.lookupClass(environment.toQualifiedName(this.getTypeSpecifier().toString()));
}
}
|
3e19d98430bb827675c91a8b071575ba840db4a4 | 408 | java | Java | src/main/java/seedu/address/model/moduleclass/exceptions/DuplicateModuleClassException.java | czhi-bin/tp | 493426c2ea4ec55b3302a3bf7e013173b5f96920 | [
"MIT"
] | null | null | null | src/main/java/seedu/address/model/moduleclass/exceptions/DuplicateModuleClassException.java | czhi-bin/tp | 493426c2ea4ec55b3302a3bf7e013173b5f96920 | [
"MIT"
] | 3 | 2021-10-06T06:28:53.000Z | 2021-10-06T10:56:58.000Z | src/main/java/seedu/address/model/moduleclass/exceptions/DuplicateModuleClassException.java | czhi-bin/tp | 493426c2ea4ec55b3302a3bf7e013173b5f96920 | [
"MIT"
] | null | null | null | 34 | 116 | 0.740196 | 10,965 | package seedu.address.model.moduleclass.exceptions;
public class DuplicateModuleClassException extends RuntimeException {
/**
* Signals that the operation will result in duplicate module classes (Classes are considered duplicates if they
* have the same identity).
*/
public DuplicateModuleClassException() {
super("Operation would result in duplicate module class");
}
}
|
3e19d9cb1e6fd2de0492045726d57d61b92ef5e6 | 8,015 | java | Java | app/src/main/java/xyz/qn0x/copypasta/ui/activities/ViewSnippetActivity.java | hafizahmmed/copypasta | cab0f0dd1b64136aa105492aa9acfb7b71ff4b9f | [
"MIT"
] | 1 | 2020-08-15T07:49:43.000Z | 2020-08-15T07:49:43.000Z | app/src/main/java/xyz/qn0x/copypasta/ui/activities/ViewSnippetActivity.java | hafizahmmed/copypasta | cab0f0dd1b64136aa105492aa9acfb7b71ff4b9f | [
"MIT"
] | 7 | 2018-03-18T14:48:55.000Z | 2018-06-09T19:41:22.000Z | app/src/main/java/xyz/qn0x/copypasta/ui/activities/ViewSnippetActivity.java | hafizahmmed/copypasta | cab0f0dd1b64136aa105492aa9acfb7b71ff4b9f | [
"MIT"
] | 1 | 2018-06-09T17:06:36.000Z | 2018-06-09T17:06:36.000Z | 34.106383 | 100 | 0.597629 | 10,966 | package xyz.qn0x.copypasta.ui.activities;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import xyz.qn0x.copypasta.R;
import xyz.qn0x.copypasta.SnippetViewModel;
import xyz.qn0x.copypasta.persistence.entities.SnippetTags;
import xyz.qn0x.copypasta.persistence.entities.Tag;
public class ViewSnippetActivity extends AppCompatActivity {
private static final String TAG = "ViewSnippetActivity";
private boolean favorite = false;
private long snippetId;
private Menu appBarMenu;
private String oldName;
private String oldText;
private String oldTags;
EditText vName;
EditText vTags;
EditText vText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_snippet);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
if (ab != null)
ab.setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
snippetId = intent.getLongExtra("ID", 1);
vName = findViewById(R.id.view_name);
vName.setEnabled(false);
oldName = intent.getStringExtra("NAME");
vName.setText(oldName);
vTags = findViewById(R.id.view_tags);
vTags.setEnabled(false);
oldTags = intent.getStringExtra("TAGS");
vTags.setText(oldTags);
vText = findViewById(R.id.view_text);
vText.setEnabled(false);
oldText = intent.getStringExtra("TEXT");
vText.setText(oldText);
favorite = intent.getBooleanExtra("FAV", false);
Log.d(TAG, "Selected Snippet. ID: " + intent.getLongExtra("ID", 1) + " FAV: "
+ intent.getBooleanExtra("FAV", false));
}
// draw app bar options
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_view_snippet, menu);
updateActionBarFavorite();
appBarMenu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SnippetViewModel snippetViewModel = ViewModelProviders.of(this).get(SnippetViewModel.class);
switch (item.getItemId()) {
case R.id.action_view_fav:
snippetViewModel.updateFavoriteStatus(snippetId, !favorite);
favorite = !favorite;
updateActionBarFavorite();
return true;
case R.id.action_edit:
Log.v(TAG, "edit clicked");
vName.setEnabled(true);
vTags.setEnabled(true);
vText.setEnabled(true);
MenuItem editButton = appBarMenu.findItem(R.id.action_edit);
editButton.setVisible(false);
MenuItem saveButton = appBarMenu.findItem(R.id.action_edit_save);
saveButton.setVisible(true);
return true;
case R.id.action_delete:
Log.d(TAG, "deleting snippet with id " + String.valueOf(snippetId));
snippetViewModel.deleteSnippet(snippetViewModel.getSnippetForId(snippetId));
snippetViewModel.deleteStrayTags();
MainActivity.instance.updateAdapter();
finish();
return true;
case R.id.action_edit_save:
Log.v(TAG, "save clicked");
// save snippet and finish
updateSnippet();
MainActivity.instance.updateAdapter();
finish();
return true;
default:
Log.wtf(TAG, "you clicked a nonexistent option");
return super.onOptionsItemSelected(item);
}
}
/**
* updates the snippet in the db
*/
private void updateSnippet() {
SnippetViewModel snippetViewModel = ViewModelProviders.of(this).get(SnippetViewModel.class);
// look for changes and save them if present
// save new name
if (!vName.getText().toString().trim().equalsIgnoreCase(oldName.trim())) {
Log.d(TAG, "name has changed");
snippetViewModel.updateSnippetName(snippetId, vName.getText().toString().trim());
}
// save new text
if (!vText.getText().toString().trim().equalsIgnoreCase(oldText.trim())) {
Log.d(TAG, "text has changed");
snippetViewModel.updateSnippetText(snippetId, vText.getText().toString().trim());
}
// save new tags
if (!vTags.getText().toString().trim().equalsIgnoreCase(oldTags.trim())) {
// parse tags from text
Log.d(TAG, "tags have changed");
List<String> tagsList = Arrays.asList(vTags.getText().toString().split(","));
for (int i = 0; i < tagsList.size(); i++) {
tagsList.set(i, tagsList.get(i).trim().toLowerCase());
}
List<String> filteredList = tagsList.stream().distinct().collect(Collectors.toList());
List<Tag> tagsToSort = new LinkedList<>();
filteredList.forEach(s -> tagsToSort.add(new Tag(s)));
// delete all tag associations of this snippet
snippetViewModel.deleteSnippetTagsForSnippetId(snippetId);
// sort tags into 2 lists: newTags, inDb
List<Tag> allTags = snippetViewModel.getAllTags();
Log.v(TAG, "number of stored tags: " + allTags.size());
Log.v(TAG, "snippet now has " + tagsToSort.size() + " tags");
List<Tag> newTags = new LinkedList<>();
List<Tag> existingTags = new LinkedList<>();
for (int i = 0; i < tagsToSort.size(); i++) {
Tag t = tagsToSort.get(i);
if (!allTags.contains(t))
newTags.add(t);
if (allTags.contains(t))
existingTags.add(t);
}
Log.v(TAG, "existing tags: ");
if (existingTags.size() != 0) {
for (Tag t : existingTags) {
Log.v(TAG, t.getTag());
}
}
Log.v(TAG, "new tags: ");
if (newTags.size() != 0) {
for (Tag t : newTags) {
Log.v(TAG, t.getTag());
}
}
// insert any new tags
if (newTags.size() >= 0)
newTags.forEach(snippetViewModel::insert);
// insert all SnippetTags entries
List<SnippetTags> snippetTags = new LinkedList<>();
tagsToSort.forEach(tag -> snippetTags.add(new SnippetTags(snippetId, tag)));
SnippetTags[] insert = new SnippetTags[snippetTags.size()];
snippetViewModel.insert(snippetTags.toArray(insert));
// delete any stray tags with no entry in SnippetTags
snippetViewModel.deleteStrayTags();
}
}
/**
* sets the app bar icon according to the favorite status
*/
private void updateActionBarFavorite() {
// set favorite state of the snippet
Toolbar toolbar = findViewById(R.id.toolbar);
MenuItem favoriteIcon = toolbar.getMenu().findItem(R.id.action_view_fav);
if (favorite) {
favoriteIcon.setIcon(R.drawable.ic_favorite_black_24dp);
} else {
favoriteIcon.setIcon(R.drawable.ic_favorite_border_black_24dp);
}
}
}
|
3e19da082ec7f7a495f79b420d704d12a9988b88 | 285 | java | Java | spizen-master/src/main/java/com/spizenstudio/master/exceptions/ArraylistsSizesMismatchException.java | rahulravindran-in/spizenutil | 7322414d520d2f0d4e301d2ae64a11bcccf70ee9 | [
"Apache-2.0"
] | null | null | null | spizen-master/src/main/java/com/spizenstudio/master/exceptions/ArraylistsSizesMismatchException.java | rahulravindran-in/spizenutil | 7322414d520d2f0d4e301d2ae64a11bcccf70ee9 | [
"Apache-2.0"
] | null | null | null | spizen-master/src/main/java/com/spizenstudio/master/exceptions/ArraylistsSizesMismatchException.java | rahulravindran-in/spizenutil | 7322414d520d2f0d4e301d2ae64a11bcccf70ee9 | [
"Apache-2.0"
] | null | null | null | 17.8125 | 64 | 0.715789 | 10,967 | package com.spizenstudio.master.exceptions;
/**
* Created by rahul on 08-10-2017.
* From company : Spizen
*/
public class ArraylistsSizesMismatchException extends Exception{
public <T> ArraylistsSizesMismatchException (T trace) {
System.out.println(trace);
}
}
|
3e19da3eff70cf16954effaed1d62b0c19108493 | 4,299 | java | Java | JAVA_DB_08_Lab/src/main/java/com/example/java_db_08_lab/App.java | 1vaPetkova/JAVADB_SpringData | f46f807832578a5e4e42a9befaf7276e379dec80 | [
"MIT"
] | null | null | null | JAVA_DB_08_Lab/src/main/java/com/example/java_db_08_lab/App.java | 1vaPetkova/JAVADB_SpringData | f46f807832578a5e4e42a9befaf7276e379dec80 | [
"MIT"
] | null | null | null | JAVA_DB_08_Lab/src/main/java/com/example/java_db_08_lab/App.java | 1vaPetkova/JAVADB_SpringData | f46f807832578a5e4e42a9befaf7276e379dec80 | [
"MIT"
] | null | null | null | 43.867347 | 115 | 0.604327 | 10,968 | package com.example.java_db_08_lab;
import com.example.java_db_08_lab.model.dto.EmployeeDto;
import com.example.java_db_08_lab.model.dto.ManagerDto;
import com.example.java_db_08_lab.model.entities.Employee;
import com.example.java_db_08_lab.services.EmployeeService;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeMap;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.List;
@Component
public class App implements CommandLineRunner {
private final EmployeeService employeeService;
private final ModelMapper modelMapper;
private final BufferedReader reader;
public App(EmployeeService employeeService, ModelMapper modelMapper) {
this.employeeService = employeeService;
this.modelMapper = modelMapper;
this.reader = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run(String... args) throws Exception {
System.out.println("Enter problem number: ");
int problem = Integer.parseInt(reader.readLine());
switch (problem) {
case 1:
//1.Create address and employee and map it to EmployeeDto
createAddressAndEmployee();
break;
case 2:
//2. Advanced Mapping - type map, mapping addresses
// and employees to ManagerDto with EmployeeDto as subordinates
typeMap();
break;
case 3:
// 3. Employees born after 1990 with manager last name
employeeBornAfter1990();
break;
}
}
private void employeeBornAfter1990() {
// 3. Employees born after 1990 with manager last Name
Converter<String, String> converterNoManager = ctx ->
ctx.getSource() == null ? "[No manager]" : ctx.getSource();
TypeMap<Employee, EmployeeDto> employeeMap = modelMapper
.getTypeMap(Employee.class, EmployeeDto.class)
.addMappings(m -> m.using(converterNoManager)
.map(src -> src.getManager().getLastName(), EmployeeDto::setLastName));
List<Employee> employeesBefore1990 = this.employeeService
.findAllByBirthdayBeforeOrderBySalaryDesc(LocalDate.of(1990, 1, 1));
employeesBefore1990.stream().map(employeeMap::map).forEach(e->
System.out.printf("%s %s %.2f – Manager: %s\n",
e.getFirstName(),e.getLastName(),e.getIncome(),e.getManagerLastName()));
}
//2. Advanced Mapping - type map, mapping addresses
// and employees to ManagerDto with EmployeeDto as subordinates
private void typeMap() {
ManagerDto managerDto = this.employeeService.findManager(1L);
System.out.println(managerDto.getFirstName() + " " + managerDto.getLastName() +
" | Employees: " + managerDto.getSubordinates().size());
managerDto.getSubordinates().forEach(e ->
System.out.println(" - " + e.getFirstName() + " " + e.getLastName() + " " + e.getIncome()));
System.out.println("==========================================================================");
List<ManagerDto> managers = this.employeeService.findAll();
managers.forEach(mDto -> {
System.out.println(mDto.getFirstName() + " " + mDto.getLastName() +
" | Employees: " + mDto.getSubordinates().size());
mDto.getSubordinates().forEach(e ->
System.out.println(" - " + e.getFirstName() + " " + e.getLastName() + " " + e.getIncome()));
});
System.out.println("==========================================================================");
}
//1.Create address and employee and map it to EmployeeDto
private void createAddressAndEmployee() {
EmployeeDto dto = this.employeeService.findOne(2L);
System.out.println(dto.getLastName() + " " + dto.getLastName() + "; salary: " + dto.getIncome());
System.out.println("==========================================================================");
}
}
|
3e19da8327465975df770901c43458bce4271552 | 3,686 | java | Java | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java | Jammyson/spring-framework | 746f9db49ff55c2bf2c258b3bc8d4e3206413f0d | [
"Apache-2.0"
] | null | null | null | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java | Jammyson/spring-framework | 746f9db49ff55c2bf2c258b3bc8d4e3206413f0d | [
"Apache-2.0"
] | null | null | null | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java | Jammyson/spring-framework | 746f9db49ff55c2bf2c258b3bc8d4e3206413f0d | [
"Apache-2.0"
] | null | null | null | 34.773585 | 89 | 0.765057 | 10,969 | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.config.annotation;
import java.util.Collections;
import javax.servlet.ServletContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
/**
* Configures a request handler for serving static resources by forwarding
* the request to the Servlet container's "default" Servlet. This is intended
* to be used when the Spring MVC {@link DispatcherServlet} is mapped to "/"
* thus overriding the Servlet container's default handling of static resources.
*
* <p>Since this handler is configured at the lowest precedence, effectively
* it allows all other handler mappings to handle the request, and if none
* of them do, this handler can forward it to the "default" Servlet.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 3.1
* @see DefaultServletHttpRequestHandler
*/
public class DefaultServletHandlerConfigurer {
private final ServletContext servletContext;
@Nullable
private DefaultServletHttpRequestHandler handler;
/**
* Create a {@link DefaultServletHandlerConfigurer} instance.
* @param servletContext the ServletContext to use.
*/
public DefaultServletHandlerConfigurer(ServletContext servletContext) {
Assert.notNull(servletContext, "ServletContext is required");
this.servletContext = servletContext;
}
/**
* Enable forwarding to the "default" Servlet.
* <p>When this method is used the {@link DefaultServletHttpRequestHandler}
* will try to autodetect the "default" Servlet name. Alternatively, you can
* specify the name of the default Servlet via {@link #enable(String)}.
* @see DefaultServletHttpRequestHandler
*/
public void enable() {
enable(null);
}
/**
* Enable forwarding to the "default" Servlet identified by the given name.
* <p>This is useful when the default Servlet cannot be autodetected,
* for example1 when it has been manually configured.
* @see DefaultServletHttpRequestHandler
*/
public void enable(@Nullable String defaultServletName) {
this.handler = new DefaultServletHttpRequestHandler();
if (defaultServletName != null) {
this.handler.setDefaultServletName(defaultServletName);
}
this.handler.setServletContext(this.servletContext);
}
/**
* Return a handler mapping instance ordered at {@link Integer#MAX_VALUE} containing the
* {@link DefaultServletHttpRequestHandler} instance mapped to {@code "/**"};
* or {@code null} if default servlet handling was not been enabled.
* @since 4.3.12
*/
@Nullable
protected SimpleUrlHandlerMapping buildHandlerMapping() {
if (this.handler == null) {
return null;
}
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setUrlMap(Collections.singletonMap("/**", this.handler));
handlerMapping.setOrder(Integer.MAX_VALUE);
return handlerMapping;
}
}
|
3e19daa9f500ec684fa5dfe590c642b9b103ed56 | 5,423 | java | Java | shardingsphere-infra/shardingsphere-infra-binder/src/test/java/org/apache/shardingsphere/infra/binder/segment/insert/values/InsertValueContextTest.java | 66951735/shardingsphere | 23dc470ae011e0d507aab6414c3d6fbe2a85121a | [
"Apache-2.0"
] | 5,788 | 2020-04-17T14:09:07.000Z | 2022-03-31T08:12:53.000Z | shardingsphere-infra/shardingsphere-infra-binder/src/test/java/org/apache/shardingsphere/infra/binder/segment/insert/values/InsertValueContextTest.java | 66951735/shardingsphere | 23dc470ae011e0d507aab6414c3d6fbe2a85121a | [
"Apache-2.0"
] | 6,488 | 2020-04-17T14:21:54.000Z | 2022-03-31T21:36:33.000Z | shardingsphere-infra/shardingsphere-infra-binder/src/test/java/org/apache/shardingsphere/infra/binder/segment/insert/values/InsertValueContextTest.java | 66951735/shardingsphere | 23dc470ae011e0d507aab6414c3d6fbe2a85121a | [
"Apache-2.0"
] | 2,504 | 2020-04-17T14:09:46.000Z | 2022-03-31T12:21:31.000Z | 54.23 | 167 | 0.763599 | 10,970 | /*
* 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.shardingsphere.infra.binder.segment.insert.values;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.column.ColumnSegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.BinaryOperationExpression;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.ExpressionSegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.simple.LiteralExpressionSegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.simple.ParameterMarkerExpressionSegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ExpressionProjectionSegment;
import org.apache.shardingsphere.sql.parser.sql.common.value.identifier.IdentifierValue;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class InsertValueContextTest {
@SuppressWarnings("unchecked")
@Test
public void assertInstanceConstructedOk() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Collection<ExpressionSegment> assignments = Collections.emptyList();
List<Object> parameters = Collections.emptyList();
int parametersOffset = 0;
InsertValueContext insertValueContext = new InsertValueContext(assignments, parameters, parametersOffset);
Method getValueExpressionsMethod = InsertValueContext.class.getDeclaredMethod("getValueExpressions", Collection.class);
getValueExpressionsMethod.setAccessible(true);
List<ExpressionSegment> getValueExpressionsResult = (List<ExpressionSegment>) getValueExpressionsMethod.invoke(insertValueContext, new Object[] {assignments});
assertThat(insertValueContext.getValueExpressions(), is(getValueExpressionsResult));
Method getParametersMethod = InsertValueContext.class.getDeclaredMethod("getParameters", List.class, int.class);
getParametersMethod.setAccessible(true);
List<Object> getParametersResult = (List<Object>) getParametersMethod.invoke(insertValueContext, new Object[] {parameters, parametersOffset});
assertThat(insertValueContext.getParameters(), is(getParametersResult));
}
@Test
public void assertGetValueWhenParameterMarker() {
Collection<ExpressionSegment> assignments = makeParameterMarkerExpressionSegment();
String parameterValue = "test";
List<Object> parameters = Collections.singletonList(parameterValue);
int parametersOffset = 0;
InsertValueContext insertValueContext = new InsertValueContext(assignments, parameters, parametersOffset);
Object valueFromInsertValueContext = insertValueContext.getValue(0);
assertThat(valueFromInsertValueContext, is(parameterValue));
}
private Collection<ExpressionSegment> makeParameterMarkerExpressionSegment() {
return Collections.singleton(new ParameterMarkerExpressionSegment(0, 10, 5));
}
@Test
public void assertGetValueWhenLiteralExpressionSegment() {
Object literalObject = new Object();
Collection<ExpressionSegment> assignments = makeLiteralExpressionSegment(literalObject);
List<Object> parameters = Collections.emptyList();
InsertValueContext insertValueContext = new InsertValueContext(assignments, parameters, 0);
Object valueFromInsertValueContext = insertValueContext.getValue(0);
assertThat(valueFromInsertValueContext, is(literalObject));
}
private Collection<ExpressionSegment> makeLiteralExpressionSegment(final Object literalObject) {
return Collections.singleton(new LiteralExpressionSegment(0, 10, literalObject));
}
@Test
public void assertGetParameterCount() {
Collection<ExpressionSegment> expressions = Arrays.asList(
new LiteralExpressionSegment(0, 10, null),
new ExpressionProjectionSegment(0, 10, ""),
new ParameterMarkerExpressionSegment(0, 10, 5),
new BinaryOperationExpression(0, 0, new ColumnSegment(0, 0, new IdentifierValue("")), new ParameterMarkerExpressionSegment(0, 10, 5), "=", "")
);
List<Object> parameters = Arrays.asList("", "");
InsertValueContext insertValueContext = new InsertValueContext(expressions, parameters, 0);
assertThat(insertValueContext.getParameterCount(), is(2));
}
}
|
3e19dbdf2588f1bee2858aa1b115cdc5e53503c0 | 23,600 | java | Java | framework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/config/ConfigurationManager.java | fideoman/geronimo | c78546a9c0e1007e65179da780727de8672f9289 | [
"Apache-2.0"
] | 21 | 2015-05-05T04:10:19.000Z | 2022-01-07T12:36:17.000Z | framework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/config/ConfigurationManager.java | fideoman/geronimo | c78546a9c0e1007e65179da780727de8672f9289 | [
"Apache-2.0"
] | 1 | 2018-02-23T20:53:31.000Z | 2018-02-23T20:53:31.000Z | framework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/config/ConfigurationManager.java | fideoman/geronimo | c78546a9c0e1007e65179da780727de8672f9289 | [
"Apache-2.0"
] | 29 | 2016-01-08T21:08:14.000Z | 2022-01-07T12:36:20.000Z | 45.559846 | 173 | 0.70911 | 10,971 | /**
* 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.geronimo.kernel.config;
import java.io.IOException;
import java.util.List;
import java.util.Collection;
import java.util.LinkedHashSet;
import org.apache.geronimo.kernel.repository.Artifact;
import org.apache.geronimo.kernel.repository.ArtifactResolver;
import org.apache.geronimo.kernel.repository.Version;
import org.apache.geronimo.kernel.repository.Repository;
import org.apache.geronimo.kernel.repository.MissingDependencyException;
import org.apache.geronimo.gbean.AbstractName;
import org.osgi.framework.Bundle;
/**
* Encapsulates logic for dealing with configurations.
*
* Configurations have a lifecycle with three states: installed, loaded, and
* running. Installed means that the configuration is present in the server's
* repository. Loaded means that the Configuration GBean (including the
* configuration's ClassLoader) is running. Running means that all the GBeans
* in the Configuration are running.
*
* From a user perspective, there's not much difference between installed and
* loaded if the configuration has not been started (it still shows up as not
* running). However, certain operations will cause a configuration to be
* loaded but not started. For example, if ModuleA depends on ModuleB, then
* when ModuleA is distributed ModuleB will normally be loaded (to fire up the
* ClassLoader and validate ModuleA). But ModuleB will not be started at that
* point. It can be started manually or it will be started automatically when
* ModuleA is started.
*
* When a Configuration is not loaded, only its ConfigurationData is available
* for inspection. It's normally not possible to inspect the GBeans in the
* configuration because there's no ClassLoader that could be used to load the
* classes needed by the GBeanDatas in the configuration. Once the
* configuration has been loaded, it's ClassLoader is available so the
* GBeanDatas can be loaded and inspected. But the GBean instances are not
* instantiated and started until the configuration is started.
*
* @version $Rev$ $Date$
*/
public interface ConfigurationManager extends ConfigurationSource {
/**
* Is the specified configuration installed into the server
* environment? That is, does it exist in the configuration store,
* regardless of whether it's loaded or running? Note that this
* always returns false if the argument does not represent a
* configuration (e.g. if it's for a plain JAR).
*
* @param configurationId the configuration identifier, which must be
* fully resolved (isResolved() == true)
*
* @return true if the configuration has been loaded; false otherwise
*/
boolean isInstalled(Artifact configurationId);
/**
* Is the specified configuration loaded into the kernel? Note that this
* always returns false if the argument does not represent a
* configuration (e.g. if it's for a plain JAR).
*
* @param configurationId the configuration identifier, which must be
* fully resolved (isResolved() == true)
*
* @return true if the configuration has been loaded; false otherwise
*/
boolean isLoaded(Artifact configurationId);
/**
* Is the specified configuation running? Note that this
* always returns false if the argument does not represent a
* configuration (e.g. if it's for a plain JAR).
*
* @param configurationId the configuration identifier, which must be
* fully resolved (isResolved() == true)
*
* @return true if the configuration is running, false otherwise
*/
boolean isRunning(Artifact configurationId);
/**
* Given an artifact that's not fully resolved (e.g. some parts are
* missing), check whether there are any instances installed into
* the server environment. That is, are there any matches in the
* configuration store, regardless of whether they're loaded or running?
* Note that this always returns an empty array if the argument does not
* represent a configuration (e.g. if it's for a plain JAR).
*
* @param query The partially-complete artifact name to check for
*
* @return All matching artifacts that are loaded in the server
*/
Artifact[] getInstalled(Artifact query);
/**
* Given an artifact that's not fully resolved (e.g. some parts are
* missing), check whether there are any instances loaded.
* Note that this always returns an empty array if the argument does not
* represent a configuration (e.g. if it's for a plain JAR).
*
* @param query The partially-complete artifact name to check for
*
* @return All matching artifacts that are loaded in the server
*/
Artifact[] getLoaded(Artifact query);
/**
* Given an artifact that's not fully resolved (e.g. some parts are
* missing), check whether there are any instances running.
* Note that this always returns an empty array if the argument does not
* represent a configuration (e.g. if it's for a plain JAR).
*
* @param query The partially-complete artifact name to check for
*
* @return All matching artifacts that are loaded in the server
*/
Artifact[] getRunning(Artifact query);
/**
* Gets a List>ConfigurationInfo< of every of every available configuation.
* This includes all configurations installed, regardless of whether they are
* currently loaded or running.
*/
List listConfigurations();
/**
* Return a list of the stores this manager knows about.
*
* @return a List>AbstractName< of the stores this manager controls
*/
List<AbstractName> listStores();
/**
* Get all the ConfigurationStores known to this manager at present
*/
ConfigurationStore[] getStores();
/**
* Gets the configuration store responsible for the specified
* configuration, or null if there is none. The configuration need not be
* loaded or running; this just checks which store holds the data for it.
*
* @param configuration The unique ID for the configuration to check for,
* which must be fully resolved (isResolved() == true)
*
* @return The ConfigurationStore for this configuration, or null if the
* configuration was not found in any configuration store.
*/
ConfigurationStore getStoreForConfiguration(Artifact configuration);
/**
* Return a list of the configurations in a specific store.
*
* @param store the store to list
*
* @return a List>ConfigurationInfo< of all the configurations in the store
*
* @throws NoSuchStoreException if the store could not be located
*/
List listConfigurations(AbstractName store) throws NoSuchStoreException;
/**
* Is the specified artifact a configuration?
*
* @param artifact the ID of the artifact to check, which must be fully
* resolved (isResolved() == true)
*
* @return true if the artifact is a configuration available in the
* server (regardless of whether it has been loaded/started)
*/
boolean isConfiguration(Artifact artifact);
/**
* Gets a loaded Configuration (does not see unloaded configurations).
*
* @param configurationId the unique ID of the configuration to get, which
* must be fully resolved (isResolved() == true)
*
* @return the specified configuration or null if the configuration has not been loaded
*/
// Configuration getConfiguration(Artifact configurationId);
/**
* Load the specified configuration (from a config store) and all
* configurations it depends on into the kernel. This causes the
* configuration gbean to be loaded and started, but does not load any of
* the gbeans contained within the configuration.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @return the results of the operation
*
* @throws NoSuchConfigException if no configuration with the given id exists in the configuration stores
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults loadConfiguration(Artifact configurationId) throws NoSuchConfigException, LifecycleException;
/**
* Load the specified configurationData and all configurations it depends
* on (from a config store) into the kernel. This causes the configuration
* gbean to be loaded and started, but does not load any of the gbeans
* contained within the configuration.
*
* @param configurationData the configuration to load
*
* @return the results of the operation
*
* @throws NoSuchConfigException if no configuration with the given id exists in the configuration stores
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults loadConfiguration(ConfigurationData configurationData) throws NoSuchConfigException, LifecycleException;
/**
* Load the specified configuration (from a config store) and all
* configurations it depends on into the kernel. This causes the
* configuration gbean to be loaded and started, but does not load any of
* the gbeans contained within the configuration.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if no configuration with the given id exists in the configuration stores
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults loadConfiguration(Artifact configurationId, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Load the specified configurationData and all configurations it depends
* on (from a config store) into the kernel. This causes the configuration
* gbean to be loaded and started, but does not load any of the gbeans
* contained within the configuration.
*
* @param configurationData the configuration to load
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if no configuration with the given id exists in the configuration stores
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults loadConfiguration(ConfigurationData configurationData, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Stops and unloads the configuration. This causes all contained gbeans
* to be stopped and unloaded, and the configuration gbean is stopped and
* unloaded. This operation causes all configurations that have a class
* or service dependency on the specified configuration to be stopped and
* unloaded.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException
*/
LifecycleResults unloadConfiguration(Artifact configurationId) throws NoSuchConfigException, LifecycleException;
/**
* Stops and unloads the configuration. This causes all contained gbeans
* to be stopped and unloaded, and the configuration gbean is stopped and
* unloaded. This operation causes all configurations that have a class
* or service dependency on the specified configuration to be stopped and
* unloaded.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the
* operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException
*/
LifecycleResults unloadConfiguration(Artifact configurationId, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Loads and starts all of the gbeans contained within the configuration.
* If any of the gbeans fails to fully start, all gbeans will be unloaded
* and an exception will be thrown. This operation causes all
* configurations that the specified configuration has a service dependency
* on to be started.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
*/
LifecycleResults startConfiguration(Artifact configurationId) throws NoSuchConfigException, LifecycleException;
/**
* Loads and starts all of the gbeans contained within the configuration.
* If any of the gbeans fails to fully start, all gbeans will be unloaded
* and an exception will be thrown. This operation causes all
* configurations that the specified configuration has a service dependency
* on to be started.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
*/
LifecycleResults startConfiguration(Artifact configurationId, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Stop the gbeans contained within the configuration. This operation
* causes all configurations that have a service dependency on the
* specified configuration to be stopped.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
*/
LifecycleResults stopConfiguration(Artifact configurationId) throws NoSuchConfigException;
/**
* Stop the gbeans contained within the configuration. This operation
* causes all configurations that have a service dependency on the
* specified configuration to be stopped.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
*/
LifecycleResults stopConfiguration(Artifact configurationId, LifecycleMonitor monitor) throws NoSuchConfigException;
/**
* Restarts the specified configuration and all configurations that have a
* service dependency on the specified configuration
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults restartConfiguration(Artifact configurationId) throws NoSuchConfigException, LifecycleException;
/**
* Restarts the specified configuration and all configurations that have a
* service dependency on the specified configuration
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults restartConfiguration(Artifact configurationId, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Reloads the specified configuration and all configurations that have a
* dependency on the specified configuration
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults reloadConfiguration(Artifact configurationId) throws NoSuchConfigException, LifecycleException;
/**
* Reloads the specified configuration and all configurations that have a
* dependency on the specified configuration
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults reloadConfiguration(Artifact configurationId, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Reloads the specified configuration and all configurations that have a
* dependency on the specified configuration
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param version new version to load from the config store
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults reloadConfiguration(Artifact configurationId, Version version) throws NoSuchConfigException, LifecycleException;
/**
* Reloads the specified configuration and all configurations that have a
* dependency on the specified configuration
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
* @param monitor the monitor that should receive events as the operation is carried out
* @param version new version to load from the config store
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults reloadConfiguration(Artifact configurationId, Version version, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Reloads the specified configuration and all configurations that have a
* dependency on the specified configuration
*
* @param configurationData the configuration to load
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults reloadConfiguration(ConfigurationData configurationData) throws NoSuchConfigException, LifecycleException;
/**
* Reloads the specified configuration and all configurations that have a
* dependency on the specified configuration
*
* @param configurationData the configuration to load
* @param monitor the monitor that should receive events as the operation is carried out
*
* @return the results of the operation
*
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException if there is a problem loading the configuration
*/
LifecycleResults reloadConfiguration(ConfigurationData configurationData, LifecycleMonitor monitor) throws NoSuchConfigException, LifecycleException;
/**
* Unstalls the specified configuration from the server. This operation
* can not be reversed.
*
* @param configurationId the configuration identifier, which must be fully
* resolved (isResolved() == true)
*
* @throws IOException if there was a problem removing the configuration
* @throws NoSuchConfigException if the configuration is not loaded
* @throws LifecycleException
*/
void uninstallConfiguration(Artifact configurationId) throws IOException, NoSuchConfigException, LifecycleException;
/**
* Gets the common ArtifactResolver in case the caller wants to use this
* directly. It is configured for all the repositories known to this
* configuration manager, etc.
*/
ArtifactResolver getArtifactResolver();
/**
* Online means full functionality. Offline typically means that configurations will never be started,
* although they may be marked in the persistent configuration list.
*
* @return online status of ConfigurationManager
*/
boolean isOnline();
void setOnline(boolean online);
Collection<? extends Repository> getRepositories();
LinkedHashSet<Artifact> sort(List<Artifact> ids, LifecycleMonitor monitor) throws InvalidConfigException, IOException, NoSuchConfigException, MissingDependencyException;
ConfigurationResolver newConfigurationResolver(ConfigurationData configurationData);
LinkedHashSet<Artifact> resolveParentIds(ConfigurationData configurationData) throws MissingDependencyException, InvalidConfigException;
Bundle getBundle(Artifact id);
}
|
3e19dc5cfb12de3d4ca78a1f5a825db8cb63cd99 | 5,460 | java | Java | helix-core/src/main/java/org/apache/helix/controller/ExternalViewGenerator.java | bfreuden/helix | c819915150f861e45ef5678e1f2b3ee3277697e9 | [
"Apache-2.0"
] | 381 | 2015-02-15T09:26:13.000Z | 2022-03-30T20:42:47.000Z | helix-core/src/main/java/org/apache/helix/controller/ExternalViewGenerator.java | bfreuden/helix | c819915150f861e45ef5678e1f2b3ee3277697e9 | [
"Apache-2.0"
] | 1,616 | 2015-02-14T16:41:05.000Z | 2022-03-31T23:41:14.000Z | helix-core/src/main/java/org/apache/helix/controller/ExternalViewGenerator.java | bfreuden/helix | c819915150f861e45ef5678e1f2b3ee3277697e9 | [
"Apache-2.0"
] | 214 | 2015-01-27T07:18:52.000Z | 2022-03-16T02:03:55.000Z | 40.444444 | 99 | 0.699267 | 10,972 | package org.apache.helix.controller;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.model.CurrentState.CurrentStateProperty;
import org.apache.helix.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* ZKRoutingInfoProvider keeps a copy of the routing table. Given a partition id,
* it will return
*
* 1. The list of partition that can be read
* 2. the master partition, for write operation
*
* The routing table is constructed from the currentState of each storage nodes.
* The current state is a list of following pairs: partition-id:State(MASTER / SLAVE)
*
* TODO: move the code as part of router process
* TODO: add listeners to node current state changes
* */
public class ExternalViewGenerator {
static Logger _logger = LoggerFactory.getLogger(ExternalViewGenerator.class);
/*
* Given a list of external view ZNRecord nodes(one for each cluster),
* calculate the routing map.
* The format of the routing map is like this:
* Map<String, Map<String, Set<String>>> maps from a partitionName to its
* states Map<String, List<String>> The second Map maps from a state
* ("MASTER", "SLAVE"...) to a list of nodeNames
* So that the we can query the map for the list of nodes by providing the
* partition name and the expected state.
*/
public Map<String, Map<String, Set<String>>> getRouterMapFromExternalView(
List<ZNRecord> externalViewList) {
Map<String, Map<String, Set<String>>> result = new TreeMap<String, Map<String, Set<String>>>();
for (ZNRecord nodeView : externalViewList) {
Map<String, Map<String, String>> partitionNodeStateMap = nodeView.getMapFields();
for (String partitionId : partitionNodeStateMap.keySet()) {
if (!result.containsKey(partitionId)) {
result.put(partitionId, new TreeMap<String, Set<String>>());
}
Map<String, String> nodeStateMap = partitionNodeStateMap.get(partitionId);
for (String nodeName : nodeStateMap.keySet()) {
String state = nodeStateMap.get(nodeName);
if (!result.get(partitionId).containsKey(state)) {
result.get(partitionId).put(state, new TreeSet<String>());
}
result.get(partitionId).get(state).add(nodeName);
}
}
}
return result;
}
/*
* The parameter is a map that maps the nodeName to a list of ZNRecords.
*/
public List<ZNRecord> computeExternalView(Map<String, List<ZNRecord>> currentStates,
List<ZNRecord> idealStates) {
List<ZNRecord> resultList = new ArrayList<ZNRecord>();
Map<String, ZNRecord> resultRoutingTable = new HashMap<String, ZNRecord>();
// maps from resourceName to another map : partition -> map <nodename,
// master/slave>;
// Fill the routing table with "empty" default state according to ideals
// states
// in the cluster
if (idealStates != null) {
for (ZNRecord idealState : idealStates) {
ZNRecord defaultExternalView = new ZNRecord(idealState.getId());
resultRoutingTable.put(idealState.getId(), defaultExternalView);
}
} else {
assert (!currentStates.isEmpty());
return resultList;
}
for (String nodeName : currentStates.keySet()) {
List<ZNRecord> znStates = currentStates.get(nodeName);
for (ZNRecord nodeStateRecord : znStates) {
Map<String, Map<String, String>> resourceStates = nodeStateRecord.getMapFields();
for (String stateUnitKey : resourceStates.keySet()) {
Map<String, String> partitionStates = resourceStates.get(stateUnitKey);
String resourceName = partitionStates.get(Message.Attributes.RESOURCE_NAME.toString());
ZNRecord partitionStatus = resultRoutingTable.get(resourceName);
if (partitionStatus == null) {
partitionStatus = new ZNRecord(resourceName);
resultRoutingTable.put(resourceName, partitionStatus);
}
String currentStateKey = CurrentStateProperty.CURRENT_STATE.name();
if (!partitionStatus.getMapFields().containsKey(stateUnitKey)) {
partitionStatus.setMapField(stateUnitKey, new TreeMap<String, String>());
}
partitionStatus.getMapField(stateUnitKey).put(nodeName,
partitionStates.get(currentStateKey));
}
}
}
for (ZNRecord record : resultRoutingTable.values()) {
resultList.add(record);
}
return resultList;
}
}
|
3e19dc73579472d281898fbf86fa4ca9f9130ec2 | 1,471 | java | Java | src/main/java/cn/lhemi/jax/repository/DeviceRepository.java | TURQUOISE11/jax | f158f5fc31bed885a1b120d0e61ebcaf0c553c1e | [
"Apache-2.0"
] | 2 | 2019-09-05T15:24:58.000Z | 2019-09-06T01:31:45.000Z | src/main/java/cn/lhemi/jax/repository/DeviceRepository.java | TURQUOISE11/jax | f158f5fc31bed885a1b120d0e61ebcaf0c553c1e | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/lhemi/jax/repository/DeviceRepository.java | TURQUOISE11/jax | f158f5fc31bed885a1b120d0e61ebcaf0c553c1e | [
"Apache-2.0"
] | null | null | null | 27.754717 | 110 | 0.730795 | 10,973 | package cn.lhemi.jax.repository;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @description: 存储Channel
* @author: TURQUOISE
* @create: 2019/8/8 9:43
*/
public class DeviceRepository {
/**
* deviceId->Channel
*/
private Map<String, ChannelHandlerContext> channelHandlerContextCache = new ConcurrentHashMap<>();
public boolean containsKey(String key) {
return channelHandlerContextCache.containsKey(key);
}
public boolean containsValue(ChannelHandlerContext value) {
return channelHandlerContextCache.containsValue(value);
}
public DeviceRepository putDeviceCache(String key, ChannelHandlerContext value) {
channelHandlerContextCache.put(key, value);
return this;
}
public ChannelHandlerContext getDeviceCache(String key) {
return channelHandlerContextCache.get(key);
}
public void removeDeviceCache(String key) {
this.channelHandlerContextCache.remove(key);
}
public int sizeDeviceCache() {
return this.channelHandlerContextCache.size();
}
public Map<String, ChannelHandlerContext> getChannelHandlerContextCache() {
return channelHandlerContextCache;
}
public void setChannelHandlerContextCache(Map<String, ChannelHandlerContext> channelHandlerContextCache) {
this.channelHandlerContextCache = channelHandlerContextCache;
}
}
|
3e19dc83b9134cb36f215b4ffd6033ef5ceb232f | 9,411 | java | Java | ed-fi-api/src/main/java/org/edfi/model/resource/TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.java | Ed-Fi-Exchange-OSS/Ed-Fi-X-TPDM-Data-Ingestion-POC | 1c230b8e8184db4e38b519e3e2b4a0a66b03099d | [
"Apache-2.0"
] | null | null | null | ed-fi-api/src/main/java/org/edfi/model/resource/TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.java | Ed-Fi-Exchange-OSS/Ed-Fi-X-TPDM-Data-Ingestion-POC | 1c230b8e8184db4e38b519e3e2b4a0a66b03099d | [
"Apache-2.0"
] | 5 | 2020-06-22T22:55:22.000Z | 2021-06-04T02:43:11.000Z | ed-fi-api/src/main/java/org/edfi/model/resource/TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.java | Ed-Fi-Exchange-OSS/Ed-Fi-X-TPDM-Data-Ingestion-POC | 1c230b8e8184db4e38b519e3e2b4a0a66b03099d | [
"Apache-2.0"
] | null | null | null | 49.015625 | 544 | 0.786633 | 10,974 | /**
* Ed-Fi Operational Data Store API
* The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. The Ed-Fi ODS / API supports both transactional and bulk modes of operation. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reasonable safeguards against cross-site scripting attacks and other malicious content, but the platform does not and cannot guarantee that the data it contains is free of all potentially harmful content.* ***
*
* OpenAPI spec version: 3
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.edfi.model.resource;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult
*/
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-09T12:36:29.493-07:00")
public class TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult {
@SerializedName("assessmentReportingMethodDescriptor")
private String assessmentReportingMethodDescriptor = null;
@SerializedName("averageScoreResultDatatypeTypeDescriptor")
private String averageScoreResultDatatypeTypeDescriptor = null;
@SerializedName("averageScoreResult")
private String averageScoreResult = null;
@SerializedName("scoreNCount")
private Integer scoreNCount = null;
@SerializedName("scoreStandardDeviation")
private Integer scoreStandardDeviation = null;
public TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult assessmentReportingMethodDescriptor(String assessmentReportingMethodDescriptor) {
this.assessmentReportingMethodDescriptor = assessmentReportingMethodDescriptor;
return this;
}
/**
* The method that the administrator of the assessment uses to report the performance and achievement of all Students. It may be a qualitative method such as performance level descriptors or a quantitative method such as a numerical grade or cut score. More than one type of reporting method may be used.
* @return assessmentReportingMethodDescriptor
**/
@ApiModelProperty(example = "null", required = true, value = "The method that the administrator of the assessment uses to report the performance and achievement of all Students. It may be a qualitative method such as performance level descriptors or a quantitative method such as a numerical grade or cut score. More than one type of reporting method may be used.")
public String getAssessmentReportingMethodDescriptor() {
return assessmentReportingMethodDescriptor;
}
public void setAssessmentReportingMethodDescriptor(String assessmentReportingMethodDescriptor) {
this.assessmentReportingMethodDescriptor = assessmentReportingMethodDescriptor;
}
public TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult averageScoreResultDatatypeTypeDescriptor(String averageScoreResultDatatypeTypeDescriptor) {
this.averageScoreResultDatatypeTypeDescriptor = averageScoreResultDatatypeTypeDescriptor;
return this;
}
/**
* The datatype of the result. The results can be expressed as a number, percentile, range, level, etc.
* @return averageScoreResultDatatypeTypeDescriptor
**/
@ApiModelProperty(example = "null", required = true, value = "The datatype of the result. The results can be expressed as a number, percentile, range, level, etc.")
public String getAverageScoreResultDatatypeTypeDescriptor() {
return averageScoreResultDatatypeTypeDescriptor;
}
public void setAverageScoreResultDatatypeTypeDescriptor(String averageScoreResultDatatypeTypeDescriptor) {
this.averageScoreResultDatatypeTypeDescriptor = averageScoreResultDatatypeTypeDescriptor;
}
public TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult averageScoreResult(String averageScoreResult) {
this.averageScoreResult = averageScoreResult;
return this;
}
/**
* A meaningful average score or statistical expression of the performance of an group. The results can be expressed as a number, percentile, range, level, etc.
* @return averageScoreResult
**/
@ApiModelProperty(example = "null", required = true, value = "A meaningful average score or statistical expression of the performance of an group. The results can be expressed as a number, percentile, range, level, etc.")
public String getAverageScoreResult() {
return averageScoreResult;
}
public void setAverageScoreResult(String averageScoreResult) {
this.averageScoreResult = averageScoreResult;
}
public TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult scoreNCount(Integer scoreNCount) {
this.scoreNCount = scoreNCount;
return this;
}
/**
* The total number of data values in set of data that makes up the average assessment score for a group
* @return scoreNCount
**/
@ApiModelProperty(example = "null", value = "The total number of data values in set of data that makes up the average assessment score for a group")
public Integer getScoreNCount() {
return scoreNCount;
}
public void setScoreNCount(Integer scoreNCount) {
this.scoreNCount = scoreNCount;
}
public TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult scoreStandardDeviation(Integer scoreStandardDeviation) {
this.scoreStandardDeviation = scoreStandardDeviation;
return this;
}
/**
* A measure used to quantify the amount of variation or dispersion of a set of data values, in this case specific to the average assessment score for a group of students
* @return scoreStandardDeviation
**/
@ApiModelProperty(example = "null", value = "A measure used to quantify the amount of variation or dispersion of a set of data values, in this case specific to the average assessment score for a group of students")
public Integer getScoreStandardDeviation() {
return scoreStandardDeviation;
}
public void setScoreStandardDeviation(Integer scoreStandardDeviation) {
this.scoreStandardDeviation = scoreStandardDeviation;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult tpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult = (TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult) o;
return Objects.equals(this.assessmentReportingMethodDescriptor, tpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.assessmentReportingMethodDescriptor) &&
Objects.equals(this.averageScoreResultDatatypeTypeDescriptor, tpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.averageScoreResultDatatypeTypeDescriptor) &&
Objects.equals(this.averageScoreResult, tpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.averageScoreResult) &&
Objects.equals(this.scoreNCount, tpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.scoreNCount) &&
Objects.equals(this.scoreStandardDeviation, tpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult.scoreStandardDeviation);
}
@Override
public int hashCode() {
return Objects.hash(assessmentReportingMethodDescriptor, averageScoreResultDatatypeTypeDescriptor, averageScoreResult, scoreNCount, scoreStandardDeviation);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TpdmEducationOrganizationStudentAssessmentFactsAggregatedScoreResult {\n");
sb.append(" assessmentReportingMethodDescriptor: ").append(toIndentedString(assessmentReportingMethodDescriptor)).append("\n");
sb.append(" averageScoreResultDatatypeTypeDescriptor: ").append(toIndentedString(averageScoreResultDatatypeTypeDescriptor)).append("\n");
sb.append(" averageScoreResult: ").append(toIndentedString(averageScoreResult)).append("\n");
sb.append(" scoreNCount: ").append(toIndentedString(scoreNCount)).append("\n");
sb.append(" scoreStandardDeviation: ").append(toIndentedString(scoreStandardDeviation)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e19dd132fdad58e07c0ec7ca95f8f137c849400 | 1,163 | java | Java | src/main/java/de/thk/das/rest/security/http/crehma/tvp/TimeVariantParameter.java | das-th-koeln/jCREHMA | 9a165c8c643ecdd25f17ed4c21908ec15fbfdc57 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/thk/das/rest/security/http/crehma/tvp/TimeVariantParameter.java | das-th-koeln/jCREHMA | 9a165c8c643ecdd25f17ed4c21908ec15fbfdc57 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/thk/das/rest/security/http/crehma/tvp/TimeVariantParameter.java | das-th-koeln/jCREHMA | 9a165c8c643ecdd25f17ed4c21908ec15fbfdc57 | [
"Apache-2.0"
] | null | null | null | 41.535714 | 81 | 0.662081 | 10,975 | /*******************************************************************************
* Copyright 2015 Hoai Viet Nguyen
*
* 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 de.thk.das.rest.security.http.crehma.tvp;
import java.util.Date;
public interface TimeVariantParameter {
public abstract String generate();
public abstract boolean verify(String tvp) throws Exception;
public abstract boolean verifyFrehness(String tvp);
public abstract Date parseTvp(String tvp) throws Exception;
public abstract long getDelta();
public abstract void setDelta(long delta);
}
|
3e19dd9bec42c25077a4a36adb65be0dae6c0101 | 5,380 | java | Java | src/aya/ext/dialog/DialogInstructionStore.java | aya-lang/aya | 2c125eca2f5fb9b8b4cc2348e8fde8ef2583b5e9 | [
"MIT"
] | 17 | 2021-01-04T04:16:06.000Z | 2022-03-19T21:42:34.000Z | src/aya/ext/dialog/DialogInstructionStore.java | nick-paul/aya-lang | 2c125eca2f5fb9b8b4cc2348e8fde8ef2583b5e9 | [
"MIT"
] | 44 | 2017-01-01T21:34:42.000Z | 2019-08-09T13:26:12.000Z | src/aya/ext/dialog/DialogInstructionStore.java | nick-paul/aya-lang | 2c125eca2f5fb9b8b4cc2348e8fde8ef2583b5e9 | [
"MIT"
] | 1 | 2021-12-20T15:32:47.000Z | 2021-12-20T15:32:47.000Z | 34.267516 | 159 | 0.686431 | 10,976 | package aya.ext.dialog;
import static aya.util.Casting.asList;
import javax.swing.JOptionPane;
import aya.exceptions.runtime.TypeError;
import aya.exceptions.runtime.ValueError;
import aya.instruction.named.NamedInstruction;
import aya.instruction.named.NamedInstructionStore;
import aya.obj.Obj;
import aya.obj.block.Block;
import aya.obj.list.List;
import aya.obj.number.Num;
import aya.obj.symbol.Symbol;
import aya.obj.symbol.SymbolConstants;
public class DialogInstructionStore extends NamedInstructionStore {
@Override
protected void init() {
addInstruction(new NamedInstruction("dialog.getstr", "message::str: popup window with a a text input field") {
@Override
public void execute(Block block) {
final Obj title = block.pop();
block.push(List.fromString(QuickDialog.requestString(title.str())));
}
});
addInstruction(new NamedInstruction("dialog.getnum", "message::str: popup window with a number input field") {
@Override
public void execute(Block block) {
final Obj title = block.pop();
block.push(QuickDialog.numberInput(title.str()));
}
});
addInstruction(new NamedInstruction("dialog.alert", "message::str title::str type::sym show an alert dialog") {
@Override
public void execute(Block block) {
final Obj type_obj = block.pop();
final Obj title_obj = block.pop();
final Obj message_obj = block.pop();
if (!type_obj.isa(Obj.SYMBOL)) throw new TypeError(this, "SSJ", type_obj, title_obj, message_obj);
int type = symToDialogType((Symbol)type_obj);
QuickDialog.alert(message_obj.str(), title_obj.str(), type);
}
});
addInstruction(new NamedInstruction("dialog.confirm", "message::str options::list title::str type::sym show an alert dialog") {
@Override
public void execute(Block block) {
final Obj type_obj = block.pop();
final Obj title_obj = block.pop();
final Obj options_obj = block.pop();
final Obj message_obj = block.pop();
if (!(type_obj.isa(Obj.SYMBOL) && options_obj.isa(Obj.LIST))) throw new TypeError(this, "SSJ", type_obj, title_obj, message_obj);
int type = symToDialogType((Symbol)type_obj);
List options = asList(options_obj);
if (options.length() != 2) throw new ValueError(":{dialog.confirm} : Expected options list of length 2. Got " + options.repr());
boolean val = QuickDialog.confirm(
message_obj.str(),
options.getExact(0).str(),
options.getExact(1).str(),
title_obj.str(),
type);
block.push(Num.fromBool(val));
}
});
addInstruction(new NamedInstruction("dialog.buttons", "message::str options::list title::str type::sym: show a dialog with several option buttons") {
@Override
public void execute(Block block) {
final Obj type_obj = block.pop();
final Obj title_obj = block.pop();
final Obj options_obj = block.pop();
final Obj message_obj = block.pop();
if (!(type_obj.isa(Obj.SYMBOL) && options_obj.isa(Obj.LIST))) throw new TypeError(this, "SSJ", type_obj, title_obj, message_obj);
int type = symToDialogType((Symbol)type_obj);
List options_list = asList(options_obj);
if (options_list.length() <= 0) throw new ValueError(":{dialog.buttons} : Expected non-empty options. Got " + options_list.repr());
String[] options = new String[options_list.length()];
for (int i = 0; i < options_list.length(); i++) {
options[i] = options_list.getExact(i).str();
}
String selected = QuickDialog.selectOptionButtons(
message_obj.str(),
options,
title_obj.str(),
type);
block.push(List.fromString(selected));
}
});
addInstruction(new NamedInstruction("dialog.dropdown", "message::str options::list title::str type::sym: show a dialog with several options as a dropdown") {
@Override
public void execute(Block block) {
final Obj type_obj = block.pop();
final Obj title_obj = block.pop();
final Obj options_obj = block.pop();
final Obj message_obj = block.pop();
if (!(type_obj.isa(Obj.SYMBOL) && options_obj.isa(Obj.LIST))) throw new TypeError(this, "SSJ", type_obj, title_obj, message_obj);
int type = symToDialogType((Symbol)type_obj);
List options_list = asList(options_obj);
if (options_list.length() <= 0) throw new ValueError(":{dialog.buttons} : Expected non-empty options. Got " + options_list.repr());
String[] options = new String[options_list.length()];
for (int i = 0; i < options_list.length(); i++) {
options[i] = options_list.getExact(i).str();
}
String selected = QuickDialog.selectOptionDropdown(
message_obj.str(),
options,
title_obj.str(),
type);
block.push(List.fromString(selected));
}
});
addInstruction(new NamedInstruction("dialog.choosefile") {
@Override
public void execute(Block block) {
block.push(List.fromString(QuickDialog.chooseFile()));
}
});
}
private int symToDialogType(Symbol sym) {
final long id = sym.id();
if (id == SymbolConstants.PLAIN.id()) return JOptionPane.PLAIN_MESSAGE;
if (id == SymbolConstants.QUESTION.id()) return JOptionPane.QUESTION_MESSAGE;
if (id == SymbolConstants.WARN.id()) return JOptionPane.WARNING_MESSAGE;
if (id == SymbolConstants.ERROR.id()) return JOptionPane.ERROR_MESSAGE;
else return JOptionPane.PLAIN_MESSAGE;
}
}
|
3e19dda560fee83cff6502b375fca0647e3d87b3 | 6,135 | java | Java | AppBody.java | Erbenner/Countdown | af8a734b49529e88fdc5b9f3f9d9da612e43ddb0 | [
"Apache-2.0"
] | null | null | null | AppBody.java | Erbenner/Countdown | af8a734b49529e88fdc5b9f3f9d9da612e43ddb0 | [
"Apache-2.0"
] | null | null | null | AppBody.java | Erbenner/Countdown | af8a734b49529e88fdc5b9f3f9d9da612e43ddb0 | [
"Apache-2.0"
] | null | null | null | 23.596154 | 74 | 0.611899 | 10,977 | /**
* @author Erbenner
*
*/
package com.ui;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.data.Data;
import com.data.ReadData;
import com.data.WriteData;
public class AppBody extends JFrame {
private static final long serialVersionUID = 1L;
static JFrame f = new JFrame("倒计时 v1.0");
public AppBody() {
/* 对主窗口的初始化 */
initJFrame();
/* 向主窗口中添加若干JPanel用于显示数据 */
initJPanel();
// 刷新窗体
f.setVisible(true);
}
/*
* 从excel中按行读取若干Data对象,并解析成String,生成对应的JLabel,然后再生成单独的JPanel,把JLabel加入其中,
* 最后在主窗口中添加改JPanel.事实上,如果不用JPanel把JLabel包装起来的话,会使得String在 主窗口中并排显示
*
*/
private void initJPanel() {
// TODO Auto-generated method stub
ArrayList<Data> list = ReadData.spider("D:/workspace/data.xls");
for (int i = 1; i < list.size(); i++) {
Data temp = list.get(i);
String str = "计算失败!";
try {
str = temp.upToFromNow();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel label = new JLabel(str);
label.setFont(new Font("仿宋", 20, 20));
label.setSize(800, 300);
JPanel jp = new JPanel();
jp.add(label);
f.add(jp);
}
}
private void initJFrame() {
/* 基本的参数设定 */
f.setSize(320, 600);
f.setLocation(300, 200);
f.setVisible(true);
f.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 5));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* 菜单栏 */
JMenuBar menuBar = new JMenuBar();
f.setJMenuBar(menuBar);
/* 菜单栏第一个按钮 */
JMenu menu = new JMenu("操作");
menu.setFont(new Font("宋体", 15, 15));
menuBar.add(menu);
/* 向第一个按钮中添加两个选项,并声明响应事件 */
JMenuItem item1 = new JMenuItem("添加纪念日");
item1.setFont(new Font("宋体", 15, 15));
JMenuItem item2 = new JMenuItem("关闭");
item2.setFont(new Font("宋体", 15, 15));
/* 按钮一的事件响应为添加新纪念日 */
item1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
/*
* 框体设计
*/
JFrame dialog = new JFrame();
// 布局设计
dialog.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 5));
dialog.setTitle("添加纪念日");
dialog.setFont(new Font("仿宋", 20, 20));
dialog.setSize(450, 200);
dialog.setLocation(200, 200);
/*
* 第一行,输入事件
*/
JPanel p1 = new JPanel();
JLabel label1 = new JLabel("纪念的事件:");
label1.setFont(new Font("仿宋", 20, 20));
JTextField text1 = new JTextField(15);
text1.setHorizontalAlignment(JTextField.LEFT);
text1.setVisible(true);
label1.setVisible(true);
p1.add(label1);
p1.add(text1);
/*
* 第二行,输入日期
*/
JPanel p2 = new JPanel();
JLabel date = new JLabel("纪念的日期:");
JLabel year = new JLabel("年");
JLabel month = new JLabel("月");
JLabel day = new JLabel("日");
date.setFont(new Font("仿宋", 20, 20));
year.setFont(new Font("仿宋", 20, 20));
month.setFont(new Font("仿宋", 20, 20));
day.setFont(new Font("仿宋", 20, 20));
JTextField text_year = new JTextField(3);
JTextField text_month = new JTextField(3);
JTextField text_day = new JTextField(3);
p2.add(date);
p2.add(text_year);
p2.add(year);
p2.add(text_month);
p2.add(month);
p2.add(text_day);
p2.add(day);
/*
* 添加按钮组件 ,并把text中三个参数传递出去
*/
JButton btn = new JButton("提交纪念日");
btn.setFont(new Font("黑体", 15, 15));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Data data = new Data();
data.event = text1.getText();
data.year = text_year.getText();
data.month = text_month.getText();
data.day = text_day.getText();
// 格式化输入的数据
data.format();
JDialog dia = new JDialog(dialog, true);
dia.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 5));
dia.setSize(180, 180);
dia.setLocation(300, 400);
dia.setTitle("提示");
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JPanel jp3 = new JPanel();
boolean tag = WriteData.write(data);
if (tag) {
// 添加成功
JLabel act1 = new JLabel("恭喜您!");
JLabel act2 = new JLabel("添加成功!");
act1.setFont(new Font("楷体", 20, 20));
act1.setVisible(true);
act2.setFont(new Font("楷体", 20, 20));
act2.setVisible(true);
jp1.add(act1);
jp2.add(act2);
// JLabel temp = new
// JLabel(ReadData.dataToStr(data));
// temp.setFont(new Font("仿宋", 20, 20));
// temp.setSize(800, 300);
// f.add(temp);
} else {
// 添加失败
JLabel act1 = new JLabel("添加失败!");
JLabel act2 = new JLabel("请重试!");
act1.setFont(new Font("楷体", 20, 20));
act1.setVisible(true);
act2.setFont(new Font("楷体", 20, 20));
act2.setVisible(true);
jp1.add(act1);
jp2.add(act2);
}
JButton b = new JButton("确定");
b.setVisible(true);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dia.dispose();
}
});
jp3.add(b);
dia.add(jp1);
dia.add(jp2);
dia.add(jp3);
dia.setVisible(true);
/* 关闭确定框 */
dia.dispose();
/* 关闭添加框 */
dialog.dispose();
f.setVisible(true);
}
});
/*
* 把组件添加进Frame中,并设置可见
*/
dialog.add(p1);
dialog.add(p2);
dialog.add(btn);
dialog.setVisible(true);
}
});
item2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
menu.add(item1);
menu.addSeparator();
menu.add(item2);
}
}
|
3e19de5c652f35dfca2a44465e90eaca8765802a | 422 | java | Java | google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/errors/ConversionAdjustmentUploadErrorEnumOrBuilder.java | giger85/google-ads-java | e91f6aba2638d172baf302dbc3ff1dceb80c70fe | [
"Apache-2.0"
] | 109 | 2018-04-26T19:43:28.000Z | 2022-03-24T06:18:50.000Z | google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/errors/ConversionAdjustmentUploadErrorEnumOrBuilder.java | giger85/google-ads-java | e91f6aba2638d172baf302dbc3ff1dceb80c70fe | [
"Apache-2.0"
] | 292 | 2018-06-07T13:37:37.000Z | 2022-03-31T16:28:00.000Z | google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/errors/ConversionAdjustmentUploadErrorEnumOrBuilder.java | giger85/google-ads-java | e91f6aba2638d172baf302dbc3ff1dceb80c70fe | [
"Apache-2.0"
] | 134 | 2018-05-07T22:01:07.000Z | 2022-03-28T13:52:52.000Z | 42.2 | 117 | 0.831754 | 10,978 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/errors/conversion_adjustment_upload_error.proto
package com.google.ads.googleads.v8.errors;
public interface ConversionAdjustmentUploadErrorEnumOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.errors.ConversionAdjustmentUploadErrorEnum)
com.google.protobuf.MessageOrBuilder {
}
|
3e19de72b793b7ebc785606ff3ad542d2e97f3eb | 5,734 | java | Java | service/src/test/java/uk/gov/hmcts/reform/fpl/service/cmo/DraftOrdersBundleHearingSelectorTest.java | uk-gov-mirror/hmcts.fpl-ccd-configuration | 2c3c155261d12fa05f61a1d706d2afad5c58df09 | [
"MIT"
] | 6 | 2019-08-16T12:58:12.000Z | 2021-09-27T09:04:36.000Z | service/src/test/java/uk/gov/hmcts/reform/fpl/service/cmo/DraftOrdersBundleHearingSelectorTest.java | uk-gov-mirror/hmcts.fpl-ccd-configuration | 2c3c155261d12fa05f61a1d706d2afad5c58df09 | [
"MIT"
] | 2,084 | 2018-10-02T16:15:34.000Z | 2022-03-31T18:04:14.000Z | service/src/test/java/uk/gov/hmcts/reform/fpl/service/cmo/DraftOrdersBundleHearingSelectorTest.java | uk-gov-mirror/hmcts.fpl-ccd-configuration | 2c3c155261d12fa05f61a1d706d2afad5c58df09 | [
"MIT"
] | 7 | 2018-11-29T18:05:37.000Z | 2022-01-25T13:57:25.000Z | 41.251799 | 120 | 0.653471 | 10,979 | package uk.gov.hmcts.reform.fpl.service.cmo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import uk.gov.hmcts.reform.fpl.enums.CMOStatus;
import uk.gov.hmcts.reform.fpl.exceptions.HearingOrdersBundleNotFoundException;
import uk.gov.hmcts.reform.fpl.model.CaseData;
import uk.gov.hmcts.reform.fpl.model.common.Element;
import uk.gov.hmcts.reform.fpl.model.common.dynamic.DynamicList;
import uk.gov.hmcts.reform.fpl.model.common.dynamic.DynamicListElement;
import uk.gov.hmcts.reform.fpl.model.order.HearingOrder;
import uk.gov.hmcts.reform.fpl.model.order.HearingOrdersBundle;
import java.util.List;
import java.util.UUID;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static uk.gov.hmcts.reform.fpl.utils.ElementUtils.element;
class DraftOrdersBundleHearingSelectorTest {
private static final UUID BUNDLE_ID = UUID.randomUUID();
private final DraftOrdersBundleHearingSelector underTest = new DraftOrdersBundleHearingSelector(new ObjectMapper());
@Test
void testIfNullBundles() {
CaseData caseDa = CaseData.builder().build();
Exception exception = assertThrows(IllegalStateException.class,
() -> underTest.getSelectedHearingDraftOrdersBundle(caseDa));
assertThat(exception).hasMessageContaining("Bundle not found");
}
@Test
void testIfOnlyOneBundleSentToJudge() {
Element<HearingOrdersBundle> hearingBundle = element(UUID.randomUUID(), HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
Element<HearingOrdersBundle> actual = underTest.getSelectedHearingDraftOrdersBundle(
CaseData.builder()
.hearingOrdersBundlesDrafts(List.of(hearingBundle))
.build()
);
assertThat(actual).isEqualTo(hearingBundle);
}
@Test
void testIfMultipleBundleSentToJudgeWhenSelected() {
Element<HearingOrdersBundle> hearingBundle = element(BUNDLE_ID, HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
Element<HearingOrdersBundle> anotherHearingBundle = element(UUID.randomUUID(), HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
Element<HearingOrdersBundle> actual = underTest.getSelectedHearingDraftOrdersBundle(
CaseData.builder()
.cmoToReviewList(BUNDLE_ID.toString())
.hearingOrdersBundlesDrafts(List.of(hearingBundle, anotherHearingBundle))
.build()
);
assertThat(actual).isEqualTo(hearingBundle);
}
@Test
void testIfMultipleBundleSentToJudgeNotMatchingId() {
Element<HearingOrdersBundle> hearingBundle = element(UUID.randomUUID(), HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
Element<HearingOrdersBundle> anotherHearingBundle = element(UUID.randomUUID(), HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
CaseData caseData = CaseData.builder()
.cmoToReviewList(BUNDLE_ID.toString())
.hearingOrdersBundlesDrafts(List.of(hearingBundle, anotherHearingBundle))
.build();
HearingOrdersBundleNotFoundException exception = assertThrows(HearingOrdersBundleNotFoundException.class,
() -> underTest.getSelectedHearingDraftOrdersBundle(caseData));
assertThat(exception.getMessage()).isEqualTo(String.format(
"Could not find hearing draft orders bundle with id %s",
BUNDLE_ID.toString()));
}
@Test
void testIfMultipleBundleSentToJudgeWhenDynamicList() {
Element<HearingOrdersBundle> hearingBundle = element(BUNDLE_ID, HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
Element<HearingOrdersBundle> anotherHearingBundle = element(UUID.randomUUID(), HearingOrdersBundle.builder()
.orders(newArrayList(element(
UUID.randomUUID(), HearingOrder.builder()
.status(CMOStatus.SEND_TO_JUDGE)
.build()
))).build());
Element<HearingOrdersBundle> actual = underTest.getSelectedHearingDraftOrdersBundle(
CaseData.builder()
.cmoToReviewList(DynamicList.builder()
.value(DynamicListElement.builder()
.code(BUNDLE_ID)
.build())
.build())
.hearingOrdersBundlesDrafts(List.of(hearingBundle, anotherHearingBundle))
.build()
);
assertThat(actual).isEqualTo(hearingBundle);
}
}
|
3e19df243421311c26f447dec52d717bbb11977a | 1,058 | java | Java | business-logic-api/src/main/java/com/tristanperry/microservices/businesslogicapi/json/FizzReport.java | TristanPerry/java8-spring-cloud-microservice-demo | 40aabd99df746bc2447b2b1902fabb909ab03718 | [
"MIT"
] | 26 | 2018-01-02T22:22:59.000Z | 2021-07-31T09:39:35.000Z | business-logic-api/src/main/java/com/tristanperry/microservices/businesslogicapi/json/FizzReport.java | TristanPerry/java8-spring-cloud-microservice-demo | 40aabd99df746bc2447b2b1902fabb909ab03718 | [
"MIT"
] | null | null | null | business-logic-api/src/main/java/com/tristanperry/microservices/businesslogicapi/json/FizzReport.java | TristanPerry/java8-spring-cloud-microservice-demo | 40aabd99df746bc2447b2b1902fabb909ab03718 | [
"MIT"
] | 18 | 2018-01-05T03:05:57.000Z | 2022-03-02T16:25:32.000Z | 23.511111 | 80 | 0.662571 | 10,980 | package com.tristanperry.microservices.businesslogicapi.json;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.tristanperry.microservices.commonresourceservices.json.FizzReportRow;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FizzReport {
private FizzBuzzJson fizzBuzz;
private FizzReportRow reportRow;
public FizzReport() {
}
public FizzReport(FizzBuzzJson fizzBuzz, FizzReportRow reportRow) {
this.fizzBuzz = fizzBuzz;
this.reportRow = reportRow;
}
public FizzBuzzJson getFizzBuzz() {
return fizzBuzz;
}
public void setFizzBuzz(FizzBuzzJson fizzBuzz) {
this.fizzBuzz = fizzBuzz;
}
public FizzReportRow getReportRow() {
return reportRow;
}
public void setReportRow(FizzReportRow reportRow) {
this.reportRow = reportRow;
}
@Override
public String toString() {
return "FizzReportRow{" +
"fizzBuzz=" + fizzBuzz +
", reportRow=" + reportRow +
'}';
}
}
|
3e19df6fa9c964aae18faf6748ec66833d097ad8 | 3,265 | java | Java | app/src/main/java/com/abhijitsinha/smartinput/wifikeyboardandmouse/controller/impl/KeyValue.java | AbhijitSinha1/Wifi-Keyboard-Mouse-Android | aecec4f1cde849c0fd26b4c73ffc8bc13413c6f7 | [
"Apache-2.0"
] | 1 | 2020-03-26T12:56:02.000Z | 2020-03-26T12:56:02.000Z | app/src/main/java/com/abhijitsinha/smartinput/wifikeyboardandmouse/controller/impl/KeyValue.java | AbhijitSinha1/Wifi-Keyboard-Mouse-Android | aecec4f1cde849c0fd26b4c73ffc8bc13413c6f7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/abhijitsinha/smartinput/wifikeyboardandmouse/controller/impl/KeyValue.java | AbhijitSinha1/Wifi-Keyboard-Mouse-Android | aecec4f1cde849c0fd26b4c73ffc8bc13413c6f7 | [
"Apache-2.0"
] | 1 | 2019-12-08T14:51:38.000Z | 2019-12-08T14:51:38.000Z | 29.954128 | 220 | 0.614089 | 10,981 | package com.abhijitsinha.smartinput.wifikeyboardandmouse.controller.impl;
import android.view.KeyEvent;
import com.abhijitsinha.smartinput.wifikeyboardandmouse.controller.CommandValue;
public class KeyValue implements CommandValue {
private final int keyCode;
private boolean isShiftPressed;
private boolean isAltPressed;
private boolean isCtrlPressed;
private boolean isNumLockPressed;
private boolean isScrollLockPressed;
private boolean isFunctionPressed;
private boolean isMetaPressed;
private boolean isSymPressed;
private boolean isCapsLockPressed;
private boolean isPrintKeyPressed;
private KeyValue(int keyCode) {
this.keyCode = keyCode;
}
public int getKeyCode() {
return keyCode;
}
public boolean isAltPressed() {
return isAltPressed;
}
public boolean isCtrlPressed() {
return isCtrlPressed;
}
public boolean isCapsLockPressed() {
return isCapsLockPressed;
}
public boolean isFunctionPressed() {
return isFunctionPressed;
}
public boolean isMetaPressed() {
return isMetaPressed;
}
public boolean isNumLockPressed() {
return isNumLockPressed;
}
public boolean isPrintKeyPressed() {
return isPrintKeyPressed;
}
public boolean isScrollLockPressed() {
return isScrollLockPressed;
}
public boolean isShiftPressed() {
return isShiftPressed;
}
public boolean isSymPressed() {
return isSymPressed;
}
public static KeyValue of(KeyEvent event) {
int keyChar = event.getUnicodeChar();
KeyValue value = new KeyValue(keyChar);
if (keyChar == 0) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DEL: {
}
break;
case KeyEvent.KEYCODE_FORWARD_DEL: {
}
break;
case KeyEvent.KEYCODE_3: {
}
break;
case KeyEvent.KEYCODE_8: {
}
break;
case KeyEvent.KEYCODE_9: {
}
break;
}
}
value.isAltPressed = event.isAltPressed();
value.isCapsLockPressed = event.isCapsLockOn();
value.isCtrlPressed = event.isCtrlPressed();
value.isFunctionPressed = event.isFunctionPressed();
value.isMetaPressed = event.isMetaPressed();
value.isNumLockPressed = event.isNumLockOn();
value.isPrintKeyPressed = event.isPrintingKey();
value.isScrollLockPressed = event.isScrollLockOn();
value.isShiftPressed = event.isShiftPressed();
value.isSymPressed = event.isSymPressed();
return value;
}
@Override
public String toString() {
return String.format("{\"keyCode\": %s, \"alt\": %s, \"caps\": %s, \"ctrl\": %s, \"fn\": %s, \"meta\": %s, \"num\": %s, \"print\": %s, \"scroll\": %s, \"shift\": %s, \"sym\": %s}",
getKeyCode(), isAltPressed(), isCapsLockPressed(), isCtrlPressed(), isFunctionPressed(), isMetaPressed(), isNumLockPressed(), isPrintKeyPressed(), isScrollLockPressed(), isShiftPressed(), isSymPressed());
}
}
|
3e19df70a7d9b550765ca5c612f629ee42b02a25 | 499 | java | Java | src/main/java/org/scribe/builder/api/SimpleGeoApi.java | ohimors/scribe-java | a496ef3c7970908fbb17686bef343d8234166dd2 | [
"MIT"
] | 4 | 2015-01-30T12:55:10.000Z | 2021-08-24T12:21:58.000Z | src/main/java/org/scribe/builder/api/SimpleGeoApi.java | creativeprogramming/scribe-java | f4c36ab27abe3dde4649bfd935aab04b25078d9b | [
"MIT"
] | 1 | 2017-03-12T19:22:46.000Z | 2017-03-15T19:52:57.000Z | src/main/java/org/scribe/builder/api/SimpleGeoApi.java | creativeprogramming/scribe-java | f4c36ab27abe3dde4649bfd935aab04b25078d9b | [
"MIT"
] | 10 | 2017-01-10T20:47:59.000Z | 2019-04-12T01:37:50.000Z | 16.633333 | 98 | 0.749499 | 10,982 | package org.scribe.builder.api;
import org.scribe.model.Token;
/**
* @author: Pablo Fernandez
*/
public class SimpleGeoApi extends DefaultApi10a
{
private static final String ENDPOINT = "these are not used since SimpleGeo uses 2 legged OAuth";
@Override
public String getRequestTokenEndpoint()
{
return ENDPOINT;
}
@Override
public String getAccessTokenEndpoint()
{
return ENDPOINT;
}
@Override
public String getAuthorizationUrl(Token requestToken)
{
return ENDPOINT;
}
}
|
3e19df9d2b6ba82eb428ec03a0b89adb044a17eb | 669 | java | Java | usbSerialForAndroid/src/androidTest/java/com/hoho/somewear/usbserial/driver/ProlificWrapper.java | someweardev/usb-serial-for-android | 3febbac689b7855cedc0d73ac0130a01d37bdf1d | [
"MIT"
] | null | null | null | usbSerialForAndroid/src/androidTest/java/com/hoho/somewear/usbserial/driver/ProlificWrapper.java | someweardev/usb-serial-for-android | 3febbac689b7855cedc0d73ac0130a01d37bdf1d | [
"MIT"
] | null | null | null | usbSerialForAndroid/src/androidTest/java/com/hoho/somewear/usbserial/driver/ProlificWrapper.java | someweardev/usb-serial-for-android | 3febbac689b7855cedc0d73ac0130a01d37bdf1d | [
"MIT"
] | null | null | null | 47.785714 | 122 | 0.80867 | 10,983 | package com.hoho.somewear.usbserial.driver;
public class ProlificWrapper {
public static boolean isDeviceTypeT(UsbSerialPort serialPort) {
ProlificSerialDriver.ProlificSerialPort prolificSerialPort = (ProlificSerialDriver.ProlificSerialPort) serialPort;
return prolificSerialPort.mDeviceType == ProlificSerialDriver.DeviceType.DEVICE_TYPE_T;
}
public static boolean isDeviceTypeHxn(UsbSerialPort serialPort) {
ProlificSerialDriver.ProlificSerialPort prolificSerialPort = (ProlificSerialDriver.ProlificSerialPort) serialPort;
return prolificSerialPort.mDeviceType == ProlificSerialDriver.DeviceType.DEVICE_TYPE_HXN;
}
}
|
3e19e1445d444d869b1f451a8cec17c4e47817cf | 2,069 | java | Java | BAEKJOON11053/src/Main.java | jerry88kim/algorithm | b860fda53b7a5efc87dd21217c5b25cf313e2ec2 | [
"MIT"
] | null | null | null | BAEKJOON11053/src/Main.java | jerry88kim/algorithm | b860fda53b7a5efc87dd21217c5b25cf313e2ec2 | [
"MIT"
] | null | null | null | BAEKJOON11053/src/Main.java | jerry88kim/algorithm | b860fda53b7a5efc87dd21217c5b25cf313e2ec2 | [
"MIT"
] | 1 | 2019-01-04T11:45:20.000Z | 2019-01-04T11:45:20.000Z | 24.630952 | 81 | 0.659739 | 10,985 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
static int N;
static int A[] = new int[1000];
static int tails[];
static int lowerBound(int left, int right, int key) {
int med;
while (left < right) {
med = (left + right) / 2;
if (tails[med] >= key) right = med;
else left = med + 1;
}
return right;
}
public static void main (String [] args) throws Exception {
System.setIn(new FileInputStream("C:\\Users\\YOUNGJOO KIM\\sample_input.txt"));
MyScanner sc = new MyScanner(System.in, System.out);
N = sc.nextInt();
tails = new int[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextInt();
}
// 초기값
tails[0] = A[0];
int length = 1;
for (int i = 1; i < N; i++) {
if (A[i] > tails[length-1]) {
// Case 1. ai가 tails의 마지막 값보다 큰 경우 tails에 ai를 추가한다.
tails[length++] = A[i];
} else {
// Case 2. ai가 tails의 마지막 값보다 작은 경우 tails 값들 중 ai의 lowerBound 위치를 찾아 값을 갱신한다.
tails[lowerBound(0, length-1, A[i])] = A[i];
}
}
System.out.println(length);
sc.close();
}
static class MyScanner {
BufferedReader reader;
BufferedWriter writer;
StringTokenizer tokenizer;
MyScanner(InputStream in, OutputStream out) throws IOException {
reader = new BufferedReader(new InputStreamReader(in));
writer = new BufferedWriter(new OutputStreamWriter(out));
tokenizer = new StringTokenizer(reader.readLine());
}
public String nextString() throws IOException {
if (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextString());
}
public void close() throws IOException {
writer.flush();
writer.close();
reader.close();
}
}
} |
3e19e1b4277c1ee91627824663ca31e36aef889c | 167 | java | Java | highcharts/src/main/java/us/ascendtech/highcharts/client/chartoptions/chart/functions/OnEnd.java | nagin/gwt-highcharts | 8604726f703e0705f1cf6a085abf5dc867d12965 | [
"Apache-2.0"
] | 7 | 2018-08-16T14:10:32.000Z | 2019-11-19T15:32:14.000Z | highcharts/src/main/java/us/ascendtech/highcharts/client/chartoptions/chart/functions/OnEnd.java | nagin/gwt-highcharts | 8604726f703e0705f1cf6a085abf5dc867d12965 | [
"Apache-2.0"
] | 1 | 2019-11-06T08:59:14.000Z | 2019-11-06T16:05:57.000Z | highcharts/src/main/java/us/ascendtech/highcharts/client/chartoptions/chart/functions/OnEnd.java | nagin/gwt-highcharts | 8604726f703e0705f1cf6a085abf5dc867d12965 | [
"Apache-2.0"
] | 4 | 2019-07-01T12:51:35.000Z | 2022-03-10T10:08:27.000Z | 18.555556 | 69 | 0.814371 | 10,986 | package us.ascendtech.highcharts.client.chartoptions.chart.functions;
import jsinterop.annotations.JsFunction;
@JsFunction
public interface OnEnd {
void onEnd();
}
|
3e19e1ef1568121d9717ae11ecb84708533d7c29 | 3,540 | java | Java | example/src/main/java/com/woodblockwithoutco/beretainedexample/widget/support/RecyclerViewFragment.java | DrBreen/BeRetained | 1891785f946448580e866b6508a9506a1d1c2023 | [
"Apache-2.0"
] | 19 | 2016-07-10T09:24:31.000Z | 2018-08-23T11:55:49.000Z | example/src/main/java/com/woodblockwithoutco/beretainedexample/widget/support/RecyclerViewFragment.java | DrBreen/BeRetained | 1891785f946448580e866b6508a9506a1d1c2023 | [
"Apache-2.0"
] | null | null | null | example/src/main/java/com/woodblockwithoutco/beretainedexample/widget/support/RecyclerViewFragment.java | DrBreen/BeRetained | 1891785f946448580e866b6508a9506a1d1c2023 | [
"Apache-2.0"
] | null | null | null | 31.327434 | 103 | 0.684181 | 10,987 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.woodblockwithoutco.beretainedexample.widget.support;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.woodblockwithoutco.beretainedexample.R;
/**
* Simple Fragment that contains RecyclerView with simple TextView items with data
* from CharSequence array.
*/
public class RecyclerViewFragment extends Fragment {
private RecyclerView mRecyclerView;
private CharSequence[] mItems;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Context parentContext = container.getContext();
View v = inflater.inflate(R.layout.fragment_recycler_view, container, false);
mRecyclerView = (RecyclerView) v;
mRecyclerView.setLayoutManager(new LinearLayoutManager(parentContext));
SimpleAdapter adapter = new SimpleAdapter();
mRecyclerView.setAdapter(adapter);
if(mItems != null) {
adapter.setItems(mItems);
}
return v;
}
public void setItems(CharSequence[] items) {
mItems = items;
if(mRecyclerView != null) {
SimpleAdapter adapter = (SimpleAdapter) mRecyclerView.getAdapter();
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
}
static class SimpleAdapter extends RecyclerView.Adapter<SimpleHolder> {
private CharSequence[] mItems;
public void setItems(CharSequence[] items) {
mItems = items;
}
@Override
public SimpleHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.simple_recyclerview_item, parent, false);
SimpleHolder holder = new SimpleHolder(view);
return holder;
}
@Override
public void onBindViewHolder(SimpleHolder holder, int position) {
holder.getTextView().setText(mItems[position]);
}
@Override
public int getItemCount() {
return mItems != null ? mItems.length : 0;
}
}
static class SimpleHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
public SimpleHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView;
}
public TextView getTextView() {
return mTextView;
}
}
}
|
3e19e200eae4e4f453c3a3ac80a53206f3d7c587 | 1,836 | java | Java | clustermate-dropwizard/src/main/java/com/fasterxml/clustermate/jaxrs/JaxrsHttpRequest.java | cowtowncoder/ClusterMate | a2609b2d2f7884acbf0e0a114d98226886dc41d0 | [
"Apache-2.0"
] | 4 | 2015-07-02T11:49:57.000Z | 2017-08-12T11:12:09.000Z | clustermate-dropwizard/src/main/java/com/fasterxml/clustermate/jaxrs/JaxrsHttpRequest.java | cowtowncoder/ClusterMate | a2609b2d2f7884acbf0e0a114d98226886dc41d0 | [
"Apache-2.0"
] | null | null | null | clustermate-dropwizard/src/main/java/com/fasterxml/clustermate/jaxrs/JaxrsHttpRequest.java | cowtowncoder/ClusterMate | a2609b2d2f7884acbf0e0a114d98226886dc41d0 | [
"Apache-2.0"
] | null | null | null | 28.6875 | 100 | 0.65305 | 10,988 | package com.fasterxml.clustermate.jaxrs;
import java.io.*;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import com.fasterxml.clustermate.api.OperationType;
import com.fasterxml.clustermate.service.ServiceRequest;
public class JaxrsHttpRequest extends ServiceRequest
{
protected final UriInfo _uriInfo;
protected final HttpHeaders _headers;
protected MultivaluedMap<String, String> _headerValues;
protected MultivaluedMap<String, String> _qp;
public JaxrsHttpRequest(UriInfo uriInfo, HttpHeaders headers, String decodedPath,
String operationType)
{
this(uriInfo, headers, decodedPath, _resolveOperation(operationType, OperationType.CUSTOM));
}
public JaxrsHttpRequest(UriInfo uriInfo, HttpHeaders headers, String decodedPath,
OperationType operationType)
{
super(decodedPath, true, operationType);
_uriInfo = uriInfo;
_headers = headers;
}
@Override
public InputStream getNativeInputStream() throws IOException {
// must be directly assigned...
throw new IOException("No InputStream available via "+getClass().getName()+" instance");
}
@Override
public String getQueryParameter(String key) {
if (_qp == null) {
_qp = _uriInfo.getQueryParameters();
if (_qp == null) {
return null;
}
}
return _qp.getFirst(key);
}
@Override
public String getHeader(String key) {
if (_headerValues == null) {
_headerValues = (_headers == null)? null : _headers.getRequestHeaders();
if (_headerValues == null) {
return null;
}
}
return _headerValues.getFirst(key);
}
}
|
3e19e2644919c26a940b800833898d2b8e39c9af | 1,729 | java | Java | src/main/java/com/me/dao/CourseDao.java | Thomastakovich/Boom | c5a2d76efc21fd1b0fafee5bcc5dea2a22b5e5c5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/me/dao/CourseDao.java | Thomastakovich/Boom | c5a2d76efc21fd1b0fafee5bcc5dea2a22b5e5c5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/me/dao/CourseDao.java | Thomastakovich/Boom | c5a2d76efc21fd1b0fafee5bcc5dea2a22b5e5c5 | [
"Apache-2.0"
] | null | null | null | 25.057971 | 143 | 0.700405 | 10,989 | package com.me.dao;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.query.Query;
import com.me.pojo.Course;
import com.me.pojo.Student;
import com.me.pojo.Teacher;
public class CourseDao extends DAO {
public List<Course> browseCourses() {
String hql = "FROM Course";
Query query = getSession().createQuery(hql);
System.out.println(query.getQueryString());
return (List<Course>) query.getResultList();
}
public Course createCourse(String name, Date startDate, Date endDate, String startTime, String endTime, String description) throws Exception {
try {
begin();
Course c = new Course(name, startDate, endDate, startTime, endTime, description);
getSession().save(c);
commit();
return c;
} catch (HibernateException e) {
throw new Exception("Could not create course ", e);
}
}
public Course getCourseById(String id) {
String hql = "FROM Course WHERE id=:id";
Query query = getSession().createQuery(hql);
query.setString("id", id);
return (Course) query.uniqueResult();
}
public void dropStudent(String studentId, String courseId) {
Course c = getCourseById(courseId);
Iterator<Student> iterator = c.getStudents().iterator();
while (iterator.hasNext()) {
Student s = iterator.next();
if (s.getId().equals(studentId)) {
iterator.remove();
}
}
}
public void assignTeacher(String courseId, String teacherId, TeacherDao dao) {
try {
begin();
Course c = getCourseById(courseId);
Teacher t = dao.getTeacherById(teacherId);
c.setTeacher(t);
commit();
} catch (HibernateException e) {
System.out.println("RollBack");
rollback();
}
}
}
|
3e19e2fd8c9489ad51c7fe264a8a6e9dbb981fe5 | 5,733 | java | Java | jeecg-boot/jeecg-boot-module-shop/src/main/java/org/jeecg/modules/shop/controller/JournalAccountController.java | Aaronqcd/ShopBSBSystem | 2a13c7dc1cd7a31353399ff2f2d22e9e677ee36d | [
"Apache-2.0"
] | null | null | null | jeecg-boot/jeecg-boot-module-shop/src/main/java/org/jeecg/modules/shop/controller/JournalAccountController.java | Aaronqcd/ShopBSBSystem | 2a13c7dc1cd7a31353399ff2f2d22e9e677ee36d | [
"Apache-2.0"
] | 5 | 2021-05-28T19:39:17.000Z | 2022-02-19T06:17:03.000Z | jeecg-boot/jeecg-boot-module-shop/src/main/java/org/jeecg/modules/shop/controller/JournalAccountController.java | Aaronqcd/ShopBSBSystem | 2a13c7dc1cd7a31353399ff2f2d22e9e677ee36d | [
"Apache-2.0"
] | null | null | null | 30.173684 | 117 | 0.73888 | 10,990 | package org.jeecg.modules.shop.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.shop.entity.JournalAccount;
import org.jeecg.modules.shop.service.IJournalAccountService;
import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.util.ToolsUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @Description: 资金流水
* @Author: jeecg-boot
* @Date: 2020-01-01
* @Version: V1.0
*/
@Slf4j
@Api(tags="资金流水")
@RestController
@RequestMapping("/journalAccount")
public class JournalAccountController extends JeecgController<JournalAccount, IJournalAccountService> {
@Autowired
private IJournalAccountService journalAccountService;
/**
* 分页列表查询
*
* @param journalAccount
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@AutoLog(value = "资金流水-分页列表查询")
@ApiOperation(value="资金流水-分页列表查询", notes="资金流水-分页列表查询")
@GetMapping(value = "/list")
public Result<?> queryPageList(JournalAccount journalAccount,
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JournalAccount> queryWrapper = QueryGenerator.initQueryWrapper(journalAccount, req.getParameterMap());
Page<JournalAccount> page = new Page<JournalAccount>(pageNo, pageSize);
IPage<JournalAccount> pageList = journalAccountService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 添加
*
* @param journalAccount
* @return
*/
@AutoLog(value = "资金流水-添加")
@ApiOperation(value="资金流水-添加", notes="资金流水-添加")
@PostMapping(value = "/add")
public Result<?> add(@RequestBody JournalAccount journalAccount) {
journalAccountService.save(journalAccount);
return Result.ok("添加成功!");
}
/**
* 生成10位纯数字的资金流水业务编号
* @return
*/
@AutoLog(value = "资金流水-生成资金流水业务编号")
@ApiOperation(value="资金流水-生成资金流水业务编号", notes="资金流水-生成资金流水业务编号")
@GetMapping(value = "/getBusinessNo")
public Result<?> getBusinessNo() {
String businessNo;
QueryWrapper queryWrapper;
JournalAccount journalAccount;
//保证资金流水业务编号不能重复
do {
businessNo = ToolsUtil.getRandomNo(10);
queryWrapper = new QueryWrapper();
queryWrapper.eq("business_no", businessNo);
journalAccount = journalAccountService.getOne(queryWrapper);
} while(journalAccount != null);
return Result.ok(businessNo);
}
/**
* 编辑
*
* @param journalAccount
* @return
*/
@AutoLog(value = "资金流水-编辑")
@ApiOperation(value="资金流水-编辑", notes="资金流水-编辑")
@PutMapping(value = "/edit")
public Result<?> edit(@RequestBody JournalAccount journalAccount) {
journalAccountService.updateById(journalAccount);
return Result.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "资金流水-通过id删除")
@ApiOperation(value="资金流水-通过id删除", notes="资金流水-通过id删除")
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name="id",required=true) String id) {
journalAccountService.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "资金流水-批量删除")
@ApiOperation(value="资金流水-批量删除", notes="资金流水-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
this.journalAccountService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "资金流水-通过id查询")
@ApiOperation(value="资金流水-通过id查询", notes="资金流水-通过id查询")
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
JournalAccount journalAccount = journalAccountService.getById(id);
return Result.ok(journalAccount);
}
/**
* 导出excel
*
* @param request
* @param journalAccount
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, JournalAccount journalAccount) {
return super.exportXls(request, journalAccount, JournalAccount.class, "资金流水");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, JournalAccount.class);
}
}
|
3e19e33e463156269cfc4d0f325f1c41ac76dff8 | 26,083 | java | Java | drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/kie/builder/impl/KieModuleRepoTest.java | Ginxo/drools | 553d4f381eb276e73d4e008b7ccfad94f04fe651 | [
"Apache-2.0"
] | 3,631 | 2017-03-14T08:54:05.000Z | 2022-03-31T19:59:10.000Z | drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/kie/builder/impl/KieModuleRepoTest.java | Ginxo/drools | 553d4f381eb276e73d4e008b7ccfad94f04fe651 | [
"Apache-2.0"
] | 2,274 | 2017-03-13T14:02:17.000Z | 2022-03-28T17:23:17.000Z | drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/kie/builder/impl/KieModuleRepoTest.java | Ginxo/drools | 553d4f381eb276e73d4e008b7ccfad94f04fe651 | [
"Apache-2.0"
] | 1,490 | 2017-03-14T11:37:37.000Z | 2022-03-31T08:50:22.000Z | 42.899671 | 159 | 0.676418 | 10,991 | package org.drools.mvel.compiler.kie.builder.impl;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.drools.compiler.kie.builder.impl.BuildContext;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kie.builder.impl.KieContainerImpl;
import org.drools.compiler.kie.builder.impl.KieModuleKieProject;
import org.drools.compiler.kie.builder.impl.KieProject;
import org.drools.compiler.kie.builder.impl.KieRepositoryImpl;
import org.drools.compiler.kie.builder.impl.KieRepositoryImpl.KieModuleRepo;
import org.drools.compiler.kproject.models.KieBaseModelImpl;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.io.internal.InternalResource;
import org.drools.reflective.ResourceProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.ReleaseIdComparator.ComparableVersion;
import org.kie.api.builder.Results;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.definition.KiePackage;
import org.kie.api.io.ResourceConfiguration;
import org.kie.internal.builder.CompositeKnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderConfiguration;
import org.kie.internal.builder.ResourceChangeSet;
import org.kie.util.maven.support.DependencyFilter;
import org.kie.util.maven.support.PomModel;
import org.kie.util.maven.support.ReleaseIdImpl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* This test contains
* - normal tests that test for concurrency issues and memory leaks (that the KieModuleRepo
* functions as a LRU cache, and evicts old {@link KieModule} instances )
*/
public class KieModuleRepoTest {
private KieModuleRepo kieModuleRepo;
private int maxSizeGaCacheOrig;
private int maxSizeGaVersionsCacheOrig;
private Field maxSizeGaCacheField;
private Field maxSizeGaVersionsCacheField;
@Before
public void before() throws Exception {
kieModuleRepo = new KieModuleRepo();
// store the original values as we need to restore them after the test
maxSizeGaCacheOrig = KieModuleRepo.MAX_SIZE_GA_CACHE;
maxSizeGaVersionsCacheOrig = KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE;
maxSizeGaCacheField = KieModuleRepo.class.getDeclaredField("MAX_SIZE_GA_CACHE");
maxSizeGaVersionsCacheField = KieModuleRepo.class.getDeclaredField("MAX_SIZE_GA_VERSIONS_CACHE");
}
@After
public void after() throws Exception {
setCacheSize(maxSizeGaCacheField, null, maxSizeGaCacheOrig);
setCacheSize(maxSizeGaVersionsCacheField, null, maxSizeGaVersionsCacheOrig);
}
/**
* HELPER METHODS -------------------------------------------------------------------------------------------------------------
*/
protected static void waitFor(final CyclicBarrier barrier) {
final String threadName = Thread.currentThread().getName();
try {
barrier.await();
} catch( final InterruptedException e ) {
fail( "Thread '" + threadName + "' was interrupted while waiting for the other threads!");
} catch( final BrokenBarrierException e ) {
fail( "Thread '" + threadName + "' barrier was broken while waiting for the other threads!");
}
}
private static KieContainerImpl createMockKieContainer( final ReleaseId projectReleaseId, final KieModuleRepo kieModuleRepo) throws Exception {
// kie module
final InternalKieModule mockKieProjectKieModule = mock(InternalKieModule.class);
final ResourceProvider mockKieProjectKieModuleResourceProvider = mock(ResourceProvider.class);
when(mockKieProjectKieModule.createResourceProvider()).thenReturn(mockKieProjectKieModuleResourceProvider);
// kie project
final KieModuleKieProject kieProject = new KieModuleKieProject(mockKieProjectKieModule);
final KieModuleKieProject mockKieProject = spy(kieProject);
doNothing().when(mockKieProject).init();
doReturn(projectReleaseId).when(mockKieProject).getGAV();
doReturn( new HashMap<String, KieBaseModel>() ).when( mockKieProject ).updateToModule( any( InternalKieModule.class ) );
// kie repository
final KieRepository kieRepository = new KieRepositoryImpl();
final Field kieModuleRepoField = KieRepositoryImpl.class.getDeclaredField("kieModuleRepo");
kieModuleRepoField.setAccessible(true);
kieModuleRepoField.set(kieRepository, kieModuleRepo);
kieModuleRepoField.setAccessible(false);
// kie container
final KieContainerImpl kieContainerImpl = new KieContainerImpl(mockKieProject, kieRepository);
return kieContainerImpl;
}
private static int countKieModules( final Map<String, NavigableMap<ComparableVersion, KieModule>> kieModulesCache ) {
int numKieModules = 0;
for( final NavigableMap<ComparableVersion, KieModule> map : kieModulesCache.values() ) {
numKieModules += map.size();
}
return numKieModules;
}
private static void setCacheSize( final Field field, final Object fieldObject, final Object newValue ) throws Exception {
// make accessible
field.setAccessible(true);
field.set(null, newValue);
field.set(fieldObject, newValue);
}
/**
* TESTS ----------------------------------------------------------------------------------------------------------------------
*/
// simultaneous requests to deploy two new deployments (different versions)
// for an empty/new GA artifactMap
@Test(timeout=5000)
public void testDeployTwoArtifactVersionsSameTime() throws Exception {
final String groupId = "org";
final String artifactId = "one";
final String firstVersion = "1.0";
final String secondVersion = "1.0-NEW-FEATURE";
final CyclicBarrier storeOperationBarrier = new CyclicBarrier(2);
final CyclicBarrier threadsFinishedBarrier = new CyclicBarrier(3);
final Thread firstThread = new Thread(
getStoreArtifactRunnable(kieModuleRepo, groupId, artifactId, firstVersion,
storeOperationBarrier, threadsFinishedBarrier));
final Thread secondThread = new Thread(
getStoreArtifactRunnable(kieModuleRepo, groupId, artifactId, secondVersion,
storeOperationBarrier, threadsFinishedBarrier));
final ExecutorService executor = Executors.newFixedThreadPool(2);
try {
firstThread.setName("normal");
executor.submit(firstThread);
secondThread.setName("newFeature");
executor.submit(secondThread);
waitFor(threadsFinishedBarrier);
} finally {
executor.shutdownNow();
}
final String ga = groupId + ":" + artifactId;
final Map<ComparableVersion, KieModule> artifactMap = kieModuleRepo.kieModules.get(ga);
final ComparableVersion normalVersion = new ComparableVersion(firstVersion);
final KieModule normalKieModule = artifactMap.get(normalVersion);
final ComparableVersion newFeatureVersion = new ComparableVersion(secondVersion);
final KieModule newFeatureKieModule = artifactMap.get(newFeatureVersion);
assertNotNull( "Race condition occurred: normal KieModule disappeared from KieModuleRepo!", normalKieModule);
assertNotNull( "Race condition occurred: new feature KieModule disappeared from KieModuleRepo!", newFeatureKieModule);
}
public Runnable getStoreArtifactRunnable(final KieModuleRepo kieModuleRepo, final String groupId, final String artifactId,
final String version, final CyclicBarrier storeOperationBarrier, final CyclicBarrier threadsFinishedBarrier) {
return () -> {
final ReleaseIdImpl firstReleaseId = new ReleaseIdImpl(groupId, artifactId, version);
final KieModule firstKieModule = mock(KieModule.class);
when(firstKieModule.getReleaseId()).thenReturn(firstReleaseId);
waitFor(storeOperationBarrier);
kieModuleRepo.store(firstKieModule);
waitFor(threadsFinishedBarrier);
};
}
// remove request followed by a store request on a high load system
// * remove does not completely finish before store starts
@Test(timeout=5000)
public void removeStoreArtifactMapTest() throws Exception {
// actual test
final ReleaseIdImpl releaseId = new ReleaseIdImpl("org", "redeploy", "2.0");
final InternalKieModule originalKieModule = mock(InternalKieModule.class);
when(originalKieModule.getReleaseId()).thenReturn(releaseId);
when(originalKieModule.getCreationTimestamp()).thenReturn(0l);
final InternalKieModule redeployKieModule = mock(InternalKieModule.class);
when(redeployKieModule.getReleaseId()).thenReturn(releaseId);
when(redeployKieModule.getCreationTimestamp()).thenReturn(1l);
// 1. initial deploy ("long ago")
kieModuleRepo.store(originalKieModule);
final CyclicBarrier storeRemoveOperationBarrier = new CyclicBarrier(2);
final CyclicBarrier operationsSerializationBarrier = new CyclicBarrier(2);
final CyclicBarrier threadsFinishedBarrier = new CyclicBarrier(3);
final Runnable removeRunnable = () -> {
waitFor(storeRemoveOperationBarrier);
kieModuleRepo.remove(releaseId);
waitFor(operationsSerializationBarrier);
waitFor(threadsFinishedBarrier);
};
final Runnable redeployRunnable = () -> {
waitFor(storeRemoveOperationBarrier);
waitFor(operationsSerializationBarrier);
kieModuleRepo.store(redeployKieModule);
waitFor(threadsFinishedBarrier);
};
final ExecutorService executor = Executors.newFixedThreadPool(2);
try {
// 2. remove and redploy
executor.submit(removeRunnable);
executor.submit(redeployRunnable);
waitFor(threadsFinishedBarrier);
} finally {
executor.shutdownNow();
}
final String ga = releaseId.getGroupId() + ":" + releaseId.getArtifactId();
final Map<ComparableVersion, KieModule> artifactMap = kieModuleRepo.kieModules.get(ga);
assertNotNull( "Artifact Map for GA '" + ga + "' not in KieModuleRepo!", artifactMap);
// never gets this far, but this is a good check
final KieModule redeployedKieModule = artifactMap.get(new ComparableVersion(releaseId.getVersion()));
assertNotNull( "Redeployed module has disappeared from KieModuleRepo!", redeployedKieModule);
assertEquals( "Original module retrieved instead of redeployed module!",
1l, redeployKieModule.getCreationTimestamp() );
}
private static class InternalKieModuleStub implements InternalKieModule {
@Override
public void cacheKnowledgeBuilderForKieBase( String kieBaseName, KnowledgeBuilder kbuilder ) {
throw new UnsupportedOperationException();
}
@Override
public KnowledgeBuilder getKnowledgeBuilderForKieBase( String kieBaseName ) {
throw new UnsupportedOperationException();
}
@Override
public InternalKnowledgePackage getPackage( String packageName) {
throw new UnsupportedOperationException();
}
@Override
public Collection<KiePackage> getKnowledgePackagesForKieBase( String kieBaseName ) {
throw new UnsupportedOperationException();
}
@Override
public void cacheResultsForKieBase( String kieBaseName, Results results ) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, Results> getKnowledgeResultsCache() {
throw new UnsupportedOperationException();
}
@Override
public KieModuleModel getKieModuleModel() {
return null;
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasResource( String fileName ) {
throw new UnsupportedOperationException();
}
@Override
public InternalResource getResource( String fileName ) {
throw new UnsupportedOperationException();
}
@Override
public ResourceConfiguration getResourceConfiguration( String fileName ) {
throw new UnsupportedOperationException();
}
@Override
public Map<ReleaseId, InternalKieModule> getKieDependencies() {
throw new UnsupportedOperationException();
}
@Override
public void addKieDependency( InternalKieModule dependency ) {
throw new UnsupportedOperationException();
}
@Override
public Collection<ReleaseId> getJarDependencies( DependencyFilter filter ) {
throw new UnsupportedOperationException();
}
@Override
public Collection<ReleaseId> getUnresolvedDependencies() {
throw new UnsupportedOperationException();
}
@Override
public void setUnresolvedDependencies( Collection<ReleaseId> unresolvedDependencies ) {
throw new UnsupportedOperationException();
}
@Override
public boolean isAvailable( String pResourceName ) {
throw new UnsupportedOperationException();
}
@Override
public byte[] getBytes( String pResourceName ) {
throw new UnsupportedOperationException();
}
@Override
public Collection<String> getFileNames() {
return Collections.emptyList();
}
@Override
public File getFile() {
throw new UnsupportedOperationException();
}
@Override
public ResourceProvider createResourceProvider() {
throw new UnsupportedOperationException();
}
@Override
public Map<String, byte[]> getClassesMap() {
throw new UnsupportedOperationException();
}
@Override
public boolean addResourceToCompiler( CompositeKnowledgeBuilder ckbuilder, KieBaseModel kieBaseModel, String fileName ) {
throw new UnsupportedOperationException();
}
@Override
public boolean addResourceToCompiler( CompositeKnowledgeBuilder ckbuilder, KieBaseModel kieBaseModel, String fileName, ResourceChangeSet rcs ) {
throw new UnsupportedOperationException();
}
@Override
public long getCreationTimestamp() {
return 0L;
}
@Override
public InputStream getPomAsStream() {
throw new UnsupportedOperationException();
}
@Override
public PomModel getPomModel() {
throw new UnsupportedOperationException();
}
@Override
public KnowledgeBuilderConfiguration createBuilderConfiguration( KieBaseModel kBaseModel, ClassLoader classLoader ) {
throw new UnsupportedOperationException();
}
@Override
public InternalKnowledgeBase createKieBase(KieBaseModelImpl kBaseModel, KieProject kieProject, BuildContext buildContext, KieBaseConfiguration conf ) {
throw new UnsupportedOperationException();
}
@Override
public ClassLoader getModuleClassLoader() {
return null;
}
@Override
public ReleaseId getReleaseId() {
return new ReleaseIdImpl("org", "deployTwiceAfterUpdateDependency", "1.0");
}
}
// 2. simultaneous deploy requests
// - multitenant UI
// - duplicate REST requests
@Test(timeout=5000)
public void newerVersionDeployOverwritesTest() throws Exception {
// setup
final ReleaseIdImpl releaseId = new ReleaseIdImpl("org", "deployTwiceAfterUpdateDependency", "1.0");
final InternalKieModule originalOldKieModule = new InternalKieModuleStub();
final ReleaseId dependentReleaseid = new ReleaseIdImpl("org", "deployTwiceAfterUpdate", "1.0");
final KieContainerImpl kieContainer = createMockKieContainer(dependentReleaseid, kieModuleRepo);
// 1. deploy
kieModuleRepo.store(originalOldKieModule);
// 2. another project is dependent on this project
kieContainer.updateDependencyToVersion(releaseId, releaseId);
final InternalKieModule newKieModule = mock(InternalKieModule.class);
when(newKieModule.getReleaseId()).thenReturn(releaseId);
when(newKieModule.getCreationTimestamp()).thenReturn(10l);
final CyclicBarrier storeOperationBarrier = new CyclicBarrier(2);
final CyclicBarrier storeSerializationBarrier = new CyclicBarrier(2);
final CyclicBarrier threadsFinishedBarrier = new CyclicBarrier(3);
final Runnable deployRunnable = () -> {
waitFor(storeOperationBarrier);
// Second thread waits with store until the first one finishes with it.
if (Thread.currentThread().getName().equals("two")) {
waitFor(storeSerializationBarrier);
}
kieModuleRepo.store(newKieModule);
if (Thread.currentThread().getName().equals("one")) {
waitFor(storeSerializationBarrier);
}
waitFor(threadsFinishedBarrier);
};
final ExecutorService executor = Executors.newFixedThreadPool(2);
try {
// 2. remove and redploy
final Thread deployThread = new Thread(deployRunnable);
deployThread.setName("one");
executor.submit(deployThread);
final Thread secondDeployThread = new Thread(deployRunnable);
secondDeployThread.setName("two");
executor.submit(secondDeployThread);
waitFor(threadsFinishedBarrier);
} finally {
executor.shutdownNow();
}
// never gets this far, but this is a good check
final KieModule oldKieModule = kieModuleRepo.oldKieModules.get(releaseId);
final long oldKieModuleTimeStamp = ((InternalKieModule) oldKieModule).getCreationTimestamp();
final long originalKieModuleTimestamp = originalOldKieModule.getCreationTimestamp();
assertEquals( "The old kie module in the repo is not the originally deployed module!",
originalKieModuleTimestamp, oldKieModuleTimeStamp);
}
@Test
public void storingNewProjectsCausesOldProjectEvictionFromKieModuleRepoTest() throws Exception {
// setup
setCacheSize(maxSizeGaCacheField, null, 3);
setCacheSize(maxSizeGaVersionsCacheField, null, 2); // to test oldKieModules caching
final ReleaseIdImpl [] releaseIds = new ReleaseIdImpl[7];
for( int i = 0; i < releaseIds.length; ++i ) {
final String artifactId = Character.toString((char)('A'+i));
releaseIds[i] = new ReleaseIdImpl("org", artifactId, "1.0");
}
// store
for( int i = 0; i < releaseIds.length; ++i ) {
final InternalKieModule kieModule = mock(InternalKieModule.class);
when(kieModule.getReleaseId()).thenReturn(releaseIds[i]);
when(kieModule.getCreationTimestamp()).thenReturn(10l);
kieModuleRepo.store(kieModule);
kieModuleRepo.store(kieModule); // store module 2 times to trigger storage to oldKieModules
}
final int numKieModules = countKieModules(kieModuleRepo.kieModules);
assertEquals( "KieModuleRepo cache should not grow past " + KieModuleRepo.MAX_SIZE_GA_CACHE + ": ",
KieModuleRepo.MAX_SIZE_GA_CACHE, numKieModules );
final int oldKieModulesSize = kieModuleRepo.oldKieModules.size();
final int max = KieModuleRepo.MAX_SIZE_GA_CACHE * KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE;
assertTrue( "KieModuleRepot old KieModules map is not limited in it's growth: " + oldKieModulesSize + " > " + max,
oldKieModulesSize <= max );
}
@Test
public void storingNewProjectVersionsCausesOldVersionEvictionFromKieModuleRepoTest() throws Exception {
// setup
setCacheSize(maxSizeGaCacheField, null, 2); // to test oldKieModules caching
setCacheSize(maxSizeGaVersionsCacheField, null, 3);
final ReleaseIdImpl [] releaseIds = new ReleaseIdImpl[7];
for( int i = 0; i < releaseIds.length; ++i ) {
releaseIds[i] = new ReleaseIdImpl("org", "test", "1." + i);
}
// store
for( int i = 0; i < releaseIds.length; ++i ) {
final InternalKieModule kieModule = mock(InternalKieModule.class);
when(kieModule.getReleaseId()).thenReturn(releaseIds[i]);
when(kieModule.getCreationTimestamp()).thenReturn(10l);
kieModuleRepo.store(kieModule);
kieModuleRepo.store(kieModule); // in order to trigger storage to oldKieModules
}
int numKieModules = countKieModules(kieModuleRepo.kieModules);
assertEquals( "KieModuleRepo cache should not grow past " + KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE + ": ",
KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE, numKieModules );
int oldKieModulesSize = kieModuleRepo.oldKieModules.size();
final int maxOldKieModules = KieModuleRepo.MAX_SIZE_GA_CACHE * KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE;
assertTrue( "KieModuleRepo old KieModules map is not limited in it's growth: " + oldKieModulesSize + " > " + maxOldKieModules,
oldKieModulesSize <= maxOldKieModules );
// store
for( int o = 0; o < 2; ++o ) {
// loop 2 times in order to trigger storage to oldKieModules
for( int i = 0; i < releaseIds.length; ++i ) {
final InternalKieModule kieModule = mock(InternalKieModule.class);
when(kieModule.getReleaseId()).thenReturn(releaseIds[i]);
when(kieModule.getCreationTimestamp()).thenReturn(10l);
kieModuleRepo.store(kieModule);
}
}
numKieModules = countKieModules(kieModuleRepo.kieModules);
assertEquals( "KieModuleRepo cache should not grow past " + KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE + ": ",
KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE, numKieModules );
oldKieModulesSize = kieModuleRepo.oldKieModules.size();
assertTrue( "KieModuleRepo old KieModules map is not limited in it's growth: " + oldKieModulesSize + " > " + maxOldKieModules,
oldKieModulesSize <= maxOldKieModules );
}
@Test
public void testOldKieModulesLRUCache() throws Exception {
// setup
setCacheSize(maxSizeGaCacheField, null, 2);
setCacheSize(maxSizeGaVersionsCacheField, null, 4);
final ReleaseIdImpl [] releaseIds = new ReleaseIdImpl[9];
for( int i = 0; i < releaseIds.length; ++i ) {
final String artifactId = Character.toString((char)('A'+i/2));
releaseIds[i] = new ReleaseIdImpl("org", artifactId, "1." + i);
}
// store
for( int i = 0; i < releaseIds.length; ++i ) {
final InternalKieModule kieModule = mock(InternalKieModule.class);
when(kieModule.getReleaseId()).thenReturn(releaseIds[i]);
when(kieModule.getCreationTimestamp()).thenReturn(10l);
kieModuleRepo.store(kieModule);
kieModuleRepo.store(kieModule); // in order to trigger storage to oldKieModules
}
int maxSameGAModules = 0;
int maxGAs = 0;
for( final Map<ComparableVersion, KieModule> artifactMap : kieModuleRepo.kieModules.values() ) {
maxGAs++;
if( artifactMap.size() > maxSameGAModules ) {
maxSameGAModules = artifactMap.size();
}
}
assertTrue( "The maximum of artifacts per GA should not grow past " + KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE + ": "
+ KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE + " < " + maxSameGAModules,
KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE >= maxSameGAModules );
assertTrue( "The number of GAs not grow past " + KieModuleRepo.MAX_SIZE_GA_CACHE + ": "
+ KieModuleRepo.MAX_SIZE_GA_CACHE + " > " + maxGAs,
KieModuleRepo.MAX_SIZE_GA_CACHE >= maxGAs );
final int oldKieModulesSize = kieModuleRepo.oldKieModules.size();
final int maxOldKieModules = KieModuleRepo.MAX_SIZE_GA_CACHE * KieModuleRepo.MAX_SIZE_GA_VERSIONS_CACHE;
assertTrue( "KieModuleRepo old KieModules map is not limited in it's growth: " + oldKieModulesSize + " > " + maxOldKieModules,
oldKieModulesSize <= maxOldKieModules );
}
} |
3e19e37270f832c6b355a10b71649236d4143b6f | 376 | java | Java | src/com/sportsclub/domain/Sports.java | itsmrajesh/Sports-Club | 4ec61dd4b4629f94c82b1ec613a90cfcad2587fb | [
"MIT"
] | 1 | 2020-08-06T07:38:59.000Z | 2020-08-06T07:38:59.000Z | src/com/sportsclub/domain/Sports.java | itsmrajesh/Sports-Club | 4ec61dd4b4629f94c82b1ec613a90cfcad2587fb | [
"MIT"
] | null | null | null | src/com/sportsclub/domain/Sports.java | itsmrajesh/Sports-Club | 4ec61dd4b4629f94c82b1ec613a90cfcad2587fb | [
"MIT"
] | null | null | null | 17.904762 | 43 | 0.789894 | 10,992 | package com.sportsclub.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@Builder
public class Sports {
private String sid;
private String sname;
private int scid;
private String sclub;
private int sprice;
private int players;
private String stype; // indoor or outdoor
}
|
3e19e37de6e3935dc4481df74dbaaf18056750e4 | 473 | java | Java | app/src/main/java/com/example/casi/uppg5_3/service/repository/action/SysMessage.java | vonplaten/android-mvc-friendlocalization | 60d4f28e1e0921d119f4aa507015b78862c1d79a | [
"MIT"
] | null | null | null | app/src/main/java/com/example/casi/uppg5_3/service/repository/action/SysMessage.java | vonplaten/android-mvc-friendlocalization | 60d4f28e1e0921d119f4aa507015b78862c1d79a | [
"MIT"
] | null | null | null | app/src/main/java/com/example/casi/uppg5_3/service/repository/action/SysMessage.java | vonplaten/android-mvc-friendlocalization | 60d4f28e1e0921d119f4aa507015b78862c1d79a | [
"MIT"
] | null | null | null | 21.5 | 60 | 0.72093 | 10,993 | package com.example.casi.uppg5_3.service.repository.action;
import com.example.casi.uppg5_3.service.model.ServerMessage;
import com.example.casi.uppg5_3.service.model.SystemMessage;
class SysMessage extends SystemAction {
private SystemMessage message;
public SysMessage(SystemMessage message) {
super();
this.message = message;
}
@Override
public void run() {
repository.getMessageObervable().postValue(message);
}
}
|
3e19e390c91a49091b207297dcd4f46248e84698 | 2,331 | java | Java | Java/Unknown/Java/assignments/otherswork/SpringYardGettingStarted/davis-uhlig/SpringYard/src/main/java/com/example/customer/repository/CustomerRepositoryImpl.java | JamieBort/LearningDirectory | afca79c5f1333c079d0e96202ff44ca21b2ceb81 | [
"Info-ZIP"
] | 1 | 2022-02-02T21:56:08.000Z | 2022-02-02T21:56:08.000Z | Java/Unknown/Java/assignments/otherswork/SpringYardGettingStarted/davis-uhlig/SpringYard/src/main/java/com/example/customer/repository/CustomerRepositoryImpl.java | JamieBort/LearningDirectory | afca79c5f1333c079d0e96202ff44ca21b2ceb81 | [
"Info-ZIP"
] | 27 | 2020-06-27T23:25:59.000Z | 2022-02-27T20:40:56.000Z | Java/Unknown/Java/assignments/otherswork/SpringYardGettingStarted/davis-uhlig/SpringYard/src/main/java/com/example/customer/repository/CustomerRepositoryImpl.java | JamieBort/LearningDirectory | afca79c5f1333c079d0e96202ff44ca21b2ceb81 | [
"Info-ZIP"
] | null | null | null | 35.318182 | 149 | 0.701416 | 10,994 | package com.example.customer.repository;
import com.example.customer.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Created by duhlig on 8/3/17.
*/
@Repository
public class CustomerRepositoryImpl implements CustomerRepository{
@Autowired
private JdbcTemplate jdbcTemplate;
private final String INSERT_SQL = "INSERT INTO customer (firstname, lastname, phone, email) VALUES (?,?,?,?)";
@Override
public void add(Customer customer) {
jdbcTemplate.update(INSERT_SQL, customer.getFirstname(), customer.getLastname(), customer.getPhone(), customer.getEmail());
}
private final String SELECT_BY_ID_SQL ="SELECT * FROM customer WHERE id = ?";
@Override
public Customer getById(int id) {
return jdbcTemplate.queryForObject(SELECT_BY_ID_SQL, new CustomerMapper(), id);
}
private final String SELECT_ALL_SQL = "SELECT * FROM customer";
@Override
public List<Customer> get() {
return jdbcTemplate.query(SELECT_ALL_SQL, new CustomerMapper());
}
private final String UPDATE_SQL = "UPDATE customer SET firstname=?, lastname=?, phone=?, email=? WHERE id=?";
@Override
public void update(Customer customer) {
jdbcTemplate.update(UPDATE_SQL, customer.getFirstname(), customer.getLastname(), customer.getPhone(), customer.getEmail(), customer.getId());
}
private final String DELETE_SQL = "DELETE FROM customer WHERE id=?";
@Override
public void delete(int id) {
jdbcTemplate.update(DELETE_SQL, id);
}
private static class CustomerMapper implements RowMapper<Customer> {
@Override
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setId(rs.getInt("id"));
customer.setFirstname(rs.getString("firstname"));
customer.setLastname(rs.getString("lastname"));
customer.setEmail(rs.getString("email"));
customer.setPhone(rs.getString("phone"));
return customer;
}
}
}
|
3e19e42713851ef8ca3287e80975fa0277825553 | 509 | java | Java | projects/batfish/src/org/batfish/representation/PolicyMapSetAddCommunityLine.java | Alexia23/batfish | 87db3c9bf22afd1974cc6eb2c2b943c903acee36 | [
"Apache-2.0"
] | 1 | 2022-01-14T05:26:24.000Z | 2022-01-14T05:26:24.000Z | projects/batfish/src/org/batfish/representation/PolicyMapSetAddCommunityLine.java | Alexia23/batfish | 87db3c9bf22afd1974cc6eb2c2b943c903acee36 | [
"Apache-2.0"
] | null | null | null | projects/batfish/src/org/batfish/representation/PolicyMapSetAddCommunityLine.java | Alexia23/batfish | 87db3c9bf22afd1974cc6eb2c2b943c903acee36 | [
"Apache-2.0"
] | 1 | 2020-04-10T15:20:46.000Z | 2020-04-10T15:20:46.000Z | 20.36 | 68 | 0.740668 | 10,995 | package org.batfish.representation;
import java.util.List;
public class PolicyMapSetAddCommunityLine extends PolicyMapSetLine {
private static final long serialVersionUID = 1L;
private List<Long> _communities;
public PolicyMapSetAddCommunityLine(List<Long> communities) {
_communities = communities;
}
public List<Long> getCommunities() {
return _communities;
}
@Override
public PolicyMapSetType getType() {
return PolicyMapSetType.ADDITIVE_COMMUNITY;
}
}
|
3e19e47b04de828d6554ca683fc5a82081e3af2e | 809 | java | Java | src/game/Physics.java | notdezzi/Ninjas-World | bb2e66db54c24ff19d3688eeb6bd55b61447681a | [
"MIT"
] | null | null | null | src/game/Physics.java | notdezzi/Ninjas-World | bb2e66db54c24ff19d3688eeb6bd55b61447681a | [
"MIT"
] | null | null | null | src/game/Physics.java | notdezzi/Ninjas-World | bb2e66db54c24ff19d3688eeb6bd55b61447681a | [
"MIT"
] | null | null | null | 25.28125 | 97 | 0.647713 | 10,996 | package game;
import java.util.ArrayList;
import game.components.AABBComponent;
public class Physics {
private static ArrayList<AABBComponent> aabbList = new ArrayList<>();
public static void addAABBComponent(AABBComponent aabb) {
aabbList.add(aabb);
}
public static void update() {
for (int i = 0; i < aabbList.size(); i++) {
for (int j = i + 1; j < aabbList.size(); j++) {
AABBComponent c0 = aabbList.get(i);
AABBComponent c1 = aabbList.get(j);
if (Math.abs(c0.getCenterX() - c1.getCenterX()) < c0.getHalfWidth() + c1.getHalfWidth()) {
if (Math.abs(c0.getCenterY() - c1.getCenterY()) < c0.getHalfHeight() + c1.getHalfHeight()) {
c0.getParent().collision(c1.getParent());
c1.getParent().collision(c0.getParent());
}
}
}
}
aabbList.clear();
}
}
|
3e19e490e7760973e16634f3a729102f20c206fa | 5,350 | java | Java | app/src/main/java/com/kfarst/apps/whispertweetnothings/models/Tweet.java | kfarst/WhisperTweetNothings | c118a5b57b9e511d63de94553f9049b0410f9931 | [
"MIT"
] | 2 | 2017-08-21T09:56:28.000Z | 2017-09-05T12:24:59.000Z | app/src/main/java/com/kfarst/apps/whispertweetnothings/models/Tweet.java | kfarst/WhisperTweetNothings | c118a5b57b9e511d63de94553f9049b0410f9931 | [
"MIT"
] | 2 | 2016-08-08T04:38:08.000Z | 2016-08-15T06:28:45.000Z | app/src/main/java/com/kfarst/apps/whispertweetnothings/models/Tweet.java | kfarst/WhisperTweetNothings | c118a5b57b9e511d63de94553f9049b0410f9931 | [
"MIT"
] | null | null | null | 27.020202 | 112 | 0.604112 | 10,997 | package com.kfarst.apps.whispertweetnothings.models;
import com.activeandroid.ActiveAndroid;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.github.underscore.$;
import com.github.underscore.Block;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcel;
import java.util.ArrayList;
import java.util.List;
/*
* This is a temporary, sample model that demonstrates the basic structure
* of a SQLite persisted Model object. Check out the ActiveAndroid wiki for more details:
* https://github.com/pardom/ActiveAndroid/wiki/Creating-your-database-model
*
*/
@Table(name = "tweets")
@Parcel(analyze={Tweet.class})
public class Tweet extends Model {
// Define table fields
@Column(name = "status")
private String status = "";
@Column(name = "uid", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
private Long uid;
@Column(name = "createdAt")
private String createdAt;
public void setUser(User user) {
this.user = user;
}
@Column(name = "user")
private User user;
@Column(name = "mediaUrl")
private String mediaUrl;
@Column(name = "retweetCount")
private int retweetCount;
public Tweet() {
super();
}
// Setters/Getters
public String getStatus() {
return status;
}
public Long getUid() {
return uid;
}
public String getCreatedAt() {
return createdAt;
}
public User getUser() {
return user;
}
public String getMediaUrl() {
return mediaUrl;
}
public void setMediaUrl(String mediaUrl) {
this.mediaUrl = mediaUrl;
}
public int getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(int retweetCount) {
this.retweetCount = retweetCount;
}
// Record Finders
public static Tweet byId(long uid) {
return new Select().from(Tweet.class).where("uid = ?", uid).executeSingle();
}
public static List<Tweet> recentItems() {
return new Select().from(Tweet.class).orderBy("uid DESC").limit("300").execute();
}
public static Tweet findOrCreateFromJSON(JSONObject json) {
Tweet existingTweet = null;
long uId = 0;
try {
uId = json.getLong("id");
existingTweet = byId(uId);
} catch (JSONException e) {
e.printStackTrace();
}
if (existingTweet != null) {
// found and return existing
return existingTweet;
} else {
// create and return new tweet
Tweet tweet = Tweet.fromJSON(json);
tweet.save();
return tweet;
}
}
public static void deleteById(long uid) {
new Delete().from(Tweet.class).where("uid = ?", uid).execute();
}
// Decodes tweet json into tweet model object
public static Tweet fromJSON(JSONObject jsonObject) {
Tweet tweet = new Tweet();
try {
tweet.status = jsonObject.getString("text");
tweet.uid = jsonObject.getLong("id");
tweet.createdAt = jsonObject.getString("created_at");
tweet.retweetCount = jsonObject.getInt("retweet_count");
tweet.user = User.findOrCreateFromJSON(jsonObject.getJSONObject("user"));
JSONObject mediaObj = (JSONObject) jsonObject.getJSONObject("entities").getJSONArray("media").get(0);
tweet.mediaUrl = mediaObj.getString("media_url");
} catch (JSONException e) {
e.printStackTrace();
}
return tweet;
}
// Decodes array of tweet json results into tweet model objects
public static ArrayList<Tweet> fromJSON(JSONArray jsonArray) {
JSONObject tweetJson;
ArrayList<Tweet> tweets = new ArrayList<Tweet>(jsonArray.length());
ActiveAndroid.beginTransaction();
try {
// Process each result in json array, decode and convert to tweet object
for (int i=0; i < jsonArray.length(); i++) {
try {
tweetJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
Tweet tweet = findOrCreateFromJSON(tweetJson);
if (tweet != null) {
tweets.add(tweet);
}
}
ActiveAndroid.setTransactionSuccessful();
}
finally {
ActiveAndroid.endTransaction();
return tweets;
}
}
public void setStatus(String status) {
this.status = status;
}
public static void deleteAll() {
new Delete().from(Tweet.class).execute();
}
public static void deleteAllById(ArrayList<Tweet> tweets) {
ActiveAndroid.beginTransaction();
try {
$.each(tweets, new Block<Tweet>() {
public void apply(Tweet tweet) {
deleteById(tweet.getUid());
}
});
ActiveAndroid.setTransactionSuccessful();
}
finally {
ActiveAndroid.endTransaction();
}
}
}
|
3e19e4aaba665e1ba5d01dfea3783a4d1f0568a1 | 321 | java | Java | testcenterservice/src/main/java/com/zoctan/api/dto/ApicasewithStatu.java | AutoMeter/AutoMeter-API | 460b7455c1df897edb901fe8a46784ea459f9891 | [
"MIT"
] | 26 | 2021-12-13T09:56:26.000Z | 2022-03-17T03:45:36.000Z | testcenterservice/src/main/java/com/zoctan/api/dto/ApicasewithStatu.java | AutoMeter/AutoMeter-API | 460b7455c1df897edb901fe8a46784ea459f9891 | [
"MIT"
] | 3 | 2021-12-10T08:39:03.000Z | 2022-03-11T08:20:24.000Z | testcenterservice/src/main/java/com/zoctan/api/dto/ApicasewithStatu.java | AutoMeter/AutoMeter-API | 460b7455c1df897edb901fe8a46784ea459f9891 | [
"MIT"
] | 10 | 2022-01-05T06:12:08.000Z | 2022-03-27T05:20:55.000Z | 15.285714 | 48 | 0.691589 | 10,998 | package com.zoctan.api.dto;
import com.zoctan.api.entity.Apicases;
/**
* @author Zoctan
* @date 2018/10/16
*/
public class ApicasewithStatu extends Apicases {
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
private Boolean status;
}
|
3e19e4d2b29215f6420f57bbe0692d4a7354a0c8 | 19,884 | java | Java | auditing-sail/src/test/java/org/openrdf/sail/auditing/PurgeTest.java | stain/alibaba | e080ef991bfc71911a37aeaffeefe900a555fefa | [
"BSD-3-Clause"
] | 3 | 2015-01-26T07:06:28.000Z | 2015-12-14T11:48:55.000Z | auditing-sail/src/test/java/org/openrdf/sail/auditing/PurgeTest.java | stain/alibaba | e080ef991bfc71911a37aeaffeefe900a555fefa | [
"BSD-3-Clause"
] | null | null | null | auditing-sail/src/test/java/org/openrdf/sail/auditing/PurgeTest.java | stain/alibaba | e080ef991bfc71911a37aeaffeefe900a555fefa | [
"BSD-3-Clause"
] | null | null | null | 46.896226 | 151 | 0.744317 | 10,999 | package org.openrdf.sail.auditing;
import javax.xml.datatype.DatatypeFactory;
import junit.framework.TestCase;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.QueryLanguage;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.auditing.vocabulary.Audit;
import org.openrdf.sail.memory.MemoryStore;
public class PurgeTest extends TestCase {
private ValueFactory vf = ValueFactoryImpl.getInstance();
private String NS = "http://example.com/";
private URI carmichael = vf.createURI(NS, "carmichael");
private URI harris = vf.createURI(NS, "harris");
private URI jackson = vf.createURI(NS, "jackson");
private URI johnston = vf.createURI(NS, "johnston");
private URI lismer = vf.createURI(NS, "lismer");
private URI macDonald = vf.createURI(NS, "macDonald");
private URI varley = vf.createURI(NS, "varley");
private URI thomson = vf.createURI(NS, "thomson");
private URI knows = vf.createURI("http://xmlns.com/foaf/0.1/knows");
private RepositoryConnection con;
private Repository repo;
private RepositoryConnection reopen(Repository repo,
RepositoryConnection con) throws Exception {
con.setAutoCommit(true);
con.close();
con = repo.getConnection();
con.setAutoCommit(false);
Thread.sleep(15); // wait a tick
return con;
}
public void setUp() throws Exception {
AuditingSail sail = new AuditingSail(new MemoryStore());
sail.setMaxArchive(2);
sail.setMinRecent(2);
sail.setMaxRecent(2);
sail.setPurgeAfter(DatatypeFactory.newInstance().newDuration("P0D"));
repo = new SailRepository(sail);
repo.initialize();
Thread.sleep(15); // wait a tick to trigger purge on next commit
con = repo.getConnection();
}
public void tearDown() throws Exception {
con.close();
repo.shutDown();
}
public void testAdd() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertFalse(con.hasStatement(null, null, null, false, new Resource[]{null}));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertFalse(con.hasStatement(null, Audit.MODIFIED, null, false));
assertFalse(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertFalse(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testAddMany() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.add(harris, knows, jackson);
con = reopen(repo, con);
con.add(jackson, knows, johnston);
con = reopen(repo, con);
con.add(johnston, knows, lismer);
con = reopen(repo, con);
con.add(lismer, knows, macDonald);
con = reopen(repo, con);
con.add(macDonald, knows, varley);
con = reopen(repo, con);
con.add(varley, knows, thomson);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertFalse(con.hasStatement(null, null, null, false, new Resource[]{null}));
assertEquals(7, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertFalse(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertFalse(con.hasStatement(null, Audit.CONTAINED, null, false));
assertEquals(2, con.getStatements(null, RDF.TYPE, Audit.RECENT, false).asList().size());
}
public void testRemove() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, knows, harris);
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testRemoveMany() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con.add(harris, knows, jackson);
con.add(jackson, knows, johnston);
con.add(johnston, knows, lismer);
con.add(lismer, knows, macDonald);
con.add(macDonald, knows, varley);
con.add(varley, knows, thomson);
con = reopen(repo, con);
con.remove((Resource)null, knows, null);
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertFalse(con.hasStatement(null, null, null, false, new Resource[]{null}));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertFalse(con.hasStatement(null, Audit.MODIFIED, null, false));
assertFalse(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertFalse(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testRemoveAdd() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, knows, harris);
con = reopen(repo, con);
con.add(carmichael, knows, jackson);
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, knows, jackson, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertFalse(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testReplace() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, knows, harris);
con.add(carmichael, knows, jackson);
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, knows, jackson, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testRemoveEach() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
RepositoryResult<Statement> stmts = con.getStatements(carmichael, null, null, false);
while (stmts.hasNext()) {
con.remove(stmts.next());
}
stmts.close();
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, null, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testRemoveRevision() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, Audit.REVISION, null);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertFalse(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(2, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testRemoveLastRevision() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
RepositoryResult<Statement> stmts = con.getStatements(carmichael, Audit.REVISION, null, false);
Value revision = stmts.next().getObject();
stmts.close();
con.remove(carmichael, Audit.REVISION, revision);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertFalse(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(2, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testTouchRevision() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, Audit.REVISION, null);
con.add(carmichael, Audit.REVISION, Audit.CURRENT_TRX);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(2, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testDoubleTouchRevision() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, Audit.REVISION, null);
con.add(carmichael, Audit.REVISION, Audit.CURRENT_TRX);
con = reopen(repo, con);
con.remove(carmichael, Audit.REVISION, null);
con.add(carmichael, Audit.REVISION, Audit.CURRENT_TRX);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(2, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testUpgrade() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, null, null);
con.add(carmichael, knows, jackson);
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, jackson, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testClear() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.remove(carmichael, null, null);
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, null, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testInsertData() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { <carmichael> <http://xmlns.com/foaf/0.1/knows> <harris> } ", "http://example.com/").execute();
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertFalse(con.hasStatement(null, null, null, false, new Resource[]{null}));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertFalse(con.hasStatement(null, Audit.MODIFIED, null, false));
assertFalse(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertFalse(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testDeleteData() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA { <carmichael> <http://xmlns.com/foaf/0.1/knows> <harris> } ", "http://example.com/").execute();
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, knows, harris, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testDelete() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.prepareUpdate(QueryLanguage.SPARQL, "DELETE { <carmichael> ?p ?o }\n" +
"WHERE { <carmichael> ?p ?o } ", "http://example.com/").execute();
con.setAutoCommit(true);
assertFalse(con.hasStatement(carmichael, null, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
public void testModify() throws Exception {
con.setAutoCommit(false);
assertTrue(con.isEmpty());
con.add(carmichael, knows, harris);
con = reopen(repo, con);
con.prepareUpdate(QueryLanguage.SPARQL, "DELETE { <carmichael> ?p ?o }\n" +
"INSERT { <carmichael> <http://xmlns.com/foaf/0.1/knows> <jackson> }\n" +
"WHERE { <carmichael> ?p ?o } ", "http://example.com/").execute();
con.setAutoCommit(true);
assertTrue(con.hasStatement(carmichael, knows, jackson, false));
assertTrue(con.hasStatement(carmichael, Audit.REVISION, null, false));
assertEquals(1, con.getContextIDs().asList().size());
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.TRANSACTION, false));
assertTrue(con.hasStatement(null, RDF.TYPE, Audit.RECENT, false));
assertFalse(con.hasStatement(null, RDF.TYPE, Audit.OBSOLETE, false));
assertTrue(con.hasStatement(null, Audit.COMMITTED_ON, null, false));
assertTrue(con.hasStatement(null, Audit.MODIFIED, null, false));
assertTrue(con.hasStatement(null, Audit.PREDECESSOR, null, false));
assertTrue(con.hasStatement(null, Audit.CONTAINED, null, false));
}
}
|
3e19e4f2dc1ab2afc0f1cd9a546e275a79753d9e | 92 | java | Java | src/main/java/com/loohp/limbo/server/packets/PacketIn.java | Ghost-chu/Limbo | 2ecf4223c6b39a8a3c6bec38ab55da94fbb63174 | [
"Apache-2.0"
] | 103 | 2020-08-09T12:00:38.000Z | 2022-03-20T12:20:36.000Z | src/main/java/com/loohp/limbo/server/packets/PacketIn.java | Ghost-chu/Limbo | 2ecf4223c6b39a8a3c6bec38ab55da94fbb63174 | [
"Apache-2.0"
] | 34 | 2020-08-09T15:53:05.000Z | 2022-03-17T21:26:37.000Z | src/main/java/com/loohp/limbo/server/packets/PacketIn.java | Ghost-chu/Limbo | 2ecf4223c6b39a8a3c6bec38ab55da94fbb63174 | [
"Apache-2.0"
] | 33 | 2020-08-11T13:14:58.000Z | 2022-02-27T03:40:35.000Z | 15.333333 | 47 | 0.793478 | 11,000 | package com.loohp.limbo.server.packets;
public abstract class PacketIn extends Packet {
}
|
3e19e577815cfe96d779b6ca0431acf235124821 | 4,748 | java | Java | ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/ciq/TObjectscenariosCIQ.java | taktos/ea2ddl | 282aa6c851be220441ee50df5c18ff575dfbe9ac | [
"Apache-2.0"
] | null | null | null | ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/ciq/TObjectscenariosCIQ.java | taktos/ea2ddl | 282aa6c851be220441ee50df5c18ff575dfbe9ac | [
"Apache-2.0"
] | 3 | 2015-07-01T10:33:38.000Z | 2016-07-13T06:57:57.000Z | ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/ciq/TObjectscenariosCIQ.java | taktos/ea2ddl | 282aa6c851be220441ee50df5c18ff575dfbe9ac | [
"Apache-2.0"
] | null | null | null | 46.54902 | 141 | 0.51706 | 11,001 | package jp.sourceforge.ea2ddl.dao.cbean.cq.ciq;
import org.seasar.dbflute.cbean.*;
import org.seasar.dbflute.cbean.ckey.*;
import org.seasar.dbflute.cbean.coption.ConditionOption;
import org.seasar.dbflute.cbean.cvalue.ConditionValue;
import org.seasar.dbflute.cbean.sqlclause.SqlClause;
import jp.sourceforge.ea2ddl.dao.cbean.*;
import jp.sourceforge.ea2ddl.dao.cbean.cq.bs.*;
import jp.sourceforge.ea2ddl.dao.cbean.cq.*;
/**
* The condition-inline-query of t_objectscenarios.
* @author DBFlute(AutoGenerator)
*/
public class TObjectscenariosCIQ extends AbstractBsTObjectscenariosCQ {
// ===================================================================================
// Attribute
// =========
protected BsTObjectscenariosCQ _myCQ;
// ===================================================================================
// Constructor
// ===========
public TObjectscenariosCIQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel, BsTObjectscenariosCQ myCQ) {
super(childQuery, sqlClause, aliasName, nestLevel);
_myCQ = myCQ;
_foreignPropertyName = _myCQ.getForeignPropertyName();// Accept foreign property name.
_relationPath = _myCQ.getRelationPath();// Accept relation path.
}
// ===================================================================================
// Override about Register
// =======================
@Override
protected void reflectRelationOnUnionQuery(ConditionQuery baseQueryAsSuper, ConditionQuery unionQueryAsSuper) {
throw new UnsupportedOperationException("InlineQuery must not need UNION method: " + baseQueryAsSuper + " : " + unionQueryAsSuper);
}
@Override
protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col) {
regIQ(k, v, cv, col);
}
@Override
protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col, ConditionOption op) {
regIQ(k, v, cv, col, op);
}
@Override
protected void registerWhereClause(String whereClause) {
registerInlineWhereClause(whereClause);
}
@Override
protected String getInScopeSubQueryRealColumnName(String columnName) {
if (_onClauseInline) {
throw new UnsupportedOperationException("InScopeSubQuery of on-clause is unsupported");
}
return _onClauseInline ? getRealAliasName() + "." + columnName : columnName;
}
@Override
protected void registerExistsSubQuery(ConditionQuery subQuery
, String columnName, String relatedColumnName, String propertyName) {
throw new UnsupportedOperationException("Sorry! ExistsSubQuery at inline view is unsupported. So please use InScopeSubQyery.");
}
// ===================================================================================
// Override about Query
// ====================
protected ConditionValue getCValueObjectId() {
return _myCQ.getObjectId();
}
protected ConditionValue getCValueScenario() {
return _myCQ.getScenario();
}
protected ConditionValue getCValueScenariotype() {
return _myCQ.getScenariotype();
}
protected ConditionValue getCValueEvalue() {
return _myCQ.getEvalue();
}
protected ConditionValue getCValueNotes() {
return _myCQ.getNotes();
}
protected ConditionValue getCValueXmlcontent() {
return _myCQ.getXmlcontent();
}
protected ConditionValue getCValueEaGuid() {
return _myCQ.getEaGuid();
}
// ===================================================================================
// Very Internal
// =============
// Very Internal (for Suppressing Warn about 'Not Use Import')
String xiCB() { return TObjectscenariosCB.class.getName(); }
String xiCQ() { return TObjectscenariosCQ.class.getName(); }
}
|
3e19e580c78004082ea8e951d9ddb1f8906e5b02 | 470 | java | Java | rodoviariapoa/src/main/java/rodoviariapoa/validationpoints/CadastroVerificationPoint.java | pepsibattaglino/s2b_projeto | 661e9623620c866fb8b9eebea21538eceed67b86 | [
"MIT"
] | null | null | null | rodoviariapoa/src/main/java/rodoviariapoa/validationpoints/CadastroVerificationPoint.java | pepsibattaglino/s2b_projeto | 661e9623620c866fb8b9eebea21538eceed67b86 | [
"MIT"
] | null | null | null | rodoviariapoa/src/main/java/rodoviariapoa/validationpoints/CadastroVerificationPoint.java | pepsibattaglino/s2b_projeto | 661e9623620c866fb8b9eebea21538eceed67b86 | [
"MIT"
] | 1 | 2018-06-09T08:51:35.000Z | 2018-06-09T08:51:35.000Z | 22.380952 | 71 | 0.791489 | 11,002 | package rodoviariapoa.validationpoints;
import static org.junit.Assert.assertTrue;
import org.openqa.selenium.WebDriver;
public class CadastroVerificationPoint {
private WebDriver driver;
public CadastroVerificationPoint(WebDriver driver) {
this.driver = driver;
}
public void verificarMensagemDeSucesso() {
final String expectedMessage = "conta de usuário criada com sucesso";
assertTrue(this.driver.getPageSource().contains(expectedMessage));
}
}
|
3e19e68cf48fdcb971ee75aa9c5efe2664e6cc4a | 2,935 | java | Java | app/src/main/java/com/cxy/im4cxy/BmobIMApplication.java | misaka9981/IM | 4c6ab04f59edd8bd1f24a605c942f078144dfde8 | [
"MIT"
] | null | null | null | app/src/main/java/com/cxy/im4cxy/BmobIMApplication.java | misaka9981/IM | 4c6ab04f59edd8bd1f24a605c942f078144dfde8 | [
"MIT"
] | null | null | null | app/src/main/java/com/cxy/im4cxy/BmobIMApplication.java | misaka9981/IM | 4c6ab04f59edd8bd1f24a605c942f078144dfde8 | [
"MIT"
] | null | null | null | 29.646465 | 110 | 0.621465 | 11,003 | package com.cxy.im4cxy;
import android.app.Application;
import android.content.Context;
import com.cxy.im4cxy.base.UniversalImageLoader;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import androidx.multidex.MultiDex;
import cn.bmob.newim.BmobIM;
import cn.bmob.push.BmobPush;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobInstallationManager;
import cn.bmob.v3.InstallationListener;
import cn.bmob.v3.exception.BmobException;
//TODO 集成:1.7、自定义Application,并在AndroidManifest.xml中配置
public class BmobIMApplication extends Application {
private static BmobIMApplication INSTANCE;
public static BmobIMApplication INSTANCE() {
return INSTANCE;
}
private void setInstance(BmobIMApplication app) {
setBmobIMApplication(app);
}
private static void setBmobIMApplication(BmobIMApplication a) {
BmobIMApplication.INSTANCE = a;
}
@Override
public void onCreate() {
super.onCreate();
setInstance(this);
//TODO 集成:1.8、初始化IM SDK,并注册消息接收器,只有主进程运行的时候才需要初始化
if (getApplicationInfo().packageName.equals(getMyProcessName())) {
Bmob.resetDomain("http://imsdk.zhixiangshu.top/8/");
BmobIM.init(this);
BmobIM.registerDefaultMessageHandler(new DemoMessageHandler(this));
super.onCreate();
/**
* 保存设备信息,用于推送功能
*/
BmobInstallationManager.getInstance().initialize(new InstallationListener<BmobInstallation>() {
@Override
public void done(BmobInstallation bmobInstallation, BmobException e) {
if (e == null) {
Logger.i(bmobInstallation.getObjectId() + "-" + bmobInstallation.getInstallationId());
} else {
Logger.e(e.getMessage());
}
}
});
/**
* 启动推送服务
*/
BmobPush.startWork(this);
}
Logger.addLogAdapter(new AndroidLogAdapter());
UniversalImageLoader.initImageLoader(this);
}
/**
* 获取当前运行的进程名
*
* @return
*/
public static String getMyProcessName() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
|
3e19e74c8cad8d0b56bb9a1daf909b7ddafb6a59 | 854 | java | Java | src/main/java/se/lu/bosmp/scanner/FileRowData.java | eriklupander/bos-fullparser-frp | 8f9c7678b806aac9218979a8d48208388e243964 | [
"MIT"
] | null | null | null | src/main/java/se/lu/bosmp/scanner/FileRowData.java | eriklupander/bos-fullparser-frp | 8f9c7678b806aac9218979a8d48208388e243964 | [
"MIT"
] | null | null | null | src/main/java/se/lu/bosmp/scanner/FileRowData.java | eriklupander/bos-fullparser-frp | 8f9c7678b806aac9218979a8d48208388e243964 | [
"MIT"
] | null | null | null | 20.333333 | 64 | 0.645199 | 11,004 | package se.lu.bosmp.scanner;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Erik
* Date: 2014-12-15
* Time: 09:39
* To change this template use File | Settings | File Templates.
*/
public class FileRowData {
private Integer fileNameHash;
private String fileName;
private List<String> rows = new ArrayList<>();
public Integer getFileNameHash() {
return fileNameHash;
}
public void setFileNameHash(Integer fileNameHash) {
this.fileNameHash = fileNameHash;
}
public List<String> getRows() {
return rows;
}
public void setRows(List<String> rows) {
this.rows = rows;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
|
3e19e74e862991f8fc1615da5cbd02fa18be4684 | 474 | java | Java | wanxinp2p/wanxindepository/src/main/java/com/moon/wanxindepository/model/DepositoryResponse.java | MooNkirA/wanxinp2p-project | 840e5c2712fa0c2f36e1cde3bbb9cf7223f4d359 | [
"Apache-2.0"
] | null | null | null | wanxinp2p/wanxindepository/src/main/java/com/moon/wanxindepository/model/DepositoryResponse.java | MooNkirA/wanxinp2p-project | 840e5c2712fa0c2f36e1cde3bbb9cf7223f4d359 | [
"Apache-2.0"
] | null | null | null | wanxinp2p/wanxindepository/src/main/java/com/moon/wanxindepository/model/DepositoryResponse.java | MooNkirA/wanxinp2p-project | 840e5c2712fa0c2f36e1cde3bbb9cf7223f4d359 | [
"Apache-2.0"
] | null | null | null | 21.545455 | 63 | 0.742616 | 11,005 | package com.moon.wanxindepository.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(value = "DepositoryResponse", description = "存管响应信息")
public class DepositoryResponse<T> {
@ApiModelProperty("对respData参数的签名")
private String signature;
@ApiModelProperty("业务数据报文")
private T respData;
public DepositoryResponse(T respData) {
this.respData = respData;
}
}
|
3e19e75a521df322492cef850e1f6e115e4dfd76 | 810 | java | Java | assets/misc/cfconnector/src/main/java/com/xcalar/sdk/XcalarResponse.java | xcalar/xcalar-idl | 69aa08fb42cde6c905b3aa2129c365c4c3e575f9 | [
"Apache-2.0"
] | null | null | null | assets/misc/cfconnector/src/main/java/com/xcalar/sdk/XcalarResponse.java | xcalar/xcalar-idl | 69aa08fb42cde6c905b3aa2129c365c4c3e575f9 | [
"Apache-2.0"
] | null | null | null | assets/misc/cfconnector/src/main/java/com/xcalar/sdk/XcalarResponse.java | xcalar/xcalar-idl | 69aa08fb42cde6c905b3aa2129c365c4c3e575f9 | [
"Apache-2.0"
] | 1 | 2021-01-31T20:52:28.000Z | 2021-01-31T20:52:28.000Z | 21.315789 | 61 | 0.696296 | 11,006 | package com.xcalar.sdk;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
public class XcalarResponse {
private static final String FIELD_VERSION = "ver";
private static final String VERSION = "1";
private Gson json;
private Response response;
public XcalarResponse(byte[] respBuf) {
this.json = new Gson();
String str = new String(respBuf, StandardCharsets.UTF_8);
this.response = this.json.fromJson(str, Response.class);
}
@Override
public String toString() {
return this.json.toJson(this.response, Response.class);
}
public String getVersion() {
return this.response.ver;
}
public int getStatus() {
return this.response.status;
}
private static class Response {
public String ver = "";
public int status = 0;
}
}
|
3e19e7faa5911288e35282357a0f5ea9869b2d4a | 13,471 | java | Java | hydra-main/src/main/java/com/addthis/hydra/util/WebSocketManager.java | worrel/hydra | d22953070b1a6c84d875d2d42e6fa6998f0eb789 | [
"Apache-2.0"
] | null | null | null | hydra-main/src/main/java/com/addthis/hydra/util/WebSocketManager.java | worrel/hydra | d22953070b1a6c84d875d2d42e6fa6998f0eb789 | [
"Apache-2.0"
] | null | null | null | hydra-main/src/main/java/com/addthis/hydra/util/WebSocketManager.java | worrel/hydra | d22953070b1a6c84d875d2d42e6fa6998f0eb789 | [
"Apache-2.0"
] | null | null | null | 34.808786 | 141 | 0.599659 | 11,007 | /*
* 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.addthis.hydra.util;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.addthis.basis.util.Parameter;
import com.addthis.hydra.job.Spawn;
import com.addthis.maljson.JSONArray;
import com.addthis.maljson.JSONObject;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is a jetty request handler that opens web sockets with clients upon request, and keeps a set of open web sockets
* so as to give a server the ability to notify all clients and send them messages.
*/
public class WebSocketManager extends WebSocketHandler {
private static final Logger log = LoggerFactory.getLogger(WebSocketManager.class);
/**
* A threadsafe list of open WebSockets
*/
private final Set<MQWebSocket> webSockets = new CopyOnWriteArraySet<MQWebSocket>();
/**
* A json factory for any json serializing
*/
private static final JsonFactory factory = new JsonFactory(new com.fasterxml.jackson.databind.ObjectMapper());
/**
* Object used as monitor that the WebUpdateThread waits on when there are no websockets, and then gets notified when a websocket arrives
*/
private final Object monitor = new Object();
/**
* A flag used to shutdown the webupdate thread
*/
private volatile boolean shutdown = false;
/**
* The update thread that pushes events to the client web sockets and waits until new websockets are created when there are none
*/
private final Thread updateThread;
private static final int clientDropQueueSize = Parameter.intValue("spawn.client.drop.queue", 2000);
private static final Counter nonConsumingClientDropCounter = Metrics.newCounter(Spawn.class, "clientDropsSpawnV2");
public WebSocketManager() {
this.updateThread = new Thread("WebUpdateThread") {
@Override
public void run() {
try {
while (!shutdown) {
synchronized (monitor) {
if (webSockets.size() == 0) {
monitor.wait();
}
}
for (MQWebSocket webSocket : webSockets) {
webSocket.drainEvents(100);
}
Thread.sleep(200);
}
} catch (Exception ex) {
log.warn("[WebSocketManager] Error updating websockets from in update thread.");
ex.printStackTrace();
}
}
};
this.updateThread.setDaemon(true);
this.updateThread.start();
}
/**
* This method will be called on every client connect. This method must
* return a WebSocket-implementing-class to work on. WebSocket is just an
* interface with different types of communication possibilities. You must
* create and return a class which implements the necessary WebSocket
* interfaces.
*/
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
MQWebSocket webSocket = new MQWebSocket(request.getParameter("user"), request.getRemoteAddr());
synchronized (monitor) {
int numberOfSockets = webSockets.size();
webSockets.add(webSocket);
if (numberOfSockets == 0) {
monitor.notify(); //to wake up update timer thread
}
}
return webSocket;
}
/**
* Creates and returns json representation of the websockets for UI reporting
*
* @return json array of websockets
* @throws IOException
*/
public String getWebSocketsJSON() throws IOException {
StringWriter writer = new StringWriter();
final JsonGenerator json = factory.createJsonGenerator(writer);
json.writeStartArray();
for (MQWebSocket webSocket : webSockets) {
json.writeStartObject();
json.writeStringField("username", webSocket.getUsername());
json.writeNumberField("lastSeenTime", webSocket.getLastSeenTime());
json.writeNumberField("loggedInTime", webSocket.getLoggedInTime());
json.writeStringField("remoteAddress", webSocket.getRemoteAddress());
json.writeEndObject();
}
json.writeEndArray();
json.close();
return writer.toString();
}
/**
* Sends a string message to all connected web sockets.
*
* @param message
*/
public void sendMessageToAll(String message) {
for (MQWebSocket webSocket : webSockets) {
webSocket.sendMessage(message);
}
}
/**
* Sends a JSON message to all websockets subscribed to a given topic
*
* @param topic
* @param messageObject
*/
public void sendMessageToAllByTopic(String topic, JSONObject messageObject) {
String message = messageObject.toString();
this.sendMessageToAllByTopic(topic, message);
}
/**
* Sends a string message to all websockets subscribed to a given topic
*
* @param topic the topic to use for the message
* @param message the message payload in string format
*/
public void sendMessageToAllByTopic(String topic, String message) {
for (MQWebSocket webSocket : webSockets) {
webSocket.sendMessageByTopic(topic, message);
}
}
/**
* Queue up an event for websockets
*
* @param event
*/
public void addEvent(Spawn.ClientEvent event) {
for (MQWebSocket webSocket : webSockets) {
webSocket.addEvent(event);
}
}
/**
* Implements an anonymous class for the websocket with the necessary
* WebSocket interfaces and the network logic.
*/
private class MQWebSocket implements WebSocket.OnTextMessage {
/**
* The connection object of every WebSocket.
*/
private Connection connection;
/**
* The time in millis when connection was established
*/
private long loggedInTime;
/**
* The time in millis when last heartbeat was received
*/
private long lastSeenTime;
/**
* The time in millis when this user was sent events
*/
private long lastEventDrainTime;
/**
* Username client provided when connection was established
*/
private String username;
/**
* Remote address from which client initiated connection
*/
private String remoteAddress;
/**
* A queue of events to queue up and push to websockets at intervals
*/
private final LinkedBlockingQueue<Spawn.ClientEvent> eventQueue = new LinkedBlockingQueue<Spawn.ClientEvent>();
public MQWebSocket(String username, String remoteAddress) {
this.username = username;
this.remoteAddress = remoteAddress;
}
public MQWebSocket() {
this("anonymous", "unkown");
}
/**
* This method is defined by the WebSocket interface. It will be called
* when a new WebSocket Connection is established.
*
* @param connection the newly opened connection
*/
public void onOpen(Connection connection) {
//System.out.println("[SERVER] Opened connection");
connection.setMaxIdleTime(30000);
// WebSocket has been opened. Store the opened connection
this.connection = connection;
// Add WebSocket in the global list of WebSocket instances
long time = System.currentTimeMillis();
this.loggedInTime = time;
this.lastSeenTime = time;
this.lastEventDrainTime = time;
}
/**
* This method is defined by the WebSocket.OnTestMessage Interface. It
* will be called when a new Text message has been received. In this
* class, we will send the received message to all connected clients.
*
* @param data message sent by client to server in String format
*/
public void onMessage(String data) {
try {
if (data.equals("ping")) {
this.connection.sendMessage("pong");
} else {
this.connection.sendMessage("The server received your message: " + data);
}
this.lastSeenTime = System.currentTimeMillis();
} catch (Exception ex) {
log.warn("Error sending message to " + this.toString());
ex.printStackTrace();
}
}
/**
* This method is defined by the WebSocket Interface. It will be called
* when a WebSocket Connection is closed.
*
* @param closeCode the exit code of the connection in integer format
* @param message a human readable message for the exit code
*/
public void onClose(int closeCode, String message) {
webSockets.remove(this);
}
/**
* This method is used to send a string message to websocket
*
* @param message text data to send to this particular websocket
*/
public void sendMessage(String message) {
try {
//TODO: Does this send blocks?
this.connection.sendMessage(message);
} catch (IOException ex) {
log.warn("Error sending message to web socket: " + message);
ex.printStackTrace();
}
}
/**
* This method is used to send json message to web socket by topic
*
* @param topic the topic of the message
* @param message the actual message payload in text format
*/
public void sendMessageByTopic(String topic, String message) {
try {
JSONObject json = new JSONObject();
json.put("topic", topic);
json.put("message", message);
this.sendMessage(json.toString());
} catch (Exception ex) {
log.warn("Error encoding web socket message: " + message);
ex.printStackTrace();
}
}
public long getLoggedInTime() {
return loggedInTime;
}
public void setLoggedInTime(long loggedInTime) {
this.loggedInTime = loggedInTime;
}
public long getLastSeenTime() {
return lastSeenTime;
}
public void setLastSeenTime(long lastSeenTime) {
this.lastSeenTime = lastSeenTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public void addEvent(Spawn.ClientEvent event) {
if (eventQueue.size() > clientDropQueueSize) {
// Queue has grown too big. Client does not appear to be consuming. Drop the socket to prevent an ugly OOM.
eventQueue.clear();
nonConsumingClientDropCounter.inc();
this.onClose(-1, null);
}
eventQueue.add(event);
}
public int drainEvents(int maxNumber) {
int events = 0;
try {
JSONArray eventArray = new JSONArray();
for (int i = 0; i < eventQueue.size() && i < maxNumber; i++) {
Spawn.ClientEvent event = eventQueue.poll(1000, TimeUnit.MILLISECONDS);
eventArray.put(event.toJSON());
events++;
}
if (events > 0) {
String eventArrayString = eventArray.toString();
sendMessageByTopic("event.batch.update", eventArrayString);
}
} catch (Exception ex) {
log.warn("[WebSocketManager] error sending batch updates to web socket");
ex.printStackTrace();
}
return events;
}
}
}
|
3e19e849e720975f1bdfec33b8cb850f2814c658 | 8,810 | java | Java | src/main/java-gen/io/dronefleet/mavlink/common/SerialControl.java | Flytrex/mavlink | 3fe399fe9bef710426f6971f1b7d8db3cd63cae9 | [
"MIT"
] | 78 | 2018-08-09T11:26:46.000Z | 2022-03-28T17:12:40.000Z | src/main/java-gen/io/dronefleet/mavlink/common/SerialControl.java | Flytrex/mavlink | 3fe399fe9bef710426f6971f1b7d8db3cd63cae9 | [
"MIT"
] | 69 | 2018-08-03T15:21:19.000Z | 2022-03-21T09:35:17.000Z | src/main/java-gen/io/dronefleet/mavlink/common/SerialControl.java | Flytrex/mavlink | 3fe399fe9bef710426f6971f1b7d8db3cd63cae9 | [
"MIT"
] | 51 | 2018-07-20T07:58:21.000Z | 2022-03-29T01:38:21.000Z | 28.603896 | 330 | 0.557662 | 11,008 | package io.dronefleet.mavlink.common;
import io.dronefleet.mavlink.annotations.MavlinkFieldInfo;
import io.dronefleet.mavlink.annotations.MavlinkMessageBuilder;
import io.dronefleet.mavlink.annotations.MavlinkMessageInfo;
import io.dronefleet.mavlink.util.EnumValue;
import java.lang.Enum;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.util.Collection;
import java.util.Objects;
/**
* Control a serial port. This can be used for raw access to an onboard serial peripheral such as a
* GPS or telemetry radio. It is designed to make it possible to update the devices firmware via
* MAVLink messages or change the devices settings. A message with zero bytes can be used to change
* just the baudrate.
*/
@MavlinkMessageInfo(
id = 126,
crc = 220,
description = "Control a serial port. This can be used for raw access to an onboard serial peripheral such as a GPS or telemetry radio. It is designed to make it possible to update the devices firmware via MAVLink messages or change the devices settings. A message with zero bytes can be used to change just the baudrate."
)
public final class SerialControl {
private final EnumValue<SerialControlDev> device;
private final EnumValue<SerialControlFlag> flags;
private final int timeout;
private final long baudrate;
private final int count;
private final byte[] data;
private SerialControl(EnumValue<SerialControlDev> device, EnumValue<SerialControlFlag> flags,
int timeout, long baudrate, int count, byte[] data) {
this.device = device;
this.flags = flags;
this.timeout = timeout;
this.baudrate = baudrate;
this.count = count;
this.data = data;
}
/**
* Returns a builder instance for this message.
*/
@MavlinkMessageBuilder
public static Builder builder() {
return new Builder();
}
/**
* Serial control device type.
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 1,
enumType = SerialControlDev.class,
description = "Serial control device type."
)
public final EnumValue<SerialControlDev> device() {
return this.device;
}
/**
* Bitmap of serial control flags.
*/
@MavlinkFieldInfo(
position = 2,
unitSize = 1,
enumType = SerialControlFlag.class,
description = "Bitmap of serial control flags."
)
public final EnumValue<SerialControlFlag> flags() {
return this.flags;
}
/**
* Timeout for reply data
*/
@MavlinkFieldInfo(
position = 3,
unitSize = 2,
description = "Timeout for reply data"
)
public final int timeout() {
return this.timeout;
}
/**
* Baudrate of transfer. Zero means no change.
*/
@MavlinkFieldInfo(
position = 4,
unitSize = 4,
description = "Baudrate of transfer. Zero means no change."
)
public final long baudrate() {
return this.baudrate;
}
/**
* how many bytes in this transfer
*/
@MavlinkFieldInfo(
position = 5,
unitSize = 1,
description = "how many bytes in this transfer"
)
public final int count() {
return this.count;
}
/**
* serial data
*/
@MavlinkFieldInfo(
position = 6,
unitSize = 1,
arraySize = 70,
description = "serial data"
)
public final byte[] data() {
return this.data;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !getClass().equals(o.getClass())) return false;
SerialControl other = (SerialControl)o;
if (!Objects.deepEquals(device, other.device)) return false;
if (!Objects.deepEquals(flags, other.flags)) return false;
if (!Objects.deepEquals(timeout, other.timeout)) return false;
if (!Objects.deepEquals(baudrate, other.baudrate)) return false;
if (!Objects.deepEquals(count, other.count)) return false;
if (!Objects.deepEquals(data, other.data)) return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + Objects.hashCode(device);
result = 31 * result + Objects.hashCode(flags);
result = 31 * result + Objects.hashCode(timeout);
result = 31 * result + Objects.hashCode(baudrate);
result = 31 * result + Objects.hashCode(count);
result = 31 * result + Objects.hashCode(data);
return result;
}
@Override
public String toString() {
return "SerialControl{device=" + device
+ ", flags=" + flags
+ ", timeout=" + timeout
+ ", baudrate=" + baudrate
+ ", count=" + count
+ ", data=" + data + "}";
}
public static final class Builder {
private EnumValue<SerialControlDev> device;
private EnumValue<SerialControlFlag> flags;
private int timeout;
private long baudrate;
private int count;
private byte[] data;
/**
* Serial control device type.
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 1,
enumType = SerialControlDev.class,
description = "Serial control device type."
)
public final Builder device(EnumValue<SerialControlDev> device) {
this.device = device;
return this;
}
/**
* Serial control device type.
*/
public final Builder device(SerialControlDev entry) {
return device(EnumValue.of(entry));
}
/**
* Serial control device type.
*/
public final Builder device(Enum... flags) {
return device(EnumValue.create(flags));
}
/**
* Serial control device type.
*/
public final Builder device(Collection<Enum> flags) {
return device(EnumValue.create(flags));
}
/**
* Bitmap of serial control flags.
*/
@MavlinkFieldInfo(
position = 2,
unitSize = 1,
enumType = SerialControlFlag.class,
description = "Bitmap of serial control flags."
)
public final Builder flags(EnumValue<SerialControlFlag> flags) {
this.flags = flags;
return this;
}
/**
* Bitmap of serial control flags.
*/
public final Builder flags(SerialControlFlag entry) {
return flags(EnumValue.of(entry));
}
/**
* Bitmap of serial control flags.
*/
public final Builder flags(Enum... flags) {
return flags(EnumValue.create(flags));
}
/**
* Bitmap of serial control flags.
*/
public final Builder flags(Collection<Enum> flags) {
return flags(EnumValue.create(flags));
}
/**
* Timeout for reply data
*/
@MavlinkFieldInfo(
position = 3,
unitSize = 2,
description = "Timeout for reply data"
)
public final Builder timeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Baudrate of transfer. Zero means no change.
*/
@MavlinkFieldInfo(
position = 4,
unitSize = 4,
description = "Baudrate of transfer. Zero means no change."
)
public final Builder baudrate(long baudrate) {
this.baudrate = baudrate;
return this;
}
/**
* how many bytes in this transfer
*/
@MavlinkFieldInfo(
position = 5,
unitSize = 1,
description = "how many bytes in this transfer"
)
public final Builder count(int count) {
this.count = count;
return this;
}
/**
* serial data
*/
@MavlinkFieldInfo(
position = 6,
unitSize = 1,
arraySize = 70,
description = "serial data"
)
public final Builder data(byte[] data) {
this.data = data;
return this;
}
public final SerialControl build() {
return new SerialControl(device, flags, timeout, baudrate, count, data);
}
}
}
|
3e19ea5b89e45a3a9bff5298bbf4d86b71dc32d6 | 480 | java | Java | chapter2-3/src/main/java/com/hl/example/mapper/primary/UserMapperPrimary.java | binglongworld/springboot-demo | 80f74576349e3299dc758b79a7e16823dfcdba58 | [
"Apache-2.0"
] | 1 | 2021-04-22T00:58:46.000Z | 2021-04-22T00:58:46.000Z | chapter2-3/src/main/java/com/hl/example/mapper/primary/UserMapperPrimary.java | binglongworld/springboot-demo | 80f74576349e3299dc758b79a7e16823dfcdba58 | [
"Apache-2.0"
] | null | null | null | chapter2-3/src/main/java/com/hl/example/mapper/primary/UserMapperPrimary.java | binglongworld/springboot-demo | 80f74576349e3299dc758b79a7e16823dfcdba58 | [
"Apache-2.0"
] | null | null | null | 22.857143 | 71 | 0.702083 | 11,009 | package com.hl.example.mapper.primary;
import com.hl.example.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Map;
@Mapper
public interface UserMapperPrimary {
int deleteUser();
User findByName(@Param("name") String name);
int insert(@Param("name") String name, @Param("age") Integer age);
int insertByMap(Map<String, Object> map);
int insertByUser(User user);
}
|
3e19eb805bea9ff7bdb468d5ded5f7a404ae37c1 | 9,452 | java | Java | Survival Game/src/Window/Game.java | bensadiku/DesktopGames | 2c3b65574f7336cd1d30fd0f146bcf9d5862670a | [
"MIT"
] | 1 | 2019-04-02T20:07:19.000Z | 2019-04-02T20:07:19.000Z | Survival Game/src/Window/Game.java | bensadiku/DesktopGames | 2c3b65574f7336cd1d30fd0f146bcf9d5862670a | [
"MIT"
] | null | null | null | Survival Game/src/Window/Game.java | bensadiku/DesktopGames | 2c3b65574f7336cd1d30fd0f146bcf9d5862670a | [
"MIT"
] | null | null | null | 25.754768 | 92 | 0.605904 | 11,010 | package Window;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import Framework.KeyInput;
import Framework.Menu;
import Framework.ObjectId;
import Framework.Texture;
import Levels.DesertBlock;
import Objects.Block;
import Objects.Flag;
import Objects.Player;
import Objects.Zombie;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private boolean running =false;
private Thread thread;
private Menu menu;
public static int WIDTH, HEIGHT;
private HUD hud;
private BufferedImage [] background= new BufferedImage[10];
Handler handler;
Camera cam;
static Texture tex;
public static int LEVEL=2;
public BufferedImage [] level = new BufferedImage[10];
public enum STATE {
Menu,
Help,
Game,
EndGame
};
public STATE gameState = STATE.Menu; // casts STATE enumeration to Menu specifically
public void innit() {
WIDTH = getWidth();
HEIGHT = getHeight();
tex= new Texture ();
cam = new Camera (0,0);
handler = new Handler (cam);
menu =new Menu (this);
this.addMouseListener(menu);
hud = new HUD();
if(gameState == STATE.Game) {
BufferedImageLoader loader= new BufferedImageLoader();
level[1] = loader.loadImage("/level_1.png"); //loades the level
level[2] = loader.loadImage("/level_2.png"); //loades the level
LoadImageLevel(level[Game.LEVEL]);
background[1] = loader.loadImage("/background_1.png"); // loads backgroynd
background[2] = loader.loadImage("/background_2.png"); // loads backgroynd
}
this.addKeyListener(new KeyInput(handler));
}
public synchronized void start () {
if(running) {
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public void run () {
innit();
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
//System.out.println(frames);
timer += 1000;
frames = 0;
}
}
stop();
}
private void stop(){
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void tick() {
handler.tick();
if(gameState == STATE.Game) {
for(int i=0; i< handler.object.size();i++) {
if(handler.object.get(i).getId() == ObjectId.Player) {
cam.tick(handler.object.get(i));
hud.tick();
if(HUD.HEALTH <=0) {
HUD.HEALTH =100;
gameState=STATE.EndGame;
handler.clearLevel();
}
}
}
}else if(gameState== STATE.Menu || gameState == STATE.EndGame){
menu.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs==null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D)g;
/////////////////////
////////////////
g.fillRect(0, 0, getWidth(), getHeight());
//handler.render(g);
if(gameState == STATE.Game) {
g2d.translate(cam.getX(),cam.getY());//begining of cam
try{
for(int xx=0;xx < background[LEVEL].getWidth()*10 ; xx+= background[LEVEL].getWidth()) {
g.drawImage(background[LEVEL], xx, 0, this);
}
}
catch (Exception e) {
}
handler.render(g);
g2d.translate(-cam.getX(),-cam.getY()); //end of cams
hud.render(g);
}
else if(gameState== STATE.Menu || gameState== STATE.Help || gameState== STATE.EndGame){
menu.render(g);
}
g.dispose();
bs.show();
}
public static int clamp (int var,int min, int max) {
if(var >= max) {
return var =max;
}
else if(var<= min) {
return var =min;
}
else
return var;
}
public void LoadImageLevel (BufferedImage image) {
try {
int w = image.getWidth();
int h = image.getHeight();
for(int xx =0; xx<h; xx++) {
for(int yy=0; yy<w; yy++) {
int pixel = image.getRGB(xx, yy);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8 ) & 0xff;
int blue = (pixel) & 0xff;
if(LEVEL==1) {
if(red== 0 && green == 0 & blue == 255)//blue color
handler.addObject(new Player(xx*32,yy*32,handler,cam,this,ObjectId.Player));
if(red== 255 && green == 216 & blue == 0)//yellow color
handler.addObject(new Flag(xx*32,yy*32,ObjectId.Flag));
if(red== 160 && green == 160 & blue == 160)//gray color
handler.addObject(new Block(xx*32,yy*32,0,ObjectId.Block));
if(red== 255 && green == 255 & blue == 255)//white color
handler.addObject(new Block(xx*32,yy*32,1,ObjectId.Block));
if(red== 127 && green == 201 & blue == 255)//blue/ish color /lava
handler.addObject(new Block(xx*32,yy*32,2,ObjectId.Block));
if(red== 214 && green == 127 & blue == 255)// pink color /lava
handler.addObject(new Block(xx*32,yy*32,3,ObjectId.Block));
if(red== 91 && green == 127 & blue == 0)//yellow/ish color /lava
handler.addObject(new Block(xx*32,yy*32,4,ObjectId.Block));
if(red== 127 && green == 51 & blue == 0)//brown color /lava
handler.addObject(new Block(xx*32,yy*32,5,ObjectId.Block));
if(red== 255 && green == 178 & blue == 127)//brown color /lava
handler.addObject(new Block(xx*32,yy*32,6,ObjectId.Block));
if(red== 255 && green == 233 & blue == 127)//yellow/ish color /lava
handler.addObject(new Block(xx*32,yy*32,7,ObjectId.Block));
if(red== 218 && green == 255 & blue == 127)//yellow/ish color /lava
handler.addObject(new Block(xx*32,yy*32,8,ObjectId.Block));
}
else if(LEVEL==2) {
//desrt level
if(red== 0 && green == 0 & blue == 255)//blue color
handler.addObject(new Player(xx*32,yy*32,handler,cam,this,ObjectId.Player));
//if(red== 255 && green == 0 & blue == 220)
//.addObject(new Robot(xx*32,yy*32,ObjectId.Robot,handler));
if(red== 127 && green == 63 & blue == 91)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,0,ObjectId.DesertBlock));
if(red== 255 && green == 0 & blue == 110)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,1,ObjectId.DesertBlock)); //
if(red== 255 && green == 127 & blue == 182)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,2,ObjectId.DesertBlock));
if(red== 255 && green == 0 & blue == 220)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,3,ObjectId.DesertBlock)); // 4
if(red== 127 && green == 0 & blue == 110)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,4,ObjectId.DesertBlock)); //5
if(red== 255 && green == 127 & blue == 237)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,5,ObjectId.DesertBlock)); //
if(red== 127 && green == 63 & blue == 118)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,6,ObjectId.DesertBlock)); //
if(red== 178 && green == 0 & blue == 255)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,7,ObjectId.DesertBlock)); //
if(red== 87 && green == 0 & blue == 127)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,8,ObjectId.DesertBlock)); //
if(red== 214 && green == 127 & blue == 255)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,9,ObjectId.DesertBlock)); //
if(red== 72 && green == 0 & blue == 255)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,10,ObjectId.DesertBlock));//
if(red== 0 && green == 19 & blue == 127)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,11,ObjectId.DesertBlock)); //
if(red== 0 && green == 148 & blue == 255)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,12,ObjectId.DesertBlock));//
if(red== 0 && green == 255 & blue == 255)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,13,ObjectId.DesertBlock)); //
if(red== 0 && green == 255 & blue == 144)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,14,ObjectId.DesertBlock)); //
if(red== 0 && green == 127 & blue == 70)//desert block color
handler.addObject(new DesertBlock(xx*32,yy*32,15,ObjectId.DesertBlock));//
if(red== 255 && green == 216 & blue == 0)//yellow color
handler.addObject(new Flag(xx*32,yy*32,ObjectId.Flag));
if(red== 255 && green == 255 & blue == 255)//white color
handler.addObject(new Zombie(xx*32,yy*32,ObjectId.Zombie,handler));
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void NextLevel () {
LoadImageLevel(level[LEVEL]);
}
public static Texture getInstance() {
return tex;
}
public static void main (String args[]) {
new Window(800,600,"Survive", new Game());
}
}
|
3e19ec60418b5068d4c14e319bda15cd6c4da4f3 | 610 | java | Java | src/main/java/com/subhadeep/rest/webservices/restfulwebservices/model/ExceptionResponse.java | subhadeep-bis/spring-boot-microservices-important-topics | 9dc97241627704c4bb045f0ffc893194a1a7ad6b | [
"MIT"
] | 1 | 2019-08-12T20:35:29.000Z | 2019-08-12T20:35:29.000Z | src/main/java/com/subhadeep/rest/webservices/restfulwebservices/model/ExceptionResponse.java | subhadeep-bis/spring-boot-microservices-important-topics | 9dc97241627704c4bb045f0ffc893194a1a7ad6b | [
"MIT"
] | null | null | null | src/main/java/com/subhadeep/rest/webservices/restfulwebservices/model/ExceptionResponse.java | subhadeep-bis/spring-boot-microservices-important-topics | 9dc97241627704c4bb045f0ffc893194a1a7ad6b | [
"MIT"
] | null | null | null | 21.785714 | 82 | 0.678689 | 11,011 | package com.subhadeep.rest.webservices.restfulwebservices.model;
import java.util.Date;
public class ExceptionResponse {
private Date timeStampDate;
private String message;
private String details;
public ExceptionResponse(Date timeStampDate, String message, String details) {
this.timeStampDate = timeStampDate;
this.message = message;
this.details = details;
}
public Date getTimeStampDate() {
return timeStampDate;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
|
3e19ec66a6f3d440c5e0da9dbac7ef1258cecad3 | 889 | java | Java | core/src/test/java/mysso/authentication/principal/SimpleUserAttributeRepositoryTest.java | rocketk/mysso | 761cd1e00c7d109060359e358af791709b5a7039 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/mysso/authentication/principal/SimpleUserAttributeRepositoryTest.java | rocketk/mysso | 761cd1e00c7d109060359e358af791709b5a7039 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/mysso/authentication/principal/SimpleUserAttributeRepositoryTest.java | rocketk/mysso | 761cd1e00c7d109060359e358af791709b5a7039 | [
"Apache-2.0"
] | null | null | null | 35.56 | 92 | 0.690664 | 11,012 | package mysso.authentication.principal;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* Created by pengyu.
*/
public class SimpleUserAttributeRepositoryTest {
private AttributeRepository getSimpleUserAttributeRepository() {
Map<String, Map<String, Object>> users = new HashMap<>();
Map<String, Object> jackAttributes = new HashMap<>();
jackAttributes.put("department", "technology");
jackAttributes.put("level", "manager");
Map<String, Object> peterAttributes = new HashMap<>();
peterAttributes.put("department", "technology");
peterAttributes.put("level", "manager");
users.put("jack", jackAttributes);
users.put("peter", peterAttributes);
SimpleUserAttributeRepository repository = new SimpleUserAttributeRepository(users);
return repository;
}
} |
3e19ed33d0bbdd081fa0fe36fe011479e1c73fbe | 439 | java | Java | app/src/main/java/com/usiellau/messageforward/other/MyApplication.java | benxhinGH/MessageForward | be6d3660900862b2a1b5af586d18ba246cee7d50 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/usiellau/messageforward/other/MyApplication.java | benxhinGH/MessageForward | be6d3660900862b2a1b5af586d18ba246cee7d50 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/usiellau/messageforward/other/MyApplication.java | benxhinGH/MessageForward | be6d3660900862b2a1b5af586d18ba246cee7d50 | [
"Apache-2.0"
] | null | null | null | 19.086957 | 48 | 0.690205 | 11,013 | package com.usiellau.messageforward.other;
import android.app.Application;
import android.content.Context;
/**
* Created by Administrator on 2017/8/8 0008.
*/
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
}
public static Context getContext(){
return context;
}
}
|
3e19ed99786304d31002985d444f2db32b63a852 | 137 | java | Java | apps/brreg-stub/src/main/java/no/nav/brregstub/api/common/Egenskap.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 3 | 2020-06-30T18:14:44.000Z | 2022-03-07T10:10:48.000Z | apps/brreg-stub/src/main/java/no/nav/brregstub/api/common/Egenskap.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 1,546 | 2020-05-25T14:39:45.000Z | 2022-03-31T13:41:00.000Z | apps/brreg-stub/src/main/java/no/nav/brregstub/api/common/Egenskap.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 1 | 2021-11-03T16:02:17.000Z | 2021-11-03T16:02:17.000Z | 13.7 | 36 | 0.678832 | 11,014 | package no.nav.brregstub.api.common;
public enum Egenskap {
Deltager,
Komplementar,
Kontaktperson,
Sameier,
Styre
}
|
3e19edb5d766afa37d20e73e53889b09a4d3e511 | 476 | java | Java | src/main/java/com/danmoop/novanode/MainApplication/model/ChatMessage.java | danmoop/Ketarn | bc01c47449dcf3d18a9a6da8290682d5ad80982b | [
"MIT"
] | 4 | 2019-11-01T22:16:59.000Z | 2021-02-22T01:40:46.000Z | src/main/java/com/danmoop/novanode/MainApplication/model/ChatMessage.java | danmoop/Ketarn | bc01c47449dcf3d18a9a6da8290682d5ad80982b | [
"MIT"
] | null | null | null | src/main/java/com/danmoop/novanode/MainApplication/model/ChatMessage.java | danmoop/Ketarn | bc01c47449dcf3d18a9a6da8290682d5ad80982b | [
"MIT"
] | 1 | 2022-03-26T07:06:58.000Z | 2022-03-26T07:06:58.000Z | 20.695652 | 52 | 0.67437 | 11,015 | package com.danmoop.novanode.MainApplication.model;
import lombok.Data;
import java.util.Date;
import java.util.UUID;
@Data
public class ChatMessage {
private String text;
private String sender;
private String timeStamp;
private String key;
public ChatMessage(String text, String sender) {
this.text = text;
this.sender = sender;
this.timeStamp = new Date().toString();
this.key = UUID.randomUUID().toString();
}
}
|
3e19eef394f6c2f37ff5e5db5b59b4722d829ff2 | 865 | java | Java | Workspace/org.collin.dashboard/src/org/collin/dashboard/servlet/CollinServlet.java | condast/Collin | 021f33e463b5d7f496fe5a3275c38095d77a31f3 | [
"Apache-2.0"
] | null | null | null | Workspace/org.collin.dashboard/src/org/collin/dashboard/servlet/CollinServlet.java | condast/Collin | 021f33e463b5d7f496fe5a3275c38095d77a31f3 | [
"Apache-2.0"
] | null | null | null | Workspace/org.collin.dashboard/src/org/collin/dashboard/servlet/CollinServlet.java | condast/Collin | 021f33e463b5d7f496fe5a3275c38095d77a31f3 | [
"Apache-2.0"
] | null | null | null | 32.037037 | 111 | 0.754913 | 11,016 | package org.collin.dashboard.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CollinServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String S_REDIRECT_URL = "http://demo.condast.com/TeamZodiac/embed.html";
private static final String S_PATH = "path";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//RequestDispatcher dispatcher = getServletContext()
// .getRequestDispatcher("http://www.condast.com");
// dispatcher.forward(req, resp);
String path = req.getParameter(S_PATH);
resp.sendRedirect( path );
}
}
|
3e19ef10e2611450291a7e4d0d0bf7d66dd00150 | 4,355 | java | Java | support/cas-server-support-pm-webflow/src/test/java/org/apereo/cas/pm/web/flow/actions/BasePasswordManagementActionTests.java | tswstarplanet/cas | c026d1a7598e02e11cd9ed248b76a7973ee67052 | [
"Apache-2.0"
] | 2 | 2018-11-25T03:11:28.000Z | 2018-11-25T03:11:30.000Z | support/cas-server-support-pm-webflow/src/test/java/org/apereo/cas/pm/web/flow/actions/BasePasswordManagementActionTests.java | tswstarplanet/cas | c026d1a7598e02e11cd9ed248b76a7973ee67052 | [
"Apache-2.0"
] | 1 | 2019-11-22T01:13:30.000Z | 2019-11-22T01:13:30.000Z | support/cas-server-support-pm-webflow/src/test/java/org/apereo/cas/pm/web/flow/actions/BasePasswordManagementActionTests.java | tswstarplanet/cas | c026d1a7598e02e11cd9ed248b76a7973ee67052 | [
"Apache-2.0"
] | 1 | 2017-06-27T13:30:08.000Z | 2017-06-27T13:30:08.000Z | 42.696078 | 91 | 0.84225 | 11,017 | package org.apereo.cas.pm.web.flow.actions;
import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasPersonDirectoryTestConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.logout.config.CasCoreLogoutConfiguration;
import org.apereo.cas.pm.PasswordManagementService;
import org.apereo.cas.pm.config.PasswordManagementConfiguration;
import org.apereo.cas.pm.config.PasswordManagementWebflowConfiguration;
import org.apereo.cas.services.web.config.CasThemesConfiguration;
import org.apereo.cas.util.junit.ConditionalIgnoreRule;
import org.apereo.cas.web.config.CasCookieConfiguration;
import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration;
import org.apereo.cas.web.flow.config.CasWebflowContextConfiguration;
import org.junit.ClassRule;
import org.junit.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.webflow.execution.Action;
/**
* This is {@link BasePasswordManagementActionTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@SpringBootTest(classes = {
MailSenderAutoConfiguration.class,
MailSenderValidatorAutoConfiguration.class,
PasswordManagementConfiguration.class,
PasswordManagementWebflowConfiguration.class,
CasCoreServicesConfiguration.class,
CasCoreServicesAuthenticationConfiguration.class,
CasCoreTicketsConfiguration.class,
CasWebApplicationServiceFactoryConfiguration.class,
CasCoreTicketCatalogConfiguration.class,
RefreshAutoConfiguration.class,
CasCoreAuthenticationSupportConfiguration.class,
CasCoreConfiguration.class,
CasCoreLogoutConfiguration.class,
CasCoreAuthenticationServiceSelectionStrategyConfiguration.class,
CasCoreAuthenticationPrincipalConfiguration.class,
CasPersonDirectoryTestConfiguration.class,
CasCookieConfiguration.class,
CasThemesConfiguration.class,
CasCoreUtilConfiguration.class,
CasCoreWebConfiguration.class,
CasCoreWebflowConfiguration.class,
CasCoreHttpConfiguration.class,
CasWebflowContextConfiguration.class
})
@TestPropertySource(locations = "classpath:cas-pm-webflow.properties")
public abstract class BasePasswordManagementActionTests {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Rule
public final ConditionalIgnoreRule conditionalIgnoreRule = new ConditionalIgnoreRule();
@Autowired
@Qualifier("passwordChangeService")
protected PasswordManagementService passwordManagementService;
@Autowired
@Qualifier("verifySecurityQuestionsAction")
protected Action verifySecurityQuestionsAction;
@Autowired
@Qualifier("initPasswordResetAction")
protected Action initPasswordResetAction;
@Autowired
@Qualifier("verifyPasswordResetRequestAction")
protected Action verifyPasswordResetRequestAction;
@Autowired
@Qualifier("sendPasswordResetInstructionsAction")
protected Action sendPasswordResetInstructionsAction;
}
|
3e19efd6a070fcddce106c9bff1e6eb8f2f48aba | 542 | java | Java | src/main/java/com/Herwaarden/Monster/Logic/MonsterLogic.java | coecomber/Juicedms_Monster | 0715631b41a7da89534dfd6fe3fc429001211028 | [
"MIT"
] | null | null | null | src/main/java/com/Herwaarden/Monster/Logic/MonsterLogic.java | coecomber/Juicedms_Monster | 0715631b41a7da89534dfd6fe3fc429001211028 | [
"MIT"
] | 1 | 2022-03-31T19:00:35.000Z | 2022-03-31T19:00:35.000Z | src/main/java/com/Herwaarden/Monster/Logic/MonsterLogic.java | coecomber/Juicedms_Monster | 0715631b41a7da89534dfd6fe3fc429001211028 | [
"MIT"
] | null | null | null | 30.111111 | 76 | 0.791513 | 11,018 | package com.Herwaarden.Monster.Logic;
import com.Herwaarden.Monster.DAL.Interface.Repositories.IMonsterRepository;
import com.Herwaarden.Monster.Factory.MonsterFactory;
import com.Herwaarden.Monster.Model.MonsterModel;
public class MonsterLogic {
private IMonsterRepository monsterRepository;
public MonsterLogic(){
monsterRepository = new MonsterFactory().getMonsterSQLRepository();
}
public MonsterModel getMonsterModelByFloorId(int floorId){
return monsterRepository.getMonsterByFloor(floorId);
}
}
|
3e19f14090712e782a9ae1ad10290b21fb3ccfaf | 3,332 | java | Java | src/com/eleks/rnd/warehouse/glass/Flow.java | pif/glass-warehouse-automation | b2310aebe58d8b96683449244d3f9c26c26f39fa | [
"MIT"
] | 1 | 2015-08-01T03:25:59.000Z | 2015-08-01T03:25:59.000Z | src/com/eleks/rnd/warehouse/glass/Flow.java | eleks/rnd-glass-warehouse-automation | a4422d7dc2f1cda5ae64e19983c9703681ad3d7e | [
"MIT"
] | null | null | null | src/com/eleks/rnd/warehouse/glass/Flow.java | eleks/rnd-glass-warehouse-automation | a4422d7dc2f1cda5ae64e19983c9703681ad3d7e | [
"MIT"
] | 2 | 2016-03-06T16:39:09.000Z | 2020-06-13T12:25:27.000Z | 28.973913 | 94 | 0.597539 | 11,019 | package com.eleks.rnd.warehouse.glass;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import net.sourceforge.zbar.Symbol;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.util.Log;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
public class Flow {
private static final String TAG = "Flow";
public static final String EXTRA_ITEM = "parsed_item";
public static final int VOICE_DATE_REQUEST = 42;
private final Context mContext;
private final Item mCurrentItem;
private static Map<Context, Flow> mContextFlow = new WeakHashMap<Context, Flow>();
public static Flow with(Context ctx) {
if (mContextFlow.containsKey(ctx)) {
return mContextFlow.get(ctx);
} else {
Flow f = new Flow(ctx);
mContextFlow.put(ctx, f);
return f;
}
}
private Flow(Context ctx) {
mContext = ctx;
mCurrentItem = new Item();
}
public void scanned(Symbol sym) {
Log.d(TAG, "Scanned: " + sym.getType() + " text: " + sym.getData());
if (sym.getType() == Symbol.QRCODE) {
String data = sym.getData();
mCurrentItem.copyFrom(Item.parseFrom(data));
if (mCurrentItem.getExpiry() == null) {
getDateViaVoice();
} else {
scannedFullItem();
}
} else {
String data = sym.getData();
mCurrentItem.setId(data);
getDateViaVoice();
}
}
private void scannedFullItem() {
Intent i = new Intent(mContext, ScannedItemActivity.class);
i.putExtra(EXTRA_ITEM, mCurrentItem);
mContext.startActivity(i);
}
private void getDateViaVoice() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say expiry date: month and day");
((Activity) mContext).startActivityForResult(intent, Flow.VOICE_DATE_REQUEST);
}
public void completeWithDate(Intent intent) {
List<String> results = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.d(TAG, "" + results);
Date d = get5thDayFromNow();
if (results.size() > 0) {
String spokenText = results.get(0);
d = parse(spokenText);
}
mCurrentItem.setExpiry(d);
scannedFullItem();
}
/**
*
* @param text
* free form text
* @return null or parsed date
*/
private static Date parse(String text) {
Log.d(TAG, "============= PARSING: " + text);
Parser parser = new Parser();
List<DateGroup> groups = parser.parse(text);
for (DateGroup group : groups) {
List<Date> dates = group.getDates();
Log.d(TAG, "PARSED: " + dates);
if (dates.size() > 0) {
return dates.get(0);
}
}
return null;
}
private static Date get5thDayFromNow() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 5);
return c.getTime();
}
}
|
3e19f1d2100fe7a511f2be0bdcb9e5fd89380ff5 | 618 | java | Java | CodeExercises-JianzhiOffer/src/main/java/com/pan/exercise/Demo008.java | panyexiong/CodeExercises | f200ec93c7fe3f16732c4b2cd8501f84c63b9ab0 | [
"Apache-2.0"
] | null | null | null | CodeExercises-JianzhiOffer/src/main/java/com/pan/exercise/Demo008.java | panyexiong/CodeExercises | f200ec93c7fe3f16732c4b2cd8501f84c63b9ab0 | [
"Apache-2.0"
] | null | null | null | CodeExercises-JianzhiOffer/src/main/java/com/pan/exercise/Demo008.java | panyexiong/CodeExercises | f200ec93c7fe3f16732c4b2cd8501f84c63b9ab0 | [
"Apache-2.0"
] | null | null | null | 21.310345 | 62 | 0.616505 | 11,020 | package com.pan.exercise;
/**
* 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
* 对于本题,前提只有 一次 1阶或者2阶的跳法。
*
* a.如果两种跳法,1阶或者2阶,那么假定第一次跳的是一阶,那么剩下的是n-1个台阶,跳法是f(n-1);
*
* b.假定第一次跳的是2阶,那么剩下的是n-2个台阶,跳法是f(n-2)
*
* c.由a\b假设可以得出总跳法为: f(n) = f(n-1) + f(n-2)
*
* d.然后通过实际的情况可以得出:只有一阶的时候 f(1) = 1 ,只有两阶的时候可以有 f(2) = 2
*
* e.可以发现最终得出的是一个斐波那契数列:
*
* @author panyexiong
* @version 1.0
* @date 2019/8/24 13:20
*/
public class Demo008 {
public int JumpFloor(int target) {
if (target <= 1) {
return 1;
}
return JumpFloor(target - 1) + JumpFloor(target - 2);
}
}
|
3e19f1f39bcc9185b1755aea20b544b28c65caa6 | 498 | java | Java | gulimall-order/src/main/java/com/clearlove3/gulimall/order/service/OrderOperateHistoryService.java | Fanjialiang18/clearlove3-gulimall | 298978807c4372cea7536061fbba5c3b0d24ee24 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/clearlove3/gulimall/order/service/OrderOperateHistoryService.java | Fanjialiang18/clearlove3-gulimall | 298978807c4372cea7536061fbba5c3b0d24ee24 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/clearlove3/gulimall/order/service/OrderOperateHistoryService.java | Fanjialiang18/clearlove3-gulimall | 298978807c4372cea7536061fbba5c3b0d24ee24 | [
"Apache-2.0"
] | null | null | null | 23.952381 | 89 | 0.791252 | 11,021 | package com.clearlove3.gulimall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.clearlove3.common.utils.PageUtils;
import com.clearlove3.gulimall.order.entity.OrderOperateHistoryEntity;
import java.util.Map;
/**
* 订单操作历史记录
*
* @author clearlove3
* @email ychag@example.com
* @date 2021-11-02 17:11:11
*/
public interface OrderOperateHistoryService extends IService<OrderOperateHistoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
3e19f1febe5fd7217c72cc26a0cb2b563fab0b69 | 611 | java | Java | src/com/techsect/clashmate/fragments/NewsFragment.java | hitenpratap/FragSliderAndroid | 7cf9cec8646a892551740f9781e62be3c7842d47 | [
"MIT"
] | null | null | null | src/com/techsect/clashmate/fragments/NewsFragment.java | hitenpratap/FragSliderAndroid | 7cf9cec8646a892551740f9781e62be3c7842d47 | [
"MIT"
] | null | null | null | src/com/techsect/clashmate/fragments/NewsFragment.java | hitenpratap/FragSliderAndroid | 7cf9cec8646a892551740f9781e62be3c7842d47 | [
"MIT"
] | null | null | null | 23.5 | 83 | 0.715221 | 11,022 | package com.techsect.clashmate.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.techsect.clashmate.R;
/**
* Created by hitenpratap on 4/8/15.
*/
public class NewsFragment extends Fragment {
public NewsFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
return rootView;
}
}
|
3e19f48ea31704a4caf741cc563dcd50efc5322d | 936 | java | Java | 2-intro-spark/src/main/java/edu/sdsc/mmtf/exercises/Solution11.java | 8cat/mmtf-workshop-2017 | 34a68857186663af6e6428815c37e6d743dd6864 | [
"Apache-2.0"
] | 19 | 2017-06-26T18:30:45.000Z | 2020-10-29T09:26:28.000Z | 2-intro-spark/src/main/java/edu/sdsc/mmtf/exercises/Solution11.java | 8cat/mmtf-workshop-2017 | 34a68857186663af6e6428815c37e6d743dd6864 | [
"Apache-2.0"
] | null | null | null | 2-intro-spark/src/main/java/edu/sdsc/mmtf/exercises/Solution11.java | 8cat/mmtf-workshop-2017 | 34a68857186663af6e6428815c37e6d743dd6864 | [
"Apache-2.0"
] | 39 | 2017-06-26T15:34:10.000Z | 2021-04-07T08:52:55.000Z | 27.529412 | 102 | 0.695513 | 11,023 | package edu.sdsc.mmtf.exercises;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;
import java.util.Arrays;
public class Solution11 {
/** Example on usage of reduceByKey() transformation.
*
* @author Yana Valasatava
*/
public static void main(String[] args) {
SparkConf conf = new SparkConf().setMaster("local[*]").setAppName(Solution11.class.getSimpleName());
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<String> rdd = sc.parallelize(Arrays.asList("a", "b", "a", "a", "b", "b", "b", "b"));
JavaPairRDD<String, Integer> pairRdd = rdd.mapToPair(t -> new Tuple2<String, Integer>(t, 1));
// TODO
// count how many times each letter occurs
pairRdd.reduceByKey((x, y) -> x + y).foreach(t -> System.out.println(t._1 + ": " + t._2));
sc.close();
}
}
|
3e19f4b3a64b1241ca5439ffb0e6e968f9e143ea | 9,256 | java | Java | main/boofcv-ip/src/boofcv/core/image/impl/ImplConvertMsToGray.java | yannickhildebrandt/BoofCV | fdc3ff778c1b4d296ee2154285d3379fb326941e | [
"Apache-2.0"
] | 1 | 2020-02-02T00:17:35.000Z | 2020-02-02T00:17:35.000Z | main/boofcv-ip/src/boofcv/core/image/impl/ImplConvertMsToGray.java | yannickhildebrandt/BoofCV | fdc3ff778c1b4d296ee2154285d3379fb326941e | [
"Apache-2.0"
] | null | null | null | main/boofcv-ip/src/boofcv/core/image/impl/ImplConvertMsToGray.java | yannickhildebrandt/BoofCV | fdc3ff778c1b4d296ee2154285d3379fb326941e | [
"Apache-2.0"
] | null | null | null | 26.828986 | 120 | 0.570657 | 11,024 | /*
* Copyright (c) 2011-2017, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.core.image.impl;
import boofcv.struct.image.*;
/**
* Low level implementations of different methods for converting {@link Planar} into
* {@link ImageGray}.
*
* <ul>
* <li>Average computes the average value of each pixel across the bands.
* </ul>
*
* <p>
* DO NOT MODIFY: This class was automatically generated by {@link boofcv.core.image.impl.GenerateImplConvertMsToSingle}
* </p>
*
* @author Peter Abeles
*/
public class ImplConvertMsToGray {
public static void average(Planar<GrayU8> from , GrayU8 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayU8 band0 = from.getBand(0);
GrayU8 band1 = from.getBand(1);
GrayU8 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = band0.data[indexFrom]& 0xFF;
sum += band1.data[indexFrom]& 0xFF;
sum += band2.data[indexFrom]& 0xFF;
to.data[indexTo++] = (byte)(sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom]& 0xFF;
}
to.data[indexTo++] = (byte)(sum/numBands);
}
}
}
}
public static void average(Planar<GrayS8> from , GrayS8 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayS8 band0 = from.getBand(0);
GrayS8 band1 = from.getBand(1);
GrayS8 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = band0.data[indexFrom];
sum += band1.data[indexFrom];
sum += band2.data[indexFrom];
to.data[indexTo++] = (byte)(sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom];
}
to.data[indexTo++] = (byte)(sum/numBands);
}
}
}
}
public static void average(Planar<GrayU16> from , GrayU16 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayU16 band0 = from.getBand(0);
GrayU16 band1 = from.getBand(1);
GrayU16 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = band0.data[indexFrom]& 0xFFFF;
sum += band1.data[indexFrom]& 0xFFFF;
sum += band2.data[indexFrom]& 0xFFFF;
to.data[indexTo++] = (short)(sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom]& 0xFFFF;
}
to.data[indexTo++] = (short)(sum/numBands);
}
}
}
}
public static void average(Planar<GrayS16> from , GrayS16 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayS16 band0 = from.getBand(0);
GrayS16 band1 = from.getBand(1);
GrayS16 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = band0.data[indexFrom];
sum += band1.data[indexFrom];
sum += band2.data[indexFrom];
to.data[indexTo++] = (short)(sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom];
}
to.data[indexTo++] = (short)(sum/numBands);
}
}
}
}
public static void average(Planar<GrayS32> from , GrayS32 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayS32 band0 = from.getBand(0);
GrayS32 band1 = from.getBand(1);
GrayS32 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = band0.data[indexFrom];
sum += band1.data[indexFrom];
sum += band2.data[indexFrom];
to.data[indexTo++] = (sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
int sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom];
}
to.data[indexTo++] = (sum/numBands);
}
}
}
}
public static void average(Planar<GrayS64> from , GrayS64 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayS64 band0 = from.getBand(0);
GrayS64 band1 = from.getBand(1);
GrayS64 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
long sum = band0.data[indexFrom];
sum += band1.data[indexFrom];
sum += band2.data[indexFrom];
to.data[indexTo++] = (sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
long sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom];
}
to.data[indexTo++] = (sum/numBands);
}
}
}
}
public static void average(Planar<GrayF32> from , GrayF32 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayF32 band0 = from.getBand(0);
GrayF32 band1 = from.getBand(1);
GrayF32 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
float sum = band0.data[indexFrom];
sum += band1.data[indexFrom];
sum += band2.data[indexFrom];
to.data[indexTo++] = (sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
float sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom];
}
to.data[indexTo++] = (sum/numBands);
}
}
}
}
public static void average(Planar<GrayF64> from , GrayF64 to ) {
int numBands = from.getNumBands();
if( numBands == 1 ) {
to.setTo(from.getBand(0));
} else if( numBands == 3 ) {
GrayF64 band0 = from.getBand(0);
GrayF64 band1 = from.getBand(1);
GrayF64 band2 = from.getBand(2);
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
double sum = band0.data[indexFrom];
sum += band1.data[indexFrom];
sum += band2.data[indexFrom];
to.data[indexTo++] = (sum/3);
}
}
} else {
for (int y = 0; y < from.height; y++) {
int indexFrom = from.getIndex(0, y);
int indexTo = to.getIndex(0, y);
for (int x = 0; x < from.width; x++ , indexFrom++ ) {
double sum = 0;
for( int b = 0; b < numBands; b++ ) {
sum += from.bands[b].data[indexFrom];
}
to.data[indexTo++] = (sum/numBands);
}
}
}
}
}
|
3e19f4bd8c083d5e4dcc98c3a94719608c302d4f | 2,033 | java | Java | Binding/apple/src/main/java/com/bugvm/apple/iad/ADClientErrorCode.java | bugvm/robovm | 430cbeb4a9f49f48b982821b40741fad110efe57 | [
"MIT"
] | 29 | 2018-06-04T21:34:00.000Z | 2022-02-21T16:34:44.000Z | Binding/apple/src/main/java/com/bugvm/apple/iad/ADClientErrorCode.java | bugvm/robovm | 430cbeb4a9f49f48b982821b40741fad110efe57 | [
"MIT"
] | 15 | 2018-03-02T03:38:56.000Z | 2021-03-22T02:06:14.000Z | Binding/apple/src/main/java/com/bugvm/apple/iad/ADClientErrorCode.java | bugvm/robovm | 430cbeb4a9f49f48b982821b40741fad110efe57 | [
"MIT"
] | 6 | 2018-10-17T02:28:28.000Z | 2020-11-27T04:47:50.000Z | 31.119403 | 91 | 0.654197 | 11,025 | /*
* Copyright (C) 2013-2015 RoboVM AB
*
* 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.bugvm.apple.iad;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import com.bugvm.objc.*;
import com.bugvm.objc.annotation.*;
import com.bugvm.objc.block.*;
import com.bugvm.rt.*;
import com.bugvm.rt.annotation.*;
import com.bugvm.rt.bro.*;
import com.bugvm.rt.bro.annotation.*;
import com.bugvm.rt.bro.ptr.*;
import com.bugvm.apple.foundation.*;
import com.bugvm.apple.uikit.*;
import com.bugvm.apple.mediaplayer.*;
import com.bugvm.apple.coregraphics.*;
import com.bugvm.apple.avkit.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<ychag@example.com)/*</annotations>*/
@ForceLinkClass(ADClientError.class)
public enum /*<name>*/ADClientErrorCode/*</name>*/ implements NSErrorCode {
/*<values>*/
Unknown(0L),
LimitAdTracking(1L);
/*</values>*/
/*<bind>*/
/*</bind>*/
/*<constants>*//*</constants>*/
/*<methods>*//*</methods>*/
private final long n;
private /*<name>*/ADClientErrorCode/*</name>*/(long n) { this.n = n; }
public long value() { return n; }
public static /*<name>*/ADClientErrorCode/*</name>*/ valueOf(long n) {
for (/*<name>*/ADClientErrorCode/*</name>*/ v : values()) {
if (v.n == n) {
return v;
}
}
throw new IllegalArgumentException("No constant with value " + n + " found in "
+ /*<name>*/ADClientErrorCode/*</name>*/.class.getName());
}
}
|
3e19f4f321b0c92f8b481633cbea05fb52b79bfb | 24,502 | java | Java | java/java.editor.base/src/org/netbeans/modules/java/editor/base/semantic/UnusedDetector.java | 86dh/netbeans | d97a211d0d44f4d13a5c0f1f8fad420a9f71cfae | [
"Apache-2.0"
] | 988 | 2017-09-11T15:04:49.000Z | 2019-04-25T14:25:21.000Z | java/java.editor.base/src/org/netbeans/modules/java/editor/base/semantic/UnusedDetector.java | 86dh/netbeans | d97a211d0d44f4d13a5c0f1f8fad420a9f71cfae | [
"Apache-2.0"
] | 907 | 2017-09-16T17:35:25.000Z | 2019-04-25T00:53:46.000Z | java/java.editor.base/src/org/netbeans/modules/java/editor/base/semantic/UnusedDetector.java | 86dh/netbeans | d97a211d0d44f4d13a5c0f1f8fad420a9f71cfae | [
"Apache-2.0"
] | 415 | 2017-09-11T16:44:14.000Z | 2019-04-25T01:09:42.000Z | 42.391003 | 145 | 0.557995 | 11,026 | /*
* 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.netbeans.modules.java.editor.base.semantic;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.netbeans.api.java.source.ClassIndex;
import org.netbeans.api.java.source.CompilationInfo;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.java.source.support.ErrorAwareTreePathScanner;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
/**
*
* @author lahvac
*/
public class UnusedDetector {
public static class UnusedDescription {
public final Element unusedElement;
public final TreePath unusedElementPath;
public final UnusedReason reason;
public UnusedDescription(Element unusedElement, TreePath unusedElementPath, UnusedReason reason) {
this.unusedElement = unusedElement;
this.unusedElementPath = unusedElementPath;
this.reason = reason;
}
}
public enum UnusedReason {
NOT_WRITTEN_READ("neither read or written to"),
NOT_WRITTEN("never written to"), //makes sense?
NOT_READ("never read"),
NOT_USED("never used");
private final String text;
private UnusedReason(String text) {
this.text = text;
}
}
public static List<UnusedDescription> findUnused(CompilationInfo info) {
List<UnusedDescription> cached = (List<UnusedDescription>) info.getCachedValue(UnusedDetector.class);
if (cached != null) {
return cached;
}
UnusedVisitor uv = new UnusedVisitor(info);
uv.scan(info.getCompilationUnit(), null);
List<UnusedDescription> result = new ArrayList<>();
for (Entry<Element, TreePath> e : uv.element2Declaration.entrySet()) {
Element el = e.getKey();
TreePath declaration = e.getValue();
Set<UseTypes> uses = uv.useTypes.getOrDefault(el, Collections.emptySet());
boolean isPrivate = el.getModifiers().contains(Modifier.PRIVATE); //TODO: effectivelly private!
boolean isPkgPrivate = !isPrivate && !el.getModifiers().contains(Modifier.PUBLIC) && !el.getModifiers().contains(Modifier.PROTECTED);
if (isLocalVariableClosure(el)) {
boolean isWritten = uses.contains(UseTypes.WRITTEN);
boolean isRead = uses.contains(UseTypes.READ);
if (!isWritten && !isRead) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_WRITTEN_READ));
} else if (!isWritten) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_WRITTEN));
} else if (!isRead) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_READ));
}
} else if (el.getKind().isField() && (isPrivate || isPkgPrivate)) {
if (!isSerialSpecField(info, el)) {
boolean isWritten = uses.contains(UseTypes.WRITTEN);
boolean isRead = uses.contains(UseTypes.READ);
if (!isWritten && !isRead) {
if (isPrivate || isUnusedInPkg(info, el)) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_WRITTEN_READ));
}
} else if (!isWritten) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_WRITTEN));
} else if (!isRead) {
if (isPrivate || isUnusedInPkg(info, el)) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_READ));
}
}
}
} else if ((el.getKind() == ElementKind.CONSTRUCTOR || el.getKind() == ElementKind.METHOD) && (isPrivate || isPkgPrivate)) {
if (!isSerializationMethod(info, (ExecutableElement)el) && !uses.contains(UseTypes.USED)) {
if (isPrivate || isUnusedInPkg(info, el)) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_USED));
}
}
} else if ((el.getKind().isClass() || el.getKind().isInterface()) && (isPrivate || isPkgPrivate)) {
if (!uses.contains(UseTypes.USED)) {
if (isPrivate || isUnusedInPkg(info, el)) {
result.add(new UnusedDescription(el, declaration, UnusedReason.NOT_USED));
}
}
}
}
info.putCachedValue(UnusedDetector.class, result, CompilationInfo.CacheClearPolicy.ON_CHANGE);
return result;
}
/** Detects static final long SerialVersionUID
* @return true if element is static final long serialVersionUID
*/
private static boolean isSerialSpecField(CompilationInfo info, Element el) {
if (el.getModifiers().contains(Modifier.FINAL)
&& el.getModifiers().contains(Modifier.STATIC)) {
if (!isInSerializableOrExternalizable(info, el)) {
return false;
}
if (info.getTypes().getPrimitiveType(TypeKind.LONG).equals(el.asType())
&& el.getSimpleName().toString().equals("serialVersionUID")) {
return true;
}
if (el.getSimpleName().contentEquals("serialPersistentFields")) {
return true;
}
}
return false;
}
/**
* Also returns true on error / undecidable situation, so the filtering
* will probably accept serial methods and will not mark them as unused, if
* the class declaration is errneous.
*
* @param info the compilation context
* @param e the class member (the enclosing element will be tested)
* @return true, if in serializable/externalizable or unknown
*/
private static boolean isInSerializableOrExternalizable(CompilationInfo info, Element e) {
Element encl = e.getEnclosingElement();
if (encl == null || !encl.getKind().isClass()) {
return true;
}
TypeMirror m = encl.asType();
if (m == null || m.getKind() != TypeKind.DECLARED) {
return true;
}
Element serEl = info.getElements().getTypeElement("java.io.Serializable"); // NOI18N
Element extEl = info.getElements().getTypeElement("java.io.Externalizable"); // NOI18N
if (serEl == null || extEl == null) {
return true;
}
if (info.getTypes().isSubtype(m, serEl.asType())) {
return true;
}
if (info.getTypes().isSubtype(m, extEl.asType())) {
return true;
}
return false;
}
private static Field signatureAccessField;
/**
* Hack to get signature out of ElementHandle - there's no API method for that
*/
private static String _getSignatureHack(ElementHandle<ExecutableElement> eh) {
try {
if (signatureAccessField == null) {
try {
Field f = ElementHandle.class.getDeclaredField("signatures"); // NOI18N
f.setAccessible(true);
signatureAccessField = f;
} catch (NoSuchFieldException | SecurityException ex) {
// ignore
return ""; // NOI18N
}
}
String[] signs = (String[])signatureAccessField.get(eh);
if (signs == null || signs.length != 3) {
return ""; // NOI18N
} else {
return signs[1] + signs[2];
}
} catch (IllegalArgumentException | IllegalAccessException ex) {
return ""; // NOI18N
}
}
/**
* Checks if the method is specified by Serialization API and the class
* extends Serializable/Externalizable. Unused methods defined in API spec
* should not be marked as unused.
*
* @param info compilation context
* @param method the method
* @return true, if the method is from serialization API and should not be reported
*/
private static boolean isSerializationMethod(CompilationInfo info, ExecutableElement method) {
if (!isInSerializableOrExternalizable(info, method)) {
return false;
}
ElementHandle<ExecutableElement> eh = ElementHandle.create(method);
String sign = _getSignatureHack(eh);
return SERIALIZABLE_SIGNATURES.contains(sign);
}
/**
* Signatures of Serializable methods.
*/
private static final Set<String> SERIALIZABLE_SIGNATURES = new HashSet<>(Arrays.asList(new String[] {
"writeObject(Ljava/io/ObjectOutputStream;)V",
"readObject(Ljava/io/ObjectInputStream;)V",
"readResolve()Ljava/lang/Object;",
"writeReplace()Ljava/lang/Object;",
"readObjectNoData()V",
}));
private static final Set<ElementKind> LOCAL_VARIABLES = EnumSet.of(
ElementKind.LOCAL_VARIABLE, ElementKind.RESOURCE_VARIABLE,
ElementKind.EXCEPTION_PARAMETER, ElementKind.BINDING_VARIABLE);
private static boolean isLocalVariableClosure(Element el) {
return el.getKind() == ElementKind.PARAMETER ||
LOCAL_VARIABLES.contains(el.getKind());
}
private static boolean isUnusedInPkg(CompilationInfo info, Element el) {
TypeElement typeElement;
Set<? extends String> packageSet = Collections.singleton(info.getElements().getPackageOf(el).getQualifiedName().toString());
Set<ClassIndex.SearchKind> searchKinds;
Set<ClassIndex.SearchScopeType> scope = Collections.singleton(new ClassIndex.SearchScopeType() {
@Override
public Set<? extends String> getPackages() {
return packageSet;
}
@Override
public boolean isSources() {
return true;
}
@Override
public boolean isDependencies() {
return false;
}
});
switch (el.getKind()) {
case FIELD:
typeElement = info.getElementUtilities().enclosingTypeElement(el);
searchKinds = EnumSet.of(ClassIndex.SearchKind.FIELD_REFERENCES);
break;
case METHOD:
case CONSTRUCTOR:
typeElement = info.getElementUtilities().enclosingTypeElement(el);
searchKinds = EnumSet.of(ClassIndex.SearchKind.METHOD_REFERENCES);
break;
case ANNOTATION_TYPE:
case CLASS:
case ENUM:
case INTERFACE:
List<? extends TypeElement> topLevelElements = info.getTopLevelElements();
if (topLevelElements.size() == 1 && topLevelElements.get(0) == el) {
return false;
}
typeElement = (TypeElement) el;
searchKinds = EnumSet.of(ClassIndex.SearchKind.TYPE_REFERENCES);
break;
default:
return true;
}
ElementHandle eh = ElementHandle.create(el);
Set<FileObject> res = info.getClasspathInfo().getClassIndex().getResources(ElementHandle.create(typeElement), searchKinds, scope);
if (res != null) {
for (FileObject fo : res) {
if (fo != info.getFileObject()) {
JavaSource js = JavaSource.forFileObject(fo);
if (js == null) {
return false;
}
AtomicBoolean found = new AtomicBoolean();
try {
js.runUserActionTask(cc -> {
cc.toPhase(JavaSource.Phase.RESOLVED);
new TreePathScanner<Void, Element>() {
@Override
public Void scan(Tree tree, Element p) {
if (!found.get() && tree != null) {
Element element = cc.getTrees().getElement(new TreePath(getCurrentPath(), tree));
if (element != null && eh.signatureEquals(element)) {
found.set(true);
}
super.scan(tree, p);
}
return null;
}
}.scan(new TreePath(cc.getCompilationUnit()), el);
}, true);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
if (found.get()) {
return false;
}
}
}
return true;
}
return false;
}
private enum UseTypes {
READ, WRITTEN, USED;
}
private static final class UnusedVisitor extends ErrorAwareTreePathScanner<Void, Void> {
private final Map<Element, Set<UseTypes>> useTypes = new HashMap<>();
private final Map<Element, TreePath> element2Declaration = new HashMap<>();
private final CompilationInfo info;
private ExecutableElement recursionDetector;
public UnusedVisitor(CompilationInfo info) {
this.info = info;
}
@Override
public Void visitIdentifier(IdentifierTree node, Void p) {
handleUse();
return super.visitIdentifier(node, p);
}
@Override
public Void visitMemberSelect(MemberSelectTree node, Void p) {
handleUse();
return super.visitMemberSelect(node, p);
}
@Override
public Void visitMemberReference(MemberReferenceTree node, Void p) {
handleUse();
return super.visitMemberReference(node, p);
}
@Override
public Void visitNewClass(NewClassTree node, Void p) {
handleUse();
return super.visitNewClass(node, p);
}
private void handleUse() {
Element el = info.getTrees().getElement(getCurrentPath());
if (el == null) {
return ;
}
boolean isPrivate = el.getModifiers().contains(Modifier.PRIVATE); //TODO: effectivelly private!
boolean isPkgPrivate = !isPrivate && !el.getModifiers().contains(Modifier.PUBLIC) && !el.getModifiers().contains(Modifier.PROTECTED);
if (isLocalVariableClosure(el) || (el.getKind().isField() && (isPrivate | isPkgPrivate))) {
TreePath effectiveUse = getCurrentPath();
boolean isWrite = false;
boolean isRead = false;
OUTER: while (true) {
TreePath parent = effectiveUse.getParentPath();
switch (parent.getLeaf().getKind()) {
case ASSIGNMENT:
AssignmentTree at = (AssignmentTree) parent.getLeaf();
if (at.getVariable() == effectiveUse.getLeaf()) {
isWrite = true;
} else if (at.getExpression() == effectiveUse.getLeaf()) {
isRead = true;
}
break OUTER;
case AND_ASSIGNMENT: case DIVIDE_ASSIGNMENT:
case LEFT_SHIFT_ASSIGNMENT: case MINUS_ASSIGNMENT:
case MULTIPLY_ASSIGNMENT: case OR_ASSIGNMENT:
case PLUS_ASSIGNMENT: case REMAINDER_ASSIGNMENT:
case RIGHT_SHIFT_ASSIGNMENT: case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT:
case XOR_ASSIGNMENT:
CompoundAssignmentTree cat = (CompoundAssignmentTree) parent.getLeaf();
if (cat.getVariable() == effectiveUse.getLeaf()) {
//check if the results of compound assignment is used:
effectiveUse = parent;
break;
}
//use on the right hand side of the compound assignment - consider as read
isRead = true;
break OUTER;
case EXPRESSION_STATEMENT:
break OUTER;
default:
isRead = true;
break OUTER;
}
}
if (isWrite) {
addUse(el, UseTypes.WRITTEN);
}
if (isRead) {
addUse(el, UseTypes.READ);
}
} else if (isPrivate | isPkgPrivate) {
if (el.getKind() != ElementKind.METHOD || recursionDetector != el)
addUse(el, UseTypes.USED);
}
}
private void addUse(Element el, UseTypes type) {
useTypes.computeIfAbsent(el, x -> EnumSet.noneOf(UseTypes.class)).add(type);
}
@Override
public Void visitClass(ClassTree node, Void p) {
ExecutableElement prevRecursionDetector = recursionDetector;
try {
recursionDetector = null;
handleDeclaration(getCurrentPath());
return super.visitClass(node, p);
} finally {
recursionDetector = prevRecursionDetector;
}
}
@Override
public Void visitVariable(VariableTree node, Void p) {
handleDeclaration(getCurrentPath());
return super.visitVariable(node, p);
}
@Override
public Void visitMethod(MethodTree node, Void p) {
ExecutableElement prevRecursionDetector = recursionDetector;
try {
Element el = info.getTrees().getElement(getCurrentPath());
recursionDetector = (el != null && el.getKind() == ElementKind.METHOD) ? (ExecutableElement) el : null;
handleDeclaration(getCurrentPath());
return super.visitMethod(node, p);
} finally {
recursionDetector = prevRecursionDetector;
}
}
private void handleDeclaration(TreePath path) {
Element el = info.getTrees().getElement(path);
if (el == null) {
return ;
}
element2Declaration.put(el, path);
if (el.getKind() == ElementKind.PARAMETER) {
addUse(el, UseTypes.WRITTEN);
boolean read = true;
Tree parent = path.getParentPath().getLeaf();
if (parent.getKind() == Kind.METHOD) {
MethodTree method = (MethodTree) parent;
Set<Modifier> mods = method.getModifiers().getFlags();
if (method.getParameters().contains(path.getLeaf()) &&
mods.contains(Modifier.PRIVATE) && !mods.contains(Modifier.ABSTRACT) &&
!mods.contains(Modifier.NATIVE)) {
read = false;
}
}
if (read) {
addUse(el, UseTypes.READ);
}
} else if (el.getKind() == ElementKind.EXCEPTION_PARAMETER) {
//Ignore unread caught exceptions. There are valid reasons why it
//could be unused; and there should be a separate hint checking if
//it makes sense to no use it:
addUse(el, UseTypes.READ);
addUse(el, UseTypes.WRITTEN);
} else if (el.getKind() == ElementKind.BINDING_VARIABLE) {
addUse(el, UseTypes.WRITTEN);
} else if (el.getKind() == ElementKind.LOCAL_VARIABLE) {
Tree parent = path.getParentPath().getLeaf();
if (parent.getKind() == Kind.ENHANCED_FOR_LOOP &&
((EnhancedForLoopTree) parent).getVariable() == path.getLeaf()) {
addUse(el, UseTypes.WRITTEN);
}
} else if (Utilities.toRecordComponent(el).getKind() == ElementKind.RECORD_COMPONENT) {
addUse(el, UseTypes.READ);
addUse(el, UseTypes.WRITTEN);
} else if (el.getKind().isField()) {
addUse(el, UseTypes.WRITTEN);
} else if (el.getKind() == ElementKind.CONSTRUCTOR &&
el.getModifiers().contains(Modifier.PRIVATE) &&
((ExecutableElement) el).getParameters().isEmpty()) {
//check if this constructor prevent initalization of "utility" class,
//in which case, it is not "unused":
TypeElement encl = (TypeElement) el.getEnclosingElement();
TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object");
boolean utility = !encl.getModifiers().contains(Modifier.ABSTRACT) &&
encl.getInterfaces().isEmpty() &&
(jlObject == null || info.getTypes().isSameType(encl.getSuperclass(), jlObject.asType()));
for (Element sibling : el.getEnclosingElement().getEnclosedElements()) {
if (sibling.getKind() == ElementKind.CONSTRUCTOR && !sibling.equals(el)) {
utility = false;
break;
} else if ((sibling.getKind().isField() || sibling.getKind() == ElementKind.METHOD) &&
!sibling.getModifiers().contains(Modifier.STATIC)) {
utility = false;
break;
}
}
if (utility) {
addUse(el, UseTypes.USED);
}
}
if (path.getLeaf().getKind() == Kind.VARIABLE) {
VariableTree vt = (VariableTree) path.getLeaf();
if (vt.getInitializer() != null) {
addUse(el, UseTypes.WRITTEN);
}
}
}
}
}
|
3e19f562ad6b2a408406b899f336b4f10bd9df63 | 2,224 | java | Java | src/main/java/com/qdesrame/openapi/diff/model/ChangedOAuthFlow.java | cortexapps/openapi-diff | 3673bbf75fb1419273a02248e45e814b7fd3980b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/qdesrame/openapi/diff/model/ChangedOAuthFlow.java | cortexapps/openapi-diff | 3673bbf75fb1419273a02248e45e814b7fd3980b | [
"Apache-2.0"
] | 1 | 2021-01-11T22:21:51.000Z | 2021-01-11T22:21:51.000Z | src/main/java/com/qdesrame/openapi/diff/model/ChangedOAuthFlow.java | cortexapps/openapi-diff | 3673bbf75fb1419273a02248e45e814b7fd3980b | [
"Apache-2.0"
] | null | null | null | 24.711111 | 75 | 0.702338 | 11,027 | package com.qdesrame.openapi.diff.model;
import io.swagger.v3.oas.models.security.OAuthFlow;
import java.util.Collections;
import java.util.List;
/** Created by adarsh.sharma on 12/01/18. */
public class ChangedOAuthFlow implements ComposedChanged {
private OAuthFlow oldOAuthFlow;
private OAuthFlow newOAuthFlow;
private boolean authorizationUrl;
private boolean tokenUrl;
private boolean refreshUrl;
private ChangedExtensions extensions;
public ChangedOAuthFlow(OAuthFlow oldOAuthFlow, OAuthFlow newOAuthFlow) {
this.oldOAuthFlow = oldOAuthFlow;
this.newOAuthFlow = newOAuthFlow;
}
@Override
public List<Changed> getChangedElements() {
return Collections.singletonList(extensions);
}
@Override
public DiffResult isCoreChanged() {
if (authorizationUrl || tokenUrl || refreshUrl) {
return DiffResult.INCOMPATIBLE;
}
return DiffResult.NO_CHANGES;
}
public OAuthFlow getOldOAuthFlow() {
return this.oldOAuthFlow;
}
public OAuthFlow getNewOAuthFlow() {
return this.newOAuthFlow;
}
public boolean isAuthorizationUrl() {
return this.authorizationUrl;
}
public boolean isTokenUrl() {
return this.tokenUrl;
}
public boolean isRefreshUrl() {
return this.refreshUrl;
}
public ChangedExtensions getExtensions() {
return this.extensions;
}
public ChangedOAuthFlow setOldOAuthFlow(OAuthFlow oldOAuthFlow) {
this.oldOAuthFlow = oldOAuthFlow;
return this;
}
public ChangedOAuthFlow setNewOAuthFlow(OAuthFlow newOAuthFlow) {
this.newOAuthFlow = newOAuthFlow;
return this;
}
public ChangedOAuthFlow setAuthorizationUrl(boolean authorizationUrl) {
this.authorizationUrl = authorizationUrl;
return this;
}
public ChangedOAuthFlow setTokenUrl(boolean tokenUrl) {
this.tokenUrl = tokenUrl;
return this;
}
public ChangedOAuthFlow setRefreshUrl(boolean refreshUrl) {
this.refreshUrl = refreshUrl;
return this;
}
public ChangedOAuthFlow setExtensions(ChangedExtensions extensions) {
this.extensions = extensions;
return this;
}
}
|
3e19f56e3e40169a524759aaf445b414bb534bcf | 1,188 | java | Java | cloudnet-common/src/test/java/de/dytanic/cloudnet/common/language/LanguageManagerTest.java | Unknown-Fllooo/CloudNet-v3 | 61530f0f0276a84661878981ceacd72396d2bdaf | [
"ECL-2.0",
"Apache-2.0"
] | 304 | 2019-05-21T17:38:14.000Z | 2022-03-28T05:21:13.000Z | cloudnet-common/src/test/java/de/dytanic/cloudnet/common/language/LanguageManagerTest.java | Unknown-Fllooo/CloudNet-v3 | 61530f0f0276a84661878981ceacd72396d2bdaf | [
"ECL-2.0",
"Apache-2.0"
] | 338 | 2019-05-25T07:21:34.000Z | 2022-03-31T06:33:00.000Z | cloudnet-common/src/test/java/de/dytanic/cloudnet/common/language/LanguageManagerTest.java | Unknown-Fllooo/CloudNet-v3 | 61530f0f0276a84661878981ceacd72396d2bdaf | [
"ECL-2.0",
"Apache-2.0"
] | 269 | 2019-05-22T05:26:45.000Z | 2022-03-02T13:11:20.000Z | 32.108108 | 84 | 0.749158 | 11,028 | /*
* Copyright 2019-2021 CloudNetService team & contributors
*
* 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 de.dytanic.cloudnet.common.language;
import de.dytanic.cloudnet.common.Properties;
import org.junit.Assert;
import org.junit.Test;
public class LanguageManagerTest {
@Test
public void test() {
Properties properties = new Properties();
properties.put("test_message", "Test_Message");
LanguageManager.setLanguage("en");
LanguageManager.addLanguageFile("en", properties);
Assert.assertNotNull(LanguageManager.getMessage("test_message"));
Assert.assertEquals("Test_Message", LanguageManager.getMessage("test_message"));
}
}
|
3e19f607ce7734a6f7f415210bfd99c583c4f5c4 | 465 | java | Java | Manager/src/main/java/com/rainbow/kam/ble_gatt_manager/exceptions/gatt/GattRssiException.java | kam6512/BLE-Gatt_Manager | 7e03d43e9e3307e5e67adfb4515011d0f32a8d01 | [
"MIT"
] | null | null | null | Manager/src/main/java/com/rainbow/kam/ble_gatt_manager/exceptions/gatt/GattRssiException.java | kam6512/BLE-Gatt_Manager | 7e03d43e9e3307e5e67adfb4515011d0f32a8d01 | [
"MIT"
] | null | null | null | Manager/src/main/java/com/rainbow/kam/ble_gatt_manager/exceptions/gatt/GattRssiException.java | kam6512/BLE-Gatt_Manager | 7e03d43e9e3307e5e67adfb4515011d0f32a8d01 | [
"MIT"
] | null | null | null | 21.136364 | 57 | 0.675269 | 11,029 | package com.rainbow.kam.ble_gatt_manager.exceptions.gatt;
import com.google.common.base.MoreObjects;
/**
* Created by Kang Young Won on 2016-05-12.
*/
public class GattRssiException extends GattException {
private final int state;
public GattRssiException(int state) {
this.state = state;
}
@Override public String toString() {
return MoreObjects.toStringHelper(this)
.add("state", state).toString();
}
}
|
3e19f69132be900baee9955a6a4ec5968c8f086e | 1,115 | java | Java | voa-server/voa-security/src/main/java/cn/yinjiahui/voa/security/component/RestAuthenticationEntryPoint.java | Light567/voa | c86504e5fd6c6365b0150de2af17290fe05cb499 | [
"Apache-2.0"
] | 2 | 2021-05-27T16:49:00.000Z | 2021-07-27T16:35:04.000Z | voa-server/voa-security/src/main/java/cn/yinjiahui/voa/security/component/RestAuthenticationEntryPoint.java | Light567/voa | c86504e5fd6c6365b0150de2af17290fe05cb499 | [
"Apache-2.0"
] | null | null | null | voa-server/voa-security/src/main/java/cn/yinjiahui/voa/security/component/RestAuthenticationEntryPoint.java | Light567/voa | c86504e5fd6c6365b0150de2af17290fe05cb499 | [
"Apache-2.0"
] | 1 | 2021-05-27T16:48:59.000Z | 2021-05-27T16:48:59.000Z | 38.448276 | 160 | 0.781166 | 11,030 | package cn.yinjiahui.voa.security.component;
import cn.hutool.json.JSONUtil;
import cn.yinjiahui.voa.common.api.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 自定义返回结果:未登录或登录过期
* Created by macro on 2018/5/14.
*/
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control","no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
response.getWriter().flush();
}
}
|
3e19f6adc4cd9bcef492e0c637504a9cd6de471d | 567 | java | Java | gulimall-product/src/main/java/com/atguigu/gulimall/product/entity/SpuInfoDescEntity.java | Arthurzy/gulimall | e4e89863c818185adabecc68350ee67fe02c9940 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/atguigu/gulimall/product/entity/SpuInfoDescEntity.java | Arthurzy/gulimall | e4e89863c818185adabecc68350ee67fe02c9940 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/atguigu/gulimall/product/entity/SpuInfoDescEntity.java | Arthurzy/gulimall | e4e89863c818185adabecc68350ee67fe02c9940 | [
"Apache-2.0"
] | null | null | null | 17.151515 | 56 | 0.733216 | 11,031 | package com.atguigu.gulimall.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* spu信息介绍
*
* @author Arthur
* @email lyhxr@example.com
* @date 2021-12-28 16:10:10
*/
@Data
@TableName("pms_spu_info_desc")
public class SpuInfoDescEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 商品id
*/
@TableId
private Long spuId;
/**
* 商品介绍
*/
private String decript;
}
|
3e19f78a1c138b29bf4cf7b920b544e7387f97bb | 1,126 | java | Java | zdemo-core-java/src/main/java/java8/datatime/Demo04_Instant.java | kinglyjn/zdemo-parent | 3b07f91e1a9a8131f0bd8d0488385e5c2a2220a5 | [
"MIT"
] | 2 | 2020-04-03T02:20:32.000Z | 2020-04-03T02:20:42.000Z | zdemo-core-java/src/main/java/java8/datatime/Demo04_Instant.java | kinglyjn/zdemo-parent | 3b07f91e1a9a8131f0bd8d0488385e5c2a2220a5 | [
"MIT"
] | 1 | 2020-03-29T12:38:16.000Z | 2020-03-29T12:38:16.000Z | zdemo-core-java/src/main/java/java8/datatime/Demo04_Instant.java | kinglyjn/zdemo-parent | 3b07f91e1a9a8131f0bd8d0488385e5c2a2220a5 | [
"MIT"
] | null | null | null | 30.432432 | 108 | 0.654529 | 11,032 | package java8.datatime;
import org.junit.Test;
import java.time.*;
/**
* 时间戳相关:时间戳以Unix元年即1970-01-01 00:00:00到某个时间点间的毫秒值
* Instant
*/
public class Demo04_Instant {
@Test
public void test01() {
Instant instant1 = Instant.now();
System.out.println(instant1); //2018-08-09T12:15:48.310Z 默认获取当前UTC时区时间(时间协调时间)
OffsetDateTime odt = instant1.atOffset(ZoneOffset.ofHours(8)); //2018-08-09T20:15:48.310+08:00 东八区时间
System.out.println(odt);
System.out.println(instant1.toEpochMilli()); //1533817133187
System.out.println(Instant.ofEpochSecond(60)); //1970-01-01T00:01:00Z
Instant instant2 = Instant.now();
System.out.println("时间间隔1:" + Duration.between(instant1, instant2).toMillis() + "ms.");
LocalDateTime ldt1 = LocalDateTime.now();
LocalDateTime ldt2 = LocalDateTime.now();
System.out.println("时间间隔2:" + Duration.between(ldt1, ldt2).toMillis());
LocalDate ld1 = LocalDate.of(2017, 7, 8);
LocalDate ld2 = LocalDate.now();
System.out.println("日期间隔1:" + Period.between(ld1, ld2)); //P1Y1M1D
}
}
|
3e19f8b46518e2c94d596e807f28558203261269 | 117 | java | Java | canal-client/src/main/java/com/tqmall/search/canal/handle/package-info.java | wxingyl/search-commons | 6876fa38f207a4ea2f8b312c6355b272acddc0fb | [
"Apache-2.0"
] | 25 | 2016-02-24T02:56:01.000Z | 2021-01-17T16:35:59.000Z | canal-client/src/main/java/com/tqmall/search/canal/handle/package-info.java | wxingyl/search-commons | 6876fa38f207a4ea2f8b312c6355b272acddc0fb | [
"Apache-2.0"
] | null | null | null | canal-client/src/main/java/com/tqmall/search/canal/handle/package-info.java | wxingyl/search-commons | 6876fa38f207a4ea2f8b312c6355b272acddc0fb | [
"Apache-2.0"
] | 8 | 2016-03-01T13:05:53.000Z | 2019-08-15T18:15:11.000Z | 16.714286 | 39 | 0.666667 | 11,033 | /**
* Created by xing on 16/3/8.
* canal 实例处理行为封装
*
* @author wxingyl
*/
package com.tqmall.search.canal.handle; |
3e19f8dd59f8b08ca6f1da132e02ce838bff445c | 9,515 | java | Java | constraintlayout/swing/src/main/java/org/constraintlayout/swing/core/MotionSceneParser.java | xtuzy/constraintlayout | 0821c4ee57d2535d3404086ec76f55b57b69fb5a | [
"Apache-2.0"
] | 927 | 2020-07-24T07:24:54.000Z | 2022-03-31T10:01:37.000Z | constraintlayout/swing/src/main/java/org/constraintlayout/swing/core/MotionSceneParser.java | vanniktech/constraintlayout | d90bd5afb2fa3fbb1f8a5f110c5f62c22efbe85e | [
"Apache-2.0"
] | 183 | 2020-09-07T17:45:12.000Z | 2022-03-31T14:56:38.000Z | constraintlayout/swing/src/main/java/org/constraintlayout/swing/core/MotionSceneParser.java | vanniktech/constraintlayout | d90bd5afb2fa3fbb1f8a5f110c5f62c22efbe85e | [
"Apache-2.0"
] | 135 | 2020-08-28T02:33:08.000Z | 2022-03-26T01:19:59.000Z | 40.147679 | 119 | 0.543248 | 11,034 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.constraintlayout.swing.core;
import androidx.constraintlayout.core.parser.*;
import static org.constraintlayout.swing.core.motion.model.JsonKeys.HEADER;
/**
* The basic parser converts the json syntax into the ConstraintLayoutState object
*/
public class MotionSceneParser {
private String exportedName;
public void parse(String content, ConstraintLayoutState state) {
try {
state.clear();
CLObject json = CLParser.parse(content);
for (CLKey key : json) {
String name = key.getName();
if (name.equals(HEADER)) {
CLElement value = key.getValue();
if (value instanceof CLObject) {
parseHeader((CLObject) value, content);
}
} else {
CLElement value = key.getValue();
if (value instanceof CLObject) {
CLObject object = (CLObject) value;
if (object.has("type")) {
String type = object.getString("type");
switch (type) {
case "hGuideline":
case "vGuideline": {
parseGuideline(state.guidelines, type, name, object);
}
break;
}
} else {
parseConstraints(state.constraints, name, (CLObject) value);
}
}
}
}
} catch (CLParsingException e) {
e.printStackTrace();
}
}
private void parseGuideline(GuidelinesState state, String type, String widgetId, CLObject json) {
for (CLKey key : json) {
String name = key.getName();
switch (name) {
case "type":
break;
case "start": {
int value = key.getValue().getInt();
state.addGuideline(widgetId, GuidelinesState.GUIDELINE_START, value);
}
break;
case "end": {
int value = key.getValue().getInt();
state.addGuideline(widgetId, GuidelinesState.GUIDELINE_END, value);
}
break;
case "top": {
int value = key.getValue().getInt();
state.addGuideline(widgetId, GuidelinesState.GUIDELINE_TOP, value);
}
break;
case "bottom": {
int value = key.getValue().getInt();
state.addGuideline(widgetId, GuidelinesState.GUIDELINE_BOTTOM, value);
}
break;
case "percent": {
float value = key.getValue().getFloat();
int guidelineType;
if (type.equals("vGuideline")) {
guidelineType = GuidelinesState.GUIDELINE_HORIZONTAL_PERCENT;
} else {
guidelineType = GuidelinesState.GUIDELINE_VERTICAL_PERCENT;
}
state.addGuideline(widgetId, guidelineType, value);
}
break;
}
}
}
static class CSetAttributes {
public static final String WIDTH = "width";
public static final String HEIGHT = "height";
public static final String CENTER = "center";
public static final String CENTER_HORIZONTALLY = "centerHorizontally";
public static final String CENTER_VERTICALLY = "centerVertically";
public static final String ALPHA = "alpha";
public static final String SCALE_X = "scaleX";
public static final String SCALE_Y = "scaleY";
public static final String TRANSLATION_X = "translationX";
public static final String TRANSLATION_Y = "translationY";
public static final String TRANSLATION_Z = "translationZ";
public static final String PIVOT_X = "pivotX";
public static final String PIVOT_Y = "pivotY";
public static final String ROTATION_X = "rotationX";
public static final String ROTATION_Y = "rotationY";
public static final String ROTATION_Z = "rotationZ";
public static final String VISIBILITY = "visibility";
public static final String CUSTOM = "custom";
public static final String CIRCULAR = "circular";
public static final String START = "start";
public static final String END = "end";
public static final String TOP = "top";
public static final String BOTTOM = "bottom";
}
private void parseConstraints(ConstraintsState state, String widgetId, CLObject json) {
for (CLKey key : json) {
String name = key.getName();
switch (name) {
case CSetAttributes.START:
case CSetAttributes.END:
case CSetAttributes.TOP:
case CSetAttributes.BOTTOM: {
CLArray constraint = (CLArray) key.getValue();
parseConstraint(state, widgetId, name, constraint);
}
break;
case CSetAttributes.CENTER: {
String target = json.getStringOrNull(name);
if (target != null) {
parseCenter(state, widgetId, target);
}
}
break;
case CSetAttributes.CENTER_HORIZONTALLY: {
parseCenterHorizontally(state, widgetId, key.getValue());
}
break;
case CSetAttributes.CENTER_VERTICALLY: {
parseCenterVertically(state, widgetId, key.getValue());
}
break;
case CSetAttributes.WIDTH:
case CSetAttributes.HEIGHT: {
parseDimension(state, widgetId, name, key.getValue());
}
break;
}
}
}
private void parseCenter(ConstraintsState state, String widgetId, String targetId) {
state.addCenterConstraint(widgetId, targetId);
}
private void parseCenterHorizontally(ConstraintsState state, String widgetId, CLElement constraint) {
if (constraint instanceof CLString) {
state.addCenterHorizontallyConstraint(widgetId, constraint.content(), 0.5f);
}
}
private void parseCenterVertically(ConstraintsState state, String widgetId, CLElement constraint) {
if (constraint instanceof CLString) {
state.addCenterVerticallyConstraint(widgetId, constraint.content(), 0.5f);
}
}
private void parseDimension(ConstraintsState state, String widgetId, String constraintName, CLElement constraint) {
switch (constraintName) {
case CSetAttributes.WIDTH:
if (constraint instanceof CLString){
state.addWidthDimension(widgetId, constraint.content(),0);
} else {
if (constraint instanceof CLNumber){
state.addWidthDimension(widgetId, "value", ((CLNumber)constraint).getInt());
}
}
break;
case CSetAttributes.HEIGHT:
if (constraint instanceof CLString){
state.addHeightDimension(widgetId, constraint.content(),0);
} else {
if (constraint instanceof CLNumber){
state.addHeightDimension(widgetId, "value", ((CLNumber)constraint).getInt());
}
}
break;
}
}
private void parseConstraint(ConstraintsState state, String widgetId, String constraintName, CLArray constraint) {
if (constraint.size() < 2) {
return;
}
try {
String targetId = constraint.getString(0);
String targetAnchor = constraint.getString(1);
int margin = 0;
int marginGone = 0;
if (constraint.size() > 2) {
margin = constraint.getInt(2);
}
if (constraint.size() > 3) {
marginGone = constraint.getInt(3);
}
state.addConstraint(widgetId, constraintName, targetId, targetAnchor, margin, marginGone);
} catch (CLParsingException e) {
e.printStackTrace();
}
}
private void parseHeader(CLObject header, String content) {
exportedName = header.getStringOrNull("exportAs");
}
public String getExportedName() {
return exportedName;
}
}
|
3e19f98fd98c5631ac2c5bba8cba6be568382818 | 606 | java | Java | src/main/java/jp/sasyou/game/othello/rule/HandGenerator.java | gatchaman-20140215/othello | bc42db06b752f80a63ebcedf16fccc59ae5105ff | [
"MIT"
] | null | null | null | src/main/java/jp/sasyou/game/othello/rule/HandGenerator.java | gatchaman-20140215/othello | bc42db06b752f80a63ebcedf16fccc59ae5105ff | [
"MIT"
] | null | null | null | src/main/java/jp/sasyou/game/othello/rule/HandGenerator.java | gatchaman-20140215/othello | bc42db06b752f80a63ebcedf16fccc59ae5105ff | [
"MIT"
] | null | null | null | 15.15 | 56 | 0.59571 | 11,035 | package jp.sasyou.game.othello.rule;
/**
* 手を生成するクラス
*
* @author sasyou
*
*/
public final class HandGenerator {
/**
* コンストラクタの使用禁止
*/
private HandGenerator() {
}
/**
* 合法手のリストを取得する。
*
* @param board 盤
* @param teban 手番
* @return 合法手のリスト
*/
public static long generate(Board board, int teban) {
return board.generateLegals(teban);
}
/**
* 合法手の数を数える。
*
* @param board 盤面
* @param teban 手番
* @return 合法手の数
*/
public static int countHands(Board board, int teban) {
return Long.bitCount(board.generateLegals(teban));
}
}
|
3e19f9ef364ad66abd61a2411cf63b0cd0d634bb | 943 | java | Java | src/main/java/br/com/zupacademy/rodrigo/casadocodigo/domain/dto/AutorRequestDTO.java | rochards/orange-talents-03-template-casa-do-codigo | f43dd77f3757c47f1923c8ee45a9ef1b2608ab64 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/rodrigo/casadocodigo/domain/dto/AutorRequestDTO.java | rochards/orange-talents-03-template-casa-do-codigo | f43dd77f3757c47f1923c8ee45a9ef1b2608ab64 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/rodrigo/casadocodigo/domain/dto/AutorRequestDTO.java | rochards/orange-talents-03-template-casa-do-codigo | f43dd77f3757c47f1923c8ee45a9ef1b2608ab64 | [
"Apache-2.0"
] | null | null | null | 29.46875 | 127 | 0.726405 | 11,036 | package br.com.zupacademy.rodrigo.casadocodigo.domain.dto;
import br.com.zupacademy.rodrigo.casadocodigo.domain.model.Autor;
import br.com.zupacademy.rodrigo.casadocodigo.exception.validation.NotDuplicate;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class AutorRequestDTO {
@NotBlank
private String nome;
@NotBlank @Email
@NotDuplicate(message = "esse email já está cadastrado", fieldName = "email", domainClass = Autor.class)
private String email;
@NotBlank @Size(max = 400)
private String descricao;
public AutorRequestDTO(@NotBlank String nome, @NotBlank @Email String email, @NotBlank @Size(max = 400) String descricao) {
this.nome = nome;
this.email = email;
this.descricao = descricao;
}
public Autor toModel() {
return new Autor(nome, email, descricao);
}
}
|
3e19fa172fee931c212c5f2195d5eabb1e26cda2 | 606 | java | Java | sjava/src/MergeTwoListRunner.java | juhee07/Projects | c2757c9b6216140d78dc010b9170d5c25b64ffa2 | [
"Apache-2.0"
] | null | null | null | sjava/src/MergeTwoListRunner.java | juhee07/Projects | c2757c9b6216140d78dc010b9170d5c25b64ffa2 | [
"Apache-2.0"
] | null | null | null | sjava/src/MergeTwoListRunner.java | juhee07/Projects | c2757c9b6216140d78dc010b9170d5c25b64ffa2 | [
"Apache-2.0"
] | null | null | null | 30.3 | 58 | 0.508251 | 11,037 | public class MergeTwoListRunner {
public void run() {
// l1: 2 -> 4 -> 7
// l2: 2 -> 8 -> 9
// result: 2 -> 2 - > 4 -> 8 -> 7 -> 9
ListNode l5 = new ListNode(2);
l5.next = new ListNode(4);
l5.next.next = new ListNode(7);
ListNode l6 = new ListNode(2);
l6.next = new ListNode(8);
l6.next.next = new ListNode(9);
MergeTwoLists mergeTwoLists = new MergeTwoLists();
ListNode result3 = mergeTwoLists.merge(l5, l6);
Print.printLinkList(result3);
System.out.println("------------------------");
}
}
|
3e19fa1f9f3daa16364ab2c7997f74aeb846671f | 1,560 | java | Java | copper-server-impl/src/main/java/com/pogeyan/cmis/impl/TypePermission/DefaultTypePermissionService.java | hubertp/copper-cms | bf228b6a17a9d4b1e5e3f2c161349c0a22881739 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2017-10-23T01:19:39.000Z | 2019-12-04T10:44:18.000Z | copper-server-impl/src/main/java/com/pogeyan/cmis/impl/TypePermission/DefaultTypePermissionService.java | hubertp/copper-cms | bf228b6a17a9d4b1e5e3f2c161349c0a22881739 | [
"ECL-2.0",
"Apache-2.0"
] | 25 | 2017-10-23T15:55:33.000Z | 2020-12-21T08:54:53.000Z | copper-server-impl/src/main/java/com/pogeyan/cmis/impl/TypePermission/DefaultTypePermissionService.java | CMYanko/copper-cms | c11e9e87cdd37c1d1381c04dd84120c625e22cac | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2019-06-22T04:06:39.000Z | 2021-03-04T13:45:12.000Z | 26 | 98 | 0.75 | 11,038 | package com.pogeyan.cmis.impl.TypePermission;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pogeyan.cmis.api.auth.IUserObject;
import com.pogeyan.cmis.api.data.ITypePermissionService;
import com.pogeyan.cmis.api.data.common.PermissionType;
public class DefaultTypePermissionService implements ITypePermissionService {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(DefaultTypePermissionService.class);
@Override
public Boolean checkTypeAccess(String repositoryId, IUserObject role, String typeId) {
if (typeId != null) {
return true;
}
return false;
}
@Override
public List<String> getFieldAccess(String repositoryId, IUserObject role, String typeId) {
if (typeId != null) {
List<String> fieldAccess = new ArrayList<String>();
return fieldAccess;
}
return null;
}
@Override
public Boolean checkPermissionAccess(String repositoryId, IUserObject role, String typeId,
PermissionType permissionAccess) {
if (typeId != null) {
return true;
}
return false;
}
@Override
public List<String> getAclPropagationList(String repositoryId, IUserObject role, String typeId) {
if (typeId != null) {
List<String> aclList = new ArrayList<String>();
return aclList;
}
return null;
}
@Override
public List<String> getRoles(String repositoryId, IUserObject role, String typeId) {
if (typeId != null) {
List<String> roleList = new ArrayList<String>();
return roleList;
}
return null;
}
} |
3e19fcb86b3fc8629fdb95e9933cb9dbb1c9d9b2 | 13,165 | java | Java | src/pasa/cbentley/framework/drawx/src4/factories/MaskOperator.java | cpbentley/pasa_cbentley_framework_drawx_src4 | a2d8aa4bbf469fbae924e52cf6ea64419ca103c6 | [
"MIT"
] | null | null | null | src/pasa/cbentley/framework/drawx/src4/factories/MaskOperator.java | cpbentley/pasa_cbentley_framework_drawx_src4 | a2d8aa4bbf469fbae924e52cf6ea64419ca103c6 | [
"MIT"
] | null | null | null | src/pasa/cbentley/framework/drawx/src4/factories/MaskOperator.java | cpbentley/pasa_cbentley_framework_drawx_src4 | a2d8aa4bbf469fbae924e52cf6ea64419ca103c6 | [
"MIT"
] | null | null | null | 43.305921 | 174 | 0.667907 | 11,039 | /*
* (c) 2018-2020 Charles-Philip Bentley
* This code is licensed under MIT license (see LICENSE.txt for details)
*/
package pasa.cbentley.framework.drawx.src4.factories;
import pasa.cbentley.byteobjects.src4.core.ByteObject;
import pasa.cbentley.byteobjects.src4.ctx.IBOTypesBOC;
import pasa.cbentley.core.src4.utils.ColorUtils;
import pasa.cbentley.framework.coredraw.src4.interfaces.IImage;
import pasa.cbentley.framework.coredraw.src4.interfaces.IMFont;
import pasa.cbentley.framework.drawx.src4.ctx.DrwCtx;
import pasa.cbentley.framework.drawx.src4.ctx.IBOTypesDrw;
import pasa.cbentley.framework.drawx.src4.engine.BlendOp;
import pasa.cbentley.framework.drawx.src4.engine.GraphicsX;
import pasa.cbentley.framework.drawx.src4.engine.RgbImage;
import pasa.cbentley.framework.drawx.src4.tech.ITechFigure;
import pasa.cbentley.framework.drawx.src4.tech.ITechMask;
public class MaskOperator extends AbstractDrwOperator {
public MaskOperator(DrwCtx drc) {
super(drc);
}
/**
*
* @param g
* @param x
* @param y
* @param mask
* @param fig
* @param w Ignored when figure has size anchor
* @param h Ignored when figure has size anchor
*/
public void drawMask(GraphicsX g, int x, int y, ByteObject mask, ByteObject fig, int w, int h) {
RgbImage figImg = createMaskedFigure(g, mask, w, h, fig);
g.drawRgbImage(figImg, x, y);
figImg.dispose();
}
public void drawMask(GraphicsX g, int x, int y, ByteObject mask, char c, IMFont f) {
RgbImage figImg = drc.getRgbImageFactory().getCharImage(ColorUtils.FULLY_OPAQUE_BLACK, c, f, ColorUtils.FULLY_OPAQUE_WHITE);
RgbImage maskedImg = createMaskedFigure(g, mask, figImg);
g.drawRgbImage(maskedImg, x, y);
figImg.dispose();
}
public void drawMask(GraphicsX g, int x, int y, ByteObject mask, char c, IMFont f, int anchor) {
RgbImage figImg = drc.getRgbImageFactory().getCharImage(ColorUtils.FULLY_OPAQUE_BLACK, c, f, ColorUtils.FULLY_OPAQUE_WHITE);
RgbImage maskedImg = createMaskedFigure(g, mask, figImg);
g.drawRgbImage(maskedImg, x, y, anchor);
figImg.dispose();
}
/**
* Merges two mask definitions.
* <br>
* <br>
* @param root
* @param merge
* @return
*/
public ByteObject mergeMask(ByteObject root, ByteObject merge) {
int maskBgColor = root.get4(ITechMask.MASK_OFFSET_2COLOR_BG4);
int maskMidColor = root.get4(ITechMask.MASK_OFFSET_3COLOR_MID4);
int maskShapeColor = root.get4(ITechMask.MASK_OFFSET_4COLOR_SHAPE4);
int blendBg = root.get1(ITechMask.MASK_OFFSET_5BLEND_BG1);
int blendMid = root.get1(ITechMask.MASK_OFFSET_6BLEND_MID1);
int blendShape = root.get1(ITechMask.MASK_OFFSET_7BLEND_SHAPE1);
int bgAlpha = root.get1(ITechMask.MASK_OFFSET_8ALPHA_BG1);
int shapeAlpha = root.get1(ITechMask.MASK_OFFSET_9ALPHA_SHAPE1);
ByteObject mm = merge.getSubFirst(IBOTypesBOC.TYPE_011_MERGE_MASK);
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_2)) {
maskBgColor = merge.get4(ITechMask.MASK_OFFSET_2COLOR_BG4);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_3)) {
maskMidColor = merge.get4(ITechMask.MASK_OFFSET_3COLOR_MID4);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_4)) {
maskShapeColor = merge.get4(ITechMask.MASK_OFFSET_4COLOR_SHAPE4);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_5)) {
blendBg = merge.get4(ITechMask.MASK_OFFSET_5BLEND_BG1);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_6)) {
blendMid = merge.get4(ITechMask.MASK_OFFSET_6BLEND_MID1);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_7)) {
blendShape = merge.get4(ITechMask.MASK_OFFSET_7BLEND_SHAPE1);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_8)) {
bgAlpha = merge.get4(ITechMask.MASK_OFFSET_8ALPHA_BG1);
}
if (mm.hasFlag(MERGE_MASK_OFFSET_5VALUES1, MERGE_MASK_FLAG5_1)) {
shapeAlpha = merge.get4(ITechMask.MASK_OFFSET_9ALPHA_SHAPE1);
}
ByteObject maskFilter = root.getSubFirst(IBOTypesDrw.TYPE_056_COLOR_FILTER);
if (merge.hasFlag(ITechMask.MASK_OFFSET_1FLAG1, ITechMask.MASK_FLAG_1MASK_FILTER)) {
maskFilter = merge.getSubFirst(IBOTypesDrw.TYPE_056_COLOR_FILTER);
}
ByteObject bgFigure = root.getSubFirst(IBOTypesDrw.TYPE_050_FIGURE);
if (merge.hasFlag(ITechMask.MASK_OFFSET_1FLAG1, ITechMask.MASK_FLAG_2BG_FIGURE)) {
bgFigure = merge.getSubFirst(IBOTypesDrw.TYPE_050_FIGURE);
}
ByteObject newMask = drc.getMaskFactory().getMask(maskBgColor, maskMidColor, maskShapeColor, bgAlpha, shapeAlpha, blendBg, blendMid, blendShape, maskFilter, bgFigure);
return newMask;
}
/**
* Create a mask
* Example\
* Input image is white pixel with the word "Hello" written in black
* Draws that image at coordinate x,y with all pixel of maskColor changed to finalMaskColor
* Other pixels are changed to fully transparent.
* @param img
* @return
*/
public IImage getImageMask(IImage srcImg, int maskColor, int finalMaskColor) {
int[] rgb = drc.getRgbCache().getImageData(srcImg);
for (int i = 0; i < rgb.length; i++) {
if (rgb[i] == maskColor) {
rgb[i] = finalMaskColor;
} else {
//sets it to fully transparent
rgb[i] = rgb[i] & 0x00FFFFFF;
}
}
return drc.getImageFactory().createRGBImage(rgb, srcImg.getWidth(), srcImg.getHeight(), true);
}
/**
*
* @param g
* @param x
* @param y
* @param mask
* @param str
* @param f
*/
public void drawMask(GraphicsX g, int x, int y, ByteObject mask, String str, IMFont f) {
ByteObject fig = drc.getFigureFactory().getFigString(str, f);
int wi = f.stringWidth(str);
int hi = f.getHeight();
RgbImage figImg = createMaskedFigure(g, mask, wi, hi, fig);
g.drawRgbImage(figImg, x, y);
figImg.dispose();
}
/**
* Create a black mask. Overrides figure color to black and remove gradients.
* <br>
* Clone of a String fig keeps the Anchor and Scaler elements.
* <br>
* This method should not create any blending operation.
* <br>
* <br>
* What happens when you clone a String figure with litteral as sub object?
* @param mask
* @param wi
* @param hi
* @param fig
* @return {@link RgbImage} flushed.
*/
public RgbImage createShapeMask(GraphicsX g, ByteObject mask, int wi, int hi, ByteObject fig) {
ByteObject cf = fig.cloneCopyHeadRefParams();
cf.setValue(ITechFigure.FIG__OFFSET_06_COLOR4, ColorUtils.FULLY_OPAQUE_BLACK, 4);
cf.setFlag(ITechFigure.FIG__OFFSET_02_FLAG, ITechFigure.FIG_FLAG_2_GRADIENT, false);
cf.setFlag(ITechFigure.FIG__OFFSET_02_FLAG, ITechFigure.FIG_FLAG_6_ANIMATED, false);
cf.setFlag(ITechFigure.FIG__OFFSET_02_FLAG, ITechFigure.FIG_FLAG_4_MASK, false);
cf.setFlag(ITechFigure.FIG__OFFSET_02_FLAG, ITechFigure.FIG_FLAG_5_FILTER, false);
//draw the mask canvas and apply color filter. bg color is opaque white
RgbImage maskImg = drc.getFigureOperator().getFigImagePrimitve(g, cf, wi, hi, true, -1);
if (mask.hasFlag(ITechMask.MASK_OFFSET_1FLAG1, ITechMask.MASK_FLAG_1MASK_FILTER)) {
ByteObject maskColorFilter = mask.getSubFirst(IBOTypesDrw.TYPE_056_COLOR_FILTER);
drc.getFilterOperator().applyColorFilter(maskColorFilter, maskImg);
//image will be switch to RGB mode.
}
return maskImg;
}
/**
* Get an image mask for the shape drawn by the figure.
* <br>
*
* <li>get shape in black and white
* <li>draw background figure
* <li>blend pixels from bg figure with mask colors.
* <br>
* <br>
*
* Draw the figure in white on a black background or in black on a white background
* <br>
* For this purpose the {@link ByteObject} figure is cloned and color set to white/black.
* <br>
* @param mask mask definition with background image and filter to apply on figure
* @param wi
* @param hi
* @param fig Figure that will paint its shape in a given color.
* @return
*/
public RgbImage createMaskedFigure(GraphicsX g, ByteObject mask, int wi, int hi, ByteObject fig) {
//SystemLog.printDraw(RgbCache.getCache().toString());
//draw the mask canvas and apply color filter
RgbImage maskImg = createShapeMask(g, mask, wi, hi, fig);
return createMaskedFigure(g, mask, maskImg);
}
public RgbImage createMaskedFigure(GraphicsX g, ByteObject mask, RgbImage maskImg) {
//SystemLog.printDraw(RgbImage.debugAlphas(maskImg.getRgbData(), maskImg.getWidth(), maskImg.getHeight()));
//the alpha value for the bgpixel not hidden by mask color
int shapeAlphaValue = mask.getValue(ITechMask.MASK_OFFSET_9ALPHA_SHAPE1, 1);
int bgAlphaValue = mask.getValue(ITechMask.MASK_OFFSET_8ALPHA_BG1, 1);
int bgColor = mask.get4(ITechMask.MASK_OFFSET_2COLOR_BG4);
int shapeColor = mask.get4(ITechMask.MASK_OFFSET_4COLOR_SHAPE4);
int midColor = mask.get4(ITechMask.MASK_OFFSET_4COLOR_SHAPE4);
int bgBlend = mask.get1(ITechMask.MASK_OFFSET_5BLEND_BG1);
int midBlend = mask.get1(ITechMask.MASK_OFFSET_6BLEND_MID1);
int shapeBlend = mask.get1(ITechMask.MASK_OFFSET_7BLEND_SHAPE1);
ByteObject bgFigure = mask.getSubFirst(IBOTypesDrw.TYPE_050_FIGURE);
int dw = maskImg.getWidth();
int dh = maskImg.getHeight();
if (mask.hasFlag(ITechMask.MASK_OFFSET_1FLAG1, ITechMask.MASK_FLAG_6SIZE_MASK)) {
dw = maskImg.getWidth();
dh = maskImg.getHeight();
}
//backgroud image with GraphicsX in RGB_IMAGE mode
RgbImage figBackgroundImg = drc.getFigureOperator().getFigImage(g, bgFigure, dw, dh, false, false, 0);
//SystemLog.printDraw(figImg);
//SystemLog.printDraw(maskImg);
//we know by construction that m and n = 0 for both images
int[] figData = figBackgroundImg.getRgbData();
int[] maskData = maskImg.getRgbData();
//SystemLog.printDraw(RgbImage.debugAlphas(maskImg.getRgbData(), maskImg.getWidth(), maskImg.getHeight()));
//SystemLog.printDraw(RgbCache.getCache().toString());
//mask blending: 3 cases Shape,Bg or Halo.
//each pixel can be blended
BlendOp shapeBlendOP = new BlendOp(drc, shapeBlend);
BlendOp bgBlendOP = new BlendOp(drc, bgBlend);
BlendOp midBlendOP = new BlendOp(drc, midBlend);
for (int i = 0; i < figData.length; i++) {
if (maskData[i] == ColorUtils.FULLY_OPAQUE_BLACK) {
//we are in the shape area. how to blend bgPixel or shape pixel? either draw pixel or blend with shapecolor
blendMaskPixel(figData, i, shapeBlendOP, shapeColor, shapeAlphaValue);
} else if (maskData[i] == ColorUtils.FULLY_OPAQUE_WHITE) {
//we are in the background area
blendMaskPixel(figData, i, bgBlendOP, bgColor, bgAlphaValue);
} else {
//middle values between black and white with various alpha values
//take the alpha value and apply it
int maskAlpha = (maskData[i] >> 24) & 0xFF;
//SystemLog.printDraw("maskAlpha = " + maskAlpha);
blendMaskPixel(figData, i, midBlendOP, midColor, maskAlpha);
}
}
maskImg.dispose();
return figBackgroundImg;
}
/**
* Blends the figData ith pixel with the given color which is given an alphaValue.
* <br>
* <br>
*
* @param figData
* @param i
* @param blendOp
* @param shapeColor
* @param alphaValue
*/
void blendMaskPixel(int[] figData, int i, BlendOp blendOp, int shapeColor, int alphaValue) {
//figData[i] = BlendOp.blendPixel(figData[i], (color & 0xFFFFFF) + (alphaValue << 24), blendOp);
if (blendOp.getMode() == ITechMask.MASK_BLEND_0) {
figData[i] = (figData[i] & 0xFFFFFF) + (alphaValue << 24);
} else if (blendOp.getMode() == ITechMask.MASK_BLEND_1) {
figData[i] = (shapeColor & 0xFFFFFF) + (alphaValue << 24);
} else {
figData[i] = blendOp.blendPixel(figData[i], (shapeColor & 0xFFFFFF) + (alphaValue << 24));
}
}
/**
* If figure does not have a mask, add the mask
* @param figure may be null
* @param mask may be null
*/
public void addMask(ByteObject figure, ByteObject mask) {
if (figure == null || mask == null)
return;
if (!figure.hasFlag(ITechFigure.FIG__OFFSET_02_FLAG, ITechFigure.FIG_FLAG_4_MASK)) {
figure.addSub(mask);
figure.setFlag(ITechFigure.FIG__OFFSET_02_FLAG, ITechFigure.FIG_FLAG_4_MASK, true);
}
}
}
|
3e19fef6de8f69c9bb62129ea8b717f4c4cdfc78 | 4,955 | java | Java | src/main/java/com/sayee/sxsy/newModules/training/entity/Train.java | fanyayang777/sxsyTwoPhase | c5187f26427d5fd112ba76631c379a8befe7084e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sayee/sxsy/newModules/training/entity/Train.java | fanyayang777/sxsyTwoPhase | c5187f26427d5fd112ba76631c379a8befe7084e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sayee/sxsy/newModules/training/entity/Train.java | fanyayang777/sxsyTwoPhase | c5187f26427d5fd112ba76631c379a8befe7084e | [
"Apache-2.0"
] | 1 | 2020-03-02T05:55:35.000Z | 2020-03-02T05:55:35.000Z | 21.924779 | 87 | 0.629869 | 11,040 | package com.sayee.sxsy.newModules.training.entity;
import java.math.BigDecimal;
import java.util.Date;
public class Train {
private String trainId;
private String title;
private String vidioType;
private String department;
private String path;
private String send;
private String introduce;
private String score;
private String createBy;
private Date createDate;
private String updateBy;
private Date updateDate;
private String delFlag;
private String picturePath;
private String payment;
private String courseChapter;
private String buyNumber;
private BigDecimal videoPrice;
private String intendedFor;
private String preknowledge;
private String lecturerName;
private String lecturerCompany;
public String getTrainId() {
return trainId;
}
public void setTrainId(String trainId) {
this.trainId = trainId == null ? null : trainId.trim();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public String getVidioType() {
return vidioType;
}
public void setVidioType(String vidioType) {
this.vidioType = vidioType == null ? null : vidioType.trim();
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department == null ? null : department.trim();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send == null ? null : send.trim();
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce == null ? null : introduce.trim();
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score == null ? null : score.trim();
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy == null ? null : createBy.trim();
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy == null ? null : updateBy.trim();
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag == null ? null : delFlag.trim();
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath == null ? null : picturePath.trim();
}
public String getPayment() {
return payment;
}
public void setPayment(String payment) {
this.payment = payment == null ? null : payment.trim();
}
public String getCourseChapter() {
return courseChapter;
}
public void setCourseChapter(String courseChapter) {
this.courseChapter = courseChapter == null ? null : courseChapter.trim();
}
public String getBuyNumber() {
return buyNumber;
}
public void setBuyNumber(String buyNumber) {
this.buyNumber = buyNumber == null ? null : buyNumber.trim();
}
public BigDecimal getVideoPrice() {
return videoPrice;
}
public void setVideoPrice(BigDecimal videoPrice) {
this.videoPrice = videoPrice;
}
public String getIntendedFor() {
return intendedFor;
}
public void setIntendedFor(String intendedFor) {
this.intendedFor = intendedFor == null ? null : intendedFor.trim();
}
public String getPreknowledge() {
return preknowledge;
}
public void setPreknowledge(String preknowledge) {
this.preknowledge = preknowledge == null ? null : preknowledge.trim();
}
public String getLecturerName() {
return lecturerName;
}
public void setLecturerName(String lecturerName) {
this.lecturerName = lecturerName == null ? null : lecturerName.trim();
}
public String getLecturerCompany() {
return lecturerCompany;
}
public void setLecturerCompany(String lecturerCompany) {
this.lecturerCompany = lecturerCompany == null ? null : lecturerCompany.trim();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.