hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
84301bde7d1dc0d0bd118973e44a8a36c8369730
| 3,779
|
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* 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.alibaba.polardbx.druid.bvt.sql.mysql.create_function;
import com.alibaba.polardbx.druid.sql.MysqlTest;
import com.alibaba.polardbx.druid.sql.SQLUtils;
import com.alibaba.polardbx.druid.sql.ast.SQLStatement;
import com.alibaba.polardbx.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.polardbx.druid.util.JdbcConstants;
import java.util.List;
public class MySql_Create_Function_2 extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR\n" +
"BEGIN\n" +
" DECLARE NAME_FOUND VARCHAR DEFAULT \"\";\n" +
"\n" +
" SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;\n" +
" RETURN NAME_FOUND;\n" +
"END;//";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL);
stmt.accept(visitor);
assertEquals("CREATE FUNCTION F_TEST (\n" +
"\tPID INT\n" +
")\n" +
"RETURNS VARCHAR\n" +
"BEGIN\n" +
"\tDECLARE NAME_FOUND VARCHAR DEFAULT '';\n" +
"\tSELECT EMPLOYEE_NAME\n" +
"\tINTO NAME_FOUND\n" +
"\tFROM TABLE_NAME\n" +
"\tWHERE ID = PID;\n" +
"\tRETURN NAME_FOUND;\n" +
"END;", //
SQLUtils.toMySqlString(stmt));
assertEquals("create function F_TEST (\n" +
"\tPID INT\n" +
")\n" +
"returns VARCHAR\n" +
"begin\n" +
"\tdeclare NAME_FOUND VARCHAR default '';\n" +
"\tselect EMPLOYEE_NAME\n" +
"\tinto NAME_FOUND\n" +
"\tfrom TABLE_NAME\n" +
"\twhere ID = PID;\n" +
"\treturn NAME_FOUND;\n" +
"end;", //
SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION));
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(3, visitor.getColumns().size());
assertEquals(2, visitor.getConditions().size());
// Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("City")));
// Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2")));
// Assert.assertTrue(visitor.getColumns().contains(new Column("t2", "id")));
}
}
| 42.460674
| 96
| 0.564435
|
892c1b01c1c11f0f66053b537133fe257db28968
| 812
|
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.domain.TaskReceiveInfo;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.commerce.operation.promoter.task.receive response.
*
* @author auto create
* @since 1.0, 2021-12-06 15:00:35
*/
public class AlipayCommerceOperationPromoterTaskReceiveResponse extends AlipayResponse {
private static final long serialVersionUID = 5887511953893168935L;
/**
* 积分领取结果
*/
@ApiField("task_receive_result")
private TaskReceiveInfo taskReceiveResult;
public void setTaskReceiveResult(TaskReceiveInfo taskReceiveResult) {
this.taskReceiveResult = taskReceiveResult;
}
public TaskReceiveInfo getTaskReceiveResult( ) {
return this.taskReceiveResult;
}
}
| 25.375
| 89
| 0.757389
|
0a7569f1d5a95fe3cb85d270be6b190e6cc8e9c0
| 1,754
|
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.activemq.broker.region.cursors;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.MessageId;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import static org.junit.Assert.assertFalse;
public class AbstractStoreCursorTest {
@Test
public void testGotToStore() throws Exception {
ActiveMQMessage message = new ActiveMQMessage();
message.setRecievedByDFBridge(true);
MessageId messageId = new MessageId();
message.setMessageId(messageId);
FutureTask<Long> futureTask = new FutureTask<Long>(new Callable<Long>() {
@Override
public Long call() {
return 0l;
}
});
messageId.setFutureOrSequenceLong(futureTask);
futureTask.cancel(false);
assertFalse(AbstractStoreCursor.gotToTheStore(message));
}
}
| 33.09434
| 81
| 0.720068
|
3e57e7e7722edb602f49d34482b57d77be182a43
| 26,538
|
/*
* Copyright (c) 2017 NCIC, Institute of Computing Technology, Chinese Academy of Sciences
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.readthreading;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import org.jgrapht.EdgeFactory;
import org.ncic.bioinfo.sparkseq.algorithms.utils.AlignmentUtils;
import org.ncic.bioinfo.sparkseq.algorithms.utils.smithwaterman.SWPairwiseAlignment;
import org.ncic.bioinfo.sparkseq.algorithms.utils.smithwaterman.SWParameterSet;
import org.ncic.bioinfo.sparkseq.algorithms.utils.smithwaterman.SmithWaterman;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.graphs.BaseGraph;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.graphs.GraphUtils;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.graphs.MultiSampleEdge;
import java.util.*;
public abstract class DanglingChainMergingGraph extends BaseGraph<MultiDeBruijnVertex, MultiSampleEdge> {
private static final int MAX_CIGAR_COMPLEXITY = 3;
private int maxMismatchesInDanglingHead = -1;
protected boolean alreadyBuilt;
/**
* Create a new ReadThreadingAssembler using kmerSize for matching
* @param kmerSize must be >= 1
*/
protected DanglingChainMergingGraph(final int kmerSize, final EdgeFactory<MultiDeBruijnVertex, MultiSampleEdge> edgeFactory) {
super(kmerSize, edgeFactory);
}
protected void setMaxMismatchesInDanglingHead(final int maxMismatchesInDanglingHead) {
this.maxMismatchesInDanglingHead = maxMismatchesInDanglingHead;
}
/**
* Edge factory that encapsulates the numPruningSamples assembly parameter
*/
protected static class MyEdgeFactory implements EdgeFactory<MultiDeBruijnVertex, MultiSampleEdge> {
final int numPruningSamples;
public MyEdgeFactory(int numPruningSamples) {
this.numPruningSamples = numPruningSamples;
}
@Override
public MultiSampleEdge createEdge(final MultiDeBruijnVertex sourceVertex, final MultiDeBruijnVertex targetVertex) {
return new MultiSampleEdge(false, 1, numPruningSamples);
}
public MultiSampleEdge createEdge(final boolean isRef, final int multiplicity) {
return new MultiSampleEdge(isRef, multiplicity, numPruningSamples);
}
}
/**
* Class to keep track of the important dangling chain merging data
*/
protected static final class DanglingChainMergeHelper {
final List<MultiDeBruijnVertex> danglingPath, referencePath;
final byte[] danglingPathString, referencePathString;
final Cigar cigar;
public DanglingChainMergeHelper(final List<MultiDeBruijnVertex> danglingPath,
final List<MultiDeBruijnVertex> referencePath,
final byte[] danglingPathString,
final byte[] referencePathString,
final Cigar cigar) {
this.danglingPath = danglingPath;
this.referencePath = referencePath;
this.danglingPathString = danglingPathString;
this.referencePathString = referencePathString;
this.cigar = cigar;
}
}
/**
* Try to recover dangling tails
*
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @param minDanglingBranchLength the minimum length of a dangling branch for us to try to merge it
*/
public void recoverDanglingTails(final int pruneFactor, final int minDanglingBranchLength) {
if ( ! alreadyBuilt ) throw new IllegalStateException("recoverDanglingTails requires the graph be already built");
int attempted = 0;
int nRecovered = 0;
for ( final MultiDeBruijnVertex v : vertexSet() ) {
if ( outDegreeOf(v) == 0 && ! isRefSink(v) ) {
attempted++;
nRecovered += recoverDanglingTail(v, pruneFactor, minDanglingBranchLength);
}
}
logger.debug("Recovered " + nRecovered + " of " + attempted + " dangling tails");
}
/**
* Try to recover dangling heads
*
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @param minDanglingBranchLength the minimum length of a dangling branch for us to try to merge it
*/
public void recoverDanglingHeads(final int pruneFactor, final int minDanglingBranchLength) {
if ( ! alreadyBuilt ) throw new IllegalStateException("recoverDanglingHeads requires the graph be already built");
// we need to build a list of dangling heads because that process can modify the graph (and otherwise generate
// a ConcurrentModificationException if we do it while iterating over the vertexes)
final List<MultiDeBruijnVertex> danglingHeads = new ArrayList<>();
int attempted = 0;
int nRecovered = 0;
for ( final MultiDeBruijnVertex v : vertexSet() ) {
if ( inDegreeOf(v) == 0 && ! isRefSource(v) )
danglingHeads.add(v);
}
// now we can try to recover the dangling heads
for ( final MultiDeBruijnVertex v : danglingHeads ) {
attempted++;
nRecovered += recoverDanglingHead(v, pruneFactor, minDanglingBranchLength);
}
logger.debug("Recovered " + nRecovered + " of " + attempted + " dangling heads");
}
/**
* Attempt to attach vertex with out-degree == 0 to the graph
*
* @param vertex the vertex to recover
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @param minDanglingBranchLength the minimum length of a dangling branch for us to try to merge it
* @return 1 if we successfully recovered the vertex and 0 otherwise
*/
protected int recoverDanglingTail(final MultiDeBruijnVertex vertex, final int pruneFactor, final int minDanglingBranchLength) {
if ( outDegreeOf(vertex) != 0 ) throw new IllegalStateException("Attempting to recover a dangling tail for " + vertex + " but it has out-degree > 0");
// generate the CIGAR string from Smith-Waterman between the dangling tail and reference paths
final DanglingChainMergeHelper danglingTailMergeResult = generateCigarAgainstDownwardsReferencePath(vertex, pruneFactor, minDanglingBranchLength);
// if the CIGAR is too complex (or couldn't be computed) then we do not allow the merge into the reference path
if ( danglingTailMergeResult == null || ! cigarIsOkayToMerge(danglingTailMergeResult.cigar, false, true) )
return 0;
// merge
return mergeDanglingTail(danglingTailMergeResult);
}
/**
* Attempt to attach vertex with in-degree == 0, or a vertex on its path, to the graph
*
* @param vertex the vertex to recover
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @param minDanglingBranchLength the minimum length of a dangling branch for us to try to merge it
* @return 1 if we successfully recovered a vertex and 0 otherwise
*/
protected int recoverDanglingHead(final MultiDeBruijnVertex vertex, final int pruneFactor, final int minDanglingBranchLength) {
if ( inDegreeOf(vertex) != 0 ) throw new IllegalStateException("Attempting to recover a dangling head for " + vertex + " but it has in-degree > 0");
// generate the CIGAR string from Smith-Waterman between the dangling tail and reference paths
final DanglingChainMergeHelper danglingHeadMergeResult = generateCigarAgainstUpwardsReferencePath(vertex, pruneFactor, minDanglingBranchLength);
// if the CIGAR is too complex (or couldn't be computed) then we do not allow the merge into the reference path
if ( danglingHeadMergeResult == null || ! cigarIsOkayToMerge(danglingHeadMergeResult.cigar, true, false) )
return 0;
// merge
return mergeDanglingHead(danglingHeadMergeResult);
}
/**
* Determine whether the provided cigar is okay to merge into the reference path
*
* @param cigar the cigar to analyze
* @param requireFirstElementM if true, require that the first cigar element be an M operator in order for it to be okay
* @param requireLastElementM if true, require that the last cigar element be an M operator in order for it to be okay
* @return true if it's okay to merge, false otherwise
*/
protected boolean cigarIsOkayToMerge(final Cigar cigar, final boolean requireFirstElementM, final boolean requireLastElementM) {
final List<CigarElement> elements = cigar.getCigarElements();
final int numElements = elements.size();
// don't allow more than a couple of different ops
if ( numElements == 0 || numElements > MAX_CIGAR_COMPLEXITY )
return false;
// the first element must be an M
if ( requireFirstElementM && elements.get(0).getOperator() != CigarOperator.M )
return false;
// the last element must be an M
if ( requireLastElementM && elements.get(numElements - 1).getOperator() != CigarOperator.M )
return false;
// note that there are checks for too many mismatches in the dangling branch later in the process
return true;
}
/**
* Actually merge the dangling tail if possible
*
* @param danglingTailMergeResult the result from generating a Cigar for the dangling tail against the reference
* @return 1 if merge was successful, 0 otherwise
*/
protected int mergeDanglingTail(final DanglingChainMergeHelper danglingTailMergeResult) {
final List<CigarElement> elements = danglingTailMergeResult.cigar.getCigarElements();
final CigarElement lastElement = elements.get(elements.size() - 1);
if ( lastElement.getOperator() != CigarOperator.M )
throw new IllegalArgumentException("The last Cigar element must be an M");
final int lastRefIndex = danglingTailMergeResult.cigar.getReferenceLength() - 1;
final int matchingSuffix = Math.min(GraphUtils.longestSuffixMatch(danglingTailMergeResult.referencePathString, danglingTailMergeResult.danglingPathString, lastRefIndex), lastElement.getLength());
if ( matchingSuffix == 0 )
return 0;
final int altIndexToMerge = Math.max(danglingTailMergeResult.cigar.getReadLength() - matchingSuffix - 1, 0);
// there is an important edge condition that we need to handle here: Smith-Waterman correctly calculates that there is a
// deletion, that deletion is left-aligned such that the LCA node is part of that deletion, and the rest of the dangling
// tail is a perfect match to the suffix of the reference path. In this case we need to push the reference index to merge
// down one position so that we don't incorrectly cut a base off of the deletion.
final boolean firstElementIsDeletion = elements.get(0).getOperator() == CigarOperator.D;
final boolean mustHandleLeadingDeletionCase = firstElementIsDeletion && (elements.get(0).getLength() + matchingSuffix == lastRefIndex + 1);
final int refIndexToMerge = lastRefIndex - matchingSuffix + 1 + (mustHandleLeadingDeletionCase ? 1 : 0);
// another edge condition occurs here: if Smith-Waterman places the whole tail into an insertion then it will try to
// merge back to the LCA, which results in a cycle in the graph. So we do not want to merge in such a case.
if ( refIndexToMerge == 0 )
return 0;
// it's safe to merge now
addEdge(danglingTailMergeResult.danglingPath.get(altIndexToMerge), danglingTailMergeResult.referencePath.get(refIndexToMerge), ((MyEdgeFactory)getEdgeFactory()).createEdge(false, 1));
return 1;
}
/**
* Actually merge the dangling head if possible
*
* @param danglingHeadMergeResult the result from generating a Cigar for the dangling head against the reference
* @return 1 if merge was successful, 0 otherwise
*/
protected int mergeDanglingHead(final DanglingChainMergeHelper danglingHeadMergeResult) {
final List<CigarElement> elements = danglingHeadMergeResult.cigar.getCigarElements();
final CigarElement firstElement = elements.get(0);
if ( firstElement.getOperator() != CigarOperator.M )
throw new IllegalArgumentException("The first Cigar element must be an M");
final int indexesToMerge = bestPrefixMatch(danglingHeadMergeResult.referencePathString, danglingHeadMergeResult.danglingPathString, firstElement.getLength());
if ( indexesToMerge <= 0 )
return 0;
// we can't push back the reference path
if ( indexesToMerge >= danglingHeadMergeResult.referencePath.size() - 1 )
return 0;
// but we can manipulate the dangling path if we need to
if ( indexesToMerge >= danglingHeadMergeResult.danglingPath.size() &&
! extendDanglingPathAgainstReference(danglingHeadMergeResult, indexesToMerge - danglingHeadMergeResult.danglingPath.size() + 2) )
return 0;
addEdge(danglingHeadMergeResult.referencePath.get(indexesToMerge+1), danglingHeadMergeResult.danglingPath.get(indexesToMerge), ((MyEdgeFactory)getEdgeFactory()).createEdge(false, 1));
return 1;
}
/**
* Generates the CIGAR string from the Smith-Waterman alignment of the dangling path (where the
* provided vertex is the sink) and the reference path.
*
* @param vertex the sink of the dangling chain
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @return a SmithWaterman object which can be null if no proper alignment could be generated
*/
protected DanglingChainMergeHelper generateCigarAgainstDownwardsReferencePath(final MultiDeBruijnVertex vertex, final int pruneFactor, final int minDanglingBranchLength) {
final int minTailPathLength = Math.max(1, minDanglingBranchLength); // while heads can be 0, tails absolutely cannot
// find the lowest common ancestor path between this vertex and the diverging master path if available
final List<MultiDeBruijnVertex> altPath = findPathUpwardsToLowestCommonAncestor(vertex, pruneFactor);
if ( altPath == null || isRefSource(altPath.get(0)) || altPath.size() < minTailPathLength + 1 ) // add 1 to include the LCA
return null;
// now get the reference path from the LCA
final List<MultiDeBruijnVertex> refPath = getReferencePath(altPath.get(0), TraversalDirection.downwards, Arrays.asList(incomingEdgeOf(altPath.get(1))));
// create the Smith-Waterman strings to use
final byte[] refBases = getBasesForPath(refPath, false);
final byte[] altBases = getBasesForPath(altPath, false);
// run Smith-Waterman to determine the best alignment (and remove trailing deletions since they aren't interesting)
final SmithWaterman alignment = new SWPairwiseAlignment(refBases, altBases, SWParameterSet.STANDARD_NGS, SWPairwiseAlignment.OVERHANG_STRATEGY.LEADING_INDEL);
return new DanglingChainMergeHelper(altPath, refPath, altBases, refBases, AlignmentUtils.removeTrailingDeletions(alignment.getCigar()));
}
/**
* Generates the CIGAR string from the Smith-Waterman alignment of the dangling path (where the
* provided vertex is the source) and the reference path.
*
* @param vertex the source of the dangling head
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @return a SmithWaterman object which can be null if no proper alignment could be generated
*/
protected DanglingChainMergeHelper generateCigarAgainstUpwardsReferencePath(final MultiDeBruijnVertex vertex, final int pruneFactor, final int minDanglingBranchLength) {
// find the highest common descendant path between vertex and the reference source if available
final List<MultiDeBruijnVertex> altPath = findPathDownwardsToHighestCommonDescendantOfReference(vertex, pruneFactor);
if ( altPath == null || isRefSink(altPath.get(0)) || altPath.size() < minDanglingBranchLength + 1 ) // add 1 to include the LCA
return null;
// now get the reference path from the LCA
final List<MultiDeBruijnVertex> refPath = getReferencePath(altPath.get(0), TraversalDirection.upwards, Collections.<MultiSampleEdge>emptyList());
// create the Smith-Waterman strings to use
final byte[] refBases = getBasesForPath(refPath, true);
final byte[] altBases = getBasesForPath(altPath, true);
// run Smith-Waterman to determine the best alignment (and remove trailing deletions since they aren't interesting)
final SmithWaterman alignment = new SWPairwiseAlignment(refBases, altBases, SWParameterSet.STANDARD_NGS, SWPairwiseAlignment.OVERHANG_STRATEGY.LEADING_INDEL);
return new DanglingChainMergeHelper(altPath, refPath, altBases, refBases, AlignmentUtils.removeTrailingDeletions(alignment.getCigar()));
}
/**
* Finds the path upwards in the graph from this vertex to the first diverging node, including that (lowest common ancestor) vertex.
* Note that nodes are excluded if their pruning weight is less than the pruning factor.
*
* @param vertex the original vertex
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @return the path if it can be determined or null if this vertex either doesn't merge onto another path or
* has an ancestor with multiple incoming edges before hitting the reference path
*/
protected List<MultiDeBruijnVertex> findPathUpwardsToLowestCommonAncestor(final MultiDeBruijnVertex vertex, final int pruneFactor) {
final LinkedList<MultiDeBruijnVertex> path = new LinkedList<>();
MultiDeBruijnVertex v = vertex;
while ( inDegreeOf(v) == 1 && outDegreeOf(v) < 2 ) {
final MultiSampleEdge edge = incomingEdgeOf(v);
// if it has too low a weight, don't use it (or previous vertexes) for the path
if ( edge.getPruningMultiplicity() < pruneFactor )
path.clear();
// otherwise it is safe to use
else
path.addFirst(v);
v = getEdgeSource(edge);
}
path.addFirst(v);
return outDegreeOf(v) > 1 ? path : null;
}
/**
* Finds the path downwards in the graph from this vertex to the reference sequence, including the highest common descendant vertex.
* However note that the path is reversed so that this vertex ends up at the end of the path.
* Also note that nodes are excluded if their pruning weight is less than the pruning factor.
*
* @param vertex the original vertex
* @param pruneFactor the prune factor to use in ignoring chain pieces
* @return the path if it can be determined or null if this vertex either doesn't merge onto the reference path or
* has a descendant with multiple outgoing edges before hitting the reference path
*/
protected List<MultiDeBruijnVertex> findPathDownwardsToHighestCommonDescendantOfReference(final MultiDeBruijnVertex vertex, final int pruneFactor) {
final LinkedList<MultiDeBruijnVertex> path = new LinkedList<>();
MultiDeBruijnVertex v = vertex;
while ( ! isReferenceNode(v) && outDegreeOf(v) == 1 ) {
final MultiSampleEdge edge = outgoingEdgeOf(v);
// if it has too low a weight, don't use it (or previous vertexes) for the path
if ( edge.getPruningMultiplicity() < pruneFactor )
path.clear();
// otherwise it is safe to use
else
path.addFirst(v);
v = getEdgeTarget(edge);
}
path.addFirst(v);
return isReferenceNode(v) ? path : null;
}
private enum TraversalDirection {
downwards,
upwards
}
/**
* Finds the path in the graph from this vertex to the reference sink, including this vertex
*
* @param start the reference vertex to start from
* @param direction describes which direction to move in the graph (i.e. down to the reference sink or up to the source)
* @param blacklistedEdges edges to ignore in the traversal down; useful to exclude the non-reference dangling paths
* @return the path (non-null, non-empty)
*/
protected List<MultiDeBruijnVertex> getReferencePath(final MultiDeBruijnVertex start,
final TraversalDirection direction,
final Collection<MultiSampleEdge> blacklistedEdges) {
final List<MultiDeBruijnVertex> path = new ArrayList<>();
MultiDeBruijnVertex v = start;
while ( v != null ) {
path.add(v);
v = (direction == TraversalDirection.downwards ? getNextReferenceVertex(v, true, blacklistedEdges) : getPrevReferenceVertex(v));
}
return path;
}
/**
* The base sequence for the given path.
*
* @param path the list of vertexes that make up the path
* @param expandSource if true and if we encounter a source node, then expand (and reverse) the character sequence for that node
* @return non-null sequence of bases corresponding to the given path
*/
public byte[] getBasesForPath(final List<MultiDeBruijnVertex> path, final boolean expandSource) {
if ( path == null ) throw new IllegalArgumentException("Path cannot be null");
final StringBuilder sb = new StringBuilder();
for ( final MultiDeBruijnVertex v : path ) {
if ( expandSource && isSource(v) ) {
final String seq = v.getSequenceString();
sb.append(new StringBuilder(seq).reverse().toString());
} else {
sb.append((char)v.getSuffix());
}
}
return sb.toString().getBytes();
}
/**
* Finds the index of the best extent of the prefix match between the provided paths, for dangling head merging.
* Assumes that path1.length >= maxIndex and path2.length >= maxIndex.
*
* @param path1 the first path
* @param path2 the second path
* @param maxIndex the maximum index to traverse (not inclusive)
* @return the index of the ideal prefix match or -1 if it cannot find one, must be less than maxIndex
*/
protected int bestPrefixMatch(final byte[] path1, final byte[] path2, final int maxIndex) {
final int maxMismatches = getMaxMismatches(maxIndex);
int mismatches = 0;
int index = 0;
int lastGoodIndex = -1;
while ( index < maxIndex ) {
if ( path1[index] != path2[index] ) {
if ( ++mismatches > maxMismatches )
return -1;
lastGoodIndex = index;
}
index++;
}
// if we got here then we hit the max index
return lastGoodIndex;
}
/**
* Determine the maximum number of mismatches permitted on the branch.
* Unless it's preset (e.g. by unit tests) it should be the length of the branch divided by the kmer size.
*
* @param lengthOfDanglingBranch the length of the branch itself
* @return positive integer
*/
private int getMaxMismatches(final int lengthOfDanglingBranch) {
return maxMismatchesInDanglingHead > 0 ? maxMismatchesInDanglingHead : Math.max(1, (lengthOfDanglingBranch / kmerSize));
}
protected boolean extendDanglingPathAgainstReference(final DanglingChainMergeHelper danglingHeadMergeResult, final int numNodesToExtend) {
final int indexOfLastDanglingNode = danglingHeadMergeResult.danglingPath.size() - 1;
final int indexOfRefNodeToUse = indexOfLastDanglingNode + numNodesToExtend;
if ( indexOfRefNodeToUse >= danglingHeadMergeResult.referencePath.size() )
return false;
final MultiDeBruijnVertex danglingSource = danglingHeadMergeResult.danglingPath.remove(indexOfLastDanglingNode);
final StringBuilder sb = new StringBuilder();
final byte[] refSourceSequence = danglingHeadMergeResult.referencePath.get(indexOfRefNodeToUse).getSequence();
for ( int i = 0; i < numNodesToExtend; i++ )
sb.append((char)refSourceSequence[i]);
sb.append(danglingSource.getSequenceString());
final byte[] sequenceToExtend = sb.toString().getBytes();
// clean up the source and edge
final MultiSampleEdge sourceEdge = outgoingEdgeOf(danglingSource);
MultiDeBruijnVertex prevV = getEdgeTarget(sourceEdge);
removeEdge(danglingSource, prevV);
// extend the path
for ( int i = numNodesToExtend; i > 0; i-- ) {
final MultiDeBruijnVertex newV = new MultiDeBruijnVertex(Arrays.copyOfRange(sequenceToExtend, i, i+kmerSize));
addVertex(newV);
final MultiSampleEdge newE = addEdge(newV, prevV);
newE.setMultiplicity(sourceEdge.getMultiplicity());
danglingHeadMergeResult.danglingPath.add(newV);
prevV = newV;
}
return true;
}
}
| 50.548571
| 203
| 0.692742
|
4035137bb78efa79dadcd7e4a685f65ad3484136
| 6,911
|
package com.softmotions.ncms.mhttl;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections4.map.Flat3Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.softmotions.commons.string.EscapeHelper;
import com.softmotions.ncms.NcmsEnvironment;
import com.softmotions.ncms.asm.render.AsmRendererContext;
import com.softmotions.ncms.mtt.http.MttHttpFilter;
import com.softmotions.ncms.mtt.tp.MttActivatedTp;
import com.softmotions.ncms.mtt.tp.MttTpService;
import com.softmotions.web.HttpUtils;
/**
* @author Adamansky Anton (adamansky@softmotions.com)
*/
@SuppressWarnings("unchecked")
public class HttlMttMethods {
private static final Logger log = LoggerFactory.getLogger(HttlMttMethods.class);
private HttlMttMethods() {
}
///////////////////////////////////////////////////////////
// A/B Testing //
///////////////////////////////////////////////////////////
public static boolean abtA() {
return abt("a", false);
}
public static boolean abtB() {
return abt("b", false);
}
public static boolean abtC() {
return abt("c", false);
}
public static boolean abtD() {
return abt("d", false);
}
public static boolean abt(String name) {
return abt(name, false);
}
/**
* A/B testing check.
*
* @param name A/B mode to test
* @param def Default value if A/B test is not passed
*/
public static boolean abt(String name, boolean def) {
if (name == null) {
return def;
}
AsmRendererContext ctx = AsmRendererContext.getSafe();
NcmsEnvironment env = ctx.getEnvironment();
HttpServletRequest req = ctx.getServletRequest();
String pi = req.getRequestURI();
boolean isAdmRequest = pi.startsWith(env.getNcmsAdminRoot());
if (isAdmRequest) { // All A/B modes are ON in admin preview mode
return true;
}
name = name.toLowerCase();
//noinspection unchecked
Collection<Long> rids = (Collection<Long>) req.getAttribute(MttHttpFilter.MTT_RIDS_KEY);
if (rids == null || rids.isEmpty()) {
Enumeration<String> pnames = req.getParameterNames();
while (pnames.hasMoreElements()) {
String pn = pnames.nextElement();
if (pn.startsWith("_abm_")) {
String pv = req.getParameter(pn);
if (pv != null) {
StringTokenizer st = new StringTokenizer(",");
while (st.hasMoreTokens()) {
String m = st.nextToken().trim();
if (m.equals(name)) {
if (log.isDebugEnabled()) {
log.debug("Found _abm_ request parameter: {}={}", pn, pv);
}
return true;
}
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("No mtt actions found, no _abm_ request parameters found");
}
return def;
}
Long mrid = null;
Cookie mcookie = null;
Set<String> marks = null;
for (Long rid : rids) {
//noinspection unchecked
Set<String> m = (Set<String>) req.getAttribute("_abm_" + rid);
if (m != null) {
mrid = rid;
marks = m;
}
}
if (marks == null) {
for (Long rid : rids) {
Cookie cookie = HttpUtils.findCookie(req, "_abm_" + rid);
if (cookie != null) {
mrid = rid;
mcookie = cookie;
}
}
if (mcookie != null) {
String[] split = StringUtils.split(EscapeHelper.decodeURIComponent(mcookie.getValue()), ",");
marks = new HashSet<>(split.length);
Collections.addAll(marks, split);
req.setAttribute("_abm_" + mrid, marks);
}
}
if (log.isDebugEnabled()) {
log.debug("AB Marks: {} matches: {}={}", marks, name,
(marks != null && marks.contains(name))
);
}
if (marks == null) {
return def;
}
return marks.contains(name) || def;
}
///////////////////////////////////////////////////////////
// Pixel tracking //
///////////////////////////////////////////////////////////
private static final AtomicReference<MttTpService> TP_SERVICE_REF = new AtomicReference<>();
public static String trackingPixels() {
return trackingPixels("*");
}
public static String trackingPixels(String tpNameGlob) {
return trackingPixels(tpNameGlob, null);
}
public static String trackingPixels(String tpNameGlob,
@Nullable Map<String, Object> params) {
if (params == null) {
params = new Flat3Map<>();
}
AsmRendererContext ctx = AsmRendererContext.getSafe();
MttTpService tps = TP_SERVICE_REF.updateAndGet(
mttTpService ->
mttTpService != null ? mttTpService : ctx.getInjector().getInstance(MttTpService.class)
);
// Pair<Tp URL, Tp Script>
Iterable<MttActivatedTp> activatedTps =
tps.activateTrackingPixels(ctx.getServletRequest(),
ctx.getServletResponse(),
tpNameGlob, params, true);
StringBuilder sb = new StringBuilder(255);
String sep = System.getProperty("line.separator");
for (final MttActivatedTp atp : activatedTps) {
if (!StringUtils.isBlank(atp.getUrl())) {
sb.append(sep)
.append("<img style=\"display:none;\" width=\"0\" height=\"0\" src=\"")
.append(atp.getUrl())
.append("\"/>");
}
if (!StringUtils.isBlank(atp.getScript())) {
sb.append(sep)
.append("<script type=\"text/javascript\">")
.append(atp.getScript())
.append("</script>");
}
}
return sb.toString();
}
}
| 34.212871
| 111
| 0.514108
|
920ef510c4999edb429fd3be5b1ac2fa3aa9174a
| 1,169
|
/**
* This file is licensed under the University of Illinois/NCSA Open Source License. See LICENSE.TXT for details.
*/
package edu.illinois.codingspectator.ui.tests.extractsuperclass;
import org.eclipse.jface.dialogs.IDialogConstants;
import edu.illinois.codingspectator.ui.tests.RefactoringTest;
/**
*
* @author Mohsen Vakilian
* @author nchen
*
*/
public class T04 extends RefactoringTest {
private static final String EXTRACT_SUPERCLASS_MENU_ITEM= "Extract Superclass...";
protected static final String SUPERCLASS_NAME_LABEL= "Superclass name:";
private final static String SELECTION= "methodToBePulledUp";
private final static String NEW_SUPERCLASS_NAME= "NewSuperClassName";
@Override
protected String getTestFileName() {
return "ExtractSuperclassTestFile";
}
@Override
protected void doExecuteRefactoring() {
bot.selectElementToRefactor(getTestFileFullName(), 11, 16, SELECTION.length());
bot.invokeRefactoringFromMenu(EXTRACT_SUPERCLASS_MENU_ITEM);
bot.fillTextField(SUPERCLASS_NAME_LABEL, NEW_SUPERCLASS_NAME);
bot.clickButtons(IDialogConstants.NEXT_LABEL, IDialogConstants.NEXT_LABEL, IDialogConstants.CANCEL_LABEL);
}
}
| 29.225
| 112
| 0.798973
|
6596f4ee5b443f1fedeb552807feb176456682ae
| 1,831
|
package com.linnanc.dao.impl;
import com.linnanc.dao.AccountDao;
import com.linnanc.entity.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Lin
* @version 1.0.0
* @ClassName AccountDao
* @description TODO
* @date 2021/12/31
*/
public class AccountDaoImpl implements AccountDao {
@Override
public Account getAccountByNumber(String accountNumber) {
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("mybatis.xml");
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Account account = sqlSession.selectOne("getAccountByNumber", accountNumber);
sqlSession.close();
return account;
}
@Override
public void updateAccountByNumber(Account account) {
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("mybatis.xml");
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int updateAccountByNumber = sqlSession.update("updateAccountByNumber", account);
System.out.println(account.getAccountNumber() + " " + account.getBalance());
System.out.println(updateAccountByNumber);
sqlSession.commit();
sqlSession.close();
}
}
| 30.516667
| 96
| 0.694702
|
d45acce1b9fec1efc71f683288a740fef90a83bc
| 947
|
package com.jun.timer.dao.po;
public class MessagePO {
private Integer id;
private String jobId;
private String address;
private String body;
private Boolean type;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId == null ? null : jobId.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body == null ? null : body.trim();
}
public Boolean getType() {
return type;
}
public void setType(Boolean type) {
this.type = type;
}
}
| 17.867925
| 63
| 0.570222
|
3e87758a0768d70bfa4bf0201dc7f6ddad73f71e
| 7,964
|
package no.ion.jake.engine;
import com.sun.management.ThreadMXBean;
import no.ion.jake.LogSink;
import no.ion.jake.graph.BuildOrder;
import no.ion.jake.util.SetUtil;
import java.lang.management.ManagementFactory;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import static java.util.function.Function.identity;
public class BuildGraph implements AutoCloseable {
private final JakeExecutor jakeExecutor;
private final ScheduledExecutorService loadUpdaterService;
private final ThreadMXBean threadMXBean;
private final BuildOrder<BuildId> buildOrder;
private final ArtifactRegistry artifactRegistry;
private final LogSink logSink;
private final Map<BuildId, BuildInfo> builds;
private final float targetLoad;
private final AtomicLong loadx1000 = new AtomicLong(0L);
private final AtomicLong artificialLoadx1000 = new AtomicLong(0L);
private final AtomicLong pendingArtificialLoadx1000 = new AtomicLong(0L);
private final Object monitor = new Object();
private static final int loadUpdateIntervalInMillis = 100;
private volatile long lastSumCpuTimeNanos = 0;
public BuildGraph(JakeExecutor jakeExecutor, float targetLoad, BuildOrder<BuildId> buildOrder,
Collection<BuildInfo> builds, ArtifactRegistry artifactRegistry, LogSink logSink) {
this.jakeExecutor = jakeExecutor;
this.targetLoad = targetLoad;
this.buildOrder = buildOrder;
this.artifactRegistry = artifactRegistry;
this.logSink = logSink;
this.builds = builds.stream().collect(Collectors.toMap(BuildInfo::id, identity()));
java.lang.management.ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
if (!(threadMXBean instanceof ThreadMXBean)) {
// add other JVMs when needed...
throw new IllegalStateException("implementation requires Sun/Oracle based JVM");
}
this.threadMXBean = (ThreadMXBean) threadMXBean;
if (!threadMXBean.isThreadCpuTimeSupported()) {
throw new IllegalStateException("implementation requires JVM supports thread CPU time");
}
if (!threadMXBean.isThreadCpuTimeEnabled()) {
threadMXBean.setThreadCpuTimeEnabled(true);
}
this.loadUpdaterService = Executors.newScheduledThreadPool(1);
loadUpdaterService.scheduleAtFixedRate(this::updateLoad, 0, loadUpdateIntervalInMillis, TimeUnit.MILLISECONDS);
}
public void runSync() {
Deque<ResultInfo> results = new ArrayDeque<>();
synchronized (monitor) {
while (true) {
BuildOrder.NextBuild<BuildId> nextBuild = buildOrder.calculateNextBuild();
if (nextBuild.isDone()) {
return;
}
if (nextBuild.isReady()) {
if (spawnBuild(nextBuild.getReadyBuild(), results)) {
continue;
}
}
if (!results.isEmpty()) {
handleResultInfo(results.pollFirst());
continue;
}
// getting here also if load is too high. Should sleep until the load have had a chance to lower.
try { monitor.wait(10); } catch (InterruptedException ignore) { }
}
}
}
private static class ResultInfo {
private final BuildInfo buildInfo;
private final BuildResult result;
public ResultInfo(BuildInfo buildInfo, BuildResult result) {
this.buildInfo = buildInfo;
this.result = result;
}
}
private boolean spawnBuild(BuildId buildId, Deque<ResultInfo> results) {
final BuildInfo buildInfo = builds.get(buildId);
if (buildInfo == null) {
throw new IllegalStateException("build ID does not exist: " + buildId.toString());
}
if (!loadAllowsAnotherBuild(buildInfo)) {
return false;
}
buildOrder.reportActiveBuild(buildId);
// TODO: Add something other than 1, e.g. expectedLoad + slack.
final long loadx1000 = 1000L;
artificialLoadx1000.addAndGet(loadx1000);
jakeExecutor.runAsync(() -> {
pendingArtificialLoadx1000.addAndGet(-loadx1000);
SingleBuildDriver driver = new SingleBuildDriver(logSink);
BuildResult result = driver.runSync(artifactRegistry, buildInfo);
synchronized (monitor) {
buildOrder.reportCompletedBuild(buildId);
results.addLast(new ResultInfo(buildInfo, result));
monitor.notify();
}
});
return true;
}
private void handleResultInfo(ResultInfo resultInfo) {
BuildResult result = resultInfo.result;
BuildInfo completedBuild = resultInfo.buildInfo;
result.getRuntimeException().ifPresent(e -> {
throw e;
});
result.getError().ifPresent(e -> {
throw e;
});
Set<ArtifactId> declaredArtifacts = completedBuild.production();
Set<ArtifactId> publishedArtifacts = result.publishedArtifacts();
Set<ArtifactId> unpublishedArtifacts = SetUtil.difference(declaredArtifacts, publishedArtifacts);
if (!unpublishedArtifacts.isEmpty()) {
throw new BadBuildException(completedBuild.build(), "failed to publish: " +
unpublishedArtifacts.stream().map(ArtifactId::artifactName).collect(Collectors.joining(", ")));
}
Set<ArtifactId> unknownArtifacts = SetUtil.difference(publishedArtifacts, declaredArtifacts);
if (!unknownArtifacts.isEmpty()) {
// this is impossible at the time this comment was made
throw new BadBuildException(completedBuild.build(), "published extraneous artifacts: " +
unknownArtifacts.stream().map(ArtifactId::artifactName).collect(Collectors.joining(", ")));
}
}
@Override
public void close() {
loadUpdaterService.shutdown();
for (;;) {
try {
if (loadUpdaterService.awaitTermination(1, TimeUnit.SECONDS)) {
break;
}
} catch (InterruptedException ignored) {
logSink.log(Level.WARNING, "was interrupted during shutdown, ignoring", null);
}
// loop around
}
}
private boolean loadAllowsAnotherBuild(BuildInfo buildInfo) {
float currentTargetLoad = targetLoad > 0 ? targetLoad : -targetLoad * Runtime.getRuntime().availableProcessors();
// If adding another builds gets us within +- 0.5 of target load, or lower.
// The artificial load is artificial load is incremented preemptively, in case true is returned.
float newLoad = (loadx1000.get() + artificialLoadx1000.get()) / 1000.0f + 1f;
return newLoad < currentTargetLoad + 0.5f;
}
private void updateLoad() {
long previousSumCpuTimes = lastSumCpuTimeNanos;
long[] threadIds = threadMXBean.getAllThreadIds();
long[] threadCpuTimesNanos = threadMXBean.getThreadCpuTime(threadIds);
long sumCpuTimeNanos = LongStream.of(threadCpuTimesNanos).sum();
long nanos = Math.max(0L, sumCpuTimeNanos - previousSumCpuTimes);
float newLoad = nanos / (1000_000f * loadUpdateIntervalInMillis);
loadx1000.set((long) (newLoad * 1000L));
lastSumCpuTimeNanos = sumCpuTimeNanos;
artificialLoadx1000.addAndGet(pendingArtificialLoadx1000.getAndSet(0L));
}
}
| 38.660194
| 121
| 0.655324
|
076a01e347b61a8002cc868029f45c082863c027
| 4,404
|
package com.yangyuan.wififileshare.wifUtils.admin;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;
import com.yangyuan.wififileshare.wifUtils.TimerCheck;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 创建热点
*/
public class WifiApAdmin
{
public static final String TAG = "WifiApAdmin";
public static void closeWifiAp(Context context)
{
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
closeWifiAp(wifiManager);
}
private WifiManager mWifiManager = null;
private Context mContext = null;
public WifiApAdmin(Context context)
{
mContext = context;
mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
closeWifiAp(mWifiManager);
}
private String mSSID = "";
private String mPasswd = "";
public void startWifiAp(String ssid, String passwd)
{
mSSID = ssid;
mPasswd = passwd;
if (mWifiManager.isWifiEnabled())
{
mWifiManager.setWifiEnabled(false);
}
stratWifiAp();
TimerCheck timerCheck = new TimerCheck()
{
@Override
public void doTimerCheckWork()
{
// TODO Auto-generated method stub
if (isWifiApEnabled(mWifiManager))
{
Log.v(TAG, "Wifi enabled success!");
this.exit();
} else
{
Log.v(TAG, "Wifi enabled failed!");
}
}
@Override
public void doTimeOutWork()
{
// TODO Auto-generated method stub
this.exit();
}
};
timerCheck.start(15, 1000);
}
public void stratWifiAp()
{
Method method1 = null;
try
{
method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = mSSID;
netConfig.preSharedKey = mPasswd;
netConfig.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.TKIP);
method1.invoke(mWifiManager, netConfig, true);
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeWifiAp(WifiManager wifiManager)
{
if (isWifiApEnabled(wifiManager))
{
try
{
Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
method.setAccessible(true);
WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method2.invoke(wifiManager, config, false);
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static boolean isWifiApEnabled(WifiManager wifiManager)
{
try
{
Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifiManager);
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return false;
}
}
| 23.301587
| 114
| 0.718665
|
ce7200e51cba22b3de27cbe225c72a050b744a5a
| 2,974
|
/**
* Copyright 2019 ISTAT
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence. You may
* obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl5
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations under
* the Licence.
*
* @author Francesco Amato <framato @ istat.it>
* @author Mauro Bruno <mbruno @ istat.it>
* @author Paolo Francescangeli <pafrance @ istat.it>
* @author Renzo Iannacone <iannacone @ istat.it>
* @author Stefano Macone <macone @ istat.it>
* @version 1.0
*/
package it.istat.is2.auth.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import it.istat.is2.auth.dao.UserDao;
import it.istat.is2.auth.dao.UserRolesDao;
import it.istat.is2.auth.domain.User;
import it.istat.is2.auth.security.CustomUserDetails;
@Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserDao userDao;
private final UserRolesDao userRolesDao;
@Autowired
private AuthenticationManager am;
@Autowired
public CustomUserDetailsService(UserDao userDao, UserRolesDao userRolesDao) {
this.userDao = userDao;
this.userRolesDao = userRolesDao;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
CustomUserDetails cud;
if (null == user) {
throw new UsernameNotFoundException("No user present with user: " + username);
} else {
List<String> userRoles = userRolesDao.findRolesByUsername(username);
cud = new CustomUserDetails(user, userRoles);
return cud;
}
}
public void authenticate(String name, Object password) {
Authentication request = new UsernamePasswordAuthenticationToken(name, password);
Authentication result = am.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
}
}
| 37.175
| 93
| 0.753531
|
bf418ef519ed3bf3d47162090e5c6003e57f2a11
| 1,123
|
package com.pivotal.pxf.plugins.redis;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.pivotal.pxf.api.Analyzer;
import com.pivotal.pxf.api.AnalyzerStats;
import com.pivotal.pxf.api.utilities.InputData;
import redis.clients.jedis.Jedis;
public class RedisHashAnalyzer extends Analyzer {
private Parameters params = null;
private static final Log LOG = LogFactory.getLog(RedisHashAnalyzer.class);
public RedisHashAnalyzer(InputData inputData) throws Exception {
super(inputData);
params = new Parameters(inputData);
}
@Override
public AnalyzerStats getEstimatedStats(String data) throws Exception {
long numberOfBlocks = params.getHosts().length;
long numberOfTuples = 0L;
for (String host : params.getHosts()) {
Jedis jedis = new Jedis(host);
numberOfTuples += jedis.hlen(params.getHashKey());
jedis.disconnect();
}
AnalyzerStats stats = new AnalyzerStats(0L, numberOfBlocks,
numberOfTuples);
LOG.info(AnalyzerStats.dataToString(stats, params.getHostString()));
return stats;
}
}
| 25.522727
| 76
| 0.73642
|
e88e325195003c8b5c807c9a47123c0d5f74977f
| 1,164
|
/*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Simple class Foo to be used in classloader testing
* This class should be kept here and not in velocity.jar
* to keep out of the parent classloader of the test
* classloader
*/
public class Foo
{
/*
* the ClassloaderChangeTest
* depends on this string as
* is. If this changes (there is no reason
* to ever do that, BTW), then
* udpate ClassloaderChangeTest as well.
*/
private static String MSG =
"Hello From Foo";
public String doIt()
{
return MSG;
}
}
| 28.390244
| 75
| 0.684708
|
7b0656a5d35b8aada20c46c8ee3acf5e5e9614b9
| 3,585
|
/* ClassPersistenceDelegate.java - A PersistenceDelegate for the Class type.
Copyright (C) 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.beans.encoder;
import java.beans.Encoder;
import java.beans.Expression;
import java.beans.PersistenceDelegate;
/** <p>The <code>ClassPersistenceDelegate</code> creates
* <code>Expression</code> instances which denote class resolutions.</p>
*
* <p>The class resolution is always the last step when serializing a tree
* of objects. Due to the recursive nature of the algorithm we need a way
* to end the recursion. This is achieved by the implementation of this
* {@link instantiate} method. Arbitrary classes are described with a call
* to <code>Class.forName</code>. However for the <code>Class</code> class
* we call <code>getClass()</code> on a <code>String.class</code> instance.
* This in turn lead to the resolution of the String class which is always
* encoded as <code>"".getClass()</code>. Finally the <code>Encoder</code>
* treats strings in a special way so that the recursion ends here.
*
* @author Robert Schuster (robertschuster@fsfe.org)
*/
public class ClassPersistenceDelegate extends PersistenceDelegate
{
protected Expression instantiate(Object oldInstance, Encoder out)
{
Class oldClass = (Class) oldInstance;
// Due to the special handling of String instances in the Encoder
// this Expression does not lead to further class resolutions.
if (oldClass == String.class)
return new Expression(oldClass, "", "getClass", null);
// This Expression will lead to the class resolution of String.class.
if (oldClass == Class.class)
return new Expression(oldClass, String.class, "getClass", null);
// This Expression will lead to the class resolution of Class.class.
return new Expression(oldClass, Class.class, "forName",
new Object[] { oldClass.getName() });
}
}
| 44.259259
| 76
| 0.759833
|
4abdc983c65314f3549d66c69bb0b75bb667f91c
| 5,044
|
// This file was generated by Mendix Studio Pro.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package myfirstmodule.proxies;
public class X6Context extends myfirstmodule.proxies.X6Node
{
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "MyFirstModule.X6Context";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
IsEditable("IsEditable"),
x("x"),
y("y"),
width("width"),
height("height"),
label("label");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@java.lang.Override
public java.lang.String toString()
{
return metaName;
}
}
public X6Context(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "MyFirstModule.X6Context"));
}
protected X6Context(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject x6ContextMendixObject)
{
super(context, x6ContextMendixObject);
if (!com.mendix.core.Core.isSubClassOf("MyFirstModule.X6Context", x6ContextMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a MyFirstModule.X6Context");
}
/**
* @deprecated Use 'X6Context.load(IContext, IMendixIdentifier)' instead.
*/
@java.lang.Deprecated
public static myfirstmodule.proxies.X6Context initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return myfirstmodule.proxies.X6Context.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static myfirstmodule.proxies.X6Context initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new myfirstmodule.proxies.X6Context(context, mendixObject);
}
public static myfirstmodule.proxies.X6Context load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return myfirstmodule.proxies.X6Context.initialize(context, mendixObject);
}
public static java.util.List<myfirstmodule.proxies.X6Context> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
{
java.util.List<myfirstmodule.proxies.X6Context> result = new java.util.ArrayList<myfirstmodule.proxies.X6Context>();
for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//MyFirstModule.X6Context" + xpathConstraint))
result.add(myfirstmodule.proxies.X6Context.initialize(context, obj));
return result;
}
/**
* @return value of IsEditable
*/
public final java.lang.Boolean getIsEditable()
{
return getIsEditable(getContext());
}
/**
* @param context
* @return value of IsEditable
*/
public final java.lang.Boolean getIsEditable(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.Boolean) getMendixObject().getValue(context, MemberNames.IsEditable.toString());
}
/**
* Set value of IsEditable
* @param iseditable
*/
public final void setIsEditable(java.lang.Boolean iseditable)
{
setIsEditable(getContext(), iseditable);
}
/**
* Set value of IsEditable
* @param context
* @param iseditable
*/
public final void setIsEditable(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Boolean iseditable)
{
getMendixObject().setValue(context, MemberNames.IsEditable.toString(), iseditable);
}
@java.lang.Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final myfirstmodule.proxies.X6Context that = (myfirstmodule.proxies.X6Context) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@java.lang.Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "MyFirstModule.X6Context";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@java.lang.Override
@java.lang.Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
| 31.72327
| 222
| 0.759318
|
a48b2f5f5780c70716b851336dcd8c5d7d4c2d35
| 843
|
/**
* 给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。
*
* 如果剩余字符少于 k 个,则将剩余字符全部反转。
* 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
*
* 示例:
* 输入: s = "abcdefg", k = 2
* 输出: "bacdfeg"
*
* 提示:
* 该字符串只包含小写英文字母。
* 给定字符串的长度和 k 在 [1, 10000] 范围内。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/reverse-string-ii
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Q00541s {
public String reverseStr(String s, int k) {
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i += 2 * k) {
swap(cs, i, Math.min(cs.length, i + k) - 1);
}
return new String(cs);
}
private void swap(char[] cs, int left, int right) {
while (left < right) {
char c = cs[left];
cs[left++] = cs[right];
cs[right--] = c;
}
}
}
| 23.416667
| 56
| 0.539739
|
ffcd785f9d14ff95285e2875dc0eff3a71f78e07
| 722
|
package dk.brics.jwig.analysis;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Parameters {
private final Map<String, Parameter> parameters;
public Parameters(Set<Parameter> parameterSet) {
this.parameters = new HashMap<String, Parameter>();
for (Parameter parameter : parameterSet) {
parameters.put(parameter.getName(), parameter);
}
}
public Set<String> getNames() {
return parameters.keySet();
}
public Parameter getParameter(String name) {
return parameters.get(name);
}
public Collection<Parameter> getParameters() {
return parameters.values();
}
}
| 23.290323
| 59
| 0.666205
|
2e1815360b93984017126d580d448bba33ce9ff6
| 14,962
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package org.godotengine.godot;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f010003;
public static final int font = 0x7f010008;
public static final int fontProviderAuthority = 0x7f010009;
public static final int fontProviderCerts = 0x7f01000a;
public static final int fontProviderFetchStrategy = 0x7f01000b;
public static final int fontProviderFetchTimeout = 0x7f01000c;
public static final int fontProviderPackage = 0x7f01000d;
public static final int fontProviderQuery = 0x7f01000e;
public static final int fontStyle = 0x7f01000f;
public static final int fontVariationSettings = 0x7f010010;
public static final int fontWeight = 0x7f010011;
public static final int ttcIndex = 0x7f01001d;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f02000f;
public static final int notification_icon_bg_color = 0x7f020010;
public static final int ripple_material_light = 0x7f020011;
public static final int secondary_text_default_material_light = 0x7f020012;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f030002;
public static final int compat_button_inset_vertical_material = 0x7f030003;
public static final int compat_button_padding_horizontal_material = 0x7f030004;
public static final int compat_button_padding_vertical_material = 0x7f030005;
public static final int compat_control_corner_material = 0x7f030006;
public static final int compat_notification_large_icon_max_height = 0x7f030007;
public static final int compat_notification_large_icon_max_width = 0x7f030008;
public static final int notification_action_icon_size = 0x7f030009;
public static final int notification_action_text_size = 0x7f03000a;
public static final int notification_big_circle_margin = 0x7f03000b;
public static final int notification_content_margin_start = 0x7f03000c;
public static final int notification_large_icon_height = 0x7f03000d;
public static final int notification_large_icon_width = 0x7f03000e;
public static final int notification_main_column_padding_top = 0x7f03000f;
public static final int notification_media_narrow_margin = 0x7f030010;
public static final int notification_right_icon_size = 0x7f030011;
public static final int notification_right_side_padding_top = 0x7f030012;
public static final int notification_small_icon_background_padding = 0x7f030013;
public static final int notification_small_icon_size_as_large = 0x7f030014;
public static final int notification_subtext_size = 0x7f030015;
public static final int notification_top_pad = 0x7f030016;
public static final int notification_top_pad_large_text = 0x7f030017;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f040015;
public static final int notification_bg = 0x7f040016;
public static final int notification_bg_low = 0x7f040017;
public static final int notification_bg_low_normal = 0x7f040018;
public static final int notification_bg_low_pressed = 0x7f040019;
public static final int notification_bg_normal = 0x7f04001a;
public static final int notification_bg_normal_pressed = 0x7f04001b;
public static final int notification_icon_background = 0x7f04001c;
public static final int notification_template_icon_bg = 0x7f04001d;
public static final int notification_template_icon_low_bg = 0x7f04001e;
public static final int notification_tile_bg = 0x7f04001f;
public static final int notify_panel_notification_icon_bg = 0x7f040020;
}
public static final class id {
private id() {}
public static final int action_container = 0x7f050000;
public static final int action_divider = 0x7f050001;
public static final int action_image = 0x7f050002;
public static final int action_text = 0x7f050003;
public static final int actions = 0x7f050004;
public static final int appIcon = 0x7f050008;
public static final int approveCellular = 0x7f050009;
public static final int async = 0x7f05000a;
public static final int blocking = 0x7f05000c;
public static final int buttonRow = 0x7f050013;
public static final int cancelButton = 0x7f050014;
public static final int chronometer = 0x7f050018;
public static final int description = 0x7f05001c;
public static final int downloadButton = 0x7f05001d;
public static final int downloaderDashboard = 0x7f05001e;
public static final int forever = 0x7f050023;
public static final int icon = 0x7f050024;
public static final int icon_group = 0x7f050025;
public static final int info = 0x7f050027;
public static final int italic = 0x7f050028;
public static final int line1 = 0x7f05002b;
public static final int line3 = 0x7f05002c;
public static final int normal = 0x7f05002e;
public static final int notificationLayout = 0x7f05002f;
public static final int notification_background = 0x7f050030;
public static final int notification_main_column = 0x7f050031;
public static final int notification_main_column_container = 0x7f050032;
public static final int pauseButton = 0x7f050033;
public static final int progressAsFraction = 0x7f050034;
public static final int progressAsPercentage = 0x7f050035;
public static final int progressAverageSpeed = 0x7f050036;
public static final int progressBar = 0x7f050037;
public static final int progressTimeRemaining = 0x7f050038;
public static final int progress_bar = 0x7f050039;
public static final int progress_bar_frame = 0x7f05003a;
public static final int progress_text = 0x7f05003b;
public static final int resumeOverCellular = 0x7f05003c;
public static final int right_icon = 0x7f05003e;
public static final int right_side = 0x7f05003f;
public static final int statusText = 0x7f050042;
public static final int tag_transition_group = 0x7f050043;
public static final int tag_unhandled_key_event_manager = 0x7f050044;
public static final int tag_unhandled_key_listeners = 0x7f050045;
public static final int text = 0x7f050046;
public static final int text2 = 0x7f050047;
public static final int textPausedParagraph1 = 0x7f050048;
public static final int textPausedParagraph2 = 0x7f050049;
public static final int time = 0x7f05004a;
public static final int time_remaining = 0x7f05004b;
public static final int title = 0x7f05004c;
public static final int wifiSettingsButton = 0x7f05004f;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f060001;
}
public static final class layout {
private layout() {}
public static final int downloading_expansion = 0x7f070002;
public static final int notification_action = 0x7f070003;
public static final int notification_action_tombstone = 0x7f070004;
public static final int notification_template_custom_big = 0x7f070005;
public static final int notification_template_icon_group = 0x7f070006;
public static final int notification_template_part_chronometer = 0x7f070007;
public static final int notification_template_part_time = 0x7f070008;
public static final int status_bar_ongoing_event_progress_bar = 0x7f070009;
}
public static final class mipmap {
private mipmap() {}
public static final int icon = 0x7f080000;
public static final int icon_background = 0x7f080001;
public static final int icon_foreground = 0x7f080002;
}
public static final class string {
private string() {}
public static final int godot_project_name_string = 0x7f090012;
public static final int kilobytes_per_second = 0x7f090014;
public static final int notification_download_complete = 0x7f090015;
public static final int notification_download_failed = 0x7f090016;
public static final int state_completed = 0x7f09001e;
public static final int state_connecting = 0x7f09001f;
public static final int state_downloading = 0x7f090020;
public static final int state_failed = 0x7f090021;
public static final int state_failed_cancelled = 0x7f090022;
public static final int state_failed_fetching_url = 0x7f090023;
public static final int state_failed_sdcard_full = 0x7f090024;
public static final int state_failed_unlicensed = 0x7f090025;
public static final int state_fetching_url = 0x7f090026;
public static final int state_idle = 0x7f090027;
public static final int state_paused_by_request = 0x7f090028;
public static final int state_paused_network_setup_failure = 0x7f090029;
public static final int state_paused_network_unavailable = 0x7f09002a;
public static final int state_paused_roaming = 0x7f09002b;
public static final int state_paused_sdcard_unavailable = 0x7f09002c;
public static final int state_paused_wifi_disabled = 0x7f09002d;
public static final int state_paused_wifi_unavailable = 0x7f09002e;
public static final int state_unknown = 0x7f09002f;
public static final int status_bar_notification_info_overflow = 0x7f090030;
public static final int text_button_cancel = 0x7f090031;
public static final int text_button_cancel_verify = 0x7f090032;
public static final int text_button_pause = 0x7f090033;
public static final int text_button_resume = 0x7f090034;
public static final int text_button_resume_cellular = 0x7f090035;
public static final int text_button_wifi_settings = 0x7f090036;
public static final int text_paused_cellular = 0x7f090037;
public static final int text_paused_cellular_2 = 0x7f090038;
public static final int text_validation_complete = 0x7f090039;
public static final int text_validation_failed = 0x7f09003a;
public static final int text_verifying_download = 0x7f09003b;
public static final int time_remaining = 0x7f09003c;
public static final int time_remaining_notification = 0x7f09003d;
}
public static final class style {
private style() {}
public static final int ButtonBackground = 0x7f0a0000;
public static final int NotificationText = 0x7f0a0001;
public static final int NotificationTextShadow = 0x7f0a0002;
public static final int NotificationTitle = 0x7f0a0003;
public static final int TextAppearance_Compat_Notification = 0x7f0a0004;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0a0005;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0a0006;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0a0007;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0a0008;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0a000a;
public static final int Widget_Compat_NotificationActionText = 0x7f0a000b;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f010003 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] FontFamily = { 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d, 0x7f01000e };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f010008, 0x7f01000f, 0x7f010010, 0x7f010011, 0x7f01001d };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
| 58.67451
| 185
| 0.739808
|
dd69ed4cab0cc924b330c8b08198482a24ba0e59
| 3,565
|
package net.gnu.pdfplugin;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import net.gnu.aidl.IOperation;
import android.os.*;
import java.io.*;
public class ITextService extends Service {
static final String LOG_TAG = "ITextService";
public void onStart(final Intent intent, final int startId) {
super.onStart( intent, startId );
}
public void onDestroy() {
super.onDestroy();
}
public IBinder onBind(final Intent intent) {
return addBinder;
}
private final IOperation.Stub addBinder = new IOperation.Stub() {
// @Override
// public String readGenExcelDict(boolean manySheet) throws RemoteException {
// try {
// if (dl == null) {
// dl = new DictionaryLoader();
// }
// Dictionary dic = dl.readGenExcelDict(manySheet);
// OutputStream fos = new BufferedOutputStream(new FileOutputStream(Constants.ORI_EXCEL_FILE + ".gen.ser"));
// ObjectOutputStream oos = new ObjectOutputStream(fos);
// oos.writeObject(dic);
// DocFileUtils.flushClose(oos);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// return Constants.ORI_EXCEL_FILE + ".gen.ser";
// }
//
// @Override
// public String readOriExcelDict() throws RemoteException {
// try {
// if (dl == null) {
// dl = new DictionaryLoader();
// }
// Dictionary dic = dl.readOriExcelDict();
// OutputStream fos = new BufferedOutputStream(new FileOutputStream(Constants.ORI_EXCEL_FILE + ".gen.ser"));
// ObjectOutputStream oos = new ObjectOutputStream(fos);
// oos.writeObject(dic);
// DocFileUtils.flushClose(oos);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// return Constants.ORI_EXCEL_FILE + ".gen.ser";
// }
//
// @Override
// public void writeNewWordsSheet(String dicFileNameSer, String outputFile, String sheetName) throws RemoteException {
// try {
// DictionaryLoader.writeNewWordsSheet(dicFileNameSer, outputFile, sheetName);
// } catch (Exception e) {
// throw new RemoteException(e.getMessage());
// }
// }
//
@Override
public void pdfToText(final String fPath, final String fOutPath) throws RemoteException {
try {
ITextUtil.pdfToText(fPath, fOutPath);
} catch (IOException e) {
throw new RemoteException(e.getMessage());
}
}
// @Override
// public String readWordFileToText(String fPath) throws RemoteException {
// try {
// return DocFileUtils.readWordFileToText(fPath);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// }
//
// @Override
// public String getPublisherText(String fPath) throws RemoteException {
// try {
// return DocFileUtils.getPublisherText(fPath);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// }
//
// @Override
// public String getVisioText(String fPath) throws RemoteException {
// try {
// return DocFileUtils.getVisioText(fPath);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// }
//
// @Override
// public String getPowerPointText(String fPath) throws RemoteException {
// try {
// return DocFileUtils.getPowerPointText(fPath);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// }
//
// @Override
// public String getExcelText(String fPath) throws RemoteException {
// try {
// return DocFileUtils.getExcelText(fPath);
// } catch (IOException e) {
// throw new RemoteException(e.getMessage());
// }
// }
};
}
| 28.070866
| 119
| 0.673773
|
9e1b9db1f7ffcc902fa18eaa53e94b1b376282cd
| 3,703
|
package io.sphere.sdk.products.commands.updateactions;
import io.sphere.sdk.models.LocalizedString;
import io.sphere.sdk.products.Product;
import javax.annotation.Nullable;
/**
* Changes the description of an asset.
*
* {@doc.gen intro}
*
* <p>By variant ID (every variant has a variantId):</p>
* {@include.example io.sphere.sdk.products.commands.ProductUpdateCommandIntegrationTest#setAssetDescriptionByVariantId()}
*
* <p>By SKU (attention, SKU is optional field in a variant):</p>
* {@include.example io.sphere.sdk.products.commands.ProductUpdateCommandIntegrationTest#setAssetDescriptionBySku()}
*/
public final class SetAssetDescription extends StagedProductUpdateActionImpl<Product> {
@Nullable
private final Integer variantId;
@Nullable
private final String sku;
private final String assetId;
private final String assetKey;
@Nullable
private final LocalizedString description;
private SetAssetDescription(final String assetId,final String assetKey, @Nullable final Integer variantId, @Nullable final String sku, @Nullable final LocalizedString description, @Nullable final Boolean staged) {
super("setAssetDescription", staged);
this.assetId = assetId;
this.variantId = variantId;
this.sku = sku;
this.description = description;
this.assetKey = assetKey;
}
public String getAssetId() {
return assetId;
}
public String getAssetKey() {
return assetKey;
}
@Nullable
public Integer getVariantId() {
return variantId;
}
@Nullable
public String getSku() {
return sku;
}
@Nullable
public LocalizedString getDescription() {
return description;
}
public static SetAssetDescription ofVariantId(final Integer variantId, final String assetId, @Nullable final LocalizedString description) {
return ofVariantId(variantId, assetId, description, null);
}
public static SetAssetDescription ofVariantId(final Integer variantId, final String assetId, @Nullable final LocalizedString description, @Nullable final Boolean staged) {
return new SetAssetDescription(assetId,null, variantId, null, description, staged);
}
public static SetAssetDescription ofSku(final String sku, final String assetId, @Nullable final LocalizedString description) {
return ofSku(sku, assetId, description, null);
}
public static SetAssetDescription ofSku(final String sku, final String assetId, @Nullable final LocalizedString description, @Nullable final Boolean staged) {
return new SetAssetDescription(assetId,null, null, sku, description, staged);
}
public static SetAssetDescription ofVariantIdAndAssetKey(final Integer variantId, final String assetId, @Nullable final LocalizedString description) {
return ofVariantIdAndAssetKey(variantId, assetId, description, null);
}
public static SetAssetDescription ofVariantIdAndAssetKey(final Integer variantId, final String assetKey, @Nullable final LocalizedString description, @Nullable final Boolean staged) {
return new SetAssetDescription(null,assetKey , variantId, null, description, staged);
}
public static SetAssetDescription ofSkuAndAssetKey(final String sku, final String assetId, @Nullable final LocalizedString description) {
return ofSkuAndAssetKey(sku, assetId, description, null);
}
public static SetAssetDescription ofSkuAndAssetKey(final String sku, final String assetKey, @Nullable final LocalizedString description, @Nullable final Boolean staged) {
return new SetAssetDescription(null,assetKey , null, sku, description, staged);
}
}
| 39.393617
| 217
| 0.742371
|
fa0085df0e3a20b711674c666281dad6ef143bfe
| 784
|
package com.github.lyd.base.client.api;
import com.github.lyd.base.client.entity.SystemAccessLogs;
import com.github.lyd.common.model.PageList;
import com.github.lyd.common.model.ResultBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
public interface SystemAccessLogsRemoteService {
/**
* 获取访问日志分页列表
*
* @return
*/
@PostMapping("/access/logs")
ResultBody<PageList<SystemAccessLogs>> accessLogs(
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
@RequestParam(name = "keyword", required = false) String keyword
);
}
| 35.636364
| 96
| 0.709184
|
bd67202f3ea26c9778c78a92489bebf5f10af156
| 1,453
|
package products.terminal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import products.controllers.CategoryController;
import products.controllers.ProductController;
import products.controllers.UserController;
@Component
public class Terminal implements CommandLineRunner {
private final UserController userController;
private final CategoryController categoryController;
private final ProductController productController;
@Autowired
public Terminal(UserController userController, CategoryController categoryController, ProductController productController) {
this.userController = userController;
this.categoryController = categoryController;
this.productController = productController;
}
@Override
public void run(String... strings) throws Exception {
// JSON Import
this.userController.importUsersFromJson();
this.categoryController.importCategoriesFromJson();
this.productController.importProductsFromJson();
// Query and Export Data - JSON Processing
this.productController.exportProductsInRangeToJson();
this.userController.exportUsersWithSoldProductsToJson();
this.categoryController.exportCategoriesByProductsCountToJson();
this.userController.exportUsersAndProductsToJson();
}
}
| 37.25641
| 128
| 0.77839
|
1f5ee7a7b200dab649dbb6ce949b97c712b3fc71
| 332
|
package designpatterns.responsibility;
/**
* @author happy
* @since 2021-05-12
*/
public abstract class Handler {
private Handler next;
public void setNext(Handler next) {
this.next = next;
}
public Handler getNext() {
return next;
}
public abstract void getRequest(String request);
}
| 16.6
| 52
| 0.644578
|
c3e403dca8cf265189f5b96d4cc10fc32defb089
| 427
|
package loop;
/**
* // 单if语句
* @author Vincent
*/
public class Demo02If {
public static void main(String[] args) {
System.out.println("今天天气不错,正在压马路……突然发现一个快乐的地方:网吧");
int age = 19;
if (age >= 18) {
System.out.println("进入网吧,开始high!");
System.out.println("遇到了一群猪队友,开始骂街。");
System.out.println("感觉不爽,结账走人。");
}
System.out.println("回家吃饭");
}
}
| 23.722222
| 59
| 0.540984
|
b8bb45733d969f129c4d7909d5dbe37342aa7fc3
| 1,266
|
package softuni;
import java.util.Scanner;
public class GreaterOfTwoValues {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String varType = scan.nextLine();
switch (varType) {
case "String": {
String value1 = scan.nextLine();
String value2 = scan.nextLine();
String greater = getMax(value1, value2);
System.out.println(greater);
break;
}
case "int": {
int value1 = scan.nextInt();
int value2 = scan.nextInt();
int greater = getMax(value1, value2);
System.out.println(greater);
break;
}
case "char": {
char value1 = scan.next().charAt(0);
char value2 = scan.next().charAt(0);
char greater = getMax(value1, value2);
System.out.println(greater);
break;
}
default: return;
}
}
private static String getMax(String value1, String value2) {
if (value1.compareTo(value2) > 0) {
return value2;
}
else if (value1.compareTo(value2) < 0) {
return value1;
} else {
return null;
}
}
private static int getMax(int value1, int value2) {
if (value1 > value2) {
return value1;
}
return value2;
}
private static char getMax(char value1, char value2) {
if (value1 > value2) {
return value1;
}
return value2;
}
}
| 20.419355
| 60
| 0.658768
|
ac5ccace0d27ea4ff55b839a01f41111932249d7
| 3,958
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator
package com.microsoft.azure.keyvault.models;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The storage account update parameters.
*/
public class StorageAccountUpdateParameters {
/**
* The current active storage account key name.
*/
@JsonProperty(value = "activeKeyName")
private String activeKeyName;
/**
* whether keyvault should manage the storage account for the user.
*/
@JsonProperty(value = "autoRegenerateKey")
private Boolean autoRegenerateKey;
/**
* The key regeneration time duration specified in ISO-8601 format.
*/
@JsonProperty(value = "regenerationPeriod")
private String regenerationPeriod;
/**
* The attributes of the storage account.
*/
@JsonProperty(value = "attributes")
private StorageAccountAttributes storageAccountAttributes;
/**
* Application specific metadata in the form of key-value pairs.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/**
* Get the activeKeyName value.
*
* @return the activeKeyName value
*/
public String activeKeyName() {
return this.activeKeyName;
}
/**
* Set the activeKeyName value.
*
* @param activeKeyName the activeKeyName value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withActiveKeyName(String activeKeyName) {
this.activeKeyName = activeKeyName;
return this;
}
/**
* Get the autoRegenerateKey value.
*
* @return the autoRegenerateKey value
*/
public Boolean autoRegenerateKey() {
return this.autoRegenerateKey;
}
/**
* Set the autoRegenerateKey value.
*
* @param autoRegenerateKey the autoRegenerateKey value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withAutoRegenerateKey(Boolean autoRegenerateKey) {
this.autoRegenerateKey = autoRegenerateKey;
return this;
}
/**
* Get the regenerationPeriod value.
*
* @return the regenerationPeriod value
*/
public String regenerationPeriod() {
return this.regenerationPeriod;
}
/**
* Set the regenerationPeriod value.
*
* @param regenerationPeriod the regenerationPeriod value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withRegenerationPeriod(String regenerationPeriod) {
this.regenerationPeriod = regenerationPeriod;
return this;
}
/**
* Get the storageAccountAttributes value.
*
* @return the storageAccountAttributes value
*/
public StorageAccountAttributes storageAccountAttributes() {
return this.storageAccountAttributes;
}
/**
* Set the storageAccountAttributes value.
*
* @param storageAccountAttributes the storageAccountAttributes value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withStorageAccountAttributes(StorageAccountAttributes storageAccountAttributes) {
this.storageAccountAttributes = storageAccountAttributes;
return this;
}
/**
* Get the tags value.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set the tags value.
*
* @param tags the tags value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
}
| 27.296552
| 123
| 0.673573
|
237c0d1ac46fc50ad65c2eb7e6b1ad8e5ca9589d
| 305
|
package Trie;
public class TrieValue implements Comparable<TrieValue>{
public String str;
public TrieValue(String str)
{
this.str = str;
}
@Override
public int compareTo(TrieValue o) {
// TODO Auto-generated method stub
int a = this.str.compareTo(o.str);
if(a==0)
a++;
return a;
}
}
| 16.944444
| 57
| 0.681967
|
fac6296868bdad11d39fb174a9321d223048c2b4
| 16,727
|
package fr.uga.iut2.genconf.vue.gui;
import fr.uga.iut2.genconf.controleur.Controleur;
import fr.uga.iut2.genconf.modele.Communication;
import fr.uga.iut2.genconf.modele.Conference;
import fr.uga.iut2.genconf.modele.Session;
import fr.uga.iut2.genconf.vue.gui.shared.Layout;
import fr.uga.iut2.genconf.vue.shared.dto.NouveauSpeaker;
import org.apache.commons.validator.routines.EmailValidator;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Optional;
public class VueCreationChairman extends Layout<Session> {
public VueCreationChairman(Controleur controleur, GUI gui) {
super(gui, controleur);
}
public void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
inputEmail = new javax.swing.JTextField();
inputPrenomSpeaker = new javax.swing.JTextField();
inputNomSpeaker = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
validerButton = new javax.swing.JButton();
validerButton.setEnabled(false);
inputEmail.setForeground(Color.red);
jLabel1.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel1.setForeground(new Color(0, 0, 0));
jLabel3.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel3.setForeground(new Color(0, 0, 0));
jLabel4.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel4.setForeground(new Color(0, 0, 0));
jLabel10.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel10.setForeground(new Color(0, 0, 0));
jLabel11.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel11.setForeground(new Color(0, 0, 0));
setBackground(new Color(204, 204, 204));
jLabel2.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel2.setForeground(new Color(0, 0, 0));
jLabel2.setText("Conférences >");
jLabel2.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
controleur.consulterConferences();
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
});
jLabel5.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel5.setForeground(new Color(0, 0, 0));
try{
jLabel5.setText("> " + model.getConference().getNom());
}catch (Exception ignored){
}
jLabel5.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
controleur.consulterConference(model.getConference().getNom());
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
});
jLabel6.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel6.setForeground(new Color(0, 0, 0));
try{
jLabel6.setText("> " + model.getNom());
}catch (Exception ignored){
}
jLabel6.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
controleur.consulterSession(model.getConference().getNom(), model.getNom());
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
});
jLabel12.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel12.setForeground(new Color(0, 0, 0));
jLabel12.setText("> Ajouter Chairman");
jLabel13.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel13.setForeground(new Color(0, 0, 0));
jLabel7.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel7.setForeground(new Color(0, 0, 0));
jLabel7.setText("Nom :");
jLabel8.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel8.setForeground(new Color(0, 0, 0));
jLabel8.setText("Prénom :");
jLabel9.setFont(new Font("Calibri", 1, 14)); // NOI18N
jLabel9.setForeground(new Color(0, 0, 0));
jLabel9.setText("Email :");
inputEmail.setBackground(new Color(255, 255, 255));
inputEmail.setFont(new Font("Calibri", 1, 14)); // NOI18N
inputEmail.setForeground(new Color(0, 0, 0));
inputEmail.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
validerSaisie(evt);
}
});
inputPrenomSpeaker.setBackground(new Color(255, 255, 255));
inputPrenomSpeaker.setFont(new Font("Calibri", 1, 14)); // NOI18N
inputPrenomSpeaker.setForeground(new Color(0, 0, 0));
inputPrenomSpeaker.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
validerSaisie(evt);
}
});
inputNomSpeaker.setBackground(new Color(255, 255, 255));
inputNomSpeaker.setFont(new Font("Calibri", 1, 14)); // NOI18N
inputNomSpeaker.setForeground(new Color(0, 0, 0));
inputNomSpeaker.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
validerSaisie(evt);
}
});
jButton1.setBackground(new Color(153, 153, 153));
jButton1.setFont(new Font("Calibri", 1, 14)); // NOI18N
jButton1.setForeground(new Color(0, 0, 0));
jButton1.setText("ANNULER");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
annulerActionPerformed(evt);
}
});
validerButton.setBackground(new Color(153, 153, 153));
validerButton.setFont(new Font("Calibri", 1, 14)); // NOI18N
validerButton.setForeground(new Color(0, 0, 0));
validerButton.setText("VALIDER");
validerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
creerActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel13)
.addContainerGap(149, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addComponent(validerButton, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(79, 79, 79))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(79, 79, 79)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inputEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(inputPrenomSpeaker, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(inputNomSpeaker, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(79, 79, 79)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel12)
.addComponent(jLabel13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 356, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(validerButton)
.addComponent(jButton1))
.addGap(113, 113, 113))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(101, 101, 101)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(inputNomSpeaker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(inputPrenomSpeaker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(inputEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addContainerGap(274, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
private void creerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_creerActionPerformed
controleur.ajouterChairManSession(model.getConference().getNom(), model.getNom(),inputEmail.getText().toLowerCase().trim());
}
private void annulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annulerActionPerformed
controleur.consulterSession(model.getConference().getNom(), model.getNom());
}//GEN-LAST:event_annulerActionPerformed
private void validerSaisie(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_validerSaisie
boolean valide;
boolean validEmail;
String nom, prenom;
EmailValidator validator = EmailValidator.getInstance(false, false);
nom = this.inputNomSpeaker.getText().trim();
prenom = this.inputPrenomSpeaker.getText().trim();
validEmail = validator.isValid(this.inputEmail.getText().trim().toLowerCase());
this.inputEmail.setForeground(validEmail ? Color.black : Color.red);
valide = validEmail
&& (nom != null) && (nom.length() > 0)
&& (prenom != null) && (prenom.length() > 0);
this.validerButton.setEnabled(valide);
}
private javax.swing.JTextField inputEmail;
private javax.swing.JTextField inputNomSpeaker;
private javax.swing.JTextField inputPrenomSpeaker;
private javax.swing.JButton jButton1;
private javax.swing.JButton validerButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
}
| 46.985955
| 200
| 0.58014
|
8c2f5e59581e1688297dd396cabd658a7b1a6487
| 1,250
|
package com.cdcAPI.api.model.Response;
import com.cdcAPI.model.Cliente;
import com.cdcAPI.model.Compra;
import com.cdcAPI.model.Livro;
import java.math.BigDecimal;
import java.util.List;
public class CompraResponse {
private ClienteResponse cliente;
private List<Livro> livros;
private BigDecimal total;
private BigDecimal totalDesconto;
public CompraResponse(Compra compra) {
cliente = new ClienteResponse(compra.getCliente());
livros = compra.getLivros();
total = compra.getTotal();
totalDesconto = compra.getTotalDesconto();
}
public ClienteResponse getCliente() {
return cliente;
}
public void setCliente(ClienteResponse cliente) {
this.cliente = cliente;
}
public List<Livro> getLivros() {
return livros;
}
public void setLivros(List<Livro> livros) {
this.livros = livros;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public BigDecimal getTotalDesconto() {
return totalDesconto;
}
public void setTotalDesconto(BigDecimal totalDesconto) {
this.totalDesconto = totalDesconto;
}
}
| 21.186441
| 60
| 0.664
|
fae1673626f85c42845cfc818b74cf8ae62c0862
| 253
|
package com.weebkun.speedqueue.db;
public class Selections {
public String[] selections;
public double price;
public Selections(String[] selections, double price) {
this.selections = selections;
this.price = price;
}
}
| 21.083333
| 58
| 0.671937
|
7b52dbcc2097605e5954a36dc197200c08a5917d
| 1,590
|
/*
* Copyright (c) 2003 World Wide Web Consortium,
* (Massachusetts Institute of Technology, Institut National de
* Recherche en Informatique et en Automatique, Keio University). All
* Rights Reserved. This program is distributed under the W3C's Software
* Intellectual Property License. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE.
* See W3C License http://www.w3.org/Consortium/Legal/ for more details.
*/
package org.w3c.dom.html2;
/**
* Document base URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>]. See the BASE element definition in HTML 4.01.
* <p>See also the <a href='http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109'>Document Object Model (DOM) Level 2 HTML Specification</a>.
*/
public interface HTMLBaseElement extends HTMLElement {
/**
* The base URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>]. See the href attribute definition in HTML 4.01.
*/
public String getHref();
/**
* The base URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>]. See the href attribute definition in HTML 4.01.
*/
public void setHref(String href);
/**
* The default target frame. See the target attribute definition in HTML
* 4.01.
*/
public String getTarget();
/**
* The default target frame. See the target attribute definition in HTML
* 4.01.
*/
public void setTarget(String target);
}
| 38.780488
| 144
| 0.693082
|
4073903c16207245e55a6b695d2e70b3e2b2b851
| 1,282
|
/*
* Copyright 2018 Martin Winandy
*
* 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.pmw.tinylog;
/**
* Severity levels for log entries.
*/
public enum Level {
/**
* Trace log entries contain very fine-grained debug information, typically the flow through.
*/
TRACE,
/**
* Debug log entries contain common debug information.
*/
DEBUG,
/**
* Info log entries contain important relevant information.
*/
INFO,
/**
* Warn log entries contain technical warnings. Typically warnings do not prevent the application from continuing.
*/
WARNING,
/**
* Error log entries contain severe technical errors. Typically errors prevent a function from continuing normally.
*/
ERROR,
/**
* Off severity level disables any logging.
*/
OFF;
}
| 24.653846
| 118
| 0.723089
|
a0c495963b528c6527c79f94679f2b640c280377
| 188
|
package ua.com.foxminded.division.output;
import ua.com.foxminded.division.maths.Step;
import java.util.List;
public interface Output {
void outputResult(List<Step> listOfSteps);
}
| 18.8
| 46
| 0.776596
|
bc18f869060d32f418fe6b2216d6591f4236c688
| 1,842
|
package com.semester;
import java.util.*;
/*
* Define a class in Java called Commission, which has an
* instance variable, salesAmount; an appropriate constructor; and
* a parameterized method, commission(float rate) that returns the commission.
* Now write a test class to test the Commission class by reading a sales values for three salespersons in an array of objects. Finally, get and show the commission for three salespersons. If the sales are negative, your program should print the message “Invalid Amount”.
*/
class Commission{
private float salesAmount, rate;
public Commission(){}
public Commission(float s, float r){
this.salesAmount = s;
this.rate = r;
}
public float getSalesAmount() {
return this.salesAmount;
}
public float getRates() {
return this.rate;
}
public void setSalesAmount(float s) {
if(s > 0) {
this.salesAmount = s;
} else {
System.out.println("Invalid");
}
}
public void setRates(float r) {
if(r > 0) {
this.rate = r;
} else {
System.out.println("Invalid");
}
}
public double Res() {
double res = (salesAmount/100)*rate;
return res;
}
}
public class Lab6_Question9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("\033[H\033[2J");
Commission c = new Commission();
System.out.print("Enter your Sales Amount: ");
c.setSalesAmount(input.nextFloat());
System.out.print("Enter your Rate: ");
c.setRates(input.nextFloat());
System.out.println("Your Commission Amount: " + c.Res());
input.close();
}
}
| 27.492537
| 272
| 0.590119
|
13828ca39a80ffcc34c2f34afe48112df1e7a726
| 883
|
package com.alibaba.tesla.appmanager.server.repository.domain;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserProfileDO {
private Long id;
private Date gmtCreate;
private Date gmtModified;
private String userId;
private String profile;
private String namespaceId;
private String stageId;
public JSONObject getJsonByProfile() {
if (StringUtils.isEmpty(profile)) {
return new JSONObject();
}
try {
return JSON.parseObject(profile);
} catch (Exception e) {
return new JSONObject();
}
}
}
| 20.534884
| 62
| 0.698754
|
64b5729f2aa64b077609767a11b0b74593965d2a
| 3,406
|
/*******************************************************************************
* (c) Copyright 2017 Hewlett Packard Enterprise Development LP 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.hp.hpl.loom.adapter.tm.backend.monitoring;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* Represents an log entry generated by the system.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"timestamp", "source", "message", "hostname", "level", "coordinate"})
public class Log {
@JsonProperty
private long timestamp;
@JsonProperty
private String source;
@JsonProperty
private String message;
@JsonProperty
private String hostname;
@JsonProperty
private String level;
@JsonProperty
private String coordinate;
public Log() {
// Jackson deserialization
}
/**
*
* @param timestamp The timestamp for the log as Unix epoch time.
* @param source The source of the log.
* @param message The message of the log.
* @param hostname The hostname generating the log.
* @param level The log level
* @param coordinate The coordinate of the element that generated the log
*/
public Log(final long timestamp, final String source, final String message, final String hostname,
final String level, final String coordinate) {
this.timestamp = timestamp;
this.source = source;
this.message = message;
this.hostname = hostname;
this.level = level;
this.coordinate = coordinate;
}
@Override
public String toString() {
String str = "Timestamp : " + timestamp + "\nSource : " + source + "\nMessage : " + message
+ "\nHostname : " + hostname + "\nLevel : " + level + "\nCoordinate: " + coordinate;
return str;
}
/**
* @return The timestamp for the log as Unix epoch time, the number of seconds since 1970-01-01
* 00:00:00 UTC.
*/
public long getTimestamp() {
return timestamp;
}
/**
* @return The source of the log (i.e System)
*/
public String getSource() {
return source;
}
/**
* @return The message of the log.
*/
public String getMessage() {
return message;
}
/**
* @return The hostname generating the log.
*/
public String getHostname() {
return hostname;
}
/**
* @return The level of the log (i.e INFO)
*/
public String getLevel() {
return level;
}
/**
* @return The location of the object generating the log.
*/
public String getCoordinate() {
return coordinate;
}
}
| 29.877193
| 105
| 0.613917
|
c2eb023e1a0987a5aa35cc608b14161ac7deb15f
| 1,961
|
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.node;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
/**
* A node represent a node within a cluster (<tt>cluster.name</tt>). The {@link #client()} can be used
* in order to use a {@link Client} to perform actions/operations against the cluster.
*
* <p>In order to create a node, the {@link NodeBuilder} can be used. When done with it, make sure to
* call {@link #close()} on it.
*
* @author kimchy (shay.banon)
*/
public interface Node {
/**
* The settings that were used to create the node.
*/
Settings settings();
/**
* A client that can be used to execute actions (operations) against the cluster.
*/
Client client();
/**
* Start the node. If the node is already started, this method is no-op.
*/
Node start();
/**
* Stops the node. If the node is already stopped, this method is no-op.
*/
Node stop();
/**
* Closes the node (and {@link #stop}s if its running).
*/
void close();
/**
* Returns <tt>true</tt> if the node is closed.
*/
boolean isClosed();
}
| 29.712121
| 102
| 0.675166
|
0ef0130ba1e9e7caa93f1cbc07253daa1c77d219
| 4,652
|
/*
* Copyright (c) 2016 Matrix Studios.
* All code is licensed under the WTFPL.
* A copy of this license is available with this software or at http://wtfpl.net/
*
*/
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.ArrayList;
/**
* The job class.
* Managing status, runtime, and synchronization
*
* @author matrix
* @since 0.1
*/
public class Job extends BaseObject implements Runnable {
/** The duration of the job */
private double duration;
/** Skills required */
private ArrayList<String> skills;
/** The current progress of the job */
private double progress = 0;
/** Whether the job should be running */
private boolean runFlag = true;
/** Whether the job should end */
private boolean endFlag = false;
/** Whether the job is finished */
private boolean finishFlag = false;
/**
* Default Constructor
*/
public Job() { super(); }
/**
* Default Constructor - name only
* @param n Job name
*/
public Job(String n) { super(n); }
/**
* Default Constructor - all parameters
* @param n Job name
* @param p Job parent
* @param d Job duration
* @param s Job skills required
*/
public Job(String n, Integer p, double d, ArrayList<String> s) {
super(n, p);
duration = d;
skills = s;
}
/**
* Return a JTree node with details about this job
* @param i The index of this
* @return JTree default node
*/
@Override
public DefaultMutableTreeNode getTree(Integer i) {
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(String.format("%d: %s", i, name));
rootNode.add(new DefaultMutableTreeNode(String.format("Time: %.2f seconds", duration)));
rootNode.add(new DefaultMutableTreeNode(String.format("Skills: %s", String.join(", ", skills))));
return rootNode;
}
/**
* Descriptive string about this job
* @return The string to be printed
*/
@Override
public String toString() {
String rtr = "";
rtr += String.format("%s\n", name);
rtr += String.format("Duration: %.2f\n", duration);
rtr += String.format("Skills: %s\n", String.join(", ", skills));
return rtr;
}
/**
* Begin running the job, including reporting progress
*/
@Override
public void run() {
double time = 0;
while(duration > time) {
try {
Thread.sleep(500);
if(!runFlag) { continue; }
if(endFlag) { finished(); return; }
time += 0.5;
progress = ((time/duration) * 100);
updateStatus();
} catch (InterruptedException e) {
return;
}
}
finished();
}
/**
* Get the duration of the job
* @return Duration in seconds
*/
public double getDuration() { return duration; }
/**
* Get skills required as a single string
* @return String of skills required
*/
public String getSkills() {
if(skills.isEmpty()) return "None";
return String.join(", ", skills);
}
/**
* Get the skills required in an array
* @return Skills list
*/
public ArrayList<String> getSkillsArray() {
return skills;
}
/**
* Get current progress of the job
* @return Current progress
*/
public double getProgress() {
return progress;
}
/**
* Get whether the job has completed
* @return Finished flag
*/
public boolean isEndFlag() {
return finishFlag;
}
/** Toggle the run state */
public void toggleFlag() {
runFlag = !runFlag;
}
/** Kill job */
public void stop() { endFlag = true; }
/**
* Report the end of a job and set its status
* to completed internally
*/
private void finished() {
finishFlag = true;
baseWorld.jobDidComplete(this);
Ship s = (Ship) baseWorld.findObject(parent);
s.jobDidFinish();
}
/**
* Report the current status to the base world
*/
private void updateStatus() {
baseWorld.updateJob(this);
}
/**
* Find a portion of this job
* @param searchTerm The term to be searched
* @return This if matches
*/
@Override
public BaseObject matchesAnyComponent(String searchTerm) {
BaseObject b = super.matchesAnyComponent(searchTerm);
if(b != null) return b;
if(skills.contains(searchTerm)) return this;
return null;
}
}
| 25.145946
| 105
| 0.572872
|
2b98cec5f7cba0b064cfa95c41678b215b3862db
| 617
|
package it.polimi.ingsw.network.messages.game.server2client;
import it.polimi.ingsw.model.util.Colors;
import it.polimi.ingsw.model.util.TokenType;
import it.polimi.ingsw.network.messages.Message;
import it.polimi.ingsw.network.messages.MessageType;
public class TokenShow extends Message {
private final TokenType tokenType;
private final Colors color;
public TokenShow(TokenType tokenType,Colors color){
super("Lobby", MessageType.TOKEN_SHOW);
this.tokenType = tokenType;
this.color=color;
}
public TokenType getTokenType() {
return tokenType;
}
public Colors getColor() {
return color;
}
}
| 22.851852
| 60
| 0.777958
|
523a88e377ea960c63a5cd07dd8317ef73723988
| 11,877
|
package info.nightscout.android.medtronic;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.mikepenz.iconics.IconicsDrawable;
import info.nightscout.android.R;
import info.nightscout.android.model.store.UserLog;
import info.nightscout.android.utils.FormatKit;
import io.realm.RealmBasedRecyclerViewAdapter;
import io.realm.RealmResults;
import io.realm.RealmViewHolder;
public class UserLogAdapter
extends RealmBasedRecyclerViewAdapter<UserLog, UserLogAdapter.ViewHolder> {
private static final String TAG = UserLogAdapter.class.getSimpleName();
private final static int FADE_DURATION_MS = 400;
// HSV Hue 0-360 Saturation 0-1 Value 0-1
private final static float[] WARN_HSV = new float[] {60f, .85f, 1f};
private final static float[] CGM_HSV =new float[] {0f, .22f, 1f};
private final static float[] HISTORY_HSV = new float[] {270f, .22f, 1f};
private final static float[] HEART_HSV = new float[] {0f, 1f, 1f};
private final static float[] SHARE_HSV = new float[] {125f, .22f, 1f};
private final static float[] PUSHOVER_HSV = new float[] {40f, .22f, 1f};
private final static float[] NOTE_HSV = new float[] {0f, 0f, .9f};
private final static float[] ESTIMATE_HSV = new float[] {185f, .22f, 1f};
private final static float[] ISIG_HSV = new float[] {185f, .22f, 1f};
private final static float HIGHLIGHT = 1.35f;
private final static float LOWLIGHT = 0.65f;
private int cNormal;
private int cHigh;
private int cLow;
private int cEestimate;
private int cIsig;
private int cHistory;
private int cPushover;
private boolean largeText;
private IconicsDrawable iWARN;
private IconicsDrawable iINFO;
private IconicsDrawable iNOTE;
private IconicsDrawable iHELP;
private IconicsDrawable iREFRESH;
private IconicsDrawable iCGM;
private IconicsDrawable iSETTING;
private IconicsDrawable iHEART;
private IconicsDrawable iSHARE;
private int iBounds;
private int iOffsetXDp;
private int iOffsetYDp;
private boolean init = false;
private int lastAnimPosition = -1;
private Context mContext;
public UserLogAdapter(
Context context,
RealmResults<UserLog> realmResults,
boolean automaticUpdate) {
super(context, realmResults, automaticUpdate, false);
mContext = context;
}
@Override
public ViewHolder onCreateRealmViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View v = inflater.inflate(R.layout.log_item, viewGroup, false);
ViewHolder vh = new ViewHolder((FrameLayout) v);
return vh;
}
@Override
public void onBindRealmViewHolder(@NonNull ViewHolder viewHolder, int position) {
final UserLog userLog = realmResults.get(position);
setContent(viewHolder.textView, userLog);
if (position > lastAnimPosition) {
setFadeAnimation(viewHolder.itemView);
lastAnimPosition = position;
}
}
public class ViewHolder extends RealmViewHolder {
public TextView textView;
public ViewHolder(FrameLayout container) {
super(container);
this.textView = container.findViewById(R.id.log_textview);
}
}
public int getLastAnimPosition() {
return lastAnimPosition;
}
public void setLastAnimPosition(int lastAnimPosition) {
this.lastAnimPosition = lastAnimPosition;
}
private void setFadeAnimation(View view) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(FADE_DURATION_MS);
view.startAnimation(anim);
}
private void setContent(TextView tv, UserLog ul) {
if (!init) initDrawables(tv);
SpannableStringBuilder ssb = new SpannableStringBuilder();
UserLogMessage.TYPE type = UserLogMessage.TYPE.convert(ul.getType());
String clock = FormatKit.getInstance().formatAsDayClockSeconds(ul.getTimestamp());
String text = ul.getMessageParsed();
if (largeText) clock += "\n";
switch (type) {
case WARN:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iWARN, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iWARN.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case HELP:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iHELP, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iHELP.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case INFO:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iINFO, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iINFO.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case NOTE:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iNOTE, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iNOTE.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case HISTORY:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iREFRESH, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iREFRESH.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case CGM:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iCGM, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iCGM.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case OPTION:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iSETTING, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iSETTING.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case STARTUP:
case SHUTDOWN:
case HEART:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iHEART, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(cHigh), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case SGV:
ssb.append(" ").append(text);
ssb.setSpan(new ForegroundColorSpan(cHigh), 1, text.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case ESTIMATE:
ssb.append(" ").append(text);
ssb.setSpan(new ForegroundColorSpan(cEestimate), 1, text.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case ISIG:
ssb.append(" ").append(text);
ssb.setSpan(new ForegroundColorSpan(cIsig), 1, text.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case REQUESTED:
case RECEIVED:
ssb.append(" ").append(text);
ssb.setSpan(new ForegroundColorSpan(cHistory), 1, text.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case SHARE:
ssb.append(" * ").append(text);
ssb.setSpan(new ImageSpan(iSHARE, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(iSHARE.getColor()), 3, text.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case PUSHOVER:
ssb.append(" ").append(text);
ssb.setSpan(new ForegroundColorSpan(cPushover), 1, text.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
default:
ssb.append(" ").append(text);
ssb.setSpan(new ForegroundColorSpan(cNormal), 1, text.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
ssb.insert(0, clock);
ssb.setSpan(new ForegroundColorSpan(cLow), 0, clock.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(new RelativeSizeSpan(0.78f), 0, clock.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(ssb);
}
private void initDrawables(TextView tv) {
largeText = mContext.getResources().getConfiguration().fontScale > 1;
int c = tv.getCurrentTextColor();
float s = tv.getTextSize();
float[] hsv = new float[3];
Color.colorToHSV(c, hsv);
int normal = c >> 24 & 0xFF;
if (normal == 0xFF) normal = Color.HSVToColor(new float[] {0.f, 0.f, hsv[2]}) & 0xFF;
int high = (int) (HIGHLIGHT *normal);
int low = (int) (LOWLIGHT * normal);
if (high > 0xFF) high = 0xFF;
if (low > 0xFF) low = 0xFF;
cNormal = Color.HSVToColor(normal, new float[] {hsv[0], hsv[1], 1.f});
cHigh = Color.HSVToColor(high, new float[] {hsv[0], hsv[1], 1.f});
cLow = Color.HSVToColor(low, new float[] {hsv[0], hsv[1], 1.f});
Log.d(TAG, String.format("textColor: %08x textSize: %s normal: %08x high: %08x low: %08x", c, s, cNormal, cHigh, cLow));
cEestimate = Color.HSVToColor(high, ESTIMATE_HSV);
cIsig = Color.HSVToColor(normal, ISIG_HSV);
cHistory = Color.HSVToColor(normal, HISTORY_HSV);
cPushover = Color.HSVToColor(normal, PUSHOVER_HSV);
iBounds = (int) (s * 1.2);
iOffsetXDp = 0;
iOffsetYDp = 3;
iWARN = icon("ion_alert_circled", Color.HSVToColor(high, WARN_HSV));
iINFO = icon("ion_information_circled", cHigh);
iNOTE = icon("ion_document", Color.HSVToColor(high, NOTE_HSV));
iHELP = icon("ion_ios_lightbulb", cHigh);
iCGM = icon("ion_ios_pulse_strong", Color.HSVToColor(high, CGM_HSV));
iHEART = icon("ion_heart", Color.HSVToColor(high, HEART_HSV));
iSHARE = icon("ion_android_share_alt", Color.HSVToColor(normal, SHARE_HSV));
iREFRESH = icon("ion_refresh", cNormal);
iSETTING = icon("ion_android_settings", cHigh);
init = true;
}
private IconicsDrawable icon(String icon, int color) {
IconicsDrawable iconicsDrawable = new IconicsDrawable(mContext)
.icon(icon)
.iconOffsetXDp(iOffsetXDp)
.iconOffsetYDp(iOffsetYDp)
.color(color);
iconicsDrawable.setBounds(0,0, iBounds, iBounds);
return iconicsDrawable;
}
}
| 41.673684
| 132
| 0.645112
|
2a403b177a1687da50ffcaf8b1232c5146459eeb
| 732
|
package org.icepear.echarts.components.marker;
import lombok.Data;
import lombok.experimental.Accessors;
import org.icepear.echarts.origin.component.marker.MarkArea1DDataItemOption;
import org.icepear.echarts.origin.util.ItemStyleOption;
import org.icepear.echarts.origin.util.SeriesLabelOption;
@Accessors(chain = true)
@Data
public class MarkArea1DDataItem implements MarkArea1DDataItemOption {
private ItemStyleOption itemStyle;
private SeriesLabelOption label;
private Object emphasis;
private Object select;
private Object blur;
private String name;
private Number xAxis;
private Number yAxis;
private Object type;
private Number valueIndex;
private String valueDim;
}
| 20.333333
| 76
| 0.780055
|
c1c183cc3aa10a7c557a69fadc2abbc66b80e008
| 786
|
/*
* Copyright (c) 2014 Plexonic Ltd
*/
package saltr.game;
/**
* The SLTAssetState class represents the asset state and provides the state related properties.
*/
public class SLTAssetState {
private String token;
private Object properties;
/**
* @param token The unique identifier of the state.
* @param properties The current state related properties.
*/
public SLTAssetState(String token, Object properties) {
this.token = token;
this.properties = properties;
}
/**
* @return The unique identifier of the state.
*/
public String getToken() {
return token;
}
/**
* @return The properties of the state.
*/
public Object getProperties() {
return properties;
}
}
| 21.833333
| 96
| 0.625954
|
a79bc5c5cad93a437c76208b44c2ad6df9517b1d
| 2,515
|
package org.afplib.samples;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Random;
import org.afplib.afplib.PTX;
import org.afplib.afplib.SFName;
import org.afplib.afplib.TRN;
import org.afplib.base.SF;
import org.afplib.base.Triplet;
import org.afplib.io.AfpFilter;
import org.afplib.io.AfpInputStream;
import org.afplib.io.AfpOutputStream;
import org.afplib.io.Filter;
public class Anonymizer {
private static final String VOWELS = "aeiou";
private static final String CONSONANTS = "bcdfghklmnpst";
private static final String DIGITS = "0123456789";
private static Random random = new Random();
private static char getRandom(String characters) {
int index = random.nextInt(characters.length());
char c = characters.charAt(index);
return c;
}
static void anonymize(TRN trn) {
Charset charset = Charset.forName("IBM500");
StringBuffer text = new StringBuffer(new String(trn.getTRNDATA(), charset));
boolean addConsonant = true;
for(int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
boolean isUpperCase = Character.isUpperCase(c);
if (isUpperCase) {
c = Character.toLowerCase(c);
}
if ('a' <= c && c <= 'z') {
if (addConsonant) {
c = getRandom(CONSONANTS);
addConsonant = false;
} else {
c = getRandom(VOWELS);
addConsonant = true;
}
} else if ('0' <= c && c <= '9') {
c = getRandom(DIGITS);
addConsonant = true;
} else {
c = 'x';
addConsonant = true;
}
if (isUpperCase) {
c = Character.toUpperCase(c);
}
text.replace(i, i + 1, ""+c);
}
byte[] s = text.toString().getBytes(charset);
trn.setTRNDATA(s);
}
public static void main(String[] args) {
try (AfpInputStream in = new AfpInputStream(
new BufferedInputStream(new FileInputStream(args[0])));
AfpOutputStream out = new AfpOutputStream(
new BufferedOutputStream(new FileOutputStream(args[1])))) {
AfpFilter.filter(in, out, new Filter() {
@Override
public STATE onStructuredField(SF sf) {
switch(sf.getId()) {
case SFName.PTX_VALUE:
PTX ptx = (PTX) sf;
for(Triplet t : ptx.getCS()) {
if(t instanceof TRN) {
anonymize((TRN) t);
}
}
return STATE.MODIFIED;
}
return STATE.UNTOUCHED;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 25.15
| 78
| 0.662028
|
93686e1ef61c37e53699e91fb08f79db5242d7dd
| 5,295
|
package yaml.element;
import java.util.ArrayList;
import yaml.element.NodeType;
import yaml.element.CapabilityType;
import yaml.element.ArchitectType;
import yaml.element.Output;
import yaml.element.Input;
import yaml.element.Group;
import yaml.element.NodeTemplate;
import yaml.element.Import;
import yaml.element.RelationshipType;
public class ServiceTemplate extends YAMLElement {
private String tosca_definitions_version;
private String tosca_default_namespace;
private String template_name;
private String template_author;
private String template_version;
private ArrayList<NodeType> nodeType = new ArrayList<NodeType>();
public ArrayList<CapabilityType> capabilityType = new ArrayList<CapabilityType>();
private ArrayList<ArchitectType> architectType = new ArrayList<ArchitectType>();
private ArrayList<Output> output = new ArrayList<Output>();
private ArrayList<Input> input = new ArrayList<Input>();
private ArrayList<Group> group = new ArrayList<Group>();
private ArrayList<NodeTemplate> nodeTemplate = new ArrayList<NodeTemplate>();
private ArrayList<Import> import = new ArrayList<Import>();
private ArrayList<RelationshipType> relationshipType = new ArrayList<RelationshipType>();
public int hashCode() {
int hashCode = 0;
if ( this.tosca_definitions_version != null ) {
hashCode += this.tosca_definitions_version.hashCode();
}
if ( this.tosca_default_namespace != null ) {
hashCode += this.tosca_default_namespace.hashCode();
}
if ( this.template_name != null ) {
hashCode += this.template_name.hashCode();
}
if ( this.template_author != null ) {
hashCode += this.template_author.hashCode();
}
if ( this.template_version != null ) {
hashCode += this.template_version.hashCode();
}
if ( this.nodeType != null ) {
hashCode += this.nodeType.hashCode();
}
if ( this.capabilityType != null ) {
hashCode += this.capabilityType.hashCode();
}
if ( this.architectType != null ) {
hashCode += this.architectType.hashCode();
}
if ( this.output != null ) {
hashCode += this.output.hashCode();
}
if ( this.input != null ) {
hashCode += this.input.hashCode();
}
if ( this.group != null ) {
hashCode += this.group.hashCode();
}
if ( this.nodeTemplate != null ) {
hashCode += this.nodeTemplate.hashCode();
}
if ( this.import != null ) {
hashCode += this.import.hashCode();
}
if ( this.relationshipType != null ) {
hashCode += this.relationshipType.hashCode();
}
if ( hashCode == 0 ) {
hashCode = super.hashCode();
}
return hashCode;
}
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object instanceof ServiceTemplate) {
ServiceTemplate serviceTemplateObject = (ServiceTemplate) object;
boolean equals = true;
equals &= ((this.tosca_definitions_version == serviceTemplateObject.tosca_definitions_version)
|| (this.tosca_definitions_version != null && this.tosca_definitions_version.equals(serviceTemplateObject.tosca_definitions_version)));
equals &= ((this.tosca_default_namespace == serviceTemplateObject.tosca_default_namespace)
|| (this.tosca_default_namespace != null && this.tosca_default_namespace.equals(serviceTemplateObject.tosca_default_namespace)));
equals &= ((this.template_name == serviceTemplateObject.template_name)
|| (this.template_name != null && this.template_name.equals(serviceTemplateObject.template_name)));
equals &= ((this.template_author == serviceTemplateObject.template_author)
|| (this.template_author != null && this.template_author.equals(serviceTemplateObject.template_author)));
equals &= ((this.template_version == serviceTemplateObject.template_version)
|| (this.template_version != null && this.template_version.equals(serviceTemplateObject.template_version)));
equals &= ((this.nodeType == serviceTemplateObject.nodeType)
|| (this.nodeType != null && this.nodeType.equals(serviceTemplateObject.nodeType)));
equals &= ((this.capabilityType == serviceTemplateObject.capabilityType)
|| (this.capabilityType != null && this.capabilityType.equals(serviceTemplateObject.capabilityType)));
equals &= ((this.architectType == serviceTemplateObject.architectType)
|| (this.architectType != null && this.architectType.equals(serviceTemplateObject.architectType)));
equals &= ((this.output == serviceTemplateObject.output)
|| (this.output != null && this.output.equals(serviceTemplateObject.output)));
equals &= ((this.input == serviceTemplateObject.input)
|| (this.input != null && this.input.equals(serviceTemplateObject.input)));
equals &= ((this.group == serviceTemplateObject.group)
|| (this.group != null && this.group.equals(serviceTemplateObject.group)));
equals &= ((this.nodeTemplate == serviceTemplateObject.nodeTemplate)
|| (this.nodeTemplate != null && this.nodeTemplate.equals(serviceTemplateObject.nodeTemplate)));
equals &= ((this.import == serviceTemplateObject.import)
|| (this.import != null && this.import.equals(serviceTemplateObject.import)));
equals &= ((this.relationshipType == serviceTemplateObject.relationshipType)
|| (this.relationshipType != null && this.relationshipType.equals(serviceTemplateObject.relationshipType)));
return equals;
}
return false;
}
}
| 44.872881
| 139
| 0.734089
|
f887dccac7ea947060c764510a821915023411d1
| 17,661
|
package org.openstreetmap.atlas.checks.event;
import static org.openstreetmap.atlas.geography.geojson.GeoJsonUtils.GEOMETRY;
import static org.openstreetmap.atlas.geography.geojson.GeoJsonUtils.OSM_IDENTIFIER;
import static org.openstreetmap.atlas.geography.geojson.GeoJsonUtils.PROPERTIES;
import static org.openstreetmap.atlas.geography.geojson.GeoJsonUtils.TYPE;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.openstreetmap.atlas.checks.base.Check;
import org.openstreetmap.atlas.checks.flag.CheckFlag;
import org.openstreetmap.atlas.checks.flag.FlaggedObject;
import org.openstreetmap.atlas.checks.flag.FlaggedRelation;
import org.openstreetmap.atlas.geography.geojson.GeoJsonBuilder;
import org.openstreetmap.atlas.geography.geojson.GeoJsonBuilder.GeometryWithProperties;
import org.openstreetmap.atlas.geography.geojson.GeoJsonObject;
import org.openstreetmap.atlas.tags.HighwayTag;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* Wraps a {@link CheckFlag} for submission to the {@link EventService} for handling {@link Check}
* results
*
* @author mkalender, bbreithaupt
*/
public final class CheckFlagEvent extends Event
{
private static final GeoJsonBuilder GEOJSON_BUILDER = new GeoJsonBuilder();
private static final String GEOMETRY_COLLECTION = "GeometryCollection";
private static final String GEOMETRIES = "geometries";
private static final String FEATURES = "features";
private static final String FEATURE_COLLECTION = "FeatureCollection";
private static final String INSTRUCTIONS = "instructions";
private final String checkName;
private final CheckFlag flag;
/**
* Converts give {@link CheckFlag} to {@link GeoJsonObject} with additional key-value parameters
*
* @param flag
* {@link CheckFlag} to convert to {@link GeoJsonObject}
* @param additionalProperties
* additional key-value parameters to be added in "properties" element of the
* top-level JSON object
* @return {@link GeoJsonObject} created from {@link CheckFlag}
*/
public static JsonObject flagToFeature(final CheckFlag flag,
final Map<String, String> additionalProperties)
{
final JsonObject flagProperties = new JsonObject();
flagProperties.addProperty(INSTRUCTIONS, flag.getInstructions());
// Add additional properties
additionalProperties.forEach(flagProperties::addProperty);
final JsonObject feature;
final List<GeometryWithProperties> geometriesWithProperties = flag
.getGeometryWithProperties();
final Set<FlaggedObject> flaggedRelations = flag.getFlaggedRelations();
final JsonArray geometriesJsonArray;
final JsonArray featureProperties = new JsonArray();
final Set<JsonElement> featureOsmIds = new HashSet<>();
if (!geometriesWithProperties.isEmpty())
{
if (geometriesWithProperties.size() + flaggedRelations.size() == 1)
{
feature = GEOJSON_BUILDER.create(geometriesWithProperties.get(0));
}
else
{
feature = GEOJSON_BUILDER.createGeometryCollectionFeature(geometriesWithProperties)
.jsonObject();
}
// Geometries with coordinates
geometriesJsonArray = feature.get(GEOMETRY).getAsJsonObject()
.getAsJsonArray(GEOMETRIES);
geometriesWithProperties.forEach(geometry -> Optional
.ofNullable(geometry.getProperties()).ifPresent(propertyMap ->
{
final JsonObject properties = new JsonObject();
propertyMap.forEach(
(key, value) -> properties.addProperty(key, (String) value));
featureProperties.add(properties);
Optional.ofNullable(properties.get(OSM_IDENTIFIER))
.ifPresent(featureOsmIds::add);
}));
}
else
{
feature = new JsonObject();
geometriesJsonArray = new JsonArray();
}
if (!flaggedRelations.isEmpty())
{
if (!feature.has(TYPE))
{
feature.addProperty(TYPE, "Feature");
}
// Get flagged relations as GeoJson features
final List<JsonObject> flaggedRelationFeatures = getFlaggedRelationsGeojsonFeatures(
flag);
if (flaggedRelations.size() == 1 && !feature.has(GEOMETRY))
{
feature.add(GEOMETRY, flaggedRelationFeatures.get(0).get(GEOMETRY));
}
else if (flaggedRelations.size() != 1 && !feature.has(GEOMETRY))
{
final JsonObject geometryCollection = new JsonObject();
geometryCollection.add(GEOMETRIES, geometriesJsonArray);
geometryCollection.addProperty(TYPE, GEOMETRY_COLLECTION);
feature.add(GEOMETRY, geometryCollection);
}
// To geometries of flagged objects add geometries of flaggedRelation
geometriesJsonArray.addAll(populateFlaggedRelationGeometries(flaggedRelationFeatures));
// To properties of flagged objects add properties of flaggedRelation
featureProperties
.addAll(populateFlaggedRelationFeatureProperties(flaggedRelationFeatures));
featureOsmIds.addAll(populateFlaggedRelationFeatureOsmIds(flaggedRelationFeatures));
}
final JsonArray uniqueFeatureOsmIds = new JsonArray();
featureOsmIds.forEach(uniqueFeatureOsmIds::add);
// Override name property if able to add a decorator to the name
CheckFlagEvent.featureDecorator(featureProperties)
.ifPresent(decorator -> flagProperties.addProperty("name",
String.format("%s (%s)",
Optional.ofNullable(flagProperties.getAsJsonPrimitive("name"))
.map(JsonPrimitive::getAsString).orElse("Task"),
decorator)));
// Reference properties lost during GeoJson conversion
flagProperties.add("feature_properties", featureProperties);
flagProperties.add("feature_osmids", uniqueFeatureOsmIds);
flagProperties.addProperty("feature_count", featureProperties.size());
feature.addProperty("id", flag.getIdentifier());
feature.add("properties", flagProperties);
return feature;
}
/**
* Get geometry of flagged relation feature.
*
* @param flaggedRelationFeature
* {@link FlaggedRelation} feature
* @return geometry as {@link JsonElement}
*/
private static JsonElement getFlaggedRelationGeometryFromFeature(
final JsonObject flaggedRelationFeature)
{
return flaggedRelationFeature.get(GEOMETRY);
}
/**
* Get property of the flagged relation feature
*
* @param flaggedRelationFeature
* {@link FlaggedRelation} feature
* @return property as {@link JsonElement}
*/
private static JsonElement getFlaggedRelationPropertyFromFeature(
final JsonObject flaggedRelationFeature)
{
return flaggedRelationFeature.get(PROPERTIES);
}
/**
* Converts all {@link FlaggedRelation} to geojson feature
*
* @param flag
* CheckFlag
* @return {@link List<JsonObject>} corresponding to geojson feature of {@link FlaggedRelation}
*/
private static List<JsonObject> getFlaggedRelationsGeojsonFeatures(final CheckFlag flag)
{
return flag.getFlaggedRelations().stream()
.map(flaggedRelation -> flaggedRelation.asGeoJsonFeature(flag.getIdentifier()))
.collect(Collectors.toList());
}
/**
* Populates geometries of flaggedRelation features to a {@link JsonArray}
*
* @param flaggedRelationFeatures
* geojson features of FlaggedRelations
* @return {@link JsonArray} of geometries of flaggedRelations
*/
private static JsonArray populateFlaggedRelationGeometries(
final List<JsonObject> flaggedRelationFeatures)
{
final JsonArray geometriesOfFlaggedRelations = new JsonArray();
// Add all geometries of flaggedRelations to the json array
flaggedRelationFeatures.stream().map(CheckFlagEvent::getFlaggedRelationGeometryFromFeature)
.forEach(geometriesOfFlaggedRelations::add);
return geometriesOfFlaggedRelations;
}
/**
* Populates properties of flaggedRelation features to a {@link JsonArray}
*
* @param flaggedRelationFeatures
* geojson features of FlaggedRelations
* @return {@link JsonArray} of properties of flaggedRelations
*/
private static JsonArray populateFlaggedRelationFeatureProperties(
final List<JsonObject> flaggedRelationFeatures)
{
final JsonArray featureProperties = new JsonArray();
// Update feature properties from flaggedRelation features
flaggedRelationFeatures.stream().map(CheckFlagEvent::getFlaggedRelationPropertyFromFeature)
.forEach(featureProperties::add);
return featureProperties;
}
/**
* Populates osmids of flaggedRelation features to a {@link Set<JsonElement>}
*
* @param flaggedRelationFeatures
* flaggedRelationFeatures geojson features of FlaggedRelations
* @return {@link Set<JsonElement>} of all osmids of flaggedRelations
*/
private static Set<JsonElement> populateFlaggedRelationFeatureOsmIds(
final List<JsonObject> flaggedRelationFeatures)
{
// Add osm id
return flaggedRelationFeatures.stream()
.map(CheckFlagEvent::getFlaggedRelationPropertyFromFeature)
.map(jsonElement -> jsonElement.getAsJsonObject().get(OSM_IDENTIFIER))
.collect(Collectors.toSet());
}
/**
* Converts given {@link CheckFlag} to {@link JsonObject} with additional key-value parameters
*
* @param flag
* {@link CheckFlag} to convert to {@link JsonObject}
* @param additionalProperties
* additional key-value parameters to be added in "properties" element of the
* top-level JSON object
* @return {@link JsonObject} created from {@link CheckFlag}
*/
public static JsonObject flagToJson(final CheckFlag flag,
final Map<String, String> additionalProperties)
{
JsonObject flagJson = new JsonObject();
if (!flag.getFlaggedObjects().isEmpty())
{
flagJson = GEOJSON_BUILDER
.createFromGeometriesWithProperties(flag.getGeometryWithProperties())
.jsonObject();
}
final Set<FlaggedObject> flaggedRelations = flag.getFlaggedRelations();
// Add features of FlaggedRelation if any
if (!flaggedRelations.isEmpty())
{
// Add type feature collection if not already set.
if (!flagJson.has(FEATURES))
{
flagJson.addProperty(TYPE, FEATURE_COLLECTION);
flagJson.add(FEATURES, new JsonArray());
}
final JsonArray features = flagJson.getAsJsonArray(FEATURES);
// Get features of each flaggedRelations and add it to the flagJson object's FEATURES
// element
flaggedRelations.stream()
.map(flaggedRelation -> flaggedRelation.asGeoJsonFeature(flag.getIdentifier()))
.forEach(features::add);
}
final JsonObject flagPropertiesJson = new JsonObject();
flagPropertiesJson.addProperty("id", flag.getIdentifier());
flagPropertiesJson.addProperty(INSTRUCTIONS, flag.getInstructions());
// Add additional properties
additionalProperties.forEach(flagPropertiesJson::addProperty);
// Add properties to the previously generate geojson
flagJson.add("properties", flagPropertiesJson);
return flagJson;
}
/**
* Extracts a decorator based on the collective features properties. Currently the only
* decoration is the highest class highway tag withing all of the feature properties for flags
* involving Edges.
*/
private static Optional<String> featureDecorator(final JsonArray featureProperties)
{
HighwayTag highestHighwayTag = null;
for (final JsonElement featureProperty : featureProperties)
{
final HighwayTag baslineHighwayTag = highestHighwayTag == null ? HighwayTag.NO
: highestHighwayTag;
try
{
highestHighwayTag = Optional
.ofNullable(
((JsonObject) featureProperty).getAsJsonPrimitive(HighwayTag.KEY))
.map(JsonPrimitive::getAsString).map(String::toUpperCase)
.map(HighwayTag::valueOf).filter(baslineHighwayTag::isLessImportantThan)
.orElse(highestHighwayTag);
}
catch (final IllegalArgumentException badValue)
{
return Optional.empty();
}
}
return Optional.ofNullable(highestHighwayTag)
.map(tag -> String.format("%s=%s", HighwayTag.KEY, tag.getTagValue()));
}
/**
* Construct a {@link CheckFlagEvent}
*
* @param checkName
* name of the check that created this event
* @param flag
* {@link CheckFlag} generated within this event
*/
public CheckFlagEvent(final String checkName, final CheckFlag flag)
{
this.checkName = checkName;
this.flag = flag;
}
/**
* @return {@link CheckFlag} generated by the check
*/
public CheckFlag getCheckFlag()
{
return this.flag;
}
/**
* @return Name of the check that generated this event
*/
public String getCheckName()
{
return this.checkName;
}
/**
* @return GeoJson Feature representation
*/
public JsonObject toGeoJsonFeature()
{
final Map<String, String> contextualProperties = new HashMap<>();
contextualProperties.put("name",
this.getCheckFlag().getChallengeName().orElse(this.getCheckName()));
contextualProperties.put("generator", "AtlasChecks");
contextualProperties.put("timestamp", this.getTimestamp().toString());
// Generate json for check flag with given contextual properties
return flagToFeature(this.getCheckFlag(), contextualProperties);
}
/**
* @return {@link JsonObject} form of the GeoJson FeatureCollection representation
*/
public JsonObject toGeoJsonFeatureCollection()
{
final Map<String, String> contextualProperties = new HashMap<>();
contextualProperties.put("generator", this.getCheckName());
contextualProperties.put("timestamp", this.getTimestamp().toString());
// Generate json for check flag with given contextual properties
return flagToJson(this.getCheckFlag(), contextualProperties);
}
/**
* @return {@link String} form of the GeoJson FeatureCollection representation
*/
@Override
public String toString()
{
return this.toGeoJsonFeatureCollection().toString();
}
public String asLineDelimitedGeoJsonFeatures()
{
return asLineDelimitedGeoJsonFeatures(jsonObject ->
{
});
}
public String asLineDelimitedGeoJsonFeatures(final Consumer<JsonObject> jsonMutator)
{
final JsonObject flagGeoJsonFeature = flag.asGeoJsonFeature();
final JsonObject flagGeoJsonProperties = flagGeoJsonFeature.get("properties")
.getAsJsonObject();
flagGeoJsonProperties.addProperty("flag:check", getCheckName());
flagGeoJsonProperties.addProperty("flag:timestamp", getTimestamp().toString());
jsonMutator.accept(flagGeoJsonFeature);
final StringBuilder builder = new StringBuilder().append(flagGeoJsonFeature.toString());
final FlaggedObject[] flaggedObjects = flag.getFlaggedObjects()
.toArray(new FlaggedObject[0]);
final int flaggedObjectsSize = flaggedObjects.length;
if (flaggedObjectsSize > 0)
{
builder.append('\n');
// loop through all the flagged objects except the last, give a new line
int index = 0;
for (; index < flaggedObjectsSize - 1; ++index)
{
final JsonObject feature = flaggedObjects[index]
.asGeoJsonFeature(flag.getIdentifier());
jsonMutator.accept(feature);
builder.append(feature.toString()).append('\n');
}
// dont give a new line to the last
final JsonObject feature = flaggedObjects[index].asGeoJsonFeature(flag.getIdentifier());
jsonMutator.accept(feature);
builder.append(feature.toString());
}
return builder.toString();
}
}
| 40.6
| 100
| 0.646
|
87932942994a2c593dde20bb1b2acd1c20239785
| 817
|
package com.chauncey.WeTeBot.model.weather;
import lombok.Data;
import org.springframework.stereotype.Component;
/**
* @author https://github.com/ChaunceyCX
* @version 1.0
* @className Now
* @description 实况天气
* @date 2019/6/29 上午10:27
**/
@Data
@Component
public class Now {
// 云量
private String cloud;
// 实况天气状况代码
private String cond_code;
// 实况天气状况描述
private String cond_txt;
// 体感温度,默认单位:摄氏度
private String fl;
// 相对湿度
private String hum;
// 降水量
private String pcpn;
// 大气压强
private String pres;
// 温度,默认单位:摄氏度
private String tmp;
// 能见度,默认单位:公里
private String vis;
// 风向360角度
private String wind_deg;
// 风向
private String wind_dir;
// 风力
private String wind_sc;
// 风速,公里/小时
private String wind_spd;
}
| 19
| 48
| 0.638923
|
062522ee964a8ea059e8414d4eb29496fb0eb848
| 1,533
|
package com.legwand.nodemonitor.config;
import com.legwand.nodemonitor.service.NodesServiceImpl;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.logging.Logger;
@Configuration
@PropertySource("classpath:application.properties")
@EnableMongoRepositories
public class MongoConfig {
private final static Logger LOG = Logger.getLogger(MongoConfig.class.getName());
@Value("${mongodb.connectionString}")
private String mongoDbConnectionString;
@Value("${mongodb.database}")
private String mongoDatabase;
@PostConstruct
void init() {
LOG.info(MessageFormat.format("Mongo connection string: {0}", mongoDbConnectionString));
LOG.info(MessageFormat.format("Mongo database: {0}", mongoDatabase));
}
@Bean
public MongoClient mongoClient() {
return MongoClients.create(mongoDbConnectionString);
}
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), mongoDatabase);
}
}
| 31.9375
| 96
| 0.778865
|
02df77809a4c53d9b9dd2c65cf100cc476d24381
| 2,044
|
package com.jaredrummler.baking.widget;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.jaredrummler.baking.R;
import com.jaredrummler.baking.data.model.Ingredient;
import com.jaredrummler.baking.data.model.Recipe;
import com.jaredrummler.baking.ui.details.DetailsActivity;
import com.jaredrummler.baking.utils.RecipeUtils;
/**
* The Adapter for the Widget's ListView items.
*/
final class WidgetViewFactory implements RemoteViewsService.RemoteViewsFactory {
private final Context context;
private final Recipe recipe;
WidgetViewFactory(Context context, Recipe recipe) {
this.context = context;
this.recipe = recipe;
}
@Override
public void onCreate() {
// no-op
}
@Override
public void onDataSetChanged() {
// no-op
}
@Override
public void onDestroy() {
// no-op
}
@Override
public int getCount() {
return recipe.getIngredients().size();
}
@Override
public RemoteViews getViewAt(int position) {
RemoteViews row = new RemoteViews(context.getPackageName(), R.layout.recipe_widget_item);
Ingredient ingredient = recipe.getIngredients().get(position);
row.setTextViewText(android.R.id.text1, RecipeUtils.formatIngredient(ingredient));
int bgColor = position % 2 == 0 ? 0xFFFFFFFF : 0xFFEFF0F1;
row.setInt(android.R.id.text1, "setBackgroundColor", bgColor);
Intent i = new Intent();
i.putExtra(DetailsActivity.EXTRA_RECIPE_ID, recipe.getId());
row.setOnClickFillInIntent(android.R.id.text1, i);
return row;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
}
| 25.234568
| 97
| 0.676614
|
a259fef9268e5664752830392a93f3b69591849a
| 96
|
package com.yuan.util.io;
/**
* 下载小工具类
* @author Yuan-9826
*/
public class DownloadUtils {
}
| 12
| 28
| 0.666667
|
e18315dc6c969fe03eb63acf807b7a8ffffc57ef
| 216
|
package com.github.inherit.demo;
/**
* @author 许大仙
* @version 1.0
* @since 2021-09-05 13:58
*/
public class Son extends Father {
public double max(double a, double b) {
return a > b ? a : b;
}
}
| 16.615385
| 43
| 0.592593
|
2f358e6cdbce1ad89c9e706f21bd4d97892b9a54
| 600
|
package pgnio;
import org.junit.Assert;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class EmbeddedDbTest extends DbTestBase {
@Test
public void testSimpleJdbc() throws SQLException {
try (java.sql.Connection conn = db.newJdbcConnection()) {
try (Statement stmt = conn.createStatement()) {
try (ResultSet rs = stmt.executeQuery("SELECT current_database();")) {
Assert.assertTrue(rs.next());
Assert.assertEquals(db.conf().dbConf.database, rs.getString(1));
}
}
}
}
}
| 26.086957
| 78
| 0.681667
|
5589060ec0b7ee84c2aa29fc6036079fe3d2ec5b
| 1,361
|
package enginecrafter77.survivalinc.client;
import java.awt.Color;
import enginecrafter77.survivalinc.stats.SimpleStatRecord;
import enginecrafter77.survivalinc.stats.StatProvider;
import enginecrafter77.survivalinc.stats.StatTracker;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Deprecated
@SideOnly(Side.CLIENT)
public class SimpleStatBar extends OverlayElementGroup<StatTracker> {
public final StatProvider<? extends SimpleStatRecord> provider;
public SimpleStatBar(StatProvider<? extends SimpleStatRecord> provider, TexturedElement icon, Color color)
{
super(Axis2D.VERTICAL);
this.provider = provider;
this.elements.add(new DifferentialArrow(provider, 8, 12, true));
this.elements.add(new ElementTypeAdapter<StatTracker, Float>(new GaugeBar(color), this::getRecordValue));
this.elements.add(icon);
}
@Override
public void draw(ScaledResolution resolution, ElementPositioner position, float partialTicks, StatTracker tracker)
{
if(tracker.isActive(this.provider, Minecraft.getMinecraft().player))
{
super.draw(resolution, position, partialTicks, tracker);
}
}
private Float getRecordValue(StatTracker tracker)
{
return tracker.getRecord(provider).getNormalizedValue();
}
}
| 34.025
| 115
| 0.806025
|
eabfbcabca722e0b6295eabf7f62c00dd93c49e8
| 216
|
package co.edu.eafit.solver.lib.systemsolver.lufactorization;
/**
* Contains the components of the output from any factorization method.
* @author halzate93
*
*/
public enum ELUResults {
L, U, Steps, X, Z, P
}
| 19.636364
| 71
| 0.722222
|
0c556bb3de69457441adb405d3604e4a76f786ff
| 486
|
package inferno_demo.core.commands;
import inferno_demo.core.BaseCommand;
import inferno_demo.models.api.WeaponInterface;
import java.util.Map;
public class PrintCommand extends BaseCommand {
@Override
public String execute() {
Map<String, WeaponInterface> weapons = super.getWeaponRepository().findAll();
if (weapons.containsKey(super.getParams()[0])) {
return weapons.get(super.getParams()[0]).toString();
}
return null;
}
}
| 27
| 85
| 0.693416
|
ff8bb3b4fa230a02c0415d0182d0cd27ef1f47d8
| 9,231
|
/*
* Copyright (C) ExBin Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.exbin.xbup.core.parser.token.event;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import org.exbin.xbup.core.block.XBBlockTerminationMode;
import org.exbin.xbup.core.parser.XBParsingException;
import org.exbin.xbup.core.parser.XBParserMode;
import org.exbin.xbup.core.parser.XBProcessingException;
import org.exbin.xbup.core.parser.XBProcessingExceptionType;
import org.exbin.xbup.core.parser.basic.XBHead;
import org.exbin.xbup.core.parser.basic.wrapper.FixedDataInputStreamWrapper;
import org.exbin.xbup.core.parser.basic.wrapper.TailDataInputStreamWrapper;
import org.exbin.xbup.core.parser.basic.wrapper.TerminatedDataInputStreamWrapper;
import org.exbin.xbup.core.parser.token.XBAttributeToken;
import org.exbin.xbup.core.parser.token.XBBeginToken;
import org.exbin.xbup.core.parser.token.XBDataToken;
import org.exbin.xbup.core.parser.token.XBEndToken;
import org.exbin.xbup.core.stream.FinishableStream;
import org.exbin.xbup.core.ubnumber.type.UBENat32;
import org.exbin.xbup.core.ubnumber.type.UBNat32;
/**
* Basic XBUP level 0 event reader - producer.
*
* @version 0.2.1 2017/05/19
* @author ExBin Project (http://exbin.org)
*/
@ParametersAreNonnullByDefault
public class XBEventReader implements XBEventProducer {
private XBParserMode parserMode = XBParserMode.FULL;
private InputStream source;
private XBEventListener listener;
public XBEventReader() {
}
public XBEventReader(InputStream inputStream) throws IOException {
this();
openStream(inputStream);
}
public XBEventReader(InputStream inputStream, XBParserMode parserMode) throws IOException {
this();
this.parserMode = parserMode;
openStream(inputStream);
}
private void openStream(InputStream stream) throws IOException {
source = stream;
}
/**
* Opens input byte-stream.
*
* @param stream input stream
* @throws java.io.IOException if input/output error
*/
public void open(InputStream stream) throws IOException {
openStream(stream);
}
/**
* Processes all events and send them to target.
*
* @throws XBProcessingException if processing error
* @throws java.io.IOException if input/output error
*/
public void read() throws XBProcessingException, IOException {
// Process header
if (parserMode != XBParserMode.SINGLE_BLOCK && parserMode != XBParserMode.SKIP_HEAD) {
XBHead.checkXBUPHead(source);
}
// Process single node
readNode();
}
/**
* Reads single node and all its child nodes.
*
* If parent node is in terminated mode, this might just close parent node.
*/
private void readNode() throws XBProcessingException, IOException {
// Size limits provides list of limits in tree structure
// with null value for terminated data parts
List<Integer> sizeLimits = new ArrayList<>();
// Process blocks until whole tree is processed
do {
UBNat32 attributePartSize = new UBNat32();
int attributePartSizeLength = attributePartSize.fromStreamUB(source);
shrinkStatus(sizeLimits, attributePartSizeLength);
if (attributePartSize.getLong() == 0) {
// Process terminator
if (sizeLimits.isEmpty() || sizeLimits.get(sizeLimits.size() - 1) != null) {
throw new XBParsingException("Unexpected terminator", XBProcessingExceptionType.UNEXPECTED_TERMINATOR);
}
sizeLimits.remove(sizeLimits.size() - 1);
if (sizeLimits.isEmpty()) {
// Process tail data
if (parserMode != XBParserMode.SINGLE_BLOCK && parserMode != XBParserMode.SKIP_TAIL && source.available() > 0) {
listener.putXBToken(XBDataToken.create(new TailDataInputStreamWrapper(source)));
}
}
listener.putXBToken(XBEndToken.create());
} else {
// Process regular block
int attributePartSizeValue = attributePartSize.getInt();
shrinkStatus(sizeLimits, attributePartSizeValue);
UBENat32 dataPartSize = new UBENat32();
int dataPartSizeLength = dataPartSize.fromStreamUB(source);
Integer dataPartSizeValue = dataPartSize.isInfinity() ? null : dataPartSize.getInt();
listener.putXBToken(XBBeginToken.create(dataPartSizeValue == null ? XBBlockTerminationMode.TERMINATED_BY_ZERO : XBBlockTerminationMode.SIZE_SPECIFIED));
if (attributePartSizeValue == dataPartSizeLength) {
// Process data block
FinishableStream dataWrapper = (dataPartSizeValue == null)
? new TerminatedDataInputStreamWrapper(source)
: new FixedDataInputStreamWrapper(source, dataPartSizeValue);
listener.putXBToken(XBDataToken.create((InputStream) dataWrapper));
dataWrapper.finish();
shrinkStatus(sizeLimits, (int) dataWrapper.getLength());
if (sizeLimits.isEmpty()) {
// Process tail data
if (parserMode != XBParserMode.SINGLE_BLOCK && parserMode != XBParserMode.SKIP_TAIL && source.available() > 0) {
listener.putXBToken(XBDataToken.create(new TailDataInputStreamWrapper(source)));
}
}
listener.putXBToken(XBEndToken.create());
} else {
// Process standard block
sizeLimits.add(dataPartSizeValue);
// Process attributes
attributePartSizeValue -= dataPartSizeLength;
while (attributePartSizeValue > 0) {
UBNat32 attribute = new UBNat32();
int attributeLength = attribute.fromStreamUB(source);
if (attributeLength > attributePartSizeValue) {
throw new XBParsingException("Attribute overflow", XBProcessingExceptionType.ATTRIBUTE_OVERFLOW);
}
attributePartSizeValue -= attributeLength;
listener.putXBToken(XBAttributeToken.create(attribute));
}
}
}
// Enclose all completed blocks
while (sizeLimits.size() > 0 && sizeLimits.get(sizeLimits.size() - 1) != null && sizeLimits.get(sizeLimits.size() - 1) == 0) {
sizeLimits.remove(sizeLimits.size() - 1);
if (sizeLimits.isEmpty()) {
// Process tail data
if (parserMode != XBParserMode.SINGLE_BLOCK && parserMode != XBParserMode.SKIP_TAIL && source.available() > 0) {
TailDataInputStreamWrapper dataWrapper = new TailDataInputStreamWrapper(source);
listener.putXBToken(XBDataToken.create(dataWrapper));
}
}
listener.putXBToken(XBEndToken.create());
}
} while (!sizeLimits.isEmpty());
}
/**
* Closes input stream.
*
* @throws java.io.IOException if input/output error
*/
public void close() throws IOException {
source.close();
}
/**
* Shrinks limits accross all depths.
*
* @param length Value to shrink all limits off
* @throws XBParsingException If limits are breached
*/
private static void shrinkStatus(List<Integer> sizeLimits, int length) throws XBParsingException {
for (int depthLevel = 0; depthLevel < sizeLimits.size(); depthLevel++) {
Integer limit = sizeLimits.get(depthLevel);
if (limit != null) {
if (limit < length) {
throw new XBParsingException("Block overflow", XBProcessingExceptionType.BLOCK_OVERFLOW);
}
sizeLimits.set(depthLevel, limit - length);
}
}
}
@Override
public void attachXBEventListener(XBEventListener eventListener) {
this.listener = eventListener;
}
@Nonnull
@Override
public String toString() {
String retValue;
retValue = super.toString();
return retValue;
}
}
| 39.448718
| 168
| 0.627993
|
adfc22e9939a69a3835f59c77e3cbfa950b316c6
| 2,907
|
package ru.stqa.training.selenium.litecart.tests;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import ru.stqa.training.selenium.TestBase;
import ru.stqa.training.selenium.litecart.tests.AutorizationTests;
import java.util.Random;
public class RegistrationTests extends TestBase {
final Random random = new Random();
@Test
public void newUserRegistration() {
AutorizationTests autorizationTests = new AutorizationTests();
String userName = "User_".concat(String.valueOf(random.nextInt()));
String lastname = "Shatilova";
String userPassword = "123";
String address1 = "Test address";
String postcode = "12345";
String city = "Washington";
String countryCode = "United States";
String phone = "+375291111111";
String emailPart = "@gmail.com";
driver.get("https://litecart.stqa.ru/ru/");
driver.findElement(By.linkText("New customers click here")).click();
WebElement customerForm = driver.findElement(By.cssSelector("form[name=customer_form]"));
while (customerForm.findElement(By.cssSelector("input[name=firstname]")).getAttribute("value").equals(""))
customerForm.findElement(By.cssSelector("input[name=firstname]")).sendKeys(userName);
customerForm.findElement(By.cssSelector("input[name=lastname]")).sendKeys(lastname);
customerForm.findElement(By.cssSelector("input[name=address1]")).sendKeys(address1);
customerForm.findElement(By.cssSelector("input[name=postcode]")).sendKeys(postcode);
customerForm.findElement(By.cssSelector("input[name=city]")).sendKeys(city);
driver.findElement(By.cssSelector("span.select2-selection__arrow")).click();
driver.findElement(By.xpath("//li[.='United States']")).click();
customerForm.findElement(By.cssSelector("select[name=zone_code]")).click();
customerForm.findElement(By.cssSelector("select[name=zone_code]")).findElement(By.xpath("./option[2]")).click();
customerForm.findElement(By.cssSelector("input[name=email]")).sendKeys(userName.concat(emailPart));
customerForm.findElement(By.cssSelector("input[name=phone]")).sendKeys((phone));
customerForm.findElement(By.cssSelector("input[name=password]")).sendKeys(userPassword);
customerForm.findElement(By.cssSelector("input[name=confirmed_password]")).sendKeys(userPassword);
customerForm.findElement(By.cssSelector("button[name=create_account]")).click();
Assert.assertTrue("Зарегистрировать нового пользователя не удалось", driver.findElement(By.xpath("//div[.=' Your customer account has been created.']")).isDisplayed());
autorizationTests.logOut();
autorizationTests.logInAsUser(userName.concat(emailPart), userPassword);
autorizationTests.logOut();
}
}
| 51
| 176
| 0.712762
|
bc27a3b0ba7c56964291ecf0d71084e5725c91ad
| 356
|
package com.github.johnsonmoon.queue;
/**
* Create by johnsonmoon at 2018/11/27 11:41.
*/
public interface Task<T> extends SimpleTask<T> {
/**
* Method before task execution.
*/
void before();
/**
* Method after task executed (was done).
*
* @param t returned value by task executed.
*/
void after(T t);
}
| 18.736842
| 48
| 0.595506
|
a5424dae67cc51a153a951135d9747c45a71ef15
| 167
|
package cz.muni.fi.spnp.gui.storage.oldformat.models;
/**
* Base class for the elements in old format.
*/
public class ElementOldFormat {
public String name;
}
| 18.555556
| 53
| 0.724551
|
3bce3a3ac71597b590c37485e00f2694116ad757
| 429
|
package com.dwarfeng.capacitychecker.impl.handler;
import com.dwarfeng.capacitychecker.stack.handler.Driver;
/**
* 驱动器构造器。
*
* @author DwArFeng
* @since 1.0.0
*/
public interface DriverProvider {
/**
* 返回制造器是否支持指定的类型。
*
* @param type 指定的类型。
* @return 制造器是否支持指定的类型。
*/
boolean supportType(String type);
/**
* 提供驱动器。
*
* @return 被提供的驱动器。
*/
Driver provide();
}
| 15.321429
| 57
| 0.596737
|
82433e7d26783c07a2557121b113e3020f6c3275
| 1,720
|
/**
* 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.cxf.binding.soap.interceptor;
import java.util.Iterator;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
public class SoapHeaderOutFilterInterceptor extends AbstractSoapInterceptor {
public static final SoapHeaderOutFilterInterceptor INSTANCE = new SoapHeaderOutFilterInterceptor();
public SoapHeaderOutFilterInterceptor() {
super(Phase.PRE_LOGICAL);
}
public void handleMessage(SoapMessage message) throws Fault {
Iterator<Header> iter = message.getHeaders().iterator();
while (iter.hasNext()) {
Header hdr = iter.next();
//Only remove inbound marked headers..
if (hdr == null || hdr.getDirection() == Header.Direction.DIRECTION_IN) {
iter.remove();
}
}
}
}
| 35.102041
| 103
| 0.719767
|
152df2ea6307bb8a68fd963c01214317912ef588
| 2,241
|
package com.example.demo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.*;
public class Commuter {
private static final Log LOG = LogFactory.getLog(Commuter.class);
private Commuter() { }
/**
* Find if destination city is reachable from origin. Will visit all the cities
* on the bucket list which is built by collecting all the neighbours of a visited place
* @param origin the origin
* @param destination the destination
* @return true if cities are connected
*/
public static boolean commute(City origin, City destination) {
LOG.info("Origin: " + origin.getName() + ", destination: " + destination.getName());
if (origin.equals(destination)) return true;
if (origin.getNearby().contains(destination)) return true;
/*
* The origin city was already visited since we have started from it
*/
Set<City> visited = new HashSet<>(Collections.singleton(origin));
/*
* Put all the neighboring cities into a bucket list
*/
Deque<City> bucketlist = new ArrayDeque<>(origin.getNearby());
while (!bucketlist.isEmpty()) {
City city = bucketlist.getLast();
if (city.equals(destination)) return true;
// remove the city from the bucket list
// first time visit?
if (!visited.contains(city)) {
visited.add(city);
// add neighbours to the bucket list and
// remove already visited cities from the list
bucketlist.addAll(city.getNearby());
bucketlist.removeAll(visited);
LOG.info("Visiting: ["
+ city.getName()
+ "] , neighbours: ["
+ (city.prettyPrint())
+ "], bucketlist: ["
+ bucketlist.toString()
+ "]");
} else {
// the city has been visited, so remove it from the bucket list
bucketlist.removeAll(Collections.singleton(city));
}
}
return false;
}
}
| 28.730769
| 92
| 0.558679
|
83c7a4638e728fad13a01ece234ef348ea1349ad
| 2,581
|
package com.bestaone.hiauth.controller;
import com.bestaone.hiauth.api.RoleApi;
import com.bestaone.hiauth.api.commom.ApiResponse;
import com.bestaone.hiauth.api.commom.PageVo;
import com.bestaone.hiauth.api.vo.RoleVo;
import com.bestaone.hiauth.domain.Role;
import com.bestaone.hiauth.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/role")
public class RoleController implements RoleApi {
@Autowired
RoleService roleService;
@Override
@GetMapping("/get_role_by_user_id/{userId:\\d+}")
public ApiResponse<List<RoleVo>> getRoleByUserId(@PathVariable Long userId) {
List<Role> roles = roleService.findByUserId(userId);
List<RoleVo> roleVos = new ArrayList();
for(Role r : roles){
RoleVo vo = new RoleVo();
vo.setId(r.getId());
vo.setCode(r.getCode());
vo.setName(r.getName());
roleVos.add(vo);
}
return ApiResponse.sucess(roleVos);
}
@Override
@GetMapping
public ApiResponse<PageVo<RoleVo>> query(Integer pageNum, Integer pageSize) {
Page pageinfo = PageHelper.startPage(pageNum, pageSize);
List<Role> roles = roleService.findAll();
List<RoleVo> roleVos = new ArrayList<>();
for(Role r : roles){
RoleVo vo = new RoleVo();
vo.setId(r.getId());
vo.setCode(r.getCode());
vo.setName(r.getName());
roleVos.add(vo);
}
return ApiResponse.sucess(new PageVo<>(pageinfo.getPageNum(), pageinfo.getPageSize(),pageinfo.getTotal(),pageinfo.getPages(),roleVos));
}
@Override
@PostMapping("/add_resources_by_role_id/{roleId:\\d+}")
public ApiResponse addRoleResources(@PathVariable Long roleId, @RequestBody Map params) {
List<Object> ids = (List<Object>) params.get("resourcesIds");
List<Long> resourcesIds = new ArrayList<>();
for(Object id : ids){
resourcesIds.add(Long.parseLong(id.toString()));
}
roleService.addRoleResources(roleId, resourcesIds);
return ApiResponse.sucess();
}
@Override
@DeleteMapping("/remove_resources_by_role_id/{roleId:\\d+}")
public ApiResponse removeRoleResources(@PathVariable Long roleId, @RequestBody Map params) {
List<Object> ids = (List<Object>) params.get("resourcesIds");
List<Long> resourcesIds = new ArrayList<>();
for(Object id : ids){
resourcesIds.add(Long.parseLong(id.toString()));
}
roleService.removeRoleResources(roleId, resourcesIds);
return ApiResponse.sucess();
}
}
| 31.864198
| 137
| 0.742735
|
9ff40de150d94b7db6edd6f125cc1f00c7b313c5
| 533
|
/*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.nr.agent.instrumentation.grpc;
import com.newrelic.api.agent.NewRelic;
public class GrpcConfig {
public static final boolean disributedTracingEnabled = NewRelic.getAgent().getConfig().getValue("grpc.distributed_tracing.enabled", true);
public static final boolean errorsEnabled = NewRelic.getAgent().getConfig().getValue("grpc.errors.enabled", true);
private GrpcConfig() {
}
}
| 24.227273
| 142
| 0.733583
|
60ce255a4ef6487e933f3aa5ca2f551c06330e83
| 446
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.csw.fotografia.adapters;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Nicolas Rincon
*/
public class Login {
public String login;
public String password;
}
| 20.272727
| 79
| 0.73991
|
60b3d582b17b5e262d4d306737810ce56a571286
| 4,031
|
package com.github.nightcodelabs.pretzel.helpers;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is used to gather and manage the information from a properties file
*/
public class ConfigReader {
public static final String PRETZELTASKPACKAGE = "pretzel";
public static final String PRETZELRESULTSPATH = "target/pretzel/";
public static final String PRETEZELINTERNALEXECUTIONFILEPATH = PRETZELRESULTSPATH + "internal/";
public static final String PRETEZELREPORTFILEPATH = PRETZELRESULTSPATH + "report/";
public static final String LOCUSTMASTERFILEPATH = PRETEZELINTERNALEXECUTIONFILEPATH + "locustMasterFile/";
public static final String LOCUSTMASTERFILENAME = "locust-master.py";
public static final String LOCUSTMASTERCOMPLETEPATH = LOCUSTMASTERFILEPATH + LOCUSTMASTERFILENAME;
public static final String CSVREPORTFOLDERPATH = PRETEZELINTERNALEXECUTIONFILEPATH + "/locustCsvReport/";
public static final String STATSREPORTPATH = CSVREPORTFOLDERPATH + "performanceResults_stats.csv";
public static final String STATSHISTORYREPORTPATH = CSVREPORTFOLDERPATH + "performanceResults_stats_history.csv";
public static final String CHARTDIR = "charts/";
public static final String CHARTPATH = PRETEZELREPORTFILEPATH + CHARTDIR;
private static final Logger logger = LoggerFactory.getLogger(ConfigReader.class);
private static ConfigReader _instance = new ConfigReader();
private Properties properties;
private ConfigReader() {
properties = new Properties();
this.loadData();
}
public static ConfigReader getInstance() {
return _instance;
}
/**
* Load data from config.properties file
*/
private void loadData(){
try {
File configPropertiesFile = new File("/configs/config.properties");
if(configPropertiesFile.exists()) properties.load(this.getClass().getResourceAsStream("/configs/config.properties"));
} catch (IOException e) {
logger.warn("Configuration properties file cannot be found");
throw new RuntimeException("Configuration properties file cannot be found");
}
}
/**
* @return Path where the Results Stats csv file of locust will be generated
*/
public String getStatsReportPath() {
if (properties.getProperty("statsReportPath") != null) return properties.getProperty("statsReportPath");
else return STATSREPORTPATH;
}
/**
* @return Path where the History Results csv file of locust will be generated
*/
public String getStatsHistoryReportPath() {
if (properties.getProperty("statsHistoryReportPath") != null) return properties.getProperty("statsHistoryReportPath");
else return STATSHISTORYREPORTPATH;
}
/**
* @return Path where the Bar Chart png file will be generated
*/
public String getChartPath() {
if (properties.getProperty("chartPath") != null) return properties.getProperty("chartPath");
else return CHARTPATH;
}
/**
* @return Path of the Bar Chart directory where the png files are going to be generated
*/
public String getChartDir() {
if (properties.getProperty("chartDir") != null) return properties.getProperty("chartDir");
else return CHARTDIR;
}
/**
* @return Path where the .py locust master file is stored (or will be generated)
*/
public String getLocustMasterFilePath() {
if (properties.getProperty("locustMasterPath") != null) return properties.getProperty("locustMasterPath");
else return LOCUSTMASTERCOMPLETEPATH;
}
/**
* @return Directory path where the csv file is going to be stored
*/
public String getCsvReportFolderPath() {
if (properties.getProperty("csvReportFolderPath") != null) return properties.getProperty("csvReportFolderPath");
else return CSVREPORTFOLDERPATH;
}
/**
* @return The name of the package where the tasks are stored
*/
public String getPretzelTaskPackage() {
if (properties.getProperty("pretzelTaskPackage") != null) return properties.getProperty("pretzelTaskPackage");
else return PRETZELTASKPACKAGE;
}
}
| 35.991071
| 120
| 0.763334
|
3f7467ae832b2cc9cb4e2c55fb981682a2404f66
| 1,226
|
package io.cucumber.core.gherkin.vintage;
import gherkin.pickles.PickleLocation;
import io.cucumber.core.gherkin.Location;
import java.util.Objects;
final class GherkinVintageLocation implements Location {
private final int line;
private final int column;
private GherkinVintageLocation(int line, int column) {
this.line = line;
this.column = column;
}
static Location from(PickleLocation location) {
return new GherkinVintageLocation(location.getLine(), location.getColumn());
}
public static Location from(gherkin.ast.Location location) {
return new GherkinVintageLocation(location.getLine(), location.getColumn());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GherkinVintageLocation that = (GherkinVintageLocation) o;
return line == that.line &&
column == that.column;
}
@Override
public int getLine() {
return line;
}
@Override
public int getColumn() {
return column;
}
@Override
public int hashCode() {
return Objects.hash(line, column);
}
}
| 24.52
| 84
| 0.650082
|
6ff847e187ed20184a2f51699c5d95733da7bf8c
| 4,838
|
package de.fxdiagram.idea.classdiagram;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import de.fxdiagram.core.XConnection;
import de.fxdiagram.core.XConnectionLabel;
import de.fxdiagram.core.XNode;
import de.fxdiagram.core.anchors.TriangleArrowHead;
import de.fxdiagram.core.extensions.ButtonExtensions;
import de.fxdiagram.idea.psi.AbstractPsiDiagramConfig;
import de.fxdiagram.mapping.*;
import de.fxdiagram.mapping.shapes.BaseClassNode;
import javafx.scene.paint.Color;
import static de.fxdiagram.mapping.shapes.BaseClassNode.*;
/**
* @author Jan Koehnlein
*/
public class IdeaClassDiagramConfig extends AbstractPsiDiagramConfig {
private NodeMapping<PsiClass> classNode = new NodeMapping<PsiClass>(this, "classNode", "Class Node") {
@Override
public XNode createNode(IMappedElementDescriptor<PsiClass> descriptor) {
return new BaseClassNode(descriptor);
}
@Override
protected void calls() {
labelFor(typeName, it -> it);
labelFor(packageName, it -> it);
labelFor(fileName, it -> it);
labelForEach(attribute, it -> PsiJavaUtil.getAttributes(it));
labelForEach(operation, it -> PsiJavaUtil.getOperations(it));
outConnectionForEach(referenceConnection, PsiJavaUtil::getReferences)
.asButton(side -> ButtonExtensions.getArrowButton(side, "Add reference"));
outConnectionForEach(superTypeConnection, PsiJavaUtil::getSuperTypes)
.asButton(side -> ButtonExtensions.getTriangleButton(side, "Add superType"));
}
};
private NodeLabelMapping<PsiClass> typeName = new NodeHeadingMapping<PsiClass>(this, CLASS_NAME) {
@Override
public String getText(PsiClass it) {
return it.getName();
}
};
private NodeLabelMapping<PsiClass> packageName = new NodeLabelMapping<PsiClass>(this, PACKAGE) {
@Override
public String getText(PsiClass it) {
String fqn = it.getQualifiedName();
final int lastIndexOf = fqn.lastIndexOf(".");
if (lastIndexOf != -1) {
return fqn.substring(0, lastIndexOf);
} else {
return "<default>";
}
}
};
private NodeLabelMapping<PsiClass> fileName = new NodeLabelMapping<PsiClass>(this, FILE_NAME) {
@Override
public String getText(PsiClass it) {
return it.getContainingFile().getName();
}
};
private NodeLabelMapping<PsiField> attribute = new NodeLabelMapping<PsiField>(this, ATTRIBUTE) {
@Override
public String getText(PsiField it) {
return it.getName() + ": " + it.getType().getPresentableText();
}
};
private NodeLabelMapping<PsiMethod> operation = new NodeLabelMapping<PsiMethod>(this, OPERATION) {
@Override
public String getText(PsiMethod it) {
return it.getName() + "() : " + it.getReturnType().getPresentableText();
}
};
private ConnectionMapping<PsiField> referenceConnection = new ConnectionMapping<PsiField>(this, "fieldConnection", "Reference") {
@Override
protected void calls() {
labelFor(referenceName, it -> it);
target(classNode, psiField -> ((PsiClassType) psiField.getType()).resolve());
}
};
private ConnectionLabelMapping<PsiField> referenceName = new ConnectionLabelMapping<PsiField>(this, "referenceName") {
@Override
public String getText(PsiField it) {
return it.getName();
}
};
private ConnectionMapping<PsiClassType> superTypeConnection = new ConnectionMapping<PsiClassType>(this, "superTypeConnection", "Super type") {
@Override
protected void calls() {
target(classNode, psiType -> psiType.resolve());
}
@Override
public XConnection createConnection(IMappedElementDescriptor<PsiClassType> descriptor) {
XConnection connection = super.createConnection(descriptor);
connection.setTargetArrowHead(new TriangleArrowHead(connection, 10, 15, null, Color.WHITE, false));
return connection;
}
};
@Override
protected <ARG> void entryCalls(ARG arg, MappingAcceptor<ARG> mappingAcceptor) {
if(arg instanceof PsiElement) {
PsiClass psiClass = PsiTreeUtil.getParentOfType((PsiElement)arg, PsiClass.class, false);
if(psiClass != null)
mappingAcceptor.add(classNode, e -> PsiTreeUtil.getParentOfType((PsiElement)e, PsiClass.class, false));
}
}
@Override
public String getID() {
return "ideaClassDiagram";
}
@Override
public String getLabel() {
return "Class diagram";
}
}
| 37.215385
| 146
| 0.652129
|
6de2cbfba269aa4d28bebd49a6069949e4ea42a1
| 471
|
/*
* 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 edu.co.sena.clases.metodos;
/**
*
* @author hernando
*/
public class Celular {
public Celular() {
}
public void llamar(String numero, String indicador){
System.out.println("esta marcando "+numero+ "indicaro"+indicador);
}
}
| 18.84
| 79
| 0.647558
|
0e9a1a7c9c3ebbf7fde6fa42cdee93ecdb87cf79
| 1,584
|
package com.nacid.data.users;
public class UserAddressRecord {
/**
* principno tezi promenlivi e dobre da se prehvyrlqt v dadeniq Impl class v bl layer-a
*/
public static final int ADDRESS_TYPE_INDIVIDUAL = 0;
public static final int ADDRESS_TYPE_GROUP = 1;
public static final int ADDRESS_RECORD_INACTIVE = 0;
public static final int ADDRESS_RECORD_ACTIVE = 1;
private int recordId;
private int userId;
/**
* Opredelq dali adresa koito e zadaden se otnasq za grupa ili e individualen
* primerno 192.168.0.1 moje da se otnasq za 192.168.0.1(individualen) ili 192.168.0.1*(grupov)
*/
private String ipAddress;
private int addressType;
private int active;
public UserAddressRecord() {
}
public UserAddressRecord(int recordId, int userId, String ipAddress, int addressType, int active) {
this.recordId = recordId;
this.userId = userId;
this.ipAddress = ipAddress;
this.addressType = addressType;
this.active = active ;
}
public int getRecordId() {
return recordId;
}
public int getUserId() {
return userId;
}
public String getIpAddress() {
return ipAddress;
}
public int getAddressType() {
return addressType;
}
public int getActive() {
return active;
}
public void setRecordId(int recordId) {
this.recordId = recordId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public void setAddressType(int addressType) {
this.addressType = addressType;
}
public void setActive(int active) {
this.active = active;
}
}
| 24
| 100
| 0.728535
|
21696ba508529b8c66ea342f523e321483349472
| 11,418
|
package controllers.settings;
import controllers.GraphicController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import library.graphic.settings.GraphicSettings;
import library.graphic.settings.WriteGraphicSettings;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
/**
* Created by Bohdan Pashko on 03.04.2016.
*/
public class GraphicSettingsController implements Initializable {
public static final ObservableList<String> colors = FXCollections.observableArrayList(
"aliceblue", "antiquewhite", "aqua", "aquamarine", "beige", "bisque", "black", "blanchedalmond", "blue", "brown", "chocolate", "coral", "cyan", "darkslategrey", "darkturquoise",
"deepskyblue", "dimgray", "dodgerblue", "firebrick", "gold", "goldenrod", "gray", "green", "greenyellow", "grey", "indigo", "khaki", "lavender", "lightsteelblue",
"lightyellow", "lime", "limegreen", "linen", "magenta", "mediumturquoise", "mediumvioletred", "moccasin", "navajowhite", "orange", "pink", "purple", "red", "skyblue", "springgreen",
"steelblue", "tan", "tomato", "wheat", "white", "yellow");
@FXML
private Label labelSubTitleCheckBox;
@FXML
private CheckBox checkBoxClearBedoreDraw, checkBoxDrawCoordinateGrid, checkBoxDrawMouseCoordinate, checkBoxDrawFunctionValue, checkBoxDrawMouseClickDots;
@FXML
private Label labelSubTitleComboBox;
@FXML
private Label labelCBColorOfBackground, labelCBColorOfEdges, labelCBColorOfCoordinateLines, labelCBColorOfCoordinateValues, labelCBColorOfCoordinateGrid,
labelCBColorOfFunctionValuesDots, labelCBColorOfMouseDots, labelCBColorOfRootsDots;
@FXML
private ComboBox comboBoxColorOfBackground, comboBoxColorOfEdges, comboBoxColorOfCoordinateLines, comboBoxColorOfCoordinateValues, comboBoxColorOfCoordinateGrid,
comboBoxColorOfFunctionValuesDots, comboBoxColorOfMouseDots, comboBoxColorOfRootsDots;
@FXML
private Label labelSubTitleSlider;
@FXML
private Label labelSlMinOneLineSegment, labelSlZoomSensivity, labelSlRunAwaySensivity;
@FXML
private Slider sliderMinOneLineSegment, sliderZoomSensivity, sliderRunAwaySensivity;
private ResourceBundle resourceBundle;
private GraphicSettings graphicSettings;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.resourceBundle = resources;
}
public GraphicSettings getGraphicSettings() {
return graphicSettings;
}
public void setGraphicSettings(GraphicSettings graphicSettings) {
this.graphicSettings = graphicSettings;
initializeBooleans();
initializeColors();
initializeSliders();
labelSubTitleCheckBox.setText(resourceBundle.getString("settings.label.titleCheckBoxes"));
labelSubTitleComboBox.setText(resourceBundle.getString("settings.label.titleColors"));
labelSubTitleSlider.setText(resourceBundle.getString("settings.label.Values"));
}
private void initializeSliders() {
labelSlMinOneLineSegment.setText(resourceBundle.getString("settings.label.MinLineSegmentWeight"));
labelSlZoomSensivity.setText(resourceBundle.getString("settings.label.ZoonSensivity"));
labelSlRunAwaySensivity.setText(resourceBundle.getString("settings.label.RunAwayGraphicSensivity"));
setSliderMajors(sliderMinOneLineSegment, 20, 300, 40, 8, graphicSettings.getMinOneLineSegment());
setSliderMajors(sliderZoomSensivity, 0, 1, 0.25, 0.05, graphicSettings.getZoomSensivity());
setSliderMajors(sliderRunAwaySensivity, 0, 1, 0.25, 0.05, graphicSettings.getRunAwaySensivity());
sliderMinOneLineSegment.valueProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setMinOneLineSegment((double) newValue);
});
sliderZoomSensivity.valueProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setZoomSensivity((double) newValue);
});
sliderRunAwaySensivity.valueProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setRunAwaySensivity((double) newValue);
});
}
private void setSliderMajors(Slider slider, double min, double max, double tickUnit, double increment, double startValue) {
slider.setMin(min);
slider.setMax(max);
slider.setMajorTickUnit(tickUnit);
slider.setBlockIncrement(increment);
slider.setShowTickMarks(true);
slider.setShowTickLabels(true);
slider.setValue(startValue);
}
private void initializeBooleans() {
checkBoxClearBedoreDraw.setSelected(graphicSettings.isClearBeforeDrawing());
checkBoxDrawCoordinateGrid.setSelected(graphicSettings.isDrawCoordinateGrid());
checkBoxDrawMouseCoordinate.setSelected(graphicSettings.isDrawCurrentMouseCoordinate());
checkBoxDrawFunctionValue.setSelected(graphicSettings.isDrawCurrentFunctionCoordinates());
checkBoxDrawMouseClickDots.setSelected(graphicSettings.isEnterMouseDots());
checkBoxClearBedoreDraw.setText(resourceBundle.getString("settings.checkBox.clearBeforeDrawing"));
checkBoxDrawCoordinateGrid.setText(resourceBundle.getString("settings.checkBox.DrawCoordinateGrid"));
checkBoxDrawMouseCoordinate.setText(resourceBundle.getString("settings.checkBox.DrawMouseCoordinate"));
checkBoxDrawFunctionValue.setText(resourceBundle.getString("settings.checkBox.DrawFunctionsValues"));
checkBoxDrawMouseClickDots.setText(resourceBundle.getString("settings.checkBox.DrawClickMouseDots"));
checkBoxClearBedoreDraw.selectedProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setClearBeforeDrawing(newValue);
});
checkBoxDrawCoordinateGrid.selectedProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setDrawCoordinateGrid(newValue);
});
checkBoxDrawMouseCoordinate.selectedProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setDrawCurrentMouseCoordinate(newValue);
});
checkBoxDrawFunctionValue.selectedProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setDrawCurrentFunctionCoordinates(newValue);
});
checkBoxDrawMouseClickDots.selectedProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setEnterMouseDots(newValue);
});
}
private void initializeColors() {
labelCBColorOfBackground.setText(resourceBundle.getString("settings.label.BackgroundColor"));
labelCBColorOfEdges.setText(resourceBundle.getString("settings.label.EdgesColor"));
labelCBColorOfCoordinateLines.setText(resourceBundle.getString("settings.label.CoordinateLinesColor"));
labelCBColorOfCoordinateValues.setText(resourceBundle.getString("settings.label.CoordinateValuesColor"));
labelCBColorOfCoordinateGrid.setText(resourceBundle.getString("settings.label.CoordinateGridColor"));
labelCBColorOfFunctionValuesDots.setText(resourceBundle.getString("settings.label.FunctionDotsColor"));
labelCBColorOfMouseDots.setText(resourceBundle.getString("settings.label.MouseDotsColor"));
labelCBColorOfRootsDots.setText(resourceBundle.getString("settings.label.RootsDotsColor"));
comboBoxColorOfBackground.setItems(colors);
comboBoxColorOfEdges.setItems(colors);
comboBoxColorOfCoordinateLines.setItems(colors);
comboBoxColorOfCoordinateValues.setItems(colors);
comboBoxColorOfCoordinateGrid.setItems(colors);
comboBoxColorOfFunctionValuesDots.setItems(colors);
comboBoxColorOfMouseDots.setItems(colors);
comboBoxColorOfRootsDots.setItems(colors);
setCurrentColor(graphicSettings.getClearColor(), comboBoxColorOfBackground, colors);
setCurrentColor(graphicSettings.getEdgesColor(), comboBoxColorOfEdges, colors);
setCurrentColor(graphicSettings.getCoordinateLinesColor(), comboBoxColorOfCoordinateLines, colors);
setCurrentColor(graphicSettings.getCoordinateValuesColor(), comboBoxColorOfCoordinateValues, colors);
setCurrentColor(graphicSettings.getCoordinateGridColor(), comboBoxColorOfCoordinateGrid, colors);
setCurrentColor(graphicSettings.getDotsOnFunctionsColor(), comboBoxColorOfFunctionValuesDots, colors);
setCurrentColor(graphicSettings.getMouseDotsColor(), comboBoxColorOfMouseDots, colors);
setCurrentColor(graphicSettings.getSolverDotsColor(), comboBoxColorOfRootsDots, colors);
comboBoxColorOfBackground.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setClearColor(Color.web((String) newValue));
});
comboBoxColorOfEdges.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setEdgesColor(Color.web((String) newValue));
});
comboBoxColorOfCoordinateLines.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setCoordinateLinesColor(Color.web((String) newValue));
});
comboBoxColorOfCoordinateValues.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setCoordinateValuesColor(Color.web((String) newValue));
});
comboBoxColorOfCoordinateGrid.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setCoordinateGridColor(Color.web((String) newValue));
});
comboBoxColorOfFunctionValuesDots.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setDotsOnFunctionsColor(Color.web((String) newValue));
});
comboBoxColorOfMouseDots.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setMouseDotsColor(Color.web((String) newValue));
});
comboBoxColorOfRootsDots.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
graphicSettings.setSolverDotsColor(Color.web((String) newValue));
});
}
public static void setCurrentColor(Color color, ComboBox<String> comboBox, List<String> colors) {
for (int i = 0; i < colors.size(); i++) {
if (color.equals(Color.web(colors.get(i)))) {
comboBox.getSelectionModel().select(i);
break;
}
}
comboBox.setCellFactory((ist) -> new ListCell<String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
Rectangle rect = new Rectangle(18, 18);
if (item != null) {
rect.setFill(Color.web(item));
setText(item);
setGraphic(rect);
}
}
});
}
}
| 54.113744
| 193
| 0.732703
|
005ed51c640afcec4a0a137fedc3a2e87c0dd529
| 15,408
|
package com.ambit.otgorithm.views;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ambit.otgorithm.R;
import com.ambit.otgorithm.adapters.GalleryRecyclerAdapter;
import com.ambit.otgorithm.dto.GalleryDTO;
import com.ambit.otgorithm.fragments.DatePickerFragment;
import com.ambit.otgorithm.modules.RecyclerViewItemClickListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dmax.dialog.SpotsDialog;
import static com.ambit.otgorithm.views.ProvinceActivity.fromProvinceActivity;
public class GalleryActivity extends AppCompatActivity
implements DatePickerDialog.OnDateSetListener {
AlertDialog mDialog;
Dialog galleryDialog;
ImageView closePopup;
Button btnToUpload;
RecyclerView recyclerView;
TextView textViewToolbarTitle;
GalleryRecyclerAdapter adapter;
Button calendar;
FirebaseDatabase mFirebaseDb;
DatabaseReference mGalleryRef;
ArrayList<GalleryDTO> mGalleryDTOS;
int position;
CoordinatorLayout mCoordinatorLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 액티비티 내 캡쳐 방지
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_gallery);
mDialog = new SpotsDialog.Builder().setContext(GalleryActivity.this).build();
mDialog.show();
mFirebaseDb = FirebaseDatabase.getInstance();
mGalleryRef = mFirebaseDb.getReference().child("galleries");
/*****************************************************************
* 커스텀 툴바 셋팅
*/
textViewToolbarTitle = (TextView) findViewById(R.id.toolbar_title);
textViewToolbarTitle.setText("전투 상황판");
textViewToolbarTitle.setGravity(View.TEXT_ALIGNMENT_CENTER);
textViewToolbarTitle.setTextColor(Color.WHITE);
Toolbar galleryToolbar = (Toolbar) findViewById(R.id.toolbar_basic);
setSupportActionBar(galleryToolbar); // 액션바와 같게 만들어줌
// 기본 타이틀을 보여줄 지 말 지 설정
getSupportActionBar().setDisplayShowTitleEnabled(false);
// 뒤로가기 버튼, Default로 true만 해도 Back 버튼이 생김
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/****************************************************************/
// 도움말 다이얼로그 객체 생성
galleryDialog = new Dialog(this);
/*
galleryToolbar.setTitle("전투 상황 보고");
galleryToolbar.setTitleTextColor(Color.WHITE);
galleryToolbar.setForegroundGravity(View.TEXT_ALIGNMENT_CENTER);
*/
/*
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_actionbar);
View view = getSupportActionBar().getCustomView();
*/
/*
ImageButton imageButton= (ImageButton)view.findViewById(R.id.action_bar_back);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
ImageButton imageButton2= (ImageButton)view.findViewById(R.id.action_bar_forward);
imageButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Forward Button is clicked",Toast.LENGTH_LONG).show();
}
});
*/
mCoordinatorLayout = findViewById(R.id.layout_gallery);
recyclerView = (RecyclerView) findViewById(R.id.recycleView);
mGalleryDTOS = new ArrayList<>();
//position = 0;
addGalleryListener();
Log.d("ㄷㄷㄷ : ","ㄷㄷㄷ");
adapter = new GalleryRecyclerAdapter(this, mGalleryDTOS);
//adapter.setmGalleryActivity(this);
//Log.d("갤러리 테스트: ", DataDTO.getData().get(0).imageUrl);
recyclerView.setAdapter(adapter);
// Vertical Orientation By Default
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL));
// adapter.setRecyclerView(recyclerView);
/* recyclerView.addOnItemTouchListener(new RecyclerViewItemClickListener(this, new RecyclerViewItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
GalleryDTO galleryDTO = adapter.getItem(position);
Intent intent = new Intent(GalleryActivity.this, ProfileActivity.class);
intent.putExtra("ranker_id",galleryDTO.getNickname());
startActivity(intent);
}
}));*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/*// 커스텀 액션바 만들기
ActionBar actionBar = getSupportActionBar();
// Custom Actionbar를 사용하기 위해 CustomEnabled을 true 시키고 필요 없는 것은 false 시킨다
actionBar.setDisplayHomeAsUpEnabled(false); //액션바 아이콘을 업 네비게이션 형태로 표시합니다.
actionBar.setDisplayShowTitleEnabled(false); //액션바에 표시되는 제목의 표시유무를 설정합니다.
actionBar.setDisplayShowHomeEnabled(false); //홈 아이콘을 숨김처리합니다.
actionBar.setDisplayShowCustomEnabled(true);
//layout을 가지고 와서 actionbar에 포팅을 시킵니다.
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View actionbar = inflater.inflate(R.layout.custom_actionbar, null);
actionBar.setCustomView(actionbar);
//액션바 양쪽 공백 없애기
Toolbar parent = (Toolbar)actionbar.getParent();
parent.setContentInsetsAbsolute(0,0);*/
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_info, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
// 툴바의 뒤로가기 키를 눌렀을 때 동작
case android.R.id.home:
/*if (fromProvinceActivity) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
fromProvinceActivity = false;
return true;
} else {*/
finish();
return true;
/*}*/
case R.id.action_information:
showGalleryInfoPopup();
break;
// will be updated since ver 2.0
case R.id.calendar:
Log.d("테스트: ", "R.id.calendar 진입");
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
break;
case R.id.linearViewHorizontal:
// LinearLayoutManager(Context context)
LinearLayoutManager mLinearLayoutManagerHorizontal = new LinearLayoutManager(this);
mLinearLayoutManagerHorizontal.setOrientation(LinearLayout.HORIZONTAL);
recyclerView.setLayoutManager(mLinearLayoutManagerHorizontal);
break;
case R.id.linearViewVertical:
LinearLayoutManager mLinearLayoutManagerVertical= new LinearLayoutManager(this);
mLinearLayoutManagerVertical.setOrientation(LinearLayout.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
break;
case R.id.gridView:
// GridLayoutManager(Context context, int spanCount)
GridLayoutManager mGridLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mGridLayoutManager);
break;
case R.id.staggeredViewHorizontal:
// StaggeredGridLayoutManager(int spanCount, int orientation)
StaggeredGridLayoutManager mStaggeredHorizontalLayoutManager =
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(mStaggeredHorizontalLayoutManager);
break;
case R.id.staggeredViewVertical: // 채택할 구조
StaggeredGridLayoutManager mStaggeredVerticalLayoutManager =
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mStaggeredVerticalLayoutManager);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* step 1: create dialog object in onCreate method
* ex. Dialog dialog = new Dialog(this);
* step 2: connecting widget
* step 3: call method and declare setContentView method
* step 4: event handling
* ex. ImageView closePopup;
*/
public void showGalleryInfoPopup() {
galleryDialog.setContentView(R.layout.dialog_gallery);
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = auth.getCurrentUser();
closePopup = galleryDialog.findViewById(R.id.close_popup);
btnToUpload = galleryDialog.findViewById(R.id.btn_to_upload);
if(firebaseUser==null)
btnToUpload.setVisibility(View.INVISIBLE);
closePopup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
galleryDialog.dismiss();
}
});
btnToUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GalleryActivity.this, UploadActivity.class);
intent.putExtra("mode", "upload");
startActivity(intent);
galleryDialog.dismiss();
}
});
galleryDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
galleryDialog.show();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance().format(c.getTime());
// TextView textView = (TextView) findViewById(R.id.textView);
}
private void addGalleryListener(){
mGalleryRef.addListenerForSingleValueEvent(new ValueEventListener() {
List<GalleryDTO> galleryDTOList = new ArrayList<>();
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
galleryDTOList.clear();
for(DataSnapshot children : dataSnapshot.getChildren()){
GalleryDTO galleryDTO = children.getValue(GalleryDTO.class);
galleryDTOList.add(galleryDTO);
}
Collections.reverse(galleryDTOList);
addition(galleryDTOList);
mDialog.dismiss();
}
@Override
public void onCancelled(DatabaseError databaseError) {
mDialog.dismiss();
}
});
}
private void addition(List<GalleryDTO> list){
adapter.addList(list);
}
/* public void accuse(final GalleryDTO galleryDTO){
Log.d("끄억","끄억");
Snackbar.make(mCoordinatorLayout,"신고는 철회가 안되니 신중히 해주십시오.",Snackbar.LENGTH_LONG).setAction("신고", new View.OnClickListener() {
@Override
public void onClick(View v) {
mGalleryRef.child(galleryDTO.gid).child("accusationCount").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
int accusationCount = dataSnapshot.getValue(Integer.class);
if(accusationCount>=4){
mGalleryRef.child(galleryDTO.gid).removeValue();
}else {
mGalleryRef.child(galleryDTO.gid).child("accusationCount").setValue(accusationCount+1);
Map<String,Boolean> map = new HashMap<>();
}
}else {
mGalleryRef.child(galleryDTO.gid).child("accusationCount").setValue(1);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}).show();
}*/
} // end of class
// 프로필 올리면 메뉴바 되는
/*public class GalleryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.content_main.activity_gallery);
final Toolbar mytoolbar = (Toolbar) findViewById(R.id.profileToolbar);
setSupportActionBar(mytoolbar);
// 뒤로가기 버튼, default로 true만 해도 백버튼이 생김
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout ctl = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
ctl.setTitle("Corock");
*//* Context context = this;
ctl.setContentScrimColor(ContextCompat.getColor());*//*
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// toolbar의 back키 눌렀을 때 동작
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}*/
| 37.857494
| 143
| 0.642004
|
9b52aac66b9c9607ddca8c58baa6278e24afa127
| 306
|
package open.sylhare.rest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "This is JChess";
}
}
| 20.4
| 62
| 0.722222
|
96ece43cd3859d0b5aec65470a9cf3ab9b1ddd2b
| 1,263
|
package com.ruoyi.tickets.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
* 用于在购买车票接口接收前端传来的数据
*/
public class TicketOrder {
private String busId;
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date startDate;
@JsonFormat(pattern="kk:mm:ss",timezone = "GMT+8")
private Date startTime;
public TicketOrder() {
}
public TicketOrder(String busId, Date startDate, Date startTime) {
this.busId = busId;
this.startDate = startDate;
this.startTime = startTime;
}
public String getBusId() {
return busId;
}
public void setBusId(String busId) {
this.busId = busId;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public String toString() {
return "TicketOrder{" +
"busId='" + busId + '\'' +
", startDate=" + startDate +
", startTime=" + startTime +
'}';
}
}
| 21.40678
| 70
| 0.588282
|
0b65eb76cc88d7d84a4fed73d309aab0194803aa
| 399
|
package com.example.jpaexamples.example02.onetomany;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
@Data
@NoArgsConstructor
@Entity
public class User02 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy = "user")
private List<Address02> addresses;
}
| 19.95
| 55
| 0.75188
|
62e117ca9a7202487f1f5907319e4f2a4f7cee07
| 2,548
|
package ru.job4j.vacancy;
import org.apache.log4j.Logger;
import java.sql.*;
import java.util.ArrayList;
public class DataBase implements AutoCloseable {
private static final Logger LOGGER = Logger.getLogger(DataBase.class);
private Connection connect;
public DataBase() {
connect = ConnectorDB.getConnect();
}
public void createDB() {
String sql = "CREATE DATABASE vacancyDB;";
try (PreparedStatement pstmt = connect.prepareStatement(sql)) {
pstmt.execute();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
}
}
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS vacancies (id serial primary key, name varchar(150), body text, link varchar(250), v_date date)";
try (PreparedStatement pstmt = connect.prepareStatement(sql)) {
pstmt.execute();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
}
}
public boolean insertVacancy(ArrayList<Vacancy> vacancyList) {
String sql = "INSERT INTO vacancies(name, body, link, v_date) VALUES (?, ?, ?, ?)";
boolean inserted = false;
try (PreparedStatement pstm = connect.prepareStatement(sql)) {
connect.setAutoCommit(false);
for (Vacancy v : vacancyList) {
pstm.setString(1, v.getName());
pstm.setString(2, v.getBody());
pstm.setString(3, v.getLink());
pstm.setDate(4, v.getDate());
pstm.addBatch();
}
pstm.executeBatch();
connect.commit();
inserted = true;
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
}
return inserted;
}
public Date lastDateInDB() {
String sql = "SELECT MAX(v_date) as date from vacancies";
ResultSet resultSet;
Date lastdate = null;
try (PreparedStatement pstmt = connect.prepareStatement(sql)) {
resultSet = pstmt.executeQuery();
while (resultSet.next()) {
lastdate = resultSet.getDate("date");
}
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
}
return lastdate;
}
@Override
public void close() {
if (connect != null) {
try {
connect.close();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
| 31.45679
| 146
| 0.556122
|
067aa36d7880609e82ddcf0b5a8aeed7c838a39d
| 521
|
/*
* 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 gwent;
/**
*
* @author kenne
*/
public class CampoBatalha {
private Carta[] listaCartas;
private int numCartas;
private Carta[] containerCartasLongo;
private Carta[] containerCartasMedio;
private Carta[] containerCartasCurto;
private Carta[] containerCartasEspecial;
}
| 23.681818
| 80
| 0.683301
|
203187fdcf95b98a6ba5683ef047e1eb991aea53
| 903
|
package cz.mg.language.entities.mg.runtime.instances;
import cz.mg.collections.array.Array;
import cz.mg.annotations.requirement.Mandatory;
import cz.mg.annotations.requirement.Optional;
import cz.mg.annotations.storage.Link;
import cz.mg.annotations.storage.Part;
import cz.mg.language.entities.mg.runtime.MgObject;
import cz.mg.language.entities.mg.runtime.components.types.classes.MgClass;
public class MgClassInstanceImpl implements MgClassInstance {
@Mandatory @Link
private final MgClass type;
@Mandatory @Part
private final Array<@Optional MgObject> objects;
public MgClassInstanceImpl(MgClass clazz) {
this.type = clazz;
this.objects = new Array<>(clazz.getCache().getVariableCount());
}
@Override
public MgClass getType() {
return type;
}
@Override
public Array<MgObject> getObjects() {
return objects;
}
}
| 26.558824
| 75
| 0.728682
|
d575a67c87557fbcabaa36aa94d6d0717728c601
| 343
|
package com.home.base.constlist.generate;
/** 机器人测试模式(generated by shine) */
public class GRobotTestModeType
{
/** 场景内随机找点移动 */
public static final int RandomMove=7;
/** 测试gm指令 */
public static final int TestGM=101;
/** 测试大乱斗 */
public static final int TestMelee=102;
/** 长度 */
public static int size=103;
}
| 18.052632
| 42
| 0.650146
|
43d11f4615730503f0772c0651b11ea47e875c9a
| 1,302
|
import java.util.Scanner;
public class lab11Task05{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Input five numbers");
int[] arr = new int[5];
for(int i = 0; i < arr.length; i++){
arr[i] = keyboard.nextInt();
}
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] < arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
int m = arr.length;
for (int i = 0; i < m-1; i++)
for (int j = 0; j < m-i-1; j++)
if (arr[j] < arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
int o = arr.length;
for (int i = 0; i < o-1; i++)
for (int j = 0; j < o-i-1; j++)
if (arr[j] < arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
int k = arr.length;
for (int i = 0; i < k-1; i++)
for (int j = 0; j < k-i-1; j++)
if (arr[j] < arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
int hm = arr.length;
for (int i=0; i<hm; ++i){
System.out.print(arr[i] + " ");
System.out.println();
}
}
}
| 22.067797
| 46
| 0.430876
|
1adf33c5daa4cbef99677c896bd8f34928e04904
| 423
|
package org.corfudb.runtime.exceptions;
/**
* This Exception is thrown when there is an invalid modification to the layout.
* Example : Manager attempting to set empty layout, sequencer or logunit segments list.
*
* <p>Created by zlokhandwala on 10/12/16.
*/
public class LayoutModificationException extends RuntimeException {
public LayoutModificationException(String message) {
super(message);
}
}
| 28.2
| 88
| 0.749409
|
ff7e85fb9b8a3252aa6b38a0638345123bcb5a84
| 2,665
|
package com.rhod.kalah.logic;
import com.rhod.kalah.models.Player;
/**
* Iterator class which controls the pit iteration over the
* pits, won't land on your opponents pit. The iterator starts
* on the first dropable pit.
*
* Can also interact with current pit.
* @author Rhodri
*
*/
class PitIterator {
int currentPitID;
int stoneCount;
final Board board;
PitIterator(final int startPitID, final Board board) {
this.board = board;
// Since we're using arrays index as our pit id negate by one
final int modifiedStartPit = startPitID - 1;
this.stoneCount = board.removeStones(modifiedStartPit);
this.currentPitID = calcNextPit(modifiedStartPit);
}
private PitIterator(final int pitID, PitIterator other) {
this.currentPitID = pitID;
this.board = other.board;
this.stoneCount = other.stoneCount;
}
/**
* Give a pit id calculate the next pit id.
* @param pitId the given pitID
* @return the calculated pipID.
*/
private int calcNextPit(final int pitId) {
return pitId != Board.KALAH_TWO ? pitId + 1 : 0;
}
/**
* Get the next pit. Skips over the opponents Kalah.
* @return null if we're out of stones otherwise the next pit
*/
public PitIterator next() {
PitIterator ret = null;
if(stoneCount > 0) {
int newPitId = calcNextPit(currentPitID);
if(board.isOpponentKalah(newPitId)) {
newPitId = calcNextPit(newPitId);
}
ret = new PitIterator(newPitId, this);
}
return ret;
}
/**
* Is this pit the players own Kalah?
* @return true if its the players Kalah
*/
public boolean isOwnKalah() {
return Board.getKalah(board.getCurrentPlayer()) == currentPitID;
}
/**
* Drop a stone in the pit
* @info decrements our stone count
*/
public void dropStone() {
board.addStonesToPit(currentPitID, 1);
stoneCount--;
}
/**
* Get the stone count of the pit
* @return the stone count
*/
public Integer getStoneCount() {
return board.getStoneCount(currentPitID);
}
/**
* Does the player own the pit
* @return true if they own the pit
*/
public boolean isOwnPit() {
return (board.getCurrentPlayer() == Player.ONE && currentPitID <= Board.KALAH_ONE)
|| (board.getCurrentPlayer() == Player.TWO && currentPitID > Board.KALAH_ONE && currentPitID <= Board.KALAH_TWO);
}
/**
* Move whatever stone we have in the pit to our Kalah
*/
public void moveStonesToKalah() {
final int stones = board.removeStones(currentPitID);
board.addStonesToKalah(board.getCurrentPlayer(), stones);
}
/**
* Get the current pitID we're iterating over
* @return the current pit id
*/
int getCurrentPitID() {
return currentPitID;
}
}
| 24.227273
| 117
| 0.687054
|
9ecb11ccf7655c43a44e06ba5d335b3721a78ff9
| 1,810
|
package cn.ffast.web.controller.sys;
import cn.ffast.core.annotations.CrudConfig;
import cn.ffast.core.annotations.Logined;
import cn.ffast.core.annotations.Permission;
import cn.ffast.core.vo.ResponseInfo;
import cn.ffast.web.entity.sys.Res;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import cn.ffast.web.service.sys.IResService;
import cn.ffast.core.support.BaseCrudController;
/**
* @description: 系统_资源数据接口
* @copyright:
* @createTime: 2017-09-13 09:14:49
* @author: dzy
* @version: 1.0
*/
@Controller
@RequestMapping("/api/sys/res")
@CrudConfig(updateAllColumn = true, retrievePermission = "")
@Permission(value = "res")
@Logined
public class ResController extends BaseCrudController<Res, IResService, Long> {
private static Logger logger = LoggerFactory.getLogger(ResController.class);
@Resource
private IResService service;
@Override
protected IResService getService() {
return this.service;
}
@Override
protected Logger getLogger() {
return logger;
}
@Override
protected ResponseInfo createBefore(Res m) {
return new ResponseInfo(false).setMessage("暂时关闭该功能!");
}
@Override
protected ResponseInfo deleteBefore(String ids) {
return new ResponseInfo(false).setMessage("暂时关闭该功能!");
}
@Override
protected ResponseInfo updateBefore(Res m) {
return new ResponseInfo(false).setMessage("暂时关闭该功能!");
}
@Override
protected void createAfter(Res m, ResponseInfo result) {
if ("true".equals(getRequestParamString("addBaseCrud")) && m.getResType() == 1) {
service.addBaseCrud(m);
}
}
}
| 25.857143
| 89
| 0.713812
|
cf0a5152e2db591325f5ea58a42a4cdc0a0d6a9f
| 1,858
|
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
* No deletion without permission, or be held responsible to law.
*/
package com.jeesite.modules.cms.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.cms.dao.SiteDao;
import com.jeesite.modules.cms.entity.Site;
import com.jeesite.modules.cms.utils.CmsUtils;
import com.jeesite.modules.file.utils.FileUploadUtils;
/**
* 站点表Service
* @author 长春叭哥、ThinkGem
* @version 2020-7-24
*/
@Service
@Transactional(readOnly = true)
public class SiteService extends CrudService<SiteDao, Site> {
/**
* 获取单条数据
* @param site
* @return
*/
@Override
public Site get(Site site) {
return super.get(site);
}
/**
* 查询分页数据
* @param site 查询条件
* @param site.page 分页对象
* @return
*/
@Override
public Page<Site> findPage(Site site) {
return super.findPage(site);
}
/**
* 保存数据(插入或更新)
* @param site
*/
@Override
@Transactional(readOnly = false)
public void save(Site site) {
super.save(site);
CmsUtils.removeCache("siteList");
// 保存logo
FileUploadUtils.saveFileUpload(site, site.getId(), "site_logo");
}
/**
* 更新状态
* @param site
*/
@Override
@Transactional(readOnly = false)
public void updateStatus(Site site) {
super.updateStatus(site);
}
/**
* 删除数据
* @param site
*/
@Override
@Transactional(readOnly = false)
public void delete(Site site) {
super.delete(site);
}
/**
* 删除站点
* @param site
* @param isRe
*/
@Transactional(readOnly = false)
public void delete(Site site, Boolean isRe) {
site.setStatus(isRe != null && isRe ? Site.STATUS_NORMAL : Site.STATUS_DELETE);
super.delete(site);
CmsUtils.removeCache("siteList");
}
}
| 20.195652
| 81
| 0.698062
|
01f0b3e2ddad49057af22ea171d7cfcf4cb3cd38
| 1,584
|
/**
* 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 camelinaction;
/**
* A bean for transforming CSV to XML in a quick and dirty way.
*
* @version $Revision$
*/
public class OrderCsvToXmlBean {
public String fromCsvToXml(String body) {
StringBuilder sb = new StringBuilder();
sb.append("<order>");
String[] parts = body.split(",");
sb.append("<id>").append(parts[0]).append("/id>");
sb.append("<customerId>").append(parts[1]).append("/customerId>");
sb.append("<date>").append(parts[2]).append("</date>");
sb.append("<item>");
sb.append("<id>").append(parts[3]).append("</id>");
sb.append("<amount>").append(parts[4]).append("</amount>");
sb.append("</itemn>");
sb.append("</order>");
return sb.toString();
}
}
| 36
| 75
| 0.660985
|
b3814a626f2c943fa49d5d3777f97332e5c1ad9a
| 1,640
|
package com.nab.dto;
public class OrderDetailResponseDTO {
private Long orderDetailId;
private int quantity;
private double price;
private String createdBy;
private String modifiedBy;
private String createdDate;
private String modifiedDate;
private String formatDateStr;
private ProductResponseDTO productResp;
public Long getOrderDetailId() {
return orderDetailId;
}
public void setOrderDetailId(Long orderDetailId) {
this.orderDetailId = orderDetailId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getFormatDateStr() {
return formatDateStr;
}
public void setFormatDateStr(String formatDateStr) {
this.formatDateStr = formatDateStr;
}
public ProductResponseDTO getProductResp() {
return productResp;
}
public void setProductResp(ProductResponseDTO productResp) {
this.productResp = productResp;
}
}
| 17.263158
| 61
| 0.748171
|
3c6ef2cf54bea3db006b2a34c5365cfcda9a5c41
| 3,212
|
package com.thebluealliance.androidclient.database.writers;
import com.thebluealliance.androidclient.database.Database;
import com.thebluealliance.androidclient.di.TBAAndroidModule;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module(includes = TBAAndroidModule.class)
public class DatabaseWriterModule {
@Provides @Singleton
public AwardListWriter awardListWriter(Database db) {
return new AwardListWriter(db);
}
@Provides @Singleton
public AwardWriter awardWriter(Database db) {
return new AwardWriter(db);
}
@Provides @Singleton
public DistrictListWriter districtListWriter(Database db) {
return new DistrictListWriter(db);
}
@Provides @Singleton
public DistrictTeamListWriter districtTeamListWriter(Database db) {
return new DistrictTeamListWriter(db);
}
@Provides @Singleton
public DistrictTeamWriter districtTeamWriter(Database db) {
return new DistrictTeamWriter(db);
}
@Provides @Singleton
public DistrictWriter districtWriter(Database db) {
return new DistrictWriter(db);
}
@Provides @Singleton
public EventListWriter eventListWriter(Database db) {
return new EventListWriter(db);
}
@Provides @Singleton
public EventTeamListWriter eventTeamListWriter(Database db) {
return new EventTeamListWriter(db);
}
@Provides @Singleton
public EventTeamWriter eventTeamWriter(Database db) {
return new EventTeamWriter(db);
}
@Provides @Singleton
public EventWriter eventWriter(Database db) {
return new EventWriter(db);
}
@Provides @Singleton
public MatchListWriter matchListWriter(Database db) {
return new MatchListWriter(db);
}
@Provides @Singleton
public MatchWriter matchWriter(Database db) {
return new MatchWriter(db);
}
@Provides @Singleton
public MediaListWriter mediaListWriter(Database db) {
return new MediaListWriter(db);
}
@Provides @Singleton
public MediaWriter mediaWriter(Database db) {
return new MediaWriter(db);
}
@Provides @Singleton
public TeamListWriter teamListWriter(Database db) {
return new TeamListWriter(db);
}
@Provides @Singleton
public TeamWriter teamWriter(Database db) {
return new TeamWriter(db);
}
@Provides @Singleton
public YearsParticipatedWriter yearsParticipatedWriter(Database db, TeamWriter teamWriter) {
return new YearsParticipatedWriter(db, teamWriter);
}
@Provides @Singleton
public EventTeamAndTeamListWriter provideEventTeamAndTeamListWriter(
Database database,
EventTeamListWriter eventTeamListWriter,
TeamListWriter teamListWriter) {
return new EventTeamAndTeamListWriter(database, eventTeamListWriter, teamListWriter);
}
@Provides @Singleton
public EventDetailWriter provideEventDetailWriter(Database db) {
return new EventDetailWriter(db);
}
@Provides @Singleton
public FavoriteCollectionWriter provideFavoriteCollectionWriter(Database db) {
return new FavoriteCollectionWriter(db);
}
}
| 27.452991
| 96
| 0.717621
|
b064d27d2d1ba99d0840c4ca7493184e8e81eaef
| 636
|
package com.twu.biblioteca.commands;
import com.twu.biblioteca.Authenticator;
import com.twu.biblioteca.lib.Command;
import com.twu.biblioteca.models.UserAccount;
/**
* Created by bhartman on 3/5/15.
*/
public class UserInfoCommand implements Command {
public String describe() {
return "Checks-out the selected book";
}
public void run() {
UserAccount currentUser = Authenticator.getInstance().getCurrentLoggedUser();
if (currentUser == null){
System.out.println("You have to login to see your information!");
return;
}
currentUser.printInfo();
}
}
| 25.44
| 85
| 0.668239
|
3573412aae15cc01920d07dfa9959d0d1a80fba1
| 835
|
package idx3d.debug;
import idx3d.idx3d_Light;
import org.jhotdraw.annotation.Nonnull;
public class idx3d_Light_Inspector extends InspectorFrame {
private final static long serialVersionUID = 1L;
public idx3d_Light_Inspector(@Nonnull idx3d_Light l, String id) {
super(l, id);
addEntry(new InspectorFrameEntry(this, "int", "diffuse", "0x" + Integer.toHexString(l.diffuse)));
addEntry(new InspectorFrameEntry(this, "int", "specular", "0x" + Integer.toHexString(l.specular)));
addEntry(new InspectorFrameEntry(this, "int", "highlightSheen", "" + l.highlightSheen));
addEntry(new InspectorFrameEntry(this, "int", "highlightSpread", "" + l.highlightSpread));
addEntry(new InspectorFrameEntry(this, l.v, "v"));
addEntry(new InspectorFrameEntry(this, l.v2, "v2"));
}
}
| 41.75
| 107
| 0.699401
|
bd4b88ebe7b653888ac0271eaf2ee9590611567d
| 760
|
package com.stephenwan.libutfood.model;
import java.util.Arrays;
public class FoodItem {
public FoodItem(String name, FoodItemFlag[] flags, String nutritionLink)
{
this.name = name;
this.flags = flags;
this.nutritionLink = nutritionLink;
}
String name;
String nutritionLink;
FoodItemFlag[] flags;
public String getName()
{
return name;
}
public FoodItemFlag[] getFlags()
{
return flags;
}
public boolean containsFlag(FoodItemFlag flag)
{
for (FoodItemFlag f : flags)
if (f.equals(flag))
return true;
return false;
}
public String getNutritionLink()
{
return nutritionLink;
}
@Override
public String toString() {
return name + " (Flag: " + Arrays.toString(flags) + ", " + nutritionLink + ")";
}
}
| 15.833333
| 81
| 0.681579
|
70ff425fabf5f07694ebf97e63fd7bf63f216496
| 252
|
package com.github.ejahns.model.interfaces.haselement;
import java.util.List;
import com.github.ejahns.model.interfaces.GherkinElement;
public interface HasTags extends GherkinElement {
List<String> getTags();
void setTags(List<String> tags);
}
| 19.384615
| 57
| 0.793651
|
880c9f91e5c7ad1e35791e1a75301e4c781e558e
| 1,485
|
package com.xballoy.aoc.challenge;
import com.xballoy.aoc.AdventOfCodeException;
import com.xballoy.aoc.InputSupplier;
import com.xballoy.aoc.challenge.day5.Seat;
import com.xballoy.aoc.challenge.day5.ToSeat;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Day5 {
private final List<Seat> seats;
public Day5(final InputSupplier inputSupplier) {
final ToSeat toSeat = new ToSeat();
this.seats = inputSupplier.get()
.map(toSeat)
.collect(Collectors.toList());
}
public int part1() {
return seats.stream()
.map(Seat::getId)
.max(Integer::compareTo)
.orElseThrow(() -> new AdventOfCodeException("Unable to find a max"));
}
public int part2() {
int minSeatId = seats.stream()
.map(Seat::getId)
.min(Integer::compareTo)
.orElseThrow(() -> new AdventOfCodeException("Unable to find a min"));
int maxSeatId = seats.stream()
.map(Seat::getId)
.max(Integer::compareTo)
.orElseThrow(() -> new AdventOfCodeException("Unable to find a max"));
final int expectedTotal = IntStream.rangeClosed(minSeatId, maxSeatId)
.reduce(0, Integer::sum);
final Integer currentTotal = seats.stream()
.map(Seat::getId)
.reduce(0, Integer::sum);
return expectedTotal - currentTotal;
}
}
| 29.117647
| 82
| 0.622222
|
225d2149f87c3ff1e9bb73b68de4f8f535b25c88
| 3,023
|
package com.amoy.pod.support.security;
import com.amoy.pod.support.base.Result;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 添加在UsernamePasswordAuthenticationFilter前,提供authentication信息
*
* @author hongjiacan
* @date 2020/6/11
*/
@Component
public class MyAuthenticationFilter extends OncePerRequestFilter {
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");
//获取header中的token信息
String redisKey = request.getHeader(tokenHeader);
if(null == redisKey || !stringRedisTemplate.hasKey(redisKey)){
filterChain.doFilter(request, response);
return;
}
String token = stringRedisTemplate.opsForValue().get(redisKey);
if(!StringUtils.isEmpty(token)){
String username = jwtTokenUtil.getUsernameFromToken(token);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(token, userDetails)){
// 将用户信息存入 authentication,方便后续校验
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// 将 authentication 存入 ThreadLocal,方便后续获取用户信息
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
}
filterChain.doFilter(request, response);
}
}
| 41.986111
| 129
| 0.73437
|
3459b833ceb7cc55559135ebe14b914131291a34
| 1,327
|
package hip.ch3.avro;
import au.com.bytecode.opencsv.CSVParser;
import com.google.common.collect.Lists;
import hip.ch3.avro.gen.Stock;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* IO utilities for {@link hip.ch3.avro.gen.Stock}s.
*/
public class AvroStockUtils {
private static CSVParser parser = new CSVParser();
public static List<Stock> fromCsvFile(File file) throws IOException {
return fromCsvStream(FileUtils.openInputStream(file));
}
public static List<Stock> fromCsvStream(InputStream is) throws IOException {
List<Stock> stocks = Lists.newArrayList();
for(String line: IOUtils.readLines(is)) {
stocks.add(fromCsv(line));
}
is.close();
return stocks;
}
public static Stock fromCsv(String line) throws IOException {
String parts[] = parser.parseLine(line);
Stock stock = new Stock();
stock.setSymbol(parts[0]);
stock.setDate(parts[1]);
stock.setOpen(Double.valueOf(parts[2]));
stock.setHigh(Double.valueOf(parts[3]));
stock.setLow(Double.valueOf(parts[4]));
stock.setClose(Double.valueOf(parts[5]));
stock.setVolume(Integer.valueOf(parts[6]));
stock.setAdjClose(Double.valueOf(parts[7]));
return stock;
}
}
| 26.019608
| 78
| 0.727958
|
734f6b24feb0a58dcf11ffd35e7c0f12ec36a084
| 1,386
|
package dev.emi.trinkets;
import dev.emi.trinkets.api.TrinketsApi;
import dev.emi.trinkets.api.client.TrinketRendererRegistry;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
public class TrinketFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> {
public TrinketFeatureRenderer(FeatureRendererContext<T, M> context) {
super(context);
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
TrinketsApi.getTrinketComponent(entity).ifPresent(component ->
component.forEach((slotReference, stack) ->
TrinketRendererRegistry.getRenderer(stack.getItem()).ifPresent(renderer -> {
matrices.push();
renderer.render(stack, slotReference, this.getContextModel(), matrices, vertexConsumers,
light, entity, limbAngle, limbDistance, tickDelta, animationProgress, headYaw, headPitch);
matrices.pop();
})
)
);
}
}
| 43.3125
| 215
| 0.787157
|
3cffcc058bd413efa2bf6513e60d68874db16f15
| 2,247
|
package org.oddjob.arooa.design.view;
import org.junit.Test;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import org.junit.Assert;
import org.oddjob.arooa.ArooaParseException;
import org.oddjob.arooa.design.SimpleTextAttribute;
import org.oddjob.arooa.design.model.MockDesignInstance;
import org.oddjob.arooa.design.screem.TextField;
import org.oddjob.arooa.parsing.ArooaElement;
public class TextFieldViewTest extends Assert {
private Component view;
class OurInstance extends MockDesignInstance {
ArooaElement element = new ArooaElement("apple");
{
element = element.addAttribute("one", "Partridge");
element = element.addAttribute("one", "Turtle Doves");
}
@Override
public ArooaElement element() {
return element;
}
}
@Test
public void testSimple() {
OurInstance design = new OurInstance();
SimpleTextAttribute attribute = new SimpleTextAttribute("test", design);
TextField textField = new TextField(attribute);
TextFieldView test = new TextFieldView(textField);
JPanel panel = new JPanel();
int nextRow = test.inline(panel, 0, 0, false);
assertEquals(1, nextRow);
assertEquals(2, panel.getComponentCount());
Component c1 = panel.getComponent(0);
Component c2 = panel.getComponent(1);
assertEquals(JLabel.class, c1.getClass());
assertEquals(JTextField.class, c2.getClass());
JLabel label = (JLabel) c1;
JTextField text = (JTextField) c2;
assertEquals("test", label.getText().trim());
assertEquals(Looks.LABEL_SIZE, label.getText().length());
assertEquals("", text.getText());
text.setText("apple");
assertEquals("apple", attribute.attribute());
this.view = panel;
}
public static void main(String args[]) throws ArooaParseException {
TextFieldViewTest test = new TextFieldViewTest();
test.testSimple();
JFrame frame = new JFrame();
frame.getContentPane().add(test.view);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
| 24.966667
| 75
| 0.70316
|
b8ff394109f2961ddfa4c28e4c7526f8faf5da35
| 124
|
package com.cmput301.cia.activities.users;
/**
* Created by Jessica on 2017-12-03.
*/
public class RankingsFragment {
}
| 13.777778
| 42
| 0.717742
|
2cdd69db964c7e8ebc1feea34ae58fb25d50c33c
| 305
|
package Objects;
import java.awt.Color;
public class BackgroundBox {
Color baseColor;
String boxPath;
public BackgroundBox(Color baseColor) {
this.baseColor = baseColor;
}
public void setBoxPath(String path) {
boxPath = path;
}
public Color getBaseColor() {
return baseColor;
}
}
| 13.26087
| 40
| 0.711475
|
d6e48b7c9677e753921a9f6f44e61cee3c96700a
| 3,390
|
package cz.salmelu.edmonds;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A class representing a graph used for edmonds algorithm.
* Also contains private fields for algorithm's markings
* @author salmelu
*/
public class Graph {
private Map<Vertex, Set<Vertex>> vertices;
private Map<Vertex, Boolean> markedVertices;
private Map<Vertex, Map<Vertex,Boolean>> markedEdges;
/**
* Constructs a new empty graph
*/
public Graph() {
vertices = new HashMap<>();
markedVertices = new HashMap<>();
markedEdges = new HashMap<>();
}
/**
* Adds a new vertex
* @param v added vertex
*/
public void addVertex(Vertex v) {
vertices.put(v, new HashSet<>());
}
/**
* Removes Vertex v from the graph
* @param v removed vertex
*/
public void removeVertex(Vertex v) {
if(vertices.containsKey(v)) {
for(Vertex u : vertices.get(v)) {
// Remove from all the neighbours
vertices.get(u).remove(v);
}
// Remove the vertex
vertices.remove(v);
}
}
/**
* Adds a new edge
* @param u first vertex of the edge
* @param v second vertex of the edge
*/
public void addEdge(Vertex u, Vertex v) {
if(!vertices.containsKey(u) || !vertices.containsKey(v)) {
return;
}
vertices.get(u).add(v);
vertices.get(v).add(u);
}
/**
* Removes an edge
* @param u first vertex of the edge
* @param v second vertex of the edge
*/
public void removeEdge(Vertex u, Vertex v) {
if(!vertices.containsKey(u) || !vertices.containsKey(v)) {
return;
}
vertices.get(u).remove(v);
vertices.get(v).remove(u);
}
/**
* Returns a map representing this graph
* @return a map with keys as vertices and values as a sets of neighbours
*/
public Map<Vertex,Set<Vertex>> getVertexMap() {
return vertices;
}
/**
* Checks if a vertex is marked in this graph
* @param v checked vertex
* @return true, if it's marked, false otherwise
*/
public boolean isVertexMarked(Vertex v) {
return (markedVertices.containsKey(v) && markedVertices.get(v) == true);
}
/**
* Sets a marked property of the v
* @param v a vertex
* @param marked a new marked value of vertex
*/
public void setVertexMarked(Vertex v, boolean marked) {
markedVertices.put(v, marked);
}
/**
* Checks, if an edge is marked
* @param v1 first vertex
* @param v2 second vertex
* @return true, if it's matched, false otherwise
*/
public boolean isEdgeMarked(Vertex v1, Vertex v2) {
if(v1.getId().compareTo(v2.getId()) < 0) {
if(!markedEdges.containsKey(v1)) return false;
if(!markedEdges.get(v1).containsKey(v2)) return false;
return markedEdges.get(v1).get(v2);
}
else {
if(!markedEdges.containsKey(v2)) return false;
if(!markedEdges.get(v2).containsKey(v1)) return false;
return markedEdges.get(v2).get(v1);
}
}
/**
* Sets a marked property of the edge
* @param v1 first vertex
* @param v2 second vertex
* @param marked a new marked value of edge
*/
public void setEdgeMarked(Vertex v1, Vertex v2, boolean marked) {
if(v1.getId().compareTo(v2.getId()) < 0) {
if(!markedEdges.containsKey(v1)) {
markedEdges.put(v1, new HashMap<>());
}
markedEdges.get(v1).put(v2, marked);
}
else {
if(!markedEdges.containsKey(v2)) {
markedEdges.put(v2, new HashMap<>());
}
markedEdges.get(v2).put(v1, marked);
}
}
}
| 23.873239
| 74
| 0.659587
|
6b983ab677a546801f0e99395f5b6d9b046b2bd0
| 5,090
|
/*
* Copyright 2018 Organizations participating in ISAAC, ISAAC's KOMET, and SOLOR development include the
US Veterans Health Administration, OSHERA, and the Health Services Platform Consortium..
*
* 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 sh.isaac.api.query.clauses;
import sh.isaac.api.query.properties.StampCoordinateClause;
import java.util.EnumSet;
import java.util.Map;
import java.util.Optional;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import sh.isaac.api.Get;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.collections.NidSet;
import sh.isaac.api.component.concept.ConceptSpecification;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.coordinate.StampCoordinate;
import sh.isaac.api.query.ClauseComputeType;
import sh.isaac.api.query.ClauseSemantic;
import sh.isaac.api.query.LeafClause;
import sh.isaac.api.query.LetItemKey;
import sh.isaac.api.query.Query;
import sh.isaac.api.query.WhereClause;
/**
*
* @author kec
*/
@XmlRootElement
@XmlAccessorType(value = XmlAccessType.NONE)
public class ReferencedComponentIsNotActive extends LeafClause implements StampCoordinateClause {
/**
* the manifold coordinate key.
*/
LetItemKey stampCoordinateKey;
//~--- constructors --------------------------------------------------------
/**
* Instantiates a new component is active clause.
*/
public ReferencedComponentIsNotActive() {
}
/**
* Instantiates a new component is active clause.
*
* @param enclosingQuery the enclosing query
* @param stampCoordinateKey the manifold coordinate key
*/
public ReferencedComponentIsNotActive(Query enclosingQuery, LetItemKey stampCoordinateKey) {
super(enclosingQuery);
this.stampCoordinateKey = stampCoordinateKey;
}
//~--- methods -------------------------------------------------------------
/**
* Compute possible components.
*
* @param incomingPossibleComponents the incoming possible components
* @return the nid set
*/
@Override
public final Map<ConceptSpecification, NidSet> computePossibleComponents(Map<ConceptSpecification, NidSet> incomingPossibleComponents) {
StampCoordinate stampCoordinate = getLetItem(stampCoordinateKey);
NidSet possibleComponents = incomingPossibleComponents.get(getAssemblageForIteration());
for (int nid: possibleComponents.asArray()) {
final Optional<? extends Chronology> chronology
= Get.identifiedObjectService()
.getChronology(nid);
if (chronology.isPresent() && chronology.get() instanceof SemanticChronology) {
SemanticChronology semanticChronology = (SemanticChronology) chronology.get();
Optional<? extends Chronology> referencedComponentChronology
= Get.identifiedObjectService()
.getChronology(semanticChronology.getReferencedComponentNid());
if (referencedComponentChronology.isPresent() &&
!referencedComponentChronology.get()
.isLatestVersionActive(stampCoordinate)) {
possibleComponents.remove(nid);
}
} else {
possibleComponents.remove(nid);
}
}
return incomingPossibleComponents;
}
//~--- get methods ---------------------------------------------------------
/**
* Gets the compute phases.
*
* @return the compute phases
*/
@Override
public EnumSet<ClauseComputeType> getComputePhases() {
return ITERATION;
}
@Override
public ClauseSemantic getClauseSemantic() {
return ClauseSemantic.REFERENCED_COMPONENT_IS_INACTIVE;
}
/**
* Gets the where clause.
*
* @return the where clause
*/
@Override
public WhereClause getWhereClause() {
final WhereClause whereClause = new WhereClause();
whereClause.setSemantic(ClauseSemantic.REFERENCED_COMPONENT_IS_INACTIVE);
return whereClause;
}
@Override
public LetItemKey getStampCoordinateKey() {
return stampCoordinateKey;
}
@Override
public void setStampCoordinateKey(LetItemKey stampCoordinateKey) {
this.stampCoordinateKey = stampCoordinateKey;
}
}
| 34.863014
| 140
| 0.668762
|
c2dababec56350a125a865a71a757644be31786f
| 3,994
|
package net.floodlightcontroller.odin.master;
import java.net.InetAddress;
import java.util.Map;
import java.util.Set;
import net.floodlightcontroller.odin.master.IOdinApplicationInterface;
import net.floodlightcontroller.odin.master.NotificationCallback;
import net.floodlightcontroller.odin.master.OdinClient;
import net.floodlightcontroller.odin.master.OdinEventSubscription;
import net.floodlightcontroller.util.MACAddress;
/**
* Base class for all Odin applications. They are
* expected to run as a thread provided by the master. *
*
* @author Lalith Suresh <suresh.lalith@gmail.com>
*
*/
public abstract class OdinApplication implements Runnable {
private IOdinApplicationInterface odinApplicationInterface;
private String pool;
/**
* Set the OdinMaster to use
*/
final void setOdinInterface (IOdinApplicationInterface om) {
odinApplicationInterface = om;
}
/**
* Sets the pool to use for the application
* @param pool
*/
final void setPool (String pool) {
this.pool = pool;
}
/**
* Needed to wrap OdinApplications into a thread, and is
* implemented by the specific application
*/
public abstract void run();
/**
* VAP-Handoff a client to a new AP. This operation is idempotent.
*
* @param newApIpAddr IPv4 address of new access point
* @param hwAddrSta Ethernet address of STA to be handed off
*/
protected final void handoffClientToAp (MACAddress staHwAddr, InetAddress newApIpAddr) {
odinApplicationInterface.handoffClientToAp(pool, staHwAddr, newApIpAddr);
}
/**
* Get the list of clients currently registered with Odin
*
* @return a map of OdinClient objects keyed by HW Addresses
*/
protected final Set<OdinClient> getClients () {
return odinApplicationInterface.getClients(pool);
}
/**
* Get the OdinClient type from the client's MACAddress
*
* @return a OdinClient instance corresponding to clientHwAddress
*/
protected final OdinClient getClientFromHwAddress (MACAddress clientHwAddress) {
return odinApplicationInterface.getClientFromHwAddress(pool, clientHwAddress);
}
/**
* Retreive RxStats from the agent
*
* @param agentAddr InetAddress of the agent
*
* @return Key-Value entries of each recorded statistic for each client
*/
protected final Map<MACAddress, Map<String, String>> getRxStatsFromAgent (InetAddress agentAddr) {
return odinApplicationInterface.getRxStatsFromAgent(pool, agentAddr);
}
/**
* Get a list of Odin agents from the agent tracker
* @return a map of OdinAgent objects keyed by Ipv4 addresses
*/
protected final Set<InetAddress> getAgents () {
return odinApplicationInterface.getAgentAddrs(pool);
}
/**
* Add a subscription for a particular event defined by oes. cb is
* defines the application specified callback to be invoked during
* notification. If the application plans to delete the subscription,
* later, the onus is upon it to keep track of the subscription
* id for removal later.
*
* @param oes the susbcription
* @param cb the callback
*/
protected final long registerSubscription (OdinEventSubscription oes, NotificationCallback cb){
return odinApplicationInterface.registerSubscription(pool, oes, cb);
}
/**
* Remove a subscription from the list
*
* @param id subscription id to remove
* @return
*/
protected final void unregisterSubscription (long id) {
odinApplicationInterface.unregisterSubscription(pool, id);
}
/**
* Add an SSID to the Odin network.
*
* @param networkName
* @return true if the network could be added, false otherwise
*/
protected final boolean addNetwork (String ssid) {
return odinApplicationInterface.addNetwork(pool, ssid);
}
/**
* Remove an SSID from the Odin network.
*
* @param networkName
* @return true if the network could be removed, false otherwise
*/
protected final boolean removeNetwork (String ssid) {
return odinApplicationInterface.removeNetwork(pool, ssid);
}
}
| 26.805369
| 99
| 0.742614
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.