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
3e08c722c38062067cde5bbeff6ab205e5b299f1
7,498
java
Java
ochre-api/src/main/java/gov/vha/isaac/ochre/api/util/DownloadUnzipTask.java
cngshow/isaac
27ed40ff1eeb73c83c25fb799b7b172ac928d609
[ "Apache-2.0" ]
null
null
null
ochre-api/src/main/java/gov/vha/isaac/ochre/api/util/DownloadUnzipTask.java
cngshow/isaac
27ed40ff1eeb73c83c25fb799b7b172ac928d609
[ "Apache-2.0" ]
null
null
null
ochre-api/src/main/java/gov/vha/isaac/ochre/api/util/DownloadUnzipTask.java
cngshow/isaac
27ed40ff1eeb73c83c25fb799b7b172ac928d609
[ "Apache-2.0" ]
null
null
null
29.570866
146
0.699641
3,718
/** * Copyright Notice * * This is a work of the U.S. Government and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * 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 gov.vha.isaac.ochre.api.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.util.Base64; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Task; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.progress.ProgressMonitor; /** * {@link DownloadUnzipTask} * * @author <a href="mailto:[email protected]">Dan Armbrust</a> */ public class DownloadUnzipTask extends Task<File> { private static Logger log = LoggerFactory.getLogger(DownloadUnzipTask.class); String username_, psswrd_; URL url_; private boolean cancel_ = false; private boolean unzip_; private boolean failOnBadCheksum_; private File targetFolder_; /** * @param username (optional) used if provided * @param psswrd (optional) used if provided * @param url The URL to download from * @param unzip - Treat the file as a zip file, and unzip it after the download * @param failOnBadChecksum - If a checksum file is found on the repository - fail if the downloaded file doesn't match the expected value. * (If no checksum file is found on the repository, this option is ignored and the download succeeds) * @param targetFolder (optional) download and/or extract into this folder. If not provided, a folder * will be created in the system temp folder for this purpose. * @throws IOException */ public DownloadUnzipTask(String username, String psswrd, URL url, boolean unzip, boolean failOnBadChecksum, File targetFolder) throws IOException { this.username_ = username; this.psswrd_ = psswrd; this.url_ = url; this.unzip_ = unzip; this.targetFolder_ = targetFolder; this.failOnBadCheksum_ = failOnBadChecksum; if (targetFolder_ == null) { targetFolder_ = File.createTempFile("ISAAC", ""); targetFolder_.delete(); } else { targetFolder_ = targetFolder_.getAbsoluteFile(); } targetFolder_.mkdirs(); } /** * @see javafx.concurrent.Task#call() */ @Override protected File call() throws Exception { File dataFile = download(url_); String calculatedSha1Value = null; String expectedSha1Value = null;; try { log.debug("Attempting to get .sha1 file"); File sha1File = download(new URL(url_.toString() + ".sha1")); expectedSha1Value = Files.readAllLines(sha1File.toPath()).get(0); Task<String> calculateTask = ChecksumGenerator.calculateChecksum("SHA1", dataFile); calculateTask.messageProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { updateMessage(newValue); } }); calculateTask.progressProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { updateProgress(calculateTask.getProgress(), calculateTask.getTotalWork()); } }); WorkExecutors.get().getExecutor().execute(calculateTask); calculatedSha1Value = calculateTask.get(); sha1File.delete(); } catch (Exception e1) { log.debug("Failed to get .sha1 file", e1); } if (calculatedSha1Value != null && !calculatedSha1Value.equals(expectedSha1Value)) { if (failOnBadCheksum_) { throw new RuntimeException("Checksum of downloaded file '" + url_.toString() + "' does not match the expected value!"); } else { log.warn("Checksum of downloaded file '" + url_.toString() + "' does not match the expected value!"); } } if (cancel_) { log.debug("Download cancelled"); throw new Exception("Cancelled!"); } if (unzip_) { updateTitle("Unzipping"); try { ZipFile zipFile = new ZipFile(dataFile); zipFile.setRunInThread(true); zipFile.extractAll(targetFolder_.getAbsolutePath()); while (zipFile.getProgressMonitor().getState() == ProgressMonitor.STATE_BUSY) { if (cancel_) { zipFile.getProgressMonitor().cancelAllTasks(); log.debug("Download cancelled"); throw new Exception("Cancelled!"); } updateProgress(zipFile.getProgressMonitor().getPercentDone(), 100); updateMessage("Unzipping " + dataFile.getName() + " at " + zipFile.getProgressMonitor().getPercentDone() + "%"); try { //TODO see if there is an API where I don't have to poll for completion Thread.sleep(25); } catch (InterruptedException e) { // noop } } log.debug("Unzip complete"); } catch (Exception e) { log.error("error unzipping", e); throw new Exception("The downloaded file doesn't appear to be a zip file"); } finally { dataFile.delete(); } return targetFolder_; } else { return dataFile; } } private File download(URL url) throws Exception { log.debug("Beginning download from " + url); updateMessage("Download from " + url); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); if (StringUtils.isNotBlank(username_) || StringUtils.isNotBlank(psswrd_)) { String encoded = Base64.getEncoder().encodeToString((username_ + ":" + psswrd_).getBytes()); httpCon.setRequestProperty("Authorization", "Basic " + encoded); } httpCon.setDoInput(true); httpCon.setRequestMethod("GET"); httpCon.setConnectTimeout(30 * 1000); httpCon.setReadTimeout(60 * 60 * 1000); long fileLength = httpCon.getContentLengthLong(); String temp = url.toString(); temp = temp.substring(temp.lastIndexOf('/') + 1, temp.length()); File file = new File(targetFolder_, temp); try (InputStream in = httpCon.getInputStream(); FileOutputStream fos= new FileOutputStream(file);) { byte[] buf = new byte[1048576]; int read = 0; long totalRead = 0; while (!cancel_ && (read = in.read(buf, 0, buf.length)) > 0) { totalRead += read; //update every 1 MB updateProgress(totalRead, fileLength); float percentDone = ((int)(((float)totalRead / (float)fileLength) * 1000)) / 10f; updateMessage("Downloading - " + url + " - " + percentDone + " % - out of " + fileLength + " bytes"); fos.write(buf, 0, read); } } if (cancel_) { log.debug("Download cancelled"); throw new Exception("Cancelled!"); } else { log.debug("Download complete"); } return file; } /** * @see javafx.concurrent.Task#cancel(boolean) */ @Override public boolean cancel(boolean mayInterruptIfRunning) { super.cancel(mayInterruptIfRunning); cancel_ = true; return true; } }
3e08c73b081276b81d2752baa53f578c8386967c
4,293
java
Java
cnd.apt.antlr4/src/test/java/org/netbeans/modules/cnd/nextapt/antlr4/ExprEvaluatorTest.java
vieiro/cnd.nextapt
d9db1172d1f664580e219a09b8ecf31260f53646
[ "Apache-2.0" ]
null
null
null
cnd.apt.antlr4/src/test/java/org/netbeans/modules/cnd/nextapt/antlr4/ExprEvaluatorTest.java
vieiro/cnd.nextapt
d9db1172d1f664580e219a09b8ecf31260f53646
[ "Apache-2.0" ]
null
null
null
cnd.apt.antlr4/src/test/java/org/netbeans/modules/cnd/nextapt/antlr4/ExprEvaluatorTest.java
vieiro/cnd.nextapt
d9db1172d1f664580e219a09b8ecf31260f53646
[ "Apache-2.0" ]
null
null
null
38.330357
164
0.689029
3,719
/* * 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.cnd.nextapt.antlr4; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.BitSet; import org.antlr.v4.runtime.ANTLRErrorListener; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.atn.ATNConfigSet; import org.antlr.v4.runtime.dfa.DFA; import org.junit.jupiter.api.Test; import org.netbeans.modules.cnd.apt.impl.support.antlr4.APTExprParserEvaluator; import org.netbeans.modules.cnd.apt.impl.support.generated.v2.APTExprParser; import org.netbeans.modules.cnd.apt.impl.support.generated.v2.APTLexer; /** * Verifies that the lexer does not produce any syntax error. */ public class ExprEvaluatorTest { public ExprEvaluatorTest() { } public static class SyntaxErrorDetector implements ANTLRErrorListener { @Override public void syntaxError(Recognizer<?, ?> rcgnzr, Object o, int i, int i1, String string, RecognitionException re) { throw new UnsupportedOperationException("Test failed"); } @Override public void reportAmbiguity(Parser parser, DFA dfa, int i, int i1, boolean bln, BitSet bitset, ATNConfigSet atncs) { throw new UnsupportedOperationException("Test failed"); } @Override public void reportAttemptingFullContext(Parser parser, DFA dfa, int i, int i1, BitSet bitset, ATNConfigSet atncs) { throw new UnsupportedOperationException("Test failed"); } @Override public void reportContextSensitivity(Parser parser, DFA dfa, int i, int i1, int i2, ATNConfigSet atncs) { throw new UnsupportedOperationException("Test failed"); } } @Test public void testShouldEvaluateAllExpressionsProperly() throws Exception { String[] testFiles = { "c/char.c", "c/define.c", "c/include.c", "c/strings.c",}; for (String testFile : testFiles) { System.out.format("TEST EXPRESSION EVALUATOR: %s%n", testFile); try (BufferedReader reader = new BufferedReader(new InputStreamReader(ExprEvaluatorTest.class.getResourceAsStream(testFile), StandardCharsets.UTF_8))) { APTLexer lexer = new APTLexer(CharStreams.fromReader(reader)); TokenStream lexerStream = new CommonTokenStream(lexer); APTExprParser parser = new APTExprParser(lexerStream); parser.addParseListener(new APTExprParserEvaluator()); // TODO ExprContext context = parser.expr(); } } } private static void dumpToken(APTLexer lexer, String previousLexerMode, Token token) { String tokenText = token.getText().replaceAll("\n", "\\n").replaceAll("\r", "\\r"); String currentLexerMode = lexer.getModeNames()[lexer._mode]; String tokenName = lexer.VOCABULARY.getSymbolicName(token.getType()); System.out.format("%4d:%4d:%-20s->%-20s:%-20s:%s%n", token.getLine(), token.getCharPositionInLine(), previousLexerMode, currentLexerMode, tokenName, tokenText ); } }
3e08c7b99dfbead4655cea2fed4283b1350f2a35
6,065
java
Java
jpaw8-benchmarks/src/main/java/de/jpaw8/benchmarks/lambda/LambdaListsTest.java
jpaw/jpaw
68bc06c379851d093f89fbf2c45f8b64e02b2108
[ "Apache-2.0" ]
null
null
null
jpaw8-benchmarks/src/main/java/de/jpaw8/benchmarks/lambda/LambdaListsTest.java
jpaw/jpaw
68bc06c379851d093f89fbf2c45f8b64e02b2108
[ "Apache-2.0" ]
null
null
null
jpaw8-benchmarks/src/main/java/de/jpaw8/benchmarks/lambda/LambdaListsTest.java
jpaw/jpaw
68bc06c379851d093f89fbf2c45f8b64e02b2108
[ "Apache-2.0" ]
1
2015-10-25T20:54:44.000Z
2015-10-25T20:54:44.000Z
39.640523
145
0.673372
3,720
package de.jpaw8.benchmarks.lambda; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; // Benchmarks to investigate how much performance the new lambda take //java -jar target/jpaw8-benchmarks.jar -i 3 -f 3 -wf 1 -wi 3 ".*LambdaListsTest.*" //# Run complete. Total time: 00:02:31 // //Benchmark Mode Samples Score Score error Units @State(value = Scope.Thread) @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public class LambdaListsTest { static class IndexedString { public final Integer ind; public final String text; public IndexedString(int i, String t) { ind = i; text = t; } } private List<IndexedString> n1; private List<IndexedString> n100; private List<IndexedString> n10000; private List<IndexedString> n1000000; private final List<List<IndexedString>> offsets = new ArrayList<>(10); private List<IndexedString> init(int num) { List<IndexedString> result = new ArrayList<>(num); for (int i = 0; i < num; ++i) { result.add(new IndexedString(i, "This is string " + i)); } return result; } @Setup public void setUp() throws IOException { n1 = init(1); n100 = init(100); n10000 = init(10000); n1000000 = init(1000000); offsets.add(n1); offsets.add(null); offsets.add(n100); offsets.add(null); offsets.add(n10000); offsets.add(null); offsets.add(n1000000); } @Param({"0", "2", "4", "6"}) public int exponent; // // Benchmarks to measure the overhead of lambdas in standard processing scenarios // Filter: extract an element of an object list, and collect it into a list of just that element // Index: create a map of the objects, indexed by an element of the object // @Benchmark public void javaFilterClassicWithKnownResultSize(Blackhole bh) { // classic java approach: preallocate the target, loop final List<IndexedString> data = offsets.get(exponent); final List<Integer> filtered = new ArrayList<>(data.size()); for (IndexedString obj: data) filtered.add(obj.ind); bh.consume(filtered); } @Benchmark public void javaFilterClassicWithDynamicResultSize(Blackhole bh) { // classic java approach: preallocate the target, with small initial size, then loop (causes GC overhead due to reallocations) final List<IndexedString> data = offsets.get(exponent); final List<Integer> filtered = new ArrayList<>(); for (IndexedString obj: data) filtered.add(obj.ind); bh.consume(filtered); } @Benchmark public void javaFilterStreamWithKnownResultSize(Blackhole bh) { // stream approach, but spend some more effort into preallocating the result structure final List<IndexedString> data = offsets.get(exponent); final List<Integer> filtered = data.stream().map(x -> x.ind).collect(Collectors.toCollection(() -> new ArrayList<Integer>(data.size()))); bh.consume(filtered); } @Benchmark public void javaFilterStreamWithDynamicResultSize(Blackhole bh) { // The streams approach seen most often (it is the shortest to write) final List<IndexedString> data = offsets.get(exponent); final List<Integer> filtered = data.stream().map(x -> x.ind).collect(Collectors.toList()); bh.consume(filtered); } @Benchmark public void javaIndexClassicWithKnownResultSize(Blackhole bh) { // classic java approach: preallocate the target, loop final List<IndexedString> data = offsets.get(exponent); final Map<Integer, IndexedString> indexed = new HashMap<>(2 * data.size()); for (IndexedString obj: data) indexed.put(obj.ind, obj); bh.consume(indexed); } @Benchmark public void javaIndexClassicWithDynamicResultSize(Blackhole bh) { // classic java approach: preallocate the target, with small initial size, then loop (causes GC overhead due to reallocations) final List<IndexedString> data = offsets.get(exponent); final Map<Integer, IndexedString> indexed = new HashMap<>(); for (IndexedString obj: data) indexed.put(obj.ind, obj); bh.consume(indexed); } @Benchmark public void javaIndexStreamWithKnownResultSize(Blackhole bh) { // streams approach with forEach final List<IndexedString> data = offsets.get(exponent); final Map<Integer, IndexedString> indexed = new HashMap<>(2 * data.size()); data.stream().forEach(obj -> indexed.put(obj.ind, obj)); bh.consume(indexed); } @Benchmark public void javaIndexForeachWithKnownResultSize(Blackhole bh) { // functional approach with forEach directly applied to collection final List<IndexedString> data = offsets.get(exponent); final Map<Integer, IndexedString> indexed = new HashMap<>(2 * data.size()); data.forEach(obj -> indexed.put(obj.ind, obj)); bh.consume(indexed); } @Benchmark public void javaIndexStreamWithDynamicResultSize(Blackhole bh) { // The streams approach seen most often (it is the shortest to write) final List<IndexedString> data = offsets.get(exponent); final Map<Integer, IndexedString> indexed = data.stream().collect(Collectors.toMap(o -> o.ind, o -> o)); bh.consume(indexed); } }
3e08c7da598f9ee95fd4a69fa7025b91239de0cf
2,204
java
Java
modules/indexing/src/main/java/org/apache/ignite/internal/processors/cache/query/RegisteredQueryCursor.java
gabrielj1994/test-ignite
4a3213b8781d84dcd292079a55f792d458cc6d2e
[ "CC0-1.0" ]
null
null
null
modules/indexing/src/main/java/org/apache/ignite/internal/processors/cache/query/RegisteredQueryCursor.java
gabrielj1994/test-ignite
4a3213b8781d84dcd292079a55f792d458cc6d2e
[ "CC0-1.0" ]
null
null
null
modules/indexing/src/main/java/org/apache/ignite/internal/processors/cache/query/RegisteredQueryCursor.java
gabrielj1994/test-ignite
4a3213b8781d84dcd292079a55f792d458cc6d2e
[ "CC0-1.0" ]
1
2020-11-09T04:24:06.000Z
2020-11-09T04:24:06.000Z
33.393939
113
0.716878
3,721
/* * 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.ignite.internal.processors.cache.query; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.ignite.internal.processors.cache.QueryCursorImpl; import org.apache.ignite.internal.processors.query.GridQueryCancel; import org.apache.ignite.internal.processors.query.RunningQueryManager; /** * Query cursor for registered as running queries. * * Running query will be unregistered during close of cursor. */ public class RegisteredQueryCursor<T> extends QueryCursorImpl<T> { /** */ private final AtomicBoolean unregistered = new AtomicBoolean(false); /** */ private RunningQueryManager runningQryMgr; /** */ private Long qryId; /** * @param iterExec Query executor. * @param cancel Cancellation closure. * @param runningQryMgr Running query manager. * @param qryId Registered running query id. */ public RegisteredQueryCursor(Iterable<T> iterExec, GridQueryCancel cancel, RunningQueryManager runningQryMgr, Long qryId) { super(iterExec, cancel); assert runningQryMgr != null; assert qryId != null; this.runningQryMgr = runningQryMgr; this.qryId = qryId; } /** {@inheritDoc} */ @Override public void close() { if (unregistered.compareAndSet(false, true)) runningQryMgr.unregister(qryId); super.close(); } }
3e08c85d20cdc3bb39ab3b8ab9f2529067951036
88
java
Java
src/main/java/nablarch/integration/log/jbosslogging/package-info.java
nablarch/nablarch-jboss-logging-adaptor
3ce9f1e70728b4fe28c2b23b98fc5fd12f614413
[ "Apache-2.0" ]
null
null
null
src/main/java/nablarch/integration/log/jbosslogging/package-info.java
nablarch/nablarch-jboss-logging-adaptor
3ce9f1e70728b4fe28c2b23b98fc5fd12f614413
[ "Apache-2.0" ]
null
null
null
src/main/java/nablarch/integration/log/jbosslogging/package-info.java
nablarch/nablarch-jboss-logging-adaptor
3ce9f1e70728b4fe28c2b23b98fc5fd12f614413
[ "Apache-2.0" ]
null
null
null
22
46
0.784091
3,722
/** * jboss-loggingを使用したログ出力機能を提供する。 */ package nablarch.integration.log.jbosslogging;
3e08c8dae97337029e1ee75f13625561a240e051
3,499
java
Java
src/org/sosy_lab/cpachecker/util/heapgraph/HeapVarLabeling.java
nishanttotla/cpachecker-1.4
d5d1b8c266a40f13a226f46577ca23744c0c4420
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/org/sosy_lab/cpachecker/util/heapgraph/HeapVarLabeling.java
nishanttotla/cpachecker-1.4
d5d1b8c266a40f13a226f46577ca23744c0c4420
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/org/sosy_lab/cpachecker/util/heapgraph/HeapVarLabeling.java
nishanttotla/cpachecker-1.4
d5d1b8c266a40f13a226f46577ca23744c0c4420
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
34.303922
123
0.699057
3,723
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.util.heapgraph; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.sosy_lab.cpachecker.util.heapgraph.Graph.ThreeVal; /* * This class stores heap variable labelings, as they exist in a current graph. * More heap variables get added as they're encountered, and a labeling from variable * to nodes is stored here. */ public class HeapVarLabeling { private class HVEdge { public Node node; public String heapVar; public HVEdge(Node node, String var) { this.node = node; this.heapVar = var; } } public Set<String> heapVarsSeen; // all heapvars seen so far, need to be tracked in the graph public HashMap<HVEdge, ThreeVal> heapVarLabels; // V: N x Vars_H -> B3. For optimality, only store TRUE/MAYBE edges public HeapVarLabeling() { this.heapVarsSeen = new HashSet<>(); this.heapVarLabels = new HashMap<>(); } public void addNewHeapVar(String var) { heapVarsSeen.add(var); // TODO add maybe edges to all nodes } // adds a new node+heapvar pair with value TRUE public void addNewNodeWithHeapVarAssignment(Node node, String var) { HVEdge newEdge = new HVEdge(node, var); // Src: http://stackoverflow.com/questions/6092642/how-to-remove-a-key-from-hashmap-while-iterating-over-it // First remove existing entries for var Iterator< Map.Entry<HVEdge, ThreeVal> > iter = heapVarLabels.entrySet().iterator(); while(iter.hasNext()) { Map.Entry<HVEdge, ThreeVal> entry = iter.next(); if(entry.getValue() == ThreeVal.TRUE || entry.getValue() == ThreeVal.MAYBE) { iter.remove(); } } heapVarLabels.put(newEdge, ThreeVal.TRUE); } public ThreeVal getHeapVarAssignmentStatus(Node node, String var) { HVEdge queryEdge = new HVEdge(node, var); if(heapVarLabels.containsKey(queryEdge)) { return heapVarLabels.get(queryEdge); } return ThreeVal.FALSE; } // used for var1 := var2 public void copyHeapVar(String var1, String var2) { // TODO delete all occurences for var1 // TODO iterate through all occurences for var2, and copy those for var 1 } public Set<Node> getAllNodesPointedByHeapVar(String var) { // Iterate over all HVEdges and find nodes that var points to (True or Maybe) Set<Node> pointedNodes = new HashSet<>(); for(Map.Entry<HVEdge, ThreeVal> entry : heapVarLabels.entrySet()) { if(entry.getKey().heapVar.equals(var) && (entry.getValue() == ThreeVal.TRUE || entry.getValue() == ThreeVal.MAYBE)) { pointedNodes.add(entry.getKey().node); } } return pointedNodes; } }
3e08c9211c923f9e345ad4e19f3b74f2c8c319a5
8,458
java
Java
app/src/main/java/com/example/android/miwok/NumbersActivity.java
destiana/miwok
a7ca5f96f95b50a2345111d68da48c2d355c2e69
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/NumbersActivity.java
destiana/miwok
a7ca5f96f95b50a2345111d68da48c2d355c2e69
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/NumbersActivity.java
destiana/miwok
a7ca5f96f95b50a2345111d68da48c2d355c2e69
[ "Apache-2.0" ]
null
null
null
47.785311
129
0.64637
3,724
package com.example.android.miwok; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class NumbersActivity extends AppCompatActivity { /** Handles playback of all the sound files */ private MediaPlayer mMediaPlayer; /** Handles audio focus when playing a sound file */ private AudioManager mAudioManager; /** * This listener gets triggered whenever the audio focus changes * (i.e., we gain or lose audio focus because of another app or device). */ private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that // our app is allowed to continue playing sound but at a lower volume. We'll treat // both cases the same way because our app is playing short sound files. // Pause playback and reset player to the start of the file. That way, we can // play the word from the beginning when we resume playback. mMediaPlayer.pause(); mMediaPlayer.seekTo(0); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback. mMediaPlayer.start(); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { // The AUDIOFOCUS_LOSS case means we've lost audio focus and // Stop playback and clean up resources releaseMediaPlayer(); } } }; /** * This listener gets triggered when the {@link MediaPlayer} has completed * playing the audio file. */ private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { // Now that the sound file has finished playing, release the media player resources. releaseMediaPlayer(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Create and setup the {@link AudioManager} to request audio focus mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Create a list of words final ArrayList<Word> words = new ArrayList<Word>(); words.add(new Word("satu", "setunggal", R.drawable.number_one, R.raw.number_one)); words.add(new Word("dua", "kalih", R.drawable.number_two, R.raw.number_two)); words.add(new Word("tiga", "tigo", R.drawable.number_three, R.raw.number_three)); words.add(new Word("empat", "sekawan", R.drawable.number_four, R.raw.number_four)); words.add(new Word("lima", "gangsal", R.drawable.number_five, R.raw.number_five)); words.add(new Word("enam", "enem", R.drawable.number_six, R.raw.number_six)); words.add(new Word("tujuh", "pitu", R.drawable.number_seven, R.raw.number_seven)); words.add(new Word("delapan", "wolu", R.drawable.number_eight, R.raw.number_eight)); words.add(new Word("sembilan", "songo", R.drawable.number_nine, R.raw.number_nine)); words.add(new Word("sepuluh", "sedoso", R.drawable.number_ten, R.raw.number_ten)); // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The // adapter knows how to create list items for each item in the list. WordAdapter adapter = new WordAdapter(this, words, R.color.category_1); // Find the {@link ListView} object in the view hierarchy of the {@link Activity}. // There should be a {@link ListView} with the view ID called list, which is declared in the // word_list.xml layout file. ListView listView = (ListView) findViewById(R.id.list); // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the // {@link ListView} will display list items for each {@link Word} in the list. listView.setAdapter(adapter); // Set a click listener to play the audio when the list item is clicked on listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { // Release the media player if it currently exists because we are about to // play a different sound file releaseMediaPlayer(); // Get the {@link Word} object at the given position the user clicked on Word word = words.get(position); // Request audio focus so in order to play the audio file. The app needs to play a // short audio file, so we will request audio focus with a short amount of time // with AUDIOFOCUS_GAIN_TRANSIENT. int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // We have audio focus now. // Create and setup the {@link MediaPlayer} for the audio resource associated // with the current word mMediaPlayer = MediaPlayer.create(NumbersActivity.this, word.getAudioResourceId()); // Start the audio file mMediaPlayer.start(); // Setup a listener on the media player, so that we can stop and release the // media player once the sound has finished playing. mMediaPlayer.setOnCompletionListener(mCompletionListener); } } }); } @Override protected void onStop() { super.onStop(); // When the activity is stopped, release the media player resources because we won't // be playing any more sounds. releaseMediaPlayer(); } /** * Clean up the media player by releasing its resources. */ private void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mMediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mMediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mMediaPlayer = null; // Regardless of whether or not we were granted audio focus, abandon it. This also // unregisters the AudioFocusChangeListener so we don't get anymore callbacks. mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); } } public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. ; int id = item.getItemId(); if(id == android.R.id.home){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); return true; } //noinspection SimplifiableIfStatement return super.onOptionsItemSelected(item); } }
3e08c9cfc56eb4c383f45f356a4fee5bc2ee3d60
13,763
java
Java
src/main/java/com/example/application/backend/service/impl/TransactionServiceImpl.java
zirpindevs/ProyectoBancaVaadin
5d25bfdb10604a7cff943ae7fadeac07614e17c3
[ "Unlicense" ]
null
null
null
src/main/java/com/example/application/backend/service/impl/TransactionServiceImpl.java
zirpindevs/ProyectoBancaVaadin
5d25bfdb10604a7cff943ae7fadeac07614e17c3
[ "Unlicense" ]
null
null
null
src/main/java/com/example/application/backend/service/impl/TransactionServiceImpl.java
zirpindevs/ProyectoBancaVaadin
5d25bfdb10604a7cff943ae7fadeac07614e17c3
[ "Unlicense" ]
null
null
null
34.843038
269
0.657923
3,725
package com.example.application.backend.service.impl; import com.example.application.backend.dao.TransactionDAO; import com.example.application.backend.model.*; import com.example.application.backend.model.transaction.operations.TransactionsCreditcardResponse; import com.example.application.backend.model.transaction.operations.TransactionsUserResponse; import com.example.application.backend.model.transaction.operations.idbankaccountTransactions.TransactionsByBankAccountResponse; import com.example.application.backend.repository.*; import com.example.application.backend.service.TransactionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @Service public class TransactionServiceImpl implements TransactionService { private final Logger log = LoggerFactory.getLogger(Transaction.class); private final TransactionRepository transactionRepository; private final BankAccountRepository bankAccountRepository; private final CategoryRepository categoryRepository; private final CreditCardRepository creditCardRepository; private final UserRepository userRepository; private final TransactionDAO transactionDAO; public TransactionServiceImpl(TransactionRepository transactionRepository, BankAccountRepository bankAccountRepository, CategoryRepository categoryRepository, CreditCardRepository creditCardRepository, UserRepository userRepository, TransactionDAO transactionDAO) { this.transactionRepository = transactionRepository; this.bankAccountRepository = bankAccountRepository; this.categoryRepository = categoryRepository; this.creditCardRepository = creditCardRepository; this.userRepository = userRepository; this.transactionDAO = transactionDAO; } @Override public List<Transaction> findAll() { log.info("REST request to find all Transactions"); return this.transactionRepository.findAll(); } @Override public Transaction findOne(Long id) { log.info("REST request to find one BankAccount by id"); if (id == null) return null; return this.transactionDAO.findById(id); } @Override public TransactionsByBankAccountResponse findAllTransactionsByDateRangeByIdBankAccount(Long idBankAccount, Map<String, String> map1) { return null; } /** * @param idUser * @param map1 * @return */ @Override public TransactionsUserResponse findAllTransactionsByDateRangeByIdUser(Long idUser, Map<String, String> map1) { try { if (map1.get("startDate") != null && map1.get("endDate") != null) { return this.transactionDAO.findAllTransactionsByDateRangeByIdUser(idUser, map1); } return new TransactionsUserResponse("-404"); } catch (Exception e) { log.error(e.getMessage()); return new TransactionsUserResponse("-500"); } } /** * Create a new transaction in database - Service * * @param transactionDTO to update * @return Transaction created in database */ @Override public Transaction createTransaction(TransactionDTO transactionDTO) { log.debug("Create Transaction: {}", transactionDTO); Transaction transactionValidated = createValidateTransaction(transactionDTO); try { transactionValidated.setCreatedDate(Timestamp.from(Instant.now())); transactionValidated.setLastModified(Instant.now()); return transactionRepository.save(transactionValidated); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); Transaction transactiondError = new Transaction(); transactiondError.setId(-500L); return transactiondError; } } @Override public Transaction createTransactionForm(TransactionDTO transactionDTO) { return this.createTransaction(transactionDTO); } /** * It update a transaction of database - Service * * @param transactionDTO to update * @return Transaction updated in database */ @Override public Transaction updateTransaction(Long id, TransactionDTO transactionDTO) { log.debug("Update a Transaction: {}", transactionDTO); try { Transaction transactionValidated = updateValidateTransaction(id, transactionDTO); if (transactionValidated.getId() == null) { Transaction transactionError = new Transaction(); transactionError.setId(-404L); return transactionError; } return transactionRepository.save(transactionValidated); } catch (Exception e) { log.error(e.getMessage()); Transaction transactionError = new Transaction(); transactionError.setId(-500L); return transactionError; } } @Override public void deleteTransaction(Transaction transactionToDelete) { log.info("REST request to delete an Transaction by id"); this.transactionRepository.deleteById(transactionToDelete.getId()); } /** * Create a new transaction in database - Service * * @param transactionDTO to update * @return Transaction created in database */ @Override public Boolean createTransactionVaadin(TransactionDTO transactionDTO) { log.debug("Create Transaction: {}", transactionDTO); /* Transaction transactionValidated = createValidateTransaction(transactionDTO); */ try { /* transactionValidated.setCreatedDate(Timestamp.from(Instant.now())); transactionValidated.setLastModified(Instant.now());*/ BankAccount bankAccount = new BankAccount(); bankAccount = bankAccountRepository.findById(transactionDTO.getIdBankAccount()).get(); return transactionDAO.insertNewTransactionAndUpdateBalance(transactionDTO, bankAccount); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); return false; } } /** * Validate a transaction before to save in db * * @param transactionDTO * @return Transaction */ private Transaction createValidateTransaction(TransactionDTO transactionDTO) { Transaction transactionEmpty = new Transaction(); if (transactionDTO.getConcepto() == null || transactionDTO.getImporte() == null || transactionDTO.getTipoMovimiento() == null || ValidateTypeOfMovimiento(transactionDTO.getTipoMovimiento()) != true) { return transactionEmpty; } if (transactionDTO.getIdBankAccount() == null && transactionDTO.getIdCreditCard() == null) { return transactionEmpty; } else { // If passed all validations Transaction transaction = new Transaction(); transaction.setConcepto(transactionDTO.getConcepto()); transaction.setImporte(transactionDTO.getImporte()); transaction.setTipoMovimiento(transactionDTO.getTipoMovimiento()); transaction.setCreatedDate(Timestamp.from(Instant.now())); if (transactionDTO.getIdBankAccount() != null) { Optional<BankAccount> bankAccount = bankAccountRepository.findById(transactionDTO.getIdBankAccount()); transaction.setBankAccount(bankAccount.get()); } if (transactionDTO.getIdCategory() != null) { Optional<Category> category = categoryRepository.findOneById(transactionDTO.getIdCategory()); transaction.setCategory(category.get()); } if (transactionDTO.getIdCreditCard() != null) { Optional<CreditCard> creditCard = creditCardRepository.findOneById(transactionDTO.getIdCreditCard()); transaction.setCreditCard(creditCard.get()); } // Function to set current balance in the BankAccounts and in Transaction before an operation currentBalance(transaction); return transaction; } } /** * Validate a Transaction before to update in db * * @param transactionDTO * @return Transaction */ private Transaction updateValidateTransaction(Long id, TransactionDTO transactionDTO) { if (transactionDTO.getConcepto() == null || transactionDTO.getImporte() == null || transactionDTO.getTipoMovimiento() == null || transactionDTO.getCreatedDate() == null) { return new Transaction(); } else { // Exist ? Optional<Transaction> transactionDB = this.transactionRepository.findById(id); if (ObjectUtils.isEmpty(transactionDB)) return new Transaction(); // Is not possible to modify the importe of the transaction if (!transactionDTO.getImporte().equals(transactionDB.get().getImporte())) return new Transaction(); // Is not possible to modify the concepto of the transaction if (!transactionDTO.getConcepto().equals(transactionDB.get().getConcepto())) return new Transaction(); // Is not possible to modify the Date of the transaction if (!transactionDTO.getCreatedDate().equals(transactionDB.get().getCreatedDate())) return new Transaction(); if (transactionDTO.getIdBankAccount() != null) { // Is not possible to modify the bankaccount own of the transaction if (!transactionDTO.getIdBankAccount().equals(transactionDB.get().getBankAccount().getId())) return new Transaction(); } if (transactionDTO.getIdCategory() != null) { // Is not possible to modify the category own of the transaction if (!transactionDTO.getIdCategory().equals(transactionDB.get().getCategory().getId())) return new Transaction(); } if (transactionDTO.getIdCreditCard() != null) { // Is not possible to modify the creditcard own of the transaction if (!transactionDTO.getCreatedDate().equals(transactionDB.get().getCreditCard().getId())) return new Transaction(); } // Only is possible to modify in a transaction el tipo de movimiento transactionDB.get().setTipoMovimiento(transactionDTO.getTipoMovimiento()); transactionDB.get().setLastModified(Instant.now()); return transactionDB.get(); } } /** * Set the current balance in the BankAccounts and Transaction before an operation * * @param transaction * @return Transaction */ private Transaction currentBalance(Transaction transaction) { if (transaction.getTipoMovimiento().equals(MovimientoType.PAGO) || transaction.getTipoMovimiento().equals(MovimientoType.RECIBO)) { transaction.getBankAccount().setBalance(transaction.getBankAccount().getBalance() - transaction.getImporte()); } if (transaction.getTipoMovimiento().equals(MovimientoType.TRANSFERENCIA) || transaction.getTipoMovimiento().equals(MovimientoType.ABONO)) { transaction.getBankAccount().setBalance(transaction.getBankAccount().getBalance() + transaction.getImporte()); } transaction.setBalanceAfterTransaction(transaction.getBankAccount().getBalance()); return transaction; } /** * Check if the type of movimiento is a right field * * @param movimientoType * @return Boolean */ private Boolean ValidateTypeOfMovimiento(Enum movimientoType) { return (movimientoType).equals(MovimientoType.PAGO) || movimientoType.equals(MovimientoType.RECIBO) || movimientoType.equals(MovimientoType.TRANSFERENCIA) || movimientoType.equals(MovimientoType.ABONO); } /**************************************************************************************************** * * * * * */ /** * Get transactions by creditcard ID - Service * * @param idCreditcard id creditcard id of transactions : Long * @return List<Transaction> from database */ @Override public TransactionsCreditcardResponse findAllTransactionsByDateRangeByIdCreditcard(Long idCreditcard, Map<String, String> map1) { try { if (map1.get("startDate") != null && map1.get("endDate") != null) { return this.transactionDAO.findAllTransactionsByDateRangeByIdCreditcard(idCreditcard, map1); } return new TransactionsCreditcardResponse("-404"); } catch (Exception e) { log.error(e.getMessage()); return new TransactionsCreditcardResponse("-500"); } } /** * Get balance after transaction by User ID - Service * * @param idUser id user id of transactions : Long * @returnObject[] from database format to a chart */ @Override public Object[] findAllBalanceAfterTransaction(Long idUser) { try { if (idUser != null) return (Object[]) this.transactionDAO.findAllBalanceAfterTransaction(idUser); } catch (Exception e) { log.error(e.getMessage()); return null; } return null; } }
3e08c9d938e091fc225864bd088adfe9ebf6550f
1,996
java
Java
fplay.plugin/src/main/java/br/com/carlosrafaelgn/fplay/plugin/SongInfo.java
hieuho1234/LTD-
b874d795c8b0bbde9fd7a3d3054e1a8fc1579778
[ "BSD-2-Clause" ]
147
2015-01-26T14:55:57.000Z
2022-01-26T19:46:41.000Z
fplay.plugin/src/main/java/br/com/carlosrafaelgn/fplay/plugin/SongInfo.java
hieuho1234/LTD-
b874d795c8b0bbde9fd7a3d3054e1a8fc1579778
[ "BSD-2-Clause" ]
15
2015-02-22T21:17:30.000Z
2020-09-04T15:15:36.000Z
fplay.plugin/src/main/java/br/com/carlosrafaelgn/fplay/plugin/SongInfo.java
hieuho1234/LTD-
b874d795c8b0bbde9fd7a3d3054e1a8fc1579778
[ "BSD-2-Clause" ]
62
2015-01-10T08:40:56.000Z
2022-02-01T17:15:27.000Z
45.363636
82
0.773547
3,726
// // FPlayAndroid is distributed under the FreeBSD License // // Copyright (c) 2013-2014, Carlos Rafael Gimenes das Neves // 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. // // 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // https://github.com/carlosrafaelgn/FPlayAndroid // package br.com.carlosrafaelgn.fplay.plugin; @SuppressWarnings("unused") public class SongInfo { public long id; public String path; public boolean isHttp; public String title, artist, album, extraInfo; public int track, lengthMS, year; public String length; }
3e08cb041861d7129e5a374722643691cac26346
2,169
java
Java
metrics-common/src/test/java/com/alibaba/metrics/common/filter/CompositeMetricFilterTest.java
FanYuliang/metrics
cef761e652a1ffa7927015ae2c27809dba18deae
[ "Apache-2.0" ]
417
2019-04-30T09:25:47.000Z
2022-03-11T10:45:08.000Z
metrics-common/src/test/java/com/alibaba/metrics/common/filter/CompositeMetricFilterTest.java
FanYuliang/metrics
cef761e652a1ffa7927015ae2c27809dba18deae
[ "Apache-2.0" ]
44
2019-05-07T03:14:22.000Z
2022-02-11T04:50:38.000Z
metrics-common/src/test/java/com/alibaba/metrics/common/filter/CompositeMetricFilterTest.java
FanYuliang/metrics
cef761e652a1ffa7927015ae2c27809dba18deae
[ "Apache-2.0" ]
118
2019-05-04T15:13:44.000Z
2022-03-29T10:03:09.000Z
32.863636
92
0.713693
3,727
/* * 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.alibaba.metrics.common.filter; import com.alibaba.metrics.Metric; import com.alibaba.metrics.MetricFilter; import com.alibaba.metrics.MetricManager; import com.alibaba.metrics.MetricName; import org.junit.Assert; import org.junit.Test; public class CompositeMetricFilterTest { @Test public void testNoFilters() { CompositeMetricFilter filter = new CompositeMetricFilter(MetricFilter.ALL); Assert.assertArrayEquals(null, filter.filters); MetricName name = MetricName.build("test"); Assert.assertTrue(filter.matches(name, MetricManager.getCounter("ttt", name))); } @Test public void testOneFilter() { MetricFilter filter2 = new MetricFilter() { @Override public boolean matches(MetricName name, Metric metric) { return name.getKey().equals("test"); } }; CompositeMetricFilter filter = new CompositeMetricFilter(MetricFilter.ALL, filter2); Assert.assertArrayEquals(new MetricFilter[]{filter2}, filter.filters); MetricName name = MetricName.build("test"); Assert.assertTrue(filter.matches(name, MetricManager.getCounter("ttt", name))); MetricName name2 = MetricName.build("test2"); Assert.assertFalse(filter.matches(name2, MetricManager.getCounter("ttt", name2))); } }
3e08cc791e526406568390d04830232a926b82f6
3,041
java
Java
app/src/main/java/com/mine/musharing/recyclerViewAdapters/CategoryAdapter.java
windsea/Musharing-Android
87b81280a2b019e6db455ddcfd5d9776005f38f8
[ "MIT" ]
3
2019-08-09T14:02:16.000Z
2019-12-14T15:00:58.000Z
app/src/main/java/com/mine/musharing/recyclerViewAdapters/CategoryAdapter.java
windsea/Musharing-Android
87b81280a2b019e6db455ddcfd5d9776005f38f8
[ "MIT" ]
13
2019-09-03T14:17:42.000Z
2020-02-04T04:00:04.000Z
app/src/main/java/com/mine/musharing/recyclerViewAdapters/CategoryAdapter.java
windsea/Musharing-Android
87b81280a2b019e6db455ddcfd5d9776005f38f8
[ "MIT" ]
1
2019-08-26T22:36:21.000Z
2019-08-26T22:36:21.000Z
29.524272
100
0.684972
3,728
package com.mine.musharing.recyclerViewAdapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.mine.musharing.R; import com.mine.musharing.models.Category; import com.mine.musharing.utils.Utility; import java.util.List; import static android.support.constraint.Constraints.TAG; /** * CategoryFragment 中 Categories RecycleView 的 Adapter */ public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{ private Context mContext; private List<Category> mCategoryList; private OnItemClickListener onItemClickListener; static class ViewHolder extends RecyclerView.ViewHolder { CardView cardView; ImageView imageView; TextView textView; public ViewHolder(View view) { super(view); cardView = (CardView) view; imageView = view.findViewById(R.id.category_image); textView = view.findViewById(R.id.category_title); } } public CategoryAdapter(List<Category> categories) { mCategoryList = categories; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { if (mContext == null) { mContext = viewGroup.getContext(); } View view = LayoutInflater.from(mContext).inflate(R.layout.category_item, viewGroup, false); final ViewHolder holder = new ViewHolder(view); holder.cardView.setOnClickListener(v -> { int position = holder.getAdapterPosition(); Category category = mCategoryList.get(position); if(onItemClickListener != null){ onItemClickListener.OnItemClick(v, category); } }); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { Log.d(TAG, "onBindViewHolder: mCategoryList: " + mCategoryList); Category category = mCategoryList.get(i); viewHolder.cardView.setCardBackgroundColor(Utility.randomCardColor()); Glide.with(mContext).load(category.getImage()).into(viewHolder.imageView); viewHolder.textView.setText(category.getTitle()); } @Override public int getItemCount() { return mCategoryList.size(); } /** * 设置item的监听事件的接口 */ public interface OnItemClickListener { /** * 接口中的点击每一项的实现方法 * * @param view 点击的item的视图 * @param member 点击的item的数据 */ public void OnItemClick(View view, Category member); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } }
3e08ccc07e24cd361cef2f69671866337b2b4245
198
java
Java
src/main/java/xyz/andrewkboyd/etltemplate/dto/LatestNumbers.java
akboyd88/etl-template
8006f322fc8d83d091cc490f702f8ecccf0336aa
[ "MIT" ]
null
null
null
src/main/java/xyz/andrewkboyd/etltemplate/dto/LatestNumbers.java
akboyd88/etl-template
8006f322fc8d83d091cc490f702f8ecccf0336aa
[ "MIT" ]
38
2021-01-30T15:09:31.000Z
2021-07-27T07:06:14.000Z
src/main/java/xyz/andrewkboyd/etltemplate/dto/LatestNumbers.java
akboyd88/etl-template
8006f322fc8d83d091cc490f702f8ecccf0336aa
[ "MIT" ]
1
2021-02-06T16:15:54.000Z
2021-02-06T16:15:54.000Z
18
40
0.767677
3,729
package xyz.andrewkboyd.etltemplate.dto; import lombok.Data; @Data public class LatestNumbers { private int postgresqlNumber; private int cassandraNumber; private int influxNumber; }
3e08cd582eab0d5851d7f6aaf1e2ab69095086e3
583
java
Java
src/main/java/com/java/poc/dto/Apple.java
sudiptobhowmick59/java8
9a791fc18288170877ffef6375adbf24f932140f
[ "MIT" ]
null
null
null
src/main/java/com/java/poc/dto/Apple.java
sudiptobhowmick59/java8
9a791fc18288170877ffef6375adbf24f932140f
[ "MIT" ]
null
null
null
src/main/java/com/java/poc/dto/Apple.java
sudiptobhowmick59/java8
9a791fc18288170877ffef6375adbf24f932140f
[ "MIT" ]
null
null
null
13.880952
62
0.653516
3,730
package com.java.poc.dto; import lombok.Data; @Data public class Apple { private String color; private Integer weight; public Apple(String color, Integer weight) { super(); this.color = color; this.weight = weight; } /*public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } @Override public String toString() { return "Apple [color=" + color + ", weight=" + weight + "]"; }*/ }
3e08cdb81abb0c9c1d8e5ca35916622facde528f
2,271
java
Java
vanilladb/core-patch/src/main/java/org/vanilladb/core/storage/file/io/jaydio/JaydioDirectIoChannel.java
didwdidw0309/Database-system
12c9e28b4d1236c65646febdc972f24e2b6742a2
[ "Apache-2.0" ]
null
null
null
vanilladb/core-patch/src/main/java/org/vanilladb/core/storage/file/io/jaydio/JaydioDirectIoChannel.java
didwdidw0309/Database-system
12c9e28b4d1236c65646febdc972f24e2b6742a2
[ "Apache-2.0" ]
null
null
null
vanilladb/core-patch/src/main/java/org/vanilladb/core/storage/file/io/jaydio/JaydioDirectIoChannel.java
didwdidw0309/Database-system
12c9e28b4d1236c65646febdc972f24e2b6742a2
[ "Apache-2.0" ]
null
null
null
34.938462
81
0.731836
3,731
/******************************************************************************* * Copyright 2016, 2017 vanilladb.org 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 org.vanilladb.core.storage.file.io.jaydio; import java.io.File; import java.io.IOException; import org.vanilladb.core.storage.file.io.IoBuffer; import org.vanilladb.core.storage.file.io.IoChannel; import net.smacke.jaydio.buffer.AlignedDirectByteBuffer; import net.smacke.jaydio.channel.BufferedChannel; import net.smacke.jaydio.channel.DirectIoByteChannel; public class JaydioDirectIoChannel implements IoChannel { private BufferedChannel<AlignedDirectByteBuffer> fileChannel; public JaydioDirectIoChannel(File file) throws IOException { fileChannel = DirectIoByteChannel.getChannel(file, false); } @Override public int read(IoBuffer buffer, long position) throws IOException { JaydioDirectByteBuffer jaydioBuffer = (JaydioDirectByteBuffer) buffer; return fileChannel.read(jaydioBuffer.getAlignedDirectByteBuffer(), position); } @Override public int write(IoBuffer buffer, long position) throws IOException { JaydioDirectByteBuffer jaydioBuffer = (JaydioDirectByteBuffer) buffer; return fileChannel.write(jaydioBuffer.getAlignedDirectByteBuffer(), position); } @Override public long append(IoBuffer buffer) throws IOException { JaydioDirectByteBuffer jaydioBuffer = (JaydioDirectByteBuffer) buffer; fileChannel.write(jaydioBuffer.getAlignedDirectByteBuffer(), size()); return size(); } @Override public long size() throws IOException { return fileChannel.size(); } @Override public void close() throws IOException { fileChannel.close(); } }
3e08ce4a426b85b5cb205e2c3f7814d51d940109
662
java
Java
app/src/main/java/com/deveryware/emitter/broadcast/StartOnBoot.java
sylvek/emitter
a38a7e3b7555fd9561b06d4f7e0c98be60a5206b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/deveryware/emitter/broadcast/StartOnBoot.java
sylvek/emitter
a38a7e3b7555fd9561b06d4f7e0c98be60a5206b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/deveryware/emitter/broadcast/StartOnBoot.java
sylvek/emitter
a38a7e3b7555fd9561b06d4f7e0c98be60a5206b
[ "Apache-2.0" ]
1
2018-05-29T17:09:40.000Z
2018-05-29T17:09:40.000Z
21.354839
105
0.716012
3,732
/** * * Copyright (C) 2011 Deveryware S.A. All Rights Reserved. * * @author sylvek * */ package com.deveryware.emitter.broadcast; import com.deveryware.emitter.Constants; import android.content.Context; import android.content.Intent; import android.preference.PreferenceManager; public class StartOnBoot extends Start { @Override protected boolean needTo(Context context, Intent intent) { return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Constants.START_ON_BOOT, Constants.DEFAULT_START_ON_BOOT); } @Override protected boolean resetAttempt() { return true; } }
3e08ce7b7b75aa50a208d7d506cfed358aed54e0
2,673
java
Java
jingjiang/src/main/java/com/iaccount/framework/cache/memcache/MemCache.java
lggzc/lggzc
6f81eb37a413d620308aeb8054c39ff70eb0e733
[ "MIT" ]
null
null
null
jingjiang/src/main/java/com/iaccount/framework/cache/memcache/MemCache.java
lggzc/lggzc
6f81eb37a413d620308aeb8054c39ff70eb0e733
[ "MIT" ]
null
null
null
jingjiang/src/main/java/com/iaccount/framework/cache/memcache/MemCache.java
lggzc/lggzc
6f81eb37a413d620308aeb8054c39ff70eb0e733
[ "MIT" ]
null
null
null
32.597561
82
0.537598
3,733
package com.iaccount.framework.cache.memcache; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeoutException; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.exception.MemcachedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MemCache { private static Logger log = LoggerFactory.getLogger(MemCache.class); private Set<String> keySet = new HashSet<String>(); private final String name; private final int expire; private final MemcachedClient memcachedClient; public MemCache(String name, int expire, MemcachedClient memcachedClient) { this.name = name; this.expire = expire; this.memcachedClient = memcachedClient; } public Object get(String key) { Object value = null; try { key = this.getKey(key); value = memcachedClient.get(key); } catch (TimeoutException e) { log.warn("获取 Memcached 缓存超时", e); } catch (InterruptedException e) { log.warn("获取 Memcached 缓存被中断", e); } catch (MemcachedException e) { log.warn("获取 Memcached 缓存错误", e); } return value; } public void put(String key, Object value) { if (value == null) return; try{ key = this.getKey(key); memcachedClient.setWithNoReply(key, expire, value); keySet.add(key); }catch (InterruptedException e){ log.warn("更新 Memcached 缓存被中断", e); }catch (MemcachedException e){ log.warn("更新 Memcached 缓存错误", e); } } public void clear(){ for (String key : keySet){ try{ memcachedClient.deleteWithNoReply(this.getKey(key)); }catch (InterruptedException e){ log.warn("删除 Memcached 缓存被中断", e); }catch (MemcachedException e){ log.warn("删除 Memcached 缓存错误", e); } } } public void delete(String key){ try{ key = this.getKey(key); memcachedClient.deleteWithNoReply(key); }catch (InterruptedException e){ log.warn("删除 Memcached 缓存被中断", e); }catch (MemcachedException e){ log.warn("删除 Memcached 缓存错误", e); } } private String getKey(String key){ return name + "_" + key; } }
3e08cf6303632b11e3e92965aaca9e57347411a3
3,096
java
Java
Backend/src/main/java/mygoogleserviceapi/security/SecurityConfig.java
tara-pogancev/my-google-service
4b0f1d10052fccfaf74457d570f8c241131be8ed
[ "MIT" ]
1
2022-02-05T09:37:51.000Z
2022-02-05T09:37:51.000Z
Backend/src/main/java/mygoogleserviceapi/security/SecurityConfig.java
tara-pogancev/my-google-service
4b0f1d10052fccfaf74457d570f8c241131be8ed
[ "MIT" ]
null
null
null
Backend/src/main/java/mygoogleserviceapi/security/SecurityConfig.java
tara-pogancev/my-google-service
4b0f1d10052fccfaf74457d570f8c241131be8ed
[ "MIT" ]
null
null
null
39.692308
107
0.732881
3,734
package mygoogleserviceapi.security; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { private final UserDetailsService userDetailsService; private final JwtRequestFilter jwtRequestFilter; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .csrf().disable() .httpBasic() .and() .authorizeRequests() .antMatchers("/login/**", "/login", "/register", "/register/**").permitAll() .antMatchers("/swagger-ui/**").permitAll() .antMatchers("/v3/api-docs/**").permitAll() .anyRequest() .authenticated() .and() .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } @Bean public CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOriginPattern("*"); config.addAllowedHeader("*"); config.addAllowedMethod("GET"); config.addAllowedMethod("POST"); config.addAllowedMethod("PUT"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("OPTIONS"); source.registerCorsConfiguration("/**", config); return source; } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
3e08cf7db5889352d8a800d7d205320790ff2003
25,213
java
Java
stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/CassandraService.java
bernhardriegler/usergrid
79e37c9df0ee7debfb080b080cf4f6a5a03ebc46
[ "Apache-2.0" ]
788
2015-08-21T16:46:57.000Z
2022-03-16T01:57:44.000Z
stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/CassandraService.java
bernhardriegler/usergrid
79e37c9df0ee7debfb080b080cf4f6a5a03ebc46
[ "Apache-2.0" ]
101
2015-08-23T04:58:13.000Z
2019-11-13T07:02:57.000Z
stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/CassandraService.java
bernhardriegler/usergrid
79e37c9df0ee7debfb080b080cf4f6a5a03ebc46
[ "Apache-2.0" ]
342
2015-08-22T06:14:20.000Z
2022-03-15T01:20:39.000Z
34.491108
127
0.621822
3,735
/* * 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.usergrid.persistence.cassandra; import com.google.inject.Injector; import me.prettyprint.cassandra.connection.HConnectionManager; import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel; import me.prettyprint.cassandra.serializers.*; import me.prettyprint.cassandra.service.CassandraHostConfigurator; import me.prettyprint.cassandra.service.ThriftKsDef; import me.prettyprint.hector.api.*; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.DynamicComposite; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.KeyspaceDefinition; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.ColumnQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SliceQuery; import org.apache.usergrid.locking.LockManager; import org.apache.usergrid.persistence.core.CassandraFig; import org.apache.usergrid.persistence.hector.CountingMutator; import org.apache.usergrid.utils.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.*; import static me.prettyprint.cassandra.service.FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE; import static me.prettyprint.hector.api.factory.HFactory.*; import static org.apache.commons.collections.MapUtils.getIntValue; import static org.apache.commons.collections.MapUtils.getString; import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.batchExecute; import static org.apache.usergrid.utils.ConversionUtils.bytebuffer; import static org.apache.usergrid.utils.JsonUtils.mapToFormattedJsonString; import static org.apache.usergrid.utils.MapUtils.asMap; import static org.apache.usergrid.utils.MapUtils.filter; public class CassandraService { //make the below two not static // public static String SYSTEM_KEYSPACE = "Usergrid"; public static String applicationKeyspace; public static final boolean USE_VIRTUAL_KEYSPACES = true; public static final int DEFAULT_COUNT = 1000; public static final int ALL_COUNT = 100000; public static final int INDEX_ENTRY_LIST_COUNT = 1000; public static final int DEFAULT_SEARCH_COUNT = 10000; public static final int RETRY_COUNT = 5; public static final String DEFAULT_APPLICATION = "default-app"; public static final String DEFAULT_ORGANIZATION = "usergrid"; public static final String MANAGEMENT_APPLICATION = "management"; private static final Logger logger = LoggerFactory.getLogger( CassandraService.class ); private static final Logger db_logger = LoggerFactory.getLogger( CassandraService.class.getPackage().getName() + ".DB" ); Cluster cluster; CassandraHostConfigurator chc; Properties properties; LockManager lockManager; ConsistencyLevelPolicy consistencyLevelPolicy; public static String SYSTEM_KEYSPACE; public static String STATIC_APPLICATION_KEYSPACE; private Keyspace systemKeyspace; private Map<String, String> accessMap; public static final StringSerializer se = new StringSerializer(); public static final ByteBufferSerializer be = new ByteBufferSerializer(); public static final UUIDSerializer ue = new UUIDSerializer(); public static final BytesArraySerializer bae = new BytesArraySerializer(); public static final DynamicCompositeSerializer dce = new DynamicCompositeSerializer(); public static final LongSerializer le = new LongSerializer(); public static final UUID NULL_ID = new UUID( 0, 0 ); //Wire guice injector via spring here, just pass the injector in the spring public CassandraService( Properties properties, Cluster cluster, CassandraHostConfigurator cassandraHostConfigurator, final Injector injector) { this.properties = properties; this.cluster = cluster; chc = cassandraHostConfigurator; lockManager = injector.getInstance( LockManager.class ); db_logger.info( "{}", cluster.getKnownPoolHosts( false ) ); //getInjector applicationKeyspace = injector.getInstance( CassandraFig.class ).getApplicationKeyspace(); } public void init() throws Exception { SYSTEM_KEYSPACE = properties.getProperty( "cassandra.system.keyspace" ,"Usergrid"); STATIC_APPLICATION_KEYSPACE = properties.getProperty( "cassandra.application.keyspace","Usergrid_Applications" ); if ( consistencyLevelPolicy == null ) { consistencyLevelPolicy = new ConfigurableConsistencyLevel(); ( ( ConfigurableConsistencyLevel ) consistencyLevelPolicy ) .setDefaultReadConsistencyLevel( HConsistencyLevel.ONE ); } accessMap = new HashMap<String, String>( 2 ); accessMap.put( "username", properties.getProperty( "cassandra.username" ) ); accessMap.put( "password", properties.getProperty( "cassandra.password" ) ); systemKeyspace = HFactory.createKeyspace( getApplicationKeyspace() , cluster, consistencyLevelPolicy, ON_FAIL_TRY_ALL_AVAILABLE, accessMap ); final int flushSize = getIntValue( properties, "cassandra.mutation.flushsize", 2000 ); CountingMutator.MAX_SIZE = flushSize; } public static String getApplicationKeyspace() { return applicationKeyspace; } public Cluster getCluster() { return cluster; } public void setCluster( Cluster cluster ) { this.cluster = cluster; } public CassandraHostConfigurator getCassandraHostConfigurator() { return chc; } public void setCassandraHostConfigurator( CassandraHostConfigurator chc ) { this.chc = chc; } public Properties getProperties() { return properties; } public void setProperties( Properties properties ) { this.properties = properties; } public Map<String, String> getPropertiesMap() { if ( properties != null ) { return asMap( properties ); } return null; } public LockManager getLockManager() { return lockManager; } public void setLockManager( LockManager lockManager ) { this.lockManager = lockManager; } public ConsistencyLevelPolicy getConsistencyLevelPolicy() { return consistencyLevelPolicy; } public void setConsistencyLevelPolicy( ConsistencyLevelPolicy consistencyLevelPolicy ) { this.consistencyLevelPolicy = consistencyLevelPolicy; } /** @return keyspace for application UUID */ public static String keyspaceForApplication( UUID applicationId ) { return getApplicationKeyspace(); } public static UUID prefixForApplication( UUID applicationId ) { return applicationId; } public Keyspace getKeyspace( String keyspace, UUID prefix ) { Keyspace ko = null; if ( ( prefix != null ) ) { ko = createVirtualKeyspace( keyspace, prefix, ue, cluster, consistencyLevelPolicy, ON_FAIL_TRY_ALL_AVAILABLE, accessMap ); } else { ko = HFactory.createKeyspace( keyspace, cluster, consistencyLevelPolicy, ON_FAIL_TRY_ALL_AVAILABLE, accessMap ); } return ko; } public Keyspace getApplicationKeyspace( UUID applicationId ) { assert applicationId != null; Keyspace ko = getKeyspace( keyspaceForApplication( applicationId ), prefixForApplication( applicationId ) ); return ko; } /** The Usergrid_Applications keyspace directly */ public Keyspace getUsergridApplicationKeyspace() { return getKeyspace( getApplicationKeyspace(), null ); } public boolean checkKeyspacesExist() { boolean exists = false; try { exists = cluster.describeKeyspace( getApplicationKeyspace() ) != null; } catch ( Exception ex ) { logger.error( "could not describe keyspaces", ex ); } return exists; } /** * Lazy creates a column family in the keyspace. If it doesn't exist, it will be created, then the call will sleep * until all nodes have acknowledged the schema change */ public void createColumnFamily( String keyspace, ColumnFamilyDefinition cfDef ) { if ( !keySpaceExists( keyspace ) ) { createKeySpace( keyspace ); } //add the cf if ( !cfExists( keyspace, cfDef.getName() ) ) { //default read repair chance to 0.1 cfDef.setReadRepairChance( 0.1d ); cfDef.setCompactionStrategy( "LeveledCompactionStrategy" ); cfDef.setCompactionStrategyOptions( new MapUtils.HashMapBuilder().map("sstable_size_in_mb", "512" ) ); cluster.addColumnFamily( cfDef, true ); logger.info( "Created column family {} in keyspace {}", cfDef.getName(), keyspace ); } } /** Create the column families in the list */ public void createColumnFamilies( String keyspace, List<ColumnFamilyDefinition> cfDefs ) { for ( ColumnFamilyDefinition cfDef : cfDefs ) { createColumnFamily( keyspace, cfDef ); } } /** Check if the keyspace exsts */ public boolean keySpaceExists( String keyspace ) { KeyspaceDefinition ksDef = cluster.describeKeyspace( keyspace ); return ksDef != null; } /** Create the keyspace */ private void createKeySpace( String keyspace ) { logger.info( "Creating keyspace: {}", keyspace ); String strategy_class = getString( properties, "cassandra.keyspace.strategy", "org.apache.cassandra.locator.SimpleStrategy" ); logger.info( "Using strategy: {}", strategy_class ); int replication_factor = getIntValue( properties, "cassandra.keyspace.replication", 1 ); logger.info( "Using replication (may be overriden by strategy options): {}", replication_factor ); // try { ThriftKsDef ks_def = ( ThriftKsDef ) HFactory .createKeyspaceDefinition( keyspace, strategy_class, replication_factor, new ArrayList<ColumnFamilyDefinition>() ); @SuppressWarnings({ "unchecked", "rawtypes" }) Map<String, String> strategy_options = filter( ( Map ) properties, "cassandra.keyspace.strategy.options.", true ); if ( strategy_options.size() > 0 ) { logger.info( "Strategy options: {}", mapToFormattedJsonString( strategy_options ) ); ks_def.setStrategyOptions( strategy_options ); } cluster.addKeyspace( ks_def ); waitForCreation( keyspace ); logger.info( "Created keyspace {}", keyspace ); } /** Wait until all nodes agree on the same schema version */ private void waitForCreation( String keyspace ) { while ( true ) { Map<String, List<String>> versions = cluster.describeSchemaVersions(); // only 1 version, return if ( versions != null && versions.size() == 1 ) { return; } // sleep and try again try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { } } } /** Return true if the column family exists */ public boolean cfExists( String keyspace, String cfName ) { KeyspaceDefinition ksDef = cluster.describeKeyspace( keyspace ); if ( ksDef == null ) { return false; } for ( ColumnFamilyDefinition cf : ksDef.getCfDefs() ) { if ( cfName.equals( cf.getName() ) ) { return true; } } return false; } /** * Gets the columns. * * @param ko the keyspace * @param columnFamily the column family * @param key the key * * @return columns * * @throws Exception the exception */ public <N, V> List<HColumn<N, V>> getAllColumns( Keyspace ko, Object columnFamily, Object key, Serializer<N> nameSerializer, Serializer<V> valueSerializer ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "getColumns cf={} key={}", columnFamily, key ); } SliceQuery<ByteBuffer, N, V> q = createSliceQuery( ko, be, nameSerializer, valueSerializer ); q.setColumnFamily( columnFamily.toString() ); q.setKey( bytebuffer( key ) ); q.setRange( null, null, false, ALL_COUNT ); QueryResult<ColumnSlice<N, V>> r = q.execute(); ColumnSlice<N, V> slice = r.get(); List<HColumn<N, V>> results = slice.getColumns(); if ( db_logger.isTraceEnabled() ) { if ( results == null ) { db_logger.trace( "getColumns returned null" ); } else { db_logger.trace( "getColumns returned {} columns", results.size() ); } } return results; } public List<HColumn<String, ByteBuffer>> getAllColumns( Keyspace ko, Object columnFamily, Object key ) throws Exception { return getAllColumns( ko, columnFamily, key, se, be ); } public Set<String> getAllColumnNames( Keyspace ko, Object columnFamily, Object key ) throws Exception { List<HColumn<String, ByteBuffer>> columns = getAllColumns( ko, columnFamily, key ); Set<String> set = new LinkedHashSet<String>(); for ( HColumn<String, ByteBuffer> column : columns ) { set.add( column.getName() ); } return set; } /** * Gets the columns. * * @param ko the keyspace * @param columnFamily the column family * @param key the key * @param start the start * @param finish the finish * @param count the count * @param reversed the reversed * * @return columns * * @throws Exception the exception */ public List<HColumn<ByteBuffer, ByteBuffer>> getColumns( Keyspace ko, Object columnFamily, Object key, Object start, Object finish, int count, boolean reversed ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.debug( "getColumns cf=" + columnFamily + " key=" + key + " start=" + start + " finish=" + finish + " count=" + count + " reversed=" + reversed ); } SliceQuery<ByteBuffer, ByteBuffer, ByteBuffer> q = createSliceQuery( ko, be, be, be ); q.setColumnFamily( columnFamily.toString() ); q.setKey( bytebuffer( key ) ); ByteBuffer start_bytes = null; if ( start instanceof DynamicComposite ) { start_bytes = ( ( DynamicComposite ) start ).serialize(); } else if ( start instanceof List ) { start_bytes = DynamicComposite.toByteBuffer( ( List<?> ) start ); } else { start_bytes = bytebuffer( start ); } ByteBuffer finish_bytes = null; if ( finish instanceof DynamicComposite ) { finish_bytes = ( ( DynamicComposite ) finish ).serialize(); } else if ( finish instanceof List ) { finish_bytes = DynamicComposite.toByteBuffer( ( List<?> ) finish ); } else { finish_bytes = bytebuffer( finish ); } /* * if (reversed) { q.setRange(finish_bytes, start_bytes, reversed, count); } * else { q.setRange(start_bytes, finish_bytes, reversed, count); } */ q.setRange( start_bytes, finish_bytes, reversed, count ); QueryResult<ColumnSlice<ByteBuffer, ByteBuffer>> r = q.execute(); ColumnSlice<ByteBuffer, ByteBuffer> slice = r.get(); List<HColumn<ByteBuffer, ByteBuffer>> results = slice.getColumns(); if ( db_logger.isTraceEnabled() ) { if ( results == null ) { db_logger.trace("getColumns returned null"); } else { db_logger.trace("getColumns returned {} columns", results.size()); } } return results; } /** * Gets the columns. * * @param ko the keyspace * @param columnFamily the column family * @param key the key * @param columnNames the column names * * @return columns * * @throws Exception the exception */ @SuppressWarnings("unchecked") public <N, V> List<HColumn<N, V>> getColumns( Keyspace ko, Object columnFamily, Object key, Set<String> columnNames, Serializer<N> nameSerializer, Serializer<V> valueSerializer ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "getColumns cf={} key={} names={}", columnFamily, key, columnNames ); } SliceQuery<ByteBuffer, N, V> q = createSliceQuery( ko, be, nameSerializer, valueSerializer ); q.setColumnFamily( columnFamily.toString() ); q.setKey( bytebuffer( key ) ); // q.setColumnNames(columnNames.toArray(new String[0])); q.setColumnNames( ( N[] ) nameSerializer.fromBytesSet( se.toBytesSet( new ArrayList<String>( columnNames ) ) ) .toArray() ); QueryResult<ColumnSlice<N, V>> r = q.execute(); ColumnSlice<N, V> slice = r.get(); List<HColumn<N, V>> results = slice.getColumns(); if ( db_logger.isTraceEnabled() ) { if ( results == null ) { db_logger.trace( "getColumns returned null" ); } else { db_logger.trace( "getColumns returned {} columns", results.size()); } } return results; } /** * Gets the column. * * @param ko the keyspace * @param columnFamily the column family * @param key the key * @param column the column * * @return column * * @throws Exception the exception */ public <N, V> HColumn<N, V> getColumn( Keyspace ko, Object columnFamily, Object key, N column, Serializer<N> nameSerializer, Serializer<V> valueSerializer ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "getColumn cf={} key={} column={}", columnFamily, key, column ); } /* * ByteBuffer column_bytes = null; if (column instanceof List) { * column_bytes = Composite.serializeToByteBuffer((List<?>) column); } else * { column_bytes = bytebuffer(column); } */ ColumnQuery<ByteBuffer, N, V> q = HFactory.createColumnQuery( ko, be, nameSerializer, valueSerializer ); QueryResult<HColumn<N, V>> r = q.setKey( bytebuffer( key ) ).setName( column ).setColumnFamily( columnFamily.toString() ).execute(); HColumn<N, V> result = r.get(); if ( db_logger.isTraceEnabled() ) { if ( result == null ) { db_logger.trace( "getColumn returned null" ); } } return result; } public <N, V> ColumnSlice<N, V> getColumns( Keyspace ko, Object columnFamily, Object key, N[] columns, Serializer<N> nameSerializer, Serializer<V> valueSerializer ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "getColumn cf={} key={} column={}", columnFamily, key, columns ); } /* * ByteBuffer column_bytes = null; if (column instanceof List) { * column_bytes = Composite.serializeToByteBuffer((List<?>) column); } else * { column_bytes = bytebuffer(column); } */ SliceQuery<ByteBuffer, N, V> q = HFactory.createSliceQuery( ko, be, nameSerializer, valueSerializer ); QueryResult<ColumnSlice<N, V>> r = q.setKey( bytebuffer( key ) ).setColumnNames( columns ).setColumnFamily( columnFamily.toString() ) .execute(); ColumnSlice<N, V> result = r.get(); if ( db_logger.isTraceEnabled() ) { if ( result == null ) { db_logger.trace( "getColumn returned null" ); } } return result; } public void setColumn( Keyspace ko, Object columnFamily, Object key, Object columnName, Object columnValue, int ttl ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "setColumn cf={} key={} name={} value={}", columnFamily, key, columnName, columnValue ); } ByteBuffer name_bytes = null; if ( columnName instanceof List ) { name_bytes = DynamicComposite.toByteBuffer( ( List<?> ) columnName ); } else { name_bytes = bytebuffer( columnName ); } ByteBuffer value_bytes = null; if ( columnValue instanceof List ) { value_bytes = DynamicComposite.toByteBuffer( ( List<?> ) columnValue ); } else { value_bytes = bytebuffer( columnValue ); } HColumn<ByteBuffer, ByteBuffer> col = createColumn( name_bytes, value_bytes, be, be ); if ( ttl != 0 ) { col.setTtl( ttl ); } Mutator<ByteBuffer> m = CountingMutator.createFlushingMutator( ko, be ); m.insert( bytebuffer( key ), columnFamily.toString(), col ); } public void setColumns( Keyspace ko, Object columnFamily, byte[] key, Map<?, ?> map, int ttl ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "setColumns cf={} key={} map={} ttl={}", columnFamily, key, map, ttl); } Mutator<ByteBuffer> m = CountingMutator.createFlushingMutator( ko, be ); long timestamp = createTimestamp(); for ( Object name : map.keySet() ) { Object value = map.get( name ); if ( value != null ) { ByteBuffer name_bytes = null; if ( name instanceof List ) { name_bytes = DynamicComposite.toByteBuffer( ( List<?> ) name ); } else { name_bytes = bytebuffer( name ); } ByteBuffer value_bytes = null; if ( value instanceof List ) { value_bytes = DynamicComposite.toByteBuffer( ( List<?> ) value ); } else { value_bytes = bytebuffer( value ); } HColumn<ByteBuffer, ByteBuffer> col = createColumn( name_bytes, value_bytes, timestamp, be, be ); if ( ttl != 0 ) { col.setTtl( ttl ); } m.addInsertion( bytebuffer( key ), columnFamily.toString(), createColumn( name_bytes, value_bytes, timestamp, be, be ) ); } } batchExecute( m, CassandraService.RETRY_COUNT ); } /** * Create a timestamp based on the TimeResolution set to the cluster. * * @return a timestamp */ public long createTimestamp() { return chc.getClockResolution().createClock(); } /** * Delete row. * * @param ko the keyspace * @param columnFamily the column family * @param key the key * * @throws Exception the exception */ public void deleteRow( Keyspace ko, final Object columnFamily, final Object key ) throws Exception { if ( db_logger.isTraceEnabled() ) { db_logger.trace( "deleteRow cf={} key={}", columnFamily, key ); } CountingMutator.createFlushingMutator( ko, be ).addDeletion( bytebuffer( key ), columnFamily.toString() ).execute(); } public void destroy() throws Exception { if (cluster != null) { HConnectionManager connectionManager = cluster.getConnectionManager(); if (connectionManager != null) { connectionManager.shutdown(); } } cluster = null; } }
3e08d03e3be3ea86aaba9d239ead20c38c5a3471
5,748
java
Java
web/gui/src/test/java/org/onosproject/ui/impl/lion/LionConfigTest.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
web/gui/src/test/java/org/onosproject/ui/impl/lion/LionConfigTest.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
web/gui/src/test/java/org/onosproject/ui/impl/lion/LionConfigTest.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
32.292135
81
0.613605
3,736
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onosproject.ui.impl.lion; import org.junit.Test; import org.onosproject.ui.AbstractUiTest; import java.util.regex.Matcher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Unit tests for {@link LionConfig}. */ public class LionConfigTest extends AbstractUiTest { private static final String ROOT = "/org/onosproject/ui/lion/"; private static final String CMD_ROOT = ROOT + "_cmd/"; private static final String CONFIG_ROOT = ROOT + "_config/"; private static final String SUFFIX = ".lioncfg"; private static final String CARD_GAME_1 = CONFIG_ROOT + "CardGame1" + SUFFIX; private LionConfig cfg; private LionConfig.CmdFrom from; private String cmdPath(String name) { return CMD_ROOT + name + SUFFIX; } private String configPath(String name) { return CONFIG_ROOT + name + SUFFIX; } private LionConfig cfg() { return new LionConfig(); } private void verifyStats(String expId, int expAliases, int expFroms) { assertEquals("wrong bundle ID", expId, cfg.id()); assertEquals("wrong alias count", expAliases, cfg.aliasCount()); assertEquals("wrong from count", expFroms, cfg.fromCount()); } private void verifyKeys(String res, String... keys) { int nkeys = keys.length; for (String k: keys) { assertEquals("key not found: " + k, true, cfg.fromContains(res, k)); } assertEquals("wrong key count", nkeys, cfg.fromKeyCount(res)); } @Test public void importMatch() { title("importMatch"); String fromParams = "cs.rank import *"; Matcher m = LionConfig.RE_IMPORT.matcher(fromParams); assertEquals("no match", true, m.matches()); assertEquals("bad group 1", "cs.rank", m.group(1)); assertEquals("bad group 2", "*", m.group(2)); } @Test public void basic() { title("basic"); cfg = cfg().load(CARD_GAME_1); print(cfg); verifyStats("CardGame1", 1, 3); } @Test public void cmd01GoodBundle() { title("cmd01GoodBundle"); cfg = cfg().load(cmdPath("01-bundle")); verifyStats("foo.bar", 0, 0); assertEquals("wrong ID", "foo.bar", cfg.id()); } @Test public void cmd02GoodAlias() { title("cmd02GoodAlias"); cfg = cfg().load(cmdPath("02-alias")); verifyStats(null, 1, 0); assertEquals("alias/subst not found", "xyzzy.wizard", cfg.alias("xy")); } @Test public void cmd03GoodFrom() { title("cmd03GoodFrom"); cfg = cfg().load(cmdPath("03-from")); verifyStats(null, 0, 1); assertEquals("from/keys bad count", 0, cfg.fromKeyCount("non.exist")); assertEquals("from/keys bad count", 1, cfg.fromKeyCount("foo.bar")); assertEquals("from/keys not found", true, cfg.fromContains("foo.bar", "fizzbuzz")); from = cfg.entries().iterator().next(); assertFalse("expected no star", from.starred()); } @Test public void cmd04GoodFromFour() { title("cmd04GoodFromFour"); cfg = cfg().load(cmdPath("04-from-four")); assertEquals("from/keys bad count", 4, cfg.fromKeyCount("hooray")); verifyKeys("hooray", "ford", "arthur", "joe", "henry"); } @Test public void cmd05FromExpand() { title("cmd05FromExpand"); cfg = cfg().load(cmdPath("05-from-expand")); assertEquals("no expand 1", 0, cfg.fromKeyCount("xy.spell")); assertEquals("no expand 2", 0, cfg.fromKeyCount("xy.learn")); verifyKeys("xyzzy.wizard.spell", "zonk", "zip", "zuffer"); verifyKeys("xyzzy.wizard.learn", "zap", "zigzag"); } @Test public void cmd06FromStar() { title("cmd06FromStar"); cfg = cfg().load(cmdPath("06-from-star")); print(cfg); assertEquals("bad from count", 1, cfg.fromCount()); from = cfg.entries().iterator().next(); assertTrue("expected a star", from.starred()); } @Test public void cmd07StarIsSpecial() { title("cmd06StarIsSpecial"); cfg = cfg().load(cmdPath("07-star-is-special")); print(cfg); assertEquals("no error detected", 3, cfg.errorCount()); int iBad = 0; for (String line: cfg.errorLines()) { print(line); iBad++; String prefix = "from star.bad" + iBad + " import "; assertTrue("unexpected bad line", line.startsWith(prefix)); } } @Test public void cardGameConfig() { title("cardGameConfig"); cfg = cfg().load(configPath("CardGame1")); assertEquals("wrong id", "CardGame1", cfg.id()); assertEquals("wrong alias count", 1, cfg.aliasCount()); assertEquals("wrong from count", 3, cfg.fromCount()); verifyKeys("app.Cards", "*"); verifyKeys("core.stuff.Rank", "ten", "jack", "queen", "king", "ace"); verifyKeys("core.stuff.Suit", "spades", "clubs"); } }
3e08d15b1bfc6af0a74adf76c74a18e53a953816
15,236
java
Java
services/evs/src/main/java/com/huaweicloud/sdk/evs/v2/model/CreateVolumeOption.java
huaweicloud/huaweicloud-sdk-java-v3
a01cd21a3d03f6dffc807bea7c522e34adfa368d
[ "Apache-2.0" ]
50
2020-05-18T11:35:20.000Z
2022-03-15T02:07:05.000Z
services/evs/src/main/java/com/huaweicloud/sdk/evs/v2/model/CreateVolumeOption.java
huaweicloud/huaweicloud-sdk-java-v3
a01cd21a3d03f6dffc807bea7c522e34adfa368d
[ "Apache-2.0" ]
45
2020-07-06T03:34:12.000Z
2022-03-31T09:41:54.000Z
services/evs/src/main/java/com/huaweicloud/sdk/evs/v2/model/CreateVolumeOption.java
huaweicloud/huaweicloud-sdk-java-v3
a01cd21a3d03f6dffc807bea7c522e34adfa368d
[ "Apache-2.0" ]
27
2020-05-28T11:08:44.000Z
2022-03-30T03:30:37.000Z
31.349794
140
0.636847
3,737
package com.huaweicloud.sdk.evs.v2.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; /** 创建云硬盘的信息。 */ public class CreateVolumeOption { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "availability_zone") private String availabilityZone; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "backup_id") private String backupId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "count") private Integer count; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "description") private String description; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "enterprise_project_id") private String enterpriseProjectId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "imageRef") private String imageRef; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "metadata") private Map<String, String> metadata = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "multiattach") private Boolean multiattach; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "name") private String name; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "size") private Integer size; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "snapshot_id") private String snapshotId; /** 云硬盘类型。 目前支持“SSD”,“GPSSD”,“SAS”三种 “SSD”为超高IO云硬盘 \"GPSSD\"为通用型SSD云硬盘 “SAS”为高IO云硬盘 * 当指定的云硬盘类型在avaliability_zone内不存在时,则创建云硬盘失败。 说明: 从快照创建云硬盘时,volume_type字段必须和快照源云硬盘保持一致。 了解不同磁盘类型的详细信息,请参见 * [磁盘类型及性能介绍](https://support.huaweicloud.com/productdesc-evs/zh-cn_topic_0044524691.html)。 * 获取region可用的卷类型,请参见[查询云硬盘类型列表](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=EVS&api=CinderListVolumeTypes) */ public static final class VolumeTypeEnum { /** Enum SSD for value: "SSD" */ public static final VolumeTypeEnum SSD = new VolumeTypeEnum("SSD"); /** Enum GPSSD for value: "GPSSD" */ public static final VolumeTypeEnum GPSSD = new VolumeTypeEnum("GPSSD"); /** Enum SAS for value: "SAS" */ public static final VolumeTypeEnum SAS = new VolumeTypeEnum("SAS"); /** Enum SATA for value: "SATA" */ public static final VolumeTypeEnum SATA = new VolumeTypeEnum("SATA"); private static final Map<String, VolumeTypeEnum> STATIC_FIELDS = createStaticFields(); private static Map<String, VolumeTypeEnum> createStaticFields() { Map<String, VolumeTypeEnum> map = new HashMap<>(); map.put("SSD", SSD); map.put("GPSSD", GPSSD); map.put("SAS", SAS); map.put("SATA", SATA); return Collections.unmodifiableMap(map); } private String value; VolumeTypeEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static VolumeTypeEnum fromValue(String value) { if (value == null) { return null; } VolumeTypeEnum result = STATIC_FIELDS.get(value); if (result == null) { result = new VolumeTypeEnum(value); } return result; } public static VolumeTypeEnum valueOf(String value) { if (value == null) { return null; } VolumeTypeEnum result = STATIC_FIELDS.get(value); if (result != null) { return result; } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } @Override public boolean equals(Object obj) { if (obj instanceof VolumeTypeEnum) { return this.value.equals(((VolumeTypeEnum) obj).value); } return false; } @Override public int hashCode() { return this.value.hashCode(); } } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "volume_type") private VolumeTypeEnum volumeType; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "tags") private Map<String, String> tags = null; public CreateVolumeOption withAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; return this; } /** 指定要创建云硬盘的可用区。 * 获取方法请参见\"[获取可用区](https://apiexplorer.developer.huaweicloud.com/apiexplorer/sdk?product=EVS&api=CinderListAvailabilityZones)\"。 * * @return availabilityZone */ public String getAvailabilityZone() { return availabilityZone; } public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } public CreateVolumeOption withBackupId(String backupId) { this.backupId = backupId; return this; } /** 备份ID,从备份创建云硬盘时为必选。 * * @return backupId */ public String getBackupId() { return backupId; } public void setBackupId(String backupId) { this.backupId = backupId; } public CreateVolumeOption withCount(Integer count) { this.count = count; return this; } /** 批量创云硬盘的个数。如果无该参数,表明只创建1个云硬盘,目前最多支持批量创建100个。 从备份创建云硬盘时,不支持批量创建,数量只能为“1”。 如果发送请求时,将参数值设置为小数,则默认取小数点前的整数。 * * @return count */ public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public CreateVolumeOption withDescription(String description) { this.description = description; return this; } /** 云硬盘的描述。最大支持255个字节。 * * @return description */ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public CreateVolumeOption withEnterpriseProjectId(String enterpriseProjectId) { this.enterpriseProjectId = enterpriseProjectId; return this; } /** 企业项目ID。创建云硬盘时,给云硬盘绑定企业项目ID。 * * @return enterpriseProjectId */ public String getEnterpriseProjectId() { return enterpriseProjectId; } public void setEnterpriseProjectId(String enterpriseProjectId) { this.enterpriseProjectId = enterpriseProjectId; } public CreateVolumeOption withImageRef(String imageRef) { this.imageRef = imageRef; return this; } /** 镜像ID,指定该参数表示创建云硬盘方式为从镜像创建云硬盘。 * * @return imageRef */ public String getImageRef() { return imageRef; } public void setImageRef(String imageRef) { this.imageRef = imageRef; } public CreateVolumeOption withMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } public CreateVolumeOption putMetadataItem(String key, String metadataItem) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, metadataItem); return this; } public CreateVolumeOption withMetadata(Consumer<Map<String, String>> metadataSetter) { if (this.metadata == null) { this.metadata = new HashMap<>(); } metadataSetter.accept(this.metadata); return this; } /** 创建云硬盘的metadata信息 可选参数如下: [\\_\\_system\\_\\_cmkid] * metadata中的加密cmkid字段,与\\_\\_system\\_\\_encrypted配合表示需要加密,cmkid长度固定为36个字节。 > 说明: > > * 请求获取密钥ID的方法请参考:\"[查询密钥列表](https://support.huaweicloud.com/api-dew/dew_02_0017.html)\"。 * [\\_\\_system\\_\\_encrypted] metadata中的表示加密功能的字段,0代表不加密,1代表加密。不指定该字段时,云硬盘的加密属性与数据源保持一致,如果不是从数据源创建的场景,则默认不加密。 * [full_clone] 从快照创建云硬盘时,如需使用link克隆方式,请指定该字段的值为0。 [hw:passthrough] * * true表示云硬盘的设备类型为SCSI类型,即允许ECS操作系统直接访问底层存储介质。支持SCSI锁命令。 * false表示云硬盘的设备类型为VBD (虚拟块存储设备 , Virtual Block * Device)类型,即为默认类型,VBD只能支持简单的SCSI读写命令。 * 该字段不存在时,云硬盘默认为VBD类型。 * * @return metadata */ public Map<String, String> getMetadata() { return metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public CreateVolumeOption withMultiattach(Boolean multiattach) { this.multiattach = multiattach; return this; } /** 是否为共享云硬盘。true为共享盘,false为普通云硬盘。 * * @return multiattach */ public Boolean getMultiattach() { return multiattach; } public void setMultiattach(Boolean multiattach) { this.multiattach = multiattach; } public CreateVolumeOption withName(String name) { this.name = name; return this; } /** 云硬盘名称。 如果为创建单个云硬盘,name为云硬盘名称。最大支持255个字节。 * 创建的云硬盘数量(count字段对应的值)大于1时,为区分不同云硬盘,创建过程中系统会自动在名称后加“-0000”的类似标记。例如:volume-0001、volume-0002。最大支持250个字节。 * * @return name */ public String getName() { return name; } public void setName(String name) { this.name = name; } public CreateVolumeOption withSize(Integer size) { this.size = size; return this; } /** 云硬盘大小,单位为GB,其限制如下: 系统盘:1GB-1024GB 数据盘:10GB-32768GB 创建空白云硬盘和从 镜像/快照 创建云硬盘时,size为必选,且云硬盘大小不能小于 镜像/快照 大小。 * 从备份创建云硬盘时,size为可选,不指定size时,云硬盘大小和备份大小一致。 * * @return size */ public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public CreateVolumeOption withSnapshotId(String snapshotId) { this.snapshotId = snapshotId; return this; } /** 快照ID,指定该参数表示创建云硬盘方式为从快照创建云硬盘 * * @return snapshotId */ public String getSnapshotId() { return snapshotId; } public void setSnapshotId(String snapshotId) { this.snapshotId = snapshotId; } public CreateVolumeOption withVolumeType(VolumeTypeEnum volumeType) { this.volumeType = volumeType; return this; } /** 云硬盘类型。 目前支持“SSD”,“GPSSD”,“SAS”三种 “SSD”为超高IO云硬盘 \"GPSSD\"为通用型SSD云硬盘 “SAS”为高IO云硬盘 * 当指定的云硬盘类型在avaliability_zone内不存在时,则创建云硬盘失败。 说明: 从快照创建云硬盘时,volume_type字段必须和快照源云硬盘保持一致。 了解不同磁盘类型的详细信息,请参见 * [磁盘类型及性能介绍](https://support.huaweicloud.com/productdesc-evs/zh-cn_topic_0044524691.html)。 * 获取region可用的卷类型,请参见[查询云硬盘类型列表](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=EVS&api=CinderListVolumeTypes) * * @return volumeType */ public VolumeTypeEnum getVolumeType() { return volumeType; } public void setVolumeType(VolumeTypeEnum volumeType) { this.volumeType = volumeType; } public CreateVolumeOption withTags(Map<String, String> tags) { this.tags = tags; return this; } public CreateVolumeOption putTagsItem(String key, String tagsItem) { if (this.tags == null) { this.tags = new HashMap<>(); } this.tags.put(key, tagsItem); return this; } public CreateVolumeOption withTags(Consumer<Map<String, String>> tagsSetter) { if (this.tags == null) { this.tags = new HashMap<>(); } tagsSetter.accept(this.tags); return this; } /** 云硬盘标签信息。 * * @return tags */ public Map<String, String> getTags() { return tags; } public void setTags(Map<String, String> tags) { this.tags = tags; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateVolumeOption createVolumeOption = (CreateVolumeOption) o; return Objects.equals(this.availabilityZone, createVolumeOption.availabilityZone) && Objects.equals(this.backupId, createVolumeOption.backupId) && Objects.equals(this.count, createVolumeOption.count) && Objects.equals(this.description, createVolumeOption.description) && Objects.equals(this.enterpriseProjectId, createVolumeOption.enterpriseProjectId) && Objects.equals(this.imageRef, createVolumeOption.imageRef) && Objects.equals(this.metadata, createVolumeOption.metadata) && Objects.equals(this.multiattach, createVolumeOption.multiattach) && Objects.equals(this.name, createVolumeOption.name) && Objects.equals(this.size, createVolumeOption.size) && Objects.equals(this.snapshotId, createVolumeOption.snapshotId) && Objects.equals(this.volumeType, createVolumeOption.volumeType) && Objects.equals(this.tags, createVolumeOption.tags); } @Override public int hashCode() { return Objects.hash(availabilityZone, backupId, count, description, enterpriseProjectId, imageRef, metadata, multiattach, name, size, snapshotId, volumeType, tags); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateVolumeOption {\n"); sb.append(" availabilityZone: ").append(toIndentedString(availabilityZone)).append("\n"); sb.append(" backupId: ").append(toIndentedString(backupId)).append("\n"); sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" enterpriseProjectId: ").append(toIndentedString(enterpriseProjectId)).append("\n"); sb.append(" imageRef: ").append(toIndentedString(imageRef)).append("\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append(" multiattach: ").append(toIndentedString(multiattach)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" size: ").append(toIndentedString(size)).append("\n"); sb.append(" snapshotId: ").append(toIndentedString(snapshotId)).append("\n"); sb.append(" volumeType: ").append(toIndentedString(volumeType)).append("\n"); sb.append(" tags: ").append(toIndentedString(tags)).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 "); } }
3e08d1de9e192e55b6629837aa0f53b8f4a8f4c1
12,691
java
Java
turms-client-kotlin/src/main/java/im/turms/client/model/proto/request/group/enrollment/CreateGroupJoinRequestRequest.java
warmchang/turms
b1ef2d262ea4cad45b5e2e178fc4cb5868d8e8c9
[ "Apache-2.0" ]
null
null
null
turms-client-kotlin/src/main/java/im/turms/client/model/proto/request/group/enrollment/CreateGroupJoinRequestRequest.java
warmchang/turms
b1ef2d262ea4cad45b5e2e178fc4cb5868d8e8c9
[ "Apache-2.0" ]
null
null
null
turms-client-kotlin/src/main/java/im/turms/client/model/proto/request/group/enrollment/CreateGroupJoinRequestRequest.java
warmchang/turms
b1ef2d262ea4cad45b5e2e178fc4cb5868d8e8c9
[ "Apache-2.0" ]
null
null
null
35.749296
144
0.708297
3,738
/* * Copyright (C) 2019 The Turms Project * https://github.com/turms-im/turms * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: request/group/enrollment/create_group_join_request_request.proto package im.turms.client.model.proto.request.group.enrollment; /** * Protobuf type {@code im.turms.proto.CreateGroupJoinRequestRequest} */ public final class CreateGroupJoinRequestRequest extends com.google.protobuf.GeneratedMessageLite< CreateGroupJoinRequestRequest, CreateGroupJoinRequestRequest.Builder> implements // @@protoc_insertion_point(message_implements:im.turms.proto.CreateGroupJoinRequestRequest) CreateGroupJoinRequestRequestOrBuilder { private CreateGroupJoinRequestRequest() { content_ = ""; } public static final int GROUP_ID_FIELD_NUMBER = 1; private long groupId_; /** * <code>int64 group_id = 1;</code> * @return The groupId. */ @java.lang.Override public long getGroupId() { return groupId_; } /** * <code>int64 group_id = 1;</code> * @param value The groupId to set. */ private void setGroupId(long value) { groupId_ = value; } /** * <code>int64 group_id = 1;</code> */ private void clearGroupId() { groupId_ = 0L; } public static final int CONTENT_FIELD_NUMBER = 2; private java.lang.String content_; /** * <code>string content = 2;</code> * @return The content. */ @java.lang.Override public java.lang.String getContent() { return content_; } /** * <code>string content = 2;</code> * @return The bytes for content. */ @java.lang.Override public com.google.protobuf.ByteString getContentBytes() { return com.google.protobuf.ByteString.copyFromUtf8(content_); } /** * <code>string content = 2;</code> * @param value The content to set. */ private void setContent( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); content_ = value; } /** * <code>string content = 2;</code> */ private void clearContent() { content_ = getDefaultInstance().getContent(); } /** * <code>string content = 2;</code> * @param value The bytes for content to set. */ private void setContentBytes( com.google.protobuf.ByteString value) { checkByteStringIsUtf8(value); content_ = value.toStringUtf8(); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code im.turms.proto.CreateGroupJoinRequestRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest, Builder> implements // @@protoc_insertion_point(builder_implements:im.turms.proto.CreateGroupJoinRequestRequest) im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequestOrBuilder { // Construct using im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>int64 group_id = 1;</code> * @return The groupId. */ @java.lang.Override public long getGroupId() { return instance.getGroupId(); } /** * <code>int64 group_id = 1;</code> * @param value The groupId to set. * @return This builder for chaining. */ public Builder setGroupId(long value) { copyOnWrite(); instance.setGroupId(value); return this; } /** * <code>int64 group_id = 1;</code> * @return This builder for chaining. */ public Builder clearGroupId() { copyOnWrite(); instance.clearGroupId(); return this; } /** * <code>string content = 2;</code> * @return The content. */ @java.lang.Override public java.lang.String getContent() { return instance.getContent(); } /** * <code>string content = 2;</code> * @return The bytes for content. */ @java.lang.Override public com.google.protobuf.ByteString getContentBytes() { return instance.getContentBytes(); } /** * <code>string content = 2;</code> * @param value The content to set. * @return This builder for chaining. */ public Builder setContent( java.lang.String value) { copyOnWrite(); instance.setContent(value); return this; } /** * <code>string content = 2;</code> * @return This builder for chaining. */ public Builder clearContent() { copyOnWrite(); instance.clearContent(); return this; } /** * <code>string content = 2;</code> * @param value The bytes for content to set. * @return This builder for chaining. */ public Builder setContentBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setContentBytes(value); return this; } // @@protoc_insertion_point(builder_scope:im.turms.proto.CreateGroupJoinRequestRequest) } @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "groupId_", "content_", }; java.lang.String info = "\u0000\u0002\u0000\u0000\u0001\u0002\u0002\u0000\u0000\u0000\u0001\u0002\u0002\u0208" + ""; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest> parser = PARSER; if (parser == null) { synchronized (im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return (byte) 1; } case SET_MEMOIZED_IS_INITIALIZED: { return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:im.turms.proto.CreateGroupJoinRequestRequest) private static final im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest DEFAULT_INSTANCE; static { CreateGroupJoinRequestRequest defaultInstance = new CreateGroupJoinRequestRequest(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( CreateGroupJoinRequestRequest.class, defaultInstance); } public static im.turms.client.model.proto.request.group.enrollment.CreateGroupJoinRequestRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<CreateGroupJoinRequestRequest> PARSER; public static com.google.protobuf.Parser<CreateGroupJoinRequestRequest> parser() { return DEFAULT_INSTANCE.getParserForType(); } }
3e08d26e5190bedfe5ed129d45aeafe730d67878
13,751
java
Java
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java
BigDataArtisans/pulsar
f8406177f037b6bf2f06e6d21e1b492b36794169
[ "Apache-2.0" ]
null
null
null
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java
BigDataArtisans/pulsar
f8406177f037b6bf2f06e6d21e1b492b36794169
[ "Apache-2.0" ]
null
null
null
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java
BigDataArtisans/pulsar
f8406177f037b6bf2f06e6d21e1b492b36794169
[ "Apache-2.0" ]
null
null
null
48.762411
111
0.718857
3,739
/** * 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.pulsar.broker.service; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.PulsarClientException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.AutoTopicCreationOverride; import org.apache.pulsar.common.policies.data.TopicType; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BrokerServiceAutoTopicCreationTest extends BrokerTestBase{ @BeforeClass @Override protected void setup() throws Exception { super.baseSetup(); } @AfterClass @Override protected void cleanup() throws Exception { super.internalCleanup(); } @AfterMethod protected void cleanupTest() throws Exception { pulsar.getAdminClient().namespaces().removeAutoTopicCreation("prop/ns-abc"); } @Test public void testAutoNonPartitionedTopicCreation() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("non-partitioned"); final String topicString = "persistent://prop/ns-abc/non-partitioned-topic"; final String subscriptionName = "non-partitioned-topic-sub"; pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); } @Test public void testAutoNonPartitionedTopicCreationOnProduce() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("non-partitioned"); final String topicString = "persistent://prop/ns-abc/non-partitioned-topic-2"; pulsarClient.newProducer().topic(topicString).create(); assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); } @Test public void testAutoPartitionedTopicCreation() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("partitioned"); pulsar.getConfiguration().setDefaultNumPartitions(3); final String topicString = "persistent://prop/ns-abc/partitioned-topic"; final String subscriptionName = "partitioned-topic-sub"; pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); for (int i = 0; i < 3; i++) { assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString + "-partition-" + i)); } } @Test public void testAutoPartitionedTopicCreationOnProduce() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("partitioned"); pulsar.getConfiguration().setDefaultNumPartitions(3); final String topicString = "persistent://prop/ns-abc/partitioned-topic-1"; pulsarClient.newProducer().topic(topicString).create(); assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); for (int i = 0; i < 3; i++) { assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString + "-partition-" + i)); } } @Test public void testAutoTopicCreationDisable() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(false); final String topicString = "persistent://prop/ns-abc/test-topic"; final String subscriptionName = "test-topic-sub"; try { pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); fail("Subscribe operation should have failed"); } catch (Exception e) { assertTrue(e instanceof PulsarClientException); } assertFalse(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); } @Test public void testAutoTopicCreationDisableIfNonPartitionedTopicAlreadyExist() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("partitioned"); pulsar.getConfiguration().setDefaultNumPartitions(3); final String topicString = "persistent://prop/ns-abc/test-topic-2"; final String subscriptionName = "partitioned-topic-sub"; admin.topics().createNonPartitionedTopic(topicString); pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); for (int i = 0; i < 3; i++) { assertFalse(admin.namespaces().getTopics("prop/ns-abc").contains(topicString + "-partition-" + i)); } assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); } /** * CheckAllowAutoCreation's default value is false. * So using getPartitionedTopicMetadata() directly will not produce partitioned topic * even if the option to automatically create partitioned topic is configured */ @Test public void testGetPartitionedMetadataWithoutCheckAllowAutoCreation() throws Exception{ pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("partitioned"); pulsar.getConfiguration().setDefaultNumPartitions(3); final String topicString = "persistent://prop/ns-abc/test-topic-3"; int partitions = admin.topics().getPartitionedTopicMetadata(topicString).partitions; assertEquals(partitions, 0); assertFalse(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); } @Test public void testAutoCreationNamespaceAllowOverridesBroker() throws Exception { final String topicString = "persistent://prop/ns-abc/test-topic-4"; final String subscriptionName = "test-topic-sub-4"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(false); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(true, TopicType.NON_PARTITIONED.toString(), null)); pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); } @Test public void testAutoCreationNamespaceDisallowOverridesBroker() throws Exception { final String topicString = "persistent://prop/ns-abc/test-topic-5"; final String subscriptionName = "test-topic-sub-5"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(false, null, null)); try { pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); fail("Subscribe operation should have failed"); } catch (Exception e) { assertTrue(e instanceof PulsarClientException); } assertFalse(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); } @Test public void testAutoCreationNamespaceOverrideAllowsPartitionedTopics() throws Exception { final String topicString = "persistent://prop/ns-abc/partitioned-test-topic-6"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(false); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(true, TopicType.PARTITIONED.toString(), 4)); final String subscriptionName = "test-topic-sub-6"; pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); for (int i = 0; i < 4; i++) { assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString + "-partition-" + i)); } } @Test public void testAutoCreationNamespaceOverridesTopicTypePartitioned() throws Exception { final String topicString = "persistent://prop/ns-abc/partitioned-test-topic-7"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("non-partitioned"); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(true, TopicType.PARTITIONED.toString(), 3)); final String subscriptionName = "test-topic-sub-7"; pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); for (int i = 0; i < 3; i++) { assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString + "-partition-" + i)); } } @Test public void testAutoCreationNamespaceOverridesTopicTypeNonPartitioned() throws Exception { final String topicString = "persistent://prop/ns-abc/partitioned-test-topic-8"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("partitioned"); pulsar.getConfiguration().setDefaultNumPartitions(2); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(true, TopicType.NON_PARTITIONED.toString(), null)); final String subscriptionName = "test-topic-sub-8"; pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); } @Test public void testAutoCreationNamespaceOverridesDefaultNumPartitions() throws Exception { final String topicString = "persistent://prop/ns-abc/partitioned-test-topic-9"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(true); pulsar.getConfiguration().setAllowAutoTopicCreationType("partitioned"); pulsar.getConfiguration().setDefaultNumPartitions(2); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(true, TopicType.PARTITIONED.toString(), 4)); final String subscriptionName = "test-topic-sub-9"; pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe(); assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); for (int i = 0; i < 4; i++) { assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString + "-partition-" + i)); } } @Test public void testAutoCreationNamespaceAllowOverridesBrokerOnProduce() throws Exception { final String topicString = "persistent://prop/ns-abc/test-topic-10"; final TopicName topicName = TopicName.get(topicString); pulsar.getConfiguration().setAllowAutoTopicCreation(false); pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), new AutoTopicCreationOverride(true, TopicType.NON_PARTITIONED.toString(), null)); pulsarClient.newProducer().topic(topicString).create(); assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString)); assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topicString)); } }
3e08d3194c2dac78a3a18cf523249ad0fb921735
2,005
java
Java
traffic_router/core/src/main/java/org/apache/traffic_control/traffic_router/core/hash/DefaultHashable.java
TaylorCFrey/trafficcontrol
308484ddfb37952901d8b138087d4b8f0c7b007d
[ "Apache-2.0", "BSD-2-Clause", "MIT-0", "MIT", "BSD-3-Clause" ]
598
2018-06-16T02:54:28.000Z
2022-03-31T22:31:25.000Z
traffic_router/core/src/main/java/org/apache/traffic_control/traffic_router/core/hash/DefaultHashable.java
TaylorCFrey/trafficcontrol
308484ddfb37952901d8b138087d4b8f0c7b007d
[ "Apache-2.0", "BSD-2-Clause", "MIT-0", "MIT", "BSD-3-Clause" ]
3,506
2018-06-13T16:39:39.000Z
2022-03-29T18:31:31.000Z
traffic_router/core/src/main/java/org/apache/traffic_control/traffic_router/core/hash/DefaultHashable.java
TaylorCFrey/trafficcontrol
308484ddfb37952901d8b138087d4b8f0c7b007d
[ "Apache-2.0", "BSD-2-Clause", "MIT-0", "MIT", "BSD-3-Clause" ]
360
2018-06-13T20:08:42.000Z
2022-03-31T10:37:47.000Z
27.094595
96
0.706733
3,740
/* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.traffic_control.traffic_router.core.hash; import java.util.Arrays; import java.util.List; import java.util.TreeSet; public class DefaultHashable implements Hashable<DefaultHashable>, Comparable<DefaultHashable> { private Double[] hashes; private int order = 0; @Override public void setOrder(final int order) { this.order = order; } @Override public int getOrder() { return order; } @Override public boolean hasHashes() { return hashes.length > 0 ? true : false; } @Override public double getClosestHash(final double hash) { return hashes[NumberSearcher.findClosest(hashes, hash)]; } @Override public DefaultHashable generateHashes(final String hashId, final int hashCount) { final TreeSet<Double> hashSet = new TreeSet<Double>(); final MD5HashFunction hashFunction = new MD5HashFunction(); for (int i = 0; i < hashCount; i++) { hashSet.add(hashFunction.hash(hashId + "--" + i)); } hashes = new Double[hashSet.size()]; System.arraycopy(hashSet.toArray(),0,hashes,0,hashSet.size()); return this; } @Override public List<Double> getHashValues() { return Arrays.asList(hashes); } @Override public int compareTo(final DefaultHashable o) { if (this.getOrder() < 0 && o.getOrder() < 0) { return getOrder() < o.getOrder() ? 1 : getOrder() > o.getOrder() ? -1 : 0; } else { return getOrder() < o.getOrder() ? -1 : getOrder() > o.getOrder() ? 1 : 0; } } }
3e08d441f031be3ad9d9703f340458997b141a1a
5,670
java
Java
src/main/java/net/kuujo/copycat/impl/DefaultReplica.java
ankurcha/copycat
b82e5c6e519cfc0f309d57f40b3e1a76c3b1292a
[ "Apache-2.0" ]
2
2019-05-22T14:33:24.000Z
2021-10-06T06:06:26.000Z
src/main/java/net/kuujo/copycat/impl/DefaultReplica.java
ankurcha/copycat
b82e5c6e519cfc0f309d57f40b3e1a76c3b1292a
[ "Apache-2.0" ]
null
null
null
src/main/java/net/kuujo/copycat/impl/DefaultReplica.java
ankurcha/copycat
b82e5c6e519cfc0f309d57f40b3e1a76c3b1292a
[ "Apache-2.0" ]
null
null
null
25.088496
124
0.721164
3,741
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kuujo.copycat.impl; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.Future; import org.vertx.java.core.Handler; import org.vertx.java.core.Vertx; import org.vertx.java.core.impl.DefaultFutureResult; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Container; import org.vertx.java.platform.Verticle; import net.kuujo.copycat.ClusterConfig; import net.kuujo.copycat.Replica; import net.kuujo.copycat.StateMachine; import net.kuujo.copycat.log.AsyncLog; import net.kuujo.copycat.log.Log; import net.kuujo.copycat.state.StateContext; import net.kuujo.copycat.state.StateType; /** * A default replica implementation. * * @author Jordan Halterman */ public class DefaultReplica implements Replica { private final StateContext context; public DefaultReplica(String address, Verticle verticle, StateMachine stateMachine) { this(address, verticle.getVertx(), verticle.getContainer(), stateMachine); } public DefaultReplica(String address, Vertx vertx, Container container, StateMachine stateMachine) { context = new StateContext(address, vertx, container, new DefaultStateMachineExecutor(stateMachine)); } public DefaultReplica(String address, Verticle verticle, StateMachine stateMachine, ClusterConfig config) { this(address, verticle, stateMachine); context.configure(config); } public DefaultReplica(String address, Vertx vertx, Container container, StateMachine stateMachine, ClusterConfig config) { this(address, vertx, container, stateMachine); context.configure(config); } @Override public String address() { return context.address(); } @Override public ClusterConfig config() { return context.config(); } @Override public Replica setLogType(Log.Type type) { context.log().setLogType(type); return this; } @Override public Log.Type getLogType() { return context.log().getLogType(); } @Override public Replica setLogFile(String filename) { context.log().setLogFile(filename); context.snapshotFile(String.format("%s.snapshot", context.log().getLogFile())); return this; } @Override public String getLogFile() { return context.log().getLogFile(); } @Override public Replica setMaxLogSize(long max) { context.log().setMaxSize(max); return this; } @Override public long getMaxLogSize() { return context.log().getMaxSize(); } @Override public AsyncLog log() { return context.log(); } @Override public long getElectionTimeout() { return context.electionTimeout(); } @Override public Replica setElectionTimeout(long timeout) { context.electionTimeout(timeout); return this; } @Override public long getHeartbeatInterval() { return context.heartbeatInterval(); } @Override public Replica setHeartbeatInterval(long interval) { context.heartbeatInterval(interval); return this; } @Override public boolean isUseAdaptiveTimeouts() { return context.useAdaptiveTimeouts(); } @Override public Replica useAdaptiveTimeouts(boolean useAdaptive) { context.useAdaptiveTimeouts(useAdaptive); return this; } @Override public double getAdaptiveTimeoutThreshold() { return context.adaptiveTimeoutThreshold(); } @Override public Replica setAdaptiveTimeoutThreshold(double threshold) { context.adaptiveTimeoutThreshold(threshold); return this; } @Override public boolean isRequireWriteMajority() { return context.requireWriteMajority(); } @Override public Replica setRequireWriteMajority(boolean require) { context.requireWriteMajority(require); return this; } @Override public boolean isRequireReadMajority() { return context.requireReadMajority(); } @Override public Replica setRequireReadMajority(boolean require) { context.requireReadMajority(require); return this; } @Override public boolean isLeader() { return context.currentState().equals(StateType.LEADER); } @Override public String getCurrentLeader() { return context.currentLeader(); } @Override public Replica start() { context.start(); return this; } @Override public Replica start(Handler<AsyncResult<Void>> doneHandler) { final Future<Void> future = new DefaultFutureResult<Void>().setHandler(doneHandler); context.start(new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { if (result.failed()) { future.setFailure(result.cause()); } else { future.setResult((Void) null); } } }); return this; } @Override public <R> Replica submitCommand(String command, JsonObject args, Handler<AsyncResult<R>> resultHandler) { context.submitCommand(command, args, resultHandler); return this; } @Override public void stop() { context.stop(); } @Override public void stop(Handler<AsyncResult<Void>> doneHandler) { context.stop(doneHandler); } }
3e08d49478846e048158dba00a983213a8441497
2,488
java
Java
gmall-ums/src/main/java/com/atguigu/gmall/ums/controller/UserStatisticsController.java
zhifei-BF/guli-0211
61fd91de7571a06d80624ff9d492d142287a14c1
[ "Apache-2.0" ]
null
null
null
gmall-ums/src/main/java/com/atguigu/gmall/ums/controller/UserStatisticsController.java
zhifei-BF/guli-0211
61fd91de7571a06d80624ff9d492d142287a14c1
[ "Apache-2.0" ]
3
2021-03-19T20:25:01.000Z
2021-09-20T21:00:52.000Z
gmall-ums/src/main/java/com/atguigu/gmall/ums/controller/UserStatisticsController.java
zhifei-BF/guli-0211
61fd91de7571a06d80624ff9d492d142287a14c1
[ "Apache-2.0" ]
null
null
null
26.468085
97
0.732717
3,742
package com.atguigu.gmall.ums.controller; import java.util.List; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gmall.ums.entity.UserStatisticsEntity; import com.atguigu.gmall.ums.service.UserStatisticsService; import com.atguigu.gmall.common.bean.PageResultVo; import com.atguigu.gmall.common.bean.ResponseVo; import com.atguigu.gmall.common.bean.PageParamVo; /** * 统计信息表 * * @author helin * @email [email protected] * @date 2020-07-22 01:09:45 */ @Api(tags = "统计信息表 管理") @RestController @RequestMapping("ums/userstatistics") public class UserStatisticsController { @Autowired private UserStatisticsService userStatisticsService; /** * 列表 */ @GetMapping @ApiOperation("分页查询") public ResponseVo<PageResultVo> queryUserStatisticsByPage(PageParamVo paramVo){ PageResultVo pageResultVo = userStatisticsService.queryPage(paramVo); return ResponseVo.ok(pageResultVo); } /** * 信息 */ @GetMapping("{id}") @ApiOperation("详情查询") public ResponseVo<UserStatisticsEntity> queryUserStatisticsById(@PathVariable("id") Long id){ UserStatisticsEntity userStatistics = userStatisticsService.getById(id); return ResponseVo.ok(userStatistics); } /** * 保存 */ @PostMapping @ApiOperation("保存") public ResponseVo<Object> save(@RequestBody UserStatisticsEntity userStatistics){ userStatisticsService.save(userStatistics); return ResponseVo.ok(); } /** * 修改 */ @PostMapping("/update") @ApiOperation("修改") public ResponseVo update(@RequestBody UserStatisticsEntity userStatistics){ userStatisticsService.updateById(userStatistics); return ResponseVo.ok(); } /** * 删除 */ @PostMapping("/delete") @ApiOperation("删除") public ResponseVo delete(@RequestBody List<Long> ids){ userStatisticsService.removeByIds(ids); return ResponseVo.ok(); } }
3e08d4bcab0df0e134508c1f927d6378bb11baf8
719
java
Java
api/src/main/java/com/chornyi/poc/database/repository/JobRepository.java
reftch/angular-app
c4e040fdff75b38ea8b4ba92c1cd3d3f23dc59b1
[ "MIT" ]
null
null
null
api/src/main/java/com/chornyi/poc/database/repository/JobRepository.java
reftch/angular-app
c4e040fdff75b38ea8b4ba92c1cd3d3f23dc59b1
[ "MIT" ]
null
null
null
api/src/main/java/com/chornyi/poc/database/repository/JobRepository.java
reftch/angular-app
c4e040fdff75b38ea8b4ba92c1cd3d3f23dc59b1
[ "MIT" ]
null
null
null
37.842105
96
0.849791
3,743
package com.chornyi.poc.database.repository; import com.chornyi.poc.database.domain.Job; import com.chornyi.poc.database.repository.specification.JobSpecification; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import java.util.List; import java.util.stream.Collectors; @Repository public interface JobRepository extends JpaRepository<Job, Long>, JpaSpecificationExecutor<Job> { }
3e08d5c99bb73df832af3d1f190b44cd7a0bcec7
21,500
java
Java
drools-core/src/main/java/org/drools/core/command/impl/CommandBasedStatefulKnowledgeSession.java
acwest-cc/drools
95f3703b0f9a566556a30a406f83f2c23dfe28d8
[ "Apache-2.0" ]
6
2015-01-11T20:48:03.000Z
2021-08-14T09:59:48.000Z
drools-core/src/main/java/org/drools/core/command/impl/CommandBasedStatefulKnowledgeSession.java
acwest-cc/drools
95f3703b0f9a566556a30a406f83f2c23dfe28d8
[ "Apache-2.0" ]
1
2015-06-14T21:10:43.000Z
2015-06-15T00:42:35.000Z
drools-core/src/main/java/org/drools/core/command/impl/CommandBasedStatefulKnowledgeSession.java
acwest-cc/drools
95f3703b0f9a566556a30a406f83f2c23dfe28d8
[ "Apache-2.0" ]
2
2016-02-14T21:52:28.000Z
2017-04-04T20:27:34.000Z
39.377289
117
0.649535
3,744
/* * Copyright 2010 JBoss 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 org.drools.core.command.impl; import java.util.Collection; import java.util.Map; import java.util.Set; import org.drools.core.command.CommandService; import org.drools.core.command.GetSessionClockCommand; import org.drools.core.command.Interceptor; import org.drools.core.command.runtime.*; import org.drools.core.command.runtime.process.AbortProcessInstanceCommand; import org.drools.core.command.runtime.process.AbortWorkItemCommand; import org.drools.core.command.runtime.process.CompleteWorkItemCommand; import org.drools.core.command.runtime.process.CreateCorrelatedProcessInstanceCommand; import org.drools.core.command.runtime.process.CreateProcessInstanceCommand; import org.drools.core.command.runtime.process.GetProcessEventListenersCommand; import org.drools.core.command.runtime.process.GetProcessInstanceByCorrelationKeyCommand; import org.drools.core.command.runtime.process.GetProcessInstanceCommand; import org.drools.core.command.runtime.process.GetProcessInstancesCommand; import org.drools.core.command.runtime.process.GetWorkItemCommand; import org.drools.core.command.runtime.process.RegisterWorkItemHandlerCommand; import org.drools.core.command.runtime.process.SignalEventCommand; import org.drools.core.command.runtime.process.StartCorrelatedProcessCommand; import org.drools.core.command.runtime.process.StartProcessCommand; import org.drools.core.command.runtime.process.StartProcessInstanceCommand; import org.drools.core.command.runtime.rule.AgendaGroupSetFocusCommand; import org.drools.core.command.runtime.rule.ClearActivationGroupCommand; import org.drools.core.command.runtime.rule.ClearAgendaCommand; import org.drools.core.command.runtime.rule.ClearAgendaGroupCommand; import org.drools.core.command.runtime.rule.ClearRuleFlowGroupCommand; import org.drools.core.command.runtime.rule.DeleteCommand; import org.drools.core.command.runtime.rule.FireAllRulesCommand; import org.drools.core.command.runtime.rule.FireUntilHaltCommand; import org.drools.core.command.runtime.rule.GetAgendaEventListenersCommand; import org.drools.core.command.runtime.rule.GetEntryPointCommand; import org.drools.core.command.runtime.rule.GetEntryPointsCommand; import org.drools.core.command.runtime.rule.GetFactHandleCommand; import org.drools.core.command.runtime.rule.GetFactHandlesCommand; import org.drools.core.command.runtime.rule.GetObjectCommand; import org.drools.core.command.runtime.rule.GetObjectsCommand; import org.drools.core.command.runtime.rule.GetRuleRuntimeEventListenersCommand; import org.drools.core.command.runtime.rule.HaltCommand; import org.drools.core.command.runtime.rule.InsertObjectCommand; import org.drools.core.command.runtime.rule.QueryCommand; import org.drools.core.command.runtime.rule.UpdateCommand; import org.drools.core.impl.AbstractRuntime; import org.drools.core.process.instance.WorkItem; import org.drools.core.process.instance.WorkItemManager; import org.drools.core.rule.EntryPointId; import org.kie.api.event.rule.RuleRuntimeEventListener; import org.kie.internal.KnowledgeBase; import org.kie.api.command.Command; import org.kie.api.event.process.ProcessEventListener; import org.kie.api.event.rule.AgendaEventListener; import org.kie.internal.process.CorrelationAwareProcessRuntime; import org.kie.internal.process.CorrelationKey; import org.kie.api.runtime.Calendars; import org.kie.api.runtime.Channel; import org.kie.api.runtime.Environment; import org.kie.api.runtime.Globals; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.ObjectFilter; import org.kie.internal.runtime.StatefulKnowledgeSession; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.runtime.process.WorkItemHandler; import org.kie.api.runtime.rule.ActivationGroup; import org.kie.api.runtime.rule.Agenda; import org.kie.api.runtime.rule.AgendaFilter; import org.kie.api.runtime.rule.AgendaGroup; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.runtime.rule.LiveQuery; import org.kie.api.runtime.rule.QueryResults; import org.kie.api.runtime.rule.RuleFlowGroup; import org.kie.api.runtime.rule.EntryPoint; import org.kie.api.runtime.rule.ViewChangedEventListener; import org.kie.api.time.SessionClock; public class CommandBasedStatefulKnowledgeSession extends AbstractRuntime implements StatefulKnowledgeSession, CorrelationAwareProcessRuntime { private CommandService commandService; private transient WorkItemManager workItemManager; private transient Agenda agenda; public CommandBasedStatefulKnowledgeSession(CommandService commandService) { this.commandService = commandService; } /** * Deprecated use {@link #getIdentifier()} instead */ @Deprecated public int getId() { return commandService.execute( new GetIdCommand() ).intValue(); } public long getIdentifier() { return commandService.execute( new GetIdCommand() ); } public ProcessInstance getProcessInstance(long id) { GetProcessInstanceCommand command = new GetProcessInstanceCommand(); command.setProcessInstanceId( id ); return commandService.execute( command ); } public ProcessInstance getProcessInstance(long id, boolean readOnly) { GetProcessInstanceCommand command = new GetProcessInstanceCommand(); command.setProcessInstanceId( id ); command.setReadOnly( readOnly ); return commandService.execute( command ); } public void abortProcessInstance(long id) { AbortProcessInstanceCommand command = new AbortProcessInstanceCommand(); command.setProcessInstanceId( id ); commandService.execute( command ); } public CommandService getCommandService() { return commandService; } public Collection<ProcessInstance> getProcessInstances() { return this.commandService.execute( new GetProcessInstancesCommand() ); } public WorkItemManager getWorkItemManager() { if ( workItemManager == null ) { workItemManager = new WorkItemManager() { public void completeWorkItem(long id, Map<String, Object> results) { CompleteWorkItemCommand command = new CompleteWorkItemCommand(); command.setWorkItemId( id ); command.setResults( results ); commandService.execute( command ); } public void abortWorkItem(long id) { AbortWorkItemCommand command = new AbortWorkItemCommand(); command.setWorkItemId( id ); commandService.execute( command ); } public void registerWorkItemHandler(String workItemName, WorkItemHandler handler) { RegisterWorkItemHandlerCommand command = new RegisterWorkItemHandlerCommand(); command.setWorkItemName( workItemName ); command.setHandler( handler ); commandService.execute( command ); } public WorkItem getWorkItem(long id) { GetWorkItemCommand command = new GetWorkItemCommand(); command.setWorkItemId( id ); return commandService.execute( command ); } public void clear() { throw new UnsupportedOperationException(); } public Set<WorkItem> getWorkItems() { throw new UnsupportedOperationException(); } public void internalAbortWorkItem(long id) { throw new UnsupportedOperationException(); } public void internalAddWorkItem(WorkItem workItem) { throw new UnsupportedOperationException(); } public void internalExecuteWorkItem(WorkItem workItem) { throw new UnsupportedOperationException(); } @Override public void signalEvent(String type, Object event) { SignalEventCommand command = new SignalEventCommand(type, event); commandService.execute(command); } @Override public void signalEvent(String type, Object event, long processInstanceId) { SignalEventCommand command = new SignalEventCommand(processInstanceId, type, event); commandService.execute(command); } @Override public void dispose() { // no-op } }; } return workItemManager; } public void signalEvent(String type, Object event) { SignalEventCommand command = new SignalEventCommand( type, event ); commandService.execute( command ); } public void signalEvent(String type, Object event, long processInstanceId) { SignalEventCommand command = new SignalEventCommand( processInstanceId, type, event ); commandService.execute( command ); } public ProcessInstance startProcess(String processId) { return startProcess( processId, null ); } public ProcessInstance startProcess(String processId, Map<String, Object> parameters) { StartProcessCommand command = new StartProcessCommand(); command.setProcessId( processId ); command.setParameters( parameters ); return commandService.execute( command ); } public ProcessInstance createProcessInstance(String processId, Map<String, Object> parameters) { CreateProcessInstanceCommand command = new CreateProcessInstanceCommand(); command.setProcessId( processId ); command.setParameters( parameters ); return commandService.execute( command ); } public ProcessInstance startProcessInstance(long processInstanceId) { StartProcessInstanceCommand command = new StartProcessInstanceCommand(); command.setProcessInstanceId( processInstanceId ); return commandService.execute( command ); } public void dispose() { commandService.execute( new DisposeCommand() ); } public void destroy() { commandService.execute( new DestroySessionCommand(commandService)); } public int fireAllRules() { return this.commandService.execute( new FireAllRulesCommand() ); } public int fireAllRules(int max) { return this.commandService.execute( new FireAllRulesCommand( max ) ); } public int fireAllRules(AgendaFilter agendaFilter) { return this.commandService.execute( new FireAllRulesCommand( agendaFilter ) ); } public int fireAllRules(AgendaFilter agendaFilter, int max) { return this.commandService.execute( new FireAllRulesCommand( agendaFilter, max ) ); } public void fireUntilHalt() { this.commandService.execute( new FireUntilHaltCommand() ); } public void fireUntilHalt(AgendaFilter agendaFilter) { this.commandService.execute( new FireUntilHaltCommand( agendaFilter ) ); } public KnowledgeBase getKieBase() { return this.commandService.execute( new GetKnowledgeBaseCommand() ); } public void registerChannel(String name, Channel channel) { this.commandService.execute( new RegisterChannelCommand( name, channel ) ); } public void unregisterChannel(String name) { this.commandService.execute( new UnregisterChannelCommand( name ) ); } @SuppressWarnings("unchecked") public Map<String, Channel> getChannels() { return (Map<String, Channel>) this.commandService.execute( new GetChannelsCommand() ); } public Agenda getAgenda() { if ( agenda == null ) { agenda = new Agenda() { public void clear() { ClearAgendaCommand command = new ClearAgendaCommand(); commandService.execute( command ); } public ActivationGroup getActivationGroup(final String name) { return new ActivationGroup() { public void clear() { ClearActivationGroupCommand command = new ClearActivationGroupCommand(); command.setName( name ); commandService.execute( command ); } public String getName() { return name; } }; } public AgendaGroup getAgendaGroup(final String name) { return new AgendaGroup() { public void clear() { ClearAgendaGroupCommand command = new ClearAgendaGroupCommand(); command.setName( name ); commandService.execute( command ); } public String getName() { return name; } public void setFocus() { AgendaGroupSetFocusCommand command = new AgendaGroupSetFocusCommand(); command.setName( name ); commandService.execute( command ); } }; } public RuleFlowGroup getRuleFlowGroup(final String name) { return new RuleFlowGroup() { public void clear() { ClearRuleFlowGroupCommand command = new ClearRuleFlowGroupCommand(); command.setName( name ); commandService.execute( command ); } public String getName() { return name; } }; } }; } return agenda; } public FactHandle getFactHandle(Object object) { return this.commandService.execute( new GetFactHandleCommand( object ) ); } public <T extends FactHandle> Collection<T> getFactHandles() { return (Collection<T>) this.commandService.execute( new GetFactHandlesCommand() ); } public <T extends FactHandle> Collection<T> getFactHandles(ObjectFilter filter) { return (Collection<T>) this.commandService.execute( new GetFactHandlesCommand( filter ) ); } public Collection<? extends Object> getObjects() { return getObjects( null ); } public Collection<? extends Object> getObjects(ObjectFilter filter) { Collection result = commandService.execute( new GetObjectsCommand( filter ) ); return result; } @SuppressWarnings("unchecked") public <T extends SessionClock> T getSessionClock() { return (T) this.commandService.execute( new GetSessionClockCommand() ); } public EntryPoint getEntryPoint(String name) { return this.commandService.execute( new GetEntryPointCommand( name ) ); } public Collection< ? extends EntryPoint> getEntryPoints() { return this.commandService.execute( new GetEntryPointsCommand() ); } public void halt() { this.commandService.execute( new HaltCommand() ); } public FactHandle insert(Object object) { return commandService.execute( new InsertObjectCommand( object ) ); } public void retract(FactHandle handle) { commandService.execute( new DeleteCommand( handle ) ); } public void delete(FactHandle handle) { commandService.execute( new DeleteCommand( handle ) ); } public void update(FactHandle handle, Object object) { commandService.execute( new UpdateCommand( handle, object ) ); } public void addEventListener(RuleRuntimeEventListener listener) { commandService.execute(new AddEventListenerCommand(listener)); } public void addEventListener(AgendaEventListener listener) { commandService.execute( new AddEventListenerCommand( listener ) ); } public Collection<AgendaEventListener> getAgendaEventListeners() { return commandService.execute( new GetAgendaEventListenersCommand() ); } public Collection<RuleRuntimeEventListener> getRuleRuntimeEventListeners() { return commandService.execute( new GetRuleRuntimeEventListenersCommand() ); } public void removeEventListener(RuleRuntimeEventListener listener) { commandService.execute( new RemoveEventListenerCommand( listener ) ); } public void removeEventListener(AgendaEventListener listener) { commandService.execute( new RemoveEventListenerCommand( listener ) ); } public void addEventListener(ProcessEventListener listener) { commandService.execute( new AddEventListenerCommand( listener ) ); } public Collection<ProcessEventListener> getProcessEventListeners() { return commandService.execute( new GetProcessEventListenersCommand() ); } public void removeEventListener(ProcessEventListener listener) { commandService.execute( new RemoveEventListenerCommand( listener ) ); } public Object getGlobal(String identifier) { return commandService.execute( new GetGlobalCommand( identifier ) ); } public void setGlobal(String identifier, Object object) { this.commandService.execute( new SetGlobalCommand( identifier, object ) ); } public Globals getGlobals() { return commandService.execute( new GetGlobalsCommand() ); } public Calendars getCalendars() { return commandService.execute( new GetCalendarsCommand() ); } public Object getObject(FactHandle factHandle) { return commandService.execute( new GetObjectCommand( factHandle ) ); } public Environment getEnvironment() { return commandService.execute( new GetEnvironmentCommand() ); } public <T> T execute(Command<T> command) { return (T) this.commandService.execute( command ); } public QueryResults getQueryResults(String query, Object... arguments) { QueryCommand cmd = new QueryCommand( (String)null, query, arguments ); return this.commandService.execute( cmd ); } public String getEntryPointId() { return EntryPointId.DEFAULT.getEntryPointId(); } public long getFactCount() { return commandService.execute( new GetFactCountCommand() ); } public LiveQuery openLiveQuery(String query, Object[] arguments, ViewChangedEventListener listener) { // TODO: implement thiss return null; } public KieSessionConfiguration getSessionConfiguration() { return ((KnowledgeCommandContext) commandService.getContext()).getKieSession().getSessionConfiguration(); } public void addInterceptor(Interceptor interceptor) { interceptor.setNext(this.commandService); this.commandService = interceptor; } @Override public ProcessInstance startProcess(String processId, CorrelationKey correlationKey, Map<String, Object> parameters) { return this.commandService.execute(new StartCorrelatedProcessCommand(processId, correlationKey, parameters)); } @Override public ProcessInstance createProcessInstance(String processId, CorrelationKey correlationKey, Map<String, Object> parameters) { return this.commandService.execute( new CreateCorrelatedProcessInstanceCommand(processId, correlationKey, parameters)); } @Override public ProcessInstance getProcessInstance(CorrelationKey correlationKey) { return this.commandService.execute(new GetProcessInstanceByCorrelationKeyCommand(correlationKey)); } }
3e08d6c03c701be96b8c549c3f7bf11722e3690f
1,947
java
Java
splunk/src/main/java/com/splunk/BooleanPivotFilter.java
BalasubramanyamEvani/splunk-sdk-java
c6f3008fb35ade42c1ae25209ca3b47b4bf1d139
[ "Apache-2.0" ]
null
null
null
splunk/src/main/java/com/splunk/BooleanPivotFilter.java
BalasubramanyamEvani/splunk-sdk-java
c6f3008fb35ade42c1ae25209ca3b47b4bf1d139
[ "Apache-2.0" ]
null
null
null
splunk/src/main/java/com/splunk/BooleanPivotFilter.java
BalasubramanyamEvani/splunk-sdk-java
c6f3008fb35ade42c1ae25209ca3b47b4bf1d139
[ "Apache-2.0" ]
null
null
null
35.4
110
0.69697
3,745
/* * Copyright 2014 Splunk, 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.splunk; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Represents a filter on a boolean valued field in a pivot. */ public class BooleanPivotFilter extends PivotFilter { private final BooleanComparison comparison; private final boolean comparisonValue; BooleanPivotFilter(DataModelObject dataModelObject, String fieldName, BooleanComparison comparison, boolean comparisonValue) { super(dataModelObject, fieldName); if (dataModelObject.getField(fieldName).getType() != FieldType.BOOLEAN) { throw new IllegalArgumentException("Field " + fieldName + " on the data model object was of type " + dataModelObject.getField(fieldName).getType().toString() + ", expected boolean."); } this.comparison = comparison; this.comparisonValue = comparisonValue; } @Override JsonElement toJson() { JsonObject root = new JsonObject(); addCommonFields(root); JsonObject filterRule = new JsonObject(); filterRule.add("comparator", new JsonPrimitive(this.comparison.toString())); filterRule.add("compareTo", new JsonPrimitive(this.comparisonValue)); root.add("rule", filterRule); return root; } }
3e08d71eb05ef18d12770afa7047820a1d2cabd5
3,435
java
Java
src/main/java/com/leetcode/tree/medium/CorrectABinaryTree_1660.java
Nalhin/Leetcode
1ab17f073c35f6d5babf6d0dd2a89dd248e599c8
[ "MIT" ]
1
2021-01-10T10:56:31.000Z
2021-01-10T10:56:31.000Z
src/main/java/com/leetcode/tree/medium/CorrectABinaryTree_1660.java
Nalhin/Leetcode
1ab17f073c35f6d5babf6d0dd2a89dd248e599c8
[ "MIT" ]
null
null
null
src/main/java/com/leetcode/tree/medium/CorrectABinaryTree_1660.java
Nalhin/Leetcode
1ab17f073c35f6d5babf6d0dd2a89dd248e599c8
[ "MIT" ]
1
2020-12-19T11:52:20.000Z
2020-12-19T11:52:20.000Z
27.701613
99
0.657351
3,746
package com.leetcode.tree.medium; // You have a binary tree with a small defect. There is exactly one invalid node // where its right child incorrectly points to another node at the same depth but t // o the invalid node's right. // // Given the root of the binary tree with this defect, root, return the root of // the binary tree after removing this invalid node and every node underneath it (m // inus the node it incorrectly points to). // // Custom testing: // // The test input is read as 3 lines: // // // TreeNode root // int fromNode (not available to correctBinaryTree) // int toNode (not available to correctBinaryTree) // // // After the binary tree rooted at root is parsed, the TreeNode with value of fr // omNode will have its right child pointer pointing to the TreeNode with a value o // f toNode. Then, root is passed to correctBinaryTree. // // // Example 1: // // // // // Input: root = [1,2,3], fromNode = 2, toNode = 3 // Output: [1,null,3] // Explanation: The node with value 2 is invalid, so remove it. // // // Example 2: // // // // // Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = // 4 // Output: [8,3,1,null,null,9,4,null,null,5,6] // Explanation: The node with value 7 is invalid, so remove it and the node under // neath it, node 2. // // // // Constraints: // // // The number of nodes in the tree is in the range [3, 104]. // -109 <= Node.val <= 109 // All Node.val are unique. // fromNode != toNode // fromNode and toNode will exist in the tree and will be on the same depth. // toNode is to the right of fromNode. // fromNode.right is null in the initial tree from the test data. // Related Topics Tree // 👍 29 👎 4 // leetcode submit region begin(Prohibit modification and deletion) import com.leetcode.utils.BinaryTree.TreeNode; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.Set; /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode * right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, * TreeNode right) { this.val = val; this.left = left; this.right = right; } } */ /* O(n) Runtime: 11 ms, faster than 13.17% of Java online submissions for Correct a Binary Tree. O(n) Memory Usage: 42.7 MB, less than 53.62% of Java online submissions for Correct a Binary Tree. */ public class CorrectABinaryTree_1660 { public TreeNode correctBinaryTree(TreeNode root) { return removeDfs(root, findNode(root)); } private TreeNode findNode(TreeNode root) { Deque<TreeNode> deque = new ArrayDeque<>(); deque.push(root); while (!deque.isEmpty()) { int size = deque.size(); Set<TreeNode> level = new HashSet<>(deque); for (int i = 0; i < size; i++) { TreeNode node = deque.pop(); if (node.left != null) { deque.add(node.left); } if (node.right != null) { if (level.contains(node.right)) { return node; } deque.add(node.right); } } } return null; } private TreeNode removeDfs(TreeNode root, TreeNode node) { if (root == null) { return null; } if (root == node) { return null; } root.left = removeDfs(root.left, node); root.right = removeDfs(root.right, node); return root; } } // leetcode submit region end(Prohibit modification and deletion)
3e08d837ce8274a13061f2fb4acc473a0afc2ef9
1,352
java
Java
src/main/java/com/hitzd/his/Beans/TPatOrderDrugSensitive.java
ljcservice/autumn
37fecc185dafa71e2bf8afbae6e455fc9533a7c5
[ "Apache-2.0" ]
5
2018-04-27T00:55:26.000Z
2020-08-29T15:28:32.000Z
src/main/java/com/hitzd/his/Beans/TPatOrderDrugSensitive.java
ljcservice/autumnprogram
37fecc185dafa71e2bf8afbae6e455fc9533a7c5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hitzd/his/Beans/TPatOrderDrugSensitive.java
ljcservice/autumnprogram
37fecc185dafa71e2bf8afbae6e455fc9533a7c5
[ "Apache-2.0" ]
null
null
null
25.037037
90
0.672337
3,747
package com.hitzd.his.Beans; import java.io.Serializable; /** * @description 医嘱药物过敏信息类:PatOrderDrugSensitive 对应数据库表:医嘱药物过敏信息(PAT_ORDER_DRUG_SENSITIVE) * @author */ public class TPatOrderDrugSensitive implements Serializable{ private static final long serialVersionUID = 1L; /* 药物过敏记录ID*/ private String patOrderDrugSensitiveID; /* 药敏信息代码 */ private String drugAllergenID; /* 过敏源*/ //private String sensitiveSource; public String getPatOrderDrugSensitiveID() { return patOrderDrugSensitiveID; } public void setPatOrderDrugSensitiveID(String patOrderDrugSensitiveID) { this.patOrderDrugSensitiveID = patOrderDrugSensitiveID; } public String getDrugAllergenID() { return drugAllergenID; } public void setDrugAllergenID(String drugAllergenID) { this.drugAllergenID = drugAllergenID; } // public String getSensitiveSource() { // return sensitiveSource; // } // public void setSensitiveSource(String sensitiveSource) { // this.sensitiveSource = sensitiveSource; // } @Override public String toString() { return "TPatOrderDrugSensitive [patOrderDrugSensitiveID=" + patOrderDrugSensitiveID + ", drugAllergenID=" + drugAllergenID + "]"; } }
3e08d8d63751ebfe1758482072d055d5bb681b30
331
java
Java
hibernate_part5/src/com/lara/Manager.java
mkp1104/localEclipseWorkspaceJava
3523a0400ac95c0495c2714b8fb17c05f03d8dba
[ "MIT" ]
null
null
null
hibernate_part5/src/com/lara/Manager.java
mkp1104/localEclipseWorkspaceJava
3523a0400ac95c0495c2714b8fb17c05f03d8dba
[ "MIT" ]
null
null
null
hibernate_part5/src/com/lara/Manager.java
mkp1104/localEclipseWorkspaceJava
3523a0400ac95c0495c2714b8fb17c05f03d8dba
[ "MIT" ]
null
null
null
17.421053
39
0.722054
3,748
package com.lara; import org.hibernate.Session; public class Manager { public static void main(String[] args) { Session s1=Util.openSession(); Porson p1=new Porson(); p1.setFirstName("Moinsh"); p1.setLastName("Prosad"); p1.setAge(23); s1.beginTransaction(); s1.save(p1); s1.getTransaction().commit(); s1.flush(); s1.close(); } }
3e08d8f821355ebefc7d8f2683dddde76e71c699
753
java
Java
src/main/java/org/trophysystem/observer/HeadCoachObserver.java
kethan-kumar/DHL
f0c6a7c81dbb31001fd23f2e7ab99c5231c0e20b
[ "Apache-2.0" ]
1
2021-05-08T07:16:06.000Z
2021-05-08T07:16:06.000Z
src/main/java/org/trophysystem/observer/HeadCoachObserver.java
kethan-kumar/DHL
f0c6a7c81dbb31001fd23f2e7ab99c5231c0e20b
[ "Apache-2.0" ]
null
null
null
src/main/java/org/trophysystem/observer/HeadCoachObserver.java
kethan-kumar/DHL
f0c6a7c81dbb31001fd23f2e7ab99c5231c0e20b
[ "Apache-2.0" ]
null
null
null
28.961538
64
0.766268
3,749
/* @Author: Kethan Kumar */ package org.trophysystem.observer; import org.trophysystem.abstractfactory.TrophyAbstractFactory; import org.trophysystem.interfaces.IPerformanceObserver; import org.trophysystem.interfaces.ITrophyNominees; public class HeadCoachObserver implements IPerformanceObserver { protected TrophyAbstractFactory trophyFactory; ITrophyNominees awardTrophy; public HeadCoachObserver() { trophyFactory = TrophyAbstractFactory.instance(); awardTrophy = trophyFactory.createAwardCeremony(); } public void update(String coachName, int coachPoints) { awardTrophy.coachNominees(coachName, coachPoints); } public ITrophyNominees getAwardTrophy() { return awardTrophy; } }
3e08d959cde3cfbe37a01adb4215f1457f640833
483
java
Java
core/src/main/j2me/java/util/ListIterator.java
matheus-eyng/bc-java
b35d626619a564db860e59e1cda353dec8d7a4fa
[ "MIT" ]
1,604
2015-01-01T16:53:59.000Z
2022-03-31T13:21:39.000Z
core/src/main/j2me/java/util/ListIterator.java
matheus-eyng/bc-java
b35d626619a564db860e59e1cda353dec8d7a4fa
[ "MIT" ]
1,015
2015-01-08T08:15:43.000Z
2022-03-31T11:05:41.000Z
core/src/main/j2me/java/util/ListIterator.java
matheus-eyng/bc-java
b35d626619a564db860e59e1cda353dec8d7a4fa
[ "MIT" ]
885
2015-01-01T16:54:08.000Z
2022-03-31T22:46:25.000Z
23
101
0.741201
3,750
package java.util; public interface ListIterator extends Iterator { public boolean hasPrevious(); public Object previous() throws NoSuchElementException; public int nextIndex(); public int previousIndex(); public void set(Object o) throws RuntimeException, ClassCastException, IllegalArgumentException, IllegalStateException; public void add(Object o) throws RuntimeException, ClassCastException, IllegalArgumentException; }
3e08d98fa17ec1cf4b293c0366e556406c2e37f3
3,420
java
Java
app/src/main/java/com/codepath/apps/restclienttemplate/ComposeActivity.java
chribos/SimpleTweet
9615a061df835eea57390a223cd1ab06d23b1ef0
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/restclienttemplate/ComposeActivity.java
chribos/SimpleTweet
9615a061df835eea57390a223cd1ab06d23b1ef0
[ "MIT" ]
1
2021-07-02T11:27:03.000Z
2021-07-02T11:27:03.000Z
app/src/main/java/com/codepath/apps/restclienttemplate/ComposeActivity.java
chribos/SimpleTweet
9615a061df835eea57390a223cd1ab06d23b1ef0
[ "MIT" ]
null
null
null
38
114
0.575439
3,751
package com.codepath.apps.restclienttemplate; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.codepath.apps.restclienttemplate.models.Tweet; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import org.json.JSONException; import org.parceler.Parcels; import okhttp3.Headers; public class ComposeActivity extends AppCompatActivity { public static final String TAG = "ComposeActivity"; public static final int MAX_TWEET_LENGTH = 140; EditText etCompose; Button btnTweet; Tweet tweet; //add reference to twitterClient TwitterClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_compose); client = TwitterApp.getRestClient(this); etCompose = findViewById(R.id.etCompose); btnTweet = findViewById(R.id.btnTweet); //unwrap intent that is sent when reply button is clicked tweet = Parcels.unwrap(getIntent().getParcelableExtra("tweet")); //if tweet is not empty start reply with user handle if(tweet != null) { etCompose.setText("@" + tweet.user.screenName); } //Set click listener on button btnTweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //get text of what user has written String tweetContent = etCompose.getText().toString(); if(tweetContent.isEmpty()) { return; } if (tweetContent.length() > MAX_TWEET_LENGTH) { return; } Toast.makeText(ComposeActivity.this, tweetContent, Toast.LENGTH_LONG ); //make an API call to Twitter to publish the tweet after making sure tweet is acceptable client.publishTweet(tweetContent, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.i(TAG, "onSuccess to publish tweet"); try { Tweet tweet = Tweet.fromJson(json.jsonObject); Log.i(TAG, "Published tweet saying:" + tweet); Intent intent = new Intent(); //bundle data for response intent.putExtra("tweet", Parcels.wrap(tweet)); setResult(RESULT_OK, intent); //close activity and send data to parcent finish(); } catch (JSONException e) { Log.e(TAG, "failed to Published tweet"); e.printStackTrace(); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.e(TAG, "onFailure to publish tweet", throwable); } }); } }); } }
3e08d9bc80a2078df79587e37237969aa0486119
1,253
java
Java
src/com/liuyinxin/HDU/NumberSequence_1005.java
SuperLiuYinXin/algorithm-study
5ab57fdefeaf429c619b81c69c0127abc83f2d7b
[ "Apache-2.0" ]
null
null
null
src/com/liuyinxin/HDU/NumberSequence_1005.java
SuperLiuYinXin/algorithm-study
5ab57fdefeaf429c619b81c69c0127abc83f2d7b
[ "Apache-2.0" ]
null
null
null
src/com/liuyinxin/HDU/NumberSequence_1005.java
SuperLiuYinXin/algorithm-study
5ab57fdefeaf429c619b81c69c0127abc83f2d7b
[ "Apache-2.0" ]
null
null
null
24.568627
66
0.408619
3,752
package com.liuyinxin.HDU; import java.util.Scanner; /** * A number sequence is defined as follows: * * f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. * * Given A, B, and n, you are to calculate the value of f(n). * 一般出现mod的地方,都会有一个循环的序列 */ public class NumberSequence_1005 { public static final int maxn = 1000 + 10; public static long [] arr = new long[maxn]; public static void main(String[] args) { Scanner input = new Scanner(System.in); int a, b, n ,i; while (true) { a = input.nextInt(); b = input.nextInt(); n = input.nextInt(); if (a == 0 && b == 0 && n == 0) break; arr[1] = 1; arr[2] = 1; // 循环 for (i = 3; i <= 55; ++i){ arr[i] = (a * arr[i - 1] + b * arr[ i - 2]) % 7; if (arr[i] == 1 && arr[i - 1] == 1) { break; } } for (int j = 1; j <= i; ++j) { // System.out.print(arr[j] + " "); if (j % 7 == 0) System.out.println(); } arr[0] = arr[i - 2]; n %= i - 2; System.out.println(arr[n]); } } }
3e08da3ff958609f9d09ee6500c24b16b3bf5d70
1,089
java
Java
src/test/java/net/mguenther/kafka/junit/KeyValueTest.java
matthewpwilson/kafka-junit
e7c58a6bfc2b8a48ad43d99496eb258849e550d9
[ "Apache-2.0" ]
null
null
null
src/test/java/net/mguenther/kafka/junit/KeyValueTest.java
matthewpwilson/kafka-junit
e7c58a6bfc2b8a48ad43d99496eb258849e550d9
[ "Apache-2.0" ]
null
null
null
src/test/java/net/mguenther/kafka/junit/KeyValueTest.java
matthewpwilson/kafka-junit
e7c58a6bfc2b8a48ad43d99496eb258849e550d9
[ "Apache-2.0" ]
null
null
null
34.03125
134
0.714417
3,753
package net.mguenther.kafka.junit; import org.apache.kafka.common.header.Headers; import org.apache.kafka.common.header.internals.RecordHeaders; import org.junit.Test; import java.nio.charset.Charset; import static org.assertj.core.api.Assertions.assertThat; public class KeyValueTest { @Test public void shouldPreserveAddedHeaders() { final KeyValue<String, String> keyValue = new KeyValue<>("k", "v"); keyValue.addHeader("headerName", "headerValue", Charset.forName("utf8")); assertThat(keyValue.getHeaders().lastHeader("headerName").value()).isEqualTo("headerValue".getBytes(Charset.forName("utf8"))); } @Test public void shouldPreserveHeadersGivenOnConstruction() { final Headers headers = new RecordHeaders(); headers.add("headerName", "headerValue".getBytes(Charset.forName("utf8"))); final KeyValue<String, String> keyValue = new KeyValue<>("k", "v", headers); assertThat(keyValue.getHeaders().lastHeader("headerName").value()).isEqualTo("headerValue".getBytes(Charset.forName("utf8"))); } }
3e08dab2445a74b34c980de342f70c1c0e665092
3,796
java
Java
app/com/omisoft/vitafu/themoviedbapi/TmdbPeople.java
koprinski/vitabox
c36b766587d2fba3b35868d5fe71b9fdc2343cbc
[ "Apache-2.0" ]
null
null
null
app/com/omisoft/vitafu/themoviedbapi/TmdbPeople.java
koprinski/vitabox
c36b766587d2fba3b35868d5fe71b9fdc2343cbc
[ "Apache-2.0" ]
null
null
null
app/com/omisoft/vitafu/themoviedbapi/TmdbPeople.java
koprinski/vitabox
c36b766587d2fba3b35868d5fe71b9fdc2343cbc
[ "Apache-2.0" ]
null
null
null
27.911765
107
0.672813
3,754
package com.omisoft.vitafu.themoviedbapi; import com.omisoft.vitafu.themoviedbapi.model.Artwork; import com.omisoft.vitafu.themoviedbapi.model.ArtworkType; import com.omisoft.vitafu.themoviedbapi.model.MovieImages; import com.omisoft.vitafu.themoviedbapi.model.core.ResultsPage; import com.omisoft.vitafu.themoviedbapi.model.people.Person; import com.omisoft.vitafu.themoviedbapi.model.people.PersonCredits; import com.omisoft.vitafu.themoviedbapi.model.people.PersonPeople; import com.omisoft.vitafu.themoviedbapi.tools.ApiUrl; import com.omisoft.vitafu.themoviedbapi.tools.MovieDbException; import com.omisoft.vitafu.themoviedbapi.tools.MovieDbExceptionType; import java.util.List; public class TmdbPeople extends AbstractTmdbApi { public static final String TMDB_METHOD_PERSON = "person"; TmdbPeople(TmdbApi tmdbApi) { super(tmdbApi); } /** * This method is used to retrieve all of the basic person information. * <p/> * It will return the single highest rated profile image. * * @param personId */ public PersonPeople getPersonInfo(int personId, String... appendToResponse) { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId); apiUrl.appendToResponse(appendToResponse); return mapJsonResult(apiUrl, PersonPeople.class); } /** * This method is used to retrieve all of the cast & crew information for the person. * <p/> * It will return the single highest rated poster for each movie record. * * @param personId */ public PersonCredits getPersonCredits(int personId) { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "credits"); return mapJsonResult(apiUrl, PersonCredits.class); } /** * This method is used to retrieve all of the profile images for a person. * * @param personId */ public List<Artwork> getPersonImages(int personId) { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "images"); return mapJsonResult(apiUrl, MovieImages.class).getAll(ArtworkType.PROFILE); } /** * Get the changes for a specific person id. * <p/> * Changes are grouped by key, and ordered by date in descending order. * <p/> * By default, only the last 24 hours of changes are returned. * <p/> * The maximum number of days that can be returned in a single request is 14. * <p/> * The language is present on fields that are translatable. * * @param personId * @param startDate * @param endDate */ public void getPersonChanges(int personId, String startDate, String endDate) { throw new MovieDbException(MovieDbExceptionType.METHOD_NOT_YET_IMPLEMENTED, "Not implemented yet"); } /** * Get the list of popular people on The Movie Database. * <p/> * This list refreshes every day. * * @return */ public List<Person> getPersonPopular() { return getPersonPopular(0); } /** * Get the list of popular people on The Movie Database. * <p/> * This list refreshes every day. * * @param page * @return */ public List<Person> getPersonPopular(Integer page) { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, "popular"); if (page != null && page > 0) { apiUrl.addParam(PARAM_PAGE, page); } return mapJsonResult(apiUrl, PersonResults.class).getResults(); } static class PersonResults extends ResultsPage<Person> { } /** * Get the latest person id. */ public PersonPeople getPersonLatest() { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, "latest"); return mapJsonResult(apiUrl, PersonPeople.class); } }
3e08dc6d5222de705503e8e5a8bfffc6354491be
782
java
Java
src/main/java/com/smartbear/soapui/template/handler/SoapResponseHandler.java
vindell/soapui-template
4cf2b09cd02939201a37658f620532bcf95595bb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/smartbear/soapui/template/handler/SoapResponseHandler.java
vindell/soapui-template
4cf2b09cd02939201a37658f620532bcf95595bb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/smartbear/soapui/template/handler/SoapResponseHandler.java
vindell/soapui-template
4cf2b09cd02939201a37658f620532bcf95595bb
[ "Apache-2.0" ]
null
null
null
31.28
85
0.712276
3,755
package com.smartbear.soapui.template.handler; import com.eviware.soapui.impl.wsdl.support.soap.SoapVersion; import com.eviware.soapui.model.iface.Response; import com.eviware.soapui.support.SoapUIException; /** * Handler that encapsulates the process of generating a response object * from a {@link Response}. */ public interface SoapResponseHandler<T> { /** * Processes an {@link Response} and returns some value * corresponding to that response. * * @param response The response to process * @return A value determined by the response * * @throws SoapUIException in case of a problem or the connection was aborted */ T handleResponse(Response response, SoapVersion version) throws SoapUIException; }
3e08dca32f01a99963e11c83111c82d5d520157e
1,735
java
Java
android_smart_phone/main/app/src/main/java/com/wearableintelligencesystem/androidsmartphone/database/facialemotion/FacialEmotionConverters.java
cyxstudio/WearableIntelligenceSystem
8ad44a1ed9d13d964356875d0184ef0e5673f11f
[ "MIT" ]
null
null
null
android_smart_phone/main/app/src/main/java/com/wearableintelligencesystem/androidsmartphone/database/facialemotion/FacialEmotionConverters.java
cyxstudio/WearableIntelligenceSystem
8ad44a1ed9d13d964356875d0184ef0e5673f11f
[ "MIT" ]
null
null
null
android_smart_phone/main/app/src/main/java/com/wearableintelligencesystem/androidsmartphone/database/facialemotion/FacialEmotionConverters.java
cyxstudio/WearableIntelligenceSystem
8ad44a1ed9d13d964356875d0184ef0e5673f11f
[ "MIT" ]
null
null
null
29.913793
100
0.639193
3,756
package com.wearableintelligencesystem.androidsmartphone.database.facialemotion; import android.location.Location; import android.location.LocationManager; import androidx.room.TypeConverter; import com.google.gson.Gson; import java.util.Date; import java.util.Dictionary; import java.util.Hashtable; //import com.wearableintelligencesystem.androidsmartphone.database.phrase.FacialEmotionRoomDatabase; public class FacialEmotionConverters { @TypeConverter public static Date fromTimestamp(Long value){ return value == null ? null : new Date(value); } @TypeConverter public static Long toTimestamp(Date time){ return time == null ? null : time.getTime(); } @TypeConverter public static Location fromLocation(String value){ if(value != null) { Gson gson = new Gson(); Hashtable stash = gson.fromJson(value, Hashtable.class); Location location = new Location(LocationManager.GPS_PROVIDER); location.setLatitude((Double) stash.get("lat")); location.setLongitude((Double) stash.get("lon")); location.setAltitude((Double) stash.get("altitude")); return location; } else{ return null; } } @TypeConverter public static String toLocation(Location location){ if(location != null) { Dictionary stash = new Hashtable(); stash.put("lat", location.getLatitude()); stash.put("lon", location.getLongitude()); stash.put("altitude", location.getAltitude()); Gson gson = new Gson(); return gson.toJson(stash); } else{ return null; } } }
3e08dd76299fd46b5fb823202eef7621a7f4b2cb
1,285
java
Java
app/src/main/java/cz/msebera/android/httpclient/impl/execchain/package-info.java
sengsational/Knurder
895ad196480d50d54b6118b00ba8f447487ca864
[ "MIT" ]
30
2019-09-06T17:24:54.000Z
2022-01-24T02:32:52.000Z
app/src/main/java/cz/msebera/android/httpclient/impl/execchain/package-info.java
sengsational/Knurder
895ad196480d50d54b6118b00ba8f447487ca864
[ "MIT" ]
null
null
null
app/src/main/java/cz/msebera/android/httpclient/impl/execchain/package-info.java
sengsational/Knurder
895ad196480d50d54b6118b00ba8f447487ca864
[ "MIT" ]
19
2019-09-17T02:56:50.000Z
2022-01-24T02:32:53.000Z
40.15625
71
0.666148
3,757
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ /** * HTTP request execution chain APIs. */ package cz.msebera.android.httpclient.impl.execchain;
3e08dd948478d0fca1397bdadd82873ad7707aac
783
java
Java
src/main/java/com/ruoyi/project/api/current/domain/WxMemberLocationCurrent.java
a83071115/HSHome
dcda51ee173824a62b020d2a36596c8112e8de92
[ "MIT" ]
null
null
null
src/main/java/com/ruoyi/project/api/current/domain/WxMemberLocationCurrent.java
a83071115/HSHome
dcda51ee173824a62b020d2a36596c8112e8de92
[ "MIT" ]
1
2021-09-20T20:54:16.000Z
2021-09-20T20:54:16.000Z
src/main/java/com/ruoyi/project/api/current/domain/WxMemberLocationCurrent.java
a83071115/HSHome
dcda51ee173824a62b020d2a36596c8112e8de92
[ "MIT" ]
null
null
null
17.795455
57
0.666667
3,758
package com.ruoyi.project.api.current.domain; import lombok.*; import com.ruoyi.framework.aspectj.lang.annotation.Excel; import com.ruoyi.framework.web.domain.BaseEntity; import org.apache.shiro.crypto.hash.Hash; /** * 会员当前位置对象 wx_member_location_current * * @author alex * @date 2019-11-29 */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class WxMemberLocationCurrent extends BaseEntity { private static final long serialVersionUID = 1L; /** null */ private Long id; /** 用户id */ @Excel(name = "用户id") private String openid; /** 纬度 */ @Excel(name = "纬度") private String latitude; /** 经度 */ @Excel(name = "经度") private String longitude; /** 速度 */ @Excel(name = "速度") private String speed; }
3e08ddd93724d19ba7097eab73a7ec8754e7f15c
2,178
java
Java
shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-spring/shardingsphere-shadow-spring-namespace/src/main/java/org/apache/shardingsphere/shadow/spring/namespace/tag/ShadowRuleBeanDefinitionTag.java
sunshine-dayup/shardingsphere
7d20ec3f96b626835cf4ee08185df6ddd61de79a
[ "Apache-2.0" ]
1
2019-12-01T08:08:31.000Z
2019-12-01T08:08:31.000Z
shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-spring/shardingsphere-shadow-spring-namespace/src/main/java/org/apache/shardingsphere/shadow/spring/namespace/tag/ShadowRuleBeanDefinitionTag.java
sunshine-dayup/shardingsphere
7d20ec3f96b626835cf4ee08185df6ddd61de79a
[ "Apache-2.0" ]
1
2021-08-20T02:09:47.000Z
2021-08-20T02:11:16.000Z
shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-spring/shardingsphere-shadow-spring-namespace/src/main/java/org/apache/shardingsphere/shadow/spring/namespace/tag/ShadowRuleBeanDefinitionTag.java
sunshine-dayup/shardingsphere
7d20ec3f96b626835cf4ee08185df6ddd61de79a
[ "Apache-2.0" ]
1
2019-12-16T01:52:35.000Z
2019-12-16T01:52:35.000Z
38.892857
93
0.753903
3,759
/* * 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.shadow.spring.namespace.tag; import lombok.AccessLevel; import lombok.NoArgsConstructor; /** * Shadow rule bean definition tag constants. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ShadowRuleBeanDefinitionTag { public static final String ROOT_TAG = "rule"; // fixme remove three fields when the api refactoring is complete public static final String COLUMN_CONFIG_TAG = "column"; public static final String SHADOW_DATASOURCE_NAMES_TAG = "shadowDataSourceNames"; public static final String SOURCE_DATASOURCE_NAMES_TAG = "sourceDataSourceNames"; public static final String SHADOW_ENABLE_TAG = "enable"; public static final String DATA_SOURCE_TAG = "data-source"; public static final String DATA_SOURCE_ID_ATTRIBUTE = "id"; public static final String SOURCE_DATA_SOURCE_NAME_ATTRIBUTE = "source-data-source-name"; public static final String SHADOW_DATA_SOURCE_NAME_ATTRIBUTE = "shadow-data-source-name"; public static final String SHADOW_TABLE_TAG = "table"; public static final String SHADOW_TABLE_NAME_ATTRIBUTE = "name"; public static final String SHADOW_TABLE_ALGORITHM_TAG = "table-algorithm"; public static final String SHADOW_TABLE_ALGORITHM_REF_ATTRIBUTE = "shadow-algorithm-ref"; }
3e08de0207f2ff0bffb577af580a44f34ddfc203
3,684
java
Java
web/src/test/java/com/graphhopper/http/resources/RouteResourceIssue1574Test.java
joachimLengacher/graphhopper
6bf852e82ce88646f56d2504f3ba54145e8df83f
[ "Apache-2.0" ]
3,427
2015-01-01T05:24:12.000Z
2022-03-31T17:09:03.000Z
web/src/test/java/com/graphhopper/http/resources/RouteResourceIssue1574Test.java
joachimLengacher/graphhopper
6bf852e82ce88646f56d2504f3ba54145e8df83f
[ "Apache-2.0" ]
2,010
2015-01-06T12:43:07.000Z
2022-03-31T08:54:39.000Z
web/src/test/java/com/graphhopper/http/resources/RouteResourceIssue1574Test.java
joachimLengacher/graphhopper
6bf852e82ce88646f56d2504f3ba54145e8df83f
[ "Apache-2.0" ]
1,432
2015-01-02T01:17:00.000Z
2022-03-30T08:52:36.000Z
43.857143
161
0.726384
3,760
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.http.resources; import com.fasterxml.jackson.databind.JsonNode; import com.graphhopper.config.CHProfile; import com.graphhopper.config.Profile; import com.graphhopper.http.GraphHopperApplication; import com.graphhopper.http.GraphHopperServerConfiguration; import com.graphhopper.http.util.GraphHopperServerTestConfiguration; import com.graphhopper.util.Helper; import io.dropwizard.testing.junit5.DropwizardAppExtension; import io.dropwizard.testing.junit5.DropwizardExtensionsSupport; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.ws.rs.core.Response; import java.io.File; import java.util.Collections; import static com.graphhopper.http.util.TestUtils.clientTarget; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Peter Karich */ @ExtendWith(DropwizardExtensionsSupport.class) public class RouteResourceIssue1574Test { private static final String DIR = "./target/andorra-1574-gh/"; private static final DropwizardAppExtension<GraphHopperServerConfiguration> app = new DropwizardAppExtension<>(GraphHopperApplication.class, createConfig()); private static GraphHopperServerConfiguration createConfig() { GraphHopperServerConfiguration config = new GraphHopperServerTestConfiguration(); // this is the reason we put this test into an extra file: we can only reproduce the bug of issue 1574 by increasing the one-way-network size config.getGraphHopperConfiguration(). putObject("graph.flag_encoders", "car"). putObject("prepare.min_network_size", 0). putObject("datareader.file", "../core/files/andorra.osm.pbf"). putObject("graph.location", DIR) .setProfiles(Collections.singletonList( new Profile("car_profile").setVehicle("car").setWeighting("fastest") )) .setCHProfiles(Collections.singletonList( new CHProfile("car_profile") )); return config; } @BeforeAll @AfterAll public static void cleanUp() { Helper.removeDir(new File(DIR)); } @Test public void testStallOnDemandBug_issue1574() { final Response response = clientTarget(app, "/route?profile=car_profile&" + "point=42.486984,1.493152&point=42.481863,1.491297&point=42.49697,1.501265&stall_on_demand=true").request().buildGet().invoke(); JsonNode json = response.readEntity(JsonNode.class); assertFalse(json.has("message"), "there should be no error, but: " + json.get("message")); System.out.println(json); assertEquals(200, response.getStatus()); } }
3e08de667b332042847987b22bb5cd7627a5c8c9
3,348
java
Java
src/main/java/dev/binarycoders/awsplayground/SQS.java
fjavierm/aws-playground
ec7991878757260ede6d57b4a8de7f7fb3704920
[ "MIT" ]
null
null
null
src/main/java/dev/binarycoders/awsplayground/SQS.java
fjavierm/aws-playground
ec7991878757260ede6d57b4a8de7f7fb3704920
[ "MIT" ]
null
null
null
src/main/java/dev/binarycoders/awsplayground/SQS.java
fjavierm/aws-playground
ec7991878757260ede6d57b4a8de7f7fb3704920
[ "MIT" ]
null
null
null
41.333333
139
0.648447
3,761
package dev.binarycoders.awsplayground; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; public class SQS { public static void main(String[] args) { final var queueName = "SQSTestQueue" + System.currentTimeMillis(); // AWS does not allow create queues with same name in 60 seconds final var sqsClient = SqsClient.builder().build(); System.out.println("Creating queue..."); final Map<QueueAttributeName, String> attributes = new HashMap<>(); attributes.put(QueueAttributeName.MESSAGE_RETENTION_PERIOD, "86400"); attributes.put(QueueAttributeName.DELAY_SECONDS, "1"); final var createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(attributes) .build(); final var createQueueResponse = sqsClient.createQueue(createQueueRequest); final var queueUrl = createQueueResponse.queueUrl(); System.out.println("Queue URL: " + queueUrl); System.out.println("Listing all queues"); listQueues(sqsClient); System.out.println("Sending a message..."); final SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("I am 1").build(), SendMessageBatchRequestEntry.builder().id("id2").messageBody("I am 2").delaySeconds(10).build()) .build(); sqsClient.sendMessageBatch(sendMessageBatchRequest); System.out.println("Receive a message..."); final var receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); var receiveMessageResponse = sqsClient.receiveMessage(receiveMessageRequest); int counter = 0; do { try { System.out.printf("Receiving message, attempt %d%n", counter); receiveMessageResponse = sqsClient.receiveMessage(receiveMessageRequest); TimeUnit.SECONDS.sleep(5); counter++; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } while (!receiveMessageResponse.hasMessages() && counter < 5); if (receiveMessageResponse.hasMessages()) { receiveMessageResponse.messages().forEach(message -> System.out.println("\t" + message.body())); receiveMessageResponse.messages().forEach(message -> sqsClient.deleteMessage(builder -> builder .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()))); } else { System.out.println("No messages received."); } System.out.println("Removing queue..."); sqsClient.deleteQueue(builder -> builder.queueUrl(queueUrl)); } private static void listQueues(final SqsClient sqsClient) { final var listQueuesResponse = sqsClient.listQueues(); for (final String url : listQueuesResponse.queueUrls()) { // Skips more than pagination. nextToken System.out.printf("\t%s%n", url); } } }
3e08de6aa2fae285566dfab7009598c930bb5392
2,637
java
Java
src/tgcache/src/com/alachisoft/tayzgrid/caching/AsyncCallbackInfo.java
Alachisoft/TayzGrid
1cd2cdfff485a08f329c44150a5f02d8a98255cc
[ "Apache-2.0" ]
9
2015-06-25T06:03:54.000Z
2019-04-21T16:57:50.000Z
src/tgcache/src/com/alachisoft/tayzgrid/caching/AsyncCallbackInfo.java
Alachisoft/TayzGrid
1cd2cdfff485a08f329c44150a5f02d8a98255cc
[ "Apache-2.0" ]
null
null
null
src/tgcache/src/com/alachisoft/tayzgrid/caching/AsyncCallbackInfo.java
Alachisoft/TayzGrid
1cd2cdfff485a08f329c44150a5f02d8a98255cc
[ "Apache-2.0" ]
9
2015-09-11T15:30:05.000Z
2022-02-24T17:28:11.000Z
29.3
93
0.639742
3,762
/* * Copyright (c) 2015, Alachisoft. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alachisoft.tayzgrid.caching; import com.alachisoft.tayzgrid.serialization.core.io.InternalCompactSerializable; import com.alachisoft.tayzgrid.serialization.standard.io.CompactReader; import com.alachisoft.tayzgrid.serialization.standard.io.CompactWriter; import java.io.IOException; public class AsyncCallbackInfo extends CallbackInfo implements InternalCompactSerializable { private int _requestId; public AsyncCallbackInfo() { } public AsyncCallbackInfo(int reqid, String clietnid, Object asyncCallback) { super(clietnid, asyncCallback); _requestId = reqid; } public final int getRequestID() { return _requestId; } @Override public boolean equals(Object obj) { if (obj instanceof CallbackInfo) { CallbackInfo other = (CallbackInfo) ((obj instanceof CallbackInfo) ? obj : null); if (!getClient().equals(other.getClient())) { return false; } if (other.getCallback() instanceof Short && theCallback instanceof Short) { if ((Short) other.getCallback() != (Short) theCallback) { return false; } } else if (other.getCallback() != theCallback) { return false; } return true; } return false; } @Override public String toString() { String cnt = theClient != null ? theClient : "NULL"; String cback = theCallback != null ? theCallback.toString() : "NULL"; return cnt + ":" + cback; } public void Deserialize(CompactReader reader) throws IOException, ClassNotFoundException { super.Deserialize(reader); _requestId = reader.ReadInt32(); } public void Serialize(CompactWriter writer) throws IOException, IOException { super.Serialize(writer); writer.Write(_requestId); } }
3e08deb42b433f1974b6daf12c7b81f55ecb9da0
87
java
Java
src/test/java/com/sgcharts/beanvalidationexample/chapter03/crossparameter/Person.java
seahrh/bean-validation-example
1f1c9dd635ba6e7dcc353e7900a8daebdd355842
[ "MIT" ]
3
2019-06-26T09:21:25.000Z
2022-03-20T13:41:27.000Z
src/test/java/com/sgcharts/beanvalidationexample/chapter03/crossparameter/Person.java
seahrh/bean-validation-example
1f1c9dd635ba6e7dcc353e7900a8daebdd355842
[ "MIT" ]
1
2020-07-21T13:23:00.000Z
2020-07-22T00:24:18.000Z
src/test/java/com/sgcharts/beanvalidationexample/chapter03/crossparameter/Person.java
seahrh/bean-validation-example
1f1c9dd635ba6e7dcc353e7900a8daebdd355842
[ "MIT" ]
2
2021-04-16T07:45:05.000Z
2021-12-30T15:50:10.000Z
17.4
68
0.83908
3,763
package com.sgcharts.beanvalidationexample.chapter03.crossparameter; class Person { }
3e08df474591c33399f1ab66799befc2535679c8
217
java
Java
compilers/official-network-plugins/src/main/resources/templates/JavaBinaryInterface.java
brice-morin/ThingML
5f800da71075e40b9ddf08e8ef5ac37d984cd140
[ "Apache-2.0" ]
53
2017-06-13T07:31:21.000Z
2022-02-20T06:52:25.000Z
compilers/official-network-plugins/src/main/resources/templates/JavaBinaryInterface.java
CaoE/ThingML
9c06202d5437328e149d1d40a4cc6191f8a85e07
[ "Apache-2.0" ]
139
2017-06-16T10:06:16.000Z
2021-07-29T15:49:54.000Z
compilers/official-network-plugins/src/main/resources/templates/JavaBinaryInterface.java
CaoE/ThingML
9c06202d5437328e149d1d40a4cc6191f8a85e07
[ "Apache-2.0" ]
30
2017-06-14T20:54:12.000Z
2022-03-31T08:28:35.000Z
21.7
52
0.732719
3,764
package org.thingml.generated.network; import no.sintef.jasm.ext.*; import java.util.Arrays; public interface BinaryJava extends Format<Byte[]> { Event instantiate(Byte[] payload); Byte[] format(Event e); }
3e08df5aebf7b760dfaef117f5c585472196cdeb
2,972
java
Java
Lowest Common Ancestor of a Binary Tree/1644Solution2.java
CeciliaRuiSun/Leetcode
e5e04d8dc4c40c3e12786e23d9385af04cad8d81
[ "MIT" ]
2
2021-01-18T04:10:41.000Z
2021-01-21T15:05:07.000Z
Lowest Common Ancestor of a Binary Tree/1644Solution2.java
CeciliaRuiSun/Leetcode
e5e04d8dc4c40c3e12786e23d9385af04cad8d81
[ "MIT" ]
null
null
null
Lowest Common Ancestor of a Binary Tree/1644Solution2.java
CeciliaRuiSun/Leetcode
e5e04d8dc4c40c3e12786e23d9385af04cad8d81
[ "MIT" ]
null
null
null
27.775701
130
0.452557
3,765
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class 1644Solution2 { // Runtime: 8 ms, faster than 39.29% // Memory Usage: 42.3 MB,less than 36.19% public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { Ret result = LCA(root, p, q); if(!result.find_lca){ return null; } return new TreeNode(result.lca); } private Ret LCA(TreeNode root, TreeNode p, TreeNode q){ Ret result = new Ret(); if(root == null){ return result; } // root = p if(root.val == p.val){ result.findp = true; if(LCA(root.left, p, q).findq || LCA(root.right, p, q).findq){ result.lca = root.val; result.find_lca = true; result.findq = true; } //result.Print(root.val); //System.out.print("P"); return result; } // root = q if(root.val == q.val){ result.findq = true; if(LCA(root.left, p, q).findp || LCA(root.right, p, q).findp){ result.lca = root.val; result.find_lca = true; result.findp = true; } //result.Print(root.val); return result; } // root != p && root != q Ret L = LCA(root.left, p, q); if(L.find_lca){ result.lca = L.lca; result.find_lca = true; result.findp = true; result.findq = true; //result.Print(root.val); return result; } Ret R = LCA(root.right, p, q); if(R.find_lca){ result.lca = R.lca; result.find_lca = true; result.findp = true; result.findq = true; //result.Print(root.val); return result; } if(L.findp && R.findq || (L.findq && R.findp)){ result.lca = root.val; result.find_lca = true; result.findp = true; result.findq = true; //result.Print(root.val); return result; } if(!L.find_lca && !R.find_lca){ result.findp = L.findp || R.findp; result.findq = L.findq || R.findq; //result.Print(root.val); return result; } return result; } public class Ret{ int lca; boolean find_lca = false; boolean findp = false; boolean findq = false; public Ret(){ } public void Print(int root) { System.out.println("root: "+ root +", lca: "+lca+", find_lca: " + find_lca + ", find_p: "+findp + ", find_q: "+findq); } } }
3e08df6a4566ce8a60b64d5388adc58b319cb6af
11,644
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Autonomous/RobotControlMethods.java
atoneyd/FtcRobotController-6.0
c9239cbc2f2c5b75a4494fe649a14d00d9460ea4
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Autonomous/RobotControlMethods.java
atoneyd/FtcRobotController-6.0
c9239cbc2f2c5b75a4494fe649a14d00d9460ea4
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Autonomous/RobotControlMethods.java
atoneyd/FtcRobotController-6.0
c9239cbc2f2c5b75a4494fe649a14d00d9460ea4
[ "MIT" ]
null
null
null
36.965079
144
0.626761
3,766
package org.firstinspires.ftc.teamcode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.hardware.bosch.BNO055IMU; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import static android.os.SystemClock.sleep; import static java.lang.Math.*; import org.firstinspires.ftc.teamcode.Autonomous.EasyOpenCV; @Disabled public class RobotControlMethods { // Configuration parameters final double TICKS_PER_WHEEL_ROTATION = 537.6; //Amount of ticks logged in one wheel rotation final double WHEEL_SIZE_IN_INCHES = 3.94; // Diameter of the wheel (in inches) double decelerationThreshold = 70; // When to start decelerating; TODO: Tune double motorPowerMultiplier = 0.7; // Controls the speed of the robot; TODO: Tune // State variables private DcMotor fl, fr, bl, br; private double flRawPower, frRawPower, blRawPower, brRawPower; private double currentAngle; BNO055IMU imu; Orientation lastAngles = new Orientation(); public RobotControlMethods(DcMotor fl, DcMotor fr, DcMotor bl, DcMotor br, BNO055IMU imu) { this.fl = fl; this.fr = fr; this.bl = bl; this.br = br; this.imu = imu; } public void resetRobotControlMethods(DcMotor fl, DcMotor fr, DcMotor bl, DcMotor br, BNO055IMU imu) { this.fl = fl; this.fr = fr; this.bl = bl; this.br = br; this.imu = imu; } EasyOpenCV OpenCV = new EasyOpenCV(); public void move(final String moveDirection, final double distanceInInches, final double motorPower) throws InterruptedException { double ticks = calculateTicks(distanceInInches); resetMotors(); determineMotorTicks(moveDirection, ticks, motorPower); runProgram(ticks); } public int calculateTicks(final double distanceInInches) { return (int) ((TICKS_PER_WHEEL_ROTATION * distanceInInches) / (WHEEL_SIZE_IN_INCHES * Math.PI)); } public void resetMotors() { fl.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); fr.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); bl.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); br.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } public void determineMotorTicks(final String direction, double ticks, double motorPower) { switch (direction) { case "forward": fl.setTargetPosition((int)Math.round(1.0 * ticks)); fr.setTargetPosition((int)Math.round(1.0 * ticks)); bl.setTargetPosition((int)Math.round(1.0 * ticks)); br.setTargetPosition((int)Math.round(1.0 * ticks)); flRawPower = frRawPower = blRawPower = brRawPower = motorPower; break; case "backward": fl.setTargetPosition((int)Math.round(-1.0 * ticks)); fr.setTargetPosition((int)Math.round(-1.0 * ticks)); bl.setTargetPosition((int)Math.round(-1.0 * ticks)); br.setTargetPosition((int)Math.round(-1.0 * ticks)); flRawPower = frRawPower = blRawPower = brRawPower = -motorPower; break; case "left": fl.setTargetPosition((int)Math.round(-1.0 * ticks)); fr.setTargetPosition((int)Math.round(1.0 * ticks)); bl.setTargetPosition((int)Math.round(1.0 * ticks)); br.setTargetPosition((int)Math.round(-1.0 * ticks)); flRawPower = brRawPower = -motorPower; frRawPower = blRawPower = motorPower; break; case "right": fl.setTargetPosition((int)Math.round(1.0 * ticks)); fr.setTargetPosition((int)Math.round(-1.0 * ticks)); bl.setTargetPosition((int)Math.round(-1.0 * ticks)); br.setTargetPosition((int)Math.round(1.0 * ticks)); flRawPower = brRawPower = motorPower; frRawPower = blRawPower = -motorPower; break; default: try { throw new IllegalStateException("Invalid move direction: " + direction); } catch (IllegalStateException e) { e.printStackTrace(); } } } public void runProgram(final double ticks) { fl.setMode(DcMotor.RunMode.RUN_TO_POSITION); fr.setMode(DcMotor.RunMode.RUN_TO_POSITION); bl.setMode(DcMotor.RunMode.RUN_TO_POSITION); br.setMode(DcMotor.RunMode.RUN_TO_POSITION); fl.setPower(motorPowerMultiplier * flRawPower); fr.setPower(motorPowerMultiplier * frRawPower); bl.setPower(motorPowerMultiplier * blRawPower); br.setPower(motorPowerMultiplier * brRawPower); while ( fl.isBusy() && fr.isBusy() && bl.isBusy() && br.isBusy() ) { if (fl.getCurrentPosition() >= (decelerationThreshold * ticks)) { // Decelerates at a rate of 1/(1-deceleration_percentage) percent of power per percent of position try { double decelerationRate = -1 / (1 - decelerationThreshold); motorPowerMultiplier *= Math.max(decelerationRate * ((fl.getCurrentPosition() / ticks) - 1), 0.2); } catch (Exception e){ break; } } } fl.setPower(0); fr.setPower(0); bl.setPower(0); br.setPower(0); sleep(100); } public void turn(final String direction, final int degrees) { double flPower = 0, frPower = 0, blPower = 0, brPower = 0; resetAngle(); switch (direction){ case "left": flPower = -motorPowerMultiplier; frPower = motorPowerMultiplier; blPower = -motorPowerMultiplier; brPower = motorPowerMultiplier; break; case "right": flPower = motorPowerMultiplier; frPower = -motorPowerMultiplier; blPower = motorPowerMultiplier; brPower = -motorPowerMultiplier; break; default: try { throw new IllegalStateException("Invalid turn direction: " + direction); } catch (IllegalStateException e) { e.printStackTrace(); } } fl.setPower(flPower); fr.setPower(frPower); bl.setPower(blPower); br.setPower(brPower); TurnUntilAngleReached(degrees); } private void resetAngle() { lastAngles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); currentAngle = 0; } private void TurnUntilAngleReached(final int degrees) { if (degrees < 0) { while (true) { if ((currentAngle() <= degrees)) break; } } else // degrees > 0 { while (true) { if ((currentAngle() >= degrees)) break; } } fl.setPower(0); fr.setPower(0); bl.setPower(0); br.setPower(0); sleep(100); resetAngle(); } private double currentAngle() { Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double changeInAngle = angles.firstAngle - lastAngles.firstAngle; if (currentAngle > 0) { currentAngle = ((currentAngle + 180) % (360)) - 180; } else // currentAngle < 0 { currentAngle = ((currentAngle - 180) % (360)) + 180; } currentAngle += changeInAngle; lastAngles = angles; return currentAngle; } public void moveInAnyDirection(double angleInDegrees, double distanceInInches, double motorPower){ int ticks = calculateTicks(distanceInInches); motorPowerMultiplier *= motorPower; resetMotors(); determineMotorTicks(angleInDegrees, ticks); determineMotorPowersInAnyDirection(angleInDegrees); runProgram(ticks); } private void determineMotorTicks(double angleInDegrees, double ticks) { double flAndbrPositions = ticks * sin(toRadians(angleInDegrees) + (PI / 4)); double frAndblPositions = ticks * sin(toRadians(angleInDegrees) - (PI / 4)); fl.setTargetPosition((int) flAndbrPositions); fr.setTargetPosition((int) frAndblPositions); bl.setTargetPosition((int) frAndblPositions); br.setTargetPosition((int) flAndbrPositions); } private void determineMotorPowersInAnyDirection(double moveAngleInDegrees){ flRawPower = brRawPower = sin(toRadians(moveAngleInDegrees) + (PI / 4)); frRawPower = blRawPower = sin(toRadians(moveAngleInDegrees) - (PI / 4)); double greatestMotorPower = Math.max(Math.abs(flRawPower), Math.abs(frRawPower)); greatestMotorPower = Math.max(greatestMotorPower, Math.abs(blRawPower)); greatestMotorPower = Math.max(greatestMotorPower, Math.abs(brRawPower)); flRawPower /= greatestMotorPower; frRawPower /= greatestMotorPower; blRawPower /= greatestMotorPower; brRawPower /= greatestMotorPower; } public void moveInAnyDirectionWithTurning(double moveAngleInDegrees, double turnAngleInDegrees, double distanceInInches, double motorPower){ int ticks = calculateTicks(distanceInInches); motorPowerMultiplier *= motorPower; resetMotors(); determineMotorTicksWithTurning(moveAngleInDegrees, turnAngleInDegrees, ticks); determineMotorPowersWithTurning(moveAngleInDegrees, turnAngleInDegrees); runProgram(ticks); } private void determineMotorTicksWithTurning(double moveAngleInDegrees, double turnAngleInDegrees, double ticks) { double flAndbrPositions = ticks * (sin(toRadians(moveAngleInDegrees) + (PI / 4)) + toRadians(turnAngleInDegrees)); double frAndblPositions = ticks * (sin(toRadians(moveAngleInDegrees) - (PI / 4)) + toRadians(turnAngleInDegrees)); fl.setTargetPosition((int) flAndbrPositions); fr.setTargetPosition((int) frAndblPositions); bl.setTargetPosition((int) frAndblPositions); br.setTargetPosition((int) flAndbrPositions); } private void determineMotorPowersWithTurning(double moveAngleInDegrees, double turnAngleInDegrees){ flRawPower = brRawPower = sin(toRadians(moveAngleInDegrees) + (PI / 4)) + toRadians(turnAngleInDegrees); frRawPower = blRawPower = sin(toRadians(moveAngleInDegrees) - (PI / 4)) + toRadians(turnAngleInDegrees); double greatestMotorPower = Math.max(Math.abs(flRawPower), Math.abs(frRawPower)); greatestMotorPower = Math.max(greatestMotorPower, Math.abs(blRawPower)); greatestMotorPower = Math.max(greatestMotorPower, Math.abs(brRawPower)); flRawPower /= greatestMotorPower; frRawPower /= greatestMotorPower; blRawPower /= greatestMotorPower; brRawPower /= greatestMotorPower; } public double toRadians(double angleInDegrees){ return angleInDegrees * PI / 180; } }
3e08df9073ec685372ad2f08c82fbaedd31b9acf
535
java
Java
library/src/main/java/studios/codelight/smartloginlibrary/util/AnimUtil.java
papiguy/smartlogin
576a679f0561d38e797453d8189fcf58df79477f
[ "MIT" ]
null
null
null
library/src/main/java/studios/codelight/smartloginlibrary/util/AnimUtil.java
papiguy/smartlogin
576a679f0561d38e797453d8189fcf58df79477f
[ "MIT" ]
null
null
null
library/src/main/java/studios/codelight/smartloginlibrary/util/AnimUtil.java
papiguy/smartlogin
576a679f0561d38e797453d8189fcf58df79477f
[ "MIT" ]
null
null
null
26.75
85
0.706542
3,767
package studios.codelight.smartloginlibrary.util; import android.view.View; import android.view.animation.TranslateAnimation; /** * Created by Kalyan on 10/3/2015. */ public class AnimUtil { // To animate view slide out from bottom to top public static void slideToTop(View view){ TranslateAnimation animate = new TranslateAnimation(0,0,0,-view.getHeight()); animate.setDuration(500); animate.setFillAfter(true); view.startAnimation(animate); view.setVisibility(View.GONE); } }
3e08dfb592408c3262b3e98edd9768c71c164e7f
750
java
Java
spring-boot-schedule/src/main/java/org/schhx/springbootlearn/scheduler/Scheduler.java
schhx/spring-boot-learn
a935daaae71e0c7cf07077cefcd40efa4d345464
[ "Apache-2.0" ]
null
null
null
spring-boot-schedule/src/main/java/org/schhx/springbootlearn/scheduler/Scheduler.java
schhx/spring-boot-learn
a935daaae71e0c7cf07077cefcd40efa4d345464
[ "Apache-2.0" ]
null
null
null
spring-boot-schedule/src/main/java/org/schhx/springbootlearn/scheduler/Scheduler.java
schhx/spring-boot-learn
a935daaae71e0c7cf07077cefcd40efa4d345464
[ "Apache-2.0" ]
null
null
null
25.862069
95
0.672
3,768
package org.schhx.springbootlearn.scheduler; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class Scheduler { private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Scheduled(fixedDelay = 5000) public void now() { System.out.println("now: " + format.format(new Date())); } @Scheduled(fixedRate = 10000) public void now2() { System.out.println("now2: " + format.format(new Date())); } @Scheduled(cron = "0/15 * * * * ?") public void now3() { System.out.println("now3: " + format.format(new Date())); } }
3e08e0256b197ca9a262fdcfc1ef76455199cb24
144
java
Java
commons/src/main/java/de/d3adspace/rebekah/commons/handler/IncomingMessageHandler.java
felixklauke/rebekah
0d8daf171be7464aba8aacc4a9007f59b82ef893
[ "MIT" ]
2
2018-07-03T11:17:05.000Z
2018-07-03T11:23:31.000Z
commons/src/main/java/de/d3adspace/rebekah/commons/handler/IncomingMessageHandler.java
FelixKlauke/rebekah
0d8daf171be7464aba8aacc4a9007f59b82ef893
[ "MIT" ]
95
2018-07-03T10:35:09.000Z
2021-06-25T15:28:42.000Z
commons/src/main/java/de/d3adspace/rebekah/commons/handler/IncomingMessageHandler.java
felixklauke/rebekah
0d8daf171be7464aba8aacc4a9007f59b82ef893
[ "MIT" ]
1
2018-07-03T11:00:39.000Z
2018-07-03T11:00:39.000Z
16.333333
46
0.748299
3,769
package de.d3adspace.rebekah.commons.handler; /** * @author Felix Klauke <[email protected]> */ public interface IncomingMessageHandler { }
3e08e0358985cdd5029f24b64a28e8acbf5395dd
2,279
java
Java
src/java/catastro/logica/entidades/Parroquia.java
ayepezv/WebAppCatastro
0ff68975a8d7dd259bcf9aa3e1a21f3121b969a3
[ "MIT" ]
null
null
null
src/java/catastro/logica/entidades/Parroquia.java
ayepezv/WebAppCatastro
0ff68975a8d7dd259bcf9aa3e1a21f3121b969a3
[ "MIT" ]
null
null
null
src/java/catastro/logica/entidades/Parroquia.java
ayepezv/WebAppCatastro
0ff68975a8d7dd259bcf9aa3e1a21f3121b969a3
[ "MIT" ]
null
null
null
22.126214
80
0.626591
3,770
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package catastro.logica.entidades; import java.sql.Timestamp; /** * * @author Geovanny */ public class Parroquia { private int idParroquia; private Canton canton; private String nombre; private String descripcion; private String codigo; private String estadoLogico; private Timestamp fechaRegistro; private Timestamp fechaActualizacion; private Timestamp fechaBaja; public Parroquia() { canton = new Canton(); } public int getIdParroquia() { return idParroquia; } public void setIdParroquia(int idParroquia) { this.idParroquia = idParroquia; } public Canton getCanton() { return canton; } public void setCanton(Canton canton) { this.canton = canton; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getEstadoLogico() { return estadoLogico; } public void setEstadoLogico(String estadoLogico) { this.estadoLogico = estadoLogico; } public Timestamp getFechaRegistro() { return fechaRegistro; } public void setFechaRegistro(Timestamp fechaRegistro) { this.fechaRegistro = fechaRegistro; } public Timestamp getFechaActualizacion() { return fechaActualizacion; } public void setFechaActualizacion(Timestamp fechaActualizacion) { this.fechaActualizacion = fechaActualizacion; } public Timestamp getFechaBaja() { return fechaBaja; } public void setFechaBaja(Timestamp fechaBaja) { this.fechaBaja = fechaBaja; } }
3e08e067ba734ed82aa24f436d5dd26c7888e04b
17,616
java
Java
cluster/src/main/java/org/apache/iotdb/cluster/config/ClusterConfig.java
holtenko/iotdb
421fca74d306ccc2c836d16f7ff07bb5b7ea9fad
[ "Apache-2.0" ]
945
2018-12-13T00:39:04.000Z
2020-10-01T04:17:02.000Z
cluster/src/main/java/org/apache/iotdb/cluster/config/ClusterConfig.java
holtenko/iotdb
421fca74d306ccc2c836d16f7ff07bb5b7ea9fad
[ "Apache-2.0" ]
923
2019-01-18T01:12:04.000Z
2020-10-01T02:17:11.000Z
cluster/src/main/java/org/apache/iotdb/cluster/config/ClusterConfig.java
holtenko/iotdb
421fca74d306ccc2c836d16f7ff07bb5b7ea9fad
[ "Apache-2.0" ]
375
2018-12-23T06:40:33.000Z
2020-10-01T02:49:20.000Z
30.112821
100
0.764021
3,771
/* * 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.iotdb.cluster.config; import org.apache.iotdb.cluster.utils.ClusterConsistent; import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; public class ClusterConfig { private static Logger logger = LoggerFactory.getLogger(ClusterConfig.class); static final String CONFIG_NAME = "iotdb-cluster.properties"; private String internalIp; private int internalMetaPort = 9003; private int internalDataPort = 40010; private int clusterRpcPort = IoTDBDescriptor.getInstance().getConfig().getRpcPort(); private int clusterInfoRpcPort = 6567; /** each one is a {internalIp | domain name}:{meta port} string tuple. */ private List<String> seedNodeUrls; @ClusterConsistent private boolean isRpcThriftCompressionEnabled = false; @ClusterConsistent private int replicationNum = 1; @ClusterConsistent private int multiRaftFactor = 1; @ClusterConsistent private String clusterName = "default"; @ClusterConsistent private boolean useAsyncServer = false; private boolean useAsyncApplier = true; private int connectionTimeoutInMS = (int) TimeUnit.SECONDS.toMillis(20); private long heartbeatIntervalMs = TimeUnit.SECONDS.toMillis(1); private long electionTimeoutMs = TimeUnit.SECONDS.toMillis(20); private int readOperationTimeoutMS = (int) TimeUnit.SECONDS.toMillis(30); private int writeOperationTimeoutMS = (int) TimeUnit.SECONDS.toMillis(30); private int catchUpTimeoutMS = (int) TimeUnit.SECONDS.toMillis(300); private boolean useBatchInLogCatchUp = true; /** max number of committed logs to be saved */ private int minNumOfLogsInMem = 1000; /** max number of committed logs in memory */ private int maxNumOfLogsInMem = 2000; /** max memory size of committed logs in memory, default 512M */ private long maxMemorySizeForRaftLog = 536870912; /** Ratio of write memory allocated for raft log */ private double RaftLogMemoryProportion = 0.2; /** deletion check period of the submitted log */ private int logDeleteCheckIntervalSecond = -1; /** max number of clients in a ClientPool of a member for one node. */ private int maxClientPerNodePerMember = 1000; /** max number of idle clients in a ClientPool of a member for one node. */ private int maxIdleClientPerNodePerMember = 500; /** * If the number of connections created for a node exceeds `max_client_pernode_permember_number`, * we need to wait so much time for other connections to be released until timeout, or a new * connection will be created. */ private long waitClientTimeoutMS = 5 * 1000L; /** * ClientPool will have so many selector threads (TAsyncClientManager) to distribute to its * clients. */ private int selectorNumOfClientPool = Runtime.getRuntime().availableProcessors() / 3 > 0 ? Runtime.getRuntime().availableProcessors() / 3 : 1; /** * Whether creating schema automatically is enabled, this will replace the one in * iotdb-engine.properties */ private boolean enableAutoCreateSchema = true; private boolean enableRaftLogPersistence = true; private int flushRaftLogThreshold = 10000; /** * Size of log buffer. If raft log persistence is enabled and the size of a insert plan is smaller * than this parameter, then the insert plan will be rejected by WAL. */ private int raftLogBufferSize = 16 * 1024 * 1024; /** * consistency level, now three consistency levels are supported: strong, mid and weak. Strong * consistency means the server will first try to synchronize with the leader to get the newest * meta data, if failed(timeout), directly report an error to the user; While mid consistency * means the server will first try to synchronize with the leader, but if failed(timeout), it will * give up and just use current data it has cached before; Weak consistency do not synchronize * with the leader and simply use the local data */ private ConsistencyLevel consistencyLevel = ConsistencyLevel.MID_CONSISTENCY; private long joinClusterTimeOutMs = TimeUnit.SECONDS.toMillis(5); private int pullSnapshotRetryIntervalMs = (int) TimeUnit.SECONDS.toMillis(5); /** * The maximum value of the raft log index stored in the memory per raft group, These indexes are * used to index the location of the log on the disk */ private int maxRaftLogIndexSizeInMemory = 10000; /** * If leader finds too many uncommitted raft logs, raft group leader will wait for a short period * of time, and then append the raft log */ private int UnCommittedRaftLogNumForRejectThreshold = 500; /** * If followers find too many committed raft logs have not been applied, followers will reject the * raft log sent by leader */ private int UnAppliedRaftLogNumForRejectThreshold = 500; /** * The maximum size of the raft log saved on disk for each file (in bytes) of each raft group. The * default size is 1GB */ private int maxRaftLogPersistDataSizePerFile = 1073741824; /** * The maximum number of persistent raft log files on disk per raft group, So each raft group's * log takes up disk space approximately equals max_raft_log_persist_data_size_per_file * * max_number_of_persist_raft_log_files */ private int maxNumberOfPersistRaftLogFiles = 5; /** The maximum number of logs saved on the disk */ private int maxPersistRaftLogNumberOnDisk = 1_000_000; private boolean enableUsePersistLogOnDiskToCatchUp = true; /** * The number of logs read on the disk at one time, which is mainly used to control the memory * usage.This value multiplied by the log size is about the amount of memory used to read logs * from the disk at one time. */ private int maxNumberOfLogsPerFetchOnDisk = 1000; /** * When set to true, if the log queue of a follower fills up, LogDispatcher will wait for a while * until the queue becomes available, otherwise LogDispatcher will just ignore that slow node. */ private boolean waitForSlowNode = true; /** * When consistency level is set to mid, query will fail if the log lag exceeds max_read_log_lag. */ private long maxReadLogLag = 1000L; /** * When a follower tries to sync log with the leader, sync will fail if the log Lag exceeds * maxSyncLogLag. */ private long maxSyncLogLag = 100000L; private boolean openServerRpcPort = false; /** * create a clusterConfig class. The internalIP will be set according to the server's hostname. If * there is something error for getting the ip of the hostname, then set the internalIp as * localhost. */ public ClusterConfig() { try { internalIp = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { logger.error(e.getMessage()); internalIp = "127.0.0.1"; } seedNodeUrls = Arrays.asList(String.format("%s:%d", internalIp, internalMetaPort)); } public int getSelectorNumOfClientPool() { return selectorNumOfClientPool; } public int getMaxClientPerNodePerMember() { return maxClientPerNodePerMember; } public void setMaxClientPerNodePerMember(int maxClientPerNodePerMember) { this.maxClientPerNodePerMember = maxClientPerNodePerMember; } public int getMaxIdleClientPerNodePerMember() { return maxIdleClientPerNodePerMember; } public void setMaxIdleClientPerNodePerMember(int maxIdleClientPerNodePerMember) { this.maxIdleClientPerNodePerMember = maxIdleClientPerNodePerMember; } public boolean isUseBatchInLogCatchUp() { return useBatchInLogCatchUp; } public void setUseBatchInLogCatchUp(boolean useBatchInLogCatchUp) { this.useBatchInLogCatchUp = useBatchInLogCatchUp; } public int getInternalMetaPort() { return internalMetaPort; } public void setInternalMetaPort(int internalMetaPort) { this.internalMetaPort = internalMetaPort; } public boolean isRpcThriftCompressionEnabled() { return isRpcThriftCompressionEnabled; } void setRpcThriftCompressionEnabled(boolean rpcThriftCompressionEnabled) { isRpcThriftCompressionEnabled = rpcThriftCompressionEnabled; } public List<String> getSeedNodeUrls() { return seedNodeUrls; } public void setSeedNodeUrls(List<String> seedNodeUrls) { this.seedNodeUrls = seedNodeUrls; } public int getReplicationNum() { return replicationNum; } public void setReplicationNum(int replicationNum) { this.replicationNum = replicationNum; } public int getMultiRaftFactor() { return multiRaftFactor; } public void setMultiRaftFactor(int multiRaftFactor) { this.multiRaftFactor = multiRaftFactor; } void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getClusterName() { return clusterName; } public int getInternalDataPort() { return internalDataPort; } public void setInternalDataPort(int internalDataPort) { this.internalDataPort = internalDataPort; } public int getClusterRpcPort() { return clusterRpcPort; } public void setClusterRpcPort(int clusterRpcPort) { this.clusterRpcPort = clusterRpcPort; } public int getConnectionTimeoutInMS() { return connectionTimeoutInMS; } void setConnectionTimeoutInMS(int connectionTimeoutInMS) { this.connectionTimeoutInMS = connectionTimeoutInMS; } public int getCatchUpTimeoutMS() { return catchUpTimeoutMS; } public void setCatchUpTimeoutMS(int catchUpTimeoutMS) { this.catchUpTimeoutMS = catchUpTimeoutMS; } public int getReadOperationTimeoutMS() { return readOperationTimeoutMS; } void setReadOperationTimeoutMS(int readOperationTimeoutMS) { this.readOperationTimeoutMS = readOperationTimeoutMS; } public int getWriteOperationTimeoutMS() { return writeOperationTimeoutMS; } public void setWriteOperationTimeoutMS(int writeOperationTimeoutMS) { this.writeOperationTimeoutMS = writeOperationTimeoutMS; } public int getMinNumOfLogsInMem() { return minNumOfLogsInMem; } public void setMinNumOfLogsInMem(int minNumOfLogsInMem) { this.minNumOfLogsInMem = minNumOfLogsInMem; } public int getLogDeleteCheckIntervalSecond() { return logDeleteCheckIntervalSecond; } void setLogDeleteCheckIntervalSecond(int logDeleteCheckIntervalSecond) { this.logDeleteCheckIntervalSecond = logDeleteCheckIntervalSecond; } public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; } public boolean isEnableAutoCreateSchema() { return enableAutoCreateSchema; } public void setEnableAutoCreateSchema(boolean enableAutoCreateSchema) { this.enableAutoCreateSchema = enableAutoCreateSchema; } public boolean isUseAsyncServer() { return useAsyncServer; } public void setUseAsyncServer(boolean useAsyncServer) { this.useAsyncServer = useAsyncServer; } public boolean isEnableRaftLogPersistence() { return enableRaftLogPersistence; } public void setEnableRaftLogPersistence(boolean enableRaftLogPersistence) { this.enableRaftLogPersistence = enableRaftLogPersistence; } public boolean isUseAsyncApplier() { return useAsyncApplier; } public void setUseAsyncApplier(boolean useAsyncApplier) { this.useAsyncApplier = useAsyncApplier; } public int getMaxNumOfLogsInMem() { return maxNumOfLogsInMem; } public void setMaxNumOfLogsInMem(int maxNumOfLogsInMem) { this.maxNumOfLogsInMem = maxNumOfLogsInMem; } public int getUnCommittedRaftLogNumForRejectThreshold() { return UnCommittedRaftLogNumForRejectThreshold; } public void setUnCommittedRaftLogNumForRejectThreshold( int unCommittedRaftLogNumForRejectThreshold) { UnCommittedRaftLogNumForRejectThreshold = unCommittedRaftLogNumForRejectThreshold; } public int getUnAppliedRaftLogNumForRejectThreshold() { return UnAppliedRaftLogNumForRejectThreshold; } public void setUnAppliedRaftLogNumForRejectThreshold(int unAppliedRaftLogNumForRejectThreshold) { UnAppliedRaftLogNumForRejectThreshold = unAppliedRaftLogNumForRejectThreshold; } public int getRaftLogBufferSize() { return raftLogBufferSize; } public void setRaftLogBufferSize(int raftLogBufferSize) { this.raftLogBufferSize = raftLogBufferSize; } public int getFlushRaftLogThreshold() { return flushRaftLogThreshold; } void setFlushRaftLogThreshold(int flushRaftLogThreshold) { this.flushRaftLogThreshold = flushRaftLogThreshold; } public long getJoinClusterTimeOutMs() { return joinClusterTimeOutMs; } public void setJoinClusterTimeOutMs(long joinClusterTimeOutMs) { this.joinClusterTimeOutMs = joinClusterTimeOutMs; } public int getPullSnapshotRetryIntervalMs() { return pullSnapshotRetryIntervalMs; } public void setPullSnapshotRetryIntervalMs(int pullSnapshotRetryIntervalMs) { this.pullSnapshotRetryIntervalMs = pullSnapshotRetryIntervalMs; } public int getMaxRaftLogIndexSizeInMemory() { return maxRaftLogIndexSizeInMemory; } public void setMaxRaftLogIndexSizeInMemory(int maxRaftLogIndexSizeInMemory) { this.maxRaftLogIndexSizeInMemory = maxRaftLogIndexSizeInMemory; } public long getMaxMemorySizeForRaftLog() { return maxMemorySizeForRaftLog; } public void setMaxMemorySizeForRaftLog(long maxMemorySizeForRaftLog) { this.maxMemorySizeForRaftLog = maxMemorySizeForRaftLog; } public double getRaftLogMemoryProportion() { return RaftLogMemoryProportion; } public void setRaftLogMemoryProportion(double raftLogMemoryProportion) { RaftLogMemoryProportion = raftLogMemoryProportion; } public int getMaxRaftLogPersistDataSizePerFile() { return maxRaftLogPersistDataSizePerFile; } public void setMaxRaftLogPersistDataSizePerFile(int maxRaftLogPersistDataSizePerFile) { this.maxRaftLogPersistDataSizePerFile = maxRaftLogPersistDataSizePerFile; } public int getMaxNumberOfPersistRaftLogFiles() { return maxNumberOfPersistRaftLogFiles; } public void setMaxNumberOfPersistRaftLogFiles(int maxNumberOfPersistRaftLogFiles) { this.maxNumberOfPersistRaftLogFiles = maxNumberOfPersistRaftLogFiles; } public int getMaxPersistRaftLogNumberOnDisk() { return maxPersistRaftLogNumberOnDisk; } public void setMaxPersistRaftLogNumberOnDisk(int maxPersistRaftLogNumberOnDisk) { this.maxPersistRaftLogNumberOnDisk = maxPersistRaftLogNumberOnDisk; } public boolean isEnableUsePersistLogOnDiskToCatchUp() { return enableUsePersistLogOnDiskToCatchUp; } public void setEnableUsePersistLogOnDiskToCatchUp(boolean enableUsePersistLogOnDiskToCatchUp) { this.enableUsePersistLogOnDiskToCatchUp = enableUsePersistLogOnDiskToCatchUp; } public int getMaxNumberOfLogsPerFetchOnDisk() { return maxNumberOfLogsPerFetchOnDisk; } public void setMaxNumberOfLogsPerFetchOnDisk(int maxNumberOfLogsPerFetchOnDisk) { this.maxNumberOfLogsPerFetchOnDisk = maxNumberOfLogsPerFetchOnDisk; } public boolean isWaitForSlowNode() { return waitForSlowNode; } public long getMaxReadLogLag() { return maxReadLogLag; } public void setMaxReadLogLag(long maxReadLogLag) { this.maxReadLogLag = maxReadLogLag; } public long getMaxSyncLogLag() { return maxSyncLogLag; } public void setMaxSyncLogLag(long maxSyncLogLag) { this.maxSyncLogLag = maxSyncLogLag; } public String getInternalIp() { return internalIp; } public void setInternalIp(String internalIp) { this.internalIp = internalIp; } public boolean isOpenServerRpcPort() { return openServerRpcPort; } public void setOpenServerRpcPort(boolean openServerRpcPort) { this.openServerRpcPort = openServerRpcPort; } public long getWaitClientTimeoutMS() { return waitClientTimeoutMS; } public void setWaitClientTimeoutMS(long waitClientTimeoutMS) { this.waitClientTimeoutMS = waitClientTimeoutMS; } public long getHeartbeatIntervalMs() { return heartbeatIntervalMs; } public void setHeartbeatIntervalMs(long heartbeatIntervalMs) { this.heartbeatIntervalMs = heartbeatIntervalMs; } public long getElectionTimeoutMs() { return electionTimeoutMs; } public void setElectionTimeoutMs(long electionTimeoutMs) { this.electionTimeoutMs = electionTimeoutMs; } public int getClusterInfoRpcPort() { return clusterInfoRpcPort; } public void setClusterInfoRpcPort(int clusterInfoRpcPort) { this.clusterInfoRpcPort = clusterInfoRpcPort; } }
3e08e12fceee4a61ed787468efa6db3d741749ce
4,585
java
Java
chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedImageLoader.java
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedImageLoader.java
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedImageLoader.java
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
38.208333
100
0.652781
3,772
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.feed; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v7.content.res.AppCompatResources; import com.google.android.libraries.feed.common.functional.Consumer; import com.google.android.libraries.feed.host.imageloader.ImageLoaderApi; import org.chromium.base.Callback; import org.chromium.chrome.browser.profiles.Profile; import java.util.ArrayList; import java.util.List; /** * Provides image loading and other host-specific asset fetches for Feed. */ public class FeedImageLoader implements ImageLoaderApi { private static final String ASSET_PREFIX = "asset://"; private static final String DRAWABLE_RESOURCE_TYPE = "drawable"; private FeedImageLoaderBridge mFeedImageLoaderBridge; private Context mActivityContext; /** * Creates a FeedImageLoader for fetching image for the current user. * * @param profile Profile of the user we are rendering the Feed for. * @param activityContext Context of the user we are rendering the Feed for. */ public FeedImageLoader(Profile profile, Context activityContext) { this(profile, activityContext, new FeedImageLoaderBridge()); } /** * Creates a FeedImageLoader for fetching image for the current user. * * @param profile Profile of the user we are rendering the Feed for. * @param activityContext Context of the user we are rendering the Feed for. * @param bridge The FeedImageLoaderBridge implementation can handle fetching image request. */ public FeedImageLoader(Profile profile, Context activityContext, FeedImageLoaderBridge bridge) { mFeedImageLoaderBridge = bridge; mFeedImageLoaderBridge.init(profile); mActivityContext = activityContext; } @Override public void loadDrawable(List<String> urls, Consumer<Drawable> consumer) { assert mFeedImageLoaderBridge != null; List<String> assetUrls = new ArrayList<>(); List<String> networkUrls = new ArrayList<>(); // Since loading APK resource("asset://"") only can be done in Java side, we filter out // asset urls, and pass the other URLs to C++ side. This will change the order of |urls|, // because we will process asset:// URLs after network URLs, but once // https://crbug.com/840578 resolved, we can process URLs ordering same as |urls|. for (String url : urls) { if (url.startsWith(ASSET_PREFIX)) { assetUrls.add(url); } else { // Assume this is a web image. networkUrls.add(url); } } if (networkUrls.size() == 0) { Drawable drawable = getAssetDrawable(assetUrls); consumer.accept(drawable); return; } mFeedImageLoaderBridge.fetchImage(networkUrls, new Callback<Bitmap>() { @Override public void onResult(Bitmap bitmap) { if (bitmap != null) { Drawable drawable = new BitmapDrawable(mActivityContext.getResources(), bitmap); consumer.accept(drawable); return; } // Since no image was available for downloading over the network, attempt to load a // drawable locally. Drawable drawable = getAssetDrawable(assetUrls); consumer.accept(drawable); } }); } /** Cleans up FeedImageLoaderBridge. */ public void destroy() { assert mFeedImageLoaderBridge != null; mFeedImageLoaderBridge.destroy(); mFeedImageLoaderBridge = null; } private Drawable getAssetDrawable(List<String> assetUrls) { for (String url : assetUrls) { String resourceName = url.substring(ASSET_PREFIX.length()); int resourceId = mActivityContext.getResources().getIdentifier( resourceName, DRAWABLE_RESOURCE_TYPE, mActivityContext.getPackageName()); if (resourceId != 0) { Drawable drawable = AppCompatResources.getDrawable(mActivityContext, resourceId); if (drawable != null) { return drawable; } } } return null; } }
3e08e302d56b8c694153c1dd5e8a6c197934eb7f
6,612
java
Java
src/test/java/com/xlongwei/light4j/HolidayUtilTest.java
APIJSON/light4j
9429b315526a0a9e66968db50d37bad54c990ffb
[ "Apache-2.0" ]
null
null
null
src/test/java/com/xlongwei/light4j/HolidayUtilTest.java
APIJSON/light4j
9429b315526a0a9e66968db50d37bad54c990ffb
[ "Apache-2.0" ]
null
null
null
src/test/java/com/xlongwei/light4j/HolidayUtilTest.java
APIJSON/light4j
9429b315526a0a9e66968db50d37bad54c990ffb
[ "Apache-2.0" ]
null
null
null
54.196721
192
0.735178
3,773
package com.xlongwei.light4j; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TreeMap; import java.util.stream.Collectors; import com.xlongwei.light4j.util.DateUtil; import com.xlongwei.light4j.util.HolidayUtil; import org.apache.commons.lang3.time.DateUtils; import org.junit.Test; /** * holiday util test * @author xlongwei * */ public class HolidayUtilTest { @Test public void test() throws Exception { new TreeMap<>(HolidayUtil.holidays).forEach((k,v) -> System.out.println(k+"="+v)); new TreeMap<>(HolidayUtil.plans).forEach((k,v) -> System.out.println(k+"="+v)); assertEquals("元旦节", HolidayUtil.nameOf(1)); assertEquals("春节", HolidayUtil.nameOf(2)); assertEquals("中秋节", HolidayUtil.nameOf(7)); } @Test public void abnormal() { String year = "2021"; String plan = "{\"元旦节\":\"1.1-3\",\"春节\":\"2.11-17,-2.7,-2.20\",\"清明节\":\"4.3-5\",\"劳动节\":\"5.1-5,-4.25,-5.8\",\"端午节\":\"6.12-14\",\"中秋节\":\"-9.18,9.19-21\",\"国庆节\":\"-9.26,10.1-7,-10.9\"}"; HolidayUtil.addPlan(year, plan); Date date = DateUtil.parse(year + "0101"); Date end = DateUtil.parse(year + "1231"); List<Date> weekendWorks = new ArrayList<>(); List<Date> weekdayBreaks = new ArrayList<>(); do { boolean isweekend = HolidayUtil.isweekend(date); boolean isworkday = HolidayUtil.isworkday(date); if (isweekend && isworkday) { weekendWorks.add(date); } else if (!isweekend && !isworkday) { weekdayBreaks.add(date); } date = DateUtils.addDays(date, 1); } while (date.before(end)); System.out.println("weekend workdays"); System.out.println(String.join(",", weekendWorks.stream().map(cn.hutool.core.date.DateUtil::formatDate).collect(Collectors.toList()))); System.out.println("weekday breakdays"); System.out.println(String.join(",", weekdayBreaks.stream().map(cn.hutool.core.date.DateUtil::formatDate).collect(Collectors.toList()))); } @Test public void isworkday() throws Exception { assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-01"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2020-01-02"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2020-01-19"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-24"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-25"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-26"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-27"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-28"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-29"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-30"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-01-31"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-02-01"))); assertFalse(HolidayUtil.isworkday(DateUtil.parse("2020-02-02"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2020-02-03"))); } @Test public void nextworkday() throws Exception { assertEquals("2020-01-02", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-01-01")))); assertEquals("2020-01-20", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-01-18"), true))); assertEquals("2020-01-23", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-01-23")))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-01-24")))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-01-30")))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-02-01")))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-02-02")))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.nextworkday(DateUtil.parse("2020-02-01"), true))); } @Test public void offsetworkday() throws Exception { assertEquals("2020-01-02", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-01"), 1))); assertEquals("2020-01-19", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-18"), 1))); assertEquals("2020-01-20", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-17"), 1, true))); assertEquals("2020-01-20", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-18"), 1, true))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-23"), 1))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-30"), 1))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-31"), 1))); assertEquals("2020-02-04", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-30"), 2))); assertEquals("2020-01-23", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-02-03"), -1))); assertEquals("2020-01-23", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-02-08"), -6))); assertEquals("2020-02-07", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-02-09"), -1))); assertEquals("2020-01-23", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-02-09"), -6))); assertEquals("2020-01-19", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-31"), -5))); assertEquals("2020-02-03", DateUtil.dateFormat.format(HolidayUtil.offsetworkday(DateUtil.parse("2020-01-31"), 1, true))); } @Test public void betweenworkday() { assertEquals(25, HolidayUtil.betweenworkday(DateUtil.parse("2020-01-01"), DateUtil.parse("2020-02-12"), false)); assertEquals(24, HolidayUtil.betweenworkday(DateUtil.parse("2020-01-01"), DateUtil.parse("2020-02-12"), true)); } @Test public void test2017To2011() { assertTrue(HolidayUtil.isworkday(DateUtil.parse("2011-10-8"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2011-12-31"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2012-4-1"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2013-4-27"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2014-5-4"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2015-2-15"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2016-9-18"))); assertTrue(HolidayUtil.isworkday(DateUtil.parse("2017-4-1"))); } }
3e08e400a53450888590b43e0c269a1078f9c553
8,006
java
Java
ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/html/core/HtmlCommonTest.java
fciubotaru/z-pec
82335600341c6fb1bb8a471fd751243a90bc4d57
[ "MIT" ]
5
2019-03-26T07:51:56.000Z
2021-08-30T07:26:05.000Z
ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/html/core/HtmlCommonTest.java
fciubotaru/z-pec
82335600341c6fb1bb8a471fd751243a90bc4d57
[ "MIT" ]
1
2015-08-18T19:03:32.000Z
2015-08-18T19:03:32.000Z
ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/html/core/HtmlCommonTest.java
fciubotaru/z-pec
82335600341c6fb1bb8a471fd751243a90bc4d57
[ "MIT" ]
13
2015-03-11T00:26:35.000Z
2020-07-26T16:25:18.000Z
29.007246
112
0.702973
3,774
package com.zimbra.qa.selenium.projects.html.core; import java.io.IOException; import java.util.*; import org.apache.log4j.*; import org.testng.annotations.*; import org.xml.sax.SAXException; import com.zimbra.qa.selenium.framework.core.ClientSessionFactory; import com.zimbra.qa.selenium.framework.ui.AbsTab; import com.zimbra.qa.selenium.framework.util.*; import com.zimbra.qa.selenium.projects.html.ui.AppHtmlClient; /** * The <code>HtmlCommonTest</code> class is the base test case class * for normal HTML client test case classes. * <p> * The HtmlCommonTest provides two basic functionalities: * <ol> * <li>{@link AbsTab} {@link #startingPage} - navigate to this * page before each test case method</li> * <li>{@link ZimbraAccount} {@link #startingAccountPreferences} - ensure this * account is authenticated before each test case method</li> * </ol> * <p> * It is important to note that no re-authentication (i.e. logout * followed by login) will occur if {@link #startingAccountPreferences} is * already the currently authenticated account. * <p> * The same rule applies to the {@link #startingPage}, as well. If * the "Contact App" is the specified starting page, and the contact * app is already opened, albiet in a "new contact" view, then the * "new contact" view will not be closed. * <p> * Typical usage:<p> * <pre> * {@code * public class TestCaseClass extends HtmlCommonTest { * * public TestCaseClass() { * * // All tests start at the Mail page * super.startingPage = app.zPageMail; * * // Create a new account to log into * ZimbraAccount account = new ZimbraAccount(); * super.startingAccount = account; * * // ... * * } * * // ... * * } * } * </pre> * * @author Matt Rhoades * */ public class HtmlCommonTest { protected static Logger logger = LogManager.getLogger(HtmlCommonTest.class); /** * The Html application object */ protected AppHtmlClient app = null; // Configurable from config file or input parameters /** * BeforeMethod variables * startingPage = the starting page before the test method starts * startingAccount = the account to log in as */ protected AbsTab startingPage = null; protected Map<String, String> startingAccountPreferences = null; protected Map<String, String> startingAccountZimletPreferences = null; protected HtmlCommonTest() { logger.info("New "+ HtmlCommonTest.class.getCanonicalName()); app = new AppHtmlClient(); startingPage = app.zPageMain; startingAccountPreferences = new HashMap<String, String>(); startingAccountZimletPreferences = new HashMap<String, String>(); } /** * Global BeforeSuite * <p> * <ol> * <li>Start the DefaultSelenium client</li> * </ol> * <p> * @throws HarnessException * @throws InterruptedException * @throws IOException * @throws SAXException */ @BeforeSuite( groups = { "always" } ) public void commonTestBeforeSuite() throws HarnessException { logger.info("commonTestBeforeSuite: start"); ZimbraSeleniumProperties.setAppType(ZimbraSeleniumProperties.AppType.HTML); ClientSessionFactory.session().selenium().start(); ClientSessionFactory.session().selenium().windowMaximize(); ClientSessionFactory.session().selenium().windowFocus(); ClientSessionFactory.session().selenium().allowNativeXpath("true"); ClientSessionFactory.session().selenium().setTimeout("30000");// Use 30 second timeout for opening the browser ClientSessionFactory.session().selenium().open(ZimbraSeleniumProperties.getBaseURL()); logger.info("commonTestBeforeSuite: finish"); } /** * Global BeforeClass * * @throws HarnessException */ @BeforeClass( groups = { "always" } ) public void commonTestBeforeClass() throws HarnessException { logger.info("commonTestBeforeClass: start"); logger.info("commonTestBeforeClass: finish"); } /** * Global BeforeMethod * <p> * <ol> * <li>For all tests, make sure {@link #startingPage} is active</li> * <li>For all tests, make sure {@link #startingAccountPreferences} is logged in</li> * <li>For all tests, make any compose tabs are closed</li> * </ol> * <p> * @throws HarnessException */ @BeforeMethod( groups = { "always" } ) public void commonTestBeforeMethod() throws HarnessException { logger.info("commonTestBeforeMethod: start"); // If test account preferences are defined, then make sure the test account // uses those preferences // if ( (startingAccountPreferences != null) && (!startingAccountPreferences.isEmpty()) ) { logger.debug("commonTestBeforeMethod: startingAccountPreferences are defined"); StringBuilder settings = new StringBuilder(); for (Map.Entry<String, String> entry : startingAccountPreferences.entrySet()) { settings.append(String.format("<a n='%s'>%s</a>", entry.getKey(), entry.getValue())); } ZimbraAdminAccount.GlobalAdmin().soapSend( "<ModifyAccountRequest xmlns='urn:zimbraAdmin'>" + "<id>"+ ZimbraAccount.AccountHTML().ZimbraId +"</id>" + settings.toString() + "</ModifyAccountRequest>"); // Set the flag so the account is reset for the next test ZimbraAccount.AccountHTML().accountIsDirty = true; } // If test account zimlet preferences are defined, then make sure the test account // uses those zimlet preferences // if ( (startingAccountZimletPreferences != null) && (!startingAccountZimletPreferences.isEmpty()) ) { logger.debug("commonTestBeforeMethod: startingAccountPreferences are defined"); ZimbraAccount.AccountHTML().modifyZimletPreferences(startingAccountZimletPreferences); } // If AccountHTML is not currently logged in, then login now if ( !ZimbraAccount.AccountHTML().equals(app.zGetActiveAccount()) ) { logger.debug("commonTestBeforeMethod: AccountHTML is not currently logged in"); if ( app.zPageMain.zIsActive() ) app.zPageMain.zLogout(); app.zPageLogin.zLogin(ZimbraAccount.AccountHTML()); // Confirm if ( !ZimbraAccount.AccountHTML().equals(app.zGetActiveAccount())) { throw new HarnessException("Unable to authenticate as "+ ZimbraAccount.AccountHTML().EmailAddress); } } // If a startingPage is defined, then make sure we are on that page if ( startingPage != null ) { logger.debug("commonTestBeforeMethod: startingPage is defined"); // If the starting page is not active, navigate to it if ( !startingPage.zIsActive() ) { startingPage.zNavigateTo(); } // Confirm that the page is active if ( !startingPage.zIsActive() ) { throw new HarnessException("Unable to navigate to "+ startingPage.myPageName()); } } logger.info("commonTestBeforeMethod: finish"); } /** * Global AfterSuite * <p> * <ol> * <li>Stop the DefaultSelenium client</li> * </ol> * * @throws HarnessException */ @AfterSuite( groups = { "always" } ) public void commonTestAfterSuite() throws HarnessException { logger.info("commonTestAfterSuite: start"); ClientSessionFactory.session().selenium().stop(); logger.info("commonTestAfterSuite: finish"); } /** * Global AfterClass * * @throws HarnessException */ @AfterClass( groups = { "always" } ) public void commonTestAfterClass() throws HarnessException { logger.info("commonTestAfterClass: start"); // For Ajax and Html, if account is considered dirty (modified), // then recreate a new account ZimbraAccount currentAccount = app.zGetActiveAccount(); if (currentAccount != null && currentAccount.accountIsDirty && currentAccount == ZimbraAccount.AccountHTML()) { ZimbraAccount.ResetAccountHTML(); } logger.info("commonTestAfterClass: finish"); } /** * Global AfterMethod * * @throws HarnessException */ @AfterMethod( groups = { "always" } ) public void commonTestAfterMethod() throws HarnessException { logger.info("commonTestAfterMethod: start"); logger.info("commonTestAfterMethod: finish"); } }
3e08e417d9bf7a34f0b1c4de86cb2ef9f159e736
5,894
java
Java
src/test/java/uk/gov/hmcts/reform/bulkscanprocessor/services/storage/LeaseMetaDataCheckerTest.java
uk-gov-mirror/hmcts.bulk-scan-processor
f2152cd3283b2f0b8ee435ba002e789bb2d30c7e
[ "MIT" ]
6
2019-07-31T22:07:51.000Z
2021-05-05T16:05:39.000Z
src/test/java/uk/gov/hmcts/reform/bulkscanprocessor/services/storage/LeaseMetaDataCheckerTest.java
uk-gov-mirror/hmcts.bulk-scan-processor
f2152cd3283b2f0b8ee435ba002e789bb2d30c7e
[ "MIT" ]
1,582
2018-06-22T08:58:47.000Z
2022-03-30T15:36:46.000Z
src/test/java/uk/gov/hmcts/reform/bulkscanprocessor/services/storage/LeaseMetaDataCheckerTest.java
hmcts/bulk-scanning
14d3e15d4b7f7d1d3a5079367c3abad596b5095a
[ "MIT" ]
5
2018-06-29T13:02:43.000Z
2021-04-10T22:36:37.000Z
40.095238
117
0.733627
3,775
package uk.gov.hmcts.reform.bulkscanprocessor.services.storage; import com.azure.core.util.Context; import com.azure.storage.blob.BlobClient; import com.azure.storage.blob.models.BlobProperties; import com.azure.storage.blob.models.BlobRequestConditions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.bulkscanprocessor.config.BlobManagementProperties; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static uk.gov.hmcts.reform.bulkscanprocessor.util.TimeZones.EUROPE_LONDON_ZONE_ID; @ExtendWith(MockitoExtension.class) @SuppressWarnings("unchecked") class LeaseMetaDataCheckerTest { @Mock private BlobClient blobClient; @Mock private BlobProperties blobProperties; @Mock private BlobManagementProperties managementProperties; private Map<String, String> blobMetaData; private static final String LEASE_EXPIRATION_TIME = "leaseExpirationTime"; private LeaseMetaDataChecker leaseMetaDataChecker; @BeforeEach void setUp() { leaseMetaDataChecker = new LeaseMetaDataChecker(managementProperties); blobMetaData = new HashMap<>(); } @Test void should_return_true_when_no_expiry_in_metadata() { //given given(blobClient.getProperties()).willReturn(blobProperties); given(blobProperties.getMetadata()).willReturn(blobMetaData); String etag = "etag-21321312"; given(blobProperties.getETag()).willReturn(etag); int leaseTimeoutISec = 300; given(managementProperties.getBlobLeaseAcquireDelayInSeconds()).willReturn(leaseTimeoutISec); LocalDateTime minExpiryTime = LocalDateTime.now(EUROPE_LONDON_ZONE_ID) .plusSeconds(leaseTimeoutISec); //when boolean isReady = leaseMetaDataChecker.isReadyToUse(blobClient); //then assertThat(isReady).isTrue(); var mapCapturer = ArgumentCaptor.forClass(Map.class); var conditionCapturer = ArgumentCaptor.forClass(BlobRequestConditions.class); verify(blobClient) .setMetadataWithResponse(mapCapturer.capture(), conditionCapturer.capture(), eq(null), eq(Context.NONE)); Map<String, String> map = mapCapturer.getValue(); LocalDateTime leaseExpiresAt = LocalDateTime.parse(map.get(LEASE_EXPIRATION_TIME)); assertThat(minExpiryTime).isBefore(leaseExpiresAt); BlobRequestConditions con = conditionCapturer.getValue(); assertThat(con.getIfMatch()).isEqualTo("\"" + etag + "\""); } @Test void should_return_false_when_expiry_in_metadata_valid() { //given given(blobClient.getProperties()).willReturn(blobProperties); blobMetaData.put(LEASE_EXPIRATION_TIME, LocalDateTime.now(EUROPE_LONDON_ZONE_ID).plusSeconds(40).toString()); given(blobProperties.getMetadata()).willReturn(blobMetaData); //when boolean isReady = leaseMetaDataChecker.isReadyToUse(blobClient); //then assertThat(isReady).isFalse(); verify(blobClient,never()).setMetadataWithResponse(any(), any(), any(), any()); } @Test void should_return_true_when_metadata_lease_expiration_expired() { //given given(blobClient.getProperties()).willReturn(blobProperties); blobMetaData.put(LEASE_EXPIRATION_TIME, LocalDateTime.now(EUROPE_LONDON_ZONE_ID).toString()); given(blobProperties.getMetadata()).willReturn(blobMetaData); given(managementProperties.getBlobLeaseAcquireDelayInSeconds()).willReturn(15); String etag = "etag-21321312"; given(blobProperties.getETag()).willReturn(etag); int leaseTimeoutISec = 10; given(managementProperties.getBlobLeaseAcquireDelayInSeconds()).willReturn(leaseTimeoutISec); LocalDateTime minExpiryTime = LocalDateTime.now(EUROPE_LONDON_ZONE_ID) .plusSeconds(leaseTimeoutISec); //when boolean isReady = leaseMetaDataChecker.isReadyToUse(blobClient); //then assertThat(isReady).isTrue(); var mapCapturer = ArgumentCaptor.forClass(Map.class); var conditionCapturer = ArgumentCaptor.forClass(BlobRequestConditions.class); verify(blobClient) .setMetadataWithResponse(mapCapturer.capture(), conditionCapturer.capture(), eq(null), eq(Context.NONE)); Map<String, String> map = mapCapturer.getValue(); LocalDateTime leaseExpiresAt = LocalDateTime.parse(map.get(LEASE_EXPIRATION_TIME)); assertThat(minExpiryTime).isBefore(leaseExpiresAt); BlobRequestConditions con = conditionCapturer.getValue(); assertThat(con.getIfMatch()).isEqualTo("\"" + etag + "\""); } @Test void should_clear_blob_metadata_when_clear_successful() { //given given(blobClient.getProperties()).willReturn(blobProperties); blobMetaData.put(LEASE_EXPIRATION_TIME, LocalDateTime.now(EUROPE_LONDON_ZONE_ID).plusSeconds(40).toString()); given(blobProperties.getMetadata()).willReturn(blobMetaData); doNothing().when(blobClient).setMetadata(any()); //when leaseMetaDataChecker.clearMetaData(blobClient); //then var metaDataCaptor = ArgumentCaptor.forClass(Map.class); verify(blobClient).setMetadata(metaDataCaptor.capture()); assertThat(metaDataCaptor.getValue()).isEmpty(); } }
3e08e4e1cea84b711196a8961801c29972a36cf5
259
java
Java
goVoz/src/main/java/com/gotako/govoz/data/Emoticon.java
rfcclub/govoz
1a275fab23cbb883eef83497967f6b11078aeb16
[ "Apache-2.0" ]
null
null
null
goVoz/src/main/java/com/gotako/govoz/data/Emoticon.java
rfcclub/govoz
1a275fab23cbb883eef83497967f6b11078aeb16
[ "Apache-2.0" ]
null
null
null
goVoz/src/main/java/com/gotako/govoz/data/Emoticon.java
rfcclub/govoz
1a275fab23cbb883eef83497967f6b11078aeb16
[ "Apache-2.0" ]
null
null
null
17.266667
46
0.629344
3,776
package com.gotako.govoz.data; import android.net.Uri; public class Emoticon { public String url; public String code; public Emoticon() {} public Emoticon(String url, String code) { this.url = url; this.code = code; } }
3e08e543de15086d3f70a60c0f7135838b27506a
9,024
java
Java
src/java/soaprmi/soaprpc/soaprmi/server/UnicastRemoteObject.java
SZUE/xsoap
6c282d0687afb6cd3678943b0758277302d08ba8
[ "xpp" ]
null
null
null
src/java/soaprmi/soaprpc/soaprmi/server/UnicastRemoteObject.java
SZUE/xsoap
6c282d0687afb6cd3678943b0758277302d08ba8
[ "xpp" ]
null
null
null
src/java/soaprmi/soaprpc/soaprmi/server/UnicastRemoteObject.java
SZUE/xsoap
6c282d0687afb6cd3678943b0758277302d08ba8
[ "xpp" ]
null
null
null
36.682927
100
0.675864
3,777
/* -*- mode: Java; c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ /* * Copyright (c) 2002 Extreme! Lab, Indiana University. All rights reserved. * * This software is open source. See the bottom of this file for the licence. * * $Id: UnicastRemoteObject.java,v 1.12 2003/04/06 00:04:19 aslom Exp $ */ package soaprmi.server; import soaprmi.AlreadyBoundException; import soaprmi.Remote; import soaprmi.RemoteException; import soaprmi.port.Port; import soaprmi.soaprpc.SoapServices; import soaprmi.util.Check; import soaprmi.util.logging.Logger; /** * Base class to create SOAP web services with RMI approach. * * @version $Revision: 1.12 $ * @author <a href="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a> */ public class UnicastRemoteObject extends RemoteObject { private static Logger l = Logger.getLogger(); //private static SoapServerFactory factory = HttpSocketSoapServerFactory.getDefault(); private static Services defaultServices = SoapServices.getDefault(); public UnicastRemoteObject() throws RemoteException { exportObject(this); } public UnicastRemoteObject(int port) throws RemoteException { exportObject(this, port); } public UnicastRemoteObject(String portName) throws RemoteException { exportObject(this, portName); } public UnicastRemoteObject(int port, String portName) throws RemoteException { exportObject(this, port, portName); } public UnicastRemoteObject(int port, String portName, Class[] ifaces ) throws RemoteException { exportObject(this, port, portName, ifaces); } public UnicastRemoteObject(String portName, Class[] ifaces) throws RemoteException { exportObject(this, portName, ifaces); } public UnicastRemoteObject(Class[] ifaces) throws RemoteException { exportObject(this, ifaces); } // // public static SoapServerFactory getSoapServerFactory() { // return factory; // } // // public static void setSoapServerFactory(SoapServerFactory value) { // factory = value; // } public static Services getDefaultServices() throws RemoteException { return defaultServices; } public static void setDefaultServices(Services services) throws RemoteException { defaultServices = services; } public static RemoteRef exportObject(Remote obj, Services services, String portName, Class[] ifaces) throws RemoteException { //register object with default dispatcher (from emebedded soap server) //if(services == SoapServices.getDefault()) startDefaultServer(); try { Port port = services.createPort( portName, ifaces, obj ); RemoteRef ref = services.createStartpoint(port); //for RemoteObject it should be always ref == this ... if(Check.ON && RemoteObject.class.isAssignableFrom(obj.getClass())) Check.assertion(ref == obj); return ref; } catch(AlreadyBoundException ex) { throw new RemoteException( "cant create port for already bound unicast remote object", ex); //} catch(NotBoundException ex) { // throw new RemoteException("cant create remote referenece to port", ex); } } public static RemoteRef exportObject(Remote obj, int port, String portName, Class[] ifaces ) throws RemoteException { Services services = SoapServices.newInstance(port); // this servie is PRIVATE so it is crucial to use default mappings DIRECTLY!!! services.setMapping(soaprmi.soap.Soap.getDefault().getMapping()); // try { // SoapServer server = factory.newSoapServer(port); // //server.setPort(port); // SoapDispatcher dsptr = server.getDispatcher(); // services.addDispatcher(dsptr); // //if(Log.ON) l.fine( // // "remote object starting embedded web server "+server); // server.startServer(); // if(Log.ON) l.fine( // "remote object web server started "+server+" on "+server.getServerPort()); // } catch(IOException ioe) { // throw new ServerException("could not start embedded saerver on port "+port, ioe); // } RemoteRef ref = exportObject(obj, services, portName, ifaces); return ref; } public static RemoteRef exportObject(Remote obj, int port, String portName) throws RemoteException { Class[] ifaces = obj.getClass().getInterfaces(); return exportObject(obj, port, portName, ifaces); } public static RemoteRef exportObject(Remote obj, int port) throws RemoteException { Services services = getDefaultServices(); Class[] ifaces = obj.getClass().getInterfaces(); return exportObject(obj, port, services.createGUID(), ifaces); } public static RemoteRef exportObject(Remote obj, Services services) throws RemoteException { Class[] ifaces = obj.getClass().getInterfaces(); return exportObject(obj, services, services.createGUID(), ifaces); } public static RemoteRef exportObject(Remote obj, String portName, Class[] ifaces) throws RemoteException { Services services = getDefaultServices(); return exportObject(obj, services, portName, ifaces); } public static RemoteRef exportObject(Remote obj, String portName) throws RemoteException { Class[] ifaces = obj.getClass().getInterfaces(); return exportObject(obj, portName, ifaces); } public static RemoteRef exportObject(Remote obj, Class[] ifaces) throws RemoteException { Services services = getDefaultServices(); return exportObject(obj, services.createGUID(), ifaces); } public static RemoteRef exportObject(Remote obj) throws RemoteException { Services services = getDefaultServices(); return exportObject(obj, services.createGUID()); } } /* * Indiana University Extreme! Lab Software License, Version 1.2 * * Copyright (C) 2002 The Trustees of Indiana University. * 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) All redistributions of source code must retain the above * copyright notice, the list of authors in the original source * code, this list of conditions and the disclaimer listed in this * license; * * 2) All redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the disclaimer * listed in this license in the documentation and/or other * materials provided with the distribution; * * 3) Any documentation included with all redistributions must include * the following acknowledgement: * * "This product includes software developed by the Indiana * University Extreme! Lab. For further information please visit * http://www.extreme.indiana.edu/" * * Alternatively, this acknowledgment may appear in the software * itself, and wherever such third-party acknowledgments normally * appear. * * 4) The name "Indiana University" or "Indiana University * Extreme! Lab" shall not be used to endorse or promote * products derived from this software without prior written * permission from Indiana University. For written permission, * please contact http://www.extreme.indiana.edu/. * * 5) Products derived from this software may not use "Indiana * University" name nor may "Indiana University" appear in their name, * without prior written permission of the Indiana University. * * Indiana University provides no reassurances that the source code * provided does not infringe the patent or any other intellectual * property rights of any other entity. Indiana University disclaims any * liability to any recipient for claims brought by any other entity * based on infringement of intellectual property rights or otherwise. * * LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH * NO WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA * UNIVERSITY GIVES NO WARRANTIES AND MAKES NO REPRESENTATION THAT * SOFTWARE IS FREE OF INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR * OTHER PROPRIETARY RIGHTS. INDIANA UNIVERSITY MAKES NO WARRANTIES THAT * SOFTWARE IS FREE FROM "BUGS", "VIRUSES", "TROJAN HORSES", "TRAP * DOORS", "WORMS", OR OTHER HARMFUL CODE. LICENSEE ASSUMES THE ENTIRE * RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR ASSOCIATED MATERIALS, * AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION GENERATED USING * SOFTWARE. */
3e08e57328672a579980472af08962dcbf9fcbd0
1,557
java
Java
JDBC_Demo/src/main/java/com/chen/jdbc/jdbc_1.java
turbohiro/kotlin_learning
55268b5c1c5e202641fd1acfce4e842d8567f9e0
[ "MIT" ]
null
null
null
JDBC_Demo/src/main/java/com/chen/jdbc/jdbc_1.java
turbohiro/kotlin_learning
55268b5c1c5e202641fd1acfce4e842d8567f9e0
[ "MIT" ]
null
null
null
JDBC_Demo/src/main/java/com/chen/jdbc/jdbc_1.java
turbohiro/kotlin_learning
55268b5c1c5e202641fd1acfce4e842d8567f9e0
[ "MIT" ]
null
null
null
29.377358
98
0.554271
3,778
package com.chen.jdbc; import com.mysql.jdbc.Driver; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class jdbc_1 { public static void main(String [] args){ Statement statement=null; Connection connection=null; //1.注册驱动,把连接mysql类的字节码加载到JVM try { DriverManager.registerDriver(new Driver()); //2.要想连接数据库连接驱动 String url="jdbc:mysql://localhost:3306/turbo?useUnicode=true&characterEncoding=utf8"; String username= "root"; String password = "asd13247167823"; connection = DriverManager.getConnection(url,username,password); //System.out.print(connection); //获得数据库连接 //3.往其中一个表添加记录(更新数据) statement = connection.createStatement(); String sql = "insert into student values (2, 'chen',89,90,91)"; int result = statement.executeUpdate(sql); //执行mysql语言 System.out.println("result = "+result); } catch (SQLException e) { e.printStackTrace(); }finally { //最后需要释放掉statement和connection try { if(statement!=null){ statement.close(); //statement= null; } if(statement!=null){ connection.close(); //connection = null; } } catch(SQLException e) { e.printStackTrace(); } } } }
3e08e69d713ebb80a173bc2d9a03bd0eb2a1073d
5,125
java
Java
src/main/java/net/bither/utils/ExchangeUtil.java
bitcoinboy/bither
2d0931586cde6df84142c7f3225e3ad410955541
[ "Apache-2.0" ]
66
2015-01-07T05:35:58.000Z
2022-03-05T07:00:48.000Z
src/main/java/net/bither/utils/ExchangeUtil.java
bitcoinboy/bither
2d0931586cde6df84142c7f3225e3ad410955541
[ "Apache-2.0" ]
11
2015-02-18T10:34:19.000Z
2020-05-10T14:42:08.000Z
src/main/java/net/bither/utils/ExchangeUtil.java
bitcoinboy/bither
2d0931586cde6df84142c7f3225e3ad410955541
[ "Apache-2.0" ]
59
2015-01-07T05:36:05.000Z
2021-12-11T11:19:47.000Z
31.832298
108
0.611122
3,779
/* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.utils; import net.bither.bitherj.BitherjSettings.MarketType; import net.bither.bitherj.utils.Utils; import net.bither.preference.UserPreference; import org.apache.commons.lang.StringEscapeUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.AbstractMap; import java.util.HashMap; public class ExchangeUtil { private ExchangeUtil() { } public static String[] exchangeNames = new String[]{ "USD", "CNY", "EUR", "GBP", "JPY", "KRW", "CAD", "AUD" }; public static Currency getCurrency(int index) { if (index >= 0 && index < Currency.values().length) { return Currency.values()[index]; } else { return Currency.USD; } } public enum Currency { USD("USD", "$"), CNY("CNY", StringEscapeUtils.unescapeHtml("&yen;")), EUR("EUR", "€"), GBP("GBP", "£"), JPY("JPY", StringEscapeUtils.unescapeHtml("&yen;")), KRW("KRW", "₩"), CAD("CAD", "C$"), AUD("AUD", "A$"); private String symbol; private String name; private Currency(String name, String symbol) { this.name = name; this.symbol = symbol; } public String getSymbol() { return symbol; } public String getName() { return name; } } private static double mRate = -1; private static AbstractMap<Currency, Double> mCurrenciesRate = null; public static void setCurrenciesRate(JSONObject currenciesRateJSon) throws Exception { mCurrenciesRate = parseCurrenciesRate(currenciesRateJSon); File file = FileUtil.getCurrenciesRateFile(); Utils.writeFile(currenciesRateJSon.toString().getBytes(), file); } public static AbstractMap<Currency, Double> getCurrenciesRate() { if (mCurrenciesRate == null) { File file = FileUtil.getCurrenciesRateFile(); String rateString = Utils.readFile(file); try { JSONObject json = new JSONObject(rateString); mCurrenciesRate = parseCurrenciesRate(json); } catch (JSONException ex) { mCurrenciesRate = null; } } return mCurrenciesRate; } private static AbstractMap<Currency, Double> parseCurrenciesRate(JSONObject json) throws JSONException { HashMap<Currency, Double> currencyDoubleHashMap = new HashMap<Currency, Double>(); currencyDoubleHashMap.put(Currency.USD, 1.0); for (Currency currency : Currency.values()) { if (!json.isNull(currency.getName())) { currencyDoubleHashMap.put(currency, json.getDouble(currency.getName())); } } return currencyDoubleHashMap; } public static double getRate(Currency currency) { Currency defaultCurrency = UserPreference.getInstance() .getDefaultCurrency(); double rate = 1; if (currency != defaultCurrency) { double preRate = getCurrenciesRate().get(currency); double defaultRate = getCurrenciesRate().get(defaultCurrency); rate = defaultRate / preRate; } return rate; } public static double getRate(MarketType marketType) { Currency defaultCurrency = UserPreference.getInstance() .getDefaultCurrency(); Currency currency = getExchangeType(marketType); double rate = 1; if (currency != defaultCurrency) { double preRate = getCurrenciesRate().get(currency); double defaultRate = getCurrenciesRate().get(defaultCurrency); rate = defaultRate / preRate; } return rate; } public static double getRate() { Currency defaultCurrency = UserPreference.getInstance() .getDefaultCurrency(); return getCurrenciesRate().get(defaultCurrency); } public static Currency getExchangeType(MarketType marketType) { switch (marketType) { case HUOBI: case OKCOIN: case BTCCHINA: case CHBTC: case BTCTRADE: return Currency.CNY; case MARKET796: case BTCE: case BITSTAMP: case BITFINEX: case COINBASE: return Currency.USD; default: break; } return Currency.CNY; } }
3e08e80c777ed3d8c11e8fb341c143cd670c0134
1,219
java
Java
src/main/java/frc/robot/commands/Transporter/TransportEject.java
FutureShock7130/2022-RapidReact-Robot-Code
473d153ffe360d2f55e6d4f803881a36d529ed6b
[ "BSD-3-Clause" ]
5
2022-03-09T08:24:15.000Z
2022-03-12T07:06:33.000Z
src/main/java/frc/robot/commands/Transporter/TransportEject.java
FutureShock7130/2022-RapidReact-Robot-Code
473d153ffe360d2f55e6d4f803881a36d529ed6b
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/Transporter/TransportEject.java
FutureShock7130/2022-RapidReact-Robot-Code
473d153ffe360d2f55e6d4f803881a36d529ed6b
[ "BSD-3-Clause" ]
null
null
null
27.704545
74
0.747334
3,780
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.Transporter; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.Constants.TransporterConstants; import frc.robot.subsystems.Transporter; public class TransportEject extends CommandBase { Transporter transporter; /** Creates a new intakeCmd. */ public TransportEject(Transporter m_robotTransporter) { transporter = m_robotTransporter; // Use addRequirements() here to declare subsystem dependencies. addRequirements(transporter); } // Called when the command is initially scheduled. @Override public void initialize() { } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { transporter.transportEject(TransporterConstants.transportSpeed); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { } // Returns true when the command should end. @Override public boolean isFinished() { return false; } }
3e08e98d935621da11f6e4c42b375423a95b5eb1
4,407
java
Java
web-services/common-util/src/test/java/datawave/security/util/DnUtilsTest.java
lbschanno/datawave
54bc4b8dc8f59d2cf52b50e54191e43d988f38f6
[ "Apache-2.0" ]
435
2018-02-01T16:06:14.000Z
2022-03-29T10:36:20.000Z
web-services/common-util/src/test/java/datawave/security/util/DnUtilsTest.java
lbschanno/datawave
54bc4b8dc8f59d2cf52b50e54191e43d988f38f6
[ "Apache-2.0" ]
901
2018-02-01T16:04:55.000Z
2022-03-28T16:35:49.000Z
web-services/common-util/src/test/java/datawave/security/util/DnUtilsTest.java
lbschanno/datawave
54bc4b8dc8f59d2cf52b50e54191e43d988f38f6
[ "Apache-2.0" ]
233
2018-02-01T15:49:55.000Z
2022-03-31T05:23:39.000Z
37.991379
96
0.648741
3,781
package datawave.security.util; import static org.junit.Assert.assertEquals; import java.util.Collection; import org.junit.Test; import com.google.common.collect.Lists; public class DnUtilsTest { @Test public void testBuildNormalizedProxyDN() { String expected = "sdn<idn>"; String actual = DnUtils.buildNormalizedProxyDN("SDN", "IDN", null, null); assertEquals(expected, actual); expected = "sdn1<idn1><sdn2><idn2>"; actual = DnUtils.buildNormalizedProxyDN("SDN1", "IDN1", "SDN2", "IDN2"); assertEquals(expected, actual); expected = "sdn1<idn1><sdn2><idn2><sdn3><idn3>"; actual = DnUtils.buildNormalizedProxyDN("SDN1", "IDN1", "SDN2<SDN3>", "IDN2<IDN3>"); assertEquals(expected, actual); expected = "sdn1<idn1><sdn2><idn2><sdn3><idn3>"; actual = DnUtils.buildNormalizedProxyDN("SDN1", "IDN1", "<SDN2><SDN3>", "<IDN2><IDN3>"); assertEquals(expected, actual); } @Test public void testBuildNormalizedDN() { Collection<String> expected = Lists.newArrayList("sdn", "idn"); Collection<String> actual = DnUtils.buildNormalizedDNList("SDN", "IDN", null, null); assertEquals(expected, actual); expected = Lists.newArrayList("sdn1", "idn1", "sdn2", "idn2"); actual = DnUtils.buildNormalizedDNList("SDN1", "IDN1", "SDN2", "IDN2"); assertEquals(expected, actual); expected = Lists.newArrayList("sdn1", "idn1", "sdn2", "idn2", "sdn3", "idn3"); actual = DnUtils.buildNormalizedDNList("SDN1", "IDN1", "SDN2<SDN3>", "IDN2<IDN3>"); assertEquals(expected, actual); expected = Lists.newArrayList("sdn1", "idn1", "sdn2", "idn2", "sdn3", "idn3"); actual = DnUtils.buildNormalizedDNList("SDN1", "IDN1", "<SDN2><SDN3>", "<IDN2><IDN3>"); assertEquals(expected, actual); } @Test public void testGetUserDnFromArray() { String userDnForTest = "snd1"; String[] array = new String[] {userDnForTest, "idn"}; String userDN = DnUtils.getUserDN(array); assertEquals(userDnForTest, userDN); } @Test(expected = IllegalArgumentException.class) public void testTest() { String[] dns = new String[] {"sdn"}; DnUtils.getUserDN(dns, true); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedProxyDNTooMissingIssuers() { DnUtils.buildNormalizedProxyDN("SDN", "IDN", "SDN2<SDN3>", null); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedProxyDNTooFewIssuers() { DnUtils.buildNormalizedProxyDN("SDN", "IDN", "SDN2<SDN3>", "IDN2"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedProxyDNTooFewSubjects() { DnUtils.buildNormalizedProxyDN("SDN", "IDN", "SDN2", "IDN2<IDN3>"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedProxyDNSubjectEqualsIssuer() { DnUtils.buildNormalizedProxyDN("SDN", "IDN", "SDN2", "SDN2"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedProxyDNSubjectDNInIssuer() { DnUtils.buildNormalizedProxyDN("SDN", "IDN", "SDN2", "CN=foo,OU=My Department"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedDNListTooMissingIssuers() { DnUtils.buildNormalizedDNList("SDN", "IDN", "SDN2<SDN3>", null); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedDNListTooFewIssuers() { DnUtils.buildNormalizedDNList("SDN", "IDN", "SDN2<SDN3>", "IDN2"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedDNListTooFewSubjects() { DnUtils.buildNormalizedDNList("SDN", "IDN", "SDN2", "IDN2<IDN3>"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedDNListSubjectEqualsIssuer() { DnUtils.buildNormalizedDNList("SDN", "IDN", "SDN2", "SDN2"); } @Test(expected = IllegalArgumentException.class) public void testBuildNormalizedDNListSubjectDNInIssuer() { DnUtils.buildNormalizedDNList("SDN", "IDN", "SDN2", "CN=foo,OU=My Department"); } }
3e08ead1870bc845fea0bcb8d86fcba44d435491
666
java
Java
springboot-feature/src/main/java/top/huzhurong/boot/feature/servlet/bean/FilterBean.java
chenshun00/jsp
e7862a3904b6c417cfffd47814058efe5baa4a21
[ "MIT" ]
null
null
null
springboot-feature/src/main/java/top/huzhurong/boot/feature/servlet/bean/FilterBean.java
chenshun00/jsp
e7862a3904b6c417cfffd47814058efe5baa4a21
[ "MIT" ]
null
null
null
springboot-feature/src/main/java/top/huzhurong/boot/feature/servlet/bean/FilterBean.java
chenshun00/jsp
e7862a3904b6c417cfffd47814058efe5baa4a21
[ "MIT" ]
null
null
null
22.3
132
0.707025
3,782
package top.huzhurong.boot.feature.servlet.bean; import lombok.extern.slf4j.Slf4j; import javax.servlet.*; import java.io.IOException; /** * @author [email protected] * @since 2019/1/4 */ @Slf4j public class FilterBean implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info("FilterBean init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.info("FilterBean doFilter"); chain.doFilter(request, response); } @Override public void destroy() { } }
3e08ebaa47a20da37c1addba3e4d4ab8b9b4a357
9,844
java
Java
byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodDelegationConstructionTest.java
scordio/byte-buddy
90afb6039d420a43682dbc3055765355b87eb094
[ "Apache-2.0" ]
4,962
2015-01-05T12:39:16.000Z
2022-03-31T22:33:40.000Z
byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodDelegationConstructionTest.java
chefdd/byte-buddy
7a41b53d7023ae047be63c8cef2871fd5860b032
[ "Apache-2.0" ]
1,138
2015-01-15T03:55:52.000Z
2022-03-30T22:17:06.000Z
byte-buddy-dep/src/test/java/net/bytebuddy/implementation/MethodDelegationConstructionTest.java
chefdd/byte-buddy
7a41b53d7023ae047be63c8cef2871fd5860b032
[ "Apache-2.0" ]
704
2015-01-15T13:35:58.000Z
2022-03-29T07:28:20.000Z
29.473054
164
0.613978
3,783
package net.bytebuddy.implementation; import net.bytebuddy.ByteBuddy; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.test.utility.CallTraceable; import org.hamcrest.CoreMatchers; import org.hamcrest.Matcher; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collection; import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; @RunWith(Parameterized.class) public class MethodDelegationConstructionTest<T extends CallTraceable> { private static final String FOO = "foo", BAR = "bar"; private static final byte BYTE_MULTIPLICATOR = 3; private static final short SHORT_MULTIPLICATOR = 3; private static final char CHAR_MULTIPLICATOR = 3; private static final int INT_MULTIPLICATOR = 3; private static final long LONG_MULTIPLICATOR = 3L; private static final float FLOAT_MULTIPLICATOR = 3f; private static final double DOUBLE_MULTIPLICATOR = 3d; private static final boolean DEFAULT_BOOLEAN = false; private static final byte DEFAULT_BYTE = 1; private static final short DEFAULT_SHORT = 1; private static final char DEFAULT_CHAR = 1; private static final int DEFAULT_INT = 1; private static final long DEFAULT_LONG = 1L; private static final float DEFAULT_FLOAT = 1f; private static final double DEFAULT_DOUBLE = 1d; private final Class<T> sourceType; private final Class<?> targetType; private final Class<?>[] parameterTypes; private final Object[] arguments; private final Matcher<?> matcher; public MethodDelegationConstructionTest(Class<T> sourceType, Class<?> targetType, Class<?>[] parameterTypes, Object[] arguments, Matcher<?> matcher) { this.sourceType = sourceType; this.targetType = targetType; this.parameterTypes = parameterTypes; this.arguments = arguments; this.matcher = matcher; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {BooleanSource.class, BooleanTarget.class, new Class<?>[]{boolean.class}, new Object[]{DEFAULT_BOOLEAN}, is(!DEFAULT_BOOLEAN)}, {ByteSource.class, ByteTarget.class, new Class<?>[]{byte.class}, new Object[]{DEFAULT_BYTE}, is((byte) (DEFAULT_BYTE * BYTE_MULTIPLICATOR))}, {ShortSource.class, ShortTarget.class, new Class<?>[]{short.class}, new Object[]{DEFAULT_SHORT}, is((short) (DEFAULT_SHORT * SHORT_MULTIPLICATOR))}, {CharSource.class, CharTarget.class, new Class<?>[]{char.class}, new Object[]{DEFAULT_CHAR}, is((char) (DEFAULT_CHAR * CHAR_MULTIPLICATOR))}, {IntSource.class, IntTarget.class, new Class<?>[]{int.class}, new Object[]{DEFAULT_INT}, is(DEFAULT_INT * INT_MULTIPLICATOR)}, {LongSource.class, LongTarget.class, new Class<?>[]{long.class}, new Object[]{DEFAULT_LONG}, is(DEFAULT_LONG * LONG_MULTIPLICATOR)}, {FloatSource.class, FloatTarget.class, new Class<?>[]{float.class}, new Object[]{DEFAULT_FLOAT}, is(DEFAULT_FLOAT * FLOAT_MULTIPLICATOR)}, {DoubleSource.class, DoubleTarget.class, new Class<?>[]{double.class}, new Object[]{DEFAULT_DOUBLE}, is(DEFAULT_DOUBLE * DOUBLE_MULTIPLICATOR)}, {VoidSource.class, VoidTarget.class, new Class<?>[0], new Object[0], nullValue()}, {StringSource.class, StringTarget.class, new Class<?>[]{String.class}, new Object[]{FOO}, is(FOO + BAR)}, }); } @Test @SuppressWarnings("unchecked") public void testConstruction() throws Exception { DynamicType.Loaded<T> loaded = new ByteBuddy() .subclass(sourceType) .method(isDeclaredBy(sourceType)) .intercept(MethodDelegation.toConstructor(targetType)) .make() .load(sourceType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); T instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(sourceType))); assertThat(instance, instanceOf(sourceType)); Object value = loaded.getLoaded().getDeclaredMethod(FOO, parameterTypes).invoke(instance, arguments); assertThat(value, instanceOf(targetType)); Field field = targetType.getDeclaredField("value"); field.setAccessible(true); assertThat(field.get(value), (Matcher) matcher); instance.assertZeroCalls(); } public static class BooleanSource extends CallTraceable { @SuppressWarnings("unused") public BooleanTarget foo(boolean b) { register(FOO); return null; } } public static class BooleanTarget { @SuppressWarnings("unused") private final boolean value; public BooleanTarget(boolean value) { this.value = !value; } } public static class ByteSource extends CallTraceable { @SuppressWarnings("unused") public ByteTarget foo(byte b) { register(FOO); return null; } } public static class ByteTarget { @SuppressWarnings("unused") private final byte value; public ByteTarget(byte b) { value = bar(b); } private static byte bar(byte b) { return (byte) (b * BYTE_MULTIPLICATOR); } } public static class ShortSource extends CallTraceable { @SuppressWarnings("unused") public ShortTarget foo(short s) { register(FOO); return null; } } public static class ShortTarget { @SuppressWarnings("unused") private final short value; public ShortTarget(short s) { this.value = bar(s); } private static short bar(short s) { return (short) (s * SHORT_MULTIPLICATOR); } } public static class CharSource extends CallTraceable { @SuppressWarnings("unused") public CharTarget foo(char s) { register(FOO); return null; } } public static class CharTarget { @SuppressWarnings("unused") private final char value; public CharTarget(char c) { this.value = bar(c); } private static char bar(char c) { return (char) (c * CHAR_MULTIPLICATOR); } } public static class IntSource extends CallTraceable { @SuppressWarnings("unused") public IntTarget foo(int i) { register(FOO); return null; } } public static class IntTarget { @SuppressWarnings("unused") private final int value; public IntTarget(int i) { this.value = bar(i); } private static int bar(int i) { return i * INT_MULTIPLICATOR; } } public static class LongSource extends CallTraceable { @SuppressWarnings("unused") public LongTarget foo(long l) { register(FOO); return null; } } public static class LongTarget { @SuppressWarnings("unused") private final long value; public LongTarget(long l) { this.value = bar(l); } private static long bar(long l) { return l * LONG_MULTIPLICATOR; } } public static class FloatSource extends CallTraceable { @SuppressWarnings("unused") public FloatTarget foo(float f) { register(FOO); return null; } } public static class FloatTarget { @SuppressWarnings("unused") private final float value; public FloatTarget(float f) { this.value = bar(f); } private static float bar(float f) { return f * FLOAT_MULTIPLICATOR; } } public static class DoubleSource extends CallTraceable { @SuppressWarnings("unused") public DoubleTarget foo(double d) { register(FOO); return null; } } public static class DoubleTarget { @SuppressWarnings("unused") private final double value; public DoubleTarget(double d) { this.value = bar(d); } public static double bar(double d) { return d * DOUBLE_MULTIPLICATOR; } } public static class VoidSource extends CallTraceable { public VoidTarget foo() { register(FOO); return null; } } public static class VoidTarget { @SuppressWarnings("unused") private final Void value = null; } public static class StringSource extends CallTraceable { public StringTarget foo(String s) { register(FOO); return null; } } public static class StringTarget { @SuppressWarnings("unused") private final String value; public StringTarget(String s) { this.value = bar(s); } public static String bar(String s) { return s + BAR; } } }
3e08ed80f6a96a5a82c5e9be2de3251ab0fb1ea3
351
java
Java
v1/code/java/jvmgo_java/ch05/src/main/java/com/github/jvmgo/instructions/base/Index16Instruction.java
yiyan1992/jvmgo-book
e34da71e8925b9a1ca0ab9085d0d762f07bc7862
[ "MIT" ]
1,401
2016-01-09T16:00:14.000Z
2022-03-29T08:50:44.000Z
v1/code/java/jvmgo_java/ch05/src/main/java/com/github/jvmgo/instructions/base/Index16Instruction.java
yiyan1992/jvmgo-book
e34da71e8925b9a1ca0ab9085d0d762f07bc7862
[ "MIT" ]
38
2016-08-21T03:40:55.000Z
2021-12-31T11:57:09.000Z
v1/code/java/jvmgo_java/ch05/src/main/java/com/github/jvmgo/instructions/base/Index16Instruction.java
yiyan1992/jvmgo-book
e34da71e8925b9a1ca0ab9085d0d762f07bc7862
[ "MIT" ]
553
2016-06-13T07:08:29.000Z
2022-03-29T01:56:57.000Z
19.5
65
0.723647
3,784
package com.github.jvmgo.instructions.base; import com.github.jvmgo.rtda.Frame; public abstract class Index16Instruction implements Instruction { private int index; @Override public void fetchOperands(BytecodeReader reader) { this.index = reader.read16(); } @Override public abstract void execute(Frame frame); }
3e08edadcff805d63aab3cee9dd1a95f0599ae71
2,557
java
Java
adito-core/src/main/java/com/adito/policyframework/DefaultPolicy.java
OldsSourcesBackups/adito
8b09921c2bec26db4ef60b4ac6ce1346a7c44b42
[ "Apache-2.0" ]
3
2016-08-23T05:21:47.000Z
2017-01-29T11:42:41.000Z
adito-core/src/main/java/com/adito/policyframework/DefaultPolicy.java
OldsSourcesBackups/adito
8b09921c2bec26db4ef60b4ac6ce1346a7c44b42
[ "Apache-2.0" ]
1
2015-02-19T10:33:19.000Z
2015-10-30T20:03:06.000Z
adito-core/src/main/java/com/adito/policyframework/DefaultPolicy.java
toepi/adito
8b09921c2bec26db4ef60b4ac6ce1346a7c44b42
[ "Apache-2.0" ]
7
2015-02-18T11:36:51.000Z
2022-03-20T04:36:24.000Z
29.390805
176
0.630817
3,785
package com.adito.policyframework; import java.util.Calendar; import java.util.List; import com.adito.core.UserDatabaseManager; import com.adito.security.Role; import com.adito.security.User; public class DefaultPolicy extends AbstractResource implements Policy { private int type; private boolean addToFavorite = false; private int attachedUsers = 0; private int attachedGroups = 0; /** * Create a blank policy * * @param selectedRealmId */ public DefaultPolicy(int selectedRealmId) { this(-1, "", "", Policy.TYPE_INVISIBLE, Calendar.getInstance(), Calendar.getInstance(), selectedRealmId); } /** * Create a new empty policy of the specified type, ID and name. * @param realmID * @param uniqueId policy id * @param name name of policy * @param description description * @param type type * @param dateCreated the date / time this policy was created * @param dateAmended the date / time this policy was last amended */ public DefaultPolicy(int uniqueId, String name, String description, int type, Calendar dateCreated, Calendar dateAmended, int realmID) { super(realmID, PolicyConstants.POLICY_RESOURCE_TYPE, uniqueId, name, description, dateCreated, dateAmended); try { this.type = type; List<Principal> principalsGrantedPolicy = PolicyDatabaseFactory.getInstance().getPrincipalsGrantedPolicy(this, UserDatabaseManager.getInstance().getRealm(realmID)); for (Principal principal : principalsGrantedPolicy) { if (principal instanceof User){ attachedUsers ++; } else if (principal instanceof Role){ attachedGroups ++; } } } catch (Exception e) { throw new RuntimeException(e); } } /* * (non-Javadoc) * * @see com.adito.policyframework.Policy#getType() */ public int getType() { return type; } /* (non-Javadoc) * @see com.adito.policyframework.Policy#setType(int) */ public void setType(int type) { this.type = type; } public boolean isAddToFavorite() { return addToFavorite; } public void setAddToFavorite(boolean addToFavorite) { this.addToFavorite = addToFavorite; } public int getAttachedGroups() { return attachedGroups; } public int getAttachedUsers() { return attachedUsers; } }
3e08f003a69ce453d95a623e7a28d11ab70c3dab
2,279
java
Java
src/main/java/com/pavikumbhar/mqtt/configuration/MqttSubcriberConfig.java
pavikumbhar/spring-boot-mqtt-integration
4a2d7db39c2dd66165e4827e07c8cef9500ba975
[ "Apache-2.0" ]
1
2020-07-26T10:19:04.000Z
2020-07-26T10:19:04.000Z
src/main/java/com/pavikumbhar/mqtt/configuration/MqttSubcriberConfig.java
pavikumbhar/spring-boot-mqtt-intgration
4a2d7db39c2dd66165e4827e07c8cef9500ba975
[ "Apache-2.0" ]
null
null
null
src/main/java/com/pavikumbhar/mqtt/configuration/MqttSubcriberConfig.java
pavikumbhar/spring-boot-mqtt-intgration
4a2d7db39c2dd66165e4827e07c8cef9500ba975
[ "Apache-2.0" ]
null
null
null
35.061538
116
0.835015
3,786
package com.pavikumbhar.mqtt.configuration; import java.util.Random; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.core.MessageProducer; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter; import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter; import org.springframework.messaging.MessageChannel; /** * * @author pavikumbhar * */ @Configuration public class MqttSubcriberConfig { public static final String MQTT_MAIL_INPUT_CHANNEL = "mqttMailInputChannel"; public static final String MQTT_COMMENT_INPUT_CHANNEL = "mqttCommentInputChannel"; @Autowired private MqttProperties mqttProp; @Autowired private MqttPahoClientFactory mqttPahoClientFactory; @Bean public MessageChannel mqttMailInputChannel() { return new DirectChannel(); } @Bean public MessageProducer mailMessageProducer() { MqttPahoMessageDrivenChannelAdapter mailMessageProducer = new MqttPahoMessageDrivenChannelAdapter( mqttProp.getClientId() + new Random().nextInt(), mqttPahoClientFactory, mqttProp.getMailSubscriptionTopic()); mailMessageProducer.setCompletionTimeout(mqttProp.getConnectionTimeout()); mailMessageProducer.setConverter(new DefaultPahoMessageConverter()); mailMessageProducer.setOutputChannel(mqttMailInputChannel()); return mailMessageProducer; } @Bean public MessageChannel mqttCommentInputChannel() { return new DirectChannel(); } @Bean public MessageProducer commentMessageProducer() { MqttPahoMessageDrivenChannelAdapter commentMessageProducer = new MqttPahoMessageDrivenChannelAdapter( mqttProp.getClientId() + new Random().nextInt(), mqttPahoClientFactory, mqttProp.getCommentSubscriptionTopic()); commentMessageProducer.setCompletionTimeout(mqttProp.getConnectionTimeout()); commentMessageProducer.setConverter(new DefaultPahoMessageConverter()); commentMessageProducer.setOutputChannel(mqttCommentInputChannel()); return commentMessageProducer; } }
3e08f060137edcd6a4d8eb31b8ef40b77a52cd9e
1,349
java
Java
gestalt-module/src/main/java/org/terasology/gestalt/module/predicates/FromModule.java
BenjaminAmos/gestalt
fc5e69a197eb37456284fb80ea1dd7d53b3d410c
[ "Apache-2.0" ]
29
2015-04-19T18:12:46.000Z
2022-03-25T17:52:31.000Z
gestalt-module/src/main/java/org/terasology/gestalt/module/predicates/FromModule.java
BenjaminAmos/gestalt
fc5e69a197eb37456284fb80ea1dd7d53b3d410c
[ "Apache-2.0" ]
59
2015-03-26T13:37:06.000Z
2022-03-01T22:56:26.000Z
gestalt-module/src/main/java/org/terasology/gestalt/module/predicates/FromModule.java
BenjaminAmos/gestalt
fc5e69a197eb37456284fb80ea1dd7d53b3d410c
[ "Apache-2.0" ]
26
2015-03-03T09:39:30.000Z
2021-03-22T19:35:30.000Z
29.977778
79
0.739066
3,787
/* * Copyright 2019 MovingBlocks * * 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.terasology.gestalt.module.predicates; import org.terasology.gestalt.module.ModuleEnvironment; import org.terasology.gestalt.naming.Name; import java.util.Objects; import java.util.function.Predicate; /** * Predicate for filtering classes to those from a specific module. * * @author Immortius */ public class FromModule implements Predicate<Class<?>> { private final ModuleEnvironment environment; private final Name moduleId; public FromModule(ModuleEnvironment environment, Name moduleId) { this.environment = environment; this.moduleId = moduleId; } @Override public boolean test(Class<?> input) { return Objects.equals(environment.getModuleProviding(input), moduleId); } }
3e08f16a0fea5ddb40e3c356fcb44ba0551642ef
4,188
java
Java
src/main/java/com/kiselev/enemy/network/vk/api/request/GroupsRequest.java
vadim8kiselev/public-enemy
e1a9fe8008228249858c258a001e79c908bb65c0
[ "MIT" ]
1
2021-09-17T11:03:34.000Z
2021-09-17T11:03:34.000Z
src/main/java/com/kiselev/enemy/network/vk/api/request/GroupsRequest.java
vadim8kiselev/public-enemy
e1a9fe8008228249858c258a001e79c908bb65c0
[ "MIT" ]
1
2020-12-25T23:59:26.000Z
2020-12-25T23:59:26.000Z
src/main/java/com/kiselev/enemy/network/vk/api/request/GroupsRequest.java
vadim8kiselev/public-enemy
e1a9fe8008228249858c258a001e79c908bb65c0
[ "MIT" ]
null
null
null
36.103448
374
0.661891
3,788
package com.kiselev.enemy.network.vk.api.request; import com.kiselev.enemy.network.vk.api.response.GroupResponse; import com.vk.api.sdk.objects.groups.Fields; import com.vk.api.sdk.objects.groups.Filter; import java.util.Collections; import java.util.List; /** * Query for Groups.get method */ public class GroupsRequest extends ApiRequest<GroupsRequest, GroupResponse> { /** * Creates a ApiRequest instance that can be used to build api request with various parameters * * @param token access token */ public GroupsRequest(String token) { super(token, "groups.get", GroupResponse.class); } /** * User ID. * * @param value value of "user id" parameter. Minimum is 0. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest userId(String value) { return unsafeParam("user_id", value); } /** * '1' — to return complete information about a user's communities, '0' — to return a list of community IDs without any additional fields (default), * * @param value value of "extended" parameter. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest extended(Boolean value) { return unsafeParam("extended", value); } /** * Offset needed to return a specific subset of communities. * * @param value value of "offset" parameter. Minimum is 0. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest offset(Integer value) { return unsafeParam("offset", value); } /** * Number of communities to return. * * @param value value of "count" parameter. Maximum is 1000. Minimum is 0. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest count(Integer value) { return unsafeParam("count", value); } /** * filter * Types of communities to return: 'admin' — to return communities administered by the user , 'editor' — to return communities where the user is an administrator or editor, 'moder' — to return communities where the user is an administrator, editor, or moderator, 'groups' — to return only groups, 'publics' — to return only public pages, 'events' — to return only events * * @param value value of "filter" parameter. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest filter(Filter... value) { return unsafeParam("filter", value); } /** * Types of communities to return: 'admin' — to return communities administered by the user , 'editor' — to return communities where the user is an administrator or editor, 'moder' — to return communities where the user is an administrator, editor, or moderator, 'groups' — to return only groups, 'publics' — to return only public pages, 'events' — to return only events * * @param value value of "filter" parameter. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest filter(List<Filter> value) { return unsafeParam("filter", value); } /** * fields * Profile fields to return. * * @param value value of "fields" parameter. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest fields(Fields... value) { return unsafeParam("fields", value); } /** * Profile fields to return. * * @param value value of "fields" parameter. * @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern. */ public GroupsRequest fields(List<Fields> value) { return unsafeParam("fields", value); } @Override protected GroupsRequest getThis() { return this; } @Override protected List<String> essentialKeys() { return Collections.singletonList("access_token"); } }
3e08f2d78d4f08d2e1a2ee680e49cd987707d10d
1,373
java
Java
qinsql-main/src/main/java/com/facebook/presto/sql/gen/CacheStatsMBean.java
codefollower/QinSQL
d85650206b3d2d7374520d344e4745fe1847b2a5
[ "Apache-2.0" ]
9,782
2016-03-18T15:16:19.000Z
2022-03-31T07:49:41.000Z
qinsql-main/src/main/java/com/facebook/presto/sql/gen/CacheStatsMBean.java
codefollower/QinSQL
d85650206b3d2d7374520d344e4745fe1847b2a5
[ "Apache-2.0" ]
10,310
2016-03-18T01:03:00.000Z
2022-03-31T23:54:08.000Z
qinsql-main/src/main/java/com/facebook/presto/sql/gen/CacheStatsMBean.java
codefollower/QinSQL
d85650206b3d2d7374520d344e4745fe1847b2a5
[ "Apache-2.0" ]
3,803
2016-03-18T22:54:24.000Z
2022-03-31T07:49:46.000Z
25.425926
81
0.690459
3,789
/* * 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.facebook.presto.sql.gen; import com.google.common.cache.LoadingCache; import org.weakref.jmx.Managed; import static java.util.Objects.requireNonNull; public class CacheStatsMBean { private final LoadingCache<?, ?> loadingCache; public CacheStatsMBean(LoadingCache<?, ?> loadingCache) { this.loadingCache = requireNonNull(loadingCache, "loadingCache is null"); } @Managed public long size() { return loadingCache.size(); } @Managed public Double getHitRate() { return loadingCache.stats().hitRate(); } @Managed public Double getMissRate() { return loadingCache.stats().missRate(); } @Managed public long getRequestCount() { return loadingCache.stats().requestCount(); } }
3e08f2fed87ce4a2c0fa878f2373341147a3fc5a
1,524
java
Java
src/main/java/mchorse/mappet/client/gui/GuiCraftingTableScreen.java
Evanechecssss/mappet
42baada8fed5e7ed088e2d6202bed0eb15e8a906
[ "MIT" ]
14
2021-04-07T10:54:16.000Z
2021-12-05T14:32:58.000Z
src/main/java/mchorse/mappet/client/gui/GuiCraftingTableScreen.java
Evanechecssss/mappet
42baada8fed5e7ed088e2d6202bed0eb15e8a906
[ "MIT" ]
10
2021-05-10T20:00:55.000Z
2022-03-10T19:25:31.000Z
src/main/java/mchorse/mappet/client/gui/GuiCraftingTableScreen.java
Evanechecssss/mappet
42baada8fed5e7ed088e2d6202bed0eb15e8a906
[ "MIT" ]
12
2021-04-07T10:54:21.000Z
2022-02-06T12:38:27.000Z
26.275862
112
0.704068
3,790
package mchorse.mappet.client.gui; import mchorse.mappet.api.crafting.CraftingTable; import mchorse.mappet.client.gui.crafting.GuiCrafting; import mchorse.mappet.client.gui.crafting.ICraftingScreen; import mchorse.mappet.network.Dispatcher; import mchorse.mappet.network.common.crafting.PacketCraftingTable; import mchorse.mclib.client.gui.framework.GuiBase; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; public class GuiCraftingTableScreen extends GuiBase implements ICraftingScreen { public GuiCrafting crafting; public GuiCraftingTableScreen(CraftingTable table) { super(); Minecraft mc = Minecraft.getMinecraft(); this.crafting = new GuiCrafting(mc); this.crafting.set(table); this.crafting.flex().relative(this.viewport).y(20).w(1F).h(1F, -20); this.root.add(this.crafting); } @Override public boolean doesGuiPauseGame() { return false; } @Override public void refresh() { this.crafting.refresh(); } @Override protected void closeScreen() { super.closeScreen(); Dispatcher.sendToServer(new PacketCraftingTable(null)); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); super.drawScreen(mouseX, mouseY, partialTicks); this.drawCenteredString(this.fontRenderer, this.crafting.get().title, this.viewport.mx(), 11, 0xffffff); } }
3e08f30f49013df8cb4e8a1ee8ddee3b49dc8732
1,006
java
Java
src/main/java/com/ruoyi/common/feign/initdata/controller/InitDataController.java
rainey520/onestation
84f502eaac6dcd3780e8d4cd5415b32e87a70d94
[ "MIT" ]
null
null
null
src/main/java/com/ruoyi/common/feign/initdata/controller/InitDataController.java
rainey520/onestation
84f502eaac6dcd3780e8d4cd5415b32e87a70d94
[ "MIT" ]
2
2021-04-22T16:59:14.000Z
2021-09-20T20:53:34.000Z
src/main/java/com/ruoyi/common/feign/initdata/controller/InitDataController.java
rainey520/onestation
84f502eaac6dcd3780e8d4cd5415b32e87a70d94
[ "MIT" ]
null
null
null
29.588235
64
0.717694
3,791
package com.ruoyi.common.feign.initdata.controller; import com.ruoyi.common.feign.initdata.domain.InitData; import com.ruoyi.common.feign.initdata.service.IInitDataService; import com.ruoyi.framework.web.domain.AjaxResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 初始用户公司信息 */ @RestController public class InitDataController { @Autowired private IInitDataService iInitDataService; /** * 初始化公司用户数据 * @param initData 封装接收数据 * @return */ @RequestMapping("/init/data") public AjaxResult initData(@RequestBody InitData initData){ try { iInitDataService.initData(initData); return AjaxResult.success(); }catch (Exception e){ e.printStackTrace(); return AjaxResult.error(); } } }
3e08f343d928b2d6a0c46e2d05164387de831638
574
java
Java
src/main/java/mbtw/mbtw/mixin/block/LitStateInvoker.java
eragaxshim/mbtw
546bcb9d28db11d13c156886dafe1ea6f79d61bd
[ "CC-BY-4.0" ]
3
2021-02-20T04:57:05.000Z
2021-03-26T04:46:23.000Z
src/main/java/mbtw/mbtw/mixin/block/LitStateInvoker.java
eragaxshim/mbtw
546bcb9d28db11d13c156886dafe1ea6f79d61bd
[ "CC-BY-4.0" ]
6
2021-02-26T10:06:24.000Z
2021-12-15T17:58:01.000Z
src/main/java/mbtw/mbtw/mixin/block/LitStateInvoker.java
eragaxshim/mbtw
546bcb9d28db11d13c156886dafe1ea6f79d61bd
[ "CC-BY-4.0" ]
null
null
null
28.7
89
0.801394
3,792
package mbtw.mbtw.mixin.block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.world.explosion.Explosion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import java.util.function.ToIntFunction; @Mixin(Blocks.class) public interface LitStateInvoker { @Invoker("createLightLevelFromBlockState") static ToIntFunction<BlockState> invokeCreateLightLevelFromBlockState(int litLevel) { throw new AssertionError(); } }
3e08f3db839ff78a265be6b468d064d9fa54230f
523
java
Java
src/main/java/com/dacn/logicsticservice/repository/WeightRankRepository.java
quangnghiauit/logistics-service
4d97a54a41bd34126d4353f092d1f174cdcb3300
[ "MIT" ]
null
null
null
src/main/java/com/dacn/logicsticservice/repository/WeightRankRepository.java
quangnghiauit/logistics-service
4d97a54a41bd34126d4353f092d1f174cdcb3300
[ "MIT" ]
null
null
null
src/main/java/com/dacn/logicsticservice/repository/WeightRankRepository.java
quangnghiauit/logistics-service
4d97a54a41bd34126d4353f092d1f174cdcb3300
[ "MIT" ]
null
null
null
37.357143
107
0.81262
3,793
package com.dacn.logicsticservice.repository; import com.dacn.logicsticservice.model.WeightRank; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface WeightRankRepository extends JpaRepository<WeightRank, Integer> { @Query(value = "select * from weightrank where weightmin < ?1 and weightmax >= ?1", nativeQuery = true) WeightRank getWeightRankByWeight(float weight); }
3e08f47abb56369311eec3e86a96b93c3b904cee
1,240
java
Java
compiler/src/main/java/com/digitoygames/compiler/model/op/If.java
mozsakalli/GamaVM
50732c192e352efbe5e944877fa030e8beecd0f2
[ "Apache-2.0" ]
null
null
null
compiler/src/main/java/com/digitoygames/compiler/model/op/If.java
mozsakalli/GamaVM
50732c192e352efbe5e944877fa030e8beecd0f2
[ "Apache-2.0" ]
null
null
null
compiler/src/main/java/com/digitoygames/compiler/model/op/If.java
mozsakalli/GamaVM
50732c192e352efbe5e944877fa030e8beecd0f2
[ "Apache-2.0" ]
null
null
null
26.382979
75
0.667742
3,794
/* * Copyright (C) 2019 Digitoy Games. * * 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.digitoygames.compiler.model.op; import com.digitoygames.compiler.model.Method; import com.digitoygames.compiler.model.Stack; /** * * @author mustafa */ public class If extends Branch { public String right; public String operand; public int elsePC; @Override public void execute(Method method, Stack stack) { code = "if("; String r = right == null ? stack.pop().value : right; code += stack.pop().value+operand+r+") goto BB"+(pc+offset); } @Override public String toString() { return "IF -> "+(pc+offset)+" else "+elsePC; } }
3e08f4ae6b2644023e502dda480a5f343e0a58ce
5,725
java
Java
jfugue-android/src/main/java/org/jfugue/temporal/TemporalPLP.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
67
2015-01-03T22:34:54.000Z
2021-07-07T12:11:40.000Z
jfugue-android/src/main/java/org/jfugue/temporal/TemporalPLP.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
10
2015-01-01T20:38:17.000Z
2021-06-27T18:02:14.000Z
jfugue-android/src/main/java/org/jfugue/temporal/TemporalPLP.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
24
2015-04-01T16:21:11.000Z
2022-02-15T07:26:36.000Z
30.614973
98
0.674061
3,795
/* * JFugue, an Application Programming Interface (API) for Music Programming * http://www.jfugue.org * * Copyright (C) 2003-2014 David Koelle * * 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.jfugue.temporal; import java.util.List; import java.util.Map; import java.util.Set; import org.jfugue.parser.Parser; import org.jfugue.parser.ParserListener; import org.jfugue.theory.Chord; import org.jfugue.theory.Note; public class TemporalPLP extends Parser implements ParserListener { private TemporalEventManager eventManager; private TemporalEvents events; public TemporalPLP() { super(); this.events = new TemporalEvents(); this.eventManager = new TemporalEventManager(); } public Map<Long, List<TemporalEvent>> getTimeToEventMap() { return eventManager.getTimeToEventMap(); } /* ParserListener Events */ @Override public void beforeParsingStarts() { this.eventManager.reset(); } @Override public void afterParsingFinished() { this.eventManager.finish(); } @Override public void onTrackChanged(byte track) { this.eventManager.setCurrentTrack(track); this.eventManager.addRealTimeEvent(events.new TrackEvent(track)); } @Override public void onLayerChanged(byte layer) { this.eventManager.setCurrentLayer(layer); this.eventManager.addRealTimeEvent(events.new LayerEvent(layer)); } @Override public void onInstrumentParsed(byte instrument) { this.eventManager.addRealTimeEvent(events.new InstrumentEvent(instrument)); } @Override public void onTempoChanged(int tempoBPM) { this.eventManager.setTempo(tempoBPM); this.eventManager.addRealTimeEvent(events.new TempoEvent(tempoBPM)); } @Override public void onKeySignatureParsed(byte key, byte scale) { this.eventManager.addRealTimeEvent(events.new KeySignatureEvent(key, scale)); } @Override public void onTimeSignatureParsed(byte numerator, byte powerOfTwo) { this.eventManager.addRealTimeEvent(events.new TimeSignatureEvent(numerator, powerOfTwo)); } @Override public void onBarLineParsed(long time) { this.eventManager.addRealTimeEvent(events.new BarEvent(time)); } @Override public void onTrackBeatTimeBookmarked(String timeBookmarkID) { this.eventManager.addTrackTickTimeBookmark(timeBookmarkID); } @Override public void onTrackBeatTimeBookmarkRequested(String timeBookmarkID) { double time = this.eventManager.getTrackBeatTimeBookmark(timeBookmarkID); this.eventManager.setTrackBeatTime(time); } @Override public void onTrackBeatTimeRequested(double time) { this.eventManager.setTrackBeatTime(time); } @Override public void onPitchWheelParsed(byte lsb, byte msb) { this.eventManager.addRealTimeEvent(events.new PitchWheelEvent(lsb, msb)); } @Override public void onChannelPressureParsed(byte pressure) { this.eventManager.addRealTimeEvent(events.new ChannelPressureEvent(pressure)); } @Override public void onPolyphonicPressureParsed(byte key, byte pressure) { this.eventManager.addRealTimeEvent(events.new PolyphonicPressureEvent(key, pressure)); } @Override public void onSystemExclusiveParsed(byte... bytes) { this.eventManager.addRealTimeEvent(events.new SystemExclusiveEvent(bytes)); } @Override public void onControllerEventParsed(byte controller, byte value) { this.eventManager.addRealTimeEvent(events.new ControllerEvent(controller, value)); } @Override public void onLyricParsed(String lyric) { this.eventManager.addRealTimeEvent(events.new LyricEvent(lyric)); } @Override public void onMarkerParsed(String marker) { this.eventManager.addRealTimeEvent(events.new MarkerEvent(marker)); } @Override public void onFunctionParsed(String id, Object message) { this.eventManager.addRealTimeEvent(events.new UserEvent(id, message)); } @Override public void onNoteParsed(Note note) { this.eventManager.addRealTimeEvent(events.new NoteEvent(note)); } @Override public void onChordParsed(Chord chord) { this.eventManager.addRealTimeEvent(events.new ChordEvent(chord)); } private void delay(long millis) { try { Thread.sleep(millis); } catch (Exception e) { // An exception? Ain't no one got time for that! } } public void parse() { fireBeforeParsingStarts(); long oldTime = 0; Set<Long> times = this.eventManager.getTimeToEventMap().keySet(); for (long time : times) { delay(time - oldTime); oldTime = time; for (TemporalEvent event : this.eventManager.getTimeToEventMap().get(time)) { event.execute(this); } } fireAfterParsingFinished(); } }
3e08f5058188bf48981efbb90f9bdd2259018f5b
3,616
java
Java
plugin/src/main/java/net/mcjukebox/plugin/bukkit/managers/RegionManager.java
GrangerTheDog/JukeboxAPI
3075e9ab3c6f56e86ab0c43a626cf5729feccbb6
[ "MIT" ]
21
2016-01-21T20:31:06.000Z
2022-02-22T13:46:14.000Z
plugin/src/main/java/net/mcjukebox/plugin/bukkit/managers/RegionManager.java
GrangerTheDog/JukeboxAPI
3075e9ab3c6f56e86ab0c43a626cf5729feccbb6
[ "MIT" ]
54
2016-01-19T22:09:47.000Z
2021-10-31T21:33:21.000Z
plugin/src/main/java/net/mcjukebox/plugin/bukkit/managers/RegionManager.java
GrangerTheDog/JukeboxAPI
3075e9ab3c6f56e86ab0c43a626cf5729feccbb6
[ "MIT" ]
40
2015-12-26T19:58:19.000Z
2021-08-19T17:21:10.000Z
33.481481
112
0.617257
3,796
package net.mcjukebox.plugin.bukkit.managers; import lombok.Getter; import net.mcjukebox.plugin.bukkit.MCJukebox; import net.mcjukebox.plugin.bukkit.api.JukeboxAPI; import net.mcjukebox.plugin.bukkit.managers.shows.ShowManager; import net.mcjukebox.plugin.bukkit.utils.DataUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.UUID; public class RegionManager implements Listener { @Getter private HashMap<String, String> regions; private String folder; public RegionManager(){ folder = MCJukebox.getInstance().getDataFolder() + ""; load(); } private void load(){ regions = DataUtils.loadObjectFromPath(folder + "/regions.data"); if(regions == null) regions = new HashMap<>(); // Import from the "shared.data" file we accidentally created HashMap<String, String> sharedFile = DataUtils.loadObjectFromPath(folder + "/shared.data"); if (sharedFile != null) { MCJukebox.getInstance().getLogger().info("Running migration of shared.data regions..."); for (String key : sharedFile.keySet()) regions.put(key, sharedFile.get(key)); new File(folder + "/shared.data").delete(); MCJukebox.getInstance().getLogger().info("Migration complete."); } } public int importFromOA() { try { File configFile = new File("plugins/OpenAudioMc/config.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); ConfigurationSection regionConfig = config.getConfigurationSection("storage.regions"); int added = 0; for (String region : regionConfig.getKeys(false)) { String url = regionConfig.getString(region + ".src"); if (url.length() > 0 && !url.contains(" ")) { regions.put(region.toLowerCase(), url); added++; } } return added; } catch (Exception ex) { return 0; } } public void save(){ DataUtils.saveObjectToPath(regions, folder + "/regions.data"); } public void addRegion(String ID, String URL){ regions.put(ID.toLowerCase(), URL); } public void removeRegion(String ID){ ShowManager showManager = MCJukebox.getInstance().getShowManager(); HashMap<UUID, String> playersInRegion = MCJukebox.getInstance().getRegionListener().getPlayerInRegion(); Iterator<UUID> keys = playersInRegion.keySet().iterator(); while (keys.hasNext()) { UUID uuid = keys.next(); String regionID = playersInRegion.get(uuid); if (regionID.equals(ID)) { Player player = Bukkit.getPlayer(uuid); if (player == null) continue; if (regions.get(ID).charAt(0) == '@') { showManager.getShow(regions.get(ID)).removeMember(player); } else { JukeboxAPI.stopMusic(player); keys.remove(); } } } regions.remove(ID); } public HashMap<String, String> getRegions() { return this.regions; } public boolean hasRegion(String ID){ return regions.containsKey(ID); } public String getURL(String ID){ return regions.get(ID); } }
3e08f5d016b12e9925a90237913275ec8b0e9335
16,864
java
Java
app/src/main/java/com/example/meeting2020/Meeting/MeetingManageActivity.java
henkishandsome/MeetingAndrew
b2f0e4363366c76fafa724fc74820859376b0037
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/meeting2020/Meeting/MeetingManageActivity.java
henkishandsome/MeetingAndrew
b2f0e4363366c76fafa724fc74820859376b0037
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/meeting2020/Meeting/MeetingManageActivity.java
henkishandsome/MeetingAndrew
b2f0e4363366c76fafa724fc74820859376b0037
[ "Apache-2.0" ]
1
2020-04-22T00:25:12.000Z
2020-04-22T00:25:12.000Z
47.909091
197
0.519806
3,797
package com.example.meeting2020.Meeting; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.example.meeting2020.Bean.Meeting; import com.example.meeting2020.Comment.SpeakerListActivity; import com.example.meeting2020.HttpConnect.HttpUtilsHttpURLConnection; import com.example.meeting2020.JavaClass.Data; import com.example.meeting2020.MainActivity; import com.example.meeting2020.R; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.lang.ref.WeakReference; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import okhttp3.Response; public class MeetingManageActivity extends AppCompatActivity { private Button button1, button2, submit, delete, remark, signinList; private Integer myear, mmonth, mday, mhour, mminute; private LocalDateTime localDateTime = null; private EditText theme, place, introduce; private TextView date, time, number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_meeting_manage); button1 = findViewById(R.id.btn1); button2 = findViewById(R.id.btn2); submit = findViewById(R.id.submit); delete = findViewById(R.id.delete); remark = findViewById(R.id.remark); signinList = findViewById(R.id.signinList); theme = findViewById(R.id.theme); place = findViewById(R.id.place); introduce = findViewById(R.id.introduce); date = findViewById(R.id.text2); time = findViewById(R.id.text3); number = findViewById(R.id.number); Integer meetingId = null; final Bundle bundle = getIntent().getExtras(); Meeting meeting = null; if (bundle != null) { meeting = (Meeting) bundle.getSerializable("meeting"); } if (meeting != null) { theme.setText(meeting.getTheme()); place.setText(meeting.getPlace()); introduce.setText(meeting.getIntroduce()); DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss"); meeting.getTime().format(dft); date.setText(meeting.getTime().toLocalDate().toString()); time.setText(" " + meeting.getTime().toLocalTime().toString()); number.setText(String.valueOf(meeting.getSigninnumber())); localDateTime = meeting.getTime(); meetingId = meeting.getMeetingid(); } else { delete.setVisibility(View.GONE); } button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar c = Calendar.getInstance(); // 直接创建一个DatePickerDialog对话框实例,并将它显示出来 new DatePickerDialog(MeetingManageActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, // 绑定监听器 new DatePickerDialog.OnDateSetListener() { String month = null, day = null; @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { myear = year; mmonth = monthOfYear + 1; mday = dayOfMonth; if (mmonth < 10) { month = "0" + mmonth; } else { month = mmonth.toString(); } if (mday < 10) { day = "0" + mday; } else { day = mday.toString(); } date.setText(year + "-" + month + "-" + day); } } // 设置初始日期 , c.get(Calendar.YEAR), c.get(Calendar.MONTH), c .get(Calendar.DAY_OF_MONTH)).show(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar c = Calendar.getInstance(); new TimePickerDialog(MeetingManageActivity.this, AlertDialog.THEME_HOLO_LIGHT, // 绑定监听器 new TimePickerDialog.OnTimeSetListener() { String hour = null, tminute = null; @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { mhour = hourOfDay; mminute = minute; if (mhour < 10) { hour = "0" + mhour; } else { hour = mhour.toString(); } if (mminute < 10) { tminute = "0" + mminute; } else { tminute = mminute.toString(); } time.setText(" " + hour + ":" + tminute); } } // 设置初始时间 , c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), // true表示采用24小时制 true).show(); } }); final Integer finalMeetingId = meetingId; remark.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (finalMeetingId == null) { new AlertDialog.Builder(MeetingManageActivity.this).setTitle("提示").setMessage("请先提交会议").setPositiveButton("确认", null).show(); } else { startActivity(new Intent(MeetingManageActivity.this, SpeakerListActivity.class).putExtras(bundle)); } } }); submit.setOnClickListener(new View.OnClickListener() { private final Data app = (Data) getApplication(); String mtheme, mplace, mintroduce; Integer meetingid = finalMeetingId; @Override public void onClick(View v) { final Meeting meeting = new Meeting(); mtheme = theme.getText().toString(); mplace = place.getText().toString(); mintroduce = introduce.getText().toString(); AlertDialog.Builder builder = new AlertDialog.Builder(MeetingManageActivity.this).setTitle("提示").setMessage("是否确认提交?").setPositiveButton("确认", null).setNegativeButton("取消", null); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String hour = null, minute = null, month = null, day = null; @Override public void onClick(View v) { if (localDateTime == null && (myear != null && mmonth != null && mday != null && mday != null && mhour != null && mminute != null && theme.getText().toString() != null && theme.getText().toString() != "" && place.getText().toString() != null && place.getText().toString() != "")) { if (mmonth < 10) { month = "0" + mmonth; } else { month = mmonth.toString(); } if (mday < 10) { day = "0" + mday; } else { day = mday.toString(); } if (mhour < 10 || mminute < 10) { if (mhour < 10 && mminute < 10) { hour = "0" + mhour; minute = "0" + mminute; localDateTime = LocalDateTime.parse(myear + "-" + month + "-" + day + " " + hour + ":" + minute + ":00", df); } if (mhour < 10 && mminute >= 10) { hour = "0" + mhour; localDateTime = LocalDateTime.parse(myear + "-" + month + "-" + day + " " + hour + ":" + mminute + ":00", df); } if (mminute < 10 && mhour >= 10) { minute = "0" + mminute; localDateTime = LocalDateTime.parse(myear + "-" + month + "-" + day + " " + mhour + ":" + minute + ":00", df); } } else { localDateTime = LocalDateTime.parse(myear + "-" + month + "-" + day + " " + mhour + ":" + mminute + ":00", df); } meeting.setPublisherid(app.getUserInfo().getWorkid()); meeting.setPublisher(app.getUserInfo().getName()); meeting.setTheme(mtheme); meeting.setPlace(mplace); meeting.setIntroduce(mintroduce); meeting.setSigninnumber(0); meeting.setTime(localDateTime); MeetingManageAsyncTask meetingManageAsyncTask = new MeetingManageAsyncTask(new WeakReference<MeetingManageActivity>(MeetingManageActivity.this)); meetingManageAsyncTask.execute(meeting); } else if (localDateTime != null) { meeting.setMeetingid(meetingid); meeting.setPublisherid(app.getUserInfo().getWorkid()); meeting.setPublisher(app.getUserInfo().getName()); meeting.setTheme(mtheme); meeting.setPlace(mplace); meeting.setIntroduce(mintroduce); meeting.setTime(localDateTime); MeetingManageAsyncTask meetingManageAsyncTask = new MeetingManageAsyncTask(new WeakReference<MeetingManageActivity>(MeetingManageActivity.this)); meetingManageAsyncTask.execute(meeting); } else { new AlertDialog.Builder(MeetingManageActivity.this).setTitle("提示").setMessage("请将信息补充完整").setPositiveButton("确认", null).show(); } } }); } }); delete.setOnClickListener(new View.OnClickListener() { Integer meetingid = finalMeetingId; @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(MeetingManageActivity.this).setTitle("提示").setMessage("是否确认取消会议?").setPositiveButton("确认", null).setNegativeButton("取消", null); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MeetingDeleteAsyncTask meetingDeleteAsyncTask = new MeetingDeleteAsyncTask(new WeakReference<MeetingManageActivity>(MeetingManageActivity.this)); meetingDeleteAsyncTask.execute(meetingid); } }); } }); signinList.setOnClickListener(new View.OnClickListener() { Integer meetingid = finalMeetingId; @Override public void onClick(View v) { if (meetingid == null) { Toast.makeText(MeetingManageActivity.this, "暂无名单!", Toast.LENGTH_LONG).show(); } else { startActivity(new Intent(MeetingManageActivity.this, SigninedUserListActivity.class).putExtras(bundle)); } } }); } private static class MeetingManageAsyncTask extends AsyncTask<Meeting, Void, String> { private final WeakReference<MeetingManageActivity> weakActivity; private MeetingManageAsyncTask(WeakReference<MeetingManageActivity> weakActivity) { this.weakActivity = weakActivity; } @Override protected String doInBackground(Meeting... meetings) { MeetingManageActivity activity = weakActivity.get(); String url = HttpUtilsHttpURLConnection.BASE_URL + "meeting/manageMeeting.do"; JSONObject jsonObject = (JSONObject) JSONObject.toJSON(meetings[0]); String result = HttpUtilsHttpURLConnection.getContextByHttp(url, jsonObject); JSONObject json = JSONObject.parseObject(result); if (json.getString("result").equals("success")) { activity.startActivity(new Intent(activity, MainActivity.class)); return "success"; } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); MeetingManageActivity activity = weakActivity.get(); if (s == null) { Toast.makeText(activity, "操作失败,请重试!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, "操作成功", Toast.LENGTH_LONG).show(); activity.finish(); } if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // activity死亡了,不再做任何的事情 return; } } } private static class MeetingDeleteAsyncTask extends AsyncTask<Integer, Void, String> { private final WeakReference<MeetingManageActivity> weakActivity; MeetingDeleteAsyncTask(WeakReference<MeetingManageActivity> weakActivity) { this.weakActivity = weakActivity; } @Override protected String doInBackground(Integer... integers) { MeetingManageActivity activity = weakActivity.get(); String url = HttpUtilsHttpURLConnection.BASE_URL + "meeting/deleteMeeting.do"; Map<String, String> map = new HashMap<String, String>(); map.put("meetingid", integers[0].toString()); String result = HttpUtilsHttpURLConnection.getContextByHttp1(url, map); JSONObject json = JSONObject.parseObject(result); if (json.getString("result").equals("success")) { activity.startActivity(new Intent(activity, MainActivity.class)); return "success"; } return "failed"; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); MeetingManageActivity activity = weakActivity.get(); if (s.equals("success")) { Toast.makeText(activity, "取消会议成功", Toast.LENGTH_LONG).show(); activity.finish(); } else { Toast.makeText(activity, "取消会议失败,请重试!", Toast.LENGTH_LONG).show(); } if (activity == null || activity.isFinishing() || activity.isDestroyed()) { // activity死亡了,不再做任何的事情 return; } // The activity is still valid, do main-thread stuff here } } }
3e08f6336e7d4b7ffbf6d00e2e8f7a1093cd6003
2,377
java
Java
javatests/dagger/internal/codegen/Compilers.java
blackboat1/dagger2
fd231d901f6f4d8f8344b4ae0dc963c3b6bd5bd3
[ "Apache-2.0" ]
2
2020-10-28T06:01:47.000Z
2021-05-09T18:33:39.000Z
javatests/dagger/internal/codegen/Compilers.java
blackboat1/dagger2
fd231d901f6f4d8f8344b4ae0dc963c3b6bd5bd3
[ "Apache-2.0" ]
1
2020-03-05T06:20:38.000Z
2020-03-05T06:20:38.000Z
javatests/dagger/internal/codegen/Compilers.java
blackboat1/dagger2
fd231d901f6f4d8f8344b4ae0dc963c3b6bd5bd3
[ "Apache-2.0" ]
null
null
null
38.967213
95
0.751367
3,798
/* * Copyright (C) 2016 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.internal.codegen; import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR; import static com.google.testing.compile.Compiler.javac; import static java.util.stream.Collectors.joining; import com.google.auto.value.processor.AutoAnnotationProcessor; import com.google.common.base.Splitter; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.testing.compile.Compiler; import javax.annotation.processing.Processor; /** {@link Compiler} instances for testing Dagger. */ final class Compilers { private static final String GUAVA = "guava"; static final ImmutableList<String> CLASS_PATH_WITHOUT_GUAVA_OPTION = ImmutableList.of( "-classpath", Splitter.on(PATH_SEPARATOR.value()).splitToList(JAVA_CLASS_PATH.value()).stream() .filter(jar -> !jar.contains(GUAVA)) .collect(joining(PATH_SEPARATOR.value()))); /** * Returns a compiler that runs the Dagger and {@code @AutoAnnotation} processors, along with * extras. */ static Compiler daggerCompiler(Processor... extraProcessors) { ImmutableList.Builder<Processor> processors = ImmutableList.builder(); processors.add(new ComponentProcessor(), new AutoAnnotationProcessor()); processors.add(extraProcessors); return javac().withProcessors(processors.build()); } static Compiler compilerWithOptions(CompilerMode... compilerModes) { FluentIterable<String> options = FluentIterable.of(); for (CompilerMode compilerMode : compilerModes) { options = options.append(compilerMode.javacopts()); } return daggerCompiler().withOptions(options); } }
3e08f6e0a92265a712b0b6ae0b55cd5588fa696c
727
java
Java
src/test/java/models/DeveloperTest.java
K-Banks/game-reviewer
a0d167692f7b260213e5bc6f9bb0b4c825eae05c
[ "MIT" ]
null
null
null
src/test/java/models/DeveloperTest.java
K-Banks/game-reviewer
a0d167692f7b260213e5bc6f9bb0b4c825eae05c
[ "MIT" ]
null
null
null
src/test/java/models/DeveloperTest.java
K-Banks/game-reviewer
a0d167692f7b260213e5bc6f9bb0b4c825eae05c
[ "MIT" ]
null
null
null
26.925926
68
0.696011
3,799
package models; import org.junit.Test; import static org.junit.Assert.*; public class DeveloperTest { @Test public void newDeveloper_instantiatesCorrectly_true() { Developer testDeveloper = new Developer("Parker Brothers"); assertTrue(testDeveloper instanceof Developer); } @Test public void newDeveloper_instantiatesWithName_parkerborthers() { Developer testDeveloper = new Developer("Parker Brothers"); assertEquals("Parker Brothers", testDeveloper.getName()); } @Test public void setId_setsId_1() { Developer testDeveloper = new Developer("Parker Brothers"); testDeveloper.setId(1); assertEquals(1, testDeveloper.getId()); } }
3e08f913cf5247ed13e757cc2e98648548aedd92
595
java
Java
dConnectSDK/dConnectSDKForAndroid/src/org/deviceconnect/android/cipher/signature/SignatureProc.java
ssdwa/android
377a27c812c8cf783fa01839ec3a442c360b1b7a
[ "MIT" ]
54
2015-05-01T06:41:38.000Z
2021-12-18T22:10:40.000Z
dConnectSDK/dConnectSDKForAndroid/src/org/deviceconnect/android/cipher/signature/SignatureProc.java
ssdwa/android
377a27c812c8cf783fa01839ec3a442c360b1b7a
[ "MIT" ]
38
2015-01-15T09:37:40.000Z
2022-02-23T00:48:53.000Z
dConnectSDK/dConnectSDKForAndroid/src/org/deviceconnect/android/cipher/signature/SignatureProc.java
ssdwa/android
377a27c812c8cf783fa01839ec3a442c360b1b7a
[ "MIT" ]
32
2015-01-15T00:56:57.000Z
2021-10-15T11:54:09.000Z
19.833333
58
0.662185
3,800
/* SignatureProc.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.cipher.signature; /** * Signature生成処理インタフェース. * @author NTT DOCOMO, INC. */ public interface SignatureProc { /** * 公開鍵を設定する. * @param cipherPublicKey 公開鍵 */ void setCipherPublicKey(final String cipherPublicKey); /** * 文字列を暗号化してSignatureを生成する. * * @param string 暗号化する文字列 * @return Signature */ String generateSignature(final String string); }
3e08f999dd949b019663f0269936c205e63685e7
285
java
Java
magichand-common/magichand-common-log/src/main/java/com/magichand/common/log/event/SysLogEvent.java
wolf0931/magichand
d03c4dfabeaa722f00d5341290d3d43602a39bd3
[ "Apache-2.0" ]
null
null
null
magichand-common/magichand-common-log/src/main/java/com/magichand/common/log/event/SysLogEvent.java
wolf0931/magichand
d03c4dfabeaa722f00d5341290d3d43602a39bd3
[ "Apache-2.0" ]
null
null
null
magichand-common/magichand-common-log/src/main/java/com/magichand/common/log/event/SysLogEvent.java
wolf0931/magichand
d03c4dfabeaa722f00d5341290d3d43602a39bd3
[ "Apache-2.0" ]
null
null
null
17.8125
52
0.768421
3,801
package com.magichand.common.log.event; import com.magichand.npms.admin.api.entity.SysLog; import org.springframework.context.ApplicationEvent; /** * @author 系统日志事件 */ public class SysLogEvent extends ApplicationEvent { public SysLogEvent(SysLog source) { super(source); } }
3e08fae157ea2e941bde4c571a5d59941b2f5ea4
11,183
java
Java
src/test/java/systemtests/CardFolderSystemTest.java
afterdusk/cs2103-know-it-all
a816abf800253377fff19766cd9fc4485a0c757c
[ "MIT" ]
null
null
null
src/test/java/systemtests/CardFolderSystemTest.java
afterdusk/cs2103-know-it-all
a816abf800253377fff19766cd9fc4485a0c757c
[ "MIT" ]
null
null
null
src/test/java/systemtests/CardFolderSystemTest.java
afterdusk/cs2103-know-it-all
a816abf800253377fff19766cd9fc4485a0c757c
[ "MIT" ]
null
null
null
38.297945
120
0.723777
3,802
package systemtests; import static guitests.guihandles.WebViewUtil.waitUntilBrowserLoaded; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.knowitall.logic.commands.CommandTestUtil.TEST_FOLDER_INDEX; import static seedu.knowitall.ui.StatusBarFooter.STATUS_IN_FOLDER; import static seedu.knowitall.ui.StatusBarFooter.STATUS_IN_HOME_DIRECTORY; import static seedu.knowitall.ui.StatusBarFooter.STATUS_IN_REPORT_DISPLAY; import static seedu.knowitall.ui.StatusBarFooter.STATUS_IN_TEST_SESSION; import static seedu.knowitall.ui.testutil.GuiTestAssert.assertListMatching; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import guitests.guihandles.BrowserPanelHandle; import guitests.guihandles.CardListPanelHandle; import guitests.guihandles.CommandBoxHandle; import guitests.guihandles.MainMenuHandle; import guitests.guihandles.MainWindowHandle; import guitests.guihandles.ResultDisplayHandle; import guitests.guihandles.StatusBarFooterHandle; import seedu.knowitall.TestApp; import seedu.knowitall.commons.core.index.Index; import seedu.knowitall.logic.commands.ChangeDirectoryCommand; import seedu.knowitall.logic.commands.ClearCommand; import seedu.knowitall.logic.commands.ListCommand; import seedu.knowitall.logic.commands.SearchCommand; import seedu.knowitall.logic.commands.SelectCommand; import seedu.knowitall.model.CardFolder; import seedu.knowitall.model.Model; import seedu.knowitall.testutil.TypicalCards; import seedu.knowitall.ui.CommandBox; /** * A system test class for CardFolder, which provides access to handles of GUI components and helper methods * for test verification. */ public abstract class CardFolderSystemTest { private static final List<String> COMMAND_BOX_DEFAULT_STYLE = Arrays.asList("text-input", "text-field"); private static final List<String> COMMAND_BOX_ERROR_STYLE = Arrays.asList("text-input", "text-field", CommandBox.ERROR_STYLE_CLASS); private MainWindowHandle mainWindowHandle; private TestApp testApp; private SystemTestSetupHelper setupHelper; @BeforeClass public static void setupBeforeClass() { SystemTestSetupHelper.initialize(); } @Before public void setUp() { setupHelper = new SystemTestSetupHelper(); testApp = setupHelper.setupApplication(this::getInitialData, getDataFileLocation()); mainWindowHandle = setupHelper.setupMainWindowHandle(); String command = ChangeDirectoryCommand.COMMAND_WORD + " " + TEST_FOLDER_INDEX.getOneBased(); String resultDisplayString = String.format(ChangeDirectoryCommand.MESSAGE_ENTER_FOLDER_SUCCESS, TEST_FOLDER_INDEX.getOneBased()); mainWindowHandle.getCommandBox().run(command); setupHelper.initialiseCardListPanelHandle(); waitUntilBrowserLoaded(getBrowserPanel()); assertApplicationStartingStateIsCorrect(resultDisplayString); } @After public void tearDown() { setupHelper.tearDownStage(); } /** * Returns the data to be loaded into the file in {@link #getDataFileLocation()}. */ protected CardFolder getInitialData() { return TypicalCards.getTypicalFolderOne(); } /** * Returns the directory of the data file. */ protected Path getDataFileLocation() { return TestApp.SAVE_LOCATION_FOR_TESTING; } public MainWindowHandle getMainWindowHandle() { return mainWindowHandle; } public CommandBoxHandle getCommandBox() { return mainWindowHandle.getCommandBox(); } public CardListPanelHandle getCardListPanel() { return mainWindowHandle.getCardListPanel(); } public MainMenuHandle getMainMenu() { return mainWindowHandle.getMainMenu(); } public BrowserPanelHandle getBrowserPanel() { return mainWindowHandle.getBrowserPanel(); } public StatusBarFooterHandle getStatusBarFooter() { return mainWindowHandle.getStatusBarFooter(); } public ResultDisplayHandle getResultDisplay() { return mainWindowHandle.getResultDisplay(); } /** * Executes {@code command} in the application's {@code CommandBox}. * Method returns after UI components have been updated. */ protected void executeCommand(String command) { rememberStates(); mainWindowHandle.getCommandBox().run(command); waitUntilBrowserLoaded(getBrowserPanel()); } /** * Displays all cards in the card folder. */ protected void showAllCards() { executeCommand(ListCommand.COMMAND_WORD); assertEquals(getModel().getActiveCardFolder().getCardList().size(), getModel().getActiveFilteredCards().size()); } /** * Displays all cards with any parts of their questions matching {@code keyword} (case-insensitive). */ protected void showCardsWithQuestion(String keyword) { executeCommand(SearchCommand.COMMAND_WORD + " " + keyword); assertTrue(getModel().getActiveFilteredCards().size() < getModel().getActiveCardFolder().getCardList().size()); } /** * Selects the card at {@code index} of the displayed list. */ protected void selectCard(Index index) { executeCommand(SelectCommand.COMMAND_WORD + " " + index.getOneBased()); assertEquals(index.getZeroBased(), getCardListPanel().getSelectedCardIndex()); } /** * Deletes all cards in the card folder. */ protected void deleteAllCards() { executeCommand(ClearCommand.COMMAND_WORD); assertEquals(0, getModel().getActiveCardFolder().getCardList().size()); } /** * Asserts that the {@code CommandBox} displays {@code expectedCommandInput}, the {@code ResultDisplay} displays * {@code expectedResultMessage}, the storage contains the same card objects as {@code expectedModel} * and the card list panel displays the cards in the model correctly. */ protected void assertApplicationDisplaysExpected(String expectedCommandInput, String expectedResultMessage, Model expectedModel) { assertEquals(expectedCommandInput, getCommandBox().getInput()); assertEquals(expectedResultMessage, getResultDisplay().getText()); if (expectedModel.getState() == Model.State.IN_FOLDER) { assertEquals(new CardFolder(expectedModel.getActiveCardFolder()), testApp.readFirstStorageCardFolder()); assertListMatching(getCardListPanel(), expectedModel.getActiveFilteredCards()); } else if (expectedModel.getState() == Model.State.IN_HOMEDIR) { assertEquals(expectedModel.getCardFolders(), testApp.getModel().getCardFolders()); } } /** * Calls {@code BrowserPanelHandle}, {@code CardListPanelHandle} and {@code StatusBarFooterHandle} to remember * their current state. */ private void rememberStates() { getBrowserPanel().rememberQuestion(); getCardListPanel().rememberSelectedCardCard(); } /** * Asserts that the previously selected card is now deselected and the browser's url is now displaying the * default page. * @see BrowserPanelHandle#isQuestionChanged() */ protected void assertSelectedCardDeselected() { assertEquals("", getBrowserPanel().getCurrentQuestion()); assertFalse(getCardListPanel().isAnyCardSelected()); } /** * Asserts that the browser's url is changed to display the details of the card in the card list panel at * {@code expectedSelectedCardIndex}, and only the card at {@code expectedSelectedCardIndex} is selected. * @see BrowserPanelHandle#isQuestionChanged() * @see CardListPanelHandle#isSelectedCardCardChanged() */ protected void assertSelectedCardChanged(Index expectedSelectedCardIndex) { getCardListPanel().navigateToCard(getCardListPanel().getSelectedCardIndex()); String expectedCardQuestion = getCardListPanel().getHandleToSelectedCard().getQuestion(); assertEquals(expectedCardQuestion, getBrowserPanel().getCurrentQuestion()); assertEquals(expectedSelectedCardIndex.getZeroBased(), getCardListPanel().getSelectedCardIndex()); } /** * Asserts that the browser's url and the selected card in the card list panel remain unchanged. * @see BrowserPanelHandle#isQuestionChanged() * @see CardListPanelHandle#isSelectedCardCardChanged() */ protected void assertSelectedCardUnchanged() { assertFalse(getBrowserPanel().isQuestionChanged()); assertFalse(getCardListPanel().isSelectedCardCardChanged()); } /** * Asserts that the command box's shows the default style. */ protected void assertCommandBoxShowsDefaultStyle() { assertEquals(COMMAND_BOX_DEFAULT_STYLE, getCommandBox().getStyleClass()); } /** * Asserts that the command box's shows the error style. */ protected void assertCommandBoxShowsErrorStyle() { assertEquals(COMMAND_BOX_ERROR_STYLE, getCommandBox().getStyleClass()); } /** * Asserts that the status bar indicates that user is in home directory. */ protected void assertStatusBarIsInHomeDirectory() { StatusBarFooterHandle handle = getStatusBarFooter(); assertEquals(STATUS_IN_HOME_DIRECTORY, handle.getCurrentStatus()); } /** * Asserts that the status bar indicates that user is inside a folder. */ protected void assertStatusBarIsInFolder(String folderName) { StatusBarFooterHandle handle = getStatusBarFooter(); assertEquals(String.format(STATUS_IN_FOLDER, folderName), handle.getCurrentStatus()); } /** * Asserts that the status bar indicates that user is in a test session. */ protected void assertStatusBarIsInTestSession() { StatusBarFooterHandle handle = getStatusBarFooter(); assertEquals(STATUS_IN_TEST_SESSION, handle.getCurrentStatus()); } /** * Asserts that the status bar indicates that user is in a report display. */ protected void assertStatusBarIsInReportDisplay() { StatusBarFooterHandle handle = getStatusBarFooter(); assertEquals(STATUS_IN_REPORT_DISPLAY, handle.getCurrentStatus()); } /** * Asserts that the starting state of the application is correct. * @param resultDisplayString is the string that result display should show. */ private void assertApplicationStartingStateIsCorrect(String resultDisplayString) { assertEquals("", getCommandBox().getInput()); assertEquals(resultDisplayString, getResultDisplay().getText()); assertListMatching(getCardListPanel(), getModel().getActiveFilteredCards()); assertEquals("", getBrowserPanel().getCurrentQuestion()); assertStatusBarIsInFolder(getModel().getActiveCardFolderName()); } /** * Returns a defensive copy of the current model. */ protected Model getModel() { return testApp.getModel(); } }
3e08fbaf4182791942e964f78803be825ef4eb6b
1,450
java
Java
src/test/java/com/github/mkolisnyk/muto/reporter/listeners/XmlListenerTest.java
mkolisnyk/Muto
5720c2aa71e8dc77194f73eaa32e2f55c6b65e02
[ "Apache-2.0" ]
1
2017-03-09T13:12:11.000Z
2017-03-09T13:12:11.000Z
src/test/java/com/github/mkolisnyk/muto/reporter/listeners/XmlListenerTest.java
mkolisnyk/Muto
5720c2aa71e8dc77194f73eaa32e2f55c6b65e02
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/mkolisnyk/muto/reporter/listeners/XmlListenerTest.java
mkolisnyk/Muto
5720c2aa71e8dc77194f73eaa32e2f55c6b65e02
[ "Apache-2.0" ]
null
null
null
36.25
103
0.702759
3,803
package com.github.mkolisnyk.muto.reporter.listeners; import java.io.File; import org.junit.Assert; import org.junit.Test; import com.github.mkolisnyk.muto.data.MutationLocation; import com.github.mkolisnyk.muto.reporter.MutoResult; public class XmlListenerTest { @Test public void testAfterTestRun() throws Exception { File reportsDir = new File("src/test/resources"); File outputDir = new File("target/muto"); File outputFile = new File(outputDir.getAbsolutePath() + File.separator + "muto_result_1.xml"); outputDir.mkdirs(); XmlListener listener = new XmlListener(); MutoResult result = new MutoResult(reportsDir.getAbsolutePath()); result.setOutputLocation(outputDir.getAbsolutePath()); result.retrieveResults(); MutationLocation location = new MutationLocation(2,10,"test_file"); location.setMatchedText("Sample < matched text"); result.setLocation(location); listener.beforeSuiteRun(); listener.beforeTestRun(); listener.beforeFileStrategyRun(); listener.beforeMutationStrategyRun(); listener.beforeMutationRuleRun(); listener.afterMutationRuleRun(new MutationLocation()); listener.afterMutationStrategyRun(); listener.afterFileStrategyRun("Test"); listener.afterTestRun(result); listener.afterSuiteRun(); Assert.assertTrue(outputFile.exists()); } }
3e08fd07562c7a8d689b4a631e4ac9b838be67ca
340
java
Java
src/main/java/com/docswebapps/homeiteminventory/repository/ItemLocationRepository.java
DocsWebApps/home-item-inventory
4fbf593af4e00ff30112e1cbdbdb2fe384e4f441
[ "MIT" ]
null
null
null
src/main/java/com/docswebapps/homeiteminventory/repository/ItemLocationRepository.java
DocsWebApps/home-item-inventory
4fbf593af4e00ff30112e1cbdbdb2fe384e4f441
[ "MIT" ]
null
null
null
src/main/java/com/docswebapps/homeiteminventory/repository/ItemLocationRepository.java
DocsWebApps/home-item-inventory
4fbf593af4e00ff30112e1cbdbdb2fe384e4f441
[ "MIT" ]
null
null
null
34
89
0.870588
3,804
package com.docswebapps.homeiteminventory.repository; import com.docswebapps.homeiteminventory.domain.ItemLocationEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ItemLocationRepository extends JpaRepository<ItemLocationEntity, Long> { }
3e08fd62fca11908900f3c931346f6a57d79c01b
2,515
java
Java
java/src/main/java/com/epi/DrawingSkylinesAlternative.java
svyatovit/epi
f39dcfd976e6c31e2d8de82fba66216f320d27a5
[ "MIT" ]
258
2016-07-18T03:28:15.000Z
2021-12-05T09:08:44.000Z
java/src/main/java/com/epi/DrawingSkylinesAlternative.java
svyatovit/epi
f39dcfd976e6c31e2d8de82fba66216f320d27a5
[ "MIT" ]
7
2016-08-13T22:12:29.000Z
2022-02-25T17:50:11.000Z
java/src/main/java/com/epi/DrawingSkylinesAlternative.java
svyatovit/epi
f39dcfd976e6c31e2d8de82fba66216f320d27a5
[ "MIT" ]
154
2016-07-18T06:29:24.000Z
2021-09-20T18:33:05.000Z
29.588235
80
0.56501
3,805
package com.epi; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class DrawingSkylinesAlternative { // @include public static class Rectangle { public int left, right, height; public Rectangle(int left, int right, int height) { this.left = left; this.right = right; this.height = height; } } public static List<Rectangle> drawingSkylines(List<Rectangle> buildings) { int minLeft = Integer.MAX_VALUE, maxRight = Integer.MIN_VALUE; for (Rectangle building : buildings) { minLeft = Math.min(minLeft, building.left); maxRight = Math.max(maxRight, building.right); } List<Integer> heights = new ArrayList<>(Collections.nCopies(maxRight - minLeft + 1, 0)); for (Rectangle building : buildings) { for (int i = building.left; i <= building.right; ++i) { heights.set(i - minLeft, Math.max(heights.get(i - minLeft), building.height)); } } List<Rectangle> result = new ArrayList<>(); int left = 0; for (int i = 1; i < heights.size(); ++i) { if (heights.get(i) != heights.get(i - 1)) { result.add( new Rectangle(left + minLeft, i - 1 + minLeft, heights.get(i - 1))); left = i; } } result.add(new Rectangle(left + minLeft, maxRight, heights.get(heights.size() - 1))); return result; } // @exclude private static void checkAnswer(List<Rectangle> ans) { // Just check there is no overlap. for (int i = 0; i < ans.size(); ++i) { assert(ans.get(i).left <= ans.get(i).right); if (i > 0) { assert(ans.get(i - 1).right <= ans.get(i).left); assert(ans.get(i - 1).right != ans.get(i).left || ans.get(i - 1).height != ans.get(i).height); } } } public static void main(String[] args) { Random r = new Random(); for (int times = 0; times < 2000; ++times) { int n; if (args.length == 1) { n = Integer.parseInt(args[0]); } else { n = r.nextInt(5000) + 1; } List<Rectangle> A = new ArrayList<>(); for (int i = 0; i < n; ++i) { int left = r.nextInt(1000); int right = r.nextInt(201) + left; int height = r.nextInt(100); A.add(new Rectangle(left, right, height)); } List<Rectangle> ans = drawingSkylines(A); System.out.println("n = " + n); checkAnswer(ans); } } }
3e08fde1341bfe8ade39689e09e4e4f2e14440bd
15,406
java
Java
src/main/java/frc/robot/RobotContainer.java
4329/frc2022
5ac12d9b704e65b15f2b87bcd03d16ae38e5df8f
[ "BSD-3-Clause" ]
3
2022-01-23T06:12:10.000Z
2022-02-23T01:21:25.000Z
src/main/java/frc/robot/RobotContainer.java
4329/frc2022
5ac12d9b704e65b15f2b87bcd03d16ae38e5df8f
[ "BSD-3-Clause" ]
2
2022-01-22T01:59:02.000Z
2022-02-21T21:00:44.000Z
src/main/java/frc/robot/RobotContainer.java
4329/frc2022
5ac12d9b704e65b15f2b87bcd03d16ae38e5df8f
[ "BSD-3-Clause" ]
2
2022-03-12T22:12:53.000Z
2022-03-12T22:28:32.000Z
47.993769
264
0.783915
3,806
package frc.robot; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.cscore.HttpCamera; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.XboxController.Button; import edu.wpi.first.wpilibj.shuffleboard.BuiltInWidgets; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import edu.wpi.first.wpilibj2.command.button.POVButton; import frc.robot.Constants.OIConstants; import frc.robot.Commands.AllBackwardsCommand; import frc.robot.Commands.BumperCommand; import frc.robot.Commands.ClimberButtonCommand; import frc.robot.Commands.ClimberButtonCommandReverse; import frc.robot.Commands.ClimberEngageCommand; import frc.robot.Commands.CommandGroups; import frc.robot.Commands.DriveByController; import frc.robot.Commands.HoodToOpenCommand; import frc.robot.Commands.IntakeAutoCommand; import frc.robot.Commands.IntakeBackwardsCommand; import frc.robot.Commands.IntakeCorrectionCommand; import frc.robot.Commands.IntakePosCommand; import frc.robot.Commands.SensorOutputCommand; import frc.robot.Commands.TowerCommand; import frc.robot.Commands.TowerOverrideCommand; import frc.robot.Commands.TurretCommand; import frc.robot.Commands.TurretToZeroCommand; import frc.robot.Commands.Autos.ComplexAuto; import frc.robot.Commands.Autos.ComplexerAuto; import frc.robot.Commands.Autos.ComplexerNoIntake; import frc.robot.Commands.Autos.KISSAuto; import frc.robot.Commands.Autos.LeftLowAuto; import frc.robot.Commands.Autos.LessComplexAuto; import frc.robot.Commands.Autos.LowAuto; import frc.robot.Commands.Autos.LowAutoMore; import frc.robot.Commands.Autos.MidLowAuto; import frc.robot.Commands.Autos.MostComplexifiedAuto; import frc.robot.Commands.Autos.OpenLowAutoMore; import frc.robot.Commands.Autos.RejectAutoHigh; import frc.robot.Commands.Autos.RejectTest; import frc.robot.Commands.Autos.RightThreeBallAuto; import frc.robot.Subsystems.Climber; import frc.robot.Subsystems.HoodSubsystem; import frc.robot.Subsystems.IntakeMotor; import frc.robot.Subsystems.IntakeSensors; import frc.robot.Subsystems.IntakeSolenoidSubsystem; import frc.robot.Subsystems.Shooter; import frc.robot.Subsystems.ShooterFeedSubsytem; import frc.robot.Subsystems.StorageIntake; import frc.robot.Subsystems.TurretSubsystem; import frc.robot.Subsystems.Swerve.Drivetrain; import frc.robot.Utilities.JoystickAnalogButton; /* * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot * (including subsystems, commands, and button mappings) should be declared here */ public class RobotContainer { //private final PneumaticHub pneumaticHub; // The robot's subsystems private final Drivetrain m_robotDrive; private final StorageIntake storageIntake; private final IntakeSensors intakeSensors; private final ShooterFeedSubsytem shooterFeed; private final TurretSubsystem turretSubsystem; private final IntakeSolenoidSubsystem intakeSolenoid; private final IntakeMotor intakeMotor; private final Shooter shooter; private final Climber climber; private final CommandGroups commandGroups; private final HoodSubsystem hoodSubsystem; // The driver's controllers final XboxController m_driverController; final XboxController m_operatorController; final SendableChooser<Command> m_chooser; private final DriveByController m_drive; // private Command moveOneMeter; // private Command twoPaths; // private Command intakeRun; private Command KISSAuto; private Command ComplexAuto; private Command ComplexerAuto; private Command LowAuto; private Command LowAutoMore; private Command LessComplexAuto; private Command MidLowAuto; private Command LeftLowAuto; private Command OpenLowAutoMore; private Command RejectAutoHigh; private Command RightThreeBallAuto; private Command ComplexerNoIntake; private Command RejectTest; private SensorOutputCommand sensorOutputCommand; private TurretCommand turretCommand; private TurretToZeroCommand turretToZeroCommand; private Command MostComplexifiedAuto; /** * The container for the robot. Contains subsystems, OI devices, and commands. * * @param drivetrain */ public RobotContainer(Drivetrain drivetrain) { m_robotDrive = drivetrain; //pneumaticHub = new PneumaticHub(Configrun.get(61, "PH_CAN_ID")); turretSubsystem = new TurretSubsystem(); shooter = new Shooter(drivetrain); shooterFeed = new ShooterFeedSubsytem(); storageIntake = new StorageIntake(); intakeMotor = new IntakeMotor(); intakeSolenoid = new IntakeSolenoidSubsystem(); intakeSensors = new IntakeSensors(); climber = new Climber(); sensorOutputCommand = new SensorOutputCommand(intakeSensors); intakeSensors.setDefaultCommand(sensorOutputCommand); hoodSubsystem = new HoodSubsystem(); turretCommand = new TurretCommand(turretSubsystem); turretToZeroCommand = new TurretToZeroCommand(turretSubsystem); commandGroups = new CommandGroups(); initializeCamera(); m_driverController = new XboxController(OIConstants.kDriverControllerPort); m_operatorController = new XboxController(OIConstants.kOperatorControllerPort); m_drive = new DriveByController(m_robotDrive, m_driverController); m_robotDrive.setDefaultCommand(m_drive); // Set drivetrain default command to "DriveByController" configureButtonBindings(); /* * Configure the button bindings to commands using configureButtonBindings * function */ m_chooser = new SendableChooser<>(); configureAutoChooser(drivetrain); } /** * Creates and establishes camera streams for the shuffleboard ~Ben */ private void initializeCamera() { CameraServer.startAutomaticCapture(); // VideoSource[] enumerateSources = VideoSource.enumerateSources(); // if (enumerateSources.length > 0 && enumerateSources[0].getName().contains("USB")) { // Shuffleboard.getTab("RobotData").add("Camera", enumerateSources[0]).withPosition(5, 0).withSize(3, 3) // .withWidget(BuiltInWidgets.kCameraStream); // } HttpCamera limelight = new HttpCamera("Limelight", "http://10.43.29.11:5800"); CameraServer.startAutomaticCapture(limelight); Shuffleboard.getTab("RobotData").add("Limelight Camera", limelight).withPosition(2, 0).withSize(2, 2) .withWidget(BuiltInWidgets.kCameraStream); } /** * Use this method to define your button->command mappings. Buttons can be * created by instantiating a {@link edu.wpi.first.wpilibj.GenericHID} or one of * its subclasses ({@link edu.wpi.first.wpilibj.Joystick} or * {@link XboxController}), and then calling passing it to a * {@link JoystickButton}. */ private void configureButtonBindings() { //Driver Controller new POVButton(m_driverController, 180).whenPressed(() -> m_robotDrive.resetOdometry(new Pose2d(new Translation2d(), new Rotation2d(Math.PI))));// Reset drivetrain when down/up on the DPad is pressed new POVButton(m_driverController, 0).whenPressed(() -> m_robotDrive.resetOdometry(new Pose2d(new Translation2d(), new Rotation2d(0.0)))); new JoystickButton(m_driverController, Button.kRightBumper.value).whenPressed(() -> m_drive.changeFieldOrient());//toggle field dorientation new JoystickButton(m_driverController, Button.kLeftStick.value).whenPressed(() -> m_robotDrive.unlock()); //Climber arm controls new JoystickButton(m_driverController, Button.kY.value).whenPressed(() -> climber.togglePivot()); new JoystickButton(m_driverController, Button.kX.value).whenPressed(() -> climber.extend()); new JoystickButton(m_driverController, Button.kA.value).whenPressed(() -> climber.retract()); // new JoystickButton(m_driverController, Button.kB.value).whenPressed(() -> climber.toggleShift()); //Climber motor controls new JoystickAnalogButton(m_driverController, false).whenHeld(new ClimberButtonCommand(m_driverController, climber));//climb up new JoystickAnalogButton(m_driverController, true).whenHeld(new ClimberButtonCommandReverse(m_driverController, climber));//climb down new JoystickButton(m_driverController, Button.kLeftBumper.value).whenPressed(new ClimberEngageCommand(climber));//extend & pivot arms //Operator Controller //Shoot new JoystickButton(m_operatorController, Button.kY.value).whenHeld(commandGroups.fire(turretSubsystem, storageIntake, shooterFeed, shooter, hoodSubsystem, m_robotDrive, intakeSensors));//shoot high with aimbot new JoystickButton(m_operatorController, Button.kBack.value).whenHeld(new TowerOverrideCommand(storageIntake, shooterFeed, shooter, hoodSubsystem, m_robotDrive));//shoot high without aimbot new JoystickButton(m_operatorController, Button.kStart.value).whenHeld(new TowerCommand(storageIntake, shooterFeed, shooter, hoodSubsystem, turretSubsystem, m_robotDrive, intakeSensors));//shoot high without limlight new JoystickButton(m_operatorController, Button.kA.value).whenHeld(new BumperCommand(storageIntake, shooterFeed, shooter, hoodSubsystem));//shoot low //Manage cargo new JoystickButton(m_operatorController, Button.kX.value).whenPressed(new IntakePosCommand(intakeSolenoid));//intake up/down new JoystickButton(m_operatorController, Button.kB.value).whenHeld(new IntakeAutoCommand(intakeSensors, shooterFeed, storageIntake, intakeMotor, intakeSolenoid));//store new JoystickButton(m_operatorController, Button.kB.value).whenReleased(new IntakeCorrectionCommand(shooterFeed, storageIntake)); new JoystickButton(m_operatorController, Button.kRightBumper.value).whenHeld(new AllBackwardsCommand(shooterFeed, storageIntake, intakeMotor, intakeSolenoid));//eject new JoystickButton(m_operatorController, Button.kLeftBumper.value).whenHeld(new IntakeBackwardsCommand(intakeMotor)); } /** * Pulls autos and configures the chooser */ private void configureAutoChooser(Drivetrain drivetrain) { KISSAuto = new KISSAuto(m_robotDrive); ComplexAuto = new ComplexAuto(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); ComplexerAuto = new ComplexerAuto(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); LowAutoMore = new LowAutoMore(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); LessComplexAuto = new LessComplexAuto (m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); LowAuto = new LowAuto(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); OpenLowAutoMore = new OpenLowAutoMore(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); MidLowAuto = new MidLowAuto(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); LeftLowAuto = new LeftLowAuto (m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); RightThreeBallAuto = new RightThreeBallAuto(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); OpenLowAutoMore = new OpenLowAutoMore(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); RejectAutoHigh = new RejectAutoHigh(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); ComplexerNoIntake = new ComplexerNoIntake(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); RejectTest = new RejectTest(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); MostComplexifiedAuto = new MostComplexifiedAuto(m_robotDrive, intakeMotor, storageIntake, shooterFeed, shooter, turretSubsystem, hoodSubsystem, intakeSolenoid, intakeSensors); // Adds autos to the chooser // m_chooser.setDefaultOption("MoveOneMeterAuto", moveOneMeter); // m_chooser.addOption("MoveOneMeterAuto", moveOneMeter); // m_chooser.addOption("TwoPathsAuto", twoPaths); // m_chooser.addOption("IntakeRunAuto", intakeRun); m_chooser.addOption("SuperSimple", KISSAuto); m_chooser.addOption("OneBallHIGHAuto", LessComplexAuto); m_chooser.addOption("TwoBallHIGH", ComplexAuto); m_chooser.addOption("RightThreeBallHigh", RightThreeBallAuto); m_chooser.addOption("RightFourBallHIGH", ComplexerAuto); m_chooser.addOption("RightFiveBallHIGH", MostComplexifiedAuto); m_chooser.addOption("RejectHighAuto", RejectAutoHigh); //m_chooser.addOption("RejectTest", RejectTest); //m_chooser.addOption("RightFiveBallTest", ComplexerNoIntake); //m_chooser.addOption("RightThreeBallLOW/HIGH", LowAutoMore); //m_chooser.addOption("RightThreeBallOPENLOW/HIGH", OpenLowAutoMore); // m_chooser.addOption("RightTwoBallLOW", LowAuto); // m_chooser.addOption("MidTwoBallLOW", MidLowAuto); // m_chooser.addOption("LeftTwoBallLOW", LeftLowAuto); // Puts autos on Shuffleboard Shuffleboard.getTab("RobotData").add("SelectAuto", m_chooser).withSize(2, 1).withPosition(0, 0); if (Configrun.get(false, "extraShuffleBoardToggle")) { Shuffleboard.getTab("Autonomous").add("Documentation", "Autonomous Modes at https://stem2u.sharepoint.com/sites/frc-4329/_layouts/15/Doc.aspx?sourcedoc={91263377-8ca5-46e1-a764-b9456a3213cf}&action=edit&wd=target%28Creating%20an%20Autonomous%20With%20Pathplanner%7Cb37e1a20-51ec-9d4d-87f9-886aa67fcb57%2F%29") .withPosition(2, 2).withSize(4, 1); } } /** * @return Selected Auto */ public Command getAuto() { return m_chooser.getSelected(); } public void disableRobot() { shooterFeed.coastShooterFeed(); storageIntake.storageIntakeCoast(); } public void robotPeriodic() { hoodSubsystem.HoodPeriodic(shooter); } public void init() { turretSubsystem.setDefaultCommand(turretToZeroCommand); hoodSubsystem.setDefaultCommand(new HoodToOpenCommand(hoodSubsystem, shooter)); //climber.engage(); climber.retract(); climber.reversePivotClimber(); } public void teleopPeriodic() { turretSubsystem.putValuesToShuffleboard(); hoodSubsystem.hoodOverride(shooter); } public void test() { hoodSubsystem.hoodTestMode(); turretSubsystem.putValuesToShuffleboard(); } public void autonomousPeriodic() { } }
3e08fdf853d1aad378fbb8e6c380562219668ce4
5,721
java
Java
server/src/main/java/io/crate/planner/operators/Insert.java
Wiewiogr/crate
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
[ "Apache-2.0" ]
3,066
2015-01-01T05:44:20.000Z
2022-03-31T19:33:32.000Z
server/src/main/java/io/crate/planner/operators/Insert.java
Wiewiogr/crate
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
[ "Apache-2.0" ]
7,255
2015-01-02T08:25:25.000Z
2022-03-31T21:05:43.000Z
server/src/main/java/io/crate/planner/operators/Insert.java
Wiewiogr/crate
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
[ "Apache-2.0" ]
563
2015-01-06T19:07:27.000Z
2022-03-25T03:03:36.000Z
33.45614
118
0.671561
3,807
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.planner.operators; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import io.crate.analyze.OrderBy; import io.crate.analyze.relations.AbstractTableRelation; import io.crate.common.collections.Lists2; import io.crate.data.Row; import io.crate.execution.dsl.projection.ColumnIndexWriterProjection; import io.crate.execution.dsl.projection.EvalProjection; import io.crate.execution.dsl.projection.MergeCountProjection; import io.crate.execution.dsl.projection.Projection; import io.crate.execution.dsl.projection.builder.ProjectionBuilder; import io.crate.expression.symbol.SelectSymbol; import io.crate.expression.symbol.Symbol; import io.crate.planner.ExecutionPlan; import io.crate.planner.Merge; import io.crate.planner.PlannerContext; import io.crate.statistics.TableStats; public class Insert implements LogicalPlan { private final ColumnIndexWriterProjection writeToTable; @Nullable private final EvalProjection applyCasts; final LogicalPlan source; public Insert(LogicalPlan source, ColumnIndexWriterProjection writeToTable, @Nullable EvalProjection applyCasts) { this.source = source; this.writeToTable = writeToTable; this.applyCasts = applyCasts; } @Override public ExecutionPlan build(PlannerContext plannerContext, Set<PlanHint> planHints, ProjectionBuilder projectionBuilder, int limit, int offset, @Nullable OrderBy order, @Nullable Integer pageSizeHint, Row params, SubQueryResults subQueryResults) { ExecutionPlan sourcePlan = source.build( plannerContext, EnumSet.of(PlanHint.PREFER_SOURCE_LOOKUP), projectionBuilder, limit, offset, order, pageSizeHint, params, subQueryResults ); if (applyCasts != null) { sourcePlan.addProjection(applyCasts); } var boundIndexWriterProjection = writeToTable .bind(x -> SubQueryAndParamBinder.convert(x, params, subQueryResults)); if (sourcePlan.resultDescription().hasRemainingLimitOrOffset()) { ExecutionPlan localMerge = Merge.ensureOnHandler(sourcePlan, plannerContext); localMerge.addProjection(boundIndexWriterProjection); return localMerge; } else { sourcePlan.addProjection(boundIndexWriterProjection); ExecutionPlan localMerge = Merge.ensureOnHandler(sourcePlan, plannerContext); if (sourcePlan != localMerge) { localMerge.addProjection(MergeCountProjection.INSTANCE); } return localMerge; } } ColumnIndexWriterProjection columnIndexWriterProjection() { return writeToTable; } @Override public List<Symbol> outputs() { return (List<Symbol>) writeToTable.outputs(); } @Override public List<AbstractTableRelation<?>> baseTables() { return Collections.emptyList(); } @Override public List<LogicalPlan> sources() { return List.of(source); } @Override public LogicalPlan replaceSources(List<LogicalPlan> sources) { return new Insert(Lists2.getOnlyElement(sources), writeToTable, applyCasts); } @Override public LogicalPlan pruneOutputsExcept(TableStats tableStats, Collection<Symbol> outputsToKeep) { LogicalPlan newSource = source.pruneOutputsExcept(tableStats, source.outputs()); if (newSource == source) { return this; } return replaceSources(List.of(newSource)); } @Override public Map<LogicalPlan, SelectSymbol> dependencies() { return source.dependencies(); } @Override public long numExpectedRows() { return 1; } @Override public long estimatedRowSize() { return source.estimatedRowSize(); } @Override public <C, R> R accept(LogicalPlanVisitor<C, R> visitor, C context) { return visitor.visitInsert(this, context); } @Override public StatementType type() { return StatementType.INSERT; } public Collection<Projection> projections() { if (applyCasts == null) { return List.of(writeToTable); } else { return List.of(applyCasts, writeToTable); } } }
3e08ffd7f652bfe4f597bcc50d06dbecd16eaa51
2,915
java
Java
sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/test/java/com/alipay/sofa/rpc/boot/test/converter/TestBindingConverter3.java
Kunple-w/sofa-boot
3d82c968e96cf506d553ed5cf1689ae3e0a81d50
[ "Apache-2.0" ]
2,748
2018-04-02T09:37:11.000Z
2019-05-13T08:26:46.000Z
sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/test/java/com/alipay/sofa/rpc/boot/test/converter/TestBindingConverter3.java
Kunple-w/sofa-boot
3d82c968e96cf506d553ed5cf1689ae3e0a81d50
[ "Apache-2.0" ]
457
2019-05-14T13:31:12.000Z
2022-03-31T08:48:40.000Z
sofa-boot-project/sofa-boot-core/rpc-sofa-boot/src/test/java/com/alipay/sofa/rpc/boot/test/converter/TestBindingConverter3.java
Kunple-w/sofa-boot
3d82c968e96cf506d553ed5cf1689ae3e0a81d50
[ "Apache-2.0" ]
698
2018-04-06T12:12:03.000Z
2019-05-13T07:30:39.000Z
39.391892
101
0.736878
3,808
/* * 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.alipay.sofa.rpc.boot.test.converter; import com.alipay.sofa.rpc.boot.runtime.binding.RpcBinding; import com.alipay.sofa.rpc.boot.runtime.converter.RpcBindingConverter; import com.alipay.sofa.rpc.boot.runtime.param.RpcBindingParam; import com.alipay.sofa.runtime.api.annotation.SofaReference; import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding; import com.alipay.sofa.runtime.api.annotation.SofaService; import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding; import com.alipay.sofa.runtime.api.binding.BindingType; import com.alipay.sofa.runtime.spi.service.BindingConverterContext; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.Order; import static com.alipay.sofa.rpc.boot.test.converter.TestBindingConverter.TARGET_NAME; import static com.alipay.sofa.rpc.boot.test.converter.TestBindingConverter.TEST; /** * @author zhaowang * @version : TestBindingConverter.java, v 0.1 2020年02月05日 2:58 下午 zhaowang Exp $ */ @Order(2) public class TestBindingConverter3 extends RpcBindingConverter { @Override protected RpcBinding createRpcBinding(RpcBindingParam bindingParam, ApplicationContext applicationContext, boolean inBinding) { return null; } @Override protected RpcBindingParam createRpcBindingParam() { return null; } @Override public RpcBinding convert(SofaService sofaServiceAnnotation, SofaServiceBinding sofaServiceBindingAnnotation, BindingConverterContext bindingConverterContext) { return null; } @Override public RpcBinding convert(SofaReference sofaReferenceAnnotation, SofaReferenceBinding sofaReferenceBindingAnnotation, BindingConverterContext bindingConverterContext) { return null; } @Override public BindingType supportBindingType() { return TEST; } @Override public String supportTagName() { return TARGET_NAME; } }
3e0900584c74f5c9f8c8ca11717aec60cb790fb4
271
java
Java
rs3 files/876 Deob/source/com/jagex/Interface63.java
emcry666/project-scape
827d213f129a9fd266cf42e7412402609191c484
[ "Apache-2.0" ]
null
null
null
rs3 files/876 Deob/source/com/jagex/Interface63.java
emcry666/project-scape
827d213f129a9fd266cf42e7412402609191c484
[ "Apache-2.0" ]
null
null
null
rs3 files/876 Deob/source/com/jagex/Interface63.java
emcry666/project-scape
827d213f129a9fd266cf42e7412402609191c484
[ "Apache-2.0" ]
null
null
null
24.636364
72
0.793358
3,809
/* Interface63 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex; public interface Interface63 { public boolean method422(Class647_Sub1_Sub3 class647_sub1_sub3, int i); public boolean method423(Class647_Sub1_Sub3 class647_sub1_sub3); }
3e09007b20db86b83fba8b77f2009925a523ac4d
1,792
java
Java
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/delimited/SimpleImage.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
null
null
null
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/delimited/SimpleImage.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
2
2021-03-24T17:58:46.000Z
2021-12-14T20:59:52.000Z
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/delimited/SimpleImage.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
null
null
null
26.746269
96
0.627232
3,810
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 03/07/2011-2.3 Chris Delahunt * - bug 338585: Issue while inserting blobs with delimited identifiers on Oracle Database ******************************************************************************/ package org.eclipse.persistence.testing.models.jpa.delimited; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; /** * @author cdelahun * */ @Entity @Table(name="CMP3_DEL_IMAGE") public class SimpleImage implements Serializable { private int id; private Byte[] picture; private String script; @Id @GeneratedValue() public int getId(){ return id; } @Lob @Column(length=4000) public Byte[] getPicture(){ return picture; } @Lob @Column(length=4000) public String getScript() { return script; } public void setId(int id) { this.id = id; } public void setPicture(Byte[] picture) { this.picture = picture; } public void setScript(String script) { this.script = script; } }
3e0900829d2ac91b5c3e0759356a5351462a3ff5
3,630
java
Java
core/content-manager/src/main/java/org/wisdom/content/engines/Engine.java
ubidreams/wisdom
a35b6431200fec56b178c0ff60837ed73fd7874d
[ "Apache-2.0" ]
59
2015-01-11T14:38:14.000Z
2022-01-07T21:04:36.000Z
core/content-manager/src/main/java/org/wisdom/content/engines/Engine.java
ubidreams/wisdom
a35b6431200fec56b178c0ff60837ed73fd7874d
[ "Apache-2.0" ]
194
2015-01-04T15:40:25.000Z
2021-12-09T19:11:35.000Z
core/content-manager/src/main/java/org/wisdom/content/engines/Engine.java
ubidreams/wisdom
a35b6431200fec56b178c0ff60837ed73fd7874d
[ "Apache-2.0" ]
46
2015-02-04T01:16:42.000Z
2022-01-21T13:50:19.000Z
34.903846
117
0.669146
3,811
/* * #%L * Wisdom-Framework * %% * Copyright (C) 2013 - 2014 Wisdom Framework * %% * 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. * #L% */ package org.wisdom.content.engines; import com.google.common.collect.ImmutableList; import com.google.common.net.MediaType; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Instantiate; import org.apache.felix.ipojo.annotations.Provides; import org.apache.felix.ipojo.annotations.Requires; import org.slf4j.LoggerFactory; import org.wisdom.api.content.*; import java.util.Collection; import java.util.List; /** * Content Engine. */ @Component @Provides @Instantiate(name = "ContentEngine") public class Engine implements ContentEngine { @Requires(specification = BodyParser.class, optional = true) List<BodyParser> parsers; @Requires(specification = ContentSerializer.class, optional = true) List<ContentSerializer> serializers; /** * Gets the body parser that can be used to parse a body with the given content type. * * @param contentType the content type * @return a body parser, {@code null} if none match */ @Override public BodyParser getBodyParserEngineForContentType(String contentType) { for (BodyParser parser : parsers) { if (parser.getContentTypes().contains(contentType)) { return parser; } } LoggerFactory.getLogger(this.getClass()).info("Cannot find a body parser for " + contentType); return null; } /** * Gets the content serializer that can be used to serialize a result to the given content type. This method uses * an exact match. * * @param contentType the content type * @return a content serializer, {@code null} if none match */ @Override public ContentSerializer getContentSerializerForContentType(String contentType) { for (ContentSerializer renderer : serializers) { if (renderer.getContentType().equals(contentType)) { return renderer; } } LoggerFactory.getLogger(this.getClass()).info("Cannot find a content renderer handling " + contentType); return null; } /** * Finds the 'best' content serializer for the given accept headers. * * @param mediaTypes the ordered set of {@link com.google.common.net.MediaType} from the {@code ACCEPT} header. * @return the best serializer from the list matching the {@code ACCEPT} header, {@code null} if none match */ @Override public ContentSerializer getBestSerializer(Collection<MediaType> mediaTypes) { if (mediaTypes == null || mediaTypes.isEmpty()) { mediaTypes = ImmutableList.of(MediaType.HTML_UTF_8); } for (MediaType type : mediaTypes) { for (ContentSerializer ser : serializers) { MediaType mt = MediaType.parse(ser.getContentType()); if (mt.is(type.withoutParameters())) { return ser; } } } return null; } }
3e09010db32c5fe7bef0a8a25c21834dd708f272
2,893
java
Java
app/src/main/java/org/theotech/ceaselessandroid/prefs/TimePickerDialogPreference.java
joejoe2016/CeaselessAndroid
5afec6661035fd1875acc05f9441fc7365961340
[ "MIT" ]
11
2015-10-04T14:15:31.000Z
2021-07-23T18:23:11.000Z
app/src/main/java/org/theotech/ceaselessandroid/prefs/TimePickerDialogPreference.java
joejoe2016/CeaselessAndroid
5afec6661035fd1875acc05f9441fc7365961340
[ "MIT" ]
89
2015-10-04T00:42:48.000Z
2019-06-22T19:55:29.000Z
app/src/main/java/org/theotech/ceaselessandroid/prefs/TimePickerDialogPreference.java
joejoe2016/CeaselessAndroid
5afec6661035fd1875acc05f9441fc7365961340
[ "MIT" ]
3
2015-10-27T17:05:06.000Z
2019-05-05T00:02:33.000Z
29.222222
113
0.659177
3,812
package org.theotech.ceaselessandroid.prefs; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import android.widget.TimePicker; import org.theotech.ceaselessandroid.R; /** * Created by jprobert on 10/4/2015. * with a lot of help from * https://github.com/commonsguy/cw-lunchlist/blob/master/19-Alarm/LunchList/src/apt/tutorial/TimePreference.java */ public class TimePickerDialogPreference extends DialogPreference { private static final String TAG = TimePickerDialogPreference.class.getSimpleName(); private int lastHour = 0; private int lastMinute = 0; private TimePicker picker = null; private TextView timeView = null; public TimePickerDialogPreference(Context ctxt, AttributeSet attrs) { super(ctxt, attrs); } public static int getHour(String time) { String[] pieces = time.split(":"); return Integer.parseInt(pieces[0]); } public static int getMinute(String time) { String[] pieces = time.split(":"); return Integer.parseInt(pieces[1]); } @Override protected View onCreateDialogView() { picker = new TimePicker(getContext()); return picker; } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); picker.setCurrentHour(lastHour); picker.setCurrentMinute(lastMinute); } @Override protected void onBindView(View v) { super.onBindView(v); timeView = (TextView) v.findViewById(R.id.timeTextView); timeView.setText(getPersistedString(getContext().getString(R.string.default_notification_time))); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { lastHour = picker.getCurrentHour(); lastMinute = picker.getCurrentMinute(); String time = String.format("%02d", lastHour) + ":" + String.format("%02d", lastMinute); if (callChangeListener(time)) { persistString(time); } timeView.setText(getPersistedString(getContext().getString(R.string.default_notification_time))); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return (a.getString(index)); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { String time = null; if (restoreValue) { if (defaultValue == null) { time = getPersistedString("00:00"); } } else { time = defaultValue.toString(); } lastHour = getHour(time); lastMinute = getMinute(time); } }
3e0901c6290ae3e40f32c1d9f092a800d1aa1adc
6,641
java
Java
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexEditorIT.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
null
null
null
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexEditorIT.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
2
2020-06-15T19:48:29.000Z
2021-02-08T21:25:54.000Z
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexEditorIT.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
null
null
null
15.516355
810
0.786478
3,813
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|index operator|. name|solr operator|. name|index package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Root import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|index operator|. name|solr operator|. name|SolrBaseTest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|solr operator|. name|client operator|. name|solrj operator|. name|SolrQuery import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|solr operator|. name|client operator|. name|solrj operator|. name|response operator|. name|QueryResponse import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_comment comment|/** * Integration test for {@link SolrIndexEditor} */ end_comment begin_class specifier|public class|class name|SolrIndexEditorIT extends|extends name|SolrBaseTest block|{ annotation|@ name|Test specifier|public name|void name|testAddSomeNodes parameter_list|() throws|throws name|Exception block|{ name|Root name|r init|= name|createRoot argument_list|() decl_stmt|; name|r operator|. name|getTree argument_list|( literal|"/" argument_list|) operator|. name|addChild argument_list|( literal|"a" argument_list|) operator|. name|addChild argument_list|( literal|"b" argument_list|) operator|. name|addChild argument_list|( literal|"doc1" argument_list|) operator|. name|setProperty argument_list|( literal|"text" argument_list|, literal|"hit that hot hat tattoo" argument_list|) expr_stmt|; name|r operator|. name|getTree argument_list|( literal|"/" argument_list|) operator|. name|getChild argument_list|( literal|"a" argument_list|) operator|. name|addChild argument_list|( literal|"c" argument_list|) operator|. name|addChild argument_list|( literal|"doc2" argument_list|) operator|. name|setProperty argument_list|( literal|"text" argument_list|, literal|"it hits hot hats" argument_list|) expr_stmt|; name|r operator|. name|getTree argument_list|( literal|"/" argument_list|) operator|. name|getChild argument_list|( literal|"a" argument_list|) operator|. name|getChild argument_list|( literal|"b" argument_list|) operator|. name|addChild argument_list|( literal|"doc3" argument_list|) operator|. name|setProperty argument_list|( literal|"text" argument_list|, literal|"tattoos hate hot hits" argument_list|) expr_stmt|; name|r operator|. name|getTree argument_list|( literal|"/" argument_list|) operator|. name|getChild argument_list|( literal|"a" argument_list|) operator|. name|getChild argument_list|( literal|"b" argument_list|) operator|. name|addChild argument_list|( literal|"doc4" argument_list|) operator|. name|setProperty argument_list|( literal|"text" argument_list|, literal|"hats tattoos hit hot" argument_list|) expr_stmt|; name|r operator|. name|commit argument_list|() expr_stmt|; name|SolrQuery name|query init|= operator|new name|SolrQuery argument_list|() decl_stmt|; name|query operator|. name|setQuery argument_list|( literal|"*:*" argument_list|) expr_stmt|; name|QueryResponse name|queryResponse init|= name|server operator|. name|query argument_list|( name|query argument_list|) decl_stmt|; name|assertTrue argument_list|( literal|"no documents were indexed" argument_list|, name|queryResponse operator|. name|getResults argument_list|() operator|. name|size argument_list|() operator|> literal|0 argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testRemoveNode parameter_list|() throws|throws name|Exception block|{ name|Root name|r init|= name|createRoot argument_list|() decl_stmt|; comment|// Add a node name|r operator|. name|getTree argument_list|( literal|"/" argument_list|) operator|. name|addChild argument_list|( literal|"testRemoveNode" argument_list|) operator|. name|setProperty argument_list|( literal|"foo" argument_list|, literal|"bar" argument_list|) expr_stmt|; name|r operator|. name|commit argument_list|() expr_stmt|; comment|// check the node is not in Solr anymore name|SolrQuery name|query init|= operator|new name|SolrQuery argument_list|() decl_stmt|; name|query operator|. name|setQuery argument_list|( literal|"path_exact:\\/testRemoveNode" argument_list|) expr_stmt|; name|assertTrue argument_list|( literal|"item with id:testRemoveNode was not found in the index" argument_list|, name|server operator|. name|query argument_list|( name|query argument_list|) operator|. name|getResults argument_list|() operator|. name|size argument_list|() operator|> literal|0 argument_list|) expr_stmt|; comment|// remove the node in oak name|r operator|. name|getTree argument_list|( literal|"/" argument_list|) operator|. name|getChild argument_list|( literal|"testRemoveNode" argument_list|) operator|. name|remove argument_list|() expr_stmt|; name|r operator|. name|commit argument_list|() expr_stmt|; comment|// check the node is not in Solr anymore name|assertTrue argument_list|( literal|"item with id:testRemoveNode was found in the index" argument_list|, name|server operator|. name|query argument_list|( name|query argument_list|) operator|. name|getResults argument_list|() operator|. name|size argument_list|() operator|== literal|0 argument_list|) expr_stmt|; block|} block|} end_class end_unit
3e0902545e9d86affa46daa27e67b7d3227296ec
5,008
java
Java
encryption/encryption-jnacl/src/test/java/com/quorum/tessera/encryption/nacl/jnacl/JnaclSecretBoxTest.java
PuneetGoel80/tessera-fork
36df042c1f113511833a9b57d52a2edadb73d2b8
[ "Apache-2.0" ]
128
2018-08-15T15:39:11.000Z
2020-08-18T19:39:41.000Z
encryption/encryption-jnacl/src/test/java/com/quorum/tessera/encryption/nacl/jnacl/JnaclSecretBoxTest.java
PuneetGoel80/tessera-fork
36df042c1f113511833a9b57d52a2edadb73d2b8
[ "Apache-2.0" ]
617
2018-08-15T16:08:01.000Z
2020-08-24T14:08:09.000Z
encryption/encryption-jnacl/src/test/java/com/quorum/tessera/encryption/nacl/jnacl/JnaclSecretBoxTest.java
PuneetGoel80/tessera-fork
36df042c1f113511833a9b57d52a2edadb73d2b8
[ "Apache-2.0" ]
99
2018-08-15T16:15:32.000Z
2020-07-21T10:06:31.000Z
30.723926
100
0.724641
3,814
package com.quorum.tessera.encryption.nacl.jnacl; import static com.neilalexander.jnacl.crypto.curve25519xsalsa20poly1305.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import java.util.Arrays; import org.junit.Before; import org.junit.Test; public class JnaclSecretBoxTest { private JnaclSecretBox secretBox = new JnaclSecretBox(); private byte[] publicKey; private byte[] privateKey; @Before public void init() { this.publicKey = new byte[crypto_secretbox_PUBLICKEYBYTES]; this.privateKey = new byte[crypto_secretbox_SECRETKEYBYTES]; this.secretBox.cryptoBoxKeypair(publicKey, privateKey); } @Test public void sharedKeyUsingValidKeys() { final byte[] sharedKey = new byte[crypto_secretbox_BEFORENMBYTES]; final int success = this.secretBox.cryptoBoxBeforenm(sharedKey, publicKey, privateKey); assertThat(success).isEqualTo(0); } @Test public void sharedKeyFailsIfOutputTooSmall() { final byte[] sharedKey = new byte[crypto_secretbox_BEFORENMBYTES - 1]; final Throwable throwable = catchThrowable(() -> this.secretBox.cryptoBoxBeforenm(sharedKey, publicKey, privateKey)); assertThat(throwable).isInstanceOf(ArrayIndexOutOfBoundsException.class); } @Test public void sharedKeyFailsIfPublicKeyTooSmall() { final byte[] sharedKey = new byte[crypto_secretbox_BEFORENMBYTES]; final Throwable throwable = catchThrowable( () -> this.secretBox.cryptoBoxBeforenm( sharedKey, Arrays.copyOf(publicKey, publicKey.length - 1), privateKey)); assertThat(throwable).isInstanceOf(ArrayIndexOutOfBoundsException.class); } @Test public void sharedKeyFailsIfPrivateKeyTooSmall() { final byte[] sharedKey = new byte[crypto_secretbox_BEFORENMBYTES]; final Throwable throwable = catchThrowable( () -> this.secretBox.cryptoBoxBeforenm( sharedKey, publicKey, Arrays.copyOf(privateKey, privateKey.length - 1))); assertThat(throwable).isInstanceOf(ArrayIndexOutOfBoundsException.class); } @Test public void sealingMessageUsingSymmetricKeyFailsIfMessageIsLessThanRequiredLength() { final int success = this.secretBox.cryptoBoxAfternm(new byte[0], new byte[0], 0, new byte[0], new byte[0]); assertThat(success).isEqualTo(-1); } @Test public void sealingMessageUsingSymmetricKeySucceeds() { final int success = this.secretBox.cryptoBoxAfternm(new byte[32], new byte[32], 32, new byte[24], new byte[32]); assertThat(success).isEqualTo(0); } @Test public void generatingNewKeysSucceedsIfArraysAreBigEnough() { final byte[] publicKey = new byte[crypto_secretbox_PUBLICKEYBYTES]; final byte[] privateKey = new byte[crypto_secretbox_SECRETKEYBYTES]; final int success = this.secretBox.cryptoBoxKeypair(publicKey, privateKey); assertThat(success).isEqualTo(0); } @Test public void generatingNewsKeysFailsIfPublicKeyTooSmall() { final byte[] publicKey = new byte[crypto_secretbox_PUBLICKEYBYTES - 1]; final byte[] privateKey = new byte[crypto_secretbox_SECRETKEYBYTES]; final Throwable throwable = catchThrowable(() -> this.secretBox.cryptoBoxKeypair(publicKey, privateKey)); assertThat(throwable).isInstanceOf(ArrayIndexOutOfBoundsException.class); } @Test public void generatingNewsKeysFailsIfPrivateKeyTooSmall() { final byte[] publicKey = new byte[crypto_secretbox_PUBLICKEYBYTES]; final byte[] privateKey = new byte[crypto_secretbox_SECRETKEYBYTES - 1]; final Throwable throwable = catchThrowable(() -> this.secretBox.cryptoBoxKeypair(publicKey, privateKey)); assertThat(throwable).isInstanceOf(ArrayIndexOutOfBoundsException.class); } @Test public void openingBoxFailsIfInputLengthTooSmall() { final int success = this.secretBox.cryptoBoxOpenAfternm(new byte[0], new byte[0], 0, new byte[0], new byte[0]); assertThat(success).isEqualTo(-1); } @Test public void openingFailsIfInputsAreInvalid() { final int success = this.secretBox.cryptoBoxOpenAfternm( new byte[32], new byte[32], 32, new byte[24], new byte[32]); assertThat(success).isEqualTo(-1); } @Test public void openingSucceedsIfInputsAreValid() { // setup final byte[] sharedKey = new byte[crypto_secretbox_BEFORENMBYTES]; this.secretBox.cryptoBoxBeforenm(sharedKey, publicKey, privateKey); final byte[] nonce = new byte[crypto_secretbox_NONCEBYTES]; final byte[] message = new byte[33]; message[32] = 1; final byte[] cipherText = new byte[33]; this.secretBox.cryptoBoxAfternm(cipherText, message, 33, nonce, sharedKey); // make the call final int success = this.secretBox.cryptoBoxOpenAfternm(new byte[33], cipherText, 33, nonce, sharedKey); // check result assertThat(success).isEqualTo(0); } }
3e0902774f4063e953bfd684838554534cf9f37f
3,426
java
Java
src/test/java/com/napier/sem/unit_tests/helpers/LanguageHelpersUnitTests.java
GregEwens/sem
dad8033bbb279d93e7a65f22ce97c45d78e6c3db
[ "Apache-2.0" ]
null
null
null
src/test/java/com/napier/sem/unit_tests/helpers/LanguageHelpersUnitTests.java
GregEwens/sem
dad8033bbb279d93e7a65f22ce97c45d78e6c3db
[ "Apache-2.0" ]
34
2022-02-01T16:10:36.000Z
2022-03-13T13:03:17.000Z
src/test/java/com/napier/sem/unit_tests/helpers/LanguageHelpersUnitTests.java
GregEwens/sem
dad8033bbb279d93e7a65f22ce97c45d78e6c3db
[ "Apache-2.0" ]
null
null
null
31.431193
118
0.693812
3,815
package com.napier.sem.unit_tests.helpers; import com.napier.sem.entities.SpokenLanguageJoinCountry; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static com.napier.sem.helpers.LanguageHelpers.*; import static org.junit.jupiter.api.Assertions.*; /** * Project Name: seMethods * Package: com.napier.sem.unit_tests * User: Greg Ewens * Date Created: 10/04/2022 19:21 * File Purpose: Unit tests for LanguageHelpers */ class LanguageHelpersUnitTests { /** * Reference data shared between many of the tests */ private final static List<SpokenLanguageJoinCountry> SpokenLanguageJoinCountryCollection = new ArrayList<>(); @BeforeAll static void initialise(){ var filteredLanguage = "Language1"; var item1 = new SpokenLanguageJoinCountry(); item1.language = filteredLanguage; SpokenLanguageJoinCountryCollection.add(item1); var item2 = new SpokenLanguageJoinCountry(); item2.language = filteredLanguage; SpokenLanguageJoinCountryCollection.add(item2); var item3 = new SpokenLanguageJoinCountry(); item3.language = "language2"; SpokenLanguageJoinCountryCollection.add(item3); var item4 = new SpokenLanguageJoinCountry(); item4.language = "Another language"; SpokenLanguageJoinCountryCollection.add(item4); } /** * Tests getCountriesWithLanguage returns a correctly filtered collection */ @Test void getCountriesWithLanguageReturnsFilteredCollectionTest(){ // Arrange var filteredLanguage = "Language1"; // Act var filteredCollection = getCountriesWithLanguage(SpokenLanguageJoinCountryCollection, filteredLanguage); // Assert assertEquals(2, filteredCollection.size(), "Mockup supplies 2 objects"); } /** * Tests getCountriesWithLanguage returns a correctly filtered collection */ @Test void getCountriesWithLanguageReturnsEmptyCollectionTest(){ // Arrange // Act var filteredCollection = getCountriesWithLanguage(SpokenLanguageJoinCountryCollection, "not a language"); // Assert assertEquals(0, filteredCollection.size(), "Mockup does not supply this data"); } /** * Tests buildLanguageModels builds the correct count of models in the response */ @Test void buildLanguageModelsBuildsCorrectCountOfModelsTest(){ // Arrange var worldPopulation = 10000; var languagesOfInterest = new String[] {"Language1", "Language2", "Language3"}; // Act var response = buildLanguageModels(SpokenLanguageJoinCountryCollection, worldPopulation, languagesOfInterest); // Assert assertEquals(3, response.size(), "Mockup supplies 3 objects"); } /** * Tests buildLanguageModels builds accurate models in the response */ @Test void buildLanguageModelsBuildsAccurateModelsTest(){ // Arrange var worldPopulation = 10000; var languagesOfInterest = new String[] {"Language2"}; // Act var response = buildLanguageModels(SpokenLanguageJoinCountryCollection, worldPopulation, languagesOfInterest); // Assert assertEquals("Language2", response.get(0).languageName, "Mockup supplies this object"); } }
3e0903add00cc1e7acf6f7effef59aa70eac53df
37,419
java
Java
app/src/main/java/com/gka/akshara/assesseasy/deviceDatastoreMgr.java
klpdotorg/a3
1b282c4411637017dc56b865d862471854c4a054
[ "MIT" ]
1
2018-08-04T23:00:04.000Z
2018-08-04T23:00:04.000Z
app/src/main/java/com/gka/akshara/assesseasy/deviceDatastoreMgr.java
klpdotorg/a3
1b282c4411637017dc56b865d862471854c4a054
[ "MIT" ]
null
null
null
app/src/main/java/com/gka/akshara/assesseasy/deviceDatastoreMgr.java
klpdotorg/a3
1b282c4411637017dc56b865d862471854c4a054
[ "MIT" ]
null
null
null
49.242105
228
0.564664
3,816
package com.gka.akshara.assesseasy; /** * Android Datastore Java API Library to save data in the local SQLite database * Configuration/Settings required: * Add android.permission.INTERNET in the AndroidManifest.xml file of the app * <uses-permission android:name="android.permission.INTERNET" /> * * @Author: [email protected] */ import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import com.akshara.assessment.a3.A3Application; import com.akshara.assessment.a3.db.KontactDatabase; import com.akshara.assessment.a3.db.StudentTable; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.UUID; public class deviceDatastoreMgr { private String a3dbname = com.akshara.assessment.a3.db.DB_CONSTANTS.DB_NAME; private Context appcontext; private SQLiteDatabase a3appdb = null; private String providerCode = "GWL"; private boolean erroralerts = true; KontactDatabase db; public void initializeDS(Context context) { appcontext = context; db = ((A3Application) context.getApplicationContext()).getDb(); try { String a3appdbfilepath = ""; a3appdbfilepath = "/data/data/" + context.getPackageName() + "/databases/"; a3appdbfilepath = a3appdbfilepath + a3dbname; if (MainActivity.debugalerts) Log.d("EASYASSESS", "a3dbfilepath: " + a3appdbfilepath); a3appdb = SQLiteDatabase.openOrCreateDatabase(a3appdbfilepath, null); a3appdb.setVersion(com.akshara.assessment.a3.db.DB_CONSTANTS.DB_VERSION); if(a3appdb != null) { if(MainActivity.debugalerts) Log.d("EASYASSESS", "EASYASSESS.initializeDS: openOrCreateDatabase success. "); this.createTables(); } else { if(erroralerts) Log.e("EASYASSESS","EASYASSESS.initializeDS: openOrCreateDatabase failed. Returned NULL SQLiteDatabase handler"); } } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.initializeDS: Error: "+e.toString()); } } public boolean createTables() { // create / open (if already exists) the Tables String query_createassessmenttbl = "CREATE TABLE IF NOT EXISTS a3app_assessment_tbl ( \n" + "id integer primary key autoincrement, \n" + "id_assessment text, \n" + "id_child text, \n" + "id_questionset integer, \n" + "score integer, datetime_start text, datetime_submission text, \n" + "synced integer not null default 0)"; String query_createassessmentdetailtbl = "CREATE TABLE IF NOT EXISTS a3app_assessmentdetail_tbl ( \n" + "id integer primary key autoincrement, \n" + "id_assessment text, id_question text, answer_given text, \n"+ "pass text, synced integer not null default 0)"; String query_createquestionsettbl = "CREATE TABLE IF NOT EXISTS a3app_questionset_tbl ( \n" + "id integer primary key autoincrement, id_questionset integer, \n"+ "qset_title text, qset_name text,language_name text, \n" + "subject_name text, grade_name text, program_name text, assesstype_name text)"; String query_createquestionsetdetailtbl = "CREATE TABLE IF NOT EXISTS a3app_questionsetdetail_tbl ( \n" + "id integer primary key autoincrement, id_questionset integer, id_question text)"; String query_createquestiontbl = "CREATE TABLE IF NOT EXISTS a3app_question_tbl ( \n" + "id integer primary key autoincrement, id_question text, \n"+ "question_title text, question_text text,correct_answer text, answerunitlabel text, language_name text, \n" + "subject_name text, grade_name text, level_name text, questiontype_name text, \n"+ "questiontempltype_name text, concept_name text, mconcept_name txt)"; String query_createquestiondatatbl = "CREATE TABLE IF NOT EXISTS a3app_questiondata_tbl ( \n" + "id integer primary key autoincrement, id_question text, \n"+ "name text, label text, datatype text, role text, position text, val text, filecontent_base64 text)" ; if(MainActivity.debugalerts) Log.d("EASYASSESS","Enter EASYASSESS.createTables"); try { a3appdb.execSQL(query_createassessmenttbl); a3appdb.execSQL(query_createassessmentdetailtbl); a3appdb.execSQL(query_createquestionsettbl); a3appdb.execSQL(query_createquestionsetdetailtbl); a3appdb.execSQL(query_createquestiontbl); a3appdb.execSQL(query_createquestiondatatbl); if(MainActivity.debugalerts) Log.d("EASYASSESS","createTables: success"); } catch(Exception e) { Log.e("EASYASSESS","createTables: failed. Error: "+e.toString()); } return true; } public boolean dropTables() { // create / open (if already exists) the Tables String query_dropassessmenttbl = "DROP TABLE a3app_assessment_tbl"; String query_dropassessmentdetailtbl = "DROP TABLE a3app_assessmentdetail_tbl"; String query_dropquestionsettbl = "DROP TABLE a3app_questionset_tbl"; String query_dropquestionsetdetailtbl = "DROP TABLE a3app_questionsetdetail_tbl"; String query_dropquestiontbl = "DROP TABLE a3app_question_tbl" ; String query_dropquestiondatatbl = "DROP TABLE a3app_questiondata_tbl" ; try { a3appdb.execSQL(query_dropassessmenttbl); a3appdb.execSQL(query_dropassessmentdetailtbl); a3appdb.execSQL(query_dropquestionsettbl); a3appdb.execSQL(query_dropquestionsetdetailtbl); a3appdb.execSQL(query_dropquestiontbl); a3appdb.execSQL(query_dropquestiondatatbl); if(MainActivity.debugalerts) Log.d("EASYASSESS","dropTables: success"); } catch(Exception e) { Log.e("EASYASSESS","dropTables: failed. Error: "+e.toString()); } return true; } public String saveAssessment(String[] arrData) { // Create a unique identifier for id_assessment (A 16 char unique string is generated as the Id). String randomstr = UUID.randomUUID().toString(); // format 8-4-4-4-12 total 36 chars String id_assessment = randomstr.substring(2, 5)+ randomstr.substring(14,17)+randomstr.substring(24,32); // provideCode + substring of 12 chars if(MainActivity.debugalerts) Log.d("EASYASSESS","Enter EASYASSESS.saveAssessment. id_assessment: "+id_assessment); String query = "INSERT INTO a3app_assessment_tbl (id_assessment, id_child, id_questionset, score, datetime_start, datetime_submission) \n"+ " VALUES (?,?,?,?,?,?)"; try { a3appdb.execSQL(query, new String[] {id_assessment,arrData[0],arrData[1],arrData[2], arrData[3], arrData[4]}); if(MainActivity.debugalerts) Log.d("EASYASSESS","EASYASSESS.saveAssessment: success "); return id_assessment; } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.saveAssessment: failed. Error: "+e.toString()); return null; } } public void saveAssessmentDetail(String[] arrData) { if(MainActivity.debugalerts) Log.d("EASYASSESS","Enter EASYASSESS.saveAssessment."); String query = "INSERT INTO a3app_assessmentdetail_tbl (id_assessment, id_question, answer_given, pass) \n"+ " VALUES (?,?,?,?)"; try { a3appdb.execSQL(query, new String[] {arrData[0],arrData[1],arrData[2], arrData[3]}); if(MainActivity.debugalerts) Log.d("EASYASSESS","EASYASSESS.saveAssessmentDetail: success "); } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.saveAssessmentDetail: failed. Error: "+e.toString()); } } // Fetch unsynced Assessment telemetry records // Return values: JSONArray (array of JSONObject containing unsynced 'assessment' records) public JSONArray fetchUnsyncedAssessmentRecords() { String query = "SELECT id AS objid, id_assessment, id_child, id_questionset, score, datetime_start, datetime_submission FROM a3app_assessment_tbl WHERE synced = 0"; JSONArray arrRecords = new JSONArray(); try { Cursor curs = a3appdb.rawQuery(query, null); if(curs.moveToFirst()){ do { JSONObject record = new JSONObject(); int objid = curs.getInt(curs.getColumnIndex("objid")); record.put("objid", objid); String id_assessment = curs.getString(curs.getColumnIndex("id_assessment")); record.put("id_assessment", id_assessment); String id_child = curs.getString(curs.getColumnIndex("id_child")); record.put("id_child", id_child); String id_questionset = curs.getString(curs.getColumnIndex("id_questionset")); record.put("id_questionset",id_questionset); String score = curs.getString(curs.getColumnIndex("score")); record.put("score",score); String datetime_start = curs.getString(curs.getColumnIndex("datetime_start")); record.put("datetime_start", datetime_start); String datetime_submission = curs.getString(curs.getColumnIndex("datetime_submission")); record.put("datetime_submission", datetime_submission); arrRecords.put(record); } while(curs.moveToNext()); } if(MainActivity.debugalerts) Log.d("EASYASSESS","EASYASSESS.fetchUnsyncedAssessmentRecords: success. arrRecords "+arrRecords.toString()); } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.fetchUnsyncedAssessmentRecords: failed. Error: "+e.toString()); } return arrRecords; } // Fetch unsynced AssessmentDetail telemetry records // Return values: JSONArray (array of JSONObject containing unsynced 'assessmentdetail' records) public JSONArray fetchUnsyncedAssessmentDetailRecords() { String query = "SELECT id AS objid, id_assessment, id_question, answer_given, pass FROM a3app_assessmentdetail_tbl WHERE synced = 0"; JSONArray arrRecords = new JSONArray(); try { Cursor curs = a3appdb.rawQuery(query, null); if(curs.moveToFirst()){ do { JSONObject record = new JSONObject(); int objid = curs.getInt(curs.getColumnIndex("objid")); record.put("objid", objid); String id_assessment = curs.getString(curs.getColumnIndex("id_assessment")); record.put("id_assessment",id_assessment); String id_question = curs.getString(curs.getColumnIndex("id_question")); record.put("id_question",id_question); String answer_given = curs.getString(curs.getColumnIndex("answer_given")); record.put("answer_given",answer_given); String pass = curs.getString(curs.getColumnIndex("pass")); record.put("pass", pass); arrRecords.put(record); } while(curs.moveToNext()); } if(MainActivity.debugalerts) Log.d("EASYASSESS","EASYASSESS.fetchUnsyncedAssessmentDetailRecords: success. arrRecords "+arrRecords.toString()); } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.fetchUnsyncedAssessmentDetailRecords: failed. Error: "+e.toString()); } return arrRecords; } // Sync the telemetry data to the A3 Server invoking A3 REST APIs // Input parameters: // Return values: public void syncTelemetry(String apibaseurl) { // Fetch the saved Unsynced Assessment records JSONArray jsondata_assessment = fetchUnsyncedAssessmentRecords(); // Invoke the txa3assessment A3 REST API to sync the telemetry data if(jsondata_assessment.length() > 0) invokeRESTAPI(apibaseurl, "txa3assessment", jsondata_assessment); // Fetch the saved Unsynced Assessment records JSONArray jsondata_assessmentdetail = fetchUnsyncedAssessmentDetailRecords(); // Invoke the txa3assessmentdetail A3 REST API to sync the telemetry data if(jsondata_assessment.length() > 0) invokeRESTAPI(apibaseurl, "txa3assessmentdetail", jsondata_assessmentdetail); } // Mark records successfully synced as 'synced' public void markRecordsAsSynced(String table, String syncedids) { if(!TextUtils.isEmpty(syncedids)) { String query_updatesynced = "UPDATE "+table+" SET synced = 1 WHERE id IN ("+syncedids+")"; try { a3appdb.execSQL(query_updatesynced); if(MainActivity.debugalerts) Log.d("EASYASSESS","EASYASSESS.markRecordsAsSynced: table:"+table+" success "); } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.markRecordsAsSynced: table:"+table+"failed. Error: "+e.toString()); } } } // Delete all the telemetry records that are synced successfuly public void deleteSyncedTelemetryRecords() { String query_deleteassessment = "DELETE FROM a3app_assessment_tbl WHERE synced = 1"; String query_deleteassessmentdetail = "DELETE FROM a3app_assessmentdetail_tbl WHERE synced = 1"; if(MainActivity.debugalerts) Log.d("EASYASSESS","In EASYASSESS.deleteSyncedTelemetryRecords:"); try { a3appdb.execSQL(query_deleteassessment); a3appdb.execSQL(query_deleteassessmentdetail); if(MainActivity.debugalerts) Log.d("EASYASSESS","EASYASSESS.deleteSyncedTelemetryRecords: success "); } catch(Exception e) { Log.e("EASYASSESS","EASYASSESS.deleteSyncedTelemetryRecords: failed. Error: "+e.toString()); } } // Fetch Questions for the given id_questionset. // The Questions are copied to globalvault.questions. Returns 'true' if success, 'false' if failed public boolean readQuestions(int id_questionset) { try { // Read the IDs of the Questions contained in the given QuestionSet String query = "SELECT id_question FROM a3app_questionsetdetail_tbl WHERE id_questionset='"+id_questionset+"'"; Cursor curs = a3appdb.rawQuery(query, null); int totalrecordscount = curs.getCount(); if(totalrecordscount == 0) { if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr.readQuestions: Retrieved 0 records from a3app_questionsetdetail_tbl."); return false; } String questionids = ""; if(curs.moveToFirst()){ do { String questionid = curs.getString(curs.getColumnIndex("id_question")); if(!questionids.contains(questionid)){ questionids += "'" + questionid + "',"; } } while(curs.moveToNext()); questionids = questionids.substring(0, questionids.length() - 1); } curs.close(); if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr.readQuestions: get all question IDs - success"); // Read the Questions from the question_tbl String query1 = "SELECT * FROM a3app_question_tbl WHERE id_question IN ("+questionids+")"; Cursor curs1 = a3appdb.rawQuery(query1, null); int totalquestions = curs1.getCount(); globalvault.questions = new assessquestion[totalquestions]; if(totalquestions == 0) { if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr.readQuestions: Retrieved 0 records from a3app_question_tbl."); return false; } int n = 0; if(curs1.moveToFirst()){ do { if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr:readQuestions: extracting Question details. n="+n); assessquestion question = new assessquestion(); String questionid = curs1.getString(curs1.getColumnIndex("id_question")); question.setQuestionID(questionid); String question_text = curs1.getString(curs1.getColumnIndex("question_text")); question.setQuestionText(question_text); String questiontype_name = curs1.getString(curs1.getColumnIndex("questiontype_name")); question.setQuestionType(questiontype_name); String questiontempltype_name = curs1.getString(curs1.getColumnIndex("questiontempltype_name")); question.setQuestionTemplType(questiontempltype_name); String correct_answer = curs1.getString(curs1.getColumnIndex("correct_answer")); question.setAnswerCorrect(correct_answer); String answerunitlabel = curs1.getString(curs1.getColumnIndex("answerunitlabel")); question.setAnswerUnitLabel(answerunitlabel); if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr:readQuestions: answerunitlabel="+answerunitlabel); globalvault.questions[n] = new assessquestion(); globalvault.questions[n] = question; n++; } while(curs1.moveToNext()); } curs1.close(); if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr:readQuestions: All Questions read. Total #of Questions="+globalvault.questions.length); // Read the QuestionData for each of the Questions for(int i=0; i < totalquestions; i++) { String qid = globalvault.questions[i].getQustionID(); String query2 = "SELECT * FROM a3app_questiondata_tbl WHERE id_question='"+qid+"'"; Cursor curs2 = a3appdb.rawQuery(query2, null); int totalquestiondata = curs2.getCount(); if(totalquestiondata != 0) { if (curs2.moveToFirst()) { do { assessquestiondata questiondata = new assessquestiondata(); questiondata.name = curs2.getString(curs2.getColumnIndex("name")); questiondata.label = curs2.getString(curs2.getColumnIndex("label")); questiondata.datatype = curs2.getString(curs2.getColumnIndex("datatype")); questiondata.role = curs2.getString(curs2.getColumnIndex("role")); questiondata.position = curs2.getString(curs2.getColumnIndex("position")); questiondata.value = curs2.getString(curs2.getColumnIndex("val")); questiondata.filecontent_base64 = curs2.getString(curs2.getColumnIndex("filecontent_base64")); globalvault.questions[i].addQuestionData(questiondata); } while (curs2.moveToNext()); } } curs2.close(); } if(MainActivity.debugalerts) Log.d("EASYASSESS","deviceDatastoreMgr:readQuestions: read questiondata : success"); return true; } catch(Exception e) { Log.e("EASYASSESS","deviceDatastoreMgr.readQuestions: failed. Error: "+e.toString()); return false; } } // Invoke the ABS REST API // Input parameters: // @param apibaseurl - String - Base URL for the REST API (e.g http://www.kodvin.com/abs/) // @param apiname - String (name of the api. e.g txabsgameplay // @param jsondata - JSONArray - array of JSONObjects // Return values: public void invokeRESTAPI(String apibaseurl, String apiname, JSONArray jsondata) { AsyncTask.execute(new RESTAPIsyncMgr(apibaseurl,apiname,jsondata,this)); } // ONLY for Testing purpose // Used for adding Questions in the Database for Testing the app public void addQuestionSet(int qsetid) { String query = "INSERT INTO a3app_questionset_tbl (id_questionset) VALUES (?)"; a3appdb.execSQL(query, new String[] {Integer.toString(qsetid)}); } // ONLY for Testing purpose // Used for adding Questions in the Database for Testing the app public void addQuestion(assessquestion question, int qsetid) { try { String query1 = "INSERT INTO a3app_questionsetdetail_tbl (id_questionset, id_question) VALUES (?,?)"; a3appdb.execSQL(query1, new String[]{Integer.toString(qsetid), question.getQustionID()}); String query2 = "INSERT INTO a3app_question_tbl ( \n" + "id_question, question_text, correct_answer, answerunitlabel, \n" + "questiontempltype_name) VALUES (?,?,?,?,?) "; a3appdb.execSQL(query2, new String[]{question.getQustionID(), question.getQuestionText(), question.getAnswerCorrect(), question.getAnswerUnitLabel(), question.getQuestionTemplType()}); ArrayList<assessquestiondata> arrquestiondata = question.getQuestionDataList(); String id_question = question.getQustionID(); for (int i = 0; i < arrquestiondata.size(); i++) { assessquestiondata questiondata = arrquestiondata.get(i); String query3 = "INSERT INTO a3app_questiondata_tbl ( \n" + "id_question, name, label, datatype, role, position, \n" + " val, filecontent_base64) \n" + " VALUES (?,?,?,?,?,?,?,?) "; a3appdb.execSQL(query3, new String[]{id_question, questiondata.name, questiondata.label, questiondata.datatype, questiondata.role, questiondata.position, questiondata.value, questiondata.filecontent_base64}); } } catch(Exception e) { Log.d("EASYASSESS", "deviceDatatoreMgr:addTestQuestionsToDatabase. exception:" + e.toString()); } } public ArrayList<com.akshara.assessment.a3.TelemetryReport.pojoReportData> getAllStudentsForReports(String questionsetId, ArrayList<StudentTable> studentIds, boolean flag, String assessmenttype, boolean by) { Cursor cs1 = null; //if flag variable true then it online report else offline db report String tableName = ""; if (flag) { tableName = "Assessment_Table"; } else { tableName = "a3app_assessment_tbl"; } ArrayList<com.akshara.assessment.a3.TelemetryReport.pojoReportData> reportDataWithStudentInfo = new ArrayList<>(); //String query="select id_assessment,id_child,score,datetime_submission from "+tableName; for (com.akshara.assessment.a3.db.StudentTable sID : studentIds) { if (flag) { if(by) { /* String[] names = { "5","14"}; // do whatever is needed first String query = "SELECT id,id_assessment,id_child,id_questionset,score,datetime_start,datetime_submission,id_questionset FROM "+tableName+ " WHERE id_child="+sID.getId()+ " AND name IN (" + makePlaceholders(names.length) + ")"; cs1= a3appdb.rawQuery(query,names); */ cs1 = a3appdb.query(tableName, new String[]{"id", "id_assessment", "id_child", "id_questionset", "score", "datetime_start", "datetime_submission", "id_questionset"}, "assessmenttype=? AND id_child=?", new String[]{ assessmenttype, sID.getId() + ""}, null, null, "datetime_start" + " DESC", "1"); }else { cs1 = a3appdb.query(tableName, new String[]{"id", "id_assessment", "id_child", "id_questionset", "score", "datetime_start", "datetime_submission", "id_questionset"}, "id_questionset=? AND id_child=?", new String[]{ questionsetId, sID.getId() + ""}, null, null, "datetime_start" + " DESC", "1"); } } else { cs1 = a3appdb.query(tableName, new String[]{"id", "id_assessment", "id_child", "id_questionset", "score", "datetime_start", "datetime_submission", "synced"}, "id_questionset=? AND id_child=?", new String[]{ questionsetId, sID.getId() + ""}, null, null, "datetime_start" + " DESC", "1"); } // Log.d("shri","studentId:"+sID.getId()+":"+sID.getUid()); com.akshara.assessment.a3.TelemetryReport.pojoReportData pojoReportData = new com.akshara.assessment.a3.TelemetryReport.pojoReportData(); if (cs1!=null&&cs1.getCount() > 0) { ArrayList<com.akshara.assessment.a3.TelemetryReport.CombinePojo> combinePojosList = new ArrayList<>(); com.akshara.assessment.a3.TelemetryReport.pojoAssessment pojoAssessment = null; // Log.d("shri", "found" + sID + ":" + cs1.getCount()); while (cs1.moveToNext()) { pojoAssessment = new com.akshara.assessment.a3.TelemetryReport.pojoAssessment(); int objid = cs1.getInt(cs1.getColumnIndex("id")); pojoAssessment.setId(objid); String id_assessment = cs1.getString(cs1.getColumnIndex("id_assessment")); pojoAssessment.setId_assessment(id_assessment); String id_child = cs1.getString(cs1.getColumnIndex("id_child")); pojoAssessment.setId_child(id_child); int id_questionset = cs1.getInt(cs1.getColumnIndex("id_questionset")); pojoAssessment.setId_questionset(id_questionset); int score = cs1.getInt(cs1.getColumnIndex("score")); pojoAssessment.setScore(score); String datetime_start = cs1.getString(cs1.getColumnIndex("datetime_start")); pojoAssessment.setDatetime_start(datetime_start); String datetime_submission = cs1.getString(cs1.getColumnIndex("datetime_submission")); pojoAssessment.setDatetime_submission(datetime_submission); if (flag) { pojoAssessment.setSynced(0); } else { int synced = cs1.getInt(cs1.getColumnIndex("synced")); pojoAssessment.setSynced(synced); } //fetching assessment detail String tablename2 = ""; Cursor assessmentDetailCursor = null; if (flag) { tablename2 = "Assessment_Detail_Table"; assessmentDetailCursor = a3appdb.query(tablename2, new String[]{"id", "id_assessment", "id_question", "pass"}, "id_assessment=?", new String[]{ id_assessment + ""}, null, null, null); } else { tablename2 = "a3app_assessmentdetail_tbl"; assessmentDetailCursor = a3appdb.query(tablename2, new String[]{"id", "id_assessment", "id_question", "answer_given", "pass", "synced"}, "id_assessment=?", new String[]{ id_assessment + ""}, null, null, null); } if (assessmentDetailCursor != null && assessmentDetailCursor.getCount() > 0) { ArrayList<com.akshara.assessment.a3.TelemetryReport.pojoAssessmentDetail> pojoAssessmentDetailArrayList = new ArrayList<>(); while (assessmentDetailCursor.moveToNext()) { com.akshara.assessment.a3.TelemetryReport.pojoAssessmentDetail pojoAssessmentDetail = new com.akshara.assessment.a3.TelemetryReport.pojoAssessmentDetail(); int id = assessmentDetailCursor.getInt(assessmentDetailCursor.getColumnIndex("id")); pojoAssessmentDetail.setId(id); String id_assessmentD = assessmentDetailCursor.getString(assessmentDetailCursor.getColumnIndex("id_assessment")); pojoAssessmentDetail.setId_assessment(id_assessmentD); String id_question = assessmentDetailCursor.getString(assessmentDetailCursor.getColumnIndex("id_question")); pojoAssessmentDetail.setId_question(id_question); String pass = assessmentDetailCursor.getString(assessmentDetailCursor.getColumnIndex("pass")); pojoAssessmentDetail.setPass(pass); if (flag) { pojoAssessmentDetail.setAnswer_given("K"); pojoAssessmentDetail.setSynced(0); } else { String answer_given = assessmentDetailCursor.getString(assessmentDetailCursor.getColumnIndex("answer_given")); pojoAssessmentDetail.setAnswer_given(answer_given); int syncedD = assessmentDetailCursor.getInt(assessmentDetailCursor.getColumnIndex("synced")); pojoAssessmentDetail.setSynced(syncedD); } pojoAssessmentDetailArrayList.add(pojoAssessmentDetail); // Log.d("shri","===id_assessmentD:"+id_assessmentD+"----id_question:"+id_question+"----pass:"+pass); } com.akshara.assessment.a3.TelemetryReport.CombinePojo combinePojo = new com.akshara.assessment.a3.TelemetryReport.CombinePojo(); combinePojo.setPojoAssessment(pojoAssessment); combinePojo.setPojoAssessmentDetail(pojoAssessmentDetailArrayList); combinePojosList.add(combinePojo); } if(assessmentDetailCursor!=null) { assessmentDetailCursor.close(); System.gc(); } } java.util.Map<Long, ArrayList<com.akshara.assessment.a3.TelemetryReport.CombinePojo>> detailReportsMap = new java.util.HashMap<>(); detailReportsMap.put(sID.getId(), combinePojosList); pojoReportData.setDetailReportsMap(detailReportsMap); pojoReportData.setTable(sID); pojoReportData.setScore(pojoAssessment.getScore()); // Log.d("shri", "------------" + sID.getId()); reportDataWithStudentInfo.add(pojoReportData); } else { java.util.Map<Long, ArrayList<com.akshara.assessment.a3.TelemetryReport.CombinePojo>> detailReportsMap = new java.util.HashMap<>(); com.akshara.assessment.a3.TelemetryReport.CombinePojo combinePojo = new com.akshara.assessment.a3.TelemetryReport.CombinePojo(); combinePojo.setPojoAssessment(new com.akshara.assessment.a3.TelemetryReport.pojoAssessment()); combinePojo.setPojoAssessmentDetail(new ArrayList<com.akshara.assessment.a3.TelemetryReport.pojoAssessmentDetail>()); detailReportsMap.put(sID.getId(), null); pojoReportData.setDetailReportsMap(detailReportsMap); pojoReportData.setTable(sID); pojoReportData.setScore(-1); reportDataWithStudentInfo.add(pojoReportData); // Log.d("shri", "------no found-----" + sID.getId()); } if (cs1 != null) { cs1.close(); cs1 = null; System.gc(); } //} // if() } if(cs1!=null) { cs1.close(); } // Log.d("shri", reportDataWithStudentInfo.size() + "--END----"); return reportDataWithStudentInfo; } public boolean isStudentAssessmentTaken(ArrayList<String> questionsetId, long studentID, String assmenttype) { try { String tableName = "a3app_assessment_tbl"; Cursor cs1 = null; for (String qsetId : questionsetId) { cs1 = a3appdb.query(tableName, new String[]{"id", "id_assessment"}, "id_questionset=? AND id_child=?", new String[]{ qsetId, studentID + ""}, null, null, null); if (cs1 != null && cs1.getCount() > 0) { return true; } } cs1 = a3appdb.query("Assessment_Table", new String[]{"id", "id_assessment"}, "assessmenttype=? AND id_child=?", new String[]{ assmenttype, studentID + ""}, null, null, null); if (cs1 != null && cs1.getCount() > 0) { return true; } }catch (Exception e) { return false; } return false; } public boolean checkSysncedData() { String query = "SELECT id AS objid, id_assessment, id_child, id_questionset, score, datetime_start, datetime_submission FROM a3app_assessment_tbl WHERE synced = 0"; int firstCount=0; int secondCound=0; Cursor curs = a3appdb.rawQuery(query, null); Log.d("shri",curs.getCount()+""); if(curs!=null&&curs.getCount()>0) { firstCount=curs.getColumnCount(); } String query2 = "SELECT id AS objid, id_assessment, id_question, answer_given, pass FROM a3app_assessmentdetail_tbl WHERE synced = 0"; Cursor curs2 = a3appdb.rawQuery(query2, null); // Log.d("shri",curs2.getCount()+""); if(curs2!=null&&curs2.getCount()>0) { secondCound=curs2.getCount(); } if(firstCount==0&&secondCound==0) { return false; } else return true; } }
3e0903bc19cbfb582060f4395f0358acf9b5662e
357
java
Java
gmall-wms/src/main/java/com/atguigu/gmall/wms/mapper/WareMapper.java
bluesky1904/gmall
49e9fe03fa7914117e444e42971c5169622fce03
[ "Apache-2.0" ]
null
null
null
gmall-wms/src/main/java/com/atguigu/gmall/wms/mapper/WareMapper.java
bluesky1904/gmall
49e9fe03fa7914117e444e42971c5169622fce03
[ "Apache-2.0" ]
3
2021-03-19T20:23:03.000Z
2021-09-20T20:58:58.000Z
gmall-wms/src/main/java/com/atguigu/gmall/wms/mapper/WareMapper.java
bluesky1904/gmall
49e9fe03fa7914117e444e42971c5169622fce03
[ "Apache-2.0" ]
null
null
null
19.888889
60
0.75419
3,817
package com.atguigu.gmall.wms.mapper; import com.atguigu.gmall.wms.entity.WareEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 仓库信息 * * @author fengge * @email [email protected] * @date 2020-05-20 01:44:26 */ @Mapper public interface WareMapper extends BaseMapper<WareEntity> { }