hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1d2388267ee2778a3f147ad1b8c6ad11731da5 | 4,102 | java | Java | server/src/main/java/com/readytalk/revori/imp/Interval.java | dicej/revori | acf10dcc17a4c1e4deab8e11dfb2a4abbc2235e5 | [
"0BSD"
] | 7 | 2015-02-13T22:07:31.000Z | 2021-04-23T19:11:24.000Z | server/src/main/java/com/readytalk/revori/imp/Interval.java | dicej/revori | acf10dcc17a4c1e4deab8e11dfb2a4abbc2235e5 | [
"0BSD"
] | null | null | null | server/src/main/java/com/readytalk/revori/imp/Interval.java | dicej/revori | acf10dcc17a4c1e4deab8e11dfb2a4abbc2235e5 | [
"0BSD"
] | 1 | 2022-03-27T06:53:45.000Z | 2022-03-27T06:53:45.000Z | 29.3 | 68 | 0.612872 | 12,349 | /* Copyright (c) 2010-2012, Revori Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies. */
package com.readytalk.revori.imp;
import java.util.Comparator;
class Interval {
public enum BoundType {
Inclusive, Exclusive;
static {
Inclusive.opposite = Exclusive;
Exclusive.opposite = Inclusive;
}
public BoundType opposite;
}
public static final Interval Unbounded = new Interval
(Compare.Undefined, Compare.Undefined);
public final Object low;
public final BoundType lowBoundType;
public final Object high;
public final BoundType highBoundType;
public Interval(Object low,
BoundType lowBoundType,
Object high,
BoundType highBoundType)
{
this.low = low;
this.lowBoundType = lowBoundType;
this.high = high;
this.highBoundType = highBoundType;
}
public Interval(Object low,
Object high)
{
this(low, BoundType.Inclusive, high, BoundType.Inclusive);
}
public String toString() {
return "interval[" + low + ":" + lowBoundType
+ " " + high + ":" + highBoundType + "]";
}
public static Interval intersection(Interval left,
Interval right,
Comparator comparator)
{
Object low;
BoundType lowBoundType;
int lowDifference = Compare.compare
(left.low, false, right.low, false, comparator);
if (lowDifference > 0) {
low = left.low;
lowBoundType = left.lowBoundType;
} else if (lowDifference < 0) {
low = right.low;
lowBoundType = right.lowBoundType;
} else {
low = left.low;
lowBoundType = (left.lowBoundType == BoundType.Exclusive
|| right.lowBoundType == BoundType.Exclusive
? BoundType.Exclusive : BoundType.Inclusive);
}
Object high;
BoundType highBoundType;
int highDifference = Compare.compare
(left.high, true, right.high, true, comparator);
if (highDifference > 0) {
high = right.high;
highBoundType = right.highBoundType;
} else if (highDifference < 0) {
high = left.high;
highBoundType = left.highBoundType;
} else {
high = left.high;
highBoundType = (left.highBoundType == BoundType.Exclusive
|| right.highBoundType == BoundType.Exclusive
? BoundType.Exclusive : BoundType.Inclusive);
}
return new Interval(low, lowBoundType, high, highBoundType);
}
public static Interval union(Interval left,
Interval right,
Comparator comparator)
{
Object low;
BoundType lowBoundType;
int lowDifference = Compare.compare
(left.low, false, right.low, false, comparator);
if (lowDifference > 0) {
low = right.low;
lowBoundType = right.lowBoundType;
} else if (lowDifference < 0) {
low = left.low;
lowBoundType = left.lowBoundType;
} else {
low = left.low;
lowBoundType = (left.lowBoundType == BoundType.Inclusive
|| right.lowBoundType == BoundType.Inclusive
? BoundType.Inclusive : BoundType.Exclusive);
}
Object high;
BoundType highBoundType;
int highDifference = Compare.compare
(left.high, true, right.high, true, comparator);
if (highDifference > 0) {
high = left.high;
highBoundType = left.highBoundType;
} else if (highDifference < 0) {
high = right.high;
highBoundType = right.highBoundType;
} else {
high = left.high;
highBoundType = (left.lowBoundType == BoundType.Inclusive
|| right.lowBoundType == BoundType.Inclusive
? BoundType.Inclusive : BoundType.Exclusive);
}
return new Interval(low, lowBoundType, high, highBoundType);
}
}
|
3e1d23a9ef6fb1744e2267653050bff49c0892c1 | 112 | java | Java | app/src/main/java/com/example/androidwearlist/ProgressActivity.java | weizhizhu/AndroidWearList | d0dd9478a0153e8969fee9ce1bab715bfa54959f | [
"Apache-2.0"
] | 1 | 2019-10-24T01:49:17.000Z | 2019-10-24T01:49:17.000Z | app/src/main/java/com/example/androidwearlist/ProgressActivity.java | weizhizhu/AndroidWearList | d0dd9478a0153e8969fee9ce1bab715bfa54959f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/androidwearlist/ProgressActivity.java | weizhizhu/AndroidWearList | d0dd9478a0153e8969fee9ce1bab715bfa54959f | [
"Apache-2.0"
] | null | null | null | 16 | 41 | 0.821429 | 12,350 | package com.example.androidwearlist;
import android.app.Activity;
class ProgressActivity extends Activity {
}
|
3e1d241b3cdfe466d2c5f0dfda2aa78e388ff62a | 2,886 | java | Java | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/harness/shutdown.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | 282 | 2015-01-06T02:30:11.000Z | 2022-03-23T06:40:17.000Z | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/harness/shutdown.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | null | null | null | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/harness/shutdown.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | 163 | 2015-01-07T00:07:53.000Z | 2022-03-07T08:35:03.000Z | 26.477064 | 75 | 0.686071 | 12,351 | /*
Derby - Class org.apache.derbyTesting.functionTests.harness.shutdown
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.derbyTesting.functionTests.harness;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.util.*;
import java.io.*;
import org.apache.derby.tools.JDBCDisplayUtil;
/*
**
** shutdown
**
** force a shutdown after a test complete to guarantee shutdown
** which doesn't always seem to happen with useprocess=false
**
*/
public class shutdown
{
static String shutdownurl;
static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
static String systemHome;
public static void main(String[] args) throws SQLException,
InterruptedException, Exception
{
systemHome = args[0];
shutdownurl = args[1];
try
{
doit();
}
catch(Exception e)
{
System.out.println("Exception in shutdown: " + e);
}
}
public static void doit() throws SQLException,
InterruptedException, Exception
{
Connection conn = null;
boolean finished = false;
Date d = new Date();
Properties sp = System.getProperties();
if (systemHome == null)
{
systemHome = sp.getProperty("user.dir") + File.separatorChar +
"testCSHome";
sp.put("derby.system.home", systemHome);
System.setProperties(sp);
}
boolean useprocess = true;
String up = sp.getProperty("useprocess");
if (up != null && up.equals("false"))
useprocess = false;
PrintStream stdout = System.out;
PrintStream stderr = System.err;
Class<?> clazz = Class.forName(driver);
clazz.getConstructor().newInstance();
try
{
conn = DriverManager.getConnection(shutdownurl);
}
catch (SQLException se)
{
if (se.getSQLState().equals("08006"))
{
// It was already shutdown
//System.out.println("Shutdown with: " + shutdownurl);
}
else
{
System.out.println("shutdown failed for " + shutdownurl);
JDBCDisplayUtil.ShowException(System.out, se);
System.exit(1);
}
}
}
}
|
3e1d2446263defe18f8573391dd4341ce02538af | 1,646 | java | Java | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/alert/sender/EmailSender.java | moutainhigh/x-pipe | 9a205d5622a8e99f3dadfe007a0e5df561914b86 | [
"Apache-2.0"
] | 2 | 2018-02-01T06:30:24.000Z | 2018-02-01T06:33:16.000Z | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/alert/sender/EmailSender.java | humaoyyj/x-pipe | 77fc8eff52f98fb585e98fb22ed9c1b711e90f4f | [
"Apache-2.0"
] | null | null | null | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/alert/sender/EmailSender.java | humaoyyj/x-pipe | 77fc8eff52f98fb585e98fb22ed9c1b711e90f4f | [
"Apache-2.0"
] | 2 | 2018-11-06T06:08:53.000Z | 2021-07-08T09:29:55.000Z | 26.126984 | 88 | 0.670717 | 12,352 | package com.ctrip.xpipe.redis.console.alert.sender;
import com.ctrip.xpipe.api.email.Email;
import com.ctrip.xpipe.api.email.EmailService;
import com.ctrip.xpipe.redis.console.alert.AlertMessageEntity;
import com.ctrip.xpipe.redis.console.config.ConsoleConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author chen.zhu
* <p>
* Oct 18, 2017
*/
@Component(EmailSender.ID)
public class EmailSender extends AbstractSender {
public static final String ID = "com.ctrip.xpipe.console.alert.sender.email.sender";
public static final String CC_ER = "ccers";
@Autowired
private ConsoleConfig consoleConfig;
@Override
public String getId() {
return ID;
}
@Override
public boolean send(AlertMessageEntity message) {
Email email = createEmail(message);
try {
EmailService.DEFAULT.sendEmail(email);
return true;
} catch (Exception e) {
return false;
}
}
private Email createEmail(AlertMessageEntity message) {
Email email = new Email();
email.setSender(consoleConfig.getRedisAlertSenderEmail());
email.setSubject(message.getTitle());
email.setCharset("UTF-8");
List<String> ccers = message.getParam(CC_ER);
if(ccers != null && !ccers.isEmpty()) {
email.setcCers(ccers);
}
email.setRecipients(message.getReceivers());
email.setBodyContent(message.getContent());
email.setEmailType(message.getType());
return email;
}
}
|
3e1d25c02b7aaea13cc9ede31a0710a103d08253 | 3,988 | java | Java | common/src/main/java/com/scottlogic/datahelix/generator/common/util/FlatMappingSpliterator.java | maoo/datahelix-2 | 2f145b077d16472f56e7bc079ac66c69b54383c3 | [
"Apache-2.0"
] | 103 | 2019-07-05T16:45:36.000Z | 2022-02-22T10:49:58.000Z | common/src/main/java/com/scottlogic/datahelix/generator/common/util/FlatMappingSpliterator.java | maoo/datahelix-2 | 2f145b077d16472f56e7bc079ac66c69b54383c3 | [
"Apache-2.0"
] | 512 | 2019-01-23T11:20:14.000Z | 2019-07-02T12:40:31.000Z | common/src/main/java/com/scottlogic/datahelix/generator/common/util/FlatMappingSpliterator.java | maoo/datahelix-2 | 2f145b077d16472f56e7bc079ac66c69b54383c3 | [
"Apache-2.0"
] | 47 | 2019-07-03T10:44:08.000Z | 2022-03-03T14:35:26.000Z | 34.08547 | 168 | 0.634152 | 12,353 | /*
* Copyright 2019 Scott Logic 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.scottlogic.datahelix.generator.common.util;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
//Copied from: Stack Overflow: https://stackoverflow.com/questions/32749148/in-java-how-do-i-efficiently-and-elegantly-stream-a-tree-nodes-descendants/32767282#32767282
//Author: Holger: https://stackoverflow.com/users/2711488/holger
public class FlatMappingSpliterator<E,S> extends Spliterators.AbstractSpliterator<E>
implements Consumer<S> {
static final boolean USE_ORIGINAL_IMPL
= Boolean.getBoolean("stream.flatmap.usestandard");
public static <T,R> Stream<R> flatMap(
Stream<T> in, Function<? super T,? extends Stream<? extends R>> mapper) {
if(USE_ORIGINAL_IMPL)
return in.flatMap(mapper);
Objects.requireNonNull(in);
Objects.requireNonNull(mapper);
return StreamSupport.stream(
new FlatMappingSpliterator<>(sp(in), mapper), in.isParallel()
).onClose(in::close);
}
final Spliterator<S> src;
final Function<? super S, ? extends Stream<? extends E>> f;
Stream<? extends E> currStream;
Spliterator<E> curr;
private FlatMappingSpliterator(
Spliterator<S> src, Function<? super S, ? extends Stream<? extends E>> f) {
// actually, the mapping function can change the size to anything,
// but it seems, with the current stream implementation, we are
// better off with an estimate being wrong by magnitudes than with
// reporting unknown size
super(src.estimateSize()+100, src.characteristics()&ORDERED);
this.src = src;
this.f = f;
}
private void closeCurr() {
try { currStream.close(); } finally { currStream=null; curr=null; }
}
public void accept(S s) {
curr=sp(currStream=f.apply(s));
}
@Override
public boolean tryAdvance(Consumer<? super E> action) {
do {
if(curr!=null) {
if(curr.tryAdvance(action))
return true;
closeCurr();
}
} while(src.tryAdvance(this));
return false;
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
if(curr!=null) {
curr.forEachRemaining(action);
closeCurr();
}
src.forEachRemaining(s->{
try(Stream<? extends E> str=f.apply(s)) {
if(str!=null) str.spliterator().forEachRemaining(action);
}
});
}
@SuppressWarnings("unchecked")
private static <X> Spliterator<X> sp(Stream<? extends X> str) {
return str!=null? ((Stream<X>)str).spliterator(): null;
}
@Override
public Spliterator<E> trySplit() {
Spliterator<S> split = src.trySplit();
if(split==null) {
Spliterator<E> prefix = curr;
while(prefix==null && src.tryAdvance(s->curr=sp(f.apply(s))))
prefix=curr;
curr=null;
return prefix;
}
FlatMappingSpliterator<E,S> prefix=new FlatMappingSpliterator<>(split, f);
if(curr!=null) {
prefix.curr=curr;
curr=null;
}
return prefix;
}
} |
3e1d26f422062c77d243a30a0e4b62837d46aeb8 | 1,722 | java | Java | codes/java/leetcodes/src/main/java/com/hit/basmath/interview/top_interview_questions/medium_collection/others/_621.java | hemanthkodandarama/myleetcode | e13073e7c2ed473a932aae72659066b3e56cfdfd | [
"MIT"
] | 41 | 2018-08-30T02:55:16.000Z | 2022-03-15T01:02:04.000Z | codes/java/leetcodes/src/main/java/com/hit/basmath/interview/top_interview_questions/medium_collection/others/_621.java | hemanthkodandarama/myleetcode | e13073e7c2ed473a932aae72659066b3e56cfdfd | [
"MIT"
] | 1 | 2019-06-27T07:42:12.000Z | 2019-06-28T02:19:59.000Z | codes/java/leetcodes/src/main/java/com/hit/basmath/interview/top_interview_questions/medium_collection/others/_621.java | hemanthkodandarama/myleetcode | e13073e7c2ed473a932aae72659066b3e56cfdfd | [
"MIT"
] | 19 | 2019-06-27T18:29:47.000Z | 2022-02-24T16:25:25.000Z | 36.638298 | 289 | 0.5964 | 12,354 | package com.hit.basmath.interview.top_interview_questions.medium_collection.others;
/**
* 621. Task Scheduler
* <p>
* Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
* <p>
* However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
* <p>
* You need to return the least number of intervals the CPU will take to finish all the given tasks.
* <p>
* Example:
* <p>
* Input: tasks = ["A","A","A","B","B","B"], n = 2
* Output: 8
* Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
* <p>
* Note:
* <p>
* 1. The number of tasks is in the range [1, 10000].
* 2. The integer n is in the range [0, 100].
*/
public class _621 {
public int leastInterval(char[] tasks, int n) {
int[] counter = new int[26];
int max = 0;
int maxCount = 0;
for (char task : tasks) {
counter[task - 'A']++;
if (max == counter[task - 'A']) {
maxCount++;
} else if (max < counter[task - 'A']) {
max = counter[task - 'A'];
maxCount = 1;
}
}
int partCount = max - 1;
int partLength = n - (maxCount - 1);
int emptySlots = partCount * partLength;
int availableTasks = tasks.length - max * maxCount;
int idles = Math.max(0, emptySlots - availableTasks);
return tasks.length + idles;
}
}
|
3e1d2757bcebb54705d28c93ece03afb8e6fa316 | 124 | java | Java | spring-xd-hadoop/src/main/java/org/springframework/xd/integration/hadoop/expression/package-info.java | prismec/spring-xd | 123a943387d25602c3b5aa4e818cdf42260953d5 | [
"Apache-2.0"
] | 332 | 2015-01-03T23:47:23.000Z | 2022-02-06T17:09:21.000Z | spring-xd-hadoop/src/main/java/org/springframework/xd/integration/hadoop/expression/package-info.java | prismec/spring-xd | 123a943387d25602c3b5aa4e818cdf42260953d5 | [
"Apache-2.0"
] | 518 | 2015-01-01T16:41:07.000Z | 2021-06-18T13:47:43.000Z | spring-xd-hadoop/src/main/java/org/springframework/xd/integration/hadoop/expression/package-info.java | prismec/spring-xd | 123a943387d25602c3b5aa4e818cdf42260953d5 | [
"Apache-2.0"
] | 229 | 2015-01-03T23:47:31.000Z | 2022-02-25T06:30:35.000Z | 20.666667 | 61 | 0.782258 | 12,355 | /**
* Package for HDFS Partitioning expression support.
*/
package org.springframework.xd.integration.hadoop.expression;
|
3e1d280b0627581bcdafd2a1a2f530f7200b4fd2 | 173 | java | Java | design-mode/src/main/java/demo_abstractFactory/MaleYellowHuman.java | xinglong-zh/designPatterns | 47d130234d2de7eb411989d17e1a17bb1621ed01 | [
"MIT"
] | null | null | null | design-mode/src/main/java/demo_abstractFactory/MaleYellowHuman.java | xinglong-zh/designPatterns | 47d130234d2de7eb411989d17e1a17bb1621ed01 | [
"MIT"
] | null | null | null | design-mode/src/main/java/demo_abstractFactory/MaleYellowHuman.java | xinglong-zh/designPatterns | 47d130234d2de7eb411989d17e1a17bb1621ed01 | [
"MIT"
] | null | null | null | 19.222222 | 58 | 0.699422 | 12,356 | package demo_abstractFactory;
public class MaleYellowHuman extends AbstractYellowHuman {
@Override
public void getSex() {
System.out.println("男性");
}
}
|
3e1d28372aa3fe06a655e7013a611f0925b2ebc1 | 14,443 | java | Java | app/src/main/java/tfg/uo/lightpen/activities/ActivityPentest.java | jose-r-lopez/LightPen | bd266f8fa9a1a4013464852b4c9b7034ae67c204 | [
"MIT"
] | 1 | 2020-05-22T16:11:15.000Z | 2020-05-22T16:11:15.000Z | app/src/main/java/tfg/uo/lightpen/activities/ActivityPentest.java | jose-r-lopez/LightPen | bd266f8fa9a1a4013464852b4c9b7034ae67c204 | [
"MIT"
] | null | null | null | app/src/main/java/tfg/uo/lightpen/activities/ActivityPentest.java | jose-r-lopez/LightPen | bd266f8fa9a1a4013464852b4c9b7034ae67c204 | [
"MIT"
] | null | null | null | 33.666667 | 105 | 0.605276 | 12,357 | package tfg.uo.lightpen.activities;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.io.File;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import tfg.uo.lightpen.R;
import tfg.uo.lightpen.activities.customElements.activityPentest.CustomPluginArrayAdapter;
import tfg.uo.lightpen.activities.customElements.activityPentest.PluginRow;
import tfg.uo.lightpen.business.impl.pluginSystem.impl.Plugin;
import tfg.uo.lightpen.infrastructure.factories.Factories;
import tfg.uo.lightpen.model.ContextData;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import tfg.uo.lightpen.business.impl.pluginSystem.impl.plugins.errors.Error;
public class ActivityPentest extends BasicActivity {
private ContextData ctxD;
private URL url;
private int pluginsFinished = 0;
private int pluginsStarted = 0;
private static String lastInput = "";
//Ejecucion de analisis
private ConcurrentHashMap<Plugin, ArrayList<Error>>
testResult = new ConcurrentHashMap<>();
final ArrayList<PluginRow> pluginRows = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pentest);
WebView wb = (WebView) findViewById(R.id.pentestLoading);
wb.setWebViewClient(new WebViewClient());
wb.loadUrl("file:///android_asset/loading.gif");
ctxD = new ContextData();
ctxD.setContext(getApplicationContext());
ctxD.setProgressBar((ProgressBar) findViewById(R.id.pentestProgressBar));
//Realizamos la carga de los plugins
ArrayList<Plugin> pluginsReady = Factories
.business
.createPluginFactory()
.createPluginLoader(getContextData())
.pluginLoad();
//Introducimos los plugins cargados en los objetos envoltorio
for (Plugin p : pluginsReady) {
p.setContextData(getContextData());
pluginRows.add(new PluginRow(p));
}
//Obtenemos el objeto listview
ListView lv = (ListView) findViewById(R.id.activityPentest_listPlugin);
lv.setAdapter(new CustomPluginArrayAdapter(this, pluginRows));
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(ActivityPentest.this,
pluginRows.get(position).getPlugin().showName(), Toast.LENGTH_SHORT)
.show();
}
});
final EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
dir.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if(b)
dir.setBackgroundColor(getColorId(R.color.pentest_urlNew));
}
});
if (lastInput != null)
dir.setText(lastInput);
dir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
//if(view.getId()==R.id.pentestEditText_dir) {
//dir.setText("");
//dir.setBackgroundColor(getColorId(R.color.pentest_urlNew));
//}
}
});
ProgressBar pentestProg = (ProgressBar) findViewById(R.id.pentestProgressBar);
pentestProg.setProgress(0);
}
public void startOperation(View view){
ArrayList<Plugin> plugins2Work = new ArrayList<>();
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
validateAddress(view);
ColorDrawable status = (ColorDrawable) dir.getBackground();
for(PluginRow r : pluginRows){
if(r.getChecked() == true)
plugins2Work.add(r.getPlugin());
}
if(plugins2Work.size() > 0
&& status.getColor() == getColorId(R.color.pentest_urlOK)){
LinearLayout pluginsLinear = (LinearLayout) findViewById(R.id.pentestLinearInicioAnalisis);
LinearLayout progresLinear = (LinearLayout) findViewById(R.id.pentestLinearLayoutInProgress);
pluginsLinear.setVisibility(View.INVISIBLE);
progresLinear.setVisibility(View.VISIBLE);
//core.startAnalysis(plugins2Work, "dir", progress);
int maxProgress = 100 / plugins2Work.size();
setPluginsStarted(plugins2Work.size());
for(Plugin p : plugins2Work){
AsyncPluginRunner runner = new AsyncPluginRunner();
runner.setMaxProgress(maxProgress);
runner.setDir(getURL());
runner.setContextData(getContextData());
runner.execute(p);
}
}else
showMessage(getBaseContext(),
getResources().getString(R.string.pentestToast_ZeroPlugins_err)
, Gravity.BOTTOM,getMsgTime());
}
public void updateProgress(int progress){
ProgressBar pentestProg = (ProgressBar) findViewById(R.id.pentestProgressBar);
synchronized (pentestProg) {
pentestProg.setProgress(progress+pentestProg.getProgress());
pluginsFinished++;
if(getPluginsFinished() == getPluginsStarted()){//Se ha terminado el analisis
File f = Factories
.business
.createHtmlBuilderFactory()
.createHtmlBuilder(ctxD, testResult)
.processOutput(url.getHost());//Comienza la escritura de errores
Intent intent = new Intent(this, ActivityPentestView.class);
intent.putExtra("pentest", f );
intent.putExtra("nav", "pentest");
startActivity(intent); //comienza cambio de activity
finish();
}
}
}
public void back(View view){finish();}
@Override
public void onBackPressed() {
if(findViewById(R.id.pentestLinearInicioAnalisis).getVisibility() == View.VISIBLE)
super.onBackPressed();
}
//region Validacion de conexion asincrona
public void validateAddress(View view){
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
lastInput = dir.getText().toString();
if(!dir.getText().toString().equals("")) {
hideKeyboard(this);
AsyncAddressValidation validationTask = new AsyncAddressValidation();
validationTask.execute(validURL(dir.getText().toString()));
}else
showMessage(getBaseContext(),
getResources().getString(R.string.pentestToast_ZeroAddress_err),
Gravity.BOTTOM,getMsgTime());
}
public void addressValidationStatus(boolean cond, String err) {
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
if (cond) {
dir.setBackgroundColor(getColorId(R.color.pentest_urlOK));
url = validURL(dir.getText().toString());
} else {
showMessage(getBaseContext(),
err
, Gravity.BOTTOM,getMsgTime());
dir.setBackgroundColor(getColorId(R.color.pentest_urlError));
}
}
public void TextFieldClicked(View view){
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
if(view.getId()==R.id.pentestEditText_dir) {
dir.setText("");
dir.setBackgroundColor(getColorId(R.color.pentest_urlNew));
}
}
public class AsyncAddressValidation extends AsyncTask<URL, Void, String>{
private static final String TAG = "AsyncAddressValidation";
HttpURLConnection con;
EditText dir;
String err = "";
int timeout;
@Override
protected String doInBackground(URL... url) {
try{
con = (HttpURLConnection) url[0]
.openConnection();
con.setConnectTimeout(timeout);
con.setReadTimeout(timeout);
con.connect();
if (con.getResponseCode() == 200) //codigo correcto
err = "200";
else
throw new HttpRetryException("ResponseCodeException",con.getResponseCode());
}catch (SocketTimeoutException e){
Log.e(TAG, "Validation doInBackgroudn: ", e);
err = getString(R.string.pentestToast_Address_err_timeout);
}catch (UnknownHostException e){
Log.e(TAG, "Validation doInBackgroudn: ", e);
err = getString(R.string.pentestToast_Address_err_host);
}catch (Exception e) {
Log.e(TAG, "Validation doInBackgroudn: ", e);
err = getString(R.string.pentestToast_Address_err);
}
finally {
if(con != null)
con.disconnect();
}
return err;
}
@Override
protected void onPreExecute(){
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
dir.setEnabled(false);
Button validateButton = (Button) findViewById(R.id.pentestButton_validateAddress);
validateButton.setClickable(false);
Button startButton = (Button) findViewById(R.id.pentestButton_Start);
startButton.setClickable(false);
dir = (EditText) findViewById(R.id.pentestEditText_dir);
ProgressBar validation =
(ProgressBar) findViewById(R.id.pentestValidateProgress);
validation.setVisibility(View.VISIBLE);
timeout = Integer.parseInt(Factories
.business
.createConfigReaderFactory()
.createConfigReader()
.run(getApplicationContext(), "validateURL_timeout"));
}
@Override
protected void onPostExecute(String status){
Log.d(TAG, "onPostExecute: Finalizada prueba de conexion");
ProgressBar validation =
(ProgressBar) findViewById(R.id.pentestValidateProgress);
validation.setVisibility(View.INVISIBLE);
Button validateButton = (Button) findViewById(R.id.pentestButton_validateAddress);
Button startButton = (Button) findViewById(R.id.pentestButton_Start);
EditText dir = (EditText) findViewById(R.id.pentestEditText_dir);
dir.setEnabled(true);
validateButton.setClickable(true);
startButton.setClickable(true);
if(status.equals("200"))
addressValidationStatus(true, status);
else
addressValidationStatus(false, status);
}
}
//endregion
//region Ejecucion asincrona de plugins
class AsyncPluginRunner
extends AsyncTask<Plugin, Integer, ArrayList<Error>> {
public final static String TAG = "AsyncPluginRunner";
//region atributos
/**
* Contexto de la aplicación
*/
private ContextData ctxD;
/**
* direccion de analisis
*/
private URL dir;
/**
* maximo progreso adquirible por un plugin
*/
private int maxProgress;
/**
* plugin a ejecutar
*/
private Plugin plugin;
//endregion
@Override
protected ArrayList<Error> doInBackground(Plugin... plugins) {
Log.d(TAG, "doInBackground: Comienza la ejecucion del plugin: "
+plugins[0].showName());
setPlugin(plugins[0]);
getPlugin().setContextData(ctxD);
return getPlugin().run(dir);
}
@Override
protected void onPostExecute(ArrayList<Error> result) {
testResult.put(getPlugin(), result);
updateProgress(getMaxProgress());
}
@Override
protected void onPreExecute() {
setMaxProgress(maxProgress);
}
//region Setter & Getter
public void setDir(URL d){
this.dir = d;
}
public URL getDir(){
return dir;
}
public void setMaxProgress(int p){
this.maxProgress = p;
}
public int getMaxProgress(){
return maxProgress;
}
public void setPlugin(Plugin plugin){
this.plugin = plugin;
}
public Plugin getPlugin(){
return plugin;
}
public void setContextData(ContextData ctxD){
this.ctxD = ctxD;
}
public ContextData getContextData(){
return ctxD;
}
//endregion
}
//endregion
//region Setters & Getters
private void setContextData(ContextData ctxD){
this.ctxD = ctxD;
}
private ContextData getContextData(){
return ctxD;
}
private void setUrl(URL url){
this.url = url;
}
private URL getURL(){
return url;
}
public int getPluginsFinished() {
return pluginsFinished;
}
public void setPluginsFinished(int pluginsFinished) {
this.pluginsFinished = pluginsFinished;
}
public int getPluginsStarted() {
return pluginsStarted;
}
public void setPluginsStarted(int plugins2Work) {
this.pluginsStarted = plugins2Work;
}
//endregion
}
|
3e1d286c9184a8341cb8c14b5ebb277030776b34 | 1,971 | java | Java | src/main/java/com/github/dimzak/neo4jslicer/services/Neo4jService.java | dimzak/neo4j-slicer | 3f35253941fcd38c09c830c175c85ec5789ba84a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/dimzak/neo4jslicer/services/Neo4jService.java | dimzak/neo4j-slicer | 3f35253941fcd38c09c830c175c85ec5789ba84a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/dimzak/neo4jslicer/services/Neo4jService.java | dimzak/neo4j-slicer | 3f35253941fcd38c09c830c175c85ec5789ba84a | [
"Apache-2.0"
] | null | null | null | 28.565217 | 140 | 0.621512 | 12,358 | package com.github.dimzak.neo4jslicer.services;
import com.github.dimzak.neo4jslicer.helpers.MiscHelpers;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.PreDestroy;
/**
* Service for all neo4j related tasks
*/
@Service
public class Neo4jService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**
* Get neo4j driver for a given bolt uri
*
* @param uri
* @return {@link Driver}
*/
public Driver getNeo4jDriver(String uri) {
Driver driver = GraphDatabase.driver(uri);
log.info("Connected to neo4j instance with uri: " + uri);
return driver;
}
public String constructApocExportQuery(String query, String filePath) {
return "CALL apoc.export.cypher.query(\"" + MiscHelpers.escapeDoubleQuotes(query) + "\",\"" + filePath + "\",{format: \"plain\"});";
}
public Session openSession(Driver driver) {
return driver.session();
}
public StatementResult runCommand(Session session, String command) {
StatementResult statementResult = null;
try {
statementResult = session.run(command);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
return statementResult;
}
public void close(Session session, Driver driver) {
try {
if (session != null) {
session.close();
}
if (driver != null) {
driver.close();
}
} catch (Exception e) {
log.error("Exception while closing neo4j connection, trying to close driver one more time");
if (driver != null) {
driver.close();
}
}
}
}
|
3e1d28708a0fa065e14775917372d8ede7d8e147 | 3,338 | java | Java | service/src/main/java/bio/terra/workspace/service/workspace/flight/CreateWorkspaceStep.java | DataBiosphere/terra-workspace-manager | 4d717f6c2b0324263b1d0c79e9c7d4b30ef6f16e | [
"BSD-3-Clause"
] | 8 | 2020-06-04T20:48:19.000Z | 2022-01-12T19:42:31.000Z | service/src/main/java/bio/terra/workspace/service/workspace/flight/CreateWorkspaceStep.java | DataBiosphere/terra-workspace-manager | 4d717f6c2b0324263b1d0c79e9c7d4b30ef6f16e | [
"BSD-3-Clause"
] | 198 | 2020-03-13T18:26:06.000Z | 2022-03-31T22:33:12.000Z | service/src/main/java/bio/terra/workspace/service/workspace/flight/CreateWorkspaceStep.java | DataBiosphere/terra-workspace-manager | 4d717f6c2b0324263b1d0c79e9c7d4b30ef6f16e | [
"BSD-3-Clause"
] | 8 | 2020-05-08T00:03:50.000Z | 2021-09-16T17:57:14.000Z | 39.738095 | 100 | 0.767226 | 12,359 | package bio.terra.workspace.service.workspace.flight;
import bio.terra.stairway.FlightContext;
import bio.terra.stairway.FlightMap;
import bio.terra.stairway.Step;
import bio.terra.stairway.StepResult;
import bio.terra.stairway.exception.RetryException;
import bio.terra.workspace.common.utils.FlightUtils;
import bio.terra.workspace.db.WorkspaceDao;
import bio.terra.workspace.service.spendprofile.SpendProfileId;
import bio.terra.workspace.service.workspace.exceptions.DuplicateWorkspaceException;
import bio.terra.workspace.service.workspace.model.Workspace;
import bio.terra.workspace.service.workspace.model.WorkspaceStage;
import java.util.Optional;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
public class CreateWorkspaceStep implements Step {
private final WorkspaceDao workspaceDao;
private final Logger logger = LoggerFactory.getLogger(CreateWorkspaceStep.class);
public CreateWorkspaceStep(WorkspaceDao workspaceDao) {
this.workspaceDao = workspaceDao;
}
@Override
public StepResult doStep(FlightContext flightContext)
throws RetryException, InterruptedException {
FlightMap inputMap = flightContext.getInputParameters();
UUID workspaceId =
UUID.fromString(inputMap.get(WorkspaceFlightMapKeys.WORKSPACE_ID, String.class));
String spendProfileIdString =
inputMap.get(WorkspaceFlightMapKeys.SPEND_PROFILE_ID, String.class);
SpendProfileId spendProfileId =
Optional.ofNullable(spendProfileIdString).map(SpendProfileId::create).orElse(null);
String displayName = inputMap.get(WorkspaceFlightMapKeys.DISPLAY_NAME, String.class);
String description = inputMap.get(WorkspaceFlightMapKeys.DESCRIPTION, String.class);
WorkspaceStage workspaceStage =
WorkspaceStage.valueOf(inputMap.get(WorkspaceFlightMapKeys.WORKSPACE_STAGE, String.class));
Workspace workspaceToCreate =
Workspace.builder()
.workspaceId(workspaceId)
.spendProfileId(spendProfileId)
.workspaceStage(workspaceStage)
.displayName(displayName)
.description(description)
.build();
try {
workspaceDao.createWorkspace(workspaceToCreate);
} catch (DuplicateWorkspaceException ex) {
// This might be the result of a step re-running, or it might be an ID conflict. We can ignore
// this if the existing workspace matches the one we were about to create, otherwise rethrow.
Workspace existingWorkspace = workspaceDao.getWorkspace(workspaceId);
if (!workspaceToCreate.equals(existingWorkspace)) {
throw ex;
}
}
FlightUtils.setResponse(flightContext, workspaceId, HttpStatus.OK);
logger.info("Workspace created with id {}", workspaceId);
return StepResult.getStepResultSuccess();
}
@Override
public StepResult undoStep(FlightContext flightContext) throws InterruptedException {
FlightMap inputMap = flightContext.getInputParameters();
UUID workspaceId =
UUID.fromString(inputMap.get(WorkspaceFlightMapKeys.WORKSPACE_ID, String.class));
// Ignore return value, as we don't care whether a workspace was deleted or just not found.
workspaceDao.deleteWorkspace(workspaceId);
return StepResult.getStepResultSuccess();
}
}
|
3e1d28ab2fd3e4f621892a58aa5fbbfad996362a | 3,407 | java | Java | open-metadata-implementation/access-services/information-view/information-view-server/src/main/java/org/odpi/openmetadata/accessservices/informationview/lookup/DatabaseLookup.java | bogdansava/egeria-test | 3828aa10a191f27ef0df36fd8a4c6ae0e5b45be8 | [
"Apache-2.0"
] | null | null | null | open-metadata-implementation/access-services/information-view/information-view-server/src/main/java/org/odpi/openmetadata/accessservices/informationview/lookup/DatabaseLookup.java | bogdansava/egeria-test | 3828aa10a191f27ef0df36fd8a4c6ae0e5b45be8 | [
"Apache-2.0"
] | null | null | null | open-metadata-implementation/access-services/information-view/information-view-server/src/main/java/org/odpi/openmetadata/accessservices/informationview/lookup/DatabaseLookup.java | bogdansava/egeria-test | 3828aa10a191f27ef0df36fd8a4c6ae0e5b45be8 | [
"Apache-2.0"
] | null | null | null | 54.079365 | 270 | 0.822131 | 12,360 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.informationview.lookup;
import org.odpi.openmetadata.accessservices.informationview.contentmanager.OMEntityDao;
import org.odpi.openmetadata.accessservices.informationview.events.DatabaseSource;
import org.odpi.openmetadata.accessservices.informationview.utils.Constants;
import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditLog;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.EntityDetail;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceProperties;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryConnector;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.EntityNotKnownException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.FunctionNotSupportedException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.InvalidParameterException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.PagingErrorException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.PropertyErrorException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.RepositoryErrorException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.TypeErrorException;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.UserNotAuthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class DatabaseLookup extends EntityLookup<DatabaseSource> {
private static final Logger log = LoggerFactory.getLogger(DatabaseLookup.class);
public DatabaseLookup(OMRSRepositoryConnector enterpriseConnector, OMEntityDao omEntityDao, EntityLookup parentChain, OMRSAuditLog auditLog) {
super(enterpriseConnector, omEntityDao, parentChain, auditLog);
}
@Override
public EntityDetail lookupEntity(DatabaseSource source) throws UserNotAuthorizedException, FunctionNotSupportedException, InvalidParameterException, RepositoryErrorException, PropertyErrorException, TypeErrorException, PagingErrorException, EntityNotKnownException {
EntityDetail parentEntity = parentChain.lookupEntity(source.getEndpointSource());
if(parentEntity == null)
return null;
List<String> allConnectionGuids = getRelatedEntities(parentEntity.getGUID(), Constants.CONNECTION_TO_ENDPOINT);
List<EntityDetail> allLinkedDatabasesList = getRelatedEntities(allConnectionGuids, Constants.CONNECTION_TO_ASSET);
EntityDetail databaseEntity = lookupEntity(source, allLinkedDatabasesList);
if(log.isDebugEnabled()) {
log.debug("Database found [{}]", databaseEntity);
}
return databaseEntity;
}
@Override
public void setParentChain(EntityLookup parentChain) {
this.parentChain = parentChain;
}
@Override
protected InstanceProperties getMatchingProperties(DatabaseSource source) {
InstanceProperties matchProperties = enterpriseConnector.getRepositoryHelper().addStringPropertyToInstance("", new InstanceProperties(), Constants.NAME, source.getName(), "findDEntity");
return matchProperties;
}
}
|
3e1d293067ae918a000bd72c69823d1c3d9ce10c | 1,815 | java | Java | src/com/serein/extras/fragments/OmniGestureSettings.java | Serein-OS/android_packages_apps_SereinExtras | 8b2d4bbe53f5fae70364f994c51147e313de1809 | [
"Apache-2.0"
] | 1 | 2019-10-22T07:02:41.000Z | 2019-10-22T07:02:41.000Z | src/com/serein/extras/fragments/OmniGestureSettings.java | Ovenoboyo/packages_apps_SereinExtras | a83d7a6372fd82edbf520ee70dd49d2055e7d1f0 | [
"Apache-2.0"
] | null | null | null | src/com/serein/extras/fragments/OmniGestureSettings.java | Ovenoboyo/packages_apps_SereinExtras | a83d7a6372fd82edbf520ee70dd49d2055e7d1f0 | [
"Apache-2.0"
] | 1 | 2018-11-17T04:31:31.000Z | 2018-11-17T04:31:31.000Z | 41.25 | 97 | 0.770248 | 12,361 | /*
* Copyright (C) 2018 The OmniROM Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.serein.extras.fragments;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceScreen;
import android.provider.Settings;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
public class OmniGestureSettings extends SettingsPreferenceFragment {
private static final String TAG = "OmniGestureSettings";
@Override
public int getMetricsCategory() {
return MetricsEvent.SEREINEXTRAS;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.omni_gesture_settings);
mFooterPreferenceMixin.createFooterPreference().setTitle(R.string.gesture_settings_info);
}
@Override
public boolean onPreferenceTreeClick(Preference preference) {
return super.onPreferenceTreeClick(preference);
}
}
|
3e1d2939d32f2c5b9e845abb73de42b96bd62c7b | 337 | java | Java | src/test/java/com/tinmegali/oauth2/Oauth2ApplicationTests.java | tinmegali/Using-Spring-Oauth2-to-secure-REST | b1bf317163aa52f4297ffa591cf473094ec8094d | [
"MIT"
] | 49 | 2017-09-20T10:44:17.000Z | 2020-11-06T23:30:15.000Z | src/test/java/com/tinmegali/oauth2/Oauth2ApplicationTests.java | tinmegali/Using-Spring-Oauth2-to-secure-REST | b1bf317163aa52f4297ffa591cf473094ec8094d | [
"MIT"
] | 1 | 2019-01-04T06:08:23.000Z | 2019-01-04T06:08:23.000Z | src/test/java/com/tinmegali/oauth2/Oauth2ApplicationTests.java | tinmegali/Using-Spring-Oauth2-to-secure-REST | b1bf317163aa52f4297ffa591cf473094ec8094d | [
"MIT"
] | 37 | 2017-06-28T02:07:45.000Z | 2022-01-11T21:48:16.000Z | 19.823529 | 60 | 0.810089 | 12,362 | package com.tinmegali.oauth2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Oauth2ApplicationTests {
@Test
public void contextLoads() {
}
}
|
3e1d293faa50e16efffce433b78b38923b129e73 | 1,128 | java | Java | app/src/main/java/danbuscaglia/googleimagesearch/helpers/ConnectionHelper.java | dbuscaglia/codepath_project_2 | 01b2360303847543eebab3a2bd2dba2112176493 | [
"Apache-2.0"
] | 1 | 2015-09-28T00:57:19.000Z | 2015-09-28T00:57:19.000Z | app/src/main/java/danbuscaglia/googleimagesearch/helpers/ConnectionHelper.java | dbuscaglia/codepath_project_2 | 01b2360303847543eebab3a2bd2dba2112176493 | [
"Apache-2.0"
] | 1 | 2015-09-28T00:02:59.000Z | 2015-09-28T16:49:38.000Z | app/src/main/java/danbuscaglia/googleimagesearch/helpers/ConnectionHelper.java | dbuscaglia/codepath_project_2 | 01b2360303847543eebab3a2bd2dba2112176493 | [
"Apache-2.0"
] | null | null | null | 31.333333 | 109 | 0.737589 | 12,363 | package danbuscaglia.googleimagesearch.helpers;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by danbuscaglia on 9/26/15.
*/
public class ConnectionHelper {
private static final String TAG = "ConnectionHelper";
public static long lastNoConnectionTs = -1;
public static boolean isOnline = true;
public static boolean isConnected(Context context) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnected();
return isConnected;
}
public static boolean isConnectedOrConnecting(Context context) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
} |
3e1d2b4383deec37e8c6e075e7b49963167376bc | 4,272 | java | Java | app/src/main/java/com/rana/movieapp/MainActivity.java | RanaAhmedHamdy/Pop-Movies | b110adc8827bfca4767e4e7c2cc8bc0d135acff1 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rana/movieapp/MainActivity.java | RanaAhmedHamdy/Pop-Movies | b110adc8827bfca4767e4e7c2cc8bc0d135acff1 | [
"Apache-2.0"
] | 1 | 2017-01-25T16:03:34.000Z | 2017-01-25T16:03:34.000Z | app/src/main/java/com/rana/movieapp/MainActivity.java | RanaAhmedHamdy/Pop-Movies | b110adc8827bfca4767e4e7c2cc8bc0d135acff1 | [
"Apache-2.0"
] | null | null | null | 38.836364 | 130 | 0.645365 | 12,364 | package com.rana.movieapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements MainActivityFragment.Callback{
private boolean mTwoPane;
private static final String DETAILFRAGMENT_TAG = "DFTAG";
SharedPreferences sharedpreferences;
private String mSort;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
mSort = sharedpreferences.getString(getString(R.string.pref_key), getString(R.string.pref_default_value));
if (findViewById(R.id.movies_detail_container) != null) {
mTwoPane = true;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.movies_detail_container, new DetailActivityFragment(), DETAILFRAGMENT_TAG)
.commit();
}
} else {
mTwoPane = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(getBaseContext(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(MovieItem item) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle args = new Bundle();
//save details to parcelable so if orientation changes it remain selected
args.putParcelable(getString(R.string.detail_movie), item);
DetailActivityFragment fragment = new DetailActivityFragment();
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.movies_detail_container, fragment, DETAILFRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(getString(R.string.title_extras), item.getOriginalTitle());
intent.putExtra(getString(R.string.date), item.getReleaseDate());
intent.putExtra(getString(R.string.image), item.getImageUrl());
intent.putExtra(getString(R.string.overview), item.getOverView());
intent.putExtra(getString(R.string.vote), item.getVoteAverage());
intent.putExtra(getString(R.string.id), item.getId());
startActivity(intent);
}
}
@Override
protected void onResume() {
super.onResume();
String sort = sharedpreferences.getString(getString(R.string.pref_key), getString(R.string.pref_default_value));
if (sort != null && !sort.equals(mSort)) {
MainActivityFragment ff = (MainActivityFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_movies);
if ( null != ff ) {
ff.onSortChanged();
}
DetailActivityFragment df = (DetailActivityFragment)getSupportFragmentManager().findFragmentByTag(DETAILFRAGMENT_TAG);
if ( null != df ) {
df.onSortingChanged(sort);
}
mSort = sort;
}
}
}
|
3e1d2cb7848828d80e2645a1873373a89be0f238 | 2,938 | java | Java | api/src/main/java/io/opentelemetry/metrics/DoubleUpDownCounter.java | parallelstream/opentelemetry-java | def5a23ca0ee12aa86cd01f34639c46ec38dbe44 | [
"Apache-2.0"
] | null | null | null | api/src/main/java/io/opentelemetry/metrics/DoubleUpDownCounter.java | parallelstream/opentelemetry-java | def5a23ca0ee12aa86cd01f34639c46ec38dbe44 | [
"Apache-2.0"
] | 18 | 2021-03-09T05:57:23.000Z | 2022-03-02T14:06:43.000Z | api/src/main/java/io/opentelemetry/metrics/DoubleUpDownCounter.java | sfriberg/opentelemetry-java | 11f25c50bf20f95c0f097cb96b7e74657bed75e6 | [
"Apache-2.0"
] | null | null | null | 30.604167 | 100 | 0.695371 | 12,365 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.metrics;
import io.opentelemetry.common.Labels;
import io.opentelemetry.metrics.DoubleUpDownCounter.BoundDoubleUpDownCounter;
import javax.annotation.concurrent.ThreadSafe;
/**
* UpDownCounter is a synchronous instrument and very similar to Counter except that Add(increment)
* supports negative increments. This makes UpDownCounter not useful for computing a rate
* aggregation. The default aggregation is `Sum`, only the sum is non-monotonic. It is generally
* useful for capturing changes in an amount of resources used, or any quantity that rises and falls
* during a request.
*
* <p>Example:
*
* <pre>{@code
* class YourClass {
* private static final Meter meter = OpenTelemetry.getMeterProvider().get("my_library_name");
* private static final DoubleUpDownCounter upDownCounter =
* meter.
* .doubleUpDownCounterBuilder("resource_usage")
* .setDescription("Current resource usage")
* .setUnit("1")
* .build();
*
* // It is recommended that the API user keep references to a Bound Counters.
* private static final BoundDoubleUpDownCounter someWorkBound =
* upDownCounter.bind("work_name", "some_work");
*
* void doSomeWork() {
* someWorkBound.add(10.2); // Resources needed for this task.
* // Your code here.
* someWorkBound.add(-10.0);
* }
* }
* }</pre>
*/
@ThreadSafe
public interface DoubleUpDownCounter extends SynchronousInstrument<BoundDoubleUpDownCounter> {
/**
* Adds the given {@code increment} to the current value.
*
* <p>The value added is associated with the current {@code Context} and provided set of labels.
*
* @param increment the value to add.
* @param labels the labels to be associated to this recording.
*/
void add(double increment, Labels labels);
/**
* Adds the given {@code increment} to the current value.
*
* <p>The value added is associated with the current {@code Context} and empty labels.
*
* @param increment the value to add.
*/
void add(double increment);
@Override
BoundDoubleUpDownCounter bind(Labels labels);
/** A {@code Bound Instrument} for a {@link DoubleUpDownCounter}. */
@ThreadSafe
interface BoundDoubleUpDownCounter extends BoundInstrument {
/**
* Adds the given {@code increment} to the current value.
*
* <p>The value added is associated with the current {@code Context}.
*
* @param increment the value to add.
*/
void add(double increment);
@Override
void unbind();
}
/** Builder class for {@link DoubleUpDownCounter}. */
interface Builder extends SynchronousInstrument.Builder {
@Override
Builder setDescription(String description);
@Override
Builder setUnit(String unit);
@Override
DoubleUpDownCounter build();
}
}
|
3e1d2cf3e99d4cf852d5e18a84cad5cd4f3f683d | 1,648 | java | Java | src/main/java/gov/nasa/jpl/mbee/mdk/validation/ValidationRule.java | cgaley-lmco/mdk | 8ad43120ee9ee8caf1f2b55d58036b7e7236adf8 | [
"Apache-2.0"
] | 30 | 2016-12-21T00:55:41.000Z | 2022-02-16T20:39:13.000Z | src/main/java/gov/nasa/jpl/mbee/mdk/validation/ValidationRule.java | cgaley-lmco/mdk | 8ad43120ee9ee8caf1f2b55d58036b7e7236adf8 | [
"Apache-2.0"
] | 47 | 2017-01-01T23:33:17.000Z | 2022-03-15T14:34:16.000Z | src/main/java/gov/nasa/jpl/mbee/mdk/validation/ValidationRule.java | cgaley-lmco/mdk | 8ad43120ee9ee8caf1f2b55d58036b7e7236adf8 | [
"Apache-2.0"
] | 18 | 2017-01-05T02:14:35.000Z | 2022-01-26T06:40:45.000Z | 27.466667 | 99 | 0.682039 | 12,366 | package gov.nasa.jpl.mbee.mdk.validation;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ValidationRule {
private String name;
private ViolationSeverity severity;
private List<ValidationRuleViolation> violations;
private String description;
public ValidationRule(String name, String description, ViolationSeverity severity) {
this.name = name;
this.severity = severity;
this.description = description;
violations = new ArrayList<ValidationRuleViolation>();
}
public ValidationRuleViolation addViolation(ValidationRuleViolation v) {
violations.add(v);
return v;
}
public ValidationRuleViolation addViolation(Element e, String comment) {
return addViolation(e, comment, false);
}
public ValidationRuleViolation addViolation(Element e, String comment, boolean reported) {
return addViolation(new ValidationRuleViolation(e, comment, reported));
}
public List<ValidationRuleViolation> addViolations(Collection<ValidationRuleViolation> viols) {
if (viols != null) {
for (ValidationRuleViolation v : viols) {
addViolation(v);
}
}
return violations;
}
public String getName() {
return name;
}
public ViolationSeverity getSeverity() {
return severity;
}
public List<ValidationRuleViolation> getViolations() {
return violations;
}
public String getDescription() {
return description;
}
}
|
3e1d2d27d9e3f035c2cef392b05ee51f99fddb8e | 935 | java | Java | jOOQ-test/src/org/jooq/test/mysql/generatedclasses/tables/pojos/TBookToBookStore.java | cybernetics/jOOQ | ab29b4a73f5bbe027eeff352be5a75e70db9760a | [
"Apache-2.0"
] | 1 | 2019-04-22T08:49:14.000Z | 2019-04-22T08:49:14.000Z | jOOQ-test/src/org/jooq/test/mysql/generatedclasses/tables/pojos/TBookToBookStore.java | ben-manes/jOOQ | 9f160d5e869de1a9d66408d90718148f76c5e000 | [
"Apache-2.0"
] | null | null | null | jOOQ-test/src/org/jooq/test/mysql/generatedclasses/tables/pojos/TBookToBookStore.java | ben-manes/jOOQ | 9f160d5e869de1a9d66408d90718148f76c5e000 | [
"Apache-2.0"
] | null | null | null | 22.261905 | 63 | 0.736898 | 12,367 | /**
* This class is generated by jOOQ
*/
package org.jooq.test.mysql.generatedclasses.tables.pojos;
/**
* This class is generated by jOOQ.
*
* An m:n relation between books and book stores
*/
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class TBookToBookStore implements java.io.Serializable {
private static final long serialVersionUID = 1008736848;
private final java.lang.String bookStoreName;
private final java.lang.Integer bookId;
private final java.lang.Integer stock;
public TBookToBookStore(
java.lang.String bookStoreName,
java.lang.Integer bookId,
java.lang.Integer stock
) {
this.bookStoreName = bookStoreName;
this.bookId = bookId;
this.stock = stock;
}
public java.lang.String getBookStoreName() {
return this.bookStoreName;
}
public java.lang.Integer getBookId() {
return this.bookId;
}
public java.lang.Integer getStock() {
return this.stock;
}
}
|
3e1d2df3bc6fab377fed8e398edc44f255e4b169 | 2,097 | java | Java | ProjetoHanoi/hanoiEstruturaDeDados/src/hanoiestruturadedados/Logicadojogo.java | brunocimattigiordano/root | 123602fcfcfca0c74ac7bc2987abea809c8189da | [
"CC0-1.0"
] | null | null | null | ProjetoHanoi/hanoiEstruturaDeDados/src/hanoiestruturadedados/Logicadojogo.java | brunocimattigiordano/root | 123602fcfcfca0c74ac7bc2987abea809c8189da | [
"CC0-1.0"
] | null | null | null | ProjetoHanoi/hanoiEstruturaDeDados/src/hanoiestruturadedados/Logicadojogo.java | brunocimattigiordano/root | 123602fcfcfca0c74ac7bc2987abea809c8189da | [
"CC0-1.0"
] | null | null | null | 24.964286 | 95 | 0.60372 | 12,368 | /*
* 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 hanoiestruturadedados;
import java.util.Stack;
/**
*
* @author FATEC
*
*/
public class Logicadojogo {
Stack<Integer> pilhaA = new Stack<>();
Stack<Integer> pilhaB = new Stack<>();
Stack<Integer> pilhaC = new Stack<>();
private int pecanamao=0;
public void novojogo() {
removepecasdapilha(pilhaA);
removepecasdapilha(pilhaB);
removepecasdapilha(pilhaC);
soltapecadamao();
enchepilhadepecas(pilhaA);
}
void removepecasdapilha(Stack<Integer> pilhaatual) {
pilhaatual.clear();
}
public void soltapecadamao(){
pecanamao=0;
}
void enchepilhadepecas(Stack<Integer> pilhaatual) {
for (int i = 4; i > 0; i--) {
pilhaatual.push(i);
}
}
public boolean naotempecanamao(){
return pecanamao==0;
}
public void pegapecadapilha(Stack<Integer> pilhaescolhida){
pecanamao=pilhaescolhida.pop();
}
public boolean pecaatualpodesercolocadanapilhadestino(Stack<Integer>pilhadestino) {
//olha o topo da pilha destino e se for maior que a peca em maos entao podesercolocada
return pilhadestino.peek()>pecanamao;
}
public void poepecanapilha(Stack<Integer> pilhadestino){
pilhadestino.push(pecanamao);
}
int emqualposicaoestaapeca(Stack<Integer> pilhaolhada,int peca){
return pilhaolhada.search(peca);
}
public int getPecanamao(){
return this.pecanamao;
}
public Stack<Integer> getTorreA(){
return this.pilhaA;
}
public Stack<Integer> getTorreB(){
return this.pilhaB;
}
public Stack<Integer> getTorreC(){
return this.pilhaC;
}
public boolean houvevitoria(){
return pilhaC.size()==4;
}
}
|
3e1d2e27a3793dbd1d6c8fee68afa287ae152c34 | 4,945 | java | Java | sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/BackendBaseParameters.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/BackendBaseParameters.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 306 | 2019-09-27T06:41:56.000Z | 2019-10-14T08:19:57.000Z | sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/BackendBaseParameters.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 24.60199 | 139 | 0.632356 | 12,369 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.apimanagement.v2019_12_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Backend entity base Parameter set.
*/
public class BackendBaseParameters {
/**
* Backend Title.
*/
@JsonProperty(value = "title")
private String title;
/**
* Backend Description.
*/
@JsonProperty(value = "description")
private String description;
/**
* Management Uri of the Resource in External System. This url can be the
* Arm Resource Id of Logic Apps, Function Apps or Api Apps.
*/
@JsonProperty(value = "resourceId")
private String resourceId;
/**
* Backend Properties contract.
*/
@JsonProperty(value = "properties")
private BackendProperties properties;
/**
* Backend Credentials Contract Properties.
*/
@JsonProperty(value = "credentials")
private BackendCredentialsContract credentials;
/**
* Backend Proxy Contract Properties.
*/
@JsonProperty(value = "proxy")
private BackendProxyContract proxy;
/**
* Backend TLS Properties.
*/
@JsonProperty(value = "tls")
private BackendTlsProperties tls;
/**
* Get backend Title.
*
* @return the title value
*/
public String title() {
return this.title;
}
/**
* Set backend Title.
*
* @param title the title value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withTitle(String title) {
this.title = title;
return this;
}
/**
* Get backend Description.
*
* @return the description value
*/
public String description() {
return this.description;
}
/**
* Set backend Description.
*
* @param description the description value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withDescription(String description) {
this.description = description;
return this;
}
/**
* Get management Uri of the Resource in External System. This url can be the Arm Resource Id of Logic Apps, Function Apps or Api Apps.
*
* @return the resourceId value
*/
public String resourceId() {
return this.resourceId;
}
/**
* Set management Uri of the Resource in External System. This url can be the Arm Resource Id of Logic Apps, Function Apps or Api Apps.
*
* @param resourceId the resourceId value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withResourceId(String resourceId) {
this.resourceId = resourceId;
return this;
}
/**
* Get backend Properties contract.
*
* @return the properties value
*/
public BackendProperties properties() {
return this.properties;
}
/**
* Set backend Properties contract.
*
* @param properties the properties value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withProperties(BackendProperties properties) {
this.properties = properties;
return this;
}
/**
* Get backend Credentials Contract Properties.
*
* @return the credentials value
*/
public BackendCredentialsContract credentials() {
return this.credentials;
}
/**
* Set backend Credentials Contract Properties.
*
* @param credentials the credentials value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withCredentials(BackendCredentialsContract credentials) {
this.credentials = credentials;
return this;
}
/**
* Get backend Proxy Contract Properties.
*
* @return the proxy value
*/
public BackendProxyContract proxy() {
return this.proxy;
}
/**
* Set backend Proxy Contract Properties.
*
* @param proxy the proxy value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withProxy(BackendProxyContract proxy) {
this.proxy = proxy;
return this;
}
/**
* Get backend TLS Properties.
*
* @return the tls value
*/
public BackendTlsProperties tls() {
return this.tls;
}
/**
* Set backend TLS Properties.
*
* @param tls the tls value to set
* @return the BackendBaseParameters object itself.
*/
public BackendBaseParameters withTls(BackendTlsProperties tls) {
this.tls = tls;
return this;
}
}
|
3e1d2e553e5f15ef4d2aa76b3cc5000f1fe7d954 | 288 | java | Java | src/main/java/org/javacore/pattern/template/WebpImageLoader.java | jackznq/java-core-learning-example | 496d2c45ce49b1dd04a7be413fe19083ecd5ebc6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/javacore/pattern/template/WebpImageLoader.java | jackznq/java-core-learning-example | 496d2c45ce49b1dd04a7be413fe19083ecd5ebc6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/javacore/pattern/template/WebpImageLoader.java | jackznq/java-core-learning-example | 496d2c45ce49b1dd04a7be413fe19083ecd5ebc6 | [
"Apache-2.0"
] | null | null | null | 32 | 95 | 0.722222 | 12,370 | package org.javacore.pattern.template;
public class WebpImageLoader extends AbstractImageLoader {
@Override
protected String getUrl(String imageUrl, int width, int height) {
return String.format("%s?imageView2/1/w/%d/h/%d/format/webp", imageUrl, width, height);
}
}
|
3e1d2ee6f44a72f11b1abc5d40fd604f2ea42259 | 2,357 | java | Java | mall-coupon/src/main/java/com/huabin/mall/coupon/controller/SeckillPromotionController.java | huabin123/mall | c3e31ddaab0f765340a4e76b29acba3030283278 | [
"Apache-2.0"
] | 1 | 2022-02-24T02:47:56.000Z | 2022-02-24T02:47:56.000Z | mall-coupon/src/main/java/com/huabin/mall/coupon/controller/SeckillPromotionController.java | huabin123/mall | c3e31ddaab0f765340a4e76b29acba3030283278 | [
"Apache-2.0"
] | null | null | null | mall-coupon/src/main/java/com/huabin/mall/coupon/controller/SeckillPromotionController.java | huabin123/mall | c3e31ddaab0f765340a4e76b29acba3030283278 | [
"Apache-2.0"
] | null | null | null | 26.233333 | 80 | 0.715375 | 12,371 | package com.huabin.mall.coupon.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.huabin.mall.coupon.entity.SeckillPromotionEntity;
import com.huabin.mall.coupon.service.SeckillPromotionService;
import com.huabin.common.utils.PageUtils;
import com.huabin.common.utils.R;
/**
* 秒杀活动
*
* @author huabin
* @email envkt@example.com
* @date 2021-12-31 08:40:29
*/
@RestController
@RequestMapping("coupon/seckillpromotion")
public class SeckillPromotionController {
@Autowired
private SeckillPromotionService seckillPromotionService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("coupon:seckillpromotion:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = seckillPromotionService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("coupon:seckillpromotion:info")
public R info(@PathVariable("id") Long id){
SeckillPromotionEntity seckillPromotion = seckillPromotionService.getById(id);
return R.ok().put("seckillPromotion", seckillPromotion);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("coupon:seckillpromotion:save")
public R save(@RequestBody SeckillPromotionEntity seckillPromotion){
seckillPromotionService.save(seckillPromotion);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("coupon:seckillpromotion:update")
public R update(@RequestBody SeckillPromotionEntity seckillPromotion){
seckillPromotionService.updateById(seckillPromotion);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("coupon:seckillpromotion:delete")
public R delete(@RequestBody Long[] ids){
seckillPromotionService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
3e1d2f3f03058a0b1d79c0b6b12c75cee085dbf0 | 1,803 | java | Java | src/main/java/com/nikichxp/util/Ret.java | NikichXP/LibPack | 4247a9c0df038a6c0e782ae70c59921f5c50f080 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/nikichxp/util/Ret.java | NikichXP/LibPack | 4247a9c0df038a6c0e782ae70c59921f5c50f080 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/nikichxp/util/Ret.java | NikichXP/LibPack | 4247a9c0df038a6c0e782ae70c59921f5c50f080 | [
"Apache-2.0"
] | null | null | null | 25.394366 | 89 | 0.642818 | 12,372 | package com.nikichxp.util;
import com.google.gson.Gson;
import org.springframework.http.ResponseEntity;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Ret {
public static ResponseEntity stMap (int code, Object... args) {
return ResponseEntity.status(code).body(map(args));
}
public static ResponseEntity okMap (Object... args) {
return ResponseEntity.ok(map(args));
}
public static Map<Object, Object> map (Object... args) {
HashMap<Object, Object> ret = new HashMap<>();
for (int i = 0; i < args.length; i += 2) {
ret.put(args[i], args[i + 1]);
}
return ret;
}
public static Map<String, Object> st (Object... args) {
HashMap<String, Object> ret = new HashMap<>();
if (args.length == 1) {
ret.put("status", args[0]);
} else {
ret.put("status", new Gson().toJson(args));
}
return ret;
}
public static ResponseEntity ok (Object... args) {
return Ret.code(200, args);
}
/**
* If 1 arg - {'status':'args[0]'}, else - map {arg[0]:arg[1],...}
*/
public static ResponseEntity code (int code, Object... args) {
if (args.length == 1) {
return ResponseEntity.status(code).body(Ret.st(args));
} else {
return ResponseEntity.status(code).body(map(args));
}
}
@SuppressWarnings ("unchecked")
public static ResponseEntity notNull (Collection... args) {
if (args == null || args.length == 0) {
return code(402, "status", new Object[]{});
}
if (Arrays.stream(args).map(Collection::size).max(Integer::compareTo).orElse(0) == 0) {
return code(402, "status", new Object[]{});
}
for (int i = 1; i < args.length; i++) {
args[0].addAll(args[i]);
}
return ResponseEntity.ok(args[0]);
}
// public static ResponseEntity notNull (Object... args) {
// }
}
|
3e1d2fd47c241aa2896ec1c7a01bfddd5ef6cb3a | 4,240 | java | Java | Android Ejercicios/ToDoAnimation/app/src/main/java/edu/programacion/tododialogos/SettingsActivity.java | AdrianLozano96/Android-RecyclerView | 9ac8fa66ee27dd02706a5226992186e17e8fee60 | [
"MIT"
] | null | null | null | Android Ejercicios/ToDoAnimation/app/src/main/java/edu/programacion/tododialogos/SettingsActivity.java | AdrianLozano96/Android-RecyclerView | 9ac8fa66ee27dd02706a5226992186e17e8fee60 | [
"MIT"
] | null | null | null | Android Ejercicios/ToDoAnimation/app/src/main/java/edu/programacion/tododialogos/SettingsActivity.java | AdrianLozano96/Android-RecyclerView | 9ac8fa66ee27dd02706a5226992186e17e8fee60 | [
"MIT"
] | null | null | null | 35.333333 | 110 | 0.602594 | 12,373 | package edu.programacion.tododialogos;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class SettingsActivity extends AppCompatActivity {
//variables
private SharedPreferences mPrefes; // para leer datos guardados en disco
private SharedPreferences.Editor mEditor; // para escribir datos en las shared
private boolean mSonido; //para activar / desactivar el sonido
public static final int RAPIDO = 0; //animaciones rapida
public static final int LENTO = 1; // animaciones lentas
public static final int NADA= 2; // sin animaciones
int mAnimacion; //para cambiar el tipo de animacion en la APP
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//inicializamos las Share preferences
mPrefes = getSharedPreferences("ToDo APP", MODE_PRIVATE);
mEditor = mPrefes.edit(); //formato editable
//logica de activar y desactivar sonido
mSonido = mPrefes.getBoolean("sonido",true); // recoger valor del disco, si no hay dato asignamos true
CheckBox checkBoxSonido = findViewById(R.id.sonido_checkbox);
//visualizamos la opcion que estaba grabada
if (mSonido){
checkBoxSonido.setChecked(true); //usuario quiere musica
} else{
checkBoxSonido.setChecked(false);
}
//para comprobar si el usuario cambia de opinion
checkBoxSonido.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// si el sonido estaba en marcha lo apagamos
// si el sonido estaba apagado lo ponemos en marcha
mSonido = ! mSonido;
mEditor.putBoolean("sonido", mSonido); //guardamos los datos en disco
mEditor.commit();
}
});
// logica de la animacion
mAnimacion = mPrefes.getInt("anim opcion", RAPIDO); //recoger dato en disco
RadioGroup radioGroup = findViewById(R.id.radio_animacion);
radioGroup.clearCheck(); //desseleccionar cualquier radio button
//en funcion de la preferencia del jugador, seleccionar una de las 3 modos de animacion
switch ( mAnimacion){
case RAPIDO:
radioGroup.check(R.id.rb_fast);
break;
case LENTO:
radioGroup.check(R.id.rb_slow);
break;
case NADA:
radioGroup.check(R.id.rb_none);
break;
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
//recuperamos el radio button que ha sido seleccionado por el usuario a traves del chceckedId
RadioButton rb = radioGroup.findViewById(checkedId);
//int id = checkedId;
if(null != rb && checkedId >-1){
switch (rb.getId()){
case R.id.rb_fast:
mAnimacion = RAPIDO;
break;
case R.id.rb_slow:
mAnimacion = LENTO;
break;
case R.id.rb_none:
mAnimacion = NADA;
break;
}
mEditor.putInt("anim opcion",mAnimacion);
mEditor.commit();
}
}
});
}
// vamos utilizar este metodo para escribir las Share preferentes
// ya que nos interesa que se grabe cuando mos movemos de la actividad
// comentamos mEditor.commit()
@Override
protected void onPause() {
super.onPause();
mEditor.commit();
}
} |
3e1d3085c1fccd12f0c50cd7f215cd2055566466 | 2,090 | java | Java | src/main/java/org/shieldproject/rocketmq/factory/MQClientFactory.java | EightMonth/rocketmq-spring-boot-starter | fd9dfc018ac2bb12e1c57235f75ad8f7c066dcdf | [
"Apache-2.0"
] | 17 | 2018-08-22T03:13:10.000Z | 2019-09-02T01:58:09.000Z | src/main/java/org/shieldproject/rocketmq/factory/MQClientFactory.java | AlittleBitch/spring-boot-starter-rocketmq | 89db92dec004080b53f6cc7bc87c58a4aebb0486 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/shieldproject/rocketmq/factory/MQClientFactory.java | AlittleBitch/spring-boot-starter-rocketmq | 89db92dec004080b53f6cc7bc87c58a4aebb0486 | [
"Apache-2.0"
] | 10 | 2018-08-24T02:11:04.000Z | 2021-08-14T08:48:24.000Z | 41.8 | 184 | 0.748804 | 12,374 | package org.shieldproject.rocketmq.factory;
import org.shieldproject.rocketmq.annotation.RocketMQListener;
import org.shieldproject.rocketmq.config.ConsumerProperties;
import org.shieldproject.rocketmq.exception.InstanceAlreadyRegistryException;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author ShawnShoper
* @date 2018/8/30 16:58
*/
public class MQClientFactory {
//instance id for key,DefaultMQPushConsumer for value
protected static Map<String, MQConsumer> mqClients = new ConcurrentHashMap<>();
public static MQConsumer registry(String instanceId, ClientConfig clientConfig, ConsumerProperties consumerProperties, RocketMQListener rocketMQListener) throws MQClientException {
if (Objects.isNull(instanceId) || instanceId.trim().isEmpty())
throw new NullPointerException("instanceId can not be null or empty.");
if (mqClients.containsKey(instanceId))
throw new InstanceAlreadyRegistryException("Instance " + instanceId + " is already reigstry,please check out and change the other one");
MQConsumer defaultMQPushConsumer = MQConsumer.custom().config(clientConfig, consumerProperties, rocketMQListener);
mqClients.putIfAbsent(instanceId, defaultMQPushConsumer);
return defaultMQPushConsumer;
}
protected static void destory(String instanceId) {
if (Objects.isNull(instanceId) || instanceId.trim().isEmpty())
throw new NullPointerException("instanceId can not be null or empty.");
if (!mqClients.containsKey(instanceId))
throw new RuntimeException("InstanceId:" + instanceId + " has not created");
MQConsumer defaultMQPushConsumer = mqClients.get(instanceId);
if (Objects.nonNull(defaultMQPushConsumer))
defaultMQPushConsumer.shutdown();
}
public static void destoryAll() {
mqClients.keySet().forEach(MQClientFactory::destory);
}
}
|
3e1d312bf3edf2530283220c275a6b1a21d86f38 | 2,294 | java | Java | app/src/main/java/net/ilexiconn/magister/adapter/SubjectAdapter.java | UnderKoen/Magis | edaccb0048f1e4e1c011697609e299d0a7e89814 | [
"Apache-2.0"
] | 14 | 2016-05-13T06:08:01.000Z | 2021-12-09T17:13:42.000Z | app/src/main/java/net/ilexiconn/magister/adapter/SubjectAdapter.java | UnderKoen/Magis | edaccb0048f1e4e1c011697609e299d0a7e89814 | [
"Apache-2.0"
] | 43 | 2016-05-14T21:32:23.000Z | 2019-04-28T16:24:15.000Z | app/src/main/java/net/ilexiconn/magister/adapter/SubjectAdapter.java | UnderKoen/Magis | edaccb0048f1e4e1c011697609e299d0a7e89814 | [
"Apache-2.0"
] | 11 | 2016-05-27T17:37:32.000Z | 2019-02-04T21:19:34.000Z | 36.412698 | 87 | 0.716216 | 12,375 | /*
* Copyright 2016 Bas van den Boom 'Z3r0byte'
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.ilexiconn.magister.adapter;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.ilexiconn.magister.container.Subject;
import net.ilexiconn.magister.util.DateUtil;
import net.ilexiconn.magister.util.GsonUtil;
import net.ilexiconn.magister.util.LogUtil;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class SubjectAdapter extends TypeAdapter<Subject[]> {
public Gson gson = GsonUtil.getGson();
@Override
public void write(JsonWriter out, Subject[] value) throws IOException {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public Subject[] read(JsonReader in) throws IOException {
JsonArray array = gson.getAdapter(JsonElement.class).read(in).getAsJsonArray();
List<Subject> subjectList = new ArrayList<Subject>();
for (JsonElement element : array) {
JsonObject object = element.getAsJsonObject();
Subject subject = gson.fromJson(object, Subject.class);
try {
subject.startDate = DateUtil.stringToDate(subject.startDateString);
subject.endDate = DateUtil.stringToDate(subject.endDateString);
} catch (ParseException e) {
LogUtil.printError("Unable to parse date", e);
}
subjectList.add(subject);
}
return subjectList.toArray(new Subject[subjectList.size()]);
}
}
|
3e1d3189d2c00e3e7d7a8a3d4073e862727b2139 | 3,090 | java | Java | kernel/impl/fabric3-system/src/main/java/org/fabric3/implementation/system/runtime/SystemTargetWireAttacher.java | chrisphe/fabric3-core | 3a29d2cb19fcce33678e3f81f3f7c09271ca7b84 | [
"Apache-2.0"
] | null | null | null | kernel/impl/fabric3-system/src/main/java/org/fabric3/implementation/system/runtime/SystemTargetWireAttacher.java | chrisphe/fabric3-core | 3a29d2cb19fcce33678e3f81f3f7c09271ca7b84 | [
"Apache-2.0"
] | null | null | null | kernel/impl/fabric3-system/src/main/java/org/fabric3/implementation/system/runtime/SystemTargetWireAttacher.java | chrisphe/fabric3-core | 3a29d2cb19fcce33678e3f81f3f7c09271ca7b84 | [
"Apache-2.0"
] | null | null | null | 39.615385 | 118 | 0.744013 | 12,376 | /*
* Fabric3
* Copyright (c) 2009-2015 Metaform Systems
*
* 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.
*
* Portions originally based on Apache Tuscany 2007
* licensed under the Apache 2.0 license.
*/
package org.fabric3.implementation.system.runtime;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.List;
import java.util.function.Supplier;
import org.fabric3.api.host.Fabric3Exception;
import org.fabric3.implementation.system.provision.SystemWireTarget;
import org.fabric3.spi.container.builder.TargetWireAttacher;
import org.fabric3.spi.container.component.ComponentManager;
import org.fabric3.spi.container.wire.InvocationChain;
import org.fabric3.spi.container.wire.Wire;
import org.fabric3.spi.model.physical.PhysicalOperation;
import org.fabric3.spi.model.physical.PhysicalWireSource;
import org.fabric3.spi.util.UriHelper;
import org.oasisopen.sca.annotation.EagerInit;
import org.oasisopen.sca.annotation.Reference;
/**
*
*/
@EagerInit
public class SystemTargetWireAttacher implements TargetWireAttacher<SystemWireTarget> {
private final ComponentManager manager;
public SystemTargetWireAttacher(@Reference ComponentManager manager) {
this.manager = manager;
}
public void attach(PhysicalWireSource source, SystemWireTarget target, Wire wire) throws Fabric3Exception {
URI targetId = UriHelper.getDefragmentedName(target.getUri());
SystemComponent targetComponent = (SystemComponent) manager.getComponent(targetId);
Class<?> implementationClass = targetComponent.getImplementationClass();
for (InvocationChain chain : wire.getInvocationChains()) {
PhysicalOperation operation = chain.getPhysicalOperation();
List<Class<?>> params = operation.getSourceParameterTypes();
Method method;
try {
method = implementationClass.getMethod(operation.getName(), params.toArray(new Class[params.size()]));
} catch (NoSuchMethodException e) {
throw new Fabric3Exception("No matching method found", e);
}
SystemInvokerInterceptor interceptor = new SystemInvokerInterceptor(method, targetComponent);
chain.addInterceptor(interceptor);
}
}
public Supplier<?> createSupplier(SystemWireTarget target) throws Fabric3Exception {
URI targetId = UriHelper.getDefragmentedName(target.getUri());
SystemComponent targetComponent = (SystemComponent) manager.getComponent(targetId);
return targetComponent.createSupplier();
}
} |
3e1d3215affe4bb5ec0425d7bdac2067f90be2d1 | 134 | java | Java | app/src/main/java/com/zuolg/fairytaleworld/model/SettingsModule.java | zuolg/FairytaleWorld | 68e30862614187a87d2d657b51b7476e4a27ea48 | [
"Apache-2.0"
] | 1 | 2019-07-02T02:20:27.000Z | 2019-07-02T02:20:27.000Z | app/src/main/java/com/zuolg/fairytaleworld/model/SettingsModule.java | zuolg/FairytaleWorld | 68e30862614187a87d2d657b51b7476e4a27ea48 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zuolg/fairytaleworld/model/SettingsModule.java | zuolg/FairytaleWorld | 68e30862614187a87d2d657b51b7476e4a27ea48 | [
"Apache-2.0"
] | 1 | 2019-07-02T02:20:28.000Z | 2019-07-02T02:20:28.000Z | 11.166667 | 39 | 0.574627 | 12,377 | package com.zuolg.fairytaleworld.model;
public class SettingsModule {
/**
* 加载
*/
public void onLoad() {
}
}
|
3e1d330fb15fbd11ca134fc9aeb54e34d354e475 | 486 | java | Java | src/main/java/com/paulmethfessel/bp/ProbeIConfigurable.java | Paulpanther/intellij-babylonian-plugin | 978cba16290ff95b7cf93b563211373877b66bdc | [
"MIT"
] | 3 | 2021-07-15T21:25:55.000Z | 2021-07-17T06:42:44.000Z | src/main/java/com/paulmethfessel/bp/ProbeIConfigurable.java | Paulpanther/intellij-babylonian-plugin | 978cba16290ff95b7cf93b563211373877b66bdc | [
"MIT"
] | 49 | 2021-06-25T14:40:40.000Z | 2022-03-31T09:17:55.000Z | src/main/java/com/paulmethfessel/bp/ProbeIConfigurable.java | Paulpanther/intellij-babylonian-plugin | 978cba16290ff95b7cf93b563211373877b66bdc | [
"MIT"
] | null | null | null | 28.588235 | 66 | 0.816872 | 12,378 | package com.paulmethfessel.bp;
import com.intellij.codeInsight.hints.ChangeListener;
import com.intellij.codeInsight.hints.ImmediateConfigurable;
import com.paulmethfessel.bp.ide.decorators.JavaPanelHelper;
import javax.swing.*;
/**
* ImmediateConfigurable cannot be extended in Kotlin for jvm 1.8
*/
public class ProbeIConfigurable implements ImmediateConfigurable {
public JComponent createComponent(ChangeListener listener) {
return new JavaPanelHelper().createPanel();
}
}
|
3e1d3338575993369ddf996ddc2c74dacdd8f570 | 686 | java | Java | gulimall-coupon/src/main/java/com/wwb/gulimall/coupon/entity/HomeSubjectSpuEntity.java | canghaibanxia/gulimall | 82e721871bf39a42f97531fdb2f78e1891f03cda | [
"Apache-2.0"
] | null | null | null | gulimall-coupon/src/main/java/com/wwb/gulimall/coupon/entity/HomeSubjectSpuEntity.java | canghaibanxia/gulimall | 82e721871bf39a42f97531fdb2f78e1891f03cda | [
"Apache-2.0"
] | null | null | null | gulimall-coupon/src/main/java/com/wwb/gulimall/coupon/entity/HomeSubjectSpuEntity.java | canghaibanxia/gulimall | 82e721871bf39a42f97531fdb2f78e1891f03cda | [
"Apache-2.0"
] | null | null | null | 15.288889 | 59 | 0.693314 | 12,379 | package com.wwb.gulimall.coupon.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 专题商品
*
* @author weiweibin
* @email efpyi@example.com
* @date 2020-06-29 14:55:34
*/
@Data
@TableName("sms_home_subject_spu")
public class HomeSubjectSpuEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 专题名字
*/
private String name;
/**
* 专题id
*/
private Long subjectId;
/**
* spu_id
*/
private Long spuId;
/**
* 排序
*/
private Integer sort;
}
|
3e1d3349142853c6efe5f16b58084b346b457f40 | 1,150 | java | Java | socket/netty/src/main/java/com/github/wugenshui/socket/netty/thirdexample/MyChatClient.java | wugenshui/demo-springboot | c665e3b317936a19a9782d31eb63113fafaa0116 | [
"MIT"
] | null | null | null | socket/netty/src/main/java/com/github/wugenshui/socket/netty/thirdexample/MyChatClient.java | wugenshui/demo-springboot | c665e3b317936a19a9782d31eb63113fafaa0116 | [
"MIT"
] | 1 | 2022-02-16T01:16:07.000Z | 2022-02-16T01:16:07.000Z | socket/netty/src/main/java/com/github/wugenshui/socket/netty/thirdexample/MyChatClient.java | wugenshui/demo-springboot | c665e3b317936a19a9782d31eb63113fafaa0116 | [
"MIT"
] | null | null | null | 30.263158 | 97 | 0.656522 | 12,380 | package com.github.wugenshui.socket.netty.thirdexample;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* @author : chenbo
* @date : 2020-03-19
*/
public class MyChatClient {
public static void main(String[] args) throws Exception {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new MyChatClientInitializer());
Channel channel = bootstrap.connect("localhost", 8899).sync().channel();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
for (; ; ) {
channel.writeAndFlush(bufferedReader.readLine() + "\r\n");
}
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
|
3e1d33c4b08494e382eca08b193179d0d61e324a | 2,376 | java | Java | jans-orm/couchbase-sample/src/main/java/io/jans/orm/couchbase/CouchbaseUpdateAttributeSample.java | duttarnab/jans | b4ae02f9cb60433a44a2b889268525532d82a247 | [
"Apache-2.0"
] | 18 | 2022-01-13T13:45:13.000Z | 2022-03-30T04:41:18.000Z | jans-orm/couchbase-sample/src/main/java/io/jans/orm/couchbase/CouchbaseUpdateAttributeSample.java | duttarnab/jans | b4ae02f9cb60433a44a2b889268525532d82a247 | [
"Apache-2.0"
] | 604 | 2022-01-13T12:32:50.000Z | 2022-03-31T20:27:36.000Z | jans-orm/couchbase-sample/src/main/java/io/jans/orm/couchbase/CouchbaseUpdateAttributeSample.java | duttarnab/jans | b4ae02f9cb60433a44a2b889268525532d82a247 | [
"Apache-2.0"
] | 8 | 2022-01-28T00:23:25.000Z | 2022-03-16T05:12:12.000Z | 35.462687 | 124 | 0.744529 | 12,381 | /*
* Janssen Project software is available under the Apache License (2004). See http://www.apache.org/licenses/ for full text.
*
* Copyright (c) 2020, Janssen Project
*/
package io.jans.orm.couchbase;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.jans.orm.couchbase.impl.CouchbaseEntryManager;
import io.jans.orm.couchbase.model.SimpleUser;
import io.jans.orm.couchbase.operation.impl.CouchbaseConnectionProvider;
import io.jans.orm.model.base.CustomAttribute;
import io.jans.orm.model.base.CustomEntry;
/**
* @author Yuriy Movchan Date: 11/03/2016
*/
public final class CouchbaseUpdateAttributeSample {
private static final Logger LOG = LoggerFactory.getLogger(CouchbaseConnectionProvider.class);
private CouchbaseUpdateAttributeSample() {
}
public static void main(String[] args) {
// Prepare sample connection details
CouchbaseEntryManagerSample couchbaseEntryManagerSample = new CouchbaseEntryManagerSample();
// Create Couchbase entry manager
CouchbaseEntryManager couchbaseEntryManager = couchbaseEntryManagerSample.createCouchbaseEntryManager();
String uid = "sample_user_" + System.currentTimeMillis();
String dn = String.format("inum=%s,ou=people,o=jans", System.currentTimeMillis());
SimpleUser newUser = new SimpleUser();
newUser.setDn(dn);
newUser.setUserId(uid);
newUser.setUserPassword("test");
couchbaseEntryManager.persist(newUser);
SimpleUser user = couchbaseEntryManager.find(SimpleUser.class, dn);
LOG.info("Found user '{}'", user);
CustomEntry customEntry = new CustomEntry();
customEntry.setDn(user.getDn());
customEntry.setCustomObjectClasses(new String[] { "jansPerson" });
Date now = new GregorianCalendar(TimeZone.getTimeZone("UTC")).getTime();
String nowDateString = couchbaseEntryManager.encodeTime(customEntry.getDn(), now);
CustomAttribute customAttribute = new CustomAttribute("jansLastLogonTime", nowDateString);
customEntry.getCustomAttributes().add(customAttribute);
couchbaseEntryManager.merge(customEntry);
SimpleUser userAfterUpdate = couchbaseEntryManager.find(SimpleUser.class, dn);
LOG.info("Found user after update '{}'", userAfterUpdate);
}
}
|
3e1d340908defc7bceb38aa7b4ec754b7650f3bb | 493 | java | Java | src/main/java/strategy1/businessEntity/StepGrowth.java | yafeng520/Binance_Futures_Java | 086615185a330816b9151746a86cad87da2a39b4 | [
"Apache-2.0"
] | null | null | null | src/main/java/strategy1/businessEntity/StepGrowth.java | yafeng520/Binance_Futures_Java | 086615185a330816b9151746a86cad87da2a39b4 | [
"Apache-2.0"
] | null | null | null | src/main/java/strategy1/businessEntity/StepGrowth.java | yafeng520/Binance_Futures_Java | 086615185a330816b9151746a86cad87da2a39b4 | [
"Apache-2.0"
] | null | null | null | 21.434783 | 57 | 0.68357 | 12,383 | package strategy1.businessEntity;
public class StepGrowth {
private float stepGrowthRate;//当前价格相比前一个价格的增长率
private float quantity;//当前价格成交的数量
public float getStepGrowthRate() {
return stepGrowthRate;
}
public void setStepGrowthRate(float stepGrowthRate) {
this.stepGrowthRate = stepGrowthRate;
}
public float getQuantity() {
return quantity;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
}
|
3e1d3537eb81b2b4d30c3e294a2fb9ca6efff147 | 2,395 | java | Java | src/main/java/com/google/testing/testify/risk/frontend/model/DataRequestOption.java | CharlesHamel/google-test-analytics | 6cd8d2377bb94569fab2c55d410deb33d79124f8 | [
"Apache-2.0"
] | 31 | 2015-01-16T00:13:17.000Z | 2022-03-16T09:50:06.000Z | src/main/java/com/google/testing/testify/risk/frontend/model/DataRequestOption.java | Angela-shi/google-test-analytics | 2b3150cb49fc236d0f06395976af17089ef8ec95 | [
"Apache-2.0"
] | 3 | 2015-03-29T16:54:01.000Z | 2020-08-13T10:47:34.000Z | src/main/java/com/google/testing/testify/risk/frontend/model/DataRequestOption.java | Angela-shi/google-test-analytics | 2b3150cb49fc236d0f06395976af17089ef8ec95 | [
"Apache-2.0"
] | 25 | 2015-07-30T19:41:30.000Z | 2020-11-09T08:04:36.000Z | 23.93 | 93 | 0.714584 | 12,384 | // Copyright 2011 Google Inc. All Rights Reseved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.testing.testify.risk.frontend.model;
import java.io.Serializable;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
/**
* An individual configuration option for a data request. For example, this is an example of
* a data request option for a Bug
*
* name = "ComponentPath"
* value = "\Testing\Tools\Test Analytics"
*
* This would import any bug under that component path.
*
* or
*
* name = "Hotlist"
* value = "123123"
*
* This would import the bugs in hotlist 123123.
*
* @author anpch@example.com (Jim Reardon)
*/
@PersistenceCapable(detachable = "true")
public class DataRequestOption implements Serializable {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private String id;
@Persistent
private String name;
@Persistent
private String value;
@Persistent
private DataRequest dataRequest;
public DataRequestOption() {
}
public DataRequestOption(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public DataRequest getDataRequest() {
return dataRequest;
}
public void setDataRequest(DataRequest dataRequest) {
this.dataRequest = dataRequest;
}
}
|
3e1d3778d58c0a9fcacaeab222660bf9c7e21a90 | 357 | java | Java | mdm-repository-businessone/src/main/java/com/avatech/edi/mdm/businessone/masterdata/B1BusinessMaterialService.java | okzhangyu/mdm.application | b5ab8168c2d2e5d927dce9c1be7bbdb986bc05ce | [
"Apache-2.0"
] | null | null | null | mdm-repository-businessone/src/main/java/com/avatech/edi/mdm/businessone/masterdata/B1BusinessMaterialService.java | okzhangyu/mdm.application | b5ab8168c2d2e5d927dce9c1be7bbdb986bc05ce | [
"Apache-2.0"
] | null | null | null | mdm-repository-businessone/src/main/java/com/avatech/edi/mdm/businessone/masterdata/B1BusinessMaterialService.java | okzhangyu/mdm.application | b5ab8168c2d2e5d927dce9c1be7bbdb986bc05ce | [
"Apache-2.0"
] | 2 | 2019-10-11T09:00:28.000Z | 2019-10-11T09:00:36.000Z | 29.75 | 97 | 0.820728 | 12,385 | package com.avatech.edi.mdm.businessone.masterdata;
import com.avatech.edi.mdm.bo.Material;
import com.avatech.edi.mdm.config.B1Connection;
import com.avatech.edi.mdm.config.DataTemple;
import java.util.List;
public interface B1BusinessMaterialService {
String syncMaterial(B1Connection connection, Material material, List<DataTemple>dataTemples);
}
|
3e1d37a933fb5a17652d78bee231d3d71f83ac0a | 1,239 | java | Java | java-demo/src/main/java/com/example/Thread/JoinTest/App2.java | huruiyi/Java201808 | a9f00e6f129aace29a50db4ba2da1e736372fa94 | [
"Apache-2.0"
] | 1 | 2020-09-27T02:40:43.000Z | 2020-09-27T02:40:43.000Z | java-demo/src/main/java/com/example/Thread/JoinTest/App2.java | huruiyi/Java201808 | a9f00e6f129aace29a50db4ba2da1e736372fa94 | [
"Apache-2.0"
] | 8 | 2020-07-15T08:52:04.000Z | 2022-01-22T09:42:48.000Z | java-demo/src/main/java/com/example/Thread/JoinTest/App2.java | huruiyi/spring-samples | ed729af789519d53e29b0596902b80c75d21c161 | [
"Apache-2.0"
] | null | null | null | 24.78 | 82 | 0.436642 | 12,386 | package com.example.Thread.JoinTest;
public class App2 {
public static void main(String[] args) {
test1();
}
private static void test0() {
JoinThread t1 = new JoinThread();
JoinThread t2 = new JoinThread();
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {
System.out.println(e.getMessage());
}
for (int i = 0; i < 100; i++) {
System.out.println("main --" + i);
}
}
private static void test1() {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getId() + "--" + i);
}
}
};
Thread t1 = new Thread(runnable, "t1");
Thread t2 = new Thread(runnable, "t2");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {
System.out.println(e.getMessage());
}
for (int i = 0; i < 100; i++) {
System.out.println("main --" + i);
}
}
}
|
3e1d37daeea380fdc8fa839377a5da03fe13772f | 903 | java | Java | extensions/security/deployment/src/main/java/io/quarkus/security/deployment/BouncyCastleJsseProviderBuildItem.java | sgregoire/quarkus | 5d77d270c81160f4ea88043efcae87e7c725d916 | [
"Apache-2.0"
] | 10,225 | 2019-03-07T11:55:54.000Z | 2022-03-31T21:16:53.000Z | extensions/security/deployment/src/main/java/io/quarkus/security/deployment/BouncyCastleJsseProviderBuildItem.java | sgregoire/quarkus | 5d77d270c81160f4ea88043efcae87e7c725d916 | [
"Apache-2.0"
] | 18,675 | 2019-03-07T11:56:33.000Z | 2022-03-31T22:25:22.000Z | extensions/security/deployment/src/main/java/io/quarkus/security/deployment/BouncyCastleJsseProviderBuildItem.java | sgregoire/quarkus | 5d77d270c81160f4ea88043efcae87e7c725d916 | [
"Apache-2.0"
] | 2,190 | 2019-03-07T12:07:18.000Z | 2022-03-30T05:41:35.000Z | 24.405405 | 87 | 0.666667 | 12,387 | package io.quarkus.security.deployment;
import java.util.Objects;
import io.quarkus.builder.item.MultiBuildItem;
public final class BouncyCastleJsseProviderBuildItem extends MultiBuildItem {
private final boolean inFipsMode;
public BouncyCastleJsseProviderBuildItem() {
this(false);
}
public BouncyCastleJsseProviderBuildItem(boolean inFipsMode) {
this.inFipsMode = inFipsMode;
}
public boolean isInFipsMode() {
return inFipsMode;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BouncyCastleJsseProviderBuildItem that = (BouncyCastleJsseProviderBuildItem) o;
return inFipsMode == that.inFipsMode;
}
@Override
public int hashCode() {
return Objects.hash(inFipsMode);
}
}
|
3e1d3a410c1ed186047603e74ae78eaf1f9fe0b5 | 7,121 | java | Java | java-ca-lib/src/test/java/io/github/olivierlemasle/tests/it/WindowsIT.java | olivierlemasle/java-certificate-authority | b129d41f885cb81e87116614b991295c93e33c88 | [
"Apache-2.0"
] | 42 | 2015-03-15T15:00:27.000Z | 2022-02-17T08:15:53.000Z | java-ca-lib/src/test/java/io/github/olivierlemasle/tests/it/WindowsIT.java | olivierlemasle/java-certificate-authority | b129d41f885cb81e87116614b991295c93e33c88 | [
"Apache-2.0"
] | 1 | 2016-06-04T03:21:35.000Z | 2017-09-29T04:38:08.000Z | java-ca-lib/src/test/java/io/github/olivierlemasle/tests/it/WindowsIT.java | olivierlemasle/java-certificate-authority | b129d41f885cb81e87116614b991295c93e33c88 | [
"Apache-2.0"
] | 40 | 2016-09-11T11:18:34.000Z | 2022-03-17T04:09:09.000Z | 35.078818 | 98 | 0.701446 | 12,388 | package io.github.olivierlemasle.tests.it;
import static io.github.olivierlemasle.ca.CA.createSelfSignedCertificate;
import static io.github.olivierlemasle.ca.CA.dn;
import static io.github.olivierlemasle.ca.CA.loadCsr;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import io.github.olivierlemasle.ca.CSR;
import io.github.olivierlemasle.ca.Certificate;
import io.github.olivierlemasle.ca.DistinguishedName;
import io.github.olivierlemasle.ca.RootCertificate;
public class WindowsIT {
@BeforeClass
@AfterClass
public static void clean() {
final File caCertPath = new File("ca.cer");
caCertPath.delete();
final File reqPath = new File("cert.req");
reqPath.delete();
final File certPath = new File("cert.cer");
certPath.delete();
}
@Before
public void checkPlatform() {
assumeTrue(TestUtils.isWindows());
assumeTrue(TestUtils.isWindowsAdministrator());
}
@Test
public void completeTest() throws IOException, InterruptedException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException, CertificateException {
// Create a self-signed root certificate
System.out.println("Generate ..");
final DistinguishedName rootDn = dn("CN=CA-Test");
final RootCertificate root = createSelfSignedCertificate(rootDn).build();
// Export the root certificate
root.save("ca.cer");
System.out.println("CA ready. CA certificate saved to \"ca.cer\".");
// Generate CSR using Windows utilities
System.out.println("Generate CSR with \"cert.req\"...");
generateCsr();
// Load the generated CSR, sign it and export the resulting certificate
System.out.println("Sign CSR...");
final CSR csr = loadCsr("cert.req").getCsr();
final Certificate cert = root.signCsr(csr)
.setRandomSerialNumber()
.sign();
cert.save("cert.cer");
System.out.println("CSR signed. Certificate saved to \"cert.cer\".");
// On Windows, install the CA certificate as a trusted certificate
System.out.println("Install \"ca.cer\" as a trusted certificate authority.");
installTrustedCaCert();
// On Windows, install the "cert.cer" certificate, with its private key
System.out.println("Install \"cert.cer\" from the CSR (with private key).");
acceptCert();
// Configure SSL
System.out.println("Configure SSL");
final String certThumbprint = getThumbPrint(cert.getX509Certificate());
configureSsl(certThumbprint, UUID.randomUUID().toString());
// NB: https binding has been set in appveyor.yml
// Add the CA certificate to a truststore
final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, null);
keystore.setCertificateEntry("cert", root.getX509Certificate());
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(keystore, null).build();
// Test the HTTPS connection
System.out.println("Test https://localhost/");
try (CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://localhost/"))) {
final HttpEntity entity = response.getEntity();
final String content = EntityUtils.toString(entity);
assertTrue(content.contains("<title>IIS Windows Server</title>"));
}
}
/**
* {@code certutil -enterprise -addstore ROOT ca.cer}
*
* @throws IOException
* @throws InterruptedException
*/
private void installTrustedCaCert() throws IOException, InterruptedException {
final Process process = new ProcessBuilder("certutil", "-enterprise", "-addstore", "ROOT",
"ca.cer")
.redirectError(Redirect.INHERIT)
.redirectOutput(Redirect.INHERIT)
.start();
process.waitFor();
}
/**
* {@code certreq -new src\test\resources\csr_template.inf cert.req}
*
* @throws IOException
* @throws InterruptedException
*/
private void generateCsr() throws IOException, InterruptedException {
final Process process = new ProcessBuilder("certreq", "-new",
"src\\test\\resources\\csr_template.inf", "cert.req")
.redirectError(Redirect.INHERIT)
.redirectOutput(Redirect.INHERIT)
.start();
process.waitFor();
}
/**
* {@code certreq -accept cert.cer}
*
* @throws IOException
* @throws InterruptedException
*/
private void acceptCert() throws IOException, InterruptedException {
final Process process = new ProcessBuilder("certreq", "-accept", "cert.cer")
.redirectError(Redirect.INHERIT)
.redirectOutput(Redirect.INHERIT)
.start();
process.waitFor();
}
/**
* {@code netsh http add sslcert ipport=0.0.0.0:443 certhash=... appid=...}
*
* @param certHash
* @param appId
* @throws IOException
* @throws InterruptedException
*/
private void configureSsl(final String certHash, final String appId) throws IOException,
InterruptedException {
final String certhashParam = "certhash=" + certHash;
final String appidParam = "appid={" + appId + "}";
final Process process = new ProcessBuilder("netsh", "http", "add", "sslcert",
"ipport=0.0.0.0:443", "certstorename=MY", certhashParam, appidParam)
.redirectError(Redirect.INHERIT)
.redirectOutput(Redirect.INHERIT)
.start();
process.waitFor();
}
private static String getThumbPrint(final X509Certificate cert) throws NoSuchAlgorithmException,
CertificateEncodingException {
final MessageDigest md = MessageDigest.getInstance("SHA-1");
final byte[] der = cert.getEncoded();
md.update(der);
final byte[] digest = md.digest();
return hexify(digest);
}
private static String hexify(final byte bytes[]) {
final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f' };
final StringBuilder buf = new StringBuilder(bytes.length * 2);
for (final byte b : bytes) {
buf.append(hexDigits[(b & 0xf0) >> 4]);
buf.append(hexDigits[b & 0x0f]);
}
return buf.toString();
}
}
|
3e1d3a910709fc0e31660e810e079994dd2497c8 | 188 | java | Java | auto-value-utils/src/annotations/java/com/slimgears/util/autovalue/annotations/HasSelf.java | ymesika/utils | 2286fb0582b400d1abfd9ba1e93b641c9b67464b | [
"MIT"
] | 1 | 2020-04-27T15:24:39.000Z | 2020-04-27T15:24:39.000Z | auto-value-utils/src/annotations/java/com/slimgears/util/autovalue/annotations/HasSelf.java | ymesika/utils | 2286fb0582b400d1abfd9ba1e93b641c9b67464b | [
"MIT"
] | null | null | null | auto-value-utils/src/annotations/java/com/slimgears/util/autovalue/annotations/HasSelf.java | ymesika/utils | 2286fb0582b400d1abfd9ba1e93b641c9b67464b | [
"MIT"
] | 3 | 2019-06-04T10:50:19.000Z | 2020-02-12T12:05:38.000Z | 20.888889 | 49 | 0.664894 | 12,389 | package com.slimgears.util.autovalue.annotations;
public interface HasSelf<B extends HasSelf<B>> {
default B self() {
//noinspection unchecked
return (B)this;
}
}
|
3e1d3ab0c7a409c8c062db0d3a9af0f40b52df44 | 3,962 | java | Java | src/main/java/de/xxschrandxx/wsc/bukkit/handler/permission/LuckPermsPermissionHandler.java | xXSchrandXx/WSC-Minecraft-Bridge | 23f9bceaf2930d8bfcff2a52df90e73062c2bb74 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/xxschrandxx/wsc/bukkit/handler/permission/LuckPermsPermissionHandler.java | xXSchrandXx/WSC-Minecraft-Bridge | 23f9bceaf2930d8bfcff2a52df90e73062c2bb74 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/xxschrandxx/wsc/bukkit/handler/permission/LuckPermsPermissionHandler.java | xXSchrandXx/WSC-Minecraft-Bridge | 23f9bceaf2930d8bfcff2a52df90e73062c2bb74 | [
"Apache-2.0"
] | null | null | null | 40.020202 | 93 | 0.614336 | 12,390 | package de.xxschrandxx.wsc.bukkit.handler.permission;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.logging.Logger;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.sun.net.httpserver.HttpExchange;
import de.xxschrandxx.wsc.bukkit.MinecraftBridgeBukkit;
import de.xxschrandxx.wsc.core.permission.LuckPermsMethods;
import de.xxschrandxx.wsc.core.permission.PermissionMethodEnum;
import net.luckperms.api.LuckPermsProvider;
public class LuckPermsPermissionHandler extends LuckPermsMethods {
private final PermissionMethodEnum method;
public LuckPermsPermissionHandler(PermissionMethodEnum method) {
super(LuckPermsProvider.get());
this.method = method;
}
@Override
protected Logger getLogger() {
return MinecraftBridgeBukkit.getInstance().getLogger();
}
@Override
protected HashMap<String, Object> run(HttpExchange exchange) {
HashMap<String, Object> response = new HashMap<String, Object>();
try {
if (method == PermissionMethodEnum.status) {
if (exchange.getRequestMethod().equalsIgnoreCase("get")) {
return status();
}
}
else if (method == PermissionMethodEnum.groupList) {
if (exchange.getRequestMethod().equalsIgnoreCase("get")) {
return groupList();
}
}
else if (method == PermissionMethodEnum.getUserGroups) {
if (exchange.getRequestMethod().equalsIgnoreCase("post")) {
return getUserGroups(readRequestBodyString(exchange));
}
}
else if (method == PermissionMethodEnum.getUsersGroups) {
if (exchange.getRequestMethod().equalsIgnoreCase("post")) {
return getUsersGroups(readRequestBodyListString(exchange));
}
}
else if (method == PermissionMethodEnum.addUserToGroup) {
if (exchange.getRequestMethod().equalsIgnoreCase("post")) {
return addUserToGroup(readRequestBodyString(exchange));
}
}
else if (method == PermissionMethodEnum.addUsersToGroups) {
if (exchange.getRequestMethod().equalsIgnoreCase("post")) {
return addUsersToGroups(readRequestBodyStringListStrings(exchange));
}
}
else if (method == PermissionMethodEnum.removeUserFromGroup) {
if (exchange.getRequestMethod().equalsIgnoreCase("post")) {
return removeUserFromGroup(readRequestBodyString(exchange));
}
}
else if (method == PermissionMethodEnum.removeUsersFromGroups) {
if (exchange.getRequestMethod().equalsIgnoreCase("post")) {
return removeUsersFromGroups(readRequestBodyStringListStrings(exchange));
}
}
else {
return this.notFound;
}
}
catch (IOException e) {
response.put("status", "Could not read request body.");
response.put("statusCode", HttpURLConnection.HTTP_INTERNAL_ERROR);
return response;
}
catch (JsonSyntaxException e) {
response.put("status", "Malformed JSON element.");
response.put("statusCode", HttpURLConnection.HTTP_BAD_REQUEST);
return response;
}
catch (JsonParseException e) {
response.put("status", "Could parse JSON.");
response.put("statusCode", HttpURLConnection.HTTP_BAD_REQUEST);
return response;
}
response.put("status", "Method Not Allowed.");
response.put("statusCode", HttpURLConnection.HTTP_BAD_METHOD);
return response;
}
}
|
3e1d3b7d3a657564d8e6b03145d55ceb5a086e45 | 805 | java | Java | src/main/java/com/bdoemu/core/network/sendable/SMChangeAwakenSkill.java | SilenceSu/S7Server491 | 5646a1f43d9b6383403bae2fd2fce811cad0adae | [
"Apache-2.0"
] | 7 | 2019-04-20T06:08:38.000Z | 2021-06-27T09:18:55.000Z | src/main/java/com/bdoemu/core/network/sendable/SMChangeAwakenSkill.java | SilenceSu/S7Server491 | 5646a1f43d9b6383403bae2fd2fce811cad0adae | [
"Apache-2.0"
] | 1 | 2019-06-29T17:58:36.000Z | 2019-06-30T08:58:36.000Z | src/main/java/com/bdoemu/core/network/sendable/SMChangeAwakenSkill.java | jessefjxm/S7Server491 | 5646a1f43d9b6383403bae2fd2fce811cad0adae | [
"Apache-2.0"
] | 12 | 2019-04-03T11:43:48.000Z | 2021-06-27T09:18:57.000Z | 28.75 | 97 | 0.730435 | 12,391 | //
// Decompiled by Procyon v0.5.30
//
package com.bdoemu.core.network.sendable;
import com.bdoemu.commons.network.SendByteBuffer;
import com.bdoemu.commons.network.SendablePacket;
import com.bdoemu.core.network.GameClient;
public class SMChangeAwakenSkill extends SendablePacket<GameClient> {
private final int oldSkillId;
private final int newSkillId;
private final int abilityId;
public SMChangeAwakenSkill(final int oldSkillId, final int newSkillId, final int abilityId) {
this.oldSkillId = oldSkillId;
this.newSkillId = newSkillId;
this.abilityId = abilityId;
}
protected void writeBody(final SendByteBuffer buffer) {
buffer.writeH(this.oldSkillId);
buffer.writeH(this.newSkillId);
buffer.writeD(this.abilityId);
}
}
|
3e1d3bcb3e682dbd12acba87cf9a8757dd3b4301 | 713 | java | Java | StartHere/src/main/java/com/lambdaschool/starthere/services/UserArticleService.java | Pintereach-BuildWeek/Backend | f654b90c9e076bcb657d50a0f60c061497a3c962 | [
"MIT"
] | null | null | null | StartHere/src/main/java/com/lambdaschool/starthere/services/UserArticleService.java | Pintereach-BuildWeek/Backend | f654b90c9e076bcb657d50a0f60c061497a3c962 | [
"MIT"
] | 5 | 2019-09-24T20:01:28.000Z | 2021-12-09T21:37:09.000Z | StartHere/src/main/java/com/lambdaschool/starthere/services/UserArticleService.java | Pintereach-BuildWeek/Backend | f654b90c9e076bcb657d50a0f60c061497a3c962 | [
"MIT"
] | null | null | null | 25.464286 | 111 | 0.776999 | 12,392 | package com.lambdaschool.starthere.services;
import com.lambdaschool.starthere.models.User;
import com.lambdaschool.starthere.models.UserArticles;
import java.util.List;
// Note role does not have an update. Changing the spelling of the role impacts resource access so is BIG DEAL!
public interface UserArticleService
{
List<UserArticles> findAll();
UserArticles findArticleById(long id);
void delete(long id);
UserArticles save(UserArticles userarticle);
UserArticles update(UserArticles user, long id, boolean isAdmin);
UserArticles findByName(String name);
List<UserArticles> findByUserName(String username);
List<UserArticles> findByCategoryName(String category);
} |
3e1d3bcffeae80764118bb36966cfdcb2d6254be | 704 | java | Java | src/creational/simple-factory/java/io/github/hooj0/simplefactory/support/_static/App.java | hooj0/design-patterns | f8c9c7e8e2b6d862b37e652d81247fb10b1d2d47 | [
"MIT"
] | null | null | null | src/creational/simple-factory/java/io/github/hooj0/simplefactory/support/_static/App.java | hooj0/design-patterns | f8c9c7e8e2b6d862b37e652d81247fb10b1d2d47 | [
"MIT"
] | null | null | null | src/creational/simple-factory/java/io/github/hooj0/simplefactory/support/_static/App.java | hooj0/design-patterns | f8c9c7e8e2b6d862b37e652d81247fb10b1d2d47 | [
"MIT"
] | null | null | null | 25.962963 | 77 | 0.758916 | 12,393 | package io.github.hooj0.simplefactory.support._static;
import io.github.hooj0.simplefactory.support.AbstractMessage;
/**
* 静态工厂方法调用示例
* @author hoojo
* @createDate 2018年9月27日 下午10:50:29
* @file App.java
* @package io.github.hooj0.simplefactory.support._static
* @project design-patterns
* @blog http://hoojo.cnblogs.com
* @email nnheo@example.com
* @version 1.0
*/
public class App {
public static void main(String[] args) {
AbstractMessage wechatMessage = StaticMethodMessageFactory.wechatFactory();
System.out.println(wechatMessage.sendMessage());
AbstractMessage emailMessage = StaticMethodMessageFactory.mailFacotry();
System.out.println(emailMessage.sendMessage());
}
}
|
3e1d3c824026e649595be68b496e9d48eb890ba8 | 1,542 | java | Java | stateful-functions-docs/src/main/java/com/ververica/statefun/docs/match/FnMatchGreeter.java | patricklucas/stateful-functions | 7aadc22a7a5531d36d44c40bf194acbccb6b6f68 | [
"Apache-2.0"
] | 271 | 2019-10-08T07:21:37.000Z | 2022-03-31T08:18:29.000Z | stateful-functions-docs/src/main/java/com/ververica/statefun/docs/match/FnMatchGreeter.java | patricklucas/stateful-functions | 7aadc22a7a5531d36d44c40bf194acbccb6b6f68 | [
"Apache-2.0"
] | 27 | 2019-10-09T06:01:53.000Z | 2020-04-07T09:18:49.000Z | stateful-functions-docs/src/main/java/com/ververica/statefun/docs/match/FnMatchGreeter.java | patricklucas/stateful-functions | 7aadc22a7a5531d36d44c40bf194acbccb6b6f68 | [
"Apache-2.0"
] | 60 | 2019-10-08T07:50:17.000Z | 2022-01-06T06:27:32.000Z | 34.266667 | 75 | 0.744488 | 12,394 | /*
* Copyright 2019 Ververica GmbH.
*
* 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.ververica.statefun.docs.match;
import com.ververica.statefun.sdk.Context;
import com.ververica.statefun.sdk.match.MatchBinder;
import com.ververica.statefun.sdk.match.StatefulMatchFunction;
public class FnMatchGreeter extends StatefulMatchFunction {
@Override
public void configure(MatchBinder binder) {
binder
.predicate(Customer.class, this::greetCustomer)
.predicate(Employee.class, Employee::isManager, this::greetManager)
.predicate(Employee.class, this::greetEmployee);
}
private void greetManager(Context context, Employee message) {
System.out.println("Hello manager " + message.getEmployeeId());
}
private void greetEmployee(Context context, Employee message) {
System.out.println("Hello employee " + message.getEmployeeId());
}
private void greetCustomer(Context context, Customer message) {
System.out.println("Hello customer " + message.getName());
}
}
|
3e1d3d875bf8dc4ec8c33b0e9ffbfa991f7e517d | 2,830 | java | Java | lyrics-core/src/main/java/com/flipkart/lyrics/processor/methods/EqualsAndHashCodeHandler.java | naveen-c/Lyrics | 5c232c78bf9da07bde3ea8bad220ab8fd067eafe | [
"Apache-2.0"
] | 7 | 2017-06-09T13:14:09.000Z | 2019-12-06T06:42:38.000Z | lyrics-core/src/main/java/com/flipkart/lyrics/processor/methods/EqualsAndHashCodeHandler.java | naveen-c/Lyrics | 5c232c78bf9da07bde3ea8bad220ab8fd067eafe | [
"Apache-2.0"
] | 7 | 2016-12-22T17:09:27.000Z | 2019-11-13T02:43:18.000Z | lyrics-core/src/main/java/com/flipkart/lyrics/processor/methods/EqualsAndHashCodeHandler.java | naveen-c/Lyrics | 5c232c78bf9da07bde3ea8bad220ab8fd067eafe | [
"Apache-2.0"
] | 8 | 2017-02-06T16:21:00.000Z | 2021-07-09T06:38:32.000Z | 38.243243 | 154 | 0.69576 | 12,395 | /*
* Copyright 2016 Flipkart Internet, pvt 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.flipkart.lyrics.processor.methods;
import com.flipkart.lyrics.config.Tune;
import com.flipkart.lyrics.model.FieldModel;
import com.flipkart.lyrics.model.MetaInfo;
import com.flipkart.lyrics.model.TypeModel;
import com.flipkart.lyrics.processor.Handler;
import com.flipkart.lyrics.sets.RuleSet;
import com.flipkart.lyrics.specs.MethodSpec;
import com.flipkart.lyrics.specs.Modifier;
import com.flipkart.lyrics.specs.TypeSpec;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by shrey.garg on 26/11/16.
*/
public class EqualsAndHashCodeHandler extends Handler {
public EqualsAndHashCodeHandler(Tune tune, MetaInfo metaInfo, RuleSet ruleSet) {
super(tune, metaInfo, ruleSet);
}
@Override
public void process(TypeSpec.Builder typeBuilder, TypeModel typeModel) {
if (!tune.areHashCodeAndEqualsNeeded() || tune.getObjectMethodsStyle() == null) {
return;
}
Map<String, FieldModel> fieldModels = typeModel.getFields();
List<String> nonStaticFields = fieldModels.entrySet().stream()
.filter(entry ->
(!entry.getValue().isExcludeFromEqualsAndHashCode() && !Arrays.stream(entry.getValue().getModifiers())
.anyMatch(modifier -> modifier.equals(Modifier.STATIC))))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
MethodSpec.Builder equalsBuilder = MethodSpec.methodBuilder("equals")
.addModifiers(Modifier.PUBLIC)
.returns(boolean.class)
.addAnnotation(Override.class)
.addParameter(Object.class, "o");
MethodSpec.Builder hashCodeBuilder = MethodSpec.methodBuilder("hashCode")
.addModifiers(Modifier.PUBLIC)
.returns(int.class)
.addAnnotation(Override.class);
tune.getObjectMethodsStyle().processEqualsAndHashCode(equalsBuilder, hashCodeBuilder, nonStaticFields, metaInfo, typeModel.isTestSuperEquality());
typeBuilder.addMethod(equalsBuilder.build());
typeBuilder.addMethod(hashCodeBuilder.build());
}
}
|
3e1d3dcae96145ffebe49a14aff98f3a158005e5 | 2,710 | java | Java | safesms-server-ejb/src/java/com/kyleruss/safesms/server/entity/UserKeys.java | denkers/hss-a2-server | 286afb69e2295e1e79b2cf8290df08025e40ba80 | [
"MIT"
] | null | null | null | safesms-server-ejb/src/java/com/kyleruss/safesms/server/entity/UserKeys.java | denkers/hss-a2-server | 286afb69e2295e1e79b2cf8290df08025e40ba80 | [
"MIT"
] | null | null | null | safesms-server-ejb/src/java/com/kyleruss/safesms/server/entity/UserKeys.java | denkers/hss-a2-server | 286afb69e2295e1e79b2cf8290df08025e40ba80 | [
"MIT"
] | 1 | 2016-09-17T02:08:22.000Z | 2016-09-17T02:08:22.000Z | 21.171875 | 75 | 0.608118 | 12,396 | //======================================
// Kyle Russell
// AUT University 2016
// Highly Secured Systems A2
//======================================
package com.kyleruss.safesms.server.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "user_keys")
public class UserKeys implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 256)
@Column(name = "pub_key")
private String pubKey;
@Column(name = "created_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
@JoinColumn(name = "user_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Users userId;
public UserKeys() {}
public UserKeys(Integer id)
{
this.id = id;
}
public UserKeys(Integer id, String pubKey)
{
this.id = id;
this.pubKey = pubKey;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getPubKey()
{
return pubKey;
}
public void setPubKey(String pubKey)
{
this.pubKey = pubKey;
}
public Date getCreatedDate()
{
return createdDate;
}
public void setCreatedDate(Date createdDate)
{
this.createdDate = createdDate;
}
public Users getUserId()
{
return userId;
}
public void setUserId(Users userId)
{
this.userId = userId;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
if (id == null || object == null || !(object instanceof UserKeys))
return false;
UserKeys other = (UserKeys) object;
return this.id.equals(other.getId());
}
@Override
public String toString()
{
return "UserKeys[ id=" + id + " ]";
}
}
|
3e1d3dd4ea49fa21dab7189745f31a5c30b9f2c2 | 3,637 | java | Java | cws-war/src/main/java/edu/ucsd/crbs/cws/cluster/JobPathImpl.java | CRBS/cws | a839f99b1338055ac90c69943f8141d73b2bcffe | [
"BSD-4-Clause-UC"
] | null | null | null | cws-war/src/main/java/edu/ucsd/crbs/cws/cluster/JobPathImpl.java | CRBS/cws | a839f99b1338055ac90c69943f8141d73b2bcffe | [
"BSD-4-Clause-UC"
] | null | null | null | cws-war/src/main/java/edu/ucsd/crbs/cws/cluster/JobPathImpl.java | CRBS/cws | a839f99b1338055ac90c69943f8141d73b2bcffe | [
"BSD-4-Clause-UC"
] | null | null | null | 38.305263 | 138 | 0.688926 | 12,397 | /*
* COPYRIGHT AND LICENSE
*
* Copyright 2014 The Regents of the University of California All Rights Reserved
*
* Permission to copy, modify and distribute any part of this CRBS Workflow
* Service for educational, research and non-profit purposes, without fee, and
* without a written agreement is hereby granted, provided that the above
* copyright notice, this paragraph and the following three paragraphs appear
* in all copies.
*
* Those desiring to incorporate this CRBS Workflow Service into commercial
* products or use for commercial purposes should contact the Technology
* Transfer Office, University of California, San Diego, 9500 Gilman Drive,
* Mail Code 0910, La Jolla, CA 92093-0910, Ph: (858) 534-5815,
* FAX: (858) 534-7345, E-MAIL:ychag@example.com.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
* LOST PROFITS, ARISING OUT OF THE USE OF THIS CRBS Workflow Service, EVEN IF
* THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE CRBS Workflow Service PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE
* UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE UNIVERSITY OF CALIFORNIA MAKES
* NO REPRESENTATIONS AND EXTENDS NO WARRANTIES OF ANY KIND, EITHER IMPLIED OR
* EXPRESS, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT THE USE OF
* THE CRBS Workflow Service WILL NOT INFRINGE ANY PATENT, TRADEMARK OR OTHER
* RIGHTS.
*/
package edu.ucsd.crbs.cws.cluster;
import edu.ucsd.crbs.cws.rest.Constants;
import edu.ucsd.crbs.cws.workflow.Job;
import java.io.File;
/**
* Generates path to {@link Job} on filesystem
* @author Christopher Churas <dycjh@example.com>
*/
public class JobPathImpl implements JobPath{
private String _baseExecDir;
/**
* Constructor
* @param baseExecDir Base file system path. All jobs will be put under this directory
*/
public JobPathImpl(final String baseExecDir){
_baseExecDir = baseExecDir;
}
/**
* Generates output directory by invoking {@link #getJobBaseDirectory(edu.ucsd.crbs.cws.workflow.Job)}
* and appending {@link Constants#OUTPUTS_DIR_NAME}
* @param j
* @return
* @throws Exception
*/
@Override
public String getJobOutputDirectory(Job j) throws Exception {
return getJobBaseDirectory(j)+File.separator+
Constants.OUTPUTS_DIR_NAME;
}
/**
* Generates base directory by appending the {@link Job#getOwner()} and
* {@link Job#getId()} to the <b>baseExecDir</b> passed in to the constructor
* @return
* @throws Exception If the <b>j</b> is null, if baseExec Directory is null, if {@link Job#getOwner() } or {@link Job#getId()} is null
*/
@Override
public String getJobBaseDirectory(Job j) throws Exception {
if (_baseExecDir == null){
throw new NullPointerException("Base directory cannot be null");
}
if (j == null){
throw new NullPointerException("Job cannot be null");
}
if (j.getOwner() == null){
throw new NullPointerException("Job owner cannot be null");
}
if (j.getId() == null){
throw new NullPointerException("Job id cannot be null");
}
return _baseExecDir+File.separator+j.getOwner()+
File.separator+j.getId().toString();
}
}
|
3e1d3eed8f02bec6ae580490f4642805b4e21acb | 1,271 | java | Java | moss-extension/src/main/java/org/xujin/moss/controller/DictController.java | itdamo/Moss | ad549e5b11de62c4d5a7c90537179fff0344c60d | [
"Apache-2.0"
] | 1,333 | 2019-04-10T08:50:50.000Z | 2022-03-24T07:07:46.000Z | moss-extension/src/main/java/org/xujin/moss/controller/DictController.java | itdamo/Moss | ad549e5b11de62c4d5a7c90537179fff0344c60d | [
"Apache-2.0"
] | 39 | 2019-04-10T13:20:43.000Z | 2022-02-27T21:17:44.000Z | moss-extension/src/main/java/org/xujin/moss/controller/DictController.java | itdamo/Moss | ad549e5b11de62c4d5a7c90537179fff0344c60d | [
"Apache-2.0"
] | 359 | 2019-04-10T13:12:39.000Z | 2022-03-30T01:22:57.000Z | 29.55814 | 123 | 0.741935 | 12,398 | package org.xujin.moss.controller;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xujin.moss.common.ResultData;
import org.xujin.moss.constant.Constants;
import org.xujin.moss.model.MetaDataModel;
import org.xujin.moss.service.DictService;
import java.util.List;
/**
* 字典控制器
* @author homeant
* @date 2019-05-26 10:32:07
*/
@RestController
@RequestMapping("dist")
public class DictController extends BaseController {
@Autowired
DictService dictService;
/**
* 通过类型获取字典项
* @param type
* @return
*/
@GetMapping("{type}")
public ResultData fecthDict(@PathVariable("type") String type){
List<MetaDataModel> dictLists = dictService.findDictDataByDictCodeAndStatus(Constants.DICT_DATA_STATUS_TRUE, type);
if(CollectionUtils.isNotEmpty(dictLists)){
return ResultData.ok(dictLists).build();
}else{
return ResultData.noContent().build();
}
}
}
|
3e1d3efb7492ef45713e43c4403c2549690fa8b2 | 10,953 | java | Java | networking/eth2/src/main/java/tech/pegasys/teku/networking/eth2/peers/Eth2PeerManager.java | mark-terry/artemis | 22e68acfdc419d1e5546c8b7ef32cc251e522b07 | [
"Apache-2.0"
] | null | null | null | networking/eth2/src/main/java/tech/pegasys/teku/networking/eth2/peers/Eth2PeerManager.java | mark-terry/artemis | 22e68acfdc419d1e5546c8b7ef32cc251e522b07 | [
"Apache-2.0"
] | 1 | 2020-04-15T01:16:55.000Z | 2020-04-15T01:16:55.000Z | networking/eth2/src/main/java/tech/pegasys/teku/networking/eth2/peers/Eth2PeerManager.java | mark-terry/artemis | 22e68acfdc419d1e5546c8b7ef32cc251e522b07 | [
"Apache-2.0"
] | null | null | null | 38.978648 | 118 | 0.718251 | 12,399 | /*
* Copyright 2019 ConsenSys AG.
*
* 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 tech.pegasys.teku.networking.eth2.peers;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.UnsignedLong;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.jetbrains.annotations.NotNull;
import tech.pegasys.teku.datastructures.networking.libp2p.rpc.GoodbyeMessage;
import tech.pegasys.teku.datastructures.networking.libp2p.rpc.MetadataMessage;
import tech.pegasys.teku.networking.eth2.AttestationSubnetService;
import tech.pegasys.teku.networking.eth2.rpc.beaconchain.BeaconChainMethods;
import tech.pegasys.teku.networking.eth2.rpc.beaconchain.methods.MetadataMessagesFactory;
import tech.pegasys.teku.networking.eth2.rpc.beaconchain.methods.StatusMessageFactory;
import tech.pegasys.teku.networking.eth2.rpc.core.RpcException;
import tech.pegasys.teku.networking.eth2.rpc.core.encodings.RpcEncoding;
import tech.pegasys.teku.networking.p2p.network.PeerHandler;
import tech.pegasys.teku.networking.p2p.peer.DisconnectRequestHandler.DisconnectReason;
import tech.pegasys.teku.networking.p2p.peer.NodeId;
import tech.pegasys.teku.networking.p2p.peer.Peer;
import tech.pegasys.teku.networking.p2p.peer.PeerConnectedSubscriber;
import tech.pegasys.teku.storage.api.StorageQueryChannel;
import tech.pegasys.teku.storage.client.CombinedChainDataClient;
import tech.pegasys.teku.storage.client.RecentChainData;
import tech.pegasys.teku.util.async.AsyncRunner;
import tech.pegasys.teku.util.async.Cancellable;
import tech.pegasys.teku.util.async.DelayedExecutorAsyncRunner;
import tech.pegasys.teku.util.async.RootCauseExceptionHandler;
import tech.pegasys.teku.util.events.Subscribers;
public class Eth2PeerManager implements PeerLookup, PeerHandler {
private static final Logger LOG = LogManager.getLogger();
private final AsyncRunner asyncRunner;
private final StatusMessageFactory statusMessageFactory;
private final MetadataMessagesFactory metadataMessagesFactory;
private final Subscribers<PeerConnectedSubscriber<Eth2Peer>> connectSubscribers =
Subscribers.create(true);
private final ConcurrentHashMap<NodeId, Eth2Peer> connectedPeerMap = new ConcurrentHashMap<>();
private final BeaconChainMethods rpcMethods;
private final PeerValidatorFactory peerValidatorFactory;
private final Duration eth2RpcPingInterval;
private final int eth2RpcOutstandingPingThreshold;
private final Duration eth2StatusUpdateInterval;
Eth2PeerManager(
final AsyncRunner asyncRunner,
final CombinedChainDataClient combinedChainDataClient,
final RecentChainData storageClient,
final MetricsSystem metricsSystem,
final PeerValidatorFactory peerValidatorFactory,
final AttestationSubnetService attestationSubnetService,
final RpcEncoding rpcEncoding,
final Duration eth2RpcPingInterval,
final int eth2RpcOutstandingPingThreshold,
Duration eth2StatusUpdateInterval) {
this.asyncRunner = asyncRunner;
this.statusMessageFactory = new StatusMessageFactory(storageClient);
metadataMessagesFactory = new MetadataMessagesFactory();
attestationSubnetService.subscribeToUpdates(metadataMessagesFactory);
this.peerValidatorFactory = peerValidatorFactory;
this.rpcMethods =
BeaconChainMethods.create(
DelayedExecutorAsyncRunner.create(),
this,
combinedChainDataClient,
storageClient,
metricsSystem,
statusMessageFactory,
metadataMessagesFactory,
rpcEncoding);
this.eth2RpcPingInterval = eth2RpcPingInterval;
this.eth2RpcOutstandingPingThreshold = eth2RpcOutstandingPingThreshold;
this.eth2StatusUpdateInterval = eth2StatusUpdateInterval;
}
public static Eth2PeerManager create(
final AsyncRunner asyncRunner,
final RecentChainData storageClient,
final StorageQueryChannel historicalChainData,
final MetricsSystem metricsSystem,
final AttestationSubnetService attestationSubnetService,
final RpcEncoding rpcEncoding,
final Duration eth2RpcPingInterval,
final int eth2RpcOutstandingPingThreshold,
Duration eth2StatusUpdateInterval) {
final PeerValidatorFactory peerValidatorFactory =
(peer, status) ->
PeerChainValidator.create(storageClient, historicalChainData, peer, status);
return new Eth2PeerManager(
asyncRunner,
new CombinedChainDataClient(storageClient, historicalChainData),
storageClient,
metricsSystem,
peerValidatorFactory,
attestationSubnetService,
rpcEncoding,
eth2RpcPingInterval,
eth2RpcOutstandingPingThreshold,
eth2StatusUpdateInterval);
}
public MetadataMessage getMetadataMessage() {
return metadataMessagesFactory.createMetadataMessage();
}
private void setUpPeriodicTasksForPeer(Eth2Peer peer) {
Cancellable periodicStatusUpdateTask = periodicallyUpdatePeerStatus(peer);
Cancellable periodicPingTask = periodicallyPingPeer(peer);
peer.subscribeDisconnect(
() -> {
periodicStatusUpdateTask.cancel();
periodicPingTask.cancel();
});
}
Cancellable periodicallyUpdatePeerStatus(Eth2Peer peer) {
return asyncRunner.runWithFixedDelay(
() ->
peer.sendStatus()
.finish(
() -> LOG.trace("Updated status for peer {}", peer),
err -> LOG.debug("Exception updating status for peer {}", peer, err)),
eth2StatusUpdateInterval.getSeconds(),
TimeUnit.SECONDS,
err -> LOG.debug("Exception calling runnable for updating peer status.", err));
}
Cancellable periodicallyPingPeer(Eth2Peer peer) {
return asyncRunner.runWithFixedDelay(
() -> sendPeriodicPing(peer),
eth2RpcPingInterval.toMillis(),
TimeUnit.MILLISECONDS,
err -> LOG.debug("Exception calling runnable for pinging peer", err));
}
@Override
public void onConnect(final Peer peer) {
Eth2Peer eth2Peer =
new Eth2Peer(peer, rpcMethods, statusMessageFactory, metadataMessagesFactory);
final boolean wasAdded = connectedPeerMap.putIfAbsent(peer.getId(), eth2Peer) == null;
if (!wasAdded) {
LOG.warn("Duplicate peer connection detected. Ignoring peer.");
return;
}
peer.setDisconnectRequestHandler(
reason -> eth2Peer.sendGoodbye(convertToEth2DisconnectReason(reason)));
if (peer.connectionInitiatedLocally()) {
eth2Peer
.sendStatus()
.finish(
() -> LOG.trace("Sent status to {}", peer.getId()),
RootCauseExceptionHandler.builder()
.addCatch(
RpcException.class,
err -> LOG.trace("Status message rejected by {}: {}", peer.getId(), err))
.defaultCatch(
err -> LOG.debug("Failed to send status to {}: {}", peer.getId(), err)));
}
eth2Peer.subscribeInitialStatus(
(status) ->
peerValidatorFactory
.create(eth2Peer, status)
.run()
.finish(
peerIsValid -> {
if (peerIsValid) {
connectSubscribers.forEach(c -> c.onConnected(eth2Peer));
setUpPeriodicTasksForPeer(eth2Peer);
}
},
error -> LOG.debug("Error while validating peer", error)));
}
@VisibleForTesting
void sendPeriodicPing(Eth2Peer peer) {
if (peer.getOutstandingPings() >= eth2RpcOutstandingPingThreshold) {
LOG.debug("Disconnecting the peer {} due to PING timeout.", peer.getId());
peer.disconnectCleanly(DisconnectReason.REMOTE_FAULT);
} else {
peer.sendPing()
.finish(
i -> LOG.trace("Periodic ping returned {} from {}", i, peer.getId()),
t -> LOG.debug("Ping request failed for peer {}", peer.getId(), t));
}
}
private UnsignedLong convertToEth2DisconnectReason(final DisconnectReason reason) {
switch (reason) {
case TOO_MANY_PEERS:
return GoodbyeMessage.REASON_TOO_MANY_PEERS;
case SHUTTING_DOWN:
return GoodbyeMessage.REASON_CLIENT_SHUT_DOWN;
case REMOTE_FAULT:
return GoodbyeMessage.REASON_FAULT_ERROR;
case IRRELEVANT_NETWORK:
return GoodbyeMessage.REASON_IRRELEVANT_NETWORK;
case UNABLE_TO_VERIFY_NETWORK:
return GoodbyeMessage.REASON_UNABLE_TO_VERIFY_NETWORK;
default:
LOG.warn("Unknown disconnect reason: " + reason);
return GoodbyeMessage.REASON_FAULT_ERROR;
}
}
public long subscribeConnect(final PeerConnectedSubscriber<Eth2Peer> subscriber) {
return connectSubscribers.subscribe(subscriber);
}
public void unsubscribeConnect(final long subscriptionId) {
connectSubscribers.unsubscribe(subscriptionId);
}
@Override
public void onDisconnect(@NotNull final Peer peer) {
connectedPeerMap.compute(
peer.getId(),
(id, existingPeer) -> {
if (peer.idMatches(existingPeer)) {
return null;
}
return existingPeer;
});
}
public BeaconChainMethods getBeaconChainMethods() {
return rpcMethods;
}
/**
* Look up peer by id, returning peer result regardless of validation status of the peer.
*
* @param nodeId The nodeId of the peer to lookup
* @return the peer corresponding to this node id.
*/
@Override
public Optional<Eth2Peer> getConnectedPeer(NodeId nodeId) {
return Optional.ofNullable(connectedPeerMap.get(nodeId));
}
public Optional<Eth2Peer> getPeer(NodeId peerId) {
return Optional.ofNullable(connectedPeerMap.get(peerId)).filter(this::peerIsReady);
}
public Stream<Eth2Peer> streamPeers() {
return connectedPeerMap.values().stream().filter(this::peerIsReady);
}
private boolean peerIsReady(Eth2Peer peer) {
return peer.isChainValidated();
}
interface PeerValidatorFactory {
PeerChainValidator create(final Eth2Peer peer, final PeerStatus status);
}
}
|
3e1d3f03956b0de05dd616261c1e03433d229c66 | 4,060 | java | Java | backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/xml/XmlDocument.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 347 | 2015-01-20T14:13:21.000Z | 2022-03-31T17:53:11.000Z | backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/xml/XmlDocument.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 128 | 2015-05-22T19:14:32.000Z | 2022-03-31T08:11:18.000Z | backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ovf/xml/XmlDocument.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 202 | 2015-01-04T06:20:49.000Z | 2022-03-08T15:30:08.000Z | 34.40678 | 95 | 0.660345 | 12,400 | package org.ovirt.engine.core.utils.ovf.xml;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.ovirt.engine.core.uutils.xml.SecureDocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XmlDocument {
private String outerXml;
public XmlNode[] childNodes;
private Document doc;
public XmlDocument() {
}
public XmlDocument(String xml) throws Exception {
loadXml(xml);
}
private void loadXml(String ovfstring) throws Exception {
// load doc
DocumentBuilderFactory fact = SecureDocumentBuilderFactory.newDocumentBuilderFactory();
fact.setNamespaceAware(true);
DocumentBuilder builder = fact.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(ovfstring)));
// initialize all the child nodes
NodeList list = doc.getElementsByTagName("*");
childNodes = new XmlNode[list.getLength()];
for (int i = 0; i < list.getLength(); i++) {
childNodes[i] = new XmlNode(list.item(i));
}
outerXml = ovfstring;
}
public XmlNode selectSingleNode(String string) {
try {
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
Object o = xPath.evaluate(string, doc, XPathConstants.NODE);
return o != null ? new XmlNode((Node) o) : null;
} catch (Exception e) {
throw new RuntimeException("Failed to evaluate xpath: " + string, e);
}
}
public XmlNode selectSingleNode(String string, XmlNamespaceManager _xmlns) {
try {
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
xPath.setNamespaceContext(_xmlns);
Object o = xPath.evaluate(string, doc, XPathConstants.NODE);
return o != null ? new XmlNode((Node) o) : null;
} catch (Exception e) {
throw new RuntimeException("Failed to evaluate xpath: " + string, e);
}
}
public XmlNodeList selectNodes(String string) {
try {
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
Object o = xPath.evaluate(string, doc, XPathConstants.NODESET);
return new XmlNodeList((NodeList) o);
} catch (Exception e) {
throw new RuntimeException("Failed to evaluate xpath: " + string, e);
}
}
public XmlNodeList selectNodes(String string, XmlNamespaceManager _xmlns) {
try {
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
xPath.setNamespaceContext(_xmlns);
Object o = xPath.evaluate(string, doc, XPathConstants.NODESET);
return new XmlNodeList((NodeList) o);
} catch (Exception e) {
throw new RuntimeException("Failed to evaluate xpath: " + string, e);
}
}
public Element createElement(String name) {
return doc.createElement(name);
}
public String getOuterXml() {
return outerXml;
}
public String convertToString() throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.toString();
}
}
|
3e1d3f4a2427cb58d4f3f026cae01671a7e39254 | 993 | java | Java | app/src/androidTest/java/com/github/drunlin/guokr/activity/SearchableActivityTest.java | drunlin/guokr-android | ee1bc941e17d22e7867892b3b3de133ef58ad9c9 | [
"MIT"
] | 22 | 2016-04-03T08:32:33.000Z | 2020-02-28T09:32:33.000Z | app/src/androidTest/java/com/github/drunlin/guokr/activity/SearchableActivityTest.java | drunlin/guokr-android | ee1bc941e17d22e7867892b3b3de133ef58ad9c9 | [
"MIT"
] | null | null | null | app/src/androidTest/java/com/github/drunlin/guokr/activity/SearchableActivityTest.java | drunlin/guokr-android | ee1bc941e17d22e7867892b3b3de133ef58ad9c9 | [
"MIT"
] | 10 | 2016-04-21T17:13:44.000Z | 2021-04-29T08:09:33.000Z | 29.264706 | 82 | 0.656281 | 12,401 | package com.github.drunlin.guokr.activity;
import com.github.drunlin.guokr.bean.SearchEntry;
import com.github.drunlin.guokr.test.ActivityTestCase;
import java.util.ArrayList;
import java.util.List;
/**
* @author ychag@example.com
*/
public class SearchableActivityTest extends ActivityTestCase<SearchableActivity> {
public SearchableActivityTest() {
super(SearchableActivity.class, false);
}
@Override
protected void init() throws Throwable {
launchActivity(SearchableActivity.getIntent("guokr"));
}
@Override
protected void onPreview() throws Throwable {
List<SearchEntry> entries = new ArrayList<>(10);
for (int i = 0; i < 10; ++i) {
SearchEntry entry = new SearchEntry();
entry.content = "<h4>[Article] Title</h4><p>This is a test.<p/>";
entry.datetime = "2015-01-0" + i;
entries.add(entry);
}
runOnUiThread(() -> activity.setSearchResult(entries));
}
}
|
3e1d3f89bf32ce9fd9cec2e7581acec58b8be8b6 | 3,829 | java | Java | core/src/test/java/feast/core/job/dataflow/DataflowJobMonitorTest.java | pradithya/feast | 9aad264124ed4bf24723c2418abb84d61d6fbb72 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/feast/core/job/dataflow/DataflowJobMonitorTest.java | pradithya/feast | 9aad264124ed4bf24723c2418abb84d61d6fbb72 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/feast/core/job/dataflow/DataflowJobMonitorTest.java | pradithya/feast | 9aad264124ed4bf24723c2418abb84d61d6fbb72 | [
"Apache-2.0"
] | 2 | 2020-05-20T22:07:11.000Z | 2021-07-25T17:28:24.000Z | 36.817308 | 105 | 0.75346 | 12,402 | /*
* Copyright 2018 The Feast Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package feast.core.job.dataflow;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.services.dataflow.Dataflow;
import com.google.api.services.dataflow.Dataflow.Projects;
import com.google.api.services.dataflow.Dataflow.Projects.Locations;
import com.google.api.services.dataflow.Dataflow.Projects.Locations.Jobs;
import com.google.api.services.dataflow.Dataflow.Projects.Locations.Jobs.Get;
import com.google.api.services.dataflow.model.Job;
import feast.core.job.Runner;
import feast.core.model.JobInfo;
import feast.core.model.JobStatus;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
public class DataflowJobMonitorTest {
private DataflowJobMonitor monitor;
private String location;
private String projectId;
private Jobs jobService;
@Before
public void setUp() throws Exception {
projectId = "myProject";
location = "asia-east1";
Dataflow dataflow = mock(Dataflow.class);
Dataflow.Projects projects = mock(Projects.class);
Dataflow.Projects.Locations locations = mock(Locations.class);
jobService = mock(Jobs.class);
when(dataflow.projects()).thenReturn(projects);
when(projects.locations()).thenReturn(locations);
when(locations.jobs()).thenReturn(jobService);
monitor = new DataflowJobMonitor(dataflow, projectId, location);
}
@Test
public void getJobStatus_shouldReturnCorrectJobStatusForValidDataflowJobState()
throws IOException {
String jobId = "myJobId";
Get getOp = mock(Get.class);
Job job = mock(Job.class);
when(getOp.execute()).thenReturn(job);
when(job.getCurrentState()).thenReturn(DataflowJobState.JOB_STATE_RUNNING.toString());
when(jobService.get(projectId, location, jobId)).thenReturn(getOp);
JobInfo jobInfo = mock(JobInfo.class);
when(jobInfo.getExtId()).thenReturn(jobId);
when(jobInfo.getRunner()).thenReturn(Runner.DATAFLOW.getName());
assertThat(monitor.getJobStatus(jobInfo), equalTo(JobStatus.RUNNING));
}
@Test
public void getJobStatus_shouldReturnUnknownStateForInvalidDataflowJobState() throws IOException {
String jobId = "myJobId";
Get getOp = mock(Get.class);
Job job = mock(Job.class);
when(getOp.execute()).thenReturn(job);
when(job.getCurrentState()).thenReturn("Random String");
when(jobService.get(projectId, location, jobId)).thenReturn(getOp);
JobInfo jobInfo = mock(JobInfo.class);
when(jobInfo.getExtId()).thenReturn(jobId);
when(jobInfo.getRunner()).thenReturn(Runner.DATAFLOW.getName());
assertThat(monitor.getJobStatus(jobInfo), equalTo(JobStatus.UNKNOWN));
}
@Test
public void getJobStatus_shouldReturnUnknownStateWhenExceptionHappen() throws IOException {
String jobId = "myJobId";
when(jobService.get(projectId, location, jobId)).thenThrow(new RuntimeException("some thing wrong"));
JobInfo jobInfo = mock(JobInfo.class);
when(jobInfo.getExtId()).thenReturn(jobId);
when(jobInfo.getRunner()).thenReturn(Runner.DATAFLOW.getName());
assertThat(monitor.getJobStatus(jobInfo), equalTo(JobStatus.UNKNOWN));
}
} |
3e1d3f9e79933f2991af1b1b25804cd386f1cd08 | 8,252 | java | Java | src/main/java/org/gfg/bst/Bst.java | andrey-yemelyanov/gfg | a95c3c8af7d0ed742a85e1b56a0f3d1267e14846 | [
"MIT"
] | null | null | null | src/main/java/org/gfg/bst/Bst.java | andrey-yemelyanov/gfg | a95c3c8af7d0ed742a85e1b56a0f3d1267e14846 | [
"MIT"
] | null | null | null | src/main/java/org/gfg/bst/Bst.java | andrey-yemelyanov/gfg | a95c3c8af7d0ed742a85e1b56a0f3d1267e14846 | [
"MIT"
] | null | null | null | 31.496183 | 108 | 0.603611 | 12,403 | package org.gfg.bst;
import java.util.*;
import org.gfg.SortedSet;
/**
* Implements {@link SortedSet} interface using a binary search tree. Note that this
* implementation makes no guarantees about the balance of the tree. E.g.
* inserting elements in sorted order will result in a degenerate binary search
* tree - a linked list essentially. Use {@link AvlTree} instead if you need
* balance guarantees.
*
* @param <T> type of elements stored in binary search tree
*/
public class Bst<T extends Comparable<T>> implements SortedSet<T> {
protected class BstNode {
public T value;
public BstNode left;
public BstNode right;
public BstNode(T value) {
this.value = value;
}
}
private class InorderBstIterator implements Iterator<T>{
private Stack<BstNode> stack;
public InorderBstIterator(){
stack = new Stack<BstNode>();
BstNode node = root;
while(node != null){
stack.push(node);
node = node.left;
}
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public T next() {
BstNode topNode = stack.pop();
BstNode node = topNode.right;
while(node != null){
stack.push(node);
node = node.left;
}
return topNode.value;
}
}
protected BstNode root;
protected int size;
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public void add(T item) {
root = add(item, root);
}
protected BstNode add(T key, BstNode root) {
if(root == null) {
size++;
return new BstNode(key);
}
if(root.value.compareTo(key) > 0) root.left = add(key, root.left);
else if(root.value.compareTo(key) < 0) root.right = add(key, root.right);
return root;
}
@Override
public boolean contains(T item) {
return search(root, item) != null;
}
private BstNode search(BstNode root, T key){
if (root == null) return null;
if (root.value.compareTo(key) == 0) return root;
if (root.value.compareTo(key) > 0) return search(root.left, key);
return search(root.right, key);
}
/**
* Returns the height of this binary search tree - the longest distance from the
* root to some leaf.
* @return height of this binary search tree
*/
public int height() {
return height(root);
}
protected int height(BstNode root){
if(root == null) return -1;
return Math.max(height(root.left), height(root.right)) + 1;
}
@Override
public Iterator<T> iterator() {
return new InorderBstIterator();
}
@Override
public void remove(T item) {
nodeDeleted = false;
root = delete(root, item);
if(nodeDeleted) {
size--;
}
}
protected boolean nodeDeleted;
protected BstNode delete(BstNode root, T key){
if(root == null) return null;
if(root.value.compareTo(key) > 0) root.left = delete(root.left, key);
else if(root.value.compareTo(key) < 0) root.right = delete(root.right, key);
else{ // key to be deleted found
nodeDeleted = true;
if(root.left == null) return root.right;
if(root.right == null) return root.left;
// replace node value with the value of inorder successor
root.value = minNode(root.right).value;
// delete inorder successor in the right subtree
root.right = delete(root.right, root.value);
}
return root;
}
@Override
public T successor(T key) {
BstNode successorNode = successor(root, null, key);
if(successorNode != null) return successorNode.value;
return null;
}
private BstNode successor(BstNode root, BstNode inorderParent, T key){
if(root == null) return inorderParent;
BstNode successorNode = null;
if(root.value.compareTo(key) == 0) successorNode = minNode(root.right);
else if(root.value.compareTo(key) > 0) successorNode = successor(root.left, root, key);
else successorNode = successor(root.right, inorderParent, key);
if(successorNode == null) successorNode = inorderParent;
return successorNode;
}
@Override
public T ceil(T key) {
BstNode ceilNode = ceil(root, null, key);
if(ceilNode != null) return ceilNode.value;
return null;
}
private BstNode ceil(BstNode root, BstNode inorderParent, T key){
if(root == null) return inorderParent;
if(root.value.compareTo(key) == 0) return root;
BstNode ceilNode = null;
if(root.value.compareTo(key) > 0) ceilNode = ceil(root.left, root, key);
else ceilNode = ceil(root.right, inorderParent, key);
if(ceilNode == null) ceilNode = inorderParent;
return ceilNode;
}
@Override
public T predecessor(T key) {
BstNode predecessorNode = predecessor(root, null, key);
if(predecessorNode != null) return predecessorNode.value;
return null;
}
private BstNode predecessor(BstNode root, BstNode inorderParent, T key){
if(root == null) return inorderParent;
BstNode predecessorNode = null;
if(root.value.compareTo(key) == 0) predecessorNode = maxNode(root.left);
else if(root.value.compareTo(key) > 0) predecessorNode = predecessor(root.left, inorderParent, key);
else predecessorNode = predecessor(root.right, root, key);
if(predecessorNode == null) predecessorNode = inorderParent;
return predecessorNode;
}
@Override
public T floor(T key) {
BstNode floorNode = floor(root, null, key);
if(floorNode != null) return floorNode.value;
return null;
}
private BstNode floor(BstNode root, BstNode inorderParent, T key){
if(root == null) return inorderParent;
if(root.value.compareTo(key) == 0) return root;
BstNode floorNode = null;
if(root.value.compareTo(key) > 0) floorNode = floor(root.left, inorderParent, key);
else floorNode = floor(root.right, root, key);
if(floorNode == null) floorNode = inorderParent;
return floorNode;
}
@Override
public T min() {
return minNode(root).value;
}
@Override
public T max() {
return maxNode(root).value;
}
protected BstNode minNode(BstNode root){
if(root == null || root.left == null) return root;
return minNode(root.left);
}
private BstNode maxNode(BstNode root){
if(root == null || root.right == null) return root;
return maxNode(root.right);
}
@Override
public List<T> toList() {
List<T> list = new ArrayList<>();
iterator().forEachRemaining(list::add);
return list;
}
/**
* Checks for balance in this binary search tree. A binary tree is balanced
* if for each node the absolute difference between the height of its left subtree
* and its right subtree is no larger than 1.
* @return true if this binary search tree is balanced
*/
public boolean isBalanced(){
return isBalanced(root).isBalanced;
}
private class BalanceResponse{
public int height;
public boolean isBalanced;
public BalanceResponse(int height, boolean isBalanced){
this.height = height;
this.isBalanced = isBalanced;
}
}
private BalanceResponse isBalanced(BstNode root){
if(root == null) return new BalanceResponse(-1, true);
BalanceResponse left = isBalanced(root.left);
BalanceResponse right = isBalanced(root.right);
if(!left.isBalanced) return left;
if(!right.isBalanced) return right;
boolean isBalanced = Math.abs(left.height - right.height) <= 1;
return new BalanceResponse(Math.max(left.height, right.height) + 1, isBalanced);
}
} |
3e1d3fc23d5ea130a8947dff93a69df6e13a6593 | 2,184 | java | Java | src/main/java/com/wavefront/datastructures/ExactDistributionIterator.java | dbaghdasarya/wavefront-trace-loader | 00362d6c189780c09dbf4c85223570d1fb563a48 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/wavefront/datastructures/ExactDistributionIterator.java | dbaghdasarya/wavefront-trace-loader | 00362d6c189780c09dbf4c85223570d1fb563a48 | [
"Apache-2.0"
] | 3 | 2019-11-07T13:54:31.000Z | 2021-04-20T16:09:40.000Z | src/main/java/com/wavefront/datastructures/ExactDistributionIterator.java | dbaghdasarya/wavefront-trace-loader | 00362d6c189780c09dbf4c85223570d1fb563a48 | [
"Apache-2.0"
] | null | null | null | 31.710145 | 96 | 0.650366 | 12,404 | package com.wavefront.datastructures;
import java.util.Collections;
import java.util.List;
/**
* An iterator for providing distributions to generate exact numbers of items according to
* distributions count.
*
* @author Norayr Chaparyan (lyhxr@example.com)
*/
public class ExactDistributionIterator<T extends Distribution> extends DistributionIterator<T> {
public ExactDistributionIterator(List<T> distributions, int count) {
super(distributions);
Collections.shuffle(distributions);
calculateDistributionsPortions(count);
}
/**
* Calculate corresponding portions of Distributions make as counts.
*/
protected void calculateDistributionsPortions(int count) {
double alreadyGenerated = 0;
double accumulate = 0;
double sumOfPercentages = distributions.stream().
mapToDouble(t -> t.percentage).sum();
for (int i = 0; i < distributions.size(); i++) {
Distribution d = distributions.get(i);
d.portion = d.percentage * count / sumOfPercentages;
int portion = (int) Math.round(d.portion);
if (Math.abs(accumulate) >= 1) {
if (accumulate >= 0) {
accumulate = accumulate - (d.portion - (int) d.portion);
d.portion = (int) d.portion;
} else {
accumulate = accumulate + (d.portion - (int) d.portion);
d.portion = Math.ceil(d.portion);
}
} else if (i == distributions.size() - 1) {
d.portion = count - alreadyGenerated;
} else {
accumulate += portion - d.portion;
d.portion = portion;
}
alreadyGenerated += d.portion;
}
}
@Override
public T getNextDistribution() {
if (distributions.isEmpty()) {
return null;
}
int index = RANDOM.nextInt(distributions.size());
// Removing of depleted distributions.
while (distributions.size() > 1 && distributions.get(index).portion <= 0) {
distributions.remove(index);
index = RANDOM.nextInt(distributions.size());
}
distributions.get(index).portion--;
if (distributions.get(index).portion < -0.1) {
distributions.remove(index);
return null;
}
return distributions.get(index);
}
} |
3e1d40e338a4958a959013d2b5fd05ab871d21d5 | 312 | java | Java | Mobile/Covid-Locker/source/butterknife/BindViews.java | rafael2025/RANSOMWARES | 6ac3c5d463bb1bedddde831bd9a20a442e29adc0 | [
"MIT"
] | 18 | 2021-07-21T00:26:34.000Z | 2022-03-26T19:22:57.000Z | Mobile/Covid-Locker/source/butterknife/BindViews.java | rafael2025/RANSOMWARES | 6ac3c5d463bb1bedddde831bd9a20a442e29adc0 | [
"MIT"
] | null | null | null | Mobile/Covid-Locker/source/butterknife/BindViews.java | rafael2025/RANSOMWARES | 6ac3c5d463bb1bedddde831bd9a20a442e29adc0 | [
"MIT"
] | 2 | 2021-07-23T12:45:45.000Z | 2022-03-11T19:33:44.000Z | 24 | 45 | 0.769231 | 12,405 | package butterknife;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BindViews {
int[] value();
}
|
3e1d42ec6670840a405cebbb7d17d615d8b9b932 | 7,873 | java | Java | components/camel-vertx/src/main/java/org/apache/camel/component/vertx/VertxConsumer.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | components/camel-vertx/src/main/java/org/apache/camel/component/vertx/VertxConsumer.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | 23 | 2021-03-23T00:01:38.000Z | 2022-01-04T16:47:34.000Z | components/camel-vertx/src/main/java/org/apache/camel/component/vertx/VertxConsumer.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | 15.257752 | 810 | 0.798171 | 12,406 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.component.vertx
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|vertx
package|;
end_package
begin_import
import|import
name|io
operator|.
name|vertx
operator|.
name|core
operator|.
name|Handler
import|;
end_import
begin_import
import|import
name|io
operator|.
name|vertx
operator|.
name|core
operator|.
name|eventbus
operator|.
name|Message
import|;
end_import
begin_import
import|import
name|io
operator|.
name|vertx
operator|.
name|core
operator|.
name|eventbus
operator|.
name|MessageConsumer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|AsyncCallback
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Exchange
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ExchangePattern
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Processor
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|support
operator|.
name|DefaultConsumer
import|;
end_import
begin_class
DECL|class|VertxConsumer
specifier|public
class|class
name|VertxConsumer
extends|extends
name|DefaultConsumer
block|{
DECL|field|endpoint
specifier|private
specifier|final
name|VertxEndpoint
name|endpoint
decl_stmt|;
DECL|field|messageConsumer
specifier|private
specifier|transient
name|MessageConsumer
name|messageConsumer
decl_stmt|;
DECL|field|handler
specifier|private
name|Handler
argument_list|<
name|Message
argument_list|<
name|Object
argument_list|>
argument_list|>
name|handler
init|=
operator|new
name|Handler
argument_list|<
name|Message
argument_list|<
name|Object
argument_list|>
argument_list|>
argument_list|()
block|{
specifier|public
name|void
name|handle
parameter_list|(
name|Message
name|event
parameter_list|)
block|{
name|onEventBusEvent
argument_list|(
name|event
argument_list|)
expr_stmt|;
block|}
block|}
decl_stmt|;
DECL|method|VertxConsumer (VertxEndpoint endpoint, Processor processor)
specifier|public
name|VertxConsumer
parameter_list|(
name|VertxEndpoint
name|endpoint
parameter_list|,
name|Processor
name|processor
parameter_list|)
block|{
name|super
argument_list|(
name|endpoint
argument_list|,
name|processor
argument_list|)
expr_stmt|;
name|this
operator|.
name|endpoint
operator|=
name|endpoint
expr_stmt|;
block|}
DECL|method|onEventBusEvent (final Message event)
specifier|protected
name|void
name|onEventBusEvent
parameter_list|(
specifier|final
name|Message
name|event
parameter_list|)
block|{
name|log
operator|.
name|debug
argument_list|(
literal|"onEvent {}"
argument_list|,
name|event
argument_list|)
expr_stmt|;
specifier|final
name|boolean
name|reply
init|=
name|event
operator|.
name|replyAddress
argument_list|()
operator|!=
literal|null
decl_stmt|;
specifier|final
name|Exchange
name|exchange
init|=
name|endpoint
operator|.
name|createExchange
argument_list|(
name|reply
condition|?
name|ExchangePattern
operator|.
name|InOut
else|:
name|ExchangePattern
operator|.
name|InOnly
argument_list|)
decl_stmt|;
name|exchange
operator|.
name|getIn
argument_list|()
operator|.
name|setBody
argument_list|(
name|event
operator|.
name|body
argument_list|()
argument_list|)
expr_stmt|;
try|try
block|{
name|getAsyncProcessor
argument_list|()
operator|.
name|process
argument_list|(
name|exchange
argument_list|,
operator|new
name|AsyncCallback
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|done
parameter_list|(
name|boolean
name|doneSync
parameter_list|)
block|{
if|if
condition|(
name|reply
condition|)
block|{
name|Object
name|body
init|=
name|exchange
operator|.
name|getMessage
argument_list|()
operator|.
name|getBody
argument_list|()
decl_stmt|;
if|if
condition|(
name|body
operator|!=
literal|null
condition|)
block|{
name|log
operator|.
name|debug
argument_list|(
literal|"Sending reply to: {} with body: {}"
argument_list|,
name|event
operator|.
name|replyAddress
argument_list|()
argument_list|,
name|body
argument_list|)
expr_stmt|;
name|event
operator|.
name|reply
argument_list|(
name|body
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|getExceptionHandler
argument_list|()
operator|.
name|handleException
argument_list|(
literal|"Error processing Vertx event: "
operator|+
name|event
argument_list|,
name|exchange
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|doStart ()
specifier|protected
name|void
name|doStart
parameter_list|()
throws|throws
name|Exception
block|{
if|if
condition|(
name|log
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|log
operator|.
name|debug
argument_list|(
literal|"Registering EventBus handler on address {}"
argument_list|,
name|endpoint
operator|.
name|getAddress
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|endpoint
operator|.
name|getEventBus
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|messageConsumer
operator|=
name|endpoint
operator|.
name|getEventBus
argument_list|()
operator|.
name|consumer
argument_list|(
name|endpoint
operator|.
name|getAddress
argument_list|()
argument_list|,
name|handler
argument_list|)
expr_stmt|;
block|}
name|super
operator|.
name|doStart
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|doStop ()
specifier|protected
name|void
name|doStop
parameter_list|()
throws|throws
name|Exception
block|{
if|if
condition|(
name|log
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|log
operator|.
name|debug
argument_list|(
literal|"Unregistering EventBus handler on address {}"
argument_list|,
name|endpoint
operator|.
name|getAddress
argument_list|()
argument_list|)
expr_stmt|;
block|}
try|try
block|{
if|if
condition|(
name|messageConsumer
operator|!=
literal|null
operator|&&
name|messageConsumer
operator|.
name|isRegistered
argument_list|()
condition|)
block|{
name|messageConsumer
operator|.
name|unregister
argument_list|()
expr_stmt|;
name|messageConsumer
operator|=
literal|null
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IllegalStateException
name|e
parameter_list|)
block|{
name|log
operator|.
name|warn
argument_list|(
literal|"EventBus already stopped on address {}"
argument_list|,
name|endpoint
operator|.
name|getAddress
argument_list|()
argument_list|)
expr_stmt|;
comment|// ignore if already stopped as vertx throws this exception if its already stopped etc.
comment|// unfortunately it does not provide an nicer api to know its state
block|}
name|super
operator|.
name|doStop
argument_list|()
expr_stmt|;
block|}
block|}
end_class
end_unit
|
3e1d45417b46f595b8b770c919c9c7206afd74bc | 2,223 | java | Java | flinketl/src/main/java/com/kedacom/flinketlgraph/accumulator/FileoffsetAccumulator.java | wangdxh/flink-job-compose | d95a62f4a5d7029a7b352b6335199f0f1c6b3041 | [
"Apache-2.0"
] | 8 | 2021-05-13T01:20:33.000Z | 2022-02-20T08:50:09.000Z | flinketl/src/main/java/com/kedacom/flinketlgraph/accumulator/FileoffsetAccumulator.java | adreamdee/flink-job-compose | d95a62f4a5d7029a7b352b6335199f0f1c6b3041 | [
"Apache-2.0"
] | 1 | 2021-05-20T02:42:56.000Z | 2021-05-20T02:42:56.000Z | flinketl/src/main/java/com/kedacom/flinketlgraph/accumulator/FileoffsetAccumulator.java | adreamdee/flink-job-compose | d95a62f4a5d7029a7b352b6335199f0f1c6b3041 | [
"Apache-2.0"
] | 1 | 2021-05-27T09:30:01.000Z | 2021-05-27T09:30:01.000Z | 32.217391 | 95 | 0.651822 | 12,407 | package com.kedacom.flinketlgraph.accumulator;
import com.kedacom.flinketlgraph.source.Fileoffset;
import org.apache.flink.api.common.accumulators.Accumulator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
public class FileoffsetAccumulator implements Accumulator<Fileoffset, ArrayList<Fileoffset>> {
private static Logger logger = LoggerFactory.getLogger(FileoffsetAccumulator.class);
private ArrayList<Fileoffset> fileoffsets = null;
public FileoffsetAccumulator(){
this(new ArrayList<Fileoffset>());
}
public FileoffsetAccumulator(ArrayList<Fileoffset> fileoffsets){
this.fileoffsets = new ArrayList<Fileoffset>(fileoffsets){
@Override
public String toString() {
String jsonStr = "no data";
ObjectMapper mapper = new ObjectMapper();
try {
jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) {
logger.error("{}", e.getMessage());
}
return jsonStr;
}
};
}
@Override
public void add(Fileoffset value) {
this.fileoffsets.add(value);
}
@Override
public ArrayList<Fileoffset> getLocalValue() {
return this.fileoffsets;
}
@Override
public void resetLocal() {
fileoffsets.clear();
}
@Override
public void merge(Accumulator<Fileoffset, ArrayList<Fileoffset>> other) {
this.fileoffsets.addAll(other.getLocalValue());
}
@Override
public Accumulator<Fileoffset, ArrayList<Fileoffset>> clone() {
ArrayList clones = new ArrayList();
try {
for (Fileoffset fileoffset : this.fileoffsets){
clones.add((Fileoffset)fileoffset.clone());
}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return new FileoffsetAccumulator(clones);
}
}
|
3e1d459bb7693566df422a8352cd6d9e556146e6 | 431 | java | Java | eureka-service/src/main/java/io/github/jdiemke/springcloud/EurekaServiceApplication.java | jdiemke/spring-cloud | db338b7523163114f435885946fd34664c119531 | [
"MIT"
] | null | null | null | eureka-service/src/main/java/io/github/jdiemke/springcloud/EurekaServiceApplication.java | jdiemke/spring-cloud | db338b7523163114f435885946fd34664c119531 | [
"MIT"
] | null | null | null | eureka-service/src/main/java/io/github/jdiemke/springcloud/EurekaServiceApplication.java | jdiemke/spring-cloud | db338b7523163114f435885946fd34664c119531 | [
"MIT"
] | null | null | null | 26.9375 | 74 | 0.842227 | 12,408 | package io.github.jdiemke.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServiceApplication.class, args);
}
}
|
3e1d45cdc367726691ac64080da9439168b07093 | 2,051 | java | Java | src/main/java/com/qa/ims/persistence/domain/Item.java | khanahoe-qa/IMS-Project | ba509f9cfbb192ac933af74faf7e4be852fd1bd0 | [
"MIT"
] | null | null | null | src/main/java/com/qa/ims/persistence/domain/Item.java | khanahoe-qa/IMS-Project | ba509f9cfbb192ac933af74faf7e4be852fd1bd0 | [
"MIT"
] | null | null | null | src/main/java/com/qa/ims/persistence/domain/Item.java | khanahoe-qa/IMS-Project | ba509f9cfbb192ac933af74faf7e4be852fd1bd0 | [
"MIT"
] | null | null | null | 18.477477 | 93 | 0.623598 | 12,409 | package com.qa.ims.persistence.domain;
public class Item {
private Long id;
private String name;
private Integer stock;
private Float price;
private Integer quantity;
public Item(String name, int stock, float price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public Item(long id, String name, int stock, float price) {
this.id = id;
this.name = name;
this.stock = stock;
this.price = price;
}
public Item(long id, int quantity) {
this.id = id;
this.quantity = quantity;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String toString() {
return "id: " + id + ", item name: " + name + ", price: " + price + ", in stock: " + stock;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (stock == null) {
if (other.stock != null)
return false;
} else if (!stock.equals(other.stock))
return false;
if (price == null) {
if (other.price != null)
return false;
} else if (!price.equals(other.price))
return false;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
return true;
}
}
|
3e1d45f632ab8175117c16a6f7c89bd0f3d0df01 | 499 | java | Java | AndroidActorModel/src/main/java/com/android/actormodel/exceptions/ActorRegistrationException.java | Ahmed-Adel-Ismail/AndroidActorModel | eea8d0f881c76972cae51704dc537e9115901bc4 | [
"Apache-2.0"
] | 11 | 2017-08-26T06:50:35.000Z | 2021-09-23T08:08:45.000Z | AndroidActorModel/src/main/java/com/android/actormodel/exceptions/ActorRegistrationException.java | Ahmed-Adel-Ismail/PlayGround | a8a6b09918ba1b7a9354f450c07eaab3686cf972 | [
"Apache-2.0"
] | null | null | null | AndroidActorModel/src/main/java/com/android/actormodel/exceptions/ActorRegistrationException.java | Ahmed-Adel-Ismail/PlayGround | a8a6b09918ba1b7a9354f450c07eaab3686cf972 | [
"Apache-2.0"
] | 3 | 2018-01-06T00:01:09.000Z | 2019-01-18T05:06:52.000Z | 23.761905 | 85 | 0.727455 | 12,410 | package com.android.actormodel.exceptions;
import com.android.actormodel.ActorSystem;
/**
* a {@link RuntimeException} that is thrown when the registration operation fails in
* {@link ActorSystem}
* <p>
* Created by Ahmed Adel Ismail on 8/6/2017.
*/
public class ActorRegistrationException extends RuntimeException {
public ActorRegistrationException(String message) {
super(message);
}
public ActorRegistrationException(Throwable cause) {
super(cause);
}
}
|
3e1d466bad036e0f3aa1e19388d5dceafcd937ae | 3,542 | java | Java | src/main/java/org/tradedigital/elasticcapturemethoddata/annotation/CaptureMethodDataAspect.java | Sellers-Community/elastic-capture-method-data | 0fe6052d9ef2104517c43137af90f4baf2869eef | [
"MIT"
] | null | null | null | src/main/java/org/tradedigital/elasticcapturemethoddata/annotation/CaptureMethodDataAspect.java | Sellers-Community/elastic-capture-method-data | 0fe6052d9ef2104517c43137af90f4baf2869eef | [
"MIT"
] | null | null | null | src/main/java/org/tradedigital/elasticcapturemethoddata/annotation/CaptureMethodDataAspect.java | Sellers-Community/elastic-capture-method-data | 0fe6052d9ef2104517c43137af90f4baf2869eef | [
"MIT"
] | null | null | null | 35.777778 | 127 | 0.761434 | 12,411 | package org.tradedigital.elasticcapturemethoddata.annotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import co.elastic.apm.api.ElasticApm;
import co.elastic.apm.api.Span;
@Aspect
@Component
public class CaptureMethodDataAspect {
public static final String METHOD_PARAMETERS = "parameters_";
public static final String METHOD_RESPONSE = "response";
@AfterReturning(pointcut = "@annotation(org.springframework.web.bind.annotation.ExceptionHandler)", returning = "returnValue")
public void sendException(JoinPoint joinPoint, Object returnValue) {
if(returnValue instanceof ResponseEntity) {
sendMethodResponse(returnValue, null);
}
}
@AfterReturning(pointcut = "@annotation(captureMethodData)", returning = "returnValue")
public void sendMethodData(JoinPoint joinPoint, Object returnValue, ElasticCaptureMethodData captureMethodData) {
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
if (isDataInconsistent(returnValue, captureMethodData, codeSignature)) {
return;
}
Span span = generateSpan(returnValue, codeSignature);
if (captureMethodData.parameters()) {
sendMethodParameters(joinPoint, codeSignature, span);
}
if (captureMethodData.response() && returnValue != null) {
sendMethodResponse(returnValue, span);
}
if (span != null) {
span.end();
}
}
private boolean isDataInconsistent(Object returnValue, ElasticCaptureMethodData captureMethodData,
CodeSignature codeSignature) {
boolean isSendingNothing = !captureMethodData.parameters() && !captureMethodData.response();
boolean isInconsistentResponseMode = returnValue == null
&& !captureMethodData.parameters() && captureMethodData.response();
boolean isInconsistentParamsMode = codeSignature.getParameterNames().length == 0
&& captureMethodData.parameters() && !captureMethodData.response();
boolean isInconsistentAllMode = returnValue == null && codeSignature.getParameterNames().length == 0
&& captureMethodData.parameters() && captureMethodData.response();
return isSendingNothing || isInconsistentResponseMode || isInconsistentParamsMode || isInconsistentAllMode;
}
private Span generateSpan(Object returnValue, CodeSignature codeSignature) {
Span span = null;
if (!(returnValue instanceof ResponseEntity)) {
span = ElasticApm.currentTransaction().startSpan();
span.setName(codeSignature.getDeclaringTypeName() + "#" + codeSignature.getName());
}
return span;
}
private void sendMethodParameters(JoinPoint joinPoint, CodeSignature codeSignature, Span span) {
for (int i = 0; i < codeSignature.getParameterNames().length; i++) {
if (span == null) {
ElasticApm.currentTransaction().addCustomContext(
METHOD_PARAMETERS + codeSignature.getParameterNames()[i],
new Gson().toJson(joinPoint.getArgs()[i]));
} else {
span.addLabel(METHOD_PARAMETERS + codeSignature.getParameterNames()[i],
new Gson().toJson(joinPoint.getArgs()[i]));
}
}
}
private void sendMethodResponse(Object returnValue, Span span) {
if (span == null) {
ElasticApm.currentTransaction().addCustomContext(METHOD_RESPONSE,
new Gson().toJson(((ResponseEntity) returnValue).getBody()));
} else {
span.addLabel(METHOD_RESPONSE, new Gson().toJson(returnValue));
}
}
}
|
3e1d46d2ddf95156373fafb2c4fe5afcf9f5f833 | 1,004 | java | Java | src/main/java/thaumicenergistics/client/particle/ParticleCrafting.java | 811Alex/ThaumicEnergistics | 51ff76b9013681966835f470d91fa622dcbf3945 | [
"MIT"
] | 2 | 2021-03-26T08:56:55.000Z | 2021-12-01T23:45:36.000Z | src/main/java/thaumicenergistics/client/particle/ParticleCrafting.java | Delfayne/ThaumicEnergistics | 70465a3a7a096782277e0560ef7dcc33f403963f | [
"MIT"
] | 6 | 2021-06-28T14:13:29.000Z | 2021-11-24T18:27:54.000Z | src/main/java/thaumicenergistics/client/particle/ParticleCrafting.java | Delfayne/ThaumicEnergistics | 70465a3a7a096782277e0560ef7dcc33f403963f | [
"MIT"
] | 2 | 2021-02-06T21:44:06.000Z | 2022-01-10T02:28:47.000Z | 30.424242 | 95 | 0.62749 | 12,412 | package thaumicenergistics.client.particle;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.awt.Color;
/**
* @author Alex811
*/
@SideOnly(Side.CLIENT)
public class ParticleCrafting extends ThEParticle {
protected static final Color[] colors = { // (ノ´ヮ´)ノ
new Color(112, 239, 253),
new Color(126, 150, 248),
new Color(234, 162, 110),
new Color(224, 92, 105),
new Color(234, 234, 100),
new Color(101, 238, 151)
};
public ParticleCrafting(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn) {
super("crafting", worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D);
setMaxAge(20);
multiplyVelocity(0.15F);
setScale(0.14F, 0.08F, 0.2F);
setAlpha(1.0F, 0.6F, 0.3F);
Color color = colors[this.rand.nextInt(6)];
setTint(color, color, 0.001F);
}
}
|
3e1d472fa99a4b9f7c601a7402b9e3d54c3c11ba | 49,704 | java | Java | src/main/java/edu/uiowa/smt/parser/antlr/SmtParser.java | mudathirmahgoub/pdl | 8dfaeb438e2fbc9de18fa0299e492adac0f269ae | [
"MIT"
] | null | null | null | src/main/java/edu/uiowa/smt/parser/antlr/SmtParser.java | mudathirmahgoub/pdl | 8dfaeb438e2fbc9de18fa0299e492adac0f269ae | [
"MIT"
] | null | null | null | src/main/java/edu/uiowa/smt/parser/antlr/SmtParser.java | mudathirmahgoub/pdl | 8dfaeb438e2fbc9de18fa0299e492adac0f269ae | [
"MIT"
] | null | null | null | 31.065 | 115 | 0.704269 | 12,413 | // Generated from Smt.g4 by ANTLR 4.7.2
package edu.uiowa.smt.parser.antlr;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class SmtParser extends Parser {
static { RuntimeMetaData.checkVersion("4.7.2", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9,
T__9=10, True=11, False=12, UnaryOperator=13, BinaryOperator=14, TernaryOperator=15,
MultiArityOperator=16, AtomPrefix=17, UninterpretedIntPrefix=18, Identifier=19,
IdentifierLetter=20, Integer=21, Digit=22, Comment=23, Whitespace=24;
public static final int
RULE_model = 0, RULE_sortDeclaration = 1, RULE_functionDefinition = 2,
RULE_argument = 3, RULE_sort = 4, RULE_setSort = 5, RULE_tupleSort = 6,
RULE_sortName = 7, RULE_arity = 8, RULE_functionName = 9, RULE_argumentName = 10,
RULE_expression = 11, RULE_unaryExpression = 12, RULE_binaryExpression = 13,
RULE_ternaryExpression = 14, RULE_multiArityExpression = 15, RULE_variable = 16,
RULE_constant = 17, RULE_boolConstant = 18, RULE_integerConstant = 19,
RULE_uninterpretedConstant = 20, RULE_emptySet = 21, RULE_getValue = 22;
private static String[] makeRuleNames() {
return new String[] {
"model", "sortDeclaration", "functionDefinition", "argument", "sort",
"setSort", "tupleSort", "sortName", "arity", "functionName", "argumentName",
"expression", "unaryExpression", "binaryExpression", "ternaryExpression",
"multiArityExpression", "variable", "constant", "boolConstant", "integerConstant",
"uninterpretedConstant", "emptySet", "getValue"
};
}
public static final String[] ruleNames = makeRuleNames();
private static String[] makeLiteralNames() {
return new String[] {
null, "'('", "'model'", "')'", "'declare-sort'", "'define-fun'", "'Set'",
"'Tuple'", "'-'", "'as'", "'emptyset'", "'true'", "'false'", null, null,
"'ite'", null, "'@uc_Atom_'", "'@uc_UninterpretedInt_'"
};
}
private static final String[] _LITERAL_NAMES = makeLiteralNames();
private static String[] makeSymbolicNames() {
return new String[] {
null, null, null, null, null, null, null, null, null, null, null, "True",
"False", "UnaryOperator", "BinaryOperator", "TernaryOperator", "MultiArityOperator",
"AtomPrefix", "UninterpretedIntPrefix", "Identifier", "IdentifierLetter",
"Integer", "Digit", "Comment", "Whitespace"
};
}
private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "Smt.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public SmtParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class ModelContext extends ParserRuleContext {
public List<SortDeclarationContext> sortDeclaration() {
return getRuleContexts(SortDeclarationContext.class);
}
public SortDeclarationContext sortDeclaration(int i) {
return getRuleContext(SortDeclarationContext.class,i);
}
public List<FunctionDefinitionContext> functionDefinition() {
return getRuleContexts(FunctionDefinitionContext.class);
}
public FunctionDefinitionContext functionDefinition(int i) {
return getRuleContext(FunctionDefinitionContext.class,i);
}
public ModelContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_model; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterModel(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitModel(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitModel(this);
else return visitor.visitChildren(this);
}
}
public final ModelContext model() throws RecognitionException {
ModelContext _localctx = new ModelContext(_ctx, getState());
enterRule(_localctx, 0, RULE_model);
int _la;
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(46);
match(T__0);
setState(47);
match(T__1);
setState(51);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,0,_ctx);
while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) {
if ( _alt==1 ) {
{
{
setState(48);
sortDeclaration();
}
}
}
setState(53);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,0,_ctx);
}
setState(57);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__0) {
{
{
setState(54);
functionDefinition();
}
}
setState(59);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(60);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SortDeclarationContext extends ParserRuleContext {
public SortNameContext sortName() {
return getRuleContext(SortNameContext.class,0);
}
public ArityContext arity() {
return getRuleContext(ArityContext.class,0);
}
public SortDeclarationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_sortDeclaration; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterSortDeclaration(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitSortDeclaration(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitSortDeclaration(this);
else return visitor.visitChildren(this);
}
}
public final SortDeclarationContext sortDeclaration() throws RecognitionException {
SortDeclarationContext _localctx = new SortDeclarationContext(_ctx, getState());
enterRule(_localctx, 2, RULE_sortDeclaration);
try {
enterOuterAlt(_localctx, 1);
{
setState(62);
match(T__0);
setState(63);
match(T__3);
setState(64);
sortName();
setState(65);
arity();
setState(66);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FunctionDefinitionContext extends ParserRuleContext {
public FunctionNameContext functionName() {
return getRuleContext(FunctionNameContext.class,0);
}
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public SortContext sort() {
return getRuleContext(SortContext.class,0);
}
public List<ArgumentContext> argument() {
return getRuleContexts(ArgumentContext.class);
}
public ArgumentContext argument(int i) {
return getRuleContext(ArgumentContext.class,i);
}
public FunctionDefinitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_functionDefinition; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterFunctionDefinition(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitFunctionDefinition(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitFunctionDefinition(this);
else return visitor.visitChildren(this);
}
}
public final FunctionDefinitionContext functionDefinition() throws RecognitionException {
FunctionDefinitionContext _localctx = new FunctionDefinitionContext(_ctx, getState());
enterRule(_localctx, 4, RULE_functionDefinition);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(68);
match(T__0);
setState(69);
match(T__4);
setState(70);
functionName();
setState(71);
match(T__0);
setState(75);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__0) {
{
{
setState(72);
argument();
}
}
setState(77);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(78);
match(T__2);
setState(84);
_errHandler.sync(this);
switch (_input.LA(1)) {
case T__0:
{
setState(79);
match(T__0);
setState(80);
sort();
setState(81);
match(T__2);
}
break;
case T__5:
case T__6:
case Identifier:
{
setState(83);
sort();
}
break;
default:
throw new NoViableAltException(this);
}
setState(86);
expression();
setState(87);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ArgumentContext extends ParserRuleContext {
public ArgumentNameContext argumentName() {
return getRuleContext(ArgumentNameContext.class,0);
}
public SortContext sort() {
return getRuleContext(SortContext.class,0);
}
public ArgumentContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_argument; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterArgument(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitArgument(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitArgument(this);
else return visitor.visitChildren(this);
}
}
public final ArgumentContext argument() throws RecognitionException {
ArgumentContext _localctx = new ArgumentContext(_ctx, getState());
enterRule(_localctx, 6, RULE_argument);
try {
enterOuterAlt(_localctx, 1);
{
setState(89);
match(T__0);
setState(90);
argumentName();
setState(91);
sort();
setState(92);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SortContext extends ParserRuleContext {
public SortNameContext sortName() {
return getRuleContext(SortNameContext.class,0);
}
public TupleSortContext tupleSort() {
return getRuleContext(TupleSortContext.class,0);
}
public SetSortContext setSort() {
return getRuleContext(SetSortContext.class,0);
}
public SortContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_sort; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterSort(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitSort(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitSort(this);
else return visitor.visitChildren(this);
}
}
public final SortContext sort() throws RecognitionException {
SortContext _localctx = new SortContext(_ctx, getState());
enterRule(_localctx, 8, RULE_sort);
try {
setState(97);
_errHandler.sync(this);
switch (_input.LA(1)) {
case Identifier:
enterOuterAlt(_localctx, 1);
{
setState(94);
sortName();
}
break;
case T__6:
enterOuterAlt(_localctx, 2);
{
setState(95);
tupleSort();
}
break;
case T__5:
enterOuterAlt(_localctx, 3);
{
setState(96);
setSort();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SetSortContext extends ParserRuleContext {
public SortContext sort() {
return getRuleContext(SortContext.class,0);
}
public SetSortContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_setSort; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterSetSort(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitSetSort(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitSetSort(this);
else return visitor.visitChildren(this);
}
}
public final SetSortContext setSort() throws RecognitionException {
SetSortContext _localctx = new SetSortContext(_ctx, getState());
enterRule(_localctx, 10, RULE_setSort);
try {
enterOuterAlt(_localctx, 1);
{
setState(99);
match(T__5);
setState(100);
match(T__0);
setState(101);
sort();
setState(102);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TupleSortContext extends ParserRuleContext {
public List<SortContext> sort() {
return getRuleContexts(SortContext.class);
}
public SortContext sort(int i) {
return getRuleContext(SortContext.class,i);
}
public TupleSortContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_tupleSort; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterTupleSort(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitTupleSort(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitTupleSort(this);
else return visitor.visitChildren(this);
}
}
public final TupleSortContext tupleSort() throws RecognitionException {
TupleSortContext _localctx = new TupleSortContext(_ctx, getState());
enterRule(_localctx, 12, RULE_tupleSort);
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(104);
match(T__6);
setState(106);
_errHandler.sync(this);
_alt = 1;
do {
switch (_alt) {
case 1:
{
{
setState(105);
sort();
}
}
break;
default:
throw new NoViableAltException(this);
}
setState(108);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,5,_ctx);
} while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER );
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SortNameContext extends ParserRuleContext {
public TerminalNode Identifier() { return getToken(SmtParser.Identifier, 0); }
public SortNameContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_sortName; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterSortName(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitSortName(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitSortName(this);
else return visitor.visitChildren(this);
}
}
public final SortNameContext sortName() throws RecognitionException {
SortNameContext _localctx = new SortNameContext(_ctx, getState());
enterRule(_localctx, 14, RULE_sortName);
try {
enterOuterAlt(_localctx, 1);
{
setState(110);
match(Identifier);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ArityContext extends ParserRuleContext {
public TerminalNode Integer() { return getToken(SmtParser.Integer, 0); }
public ArityContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_arity; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterArity(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitArity(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitArity(this);
else return visitor.visitChildren(this);
}
}
public final ArityContext arity() throws RecognitionException {
ArityContext _localctx = new ArityContext(_ctx, getState());
enterRule(_localctx, 16, RULE_arity);
try {
enterOuterAlt(_localctx, 1);
{
setState(112);
match(Integer);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FunctionNameContext extends ParserRuleContext {
public TerminalNode Identifier() { return getToken(SmtParser.Identifier, 0); }
public FunctionNameContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_functionName; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterFunctionName(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitFunctionName(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitFunctionName(this);
else return visitor.visitChildren(this);
}
}
public final FunctionNameContext functionName() throws RecognitionException {
FunctionNameContext _localctx = new FunctionNameContext(_ctx, getState());
enterRule(_localctx, 18, RULE_functionName);
try {
enterOuterAlt(_localctx, 1);
{
setState(114);
match(Identifier);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ArgumentNameContext extends ParserRuleContext {
public TerminalNode Identifier() { return getToken(SmtParser.Identifier, 0); }
public ArgumentNameContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_argumentName; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterArgumentName(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitArgumentName(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitArgumentName(this);
else return visitor.visitChildren(this);
}
}
public final ArgumentNameContext argumentName() throws RecognitionException {
ArgumentNameContext _localctx = new ArgumentNameContext(_ctx, getState());
enterRule(_localctx, 20, RULE_argumentName);
try {
enterOuterAlt(_localctx, 1);
{
setState(116);
match(Identifier);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ExpressionContext extends ParserRuleContext {
public ConstantContext constant() {
return getRuleContext(ConstantContext.class,0);
}
public VariableContext variable() {
return getRuleContext(VariableContext.class,0);
}
public UnaryExpressionContext unaryExpression() {
return getRuleContext(UnaryExpressionContext.class,0);
}
public BinaryExpressionContext binaryExpression() {
return getRuleContext(BinaryExpressionContext.class,0);
}
public TernaryExpressionContext ternaryExpression() {
return getRuleContext(TernaryExpressionContext.class,0);
}
public MultiArityExpressionContext multiArityExpression() {
return getRuleContext(MultiArityExpressionContext.class,0);
}
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public ExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_expression; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitExpression(this);
else return visitor.visitChildren(this);
}
}
public final ExpressionContext expression() throws RecognitionException {
ExpressionContext _localctx = new ExpressionContext(_ctx, getState());
enterRule(_localctx, 22, RULE_expression);
try {
setState(128);
_errHandler.sync(this);
switch (_input.LA(1)) {
case T__7:
case T__8:
case True:
case False:
case AtomPrefix:
case UninterpretedIntPrefix:
case Integer:
enterOuterAlt(_localctx, 1);
{
setState(118);
constant();
}
break;
case Identifier:
enterOuterAlt(_localctx, 2);
{
setState(119);
variable();
}
break;
case UnaryOperator:
enterOuterAlt(_localctx, 3);
{
setState(120);
unaryExpression();
}
break;
case BinaryOperator:
enterOuterAlt(_localctx, 4);
{
setState(121);
binaryExpression();
}
break;
case TernaryOperator:
enterOuterAlt(_localctx, 5);
{
setState(122);
ternaryExpression();
}
break;
case MultiArityOperator:
enterOuterAlt(_localctx, 6);
{
setState(123);
multiArityExpression();
}
break;
case T__0:
enterOuterAlt(_localctx, 7);
{
setState(124);
match(T__0);
setState(125);
expression();
setState(126);
match(T__2);
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class UnaryExpressionContext extends ParserRuleContext {
public TerminalNode UnaryOperator() { return getToken(SmtParser.UnaryOperator, 0); }
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public UnaryExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_unaryExpression; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterUnaryExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitUnaryExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitUnaryExpression(this);
else return visitor.visitChildren(this);
}
}
public final UnaryExpressionContext unaryExpression() throws RecognitionException {
UnaryExpressionContext _localctx = new UnaryExpressionContext(_ctx, getState());
enterRule(_localctx, 24, RULE_unaryExpression);
try {
enterOuterAlt(_localctx, 1);
{
setState(130);
match(UnaryOperator);
setState(131);
expression();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class BinaryExpressionContext extends ParserRuleContext {
public TerminalNode BinaryOperator() { return getToken(SmtParser.BinaryOperator, 0); }
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public BinaryExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_binaryExpression; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterBinaryExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitBinaryExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitBinaryExpression(this);
else return visitor.visitChildren(this);
}
}
public final BinaryExpressionContext binaryExpression() throws RecognitionException {
BinaryExpressionContext _localctx = new BinaryExpressionContext(_ctx, getState());
enterRule(_localctx, 26, RULE_binaryExpression);
try {
enterOuterAlt(_localctx, 1);
{
setState(133);
match(BinaryOperator);
setState(134);
expression();
setState(135);
expression();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TernaryExpressionContext extends ParserRuleContext {
public TerminalNode TernaryOperator() { return getToken(SmtParser.TernaryOperator, 0); }
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TernaryExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_ternaryExpression; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterTernaryExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitTernaryExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitTernaryExpression(this);
else return visitor.visitChildren(this);
}
}
public final TernaryExpressionContext ternaryExpression() throws RecognitionException {
TernaryExpressionContext _localctx = new TernaryExpressionContext(_ctx, getState());
enterRule(_localctx, 28, RULE_ternaryExpression);
try {
enterOuterAlt(_localctx, 1);
{
setState(137);
match(TernaryOperator);
setState(138);
expression();
setState(139);
expression();
setState(140);
expression();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class MultiArityExpressionContext extends ParserRuleContext {
public TerminalNode MultiArityOperator() { return getToken(SmtParser.MultiArityOperator, 0); }
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public MultiArityExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_multiArityExpression; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterMultiArityExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitMultiArityExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitMultiArityExpression(this);
else return visitor.visitChildren(this);
}
}
public final MultiArityExpressionContext multiArityExpression() throws RecognitionException {
MultiArityExpressionContext _localctx = new MultiArityExpressionContext(_ctx, getState());
enterRule(_localctx, 30, RULE_multiArityExpression);
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(142);
match(MultiArityOperator);
setState(144);
_errHandler.sync(this);
_alt = 1;
do {
switch (_alt) {
case 1:
{
{
setState(143);
expression();
}
}
break;
default:
throw new NoViableAltException(this);
}
setState(146);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,7,_ctx);
} while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER );
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class VariableContext extends ParserRuleContext {
public TerminalNode Identifier() { return getToken(SmtParser.Identifier, 0); }
public VariableContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_variable; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterVariable(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitVariable(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitVariable(this);
else return visitor.visitChildren(this);
}
}
public final VariableContext variable() throws RecognitionException {
VariableContext _localctx = new VariableContext(_ctx, getState());
enterRule(_localctx, 32, RULE_variable);
try {
enterOuterAlt(_localctx, 1);
{
setState(148);
match(Identifier);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ConstantContext extends ParserRuleContext {
public BoolConstantContext boolConstant() {
return getRuleContext(BoolConstantContext.class,0);
}
public IntegerConstantContext integerConstant() {
return getRuleContext(IntegerConstantContext.class,0);
}
public UninterpretedConstantContext uninterpretedConstant() {
return getRuleContext(UninterpretedConstantContext.class,0);
}
public EmptySetContext emptySet() {
return getRuleContext(EmptySetContext.class,0);
}
public ConstantContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_constant; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterConstant(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitConstant(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitConstant(this);
else return visitor.visitChildren(this);
}
}
public final ConstantContext constant() throws RecognitionException {
ConstantContext _localctx = new ConstantContext(_ctx, getState());
enterRule(_localctx, 34, RULE_constant);
try {
setState(154);
_errHandler.sync(this);
switch (_input.LA(1)) {
case True:
case False:
enterOuterAlt(_localctx, 1);
{
setState(150);
boolConstant();
}
break;
case T__7:
case Integer:
enterOuterAlt(_localctx, 2);
{
setState(151);
integerConstant();
}
break;
case AtomPrefix:
case UninterpretedIntPrefix:
enterOuterAlt(_localctx, 3);
{
setState(152);
uninterpretedConstant();
}
break;
case T__8:
enterOuterAlt(_localctx, 4);
{
setState(153);
emptySet();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class BoolConstantContext extends ParserRuleContext {
public TerminalNode True() { return getToken(SmtParser.True, 0); }
public TerminalNode False() { return getToken(SmtParser.False, 0); }
public BoolConstantContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_boolConstant; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterBoolConstant(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitBoolConstant(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitBoolConstant(this);
else return visitor.visitChildren(this);
}
}
public final BoolConstantContext boolConstant() throws RecognitionException {
BoolConstantContext _localctx = new BoolConstantContext(_ctx, getState());
enterRule(_localctx, 36, RULE_boolConstant);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(156);
_la = _input.LA(1);
if ( !(_la==True || _la==False) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class IntegerConstantContext extends ParserRuleContext {
public TerminalNode Integer() { return getToken(SmtParser.Integer, 0); }
public IntegerConstantContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_integerConstant; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterIntegerConstant(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitIntegerConstant(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitIntegerConstant(this);
else return visitor.visitChildren(this);
}
}
public final IntegerConstantContext integerConstant() throws RecognitionException {
IntegerConstantContext _localctx = new IntegerConstantContext(_ctx, getState());
enterRule(_localctx, 38, RULE_integerConstant);
try {
setState(161);
_errHandler.sync(this);
switch (_input.LA(1)) {
case T__7:
enterOuterAlt(_localctx, 1);
{
setState(158);
match(T__7);
setState(159);
match(Integer);
}
break;
case Integer:
enterOuterAlt(_localctx, 2);
{
setState(160);
match(Integer);
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class UninterpretedConstantContext extends ParserRuleContext {
public TerminalNode Integer() { return getToken(SmtParser.Integer, 0); }
public TerminalNode AtomPrefix() { return getToken(SmtParser.AtomPrefix, 0); }
public TerminalNode UninterpretedIntPrefix() { return getToken(SmtParser.UninterpretedIntPrefix, 0); }
public UninterpretedConstantContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_uninterpretedConstant; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterUninterpretedConstant(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitUninterpretedConstant(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitUninterpretedConstant(this);
else return visitor.visitChildren(this);
}
}
public final UninterpretedConstantContext uninterpretedConstant() throws RecognitionException {
UninterpretedConstantContext _localctx = new UninterpretedConstantContext(_ctx, getState());
enterRule(_localctx, 40, RULE_uninterpretedConstant);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(163);
_la = _input.LA(1);
if ( !(_la==AtomPrefix || _la==UninterpretedIntPrefix) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
setState(164);
match(Integer);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class EmptySetContext extends ParserRuleContext {
public SortContext sort() {
return getRuleContext(SortContext.class,0);
}
public EmptySetContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_emptySet; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterEmptySet(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitEmptySet(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitEmptySet(this);
else return visitor.visitChildren(this);
}
}
public final EmptySetContext emptySet() throws RecognitionException {
EmptySetContext _localctx = new EmptySetContext(_ctx, getState());
enterRule(_localctx, 42, RULE_emptySet);
try {
enterOuterAlt(_localctx, 1);
{
setState(166);
match(T__8);
setState(167);
match(T__9);
setState(168);
match(T__0);
setState(169);
match(T__5);
setState(170);
match(T__0);
setState(171);
sort();
setState(172);
match(T__2);
setState(173);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class GetValueContext extends ParserRuleContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public GetValueContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_getValue; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).enterGetValue(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SmtListener ) ((SmtListener)listener).exitGetValue(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof SmtVisitor ) return ((SmtVisitor<? extends T>)visitor).visitGetValue(this);
else return visitor.visitChildren(this);
}
}
public final GetValueContext getValue() throws RecognitionException {
GetValueContext _localctx = new GetValueContext(_ctx, getState());
enterRule(_localctx, 44, RULE_getValue);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(175);
match(T__0);
setState(181);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(176);
match(T__0);
setState(177);
expression();
setState(178);
expression();
setState(179);
match(T__2);
}
}
setState(183);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( _la==T__0 );
setState(185);
match(T__2);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\32\u00be\4\2\t\2"+
"\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+
"\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+
"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\3\2\3\2\3"+
"\2\7\2\64\n\2\f\2\16\2\67\13\2\3\2\7\2:\n\2\f\2\16\2=\13\2\3\2\3\2\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\7\4L\n\4\f\4\16\4O\13\4\3\4\3"+
"\4\3\4\3\4\3\4\3\4\5\4W\n\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5\3\6\3\6\3"+
"\6\5\6d\n\6\3\7\3\7\3\7\3\7\3\7\3\b\3\b\6\bm\n\b\r\b\16\bn\3\t\3\t\3\n"+
"\3\n\3\13\3\13\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\5\r\u0083"+
"\n\r\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3\20\3\21"+
"\3\21\6\21\u0093\n\21\r\21\16\21\u0094\3\22\3\22\3\23\3\23\3\23\3\23\5"+
"\23\u009d\n\23\3\24\3\24\3\25\3\25\3\25\5\25\u00a4\n\25\3\26\3\26\3\26"+
"\3\27\3\27\3\27\3\27\3\27\3\27\3\27\3\27\3\27\3\30\3\30\3\30\3\30\3\30"+
"\3\30\6\30\u00b8\n\30\r\30\16\30\u00b9\3\30\3\30\3\30\2\2\31\2\4\6\b\n"+
"\f\16\20\22\24\26\30\32\34\36 \"$&(*,.\2\4\3\2\r\16\3\2\23\24\2\u00b9"+
"\2\60\3\2\2\2\4@\3\2\2\2\6F\3\2\2\2\b[\3\2\2\2\nc\3\2\2\2\fe\3\2\2\2\16"+
"j\3\2\2\2\20p\3\2\2\2\22r\3\2\2\2\24t\3\2\2\2\26v\3\2\2\2\30\u0082\3\2"+
"\2\2\32\u0084\3\2\2\2\34\u0087\3\2\2\2\36\u008b\3\2\2\2 \u0090\3\2\2\2"+
"\"\u0096\3\2\2\2$\u009c\3\2\2\2&\u009e\3\2\2\2(\u00a3\3\2\2\2*\u00a5\3"+
"\2\2\2,\u00a8\3\2\2\2.\u00b1\3\2\2\2\60\61\7\3\2\2\61\65\7\4\2\2\62\64"+
"\5\4\3\2\63\62\3\2\2\2\64\67\3\2\2\2\65\63\3\2\2\2\65\66\3\2\2\2\66;\3"+
"\2\2\2\67\65\3\2\2\28:\5\6\4\298\3\2\2\2:=\3\2\2\2;9\3\2\2\2;<\3\2\2\2"+
"<>\3\2\2\2=;\3\2\2\2>?\7\5\2\2?\3\3\2\2\2@A\7\3\2\2AB\7\6\2\2BC\5\20\t"+
"\2CD\5\22\n\2DE\7\5\2\2E\5\3\2\2\2FG\7\3\2\2GH\7\7\2\2HI\5\24\13\2IM\7"+
"\3\2\2JL\5\b\5\2KJ\3\2\2\2LO\3\2\2\2MK\3\2\2\2MN\3\2\2\2NP\3\2\2\2OM\3"+
"\2\2\2PV\7\5\2\2QR\7\3\2\2RS\5\n\6\2ST\7\5\2\2TW\3\2\2\2UW\5\n\6\2VQ\3"+
"\2\2\2VU\3\2\2\2WX\3\2\2\2XY\5\30\r\2YZ\7\5\2\2Z\7\3\2\2\2[\\\7\3\2\2"+
"\\]\5\26\f\2]^\5\n\6\2^_\7\5\2\2_\t\3\2\2\2`d\5\20\t\2ad\5\16\b\2bd\5"+
"\f\7\2c`\3\2\2\2ca\3\2\2\2cb\3\2\2\2d\13\3\2\2\2ef\7\b\2\2fg\7\3\2\2g"+
"h\5\n\6\2hi\7\5\2\2i\r\3\2\2\2jl\7\t\2\2km\5\n\6\2lk\3\2\2\2mn\3\2\2\2"+
"nl\3\2\2\2no\3\2\2\2o\17\3\2\2\2pq\7\25\2\2q\21\3\2\2\2rs\7\27\2\2s\23"+
"\3\2\2\2tu\7\25\2\2u\25\3\2\2\2vw\7\25\2\2w\27\3\2\2\2x\u0083\5$\23\2"+
"y\u0083\5\"\22\2z\u0083\5\32\16\2{\u0083\5\34\17\2|\u0083\5\36\20\2}\u0083"+
"\5 \21\2~\177\7\3\2\2\177\u0080\5\30\r\2\u0080\u0081\7\5\2\2\u0081\u0083"+
"\3\2\2\2\u0082x\3\2\2\2\u0082y\3\2\2\2\u0082z\3\2\2\2\u0082{\3\2\2\2\u0082"+
"|\3\2\2\2\u0082}\3\2\2\2\u0082~\3\2\2\2\u0083\31\3\2\2\2\u0084\u0085\7"+
"\17\2\2\u0085\u0086\5\30\r\2\u0086\33\3\2\2\2\u0087\u0088\7\20\2\2\u0088"+
"\u0089\5\30\r\2\u0089\u008a\5\30\r\2\u008a\35\3\2\2\2\u008b\u008c\7\21"+
"\2\2\u008c\u008d\5\30\r\2\u008d\u008e\5\30\r\2\u008e\u008f\5\30\r\2\u008f"+
"\37\3\2\2\2\u0090\u0092\7\22\2\2\u0091\u0093\5\30\r\2\u0092\u0091\3\2"+
"\2\2\u0093\u0094\3\2\2\2\u0094\u0092\3\2\2\2\u0094\u0095\3\2\2\2\u0095"+
"!\3\2\2\2\u0096\u0097\7\25\2\2\u0097#\3\2\2\2\u0098\u009d\5&\24\2\u0099"+
"\u009d\5(\25\2\u009a\u009d\5*\26\2\u009b\u009d\5,\27\2\u009c\u0098\3\2"+
"\2\2\u009c\u0099\3\2\2\2\u009c\u009a\3\2\2\2\u009c\u009b\3\2\2\2\u009d"+
"%\3\2\2\2\u009e\u009f\t\2\2\2\u009f\'\3\2\2\2\u00a0\u00a1\7\n\2\2\u00a1"+
"\u00a4\7\27\2\2\u00a2\u00a4\7\27\2\2\u00a3\u00a0\3\2\2\2\u00a3\u00a2\3"+
"\2\2\2\u00a4)\3\2\2\2\u00a5\u00a6\t\3\2\2\u00a6\u00a7\7\27\2\2\u00a7+"+
"\3\2\2\2\u00a8\u00a9\7\13\2\2\u00a9\u00aa\7\f\2\2\u00aa\u00ab\7\3\2\2"+
"\u00ab\u00ac\7\b\2\2\u00ac\u00ad\7\3\2\2\u00ad\u00ae\5\n\6\2\u00ae\u00af"+
"\7\5\2\2\u00af\u00b0\7\5\2\2\u00b0-\3\2\2\2\u00b1\u00b7\7\3\2\2\u00b2"+
"\u00b3\7\3\2\2\u00b3\u00b4\5\30\r\2\u00b4\u00b5\5\30\r\2\u00b5\u00b6\7"+
"\5\2\2\u00b6\u00b8\3\2\2\2\u00b7\u00b2\3\2\2\2\u00b8\u00b9\3\2\2\2\u00b9"+
"\u00b7\3\2\2\2\u00b9\u00ba\3\2\2\2\u00ba\u00bb\3\2\2\2\u00bb\u00bc\7\5"+
"\2\2\u00bc/\3\2\2\2\r\65;MVcn\u0082\u0094\u009c\u00a3\u00b9";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} |
3e1d474a3488663f83047859e388fbce60a60e87 | 784 | java | Java | src/main/java/com/seleniumtests/core/IContextAttributeListener.java | pradeep26apr/sampleimport | af57ef05c43959b564aed3040479d0842851c1cc | [
"Apache-2.0"
] | 1 | 2019-07-22T16:21:20.000Z | 2019-07-22T16:21:20.000Z | src/main/java/com/seleniumtests/core/IContextAttributeListener.java | sanjeeth-07/seleniumtestsframework | a75f63f10e9b61f0df6e5252d77f775693e3483a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/seleniumtests/core/IContextAttributeListener.java | sanjeeth-07/seleniumtestsframework | a75f63f10e9b61f0df6e5252d77f775693e3483a | [
"Apache-2.0"
] | 2 | 2017-06-06T08:27:31.000Z | 2017-06-06T17:32:38.000Z | 37.333333 | 77 | 0.774235 | 12,414 | /*
* Copyright 2015 www.seleniumtests.com
* 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.seleniumtests.core;
import org.testng.ITestContext;
public interface IContextAttributeListener {
void load(ITestContext testNGCtx, SeleniumTestsContext seleniumTestsCtx);
}
|
3e1d47841c4b4faaad93496765ba5c3bec630e00 | 7,062 | java | Java | catalog-rest-service/src/main/java/org/openmetadata/catalog/jdbi3/PipelineServiceRepository.java | zionrubin/OpenMetadata | 09634e1a79960648b46827327435044c4f03548b | [
"Apache-2.0"
] | null | null | null | catalog-rest-service/src/main/java/org/openmetadata/catalog/jdbi3/PipelineServiceRepository.java | zionrubin/OpenMetadata | 09634e1a79960648b46827327435044c4f03548b | [
"Apache-2.0"
] | null | null | null | catalog-rest-service/src/main/java/org/openmetadata/catalog/jdbi3/PipelineServiceRepository.java | zionrubin/OpenMetadata | 09634e1a79960648b46827327435044c4f03548b | [
"Apache-2.0"
] | null | null | null | 33.15493 | 129 | 0.750779 | 12,415 | /*
* 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.openmetadata.catalog.jdbi3;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.jdbi.v3.sqlobject.transaction.Transaction;
import org.openmetadata.catalog.Entity;
import org.openmetadata.catalog.entity.services.PipelineService;
import org.openmetadata.catalog.exception.EntityNotFoundException;
import org.openmetadata.catalog.resources.services.pipeline.PipelineServiceResource;
import org.openmetadata.catalog.type.ChangeDescription;
import org.openmetadata.catalog.type.EntityReference;
import org.openmetadata.catalog.type.Schedule;
import org.openmetadata.catalog.type.TagLabel;
import org.openmetadata.catalog.util.EntityInterface;
import org.openmetadata.catalog.util.EntityUtil;
import org.openmetadata.catalog.util.EntityUtil.Fields;
import org.openmetadata.catalog.util.JsonUtils;
import java.io.IOException;
import java.net.URI;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import static org.openmetadata.catalog.exception.CatalogExceptionMessage.entityNotFound;
public class PipelineServiceRepository extends EntityRepository<PipelineService> {
private final CollectionDAO dao;
public PipelineServiceRepository(CollectionDAO dao) {
super(PipelineServiceResource.COLLECTION_PATH, Entity.PIPELINE_SERVICE, PipelineService.class,
dao.pipelineServiceDAO(), dao, Fields.EMPTY_FIELDS, Fields.EMPTY_FIELDS);
this.dao = dao;
}
@Transaction
public void delete(UUID id) {
if (dao.pipelineServiceDAO().delete(id) <= 0) {
throw EntityNotFoundException.byMessage(entityNotFound(Entity.PIPELINE_SERVICE, id));
}
dao.relationshipDAO().deleteAll(id.toString());
}
@Override
public PipelineService setFields(PipelineService entity, Fields fields) throws IOException, ParseException {
return entity;
}
@Override
public void restorePatchAttributes(PipelineService original, PipelineService updated) throws IOException,
ParseException {
}
@Override
public EntityInterface<PipelineService> getEntityInterface(PipelineService entity) {
return new PipelineServiceEntityInterface(entity);
}
@Override
public void prepare(PipelineService entity) throws IOException {
EntityUtil.validateIngestionSchedule(entity.getIngestionSchedule());
}
@Override
public void storeEntity(PipelineService service, boolean update) throws IOException {
if (update) {
dao.pipelineServiceDAO().update(service.getId(), JsonUtils.pojoToJson(service));
} else {
dao.pipelineServiceDAO().insert(service);
}
}
@Override
public void storeRelationships(PipelineService entity) throws IOException {
}
@Override
public EntityUpdater getUpdater(PipelineService original, PipelineService updated, boolean patchOperation) throws IOException {
return new PipelineServiceUpdater(original, updated, patchOperation);
}
public static class PipelineServiceEntityInterface implements EntityInterface<PipelineService> {
private final PipelineService entity;
public PipelineServiceEntityInterface(PipelineService entity) {
this.entity = entity;
}
@Override
public UUID getId() {
return entity.getId();
}
@Override
public String getDescription() {
return entity.getDescription();
}
@Override
public String getDisplayName() {
return entity.getDisplayName();
}
@Override
public EntityReference getOwner() { return null; }
@Override
public String getFullyQualifiedName() { return entity.getName(); }
@Override
public List<TagLabel> getTags() { return null; }
@Override
public Double getVersion() { return entity.getVersion(); }
@Override
public String getUpdatedBy() { return entity.getUpdatedBy(); }
@Override
public Date getUpdatedAt() { return entity.getUpdatedAt(); }
@Override
public URI getHref() { return entity.getHref(); }
@Override
public List<EntityReference> getFollowers() {
throw new UnsupportedOperationException("Pipeline service does not support followers");
}
@Override
public ChangeDescription getChangeDescription() { return entity.getChangeDescription(); }
@Override
public EntityReference getEntityReference() {
return new EntityReference().withId(getId()).withName(getFullyQualifiedName()).withDescription(getDescription())
.withDisplayName(getDisplayName()).withType(Entity.PIPELINE_SERVICE);
}
@Override
public PipelineService getEntity() { return entity; }
@Override
public void setId(UUID id) { entity.setId(id); }
@Override
public void setDescription(String description) {
entity.setDescription(description);
}
@Override
public void setDisplayName(String displayName) {
entity.setDisplayName(displayName);
}
@Override
public void setUpdateDetails(String updatedBy, Date updatedAt) {
entity.setUpdatedBy(updatedBy);
entity.setUpdatedAt(updatedAt);
}
@Override
public void setChangeDescription(Double newVersion, ChangeDescription changeDescription) {
entity.setVersion(newVersion);
entity.setChangeDescription(changeDescription);
}
@Override
public void setOwner(EntityReference owner) { }
@Override
public PipelineService withHref(URI href) { return entity.withHref(href); }
@Override
public void setTags(List<TagLabel> tags) { }
}
public class PipelineServiceUpdater extends EntityUpdater {
public PipelineServiceUpdater(PipelineService original, PipelineService updated, boolean patchOperation) {
super(original, updated, patchOperation);
}
@Override
public void entitySpecificUpdate() throws IOException {
recordChange("pipelineUrl", original.getEntity().getPipelineUrl(), updated.getEntity().getPipelineUrl());
updateIngestionSchedule();
}
private void updateIngestionSchedule() throws JsonProcessingException {
Schedule origSchedule = original.getEntity().getIngestionSchedule();
Schedule updatedSchedule = updated.getEntity().getIngestionSchedule();
recordChange("ingestionSchedule", origSchedule, updatedSchedule, true);
}
}
} |
3e1d47a3a6d6f42e5fc06fd1b130838b12e54ad9 | 3,451 | java | Java | spring-boot-examples/spring-boot-excel/src/test/java/com/yin/springbootexcel/util/DataUtil.java | yinfuquan/spring-boot-examples | 702cbf46ce894f499f2b4727c85c5e99c27f5690 | [
"Apache-2.0"
] | null | null | null | spring-boot-examples/spring-boot-excel/src/test/java/com/yin/springbootexcel/util/DataUtil.java | yinfuquan/spring-boot-examples | 702cbf46ce894f499f2b4727c85c5e99c27f5690 | [
"Apache-2.0"
] | 1 | 2022-02-09T22:27:56.000Z | 2022-02-09T22:27:56.000Z | spring-boot-examples/spring-boot-excel/src/test/java/com/yin/springbootexcel/util/DataUtil.java | yinfuquan/spring-boot-examples | 702cbf46ce894f499f2b4727c85c5e99c27f5690 | [
"Apache-2.0"
] | null | null | null | 36.712766 | 82 | 0.621559 | 12,416 | package com.yin.springbootexcel.util;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.TableStyle;
import com.yin.springbootexcel.model.WriteModel;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DataUtil {
public static List<List<Object>> createTestListObject() {
List<List<Object>> object = new ArrayList<List<Object>>();
for (int i = 0; i < 1000; i++) {
List<Object> da = new ArrayList<Object>();
da.add("字符串"+i);
da.add(Long.valueOf(187837834l+i));
da.add(Integer.valueOf(2233+i));
da.add(Double.valueOf(2233.00+i));
da.add(Float.valueOf(2233.0f+i));
da.add(new Date());
da.add(new BigDecimal("3434343433554545"+i));
da.add(Short.valueOf((short)i));
object.add(da);
}
return object;
}
public static List<List<String>> createTestListStringHead(){
//写sheet3 模型上没有注解,表头数据动态传入
List<List<String>> head = new ArrayList<List<String>>();
List<String> headCoulumn1 = new ArrayList<String>();
List<String> headCoulumn2 = new ArrayList<String>();
List<String> headCoulumn3 = new ArrayList<String>();
List<String> headCoulumn4 = new ArrayList<String>();
List<String> headCoulumn5 = new ArrayList<String>();
headCoulumn1.add("第一列");headCoulumn1.add("第一列");headCoulumn1.add("第一列");
headCoulumn2.add("第一列");headCoulumn2.add("第一列");headCoulumn2.add("第一列");
headCoulumn3.add("第二列");headCoulumn3.add("第二列");headCoulumn3.add("第二列");
headCoulumn4.add("第三列");headCoulumn4.add("第三列2");headCoulumn4.add("第三列2");
headCoulumn5.add("第一列");headCoulumn5.add("第3列");headCoulumn5.add("第4列");
head.add(headCoulumn1);
head.add(headCoulumn2);
head.add(headCoulumn3);
head.add(headCoulumn4);
head.add(headCoulumn5);
return head;
}
public static List<WriteModel> createTestListJavaMode(){
List<WriteModel> model1s = new ArrayList<WriteModel>();
for (int i = 0; i <10000 ; i++) {
WriteModel model1 = new WriteModel();
model1.setP1("第一列,第行");
model1.setP2("121212jjj");
model1.setP3(33+i);
model1.setP4(44);
model1.setP5("555");
model1.setP6(666.2f);
model1.setP7(new BigDecimal("454545656343434"+i));
model1.setP8(new Date());
model1.setP9("llll9999>&&&&&6666^^^^");
model1.setP10(1111.77+i);
model1s.add(model1);
}
return model1s;
}
public static TableStyle createTableStyle() {
TableStyle tableStyle = new TableStyle();
Font headFont = new Font();
headFont.setBold(true);
headFont.setFontHeightInPoints((short)22);
headFont.setFontName("楷体");
tableStyle.setTableHeadFont(headFont);
tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE);
Font contentFont = new Font();
contentFont.setBold(true);
contentFont.setFontHeightInPoints((short)22);
contentFont.setFontName("黑体");
tableStyle.setTableContentFont(contentFont);
tableStyle.setTableContentBackGroundColor(IndexedColors.GREEN);
return tableStyle;
}
}
|
3e1d47f21ac79f5c7e840d6c0de8aec5b371b540 | 4,976 | java | Java | src/test/java/de/vandermeer/asciilist/itemize/Test_ItemizeList.java | vdmeer/asciilist | 3a2d6a0907b90c8ecab0f0430b37a46f0c020ba7 | [
"Apache-2.0"
] | 5 | 2017-12-01T09:50:52.000Z | 2021-12-24T06:02:51.000Z | src/test/java/de/vandermeer/asciilist/itemize/Test_ItemizeList.java | vdmeer/asciilist | 3a2d6a0907b90c8ecab0f0430b37a46f0c020ba7 | [
"Apache-2.0"
] | null | null | null | src/test/java/de/vandermeer/asciilist/itemize/Test_ItemizeList.java | vdmeer/asciilist | 3a2d6a0907b90c8ecab0f0430b37a46f0c020ba7 | [
"Apache-2.0"
] | null | null | null | 30.944099 | 86 | 0.673424 | 12,417 | /* Copyright 2016 Sven van der Meer <ychag@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.vandermeer.asciilist.itemize;
import org.apache.commons.lang3.text.StrBuilder;
import org.junit.Test;
import de.svenjacobs.loremipsum.LoremIpsum;
import de.vandermeer.asciithemes.a7.A7_ItemizeLists;
import de.vandermeer.asciithemes.u8.U8_ItemizeLists;
import de.vandermeer.skb.interfaces.strategies.collections.sortedset.TreeSetStrategy;
import de.vandermeer.skb.interfaces.transformers.textformat.TextAlignment;
/**
* Tests for {@link ItemizeList}.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
* @version v0.0.5 build 170502 (02-May-17) for Java 1.8
* @since v0.1.0
*/
public class Test_ItemizeList {
@Test
public void test_me(){
ItemizeList il4 = new ItemizeList();
il4.addItem("l4 i1");
il4.addItem("l4 i2");
ItemizeList il3 = new ItemizeList();
il3.addItem("l3 i1");
il3.addItem("l3 i2");
il3.addItem("l3 i3", il4);
ItemizeList il2 = new ItemizeList();
il2.addItem("l2 i1");
il2.addItem("l2 i2");
il2.addItem("l2 i3", il3);
ItemizeList il = new ItemizeList();
il.addItem("line 1");
il.addItem(new StrBuilder().append("line 2"));
il.addItem("item with list", il2);
il.addItem(new LoremIpsum().getWords(10));
// il.getContext().setStyle(A7_ItemizeLists.allStar());
il.getContext().setStyle(A7_ItemizeLists.allStarIncremental());
// il.getContext().setWidth(13);
System.err.println(il.render());
}
@Test
public void test_Itemize(){
ItemizeList list = new ItemizeList();
list.getContext().setAlignment(TextAlignment.LEFT);
list.addItem(new LoremIpsum().getWords(10));
list.addItem("item 2");
list.addItem("item 3");
list.getContext().setWidth(15);
String rend = list.render();
System.out.println(rend);
list.getContext().setLabelLeftMargin(5);
System.out.println("\n" + list.render());
list.getContext().init();
list.getContext().setLabelRightMargin(4);
System.out.println("\n" + list.render());
list.getContext().init();
list.getContext().setLeftLabelString(">>");
list.getContext().setRightLabelString("<<");
System.out.println("\n" + list.render());
list.getContext().init();
list.getContext().setStyle(U8_ItemizeLists.htmlLike());
System.out.println("\n" + list.render());
}
@Test
public void test_List(){
ItemizeList list = new ItemizeList();
list.addItem("item 1");
list.addItem("item 2");
list.addItem("item 3");
System.out.println(list.render() + "\n");
list.getContext().setTextLeftMargin(4);
System.out.println(list.render() + "\n");
list.getContext().setStyle(A7_ItemizeLists.allStarIncremental());
list.getContext().setTextLeftMargin(1);
ItemizeList list2 = new ItemizeList();
list2.addItem("two item one");
list2.addItem("two item two");
list2.addItem("two item three four five six seven eight nine ten");
list.addItem("item 4 w/child", list2);
System.out.println(list.render() + "\n");
list.getContext().setStyle(U8_ItemizeLists.htmlLike());
System.out.println(list.render() + "\n");
list.getContext().setWidth(19);
System.out.println(list.render() + "\n");
}
@Test
public void test_19(){
ItemizeList il = new ItemizeList();
il.addItem("il 1 item 1 some text");
il.addItem("il 1 item 2 some text");
il.addItem("il 1 item 3 some text");
ItemizeList il2 = new ItemizeList();
il2.addItem("il 2 item 1 text");
il2.addItem("il 2 item 2 text");
il2.addItem("il 2 item 3 text");
il.addItem("il 1 item 4 some text", il2);
il.getContext().setStyle(A7_ItemizeLists.allStarIncremental());
il.getContext().setWidth(18);
System.out.println(il.render() + "\n");
}
@Test
public void test_Themes(){
ItemizeList il = new ItemizeList();
il.addItem("il 1 item 1 some text");
il.addItem("il 1 item 2 some text");
il.addItem("il 1 item 3 some text");
il.applyTheme(Il_Themes.latex());
System.out.println(il.render() + "\n");
}
@Test
public void test_Sorting(){
ItemizeList il = new ItemizeList(TreeSetStrategy.create());
il.addItem("il 1 item 4 some text");
il.addItem("il 1 item 1 some text");
il.addItem("il 1 item 3 some text");
il.addItem("il 1 item 2 some text");
il.applyTheme(Il_Themes.latex());
System.out.println(il.render() + "\n");
}
}
|
3e1d4824519818fc40138802179f5d14bad739a8 | 802 | java | Java | tomcat_files/6.0.0/JspTag.java | plumer/codana | 8c9e95614265005ae4e49527eed24d6a8bbdd5fc | [
"MIT"
] | 1 | 2015-04-02T14:58:51.000Z | 2015-04-02T14:58:51.000Z | tomcat_files/6.0.0/JspTag.java | plumer/codana | 8c9e95614265005ae4e49527eed24d6a8bbdd5fc | [
"MIT"
] | null | null | null | tomcat_files/6.0.0/JspTag.java | plumer/codana | 8c9e95614265005ae4e49527eed24d6a8bbdd5fc | [
"MIT"
] | null | null | null | 30.846154 | 74 | 0.745636 | 12,418 | /*
* Copyright 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.
*/
package javax.servlet.jsp.tagext;
/**
* Serves as a base class for Tag and SimpleTag.
* This is mostly for organizational and type-safety purposes.
*
* @since 2.0
*/
public interface JspTag {
}
|
3e1d48d946dd57fcd1e0b90e0b725bf9d3cb03a5 | 2,533 | java | Java | modules/core-module/src/main/java/org/simplejavamail/api/internal/clisupport/model/CliDeclaredOptionSpec.java | frechett/simple-java-mail | dd11ad9c1fa48a38886684be43e93f600caf497d | [
"Apache-2.0"
] | 1,043 | 2015-04-24T14:15:07.000Z | 2022-03-30T20:45:24.000Z | modules/core-module/src/main/java/org/simplejavamail/api/internal/clisupport/model/CliDeclaredOptionSpec.java | frechett/simple-java-mail | dd11ad9c1fa48a38886684be43e93f600caf497d | [
"Apache-2.0"
] | 368 | 2015-04-29T06:03:43.000Z | 2022-03-27T15:31:50.000Z | modules/core-module/src/main/java/org/simplejavamail/api/internal/clisupport/model/CliDeclaredOptionSpec.java | frechett/simple-java-mail | dd11ad9c1fa48a38886684be43e93f600caf497d | [
"Apache-2.0"
] | 271 | 2015-04-24T14:39:32.000Z | 2022-03-14T16:53:09.000Z | 29.114943 | 112 | 0.782077 | 12,419 | package org.simplejavamail.api.internal.clisupport.model;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class CliDeclaredOptionSpec implements Comparable<CliDeclaredOptionSpec> {
@NotNull
private final String name;
@NotNull
private final List<String> description;
@NotNull
private final CliBuilderApiType fromBuilderApiType;
@NotNull
private final List<CliDeclaredOptionValue> possibleOptionValues;
@NotNull
private final Method sourceMethod;
public CliDeclaredOptionSpec(@NotNull String name, @NotNull List<String> description,
@NotNull List<CliDeclaredOptionValue> possibleArguments, @NotNull CliBuilderApiType fromBuilderApiType,
@NotNull Method sourceMethod) {
this.name = name;
this.description = Collections.unmodifiableList(description);
this.fromBuilderApiType = fromBuilderApiType;
this.possibleOptionValues = Collections.unmodifiableList(possibleArguments);
this.sourceMethod = sourceMethod;
}
@Override
public String toString() {
return name;
}
public boolean applicableToRootCommand(Collection<CliBuilderApiType> compatibleBuilderApiTypes) {
return compatibleBuilderApiTypes.contains(fromBuilderApiType);
}
public List<CliDeclaredOptionValue> getMandatoryOptionValues() {
List<CliDeclaredOptionValue> mandatoryOptionValues = new ArrayList<>();
for (CliDeclaredOptionValue optionValue : possibleOptionValues) {
if (optionValue.isRequired()) {
mandatoryOptionValues.add(optionValue);
}
}
return mandatoryOptionValues;
}
@Override
@SuppressFBWarnings("EQ_COMPARETO_USE_OBJECT_EQUALS")
public int compareTo(@NotNull CliDeclaredOptionSpec other) {
int prefixOrder = getNamePrefix().compareTo(other.getNamePrefix());
return prefixOrder != 0 ? prefixOrder : getNameAfterPrefix().compareTo(other.getNameAfterPrefix());
}
private String getNamePrefix() {
return getName().substring(0, getName().indexOf(":"));
}
private String getNameAfterPrefix() {
return getName().substring(getName().indexOf(":"));
}
@NotNull
public String getName() {
return name;
}
@NotNull
public List<String> getDescription() {
return description;
}
@NotNull
public List<CliDeclaredOptionValue> getPossibleOptionValues() {
return possibleOptionValues;
}
@NotNull
public Method getSourceMethod() {
return sourceMethod;
}
} |
3e1d497b51efd52226abcf9e516395044bbe2853 | 9,754 | java | Java | test/src/main/java/org/apache/accumulo/test/performance/ContinuousIngest.java | DonResnik/accumulo | 89c94b33a10e9b8f574f0927d90ba6f23ef3610d | [
"Apache-2.0"
] | 2 | 2021-06-02T14:31:16.000Z | 2021-07-23T12:54:41.000Z | test/src/main/java/org/apache/accumulo/test/performance/ContinuousIngest.java | DonResnik/accumulo | 89c94b33a10e9b8f574f0927d90ba6f23ef3610d | [
"Apache-2.0"
] | 1 | 2022-01-13T15:20:39.000Z | 2022-01-13T15:20:39.000Z | test/src/main/java/org/apache/accumulo/test/performance/ContinuousIngest.java | DonResnik/accumulo | 89c94b33a10e9b8f574f0927d90ba6f23ef3610d | [
"Apache-2.0"
] | 1 | 2021-06-14T14:49:08.000Z | 2021-06-14T14:49:08.000Z | 35.728938 | 100 | 0.66055 | 12,420 | /*
* 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.accumulo.test.performance;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import org.apache.accumulo.core.cli.ClientOpts;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.core.trace.TraceUtil;
import org.apache.accumulo.core.util.FastFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.htrace.TraceScope;
import org.apache.htrace.wrappers.TraceProxy;
import com.beust.jcommander.Parameter;
public class ContinuousIngest {
private static final byte[] EMPTY_BYTES = new byte[0];
private static List<ColumnVisibility> visibilities;
private static void initVisibilities(ContinuousOpts opts) throws Exception {
if (opts.visFile == null) {
visibilities = Collections.singletonList(new ColumnVisibility());
return;
}
visibilities = new ArrayList<>();
FileSystem fs = FileSystem.get(new Configuration());
BufferedReader in =
new BufferedReader(new InputStreamReader(fs.open(new Path(opts.visFile)), UTF_8));
String line;
while ((line = in.readLine()) != null) {
visibilities.add(new ColumnVisibility(line));
}
in.close();
}
private static ColumnVisibility getVisibility(Random rand) {
return visibilities.get(rand.nextInt(visibilities.size()));
}
static class TestOpts extends ClientOpts {
@Parameter(names = "--table", description = "table to use")
String tableName = "ci";
}
public static void main(String[] args) throws Exception {
ContinuousOpts opts = new ContinuousOpts();
TestOpts clientOpts = new TestOpts();
try (TraceScope clientSpan =
clientOpts.parseArgsAndTrace(ContinuousIngest.class.getName(), args, opts)) {
initVisibilities(opts);
if (opts.min < 0 || opts.max < 0 || opts.max <= opts.min) {
throw new IllegalArgumentException("bad min and max");
}
try (AccumuloClient client = Accumulo.newClient().from(clientOpts.getClientProps()).build()) {
if (!client.tableOperations().exists(clientOpts.tableName)) {
throw new TableNotFoundException(null, clientOpts.tableName,
"Consult the README and create the table before starting ingest.");
}
BatchWriter bw = client.createBatchWriter(clientOpts.tableName);
bw = TraceProxy.trace(bw, TraceUtil.countSampler(1024));
Random r = new SecureRandom();
byte[] ingestInstanceId = UUID.randomUUID().toString().getBytes(UTF_8);
System.out.printf("UUID %d %s%n", System.currentTimeMillis(),
new String(ingestInstanceId, UTF_8));
long count = 0;
final int flushInterval = 1000000;
final int maxDepth = 25;
// always want to point back to flushed data. This way the previous item should
// always exist in accumulo when verifying data. To do this make insert N point
// back to the row from insert (N - flushInterval). The array below is used to keep
// track of this.
long[] prevRows = new long[flushInterval];
long[] firstRows = new long[flushInterval];
int[] firstColFams = new int[flushInterval];
int[] firstColQuals = new int[flushInterval];
long lastFlushTime = System.currentTimeMillis();
out: while (true) {
// generate first set of nodes
ColumnVisibility cv = getVisibility(r);
for (int index = 0; index < flushInterval; index++) {
long rowLong = genLong(opts.min, opts.max, r);
prevRows[index] = rowLong;
firstRows[index] = rowLong;
int cf = r.nextInt(opts.maxColF);
int cq = r.nextInt(opts.maxColQ);
firstColFams[index] = cf;
firstColQuals[index] = cq;
Mutation m =
genMutation(rowLong, cf, cq, cv, ingestInstanceId, count, null, opts.checksum);
count++;
bw.addMutation(m);
}
lastFlushTime = flush(bw, count, flushInterval, lastFlushTime);
if (count >= opts.num)
break out;
// generate subsequent sets of nodes that link to previous set of nodes
for (int depth = 1; depth < maxDepth; depth++) {
for (int index = 0; index < flushInterval; index++) {
long rowLong = genLong(opts.min, opts.max, r);
byte[] prevRow = genRow(prevRows[index]);
prevRows[index] = rowLong;
Mutation m = genMutation(rowLong, r.nextInt(opts.maxColF), r.nextInt(opts.maxColQ),
cv, ingestInstanceId, count, prevRow, opts.checksum);
count++;
bw.addMutation(m);
}
lastFlushTime = flush(bw, count, flushInterval, lastFlushTime);
if (count >= opts.num)
break out;
}
// create one big linked list, this makes all of the first inserts
// point to something
for (int index = 0; index < flushInterval - 1; index++) {
Mutation m = genMutation(firstRows[index], firstColFams[index], firstColQuals[index],
cv, ingestInstanceId, count, genRow(prevRows[index + 1]), opts.checksum);
count++;
bw.addMutation(m);
}
lastFlushTime = flush(bw, count, flushInterval, lastFlushTime);
if (count >= opts.num)
break out;
}
bw.close();
}
}
}
private static long flush(BatchWriter bw, long count, final int flushInterval, long lastFlushTime)
throws MutationsRejectedException {
long t1 = System.currentTimeMillis();
bw.flush();
long t2 = System.currentTimeMillis();
System.out.printf("FLUSH %d %d %d %d %d%n", t2, (t2 - lastFlushTime), (t2 - t1), count,
flushInterval);
lastFlushTime = t2;
return lastFlushTime;
}
public static Mutation genMutation(long rowLong, int cfInt, int cqInt, ColumnVisibility cv,
byte[] ingestInstanceId, long count, byte[] prevRow, boolean checksum) {
// Adler32 is supposed to be faster, but according to wikipedia is not good for small data....
// so used CRC32 instead
CRC32 cksum = null;
byte[] rowString = genRow(rowLong);
byte[] cfString = FastFormat.toZeroPaddedString(cfInt, 4, 16, EMPTY_BYTES);
byte[] cqString = FastFormat.toZeroPaddedString(cqInt, 4, 16, EMPTY_BYTES);
if (checksum) {
cksum = new CRC32();
cksum.update(rowString);
cksum.update(cfString);
cksum.update(cqString);
cksum.update(cv.getExpression());
}
Mutation m = new Mutation(new Text(rowString));
m.put(new Text(cfString), new Text(cqString), cv,
createValue(ingestInstanceId, count, prevRow, cksum));
return m;
}
public static final long genLong(long min, long max, Random r) {
return ((r.nextLong() & 0x7fffffffffffffffL) % (max - min)) + min;
}
static final byte[] genRow(long min, long max, Random r) {
return genRow(genLong(min, max, r));
}
static final byte[] genRow(long rowLong) {
return FastFormat.toZeroPaddedString(rowLong, 16, 16, EMPTY_BYTES);
}
private static Value createValue(byte[] ingestInstanceId, long count, byte[] prevRow,
Checksum cksum) {
int dataLen = ingestInstanceId.length + 16 + (prevRow == null ? 0 : prevRow.length) + 3;
if (cksum != null)
dataLen += 8;
byte[] val = new byte[dataLen];
System.arraycopy(ingestInstanceId, 0, val, 0, ingestInstanceId.length);
int index = ingestInstanceId.length;
val[index++] = ':';
int added = FastFormat.toZeroPaddedString(val, index, count, 16, 16, EMPTY_BYTES);
if (added != 16)
throw new RuntimeException(" " + added);
index += 16;
val[index++] = ':';
if (prevRow != null) {
System.arraycopy(prevRow, 0, val, index, prevRow.length);
index += prevRow.length;
}
val[index++] = ':';
if (cksum != null) {
cksum.update(val, 0, index);
cksum.getValue();
FastFormat.toZeroPaddedString(val, index, cksum.getValue(), 8, 16, EMPTY_BYTES);
}
// System.out.println("val "+new String(val));
return new Value(val);
}
}
|
3e1d49a1b147d7495454c2b14a3226dee5fd8127 | 994 | java | Java | nodes/src/test/java/io/aexp/nodes/graphql/models/TestModelEnum.java | jleibund/nodes | df20fe627d298b35a33a184b1cec18241e96feb0 | [
"Apache-2.0"
] | 292 | 2018-05-15T16:50:21.000Z | 2022-03-12T03:31:42.000Z | nodes/src/test/java/io/aexp/nodes/graphql/models/TestModelEnum.java | jleibund/nodes | df20fe627d298b35a33a184b1cec18241e96feb0 | [
"Apache-2.0"
] | 113 | 2018-05-15T18:28:59.000Z | 2022-03-20T20:44:59.000Z | nodes/src/test/java/io/aexp/nodes/graphql/models/TestModelEnum.java | jleibund/nodes | df20fe627d298b35a33a184b1cec18241e96feb0 | [
"Apache-2.0"
] | 64 | 2018-05-15T17:27:01.000Z | 2022-03-28T01:18:24.000Z | 31.0625 | 100 | 0.699195 | 12,421 | /*
* Copyright (c) 2018 American Express Travel Related Services Company, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.aexp.nodes.graphql.models;
public class TestModelEnum {
private TestEnum number;
public TestEnum getNumber() {
return number;
}
public void setNumber(TestEnum number) {
this.number = number;
}
@Override
public String toString() {
return "TestModelEnum{" + "number='" + number+ '\'' + '}';
}
}
|
3e1d49c70ac2209cfcec310f5f0ff5b560b0fff8 | 192 | java | Java | client/src/main/java/me/izstas/rfs/client/rfs/RfsRequestException.java | izstas/RFS | f75faca1a28836089791c9e3f9ab694daa88c1f9 | [
"MIT"
] | null | null | null | client/src/main/java/me/izstas/rfs/client/rfs/RfsRequestException.java | izstas/RFS | f75faca1a28836089791c9e3f9ab694daa88c1f9 | [
"MIT"
] | null | null | null | client/src/main/java/me/izstas/rfs/client/rfs/RfsRequestException.java | izstas/RFS | f75faca1a28836089791c9e3f9ab694daa88c1f9 | [
"MIT"
] | null | null | null | 24 | 90 | 0.760417 | 12,422 | package me.izstas.rfs.client.rfs;
/**
* This exception is thrown when the API call results in a status code of 400 Bad Request.
*/
public class RfsRequestException extends RfsException {
}
|
3e1d4ab14d7d499d3d4d9766150ca55d558ab8a1 | 12,504 | java | Java | controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | 67.956522 | 242 | 0.727287 | 12,423 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.notification;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.path.Path;
import com.yahoo.test.ManualClock;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.ClusterMetrics;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.persistence.MockCuratorDb;
import org.junit.Before;
import org.junit.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Level;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Type;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author freva
*/
public class NotificationsDbTest {
private static final TenantName tenant = TenantName.from("tenant1");
private static final List<Notification> notifications = List.of(
notification(1001, Type.deployment, Level.error, NotificationSource.from(tenant), "tenant msg"),
notification(1101, Type.applicationPackage, Level.warning, NotificationSource.from(TenantAndApplicationId.from(tenant.value(), "app1")), "app msg"),
notification(1201, Type.deployment, Level.error, NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), "instance msg"),
notification(1301, Type.deployment, Level.warning, NotificationSource.from(new DeploymentId(ApplicationId.from(tenant.value(), "app2", "instance2"), ZoneId.from("prod", "us-north-2"))), "deployment msg"),
notification(1401, Type.feedBlock, Level.error, NotificationSource.from(new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("dev", "us-south-1")), ClusterSpec.Id.from("cluster1")), "cluster msg"),
notification(1501, Type.deployment, Level.warning, NotificationSource.from(new RunId(ApplicationId.from(tenant.value(), "app1", "instance1"), JobType.devUsEast1, 4)), "run id msg"));
private final ManualClock clock = new ManualClock(Instant.ofEpochSecond(12345));
private final MockCuratorDb curatorDb = new MockCuratorDb();
private final NotificationsDb notificationsDb = new NotificationsDb(clock, curatorDb);
@Test
public void list_test() {
assertEquals(notifications, notificationsDb.listNotifications(NotificationSource.from(tenant), false));
assertEquals(notificationIndices(0, 1, 2, 3), notificationsDb.listNotifications(NotificationSource.from(tenant), true));
assertEquals(notificationIndices(2, 3), notificationsDb.listNotifications(NotificationSource.from(TenantAndApplicationId.from(tenant.value(), "app2")), false));
assertEquals(notificationIndices(4, 5), notificationsDb.listNotifications(NotificationSource.from(ApplicationId.from(tenant.value(), "app1", "instance1")), false));
assertEquals(notificationIndices(5), notificationsDb.listNotifications(NotificationSource.from(new RunId(ApplicationId.from(tenant.value(), "app1", "instance1"), JobType.devUsEast1, 5)), false));
assertEquals(List.of(), notificationsDb.listNotifications(NotificationSource.from(new RunId(ApplicationId.from(tenant.value(), "app1", "instance1"), JobType.productionUsEast3, 4)), false));
}
@Test
public void add_test() {
Notification notification1 = notification(12345, Type.deployment, Level.warning, NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), "instance msg #2");
Notification notification2 = notification(12345, Type.deployment, Level.error, NotificationSource.from(ApplicationId.from(tenant.value(), "app3", "instance2")), "instance msg #3");
// Replace the 3rd notification
notificationsDb.setNotification(notification1.source(), notification1.type(), notification1.level(), notification1.messages());
// Notification for a new app, add without replacement
notificationsDb.setNotification(notification2.source(), notification2.type(), notification2.level(), notification2.messages());
List<Notification> expected = notificationIndices(0, 1, 3, 4, 5);
expected.addAll(List.of(notification1, notification2));
assertEquals(expected, curatorDb.readNotifications(tenant));
}
@Test
public void remove_single_test() {
// Remove the 3rd notification
notificationsDb.removeNotification(NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), Type.deployment);
// Removing something that doesn't exist is OK
notificationsDb.removeNotification(NotificationSource.from(ApplicationId.from(tenant.value(), "app3", "instance2")), Type.deployment);
assertEquals(notificationIndices(0, 1, 3, 4, 5), curatorDb.readNotifications(tenant));
}
@Test
public void remove_multiple_test() {
// Remove the 3rd notification
notificationsDb.removeNotifications(NotificationSource.from(ApplicationId.from(tenant.value(), "app1", "instance1")));
assertEquals(notificationIndices(0, 1, 2, 3), curatorDb.readNotifications(tenant));
assertTrue(curatorDb.curator().exists(Path.fromString("/controller/v1/notifications/" + tenant.value())));
notificationsDb.removeNotifications(NotificationSource.from(tenant));
assertEquals(List.of(), curatorDb.readNotifications(tenant));
assertFalse(curatorDb.curator().exists(Path.fromString("/controller/v1/notifications/" + tenant.value())));
}
@Test
public void feed_blocked_single_cluster_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
List<Notification> expected = new ArrayList<>(notifications);
// No metrics, no new notification
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of());
assertEquals(expected, curatorDb.readNotifications(tenant));
// Metrics that contain none of the feed block metrics does not create new notification
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(clusterMetrics("cluster1", null, null, null, null, Map.of())));
assertEquals(expected, curatorDb.readNotifications(tenant));
// Metrics that only contain util or limit (should not be possible) should not cause any issues
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(clusterMetrics("cluster1", 0.95, null, null, 0.5, Map.of())));
assertEquals(expected, curatorDb.readNotifications(tenant));
// One resource is at warning
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(clusterMetrics("cluster1", 0.85, 0.9, 0.3, 0.5, Map.of())));
expected.add(notification(12345, Type.feedBlock, Level.warning, sourceCluster1, "disk (usage: 85.0%, feed block limit: 90.0%)"));
assertEquals(expected, curatorDb.readNotifications(tenant));
// Both resources over the limit
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(clusterMetrics("cluster1", 0.95, 0.9, 0.3, 0.5, Map.of())));
expected.set(6, notification(12345, Type.feedBlock, Level.error, sourceCluster1, "disk (usage: 95.0%, feed block limit: 90.0%)"));
assertEquals(expected, curatorDb.readNotifications(tenant));
// One resource at warning, one at error: Only show error message
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(clusterMetrics("cluster1", 0.95, 0.9, 0.7, 0.5, Map.of())));
expected.set(6, notification(12345, Type.feedBlock, Level.error, sourceCluster1,
"memory (usage: 70.0%, feed block limit: 50.0%)", "disk (usage: 95.0%, feed block limit: 90.0%)"));
assertEquals(expected, curatorDb.readNotifications(tenant));
}
@Test
public void deployment_metrics_multiple_cluster_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
NotificationSource sourceCluster2 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster2"));
NotificationSource sourceCluster3 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster3"));
List<Notification> expected = new ArrayList<>(notifications);
// Cluster1 and cluster2 are having feed block issues, cluster 3 is reindexing
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(
clusterMetrics("cluster1", 0.85, 0.9, 0.3, 0.5, Map.of()), clusterMetrics("cluster2", 0.6, 0.8, 0.9, 0.75, Map.of()), clusterMetrics("cluster3", 0.1, 0.8, 0.2, 0.9, Map.of("announcements", 0.75, "build", 0.5))));
expected.add(notification(12345, Type.feedBlock, Level.warning, sourceCluster1, "disk (usage: 85.0%, feed block limit: 90.0%)"));
expected.add(notification(12345, Type.feedBlock, Level.error, sourceCluster2, "memory (usage: 90.0%, feed block limit: 75.0%)"));
expected.add(notification(12345, Type.reindex, Level.info, sourceCluster3, "document type 'announcements' (75.0% done)", "document type 'build' (50.0% done)"));
assertEquals(expected, curatorDb.readNotifications(tenant));
// Cluster1 improves, while cluster3 starts having feed block issues and finishes reindexing 'build' documents
notificationsDb.setDeploymentMetricsNotifications(deploymentId, List.of(
clusterMetrics("cluster1", 0.15, 0.9, 0.3, 0.5, Map.of()), clusterMetrics("cluster2", 0.6, 0.8, 0.9, 0.75, Map.of()), clusterMetrics("cluster3", 0.75, 0.8, 0.2, 0.9, Map.of("announcements", 0.9))));
expected.set(6, notification(12345, Type.feedBlock, Level.error, sourceCluster2, "memory (usage: 90.0%, feed block limit: 75.0%)"));
expected.set(7, notification(12345, Type.feedBlock, Level.warning, sourceCluster3, "disk (usage: 75.0%, feed block limit: 80.0%)"));
expected.set(8, notification(12345, Type.reindex, Level.info, sourceCluster3, "document type 'announcements' (90.0% done)"));
assertEquals(expected, curatorDb.readNotifications(tenant));
}
@Before
public void init() {
curatorDb.writeNotifications(tenant, notifications);
}
private static List<Notification> notificationIndices(int... indices) {
return Arrays.stream(indices).mapToObj(notifications::get).collect(Collectors.toCollection(ArrayList::new));
}
private static Notification notification(long secondsSinceEpoch, Type type, Level level, NotificationSource source, String... messages) {
return new Notification(Instant.ofEpochSecond(secondsSinceEpoch), type, level, source, List.of(messages));
}
private static ClusterMetrics clusterMetrics(String clusterId,
Double diskUtil, Double diskLimit, Double memoryUtil, Double memoryLimit,
Map<String, Double> reindexingProgress) {
Map<String, Double> metrics = new HashMap<>();
if (diskUtil != null) metrics.put(ClusterMetrics.DISK_UTIL, diskUtil);
if (diskLimit != null) metrics.put(ClusterMetrics.DISK_FEED_BLOCK_LIMIT, diskLimit);
if (memoryUtil != null) metrics.put(ClusterMetrics.MEMORY_UTIL, memoryUtil);
if (memoryLimit != null) metrics.put(ClusterMetrics.MEMORY_FEED_BLOCK_LIMIT, memoryLimit);
return new ClusterMetrics(clusterId, "content", metrics, reindexingProgress);
}
}
|
3e1d4ae34af260916684d8f141a1b338b36f7472 | 1,997 | java | Java | src/main/java/edu/colostate/cs/galileo/dht/QueryTracker.java | ayush-usf/galileo | 06fe69615d2b443e3d2779af08693cb7aa703004 | [
"BSD-2-Clause"
] | 5 | 2015-05-17T06:54:01.000Z | 2017-03-02T02:33:04.000Z | src/main/java/edu/colostate/cs/galileo/dht/QueryTracker.java | ayush-usf/galileo | 06fe69615d2b443e3d2779af08693cb7aa703004 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/edu/colostate/cs/galileo/dht/QueryTracker.java | ayush-usf/galileo | 06fe69615d2b443e3d2779af08693cb7aa703004 | [
"BSD-2-Clause"
] | 2 | 2015-09-01T23:39:15.000Z | 2021-11-26T04:21:00.000Z | 35.660714 | 80 | 0.752629 | 12,424 | /*
Copyright (c) 2013, Colorado State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/
package edu.colostate.cs.galileo.dht;
import java.nio.channels.SelectionKey;
public class QueryTracker {
private static final Object counterLock = new Object();
private static long queryCounter = 0;
private long queryId;
private SelectionKey key;
public QueryTracker(SelectionKey key) {
synchronized (counterLock) {
this.queryId = QueryTracker.queryCounter++;
}
this.key = key;
}
public long getQueryId() {
return queryId;
}
public String getIdString(String sessionId) {
return sessionId + "$" + queryId;
}
public SelectionKey getSelectionKey() {
return key;
}
}
|
3e1d4cb24a4ca20fcd11eec07c02167b68f0b755 | 495 | java | Java | src/main/java/br/org/libros/usuario/dto/mapper/IUsuarioMapper.java | alissonwilker/br.org.libros | e6459141ab4784a6e29d8d07e04e7d1865df8a1a | [
"MIT"
] | null | null | null | src/main/java/br/org/libros/usuario/dto/mapper/IUsuarioMapper.java | alissonwilker/br.org.libros | e6459141ab4784a6e29d8d07e04e7d1865df8a1a | [
"MIT"
] | null | null | null | src/main/java/br/org/libros/usuario/dto/mapper/IUsuarioMapper.java | alissonwilker/br.org.libros | e6459141ab4784a6e29d8d07e04e7d1865df8a1a | [
"MIT"
] | null | null | null | 26.052632 | 77 | 0.80202 | 12,425 | package br.org.libros.usuario.dto.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import br.org.arquitetura.dto.mapper.IGenericMapper;
import br.org.libros.usuario.dto.UsuarioDto;
import br.org.libros.usuario.model.persistence.entity.Usuario;
/**
*
* @see br.org.arquitetura.dto.mapper.IGenericMapper
*/
@Mapper
public interface IUsuarioMapper extends IGenericMapper<Usuario, UsuarioDto> {
IUsuarioMapper INSTANCE = Mappers.getMapper(IUsuarioMapper.class);
}
|
3e1d4d56ee1796d4b29c3f75a9f8383f1144e307 | 3,277 | java | Java | state/src/main/java/io/github/astrapi69/design/pattern/state/wizard/BaseWizardState.java | lightblueseas/design-patterns | 802fde9c31617b5be741791c8100e398d937feba | [
"MIT"
] | 2 | 2016-08-08T11:38:41.000Z | 2021-06-30T15:37:51.000Z | state/src/main/java/io/github/astrapi69/design/pattern/state/wizard/BaseWizardState.java | lightblueseas/design-patterns | 802fde9c31617b5be741791c8100e398d937feba | [
"MIT"
] | null | null | null | state/src/main/java/io/github/astrapi69/design/pattern/state/wizard/BaseWizardState.java | lightblueseas/design-patterns | 802fde9c31617b5be741791c8100e398d937feba | [
"MIT"
] | null | null | null | 27.308333 | 94 | 0.683552 | 12,426 | /**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* 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 io.github.astrapi69.design.pattern.state.wizard;
/**
* The interface {@link BaseWizardState} represents a wizard state.
*/
public interface BaseWizardState<ST> extends WizardState<ST>
{
/**
* Gets the simple name of this {@link WizardState} object.
*
* @return the simple name of this {@link WizardState} object.
*/
default String getName()
{
return this.getClass().getSimpleName();
}
/**
* Go to the next {@link WizardState} object.
*
* @param input
* the {@link WizardStateMachine} object
*/
void goNext(ST input);
/**
* Go to the previous {@link WizardState} object.
*
* @param input
* the {@link WizardStateMachine} object
*/
void goPrevious(ST input);
/**
* Checks if this {@link WizardState} object has a next {@link WizardState} object.
*
* @return true, if this {@link WizardState} object has a next {@link WizardState} object
* otherwise false.
*/
default boolean hasNext()
{
return true;
}
/**
* Checks if this {@link WizardState} object has a previous {@link WizardState} object.
*
* @return true, if this {@link WizardState} object has a previous {@link WizardState} object
* otherwise false.
*/
default boolean hasPrevious()
{
return true;
}
/**
* Checks if this {@link WizardState} object is the first {@link WizardState} object.
*
* @return true, if this {@link WizardState} object is the first {@link WizardState} object
* otherwise false.
*/
default boolean isFirst()
{
return false;
}
/**
* Checks if this {@link WizardState} object is the last {@link WizardState} object.
*
* @return true, if this {@link WizardState} object is the last {@link WizardState} object
* otherwise false.
*/
default boolean isLast()
{
return false;
}
/**
* Cancel the {@link BaseWizardState}.
*
* @param input
* the {@link BaseWizardStateMachine} object
*/
void cancel(ST input);
/**
* Finish the {@link BaseWizardState}.
*
* @param input
* the {@link BaseWizardStateMachine} object
*/
void finish(ST input);
}
|
3e1d4d5d336fc3c8abaa71ab28915f74705cb2e2 | 1,091 | java | Java | quickstart-netty/src/main/java/org/quickstart/netty/v4x/helloworld/HelloClientHandler1.java | youngzil/quickstart-remoting | ccc22972e0b8ab5e08b2fbdbc45aca2410fbf9bc | [
"Apache-2.0"
] | null | null | null | quickstart-netty/src/main/java/org/quickstart/netty/v4x/helloworld/HelloClientHandler1.java | youngzil/quickstart-remoting | ccc22972e0b8ab5e08b2fbdbc45aca2410fbf9bc | [
"Apache-2.0"
] | 2 | 2020-05-26T13:05:50.000Z | 2020-06-01T13:20:19.000Z | quickstart-netty/src/main/java/org/quickstart/netty/v4x/helloworld/HelloClientHandler1.java | youngzil/quickstart-remoting | ccc22972e0b8ab5e08b2fbdbc45aca2410fbf9bc | [
"Apache-2.0"
] | null | null | null | 28.868421 | 115 | 0.753874 | 12,427 | /**
* 项目名称:quickstart-netty 文件名:HelloClientHandler.java 版本信息: 日期:2017年1月13日 Copyright youngzil Corporation 2017 版权所有 *
*/
package org.quickstart.netty.v4x.helloworld;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* HelloClientHandler
*
* @version 1.0
* @efpyi@example.com
* @2017年1月13日 下午3:29:58
*/
public class HelloClientHandler1 extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("HelloClientHandler1 channelRead0 Server say : " + msg);
// 通知执行下一个InboundHandler
ctx.fireChannelRead(msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("HelloClientHandler1 channelActive ");
super.channelActive(ctx);
}
// @Override
// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// System.out.println("HelloClientHandler1 channelInactive close ");
// super.channelInactive(ctx);
// }
}
|
3e1d4fd67fd913537733458b4831fedcc2131c00 | 1,372 | java | Java | sdk/jme3-ogretools/src/com/jme3/gde/ogretools/convert/OutputReader.java | jincai123/MikuMikuStudio | 76ffb3fc39af223c1ddf6f86de345024997e3321 | [
"BSD-2-Clause"
] | 30 | 2015-07-28T06:12:53.000Z | 2021-12-10T18:45:27.000Z | sdk/jme3-ogretools/src/com/jme3/gde/ogretools/convert/OutputReader.java | chototsu/MikuMikuStudio | 76ffb3fc39af223c1ddf6f86de345024997e3321 | [
"BSD-2-Clause"
] | null | null | null | sdk/jme3-ogretools/src/com/jme3/gde/ogretools/convert/OutputReader.java | chototsu/MikuMikuStudio | 76ffb3fc39af223c1ddf6f86de345024997e3321 | [
"BSD-2-Clause"
] | 11 | 2015-02-21T17:17:43.000Z | 2021-12-10T18:45:29.000Z | 23.254237 | 64 | 0.555394 | 12,428 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.jme3.gde.ogretools.convert;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.netbeans.api.progress.ProgressHandle;
/**
*
* @author normenhansen
*/
public class OutputReader implements Runnable {
private Thread thread;
private BufferedReader in;
private ProgressHandle progress;
public OutputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public OutputReader(BufferedReader in) {
this.in = in;
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void run() {
try {
String line;
while ((line = in.readLine()) != null) {
if (line.trim().length() > 0) {
if (progress != null) {
progress.progress(line);
} else {
System.out.println(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param progress the progress to set
*/
public void setProgress(ProgressHandle progress) {
this.progress = progress;
}
}
|
3e1d507e492703abe38ca72117972d80a7674241 | 2,526 | java | Java | google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/NodeTypesStub.java | renovate-bot/java-compute | 4079fb224c99175e9ef1b361c2127683695d5342 | [
"Apache-2.0"
] | 19 | 2020-01-28T12:32:27.000Z | 2022-02-12T07:48:33.000Z | google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/NodeTypesStub.java | renovate-bot/java-compute | 4079fb224c99175e9ef1b361c2127683695d5342 | [
"Apache-2.0"
] | 458 | 2019-11-04T22:32:18.000Z | 2022-03-30T00:03:12.000Z | google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/NodeTypesStub.java | renovate-bot/java-compute | 4079fb224c99175e9ef1b361c2127683695d5342 | [
"Apache-2.0"
] | 23 | 2019-10-31T21:05:28.000Z | 2021-08-24T16:35:45.000Z | 38.272727 | 94 | 0.790974 | 12,429 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import static com.google.cloud.compute.v1.NodeTypesClient.AggregatedListPagedResponse;
import static com.google.cloud.compute.v1.NodeTypesClient.ListPagedResponse;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.AggregatedListNodeTypesRequest;
import com.google.cloud.compute.v1.GetNodeTypeRequest;
import com.google.cloud.compute.v1.ListNodeTypesRequest;
import com.google.cloud.compute.v1.NodeType;
import com.google.cloud.compute.v1.NodeTypeAggregatedList;
import com.google.cloud.compute.v1.NodeTypeList;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Base stub class for the NodeTypes service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public abstract class NodeTypesStub implements BackgroundResource {
public UnaryCallable<AggregatedListNodeTypesRequest, AggregatedListPagedResponse>
aggregatedListPagedCallable() {
throw new UnsupportedOperationException("Not implemented: aggregatedListPagedCallable()");
}
public UnaryCallable<AggregatedListNodeTypesRequest, NodeTypeAggregatedList>
aggregatedListCallable() {
throw new UnsupportedOperationException("Not implemented: aggregatedListCallable()");
}
public UnaryCallable<GetNodeTypeRequest, NodeType> getCallable() {
throw new UnsupportedOperationException("Not implemented: getCallable()");
}
public UnaryCallable<ListNodeTypesRequest, ListPagedResponse> listPagedCallable() {
throw new UnsupportedOperationException("Not implemented: listPagedCallable()");
}
public UnaryCallable<ListNodeTypesRequest, NodeTypeList> listCallable() {
throw new UnsupportedOperationException("Not implemented: listCallable()");
}
@Override
public abstract void close();
}
|
3e1d50e62aced81c99a2052d4a546bf2c084786d | 1,336 | java | Java | app/src/main/java/com/dchip/door/smartdoorsdk/Bean/AppUpdateModel.java | llakcs/SDoor | f4019bfab3fc8a98f70044eda5a95c6077a30173 | [
"Apache-2.0"
] | 1 | 2020-04-09T07:00:51.000Z | 2020-04-09T07:00:51.000Z | app/src/main/java/com/dchip/door/smartdoorsdk/Bean/AppUpdateModel.java | llakcs/SDoor | f4019bfab3fc8a98f70044eda5a95c6077a30173 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/dchip/door/smartdoorsdk/Bean/AppUpdateModel.java | llakcs/SDoor | f4019bfab3fc8a98f70044eda5a95c6077a30173 | [
"Apache-2.0"
] | null | null | null | 16.292683 | 56 | 0.571856 | 12,430 | package com.dchip.door.smartdoorsdk.Bean;
/**
* Created by jelly on 2017/8/3.
*/
public class AppUpdateModel {
//文件名
String address ;
//状态暂时无用
int status;
//更新信息
String remark;
//下载地址
String detailAddress;
//校验码
String md5;
//命令分类 默认为1
int type;
//
String version;
public String getDetailAddress() {
return detailAddress;
}
public void setDetailAddress(String detailAddress) {
this.detailAddress = detailAddress;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
|
3e1d51b491e828e0772daf123f657d8c1aff1d0c | 16,033 | java | Java | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/StructureFilterPopupComponent.java | zaypen/intellij-community | e48315b0dece963009ed3c3abd93cc03ee811898 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:12.000Z | 2018-10-03T12:35:12.000Z | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/StructureFilterPopupComponent.java | zaypen/intellij-community | e48315b0dece963009ed3c3abd93cc03ee811898 | [
"Apache-2.0"
] | null | null | null | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/StructureFilterPopupComponent.java | zaypen/intellij-community | e48315b0dece963009ed3c3abd93cc03ee811898 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:06.000Z | 2018-10-03T12:35:06.000Z | 38.540865 | 136 | 0.686584 | 12,431 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.ui.filter;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.SizedIcon;
import com.intellij.ui.popup.KeepingPopupOpenAction;
import com.intellij.util.NotNullFunction;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.ColorIcon;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.vcs.log.VcsLogDataPack;
import com.intellij.vcs.log.VcsLogRootFilter;
import com.intellij.vcs.log.VcsLogStructureFilter;
import com.intellij.vcs.log.data.VcsLogStructureFilterImpl;
import com.intellij.vcs.log.impl.MainVcsLogUiProperties;
import com.intellij.vcs.log.impl.VcsLogFileFilter;
import com.intellij.vcs.log.impl.VcsLogRootFilterImpl;
import com.intellij.vcs.log.ui.VcsLogColorManager;
import com.intellij.vcs.log.ui.table.VcsLogGraphTable;
import com.intellij.vcs.log.util.VcsLogUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.List;
class StructureFilterPopupComponent extends FilterPopupComponent<VcsLogFileFilter> {
private static final int FILTER_LABEL_LENGTH = 30;
private static final int CHECKBOX_ICON_SIZE = 15;
private static final FileByNameComparator FILE_BY_NAME_COMPARATOR = new FileByNameComparator();
private static final FilePathByPathComparator FILE_PATH_BY_PATH_COMPARATOR = new FilePathByPathComparator();
@NotNull private final MainVcsLogUiProperties myUiProperties;
@NotNull private final VcsLogColorManager myColorManager;
StructureFilterPopupComponent(@NotNull MainVcsLogUiProperties uiProperties,
@NotNull FilterModel<VcsLogFileFilter> filterModel,
@NotNull VcsLogColorManager colorManager) {
super("Paths", filterModel);
myUiProperties = uiProperties;
myColorManager = colorManager;
}
@NotNull
@Override
protected String getText(@NotNull VcsLogFileFilter filter) {
Collection<VirtualFile> roots = filter.getRootFilter() == null ? getAllRoots() : filter.getRootFilter().getRoots();
Collection<FilePath> files =
filter.getStructureFilter() == null ? Collections.emptySet() : filter.getStructureFilter().getFiles();
Collection<VirtualFile> visibleRoots =
VcsLogUtil.getAllVisibleRoots(getAllRoots(), filter.getRootFilter(), filter.getStructureFilter());
if (files.isEmpty()) {
return getTextFromRoots(roots, visibleRoots.size() == getAllRoots().size());
}
return getTextFromFilePaths(files, "folders", false);
}
@NotNull
private static String getTextFromRoots(@NotNull Collection<VirtualFile> files,
boolean full) {
return getText(files, "roots", FILE_BY_NAME_COMPARATOR, VirtualFile::getName, full);
}
@NotNull
private static String getTextFromFilePaths(@NotNull Collection<FilePath> files,
@NotNull String category,
boolean full) {
return getText(files, category, FILE_PATH_BY_PATH_COMPARATOR,
file -> StringUtil.shortenPathWithEllipsis(file.getPresentableUrl(), FILTER_LABEL_LENGTH), full);
}
@NotNull
private static <F> String getText(@NotNull Collection<F> files,
@NotNull String category,
@NotNull Comparator<F> comparator,
@NotNull NotNullFunction<F, String> getText,
boolean full) {
if (full) {
return ALL;
}
else if (files.isEmpty()) {
return "No " + category;
}
else {
F firstFile = Collections.min(files, comparator);
String firstFileName = getText.fun(firstFile);
if (files.size() == 1) {
return firstFileName;
}
return firstFileName + " + " + (files.size() - 1);
}
}
@Nullable
@Override
protected String getToolTip(@NotNull VcsLogFileFilter filter) {
return getToolTip(filter.getRootFilter() == null ? getAllRoots() : filter.getRootFilter().getRoots(),
filter.getStructureFilter() == null ? Collections.emptySet() : filter.getStructureFilter().getFiles());
}
@NotNull
private String getToolTip(@NotNull Collection<VirtualFile> roots, @NotNull Collection<FilePath> files) {
String tooltip = "";
if (roots.isEmpty()) {
tooltip += "No Roots Selected";
}
else if (roots.size() != getAllRoots().size()) {
tooltip += "Roots:\n" + getTooltipTextForRoots(roots);
}
if (!files.isEmpty()) {
if (!tooltip.isEmpty()) tooltip += "\n";
tooltip += "Folders:\n" + getTooltipTextForFilePaths(files);
}
return tooltip;
}
@NotNull
private static String getTooltipTextForRoots(@NotNull Collection<VirtualFile> files) {
return getTooltipTextForFiles(files, FILE_BY_NAME_COMPARATOR, VirtualFile::getName);
}
@NotNull
private static String getTooltipTextForFilePaths(@NotNull Collection<FilePath> files) {
return getTooltipTextForFiles(files, FILE_PATH_BY_PATH_COMPARATOR, FilePath::getPresentableUrl);
}
@NotNull
private static <F> String getTooltipTextForFiles(@NotNull Collection<F> files,
@NotNull Comparator<F> comparator,
@NotNull NotNullFunction<F, String> getText) {
List<F> filesToDisplay = ContainerUtil.sorted(files, comparator);
if (files.size() > 10) {
filesToDisplay = filesToDisplay.subList(0, 10);
}
String tooltip = StringUtil.join(filesToDisplay, getText, "\n");
if (files.size() > 10) {
tooltip += "\n...";
}
return tooltip;
}
@Override
protected ActionGroup createActionGroup() {
Set<VirtualFile> roots = getAllRoots();
List<AnAction> rootActions = new ArrayList<>();
if (myColorManager.isMultipleRoots()) {
for (VirtualFile root : ContainerUtil.sorted(roots, FILE_BY_NAME_COMPARATOR)) {
rootActions.add(new SelectVisibleRootAction(root));
}
}
List<AnAction> structureActions = new ArrayList<>();
for (VcsLogStructureFilter filter : getRecentFilters()) {
structureActions.add(new SelectFromHistoryAction(filter));
}
if (roots.size() > 15) {
return new DefaultActionGroup(createAllAction(), new SelectFoldersAction(),
new Separator("Recent"), new DefaultActionGroup(structureActions),
new Separator("Roots"), new DefaultActionGroup(rootActions));
}
return new DefaultActionGroup(createAllAction(), new SelectFoldersAction(),
new Separator("Roots"), new DefaultActionGroup(rootActions),
new Separator("Recent"), new DefaultActionGroup(structureActions));
}
@NotNull
private List<VcsLogStructureFilter> getRecentFilters() {
List<List<String>> filterValues = myUiProperties.getRecentlyFilteredGroups(myName);
return ContainerUtil.map2List(filterValues, values -> VcsLogClassicFilterUi.FileFilterModel.createStructureFilter(values));
}
private Set<VirtualFile> getAllRoots() {
return myFilterModel.getDataPack().getLogProviders().keySet();
}
private boolean isVisible(@NotNull VirtualFile root) {
VcsLogFileFilter filter = myFilterModel.getFilter();
if (filter != null && filter.getRootFilter() != null) {
return filter.getRootFilter().getRoots().contains(root);
}
return true;
}
private void setVisible(@NotNull VirtualFile root, boolean visible) {
Set<VirtualFile> roots = getAllRoots();
VcsLogFileFilter previousFilter = myFilterModel.getFilter();
VcsLogRootFilter rootFilter = previousFilter != null ? previousFilter.getRootFilter() : null;
Collection<VirtualFile> visibleRoots;
if (rootFilter == null) {
visibleRoots = visible ? roots : ContainerUtil.subtract(roots, Collections.singleton(root));
}
else {
visibleRoots = visible
? ContainerUtil.union(new HashSet<>(rootFilter.getRoots()), Collections.singleton(root))
: ContainerUtil.subtract(rootFilter.getRoots(), Collections.singleton(root));
}
myFilterModel.setFilter(new VcsLogFileFilter(null, new VcsLogRootFilterImpl(visibleRoots)));
}
private void setVisibleOnly(@NotNull VirtualFile root) {
myFilterModel.setFilter(new VcsLogFileFilter(null, new VcsLogRootFilterImpl(Collections.singleton(root))));
}
@NotNull
private static String getStructureActionText(@NotNull VcsLogStructureFilter filter) {
return getTextFromFilePaths(filter.getFiles(), "items", filter.getFiles().isEmpty());
}
private static class FileByNameComparator implements Comparator<VirtualFile> {
@Override
public int compare(VirtualFile o1, VirtualFile o2) {
return o1.getName().compareTo(o2.getName());
}
}
private static class FilePathByPathComparator implements Comparator<FilePath> {
@Override
public int compare(FilePath o1, FilePath o2) {
return o1.getPresentableUrl().compareTo(o2.getPresentableUrl());
}
}
private class SelectVisibleRootAction extends ToggleAction implements DumbAware, KeepingPopupOpenAction {
@NotNull private final CheckboxColorIcon myIcon;
@NotNull private final VirtualFile myRoot;
private SelectVisibleRootAction(@NotNull VirtualFile root) {
super(root.getName(), root.getPresentableUrl(), null);
myRoot = root;
myIcon = JBUI.scale(new CheckboxColorIcon(CHECKBOX_ICON_SIZE, VcsLogGraphTable.getRootBackgroundColor(myRoot, myColorManager)));
getTemplatePresentation().setIcon(JBUI.scale(EmptyIcon.create(CHECKBOX_ICON_SIZE))); // see PopupFactoryImpl.calcMaxIconSize
}
@Override
public boolean isSelected(AnActionEvent e) {
return isVisible(myRoot);
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
if (!isEnabled()) {
setVisibleOnly(myRoot);
}
else {
if ((e.getModifiers() & getMask()) != 0) {
setVisibleOnly(myRoot);
}
else {
setVisible(myRoot, state);
}
}
}
@JdkConstants.InputEventMask
private int getMask() {
return SystemInfo.isMac ? InputEvent.META_MASK : InputEvent.CTRL_MASK;
}
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
updateIcon();
e.getPresentation().setIcon(myIcon);
e.getPresentation().putClientProperty(TOOL_TIP_TEXT_KEY, KeyEvent.getKeyModifiersText(getMask()) +
"+Click to see only \"" +
e.getPresentation().getText() +
"\"");
}
private void updateIcon() {
myIcon.prepare(isVisible(myRoot) && isEnabled());
}
private boolean isEnabled() {
return myFilterModel.getFilter() == null || myFilterModel.getFilter().getStructureFilter() == null;
}
}
private static class CheckboxColorIcon extends ColorIcon {
private final int mySize;
private boolean mySelected;
private SizedIcon mySizedIcon;
CheckboxColorIcon(int size, @NotNull Color color) {
super(size, color);
mySize = size;
mySizedIcon = new SizedIcon(PlatformIcons.CHECK_ICON_SMALL, mySize, mySize);
}
public void prepare(boolean selected) {
mySelected = selected;
}
@NotNull
@Override
public CheckboxColorIcon withIconPreScaled(boolean preScaled) {
mySizedIcon = (SizedIcon)mySizedIcon.withIconPreScaled(preScaled);
return (CheckboxColorIcon)super.withIconPreScaled(preScaled);
}
@Override
public void paintIcon(Component component, Graphics g, int i, int j) {
super.paintIcon(component, g, i, j);
if (mySelected) {
mySizedIcon.paintIcon(component, g, i, j);
}
}
}
private class SelectFoldersAction extends DumbAwareAction {
static final String STRUCTURE_FILTER_TEXT = "Select Folders...";
SelectFoldersAction() {
super(STRUCTURE_FILTER_TEXT);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getRequiredData(CommonDataKeys.PROJECT);
VcsLogDataPack dataPack = myFilterModel.getDataPack();
VcsLogFileFilter filter = myFilterModel.getFilter();
Collection<VirtualFile> files;
if (filter == null || filter.getStructureFilter() == null) {
files = Collections.emptySet();
}
else {
// for now, ignoring non-existing paths
files = ContainerUtil.mapNotNull(filter.getStructureFilter().getFiles(), FilePath::getVirtualFile);
}
VcsStructureChooser chooser = new VcsStructureChooser(project, "Select Files or Folders to Filter by", files,
new ArrayList<>(dataPack.getLogProviders().keySet()));
if (chooser.showAndGet()) {
VcsLogStructureFilterImpl structureFilter = new VcsLogStructureFilterImpl(new HashSet<VirtualFile>(chooser.getSelectedFiles()));
myFilterModel.setFilter(new VcsLogFileFilter(structureFilter, null));
myUiProperties.addRecentlyFilteredGroup(myName, VcsLogClassicFilterUi.FileFilterModel.getFilterValues(structureFilter));
}
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabledAndVisible(e.getProject() != null);
}
}
private class SelectFromHistoryAction extends ToggleAction implements DumbAware {
@NotNull private final VcsLogStructureFilter myFilter;
@NotNull private final Icon myIcon;
@NotNull private final Icon myEmptyIcon;
private SelectFromHistoryAction(@NotNull VcsLogStructureFilter filter) {
super(getStructureActionText(filter), getTooltipTextForFilePaths(filter.getFiles()).replace("\n", " "), null);
myFilter = filter;
myIcon = JBUI.scale(new SizedIcon(PlatformIcons.CHECK_ICON_SMALL, CHECKBOX_ICON_SIZE, CHECKBOX_ICON_SIZE));
myEmptyIcon = JBUI.scale(EmptyIcon.create(CHECKBOX_ICON_SIZE));
}
@Override
public boolean isSelected(AnActionEvent e) {
return myFilterModel.getFilter() != null && myFilterModel.getFilter().getStructureFilter() == myFilter;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
myFilterModel.setFilter(new VcsLogFileFilter(myFilter, null));
}
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
Presentation presentation = e.getPresentation();
if (isSelected(e)) {
presentation.setIcon(myIcon);
}
else {
presentation.setIcon(myEmptyIcon);
}
}
}
}
|
3e1d528e13a0e54d8f08a7fc2263eecffd525352 | 2,745 | java | Java | freenas-client/src/test/java/com/ixsystems/truenas/TestGlobalConfigurationConnector.java | freenas/freenas-java-api-client | ebf83bd432016f77c46956a7145efcafb556004a | [
"BSD-3-Clause"
] | 8 | 2018-12-01T20:37:08.000Z | 2021-01-11T20:38:17.000Z | freenas-client/src/test/java/com/ixsystems/truenas/TestGlobalConfigurationConnector.java | freenas/freenas-java-api-client | ebf83bd432016f77c46956a7145efcafb556004a | [
"BSD-3-Clause"
] | 8 | 2019-03-14T04:08:56.000Z | 2020-08-05T16:46:54.000Z | freenas-client/src/test/java/com/ixsystems/truenas/TestGlobalConfigurationConnector.java | freenas/freenas-java-api-client | ebf83bd432016f77c46956a7145efcafb556004a | [
"BSD-3-Clause"
] | 4 | 2018-12-23T17:16:48.000Z | 2020-12-23T11:52:17.000Z | 42.890625 | 95 | 0.75847 | 12,432 | /**
* Copyright (C) 2018 iXsystems
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of freenas-java-api-client nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ixsystems.truenas;
import com.ixsystems.vcp.entities.network.GlobalConfigurations;
import org.freenas.client.v1.connectors.rest.imp.AuthenticationConnector;
import org.freenas.client.v1.connectors.rest.imp.EndpointConnector;
import org.freenas.client.v1.network.GlobalConfigurationConnector;
import org.freenas.client.v1.network.rest.impl.GlobalConfigurationRestConnector;
import org.junit.jupiter.api.Test;
public class TestGlobalConfigurationConnector {
@Test
public void tryFetch() {
AuthenticationConnector auth = AuxiliarAuth.getAuth();
EndpointConnector ep = new EndpointConnector(AuxiliarAuth.HOST, AuxiliarAuth.PROTOCOL);
GlobalConfigurationConnector gs = new GlobalConfigurationRestConnector(ep, auth);
String hostname = gs.getHostname();
System.out.println("The FreeNAS hostname is: " + hostname);
GlobalConfigurations gc = gs.get();
System.out.println("The FreeNAS domain is: " + gc.getGcDomain());
System.out.println("The FreeNAS hostname is: " + gc.getGcHostnameB());
System.out.println("The FreeNAS Ipv4Gateway is: " + gc.getGcIpv4Gateway());
}
}
|
3e1d52b0374aa74291e0dc1392a48be2516382ff | 1,488 | java | Java | aasexplorer-core/src/test/java/com/ficture7/aasexplorer/model/Subject_FactoryTest.java | FICTURE7/aasexplorer | 07dca30e5fb2d62930859ae7e76cc5aac05a9f13 | [
"MIT"
] | null | null | null | aasexplorer-core/src/test/java/com/ficture7/aasexplorer/model/Subject_FactoryTest.java | FICTURE7/aasexplorer | 07dca30e5fb2d62930859ae7e76cc5aac05a9f13 | [
"MIT"
] | 1 | 2018-03-05T15:03:57.000Z | 2018-03-05T15:03:57.000Z | aasexplorer-core/src/test/java/com/ficture7/aasexplorer/model/Subject_FactoryTest.java | FICTURE7/aasexplorer | 07dca30e5fb2d62930859ae7e76cc5aac05a9f13 | [
"MIT"
] | null | null | null | 35.428571 | 119 | 0.714382 | 12,433 | package com.ficture7.aasexplorer.model;
import com.ficture7.aasexplorer.Loader;
import com.ficture7.aasexplorer.Saver;
import com.ficture7.aasexplorer.model.examination.Examination;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
public class Subject_FactoryTest {
@Test(expected = IllegalArgumentException.class)
public void ctor__null_examination__throwsException() {
new Subject.Factory(null, mock(Loader.class), mock(Saver.class));
}
@Test(expected = IllegalArgumentException.class)
public void ctor__null_loader__throwsException() {
new Subject.Factory(mock(Examination.class), null, mock(Saver.class));
}
@Test(expected = IllegalArgumentException.class)
public void ctor__null_saver__throwsException() {
new Subject.Factory(mock(Examination.class), mock(Loader.class), null);
}
@Test(expected = IllegalArgumentException.class)
public void create__null_name__throwsException() {
Subject.Factory factory = new Subject.Factory(mock(Examination.class), mock(Loader.class), mock(Saver.class));
factory.create(10, null);
}
@Test
public void create__instance_created() {
Subject.Factory factory = new Subject.Factory(mock(Examination.class), mock(Loader.class), mock(Saver.class));
Subject subject = factory.create(10, "oi");
assertNotNull(subject);
}
} |
3e1d53870b44f0ab543b19ee489cb7dd5d86632f | 16,430 | java | Java | week11-week11_40.Calculator/test/CalculatorTest.java | lezzles11/Java-Course-Pt-2 | 3e5ea037981f82011f7c074f083a94d5f2e20048 | [
"MIT"
] | null | null | null | week11-week11_40.Calculator/test/CalculatorTest.java | lezzles11/Java-Course-Pt-2 | 3e5ea037981f82011f7c074f083a94d5f2e20048 | [
"MIT"
] | null | null | null | week11-week11_40.Calculator/test/CalculatorTest.java | lezzles11/Java-Course-Pt-2 | 3e5ea037981f82011f7c074f083a94d5f2e20048 | [
"MIT"
] | null | null | null | 35.257511 | 181 | 0.582715 | 12,434 |
import fi.helsinki.cs.tmc.edutestutils.Points;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.util.Collection;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import junit.framework.Assert;
import org.fest.swing.core.ComponentMatcher;
import org.fest.swing.core.GenericTypeMatcher;
import org.fest.swing.edt.GuiActionRunner;
import org.fest.swing.edt.GuiTask;
import org.fest.swing.exception.ComponentLookupException;
import org.fest.swing.finder.WindowFinder;
import org.fest.swing.fixture.FrameFixture;
import org.fest.swing.junit.testcase.FestSwingJUnitTestCase;
import org.fest.swing.launcher.ApplicationLauncher;
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest extends FestSwingJUnitTestCase {
private FrameFixture frame;
@Override
protected void onSetUp() {
try {
ApplicationLauncher.application(Main.class).start();
robot().settings().delayBetweenEvents(100);
frame = WindowFinder.findFrame(JFrame.class).using(robot());
} catch (Throwable t) {
Assert.fail("Does your user interface create a JFrame-object and is it set visible with statement frame.setVisible(true)?");
}
}
// ulkonäkö
@Points("40.1")
@Test
public void sizeAndTitleCorrect() {
Dimension d = frame.component().getSize();
Assert.assertTrue("Set JFrame's width to be at least 300px and height 150px", d.height > 100 && d.width > 200);
Assert.assertEquals("Set correct title to JFrame", "Calculator", frame.component().getTitle());
}
@Points("40.1")
@Test
public void layoutOK() {
LayoutManager lm = ((JFrame) frame.component()).getContentPane().getLayout();
assertTrue("Layout manager of the graphic calculator should be GridLayout", lm instanceof GridLayout);
GridLayout gl = (GridLayout) lm;
assertEquals("GridLayout which is graphic calculator's layout manager has an incorrect number of lines",
3, gl.getRows());
assertEquals("GridLayout which is graphic calculator's layout manager has an incorrect number of columns",
1, gl.getColumns());
assertTrue("JPanel, which contains the buttons, should have GridLayout as its layout manager with 1 row and 3 columns", paneliKunnossa());
}
@Points("40.1")
@Test
public void testComponentsAreFound() {
varmista("\\+", JButton.class);
varmista("-", JButton.class);
varmista("Z", JButton.class);
Collection<JTextField> kentat = haeTekstikentat();
assertEquals("Calculator has wrong amount of JTextField-elements", 2, kentat.size());
int e = 0;
int d = 0;
for (JTextField jTextField : kentat) {
if (jTextField.isEnabled()) {
e++;
} else {
d++;
}
}
assertEquals("Calculator has wrong amount of JTextField-elements which are set to enabled-state", 1, e);
assertEquals("Calculator has wrong amount of JTextField-elements which are not enabled", 1, d);
}
@Points("40.1")
@Test
public void testOrder() {
JFrame jf = frame.targetCastedTo(JFrame.class);
Component[] cs = jf.getContentPane().getComponents();
assertEquals("First component should be JTextField ",
JTextField.class,
cs[0].getClass());
assertEquals("Second component should be JTextField ",
JTextField.class,
cs[1].getClass());
assertEquals("First JTextField's content is wrong in the beginning",
"0",
((JTextField) cs[0]).getText());
assertEquals("First component should be JTextField which is not enabled, meaning you can't write any text to it",
false,
((JTextField) cs[0]).isEnabled());
assertEquals("Second component should be JTextField which is enabled, meaning that you can write text to it",
true,
((JTextField) cs[1]).isEnabled());
assertTrue(editoitavaTekstikentta() != null);
assertTrue(tulosTekstikentta() != null);
}
// plus miinus, nollaus
@Test
@Points("40.2")
public void plusMinusAndResettingWorks() {
final JButton plus = (JButton) varmista("\\+", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("2");
plus.doClick();
}
});
assertEquals("When user writes 2 to input field and presses +, result field should have value", "2", tulosTekstikentta().getText());
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("7");
plus.doClick();
}
});
assertEquals("At first result field has value 2. When user writes 7 to input field and presses +, result field should have value", "9", tulosTekstikentta().getText());
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("101");
plus.doClick();
}
});
assertEquals("At first result field has value 9. When user writes 101 to input field and presses +, result field should have value", "110", tulosTekstikentta().getText());
final JButton miinus = (JButton) varmista("-", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("11");
miinus.doClick();
}
});
assertEquals("At first result field has value 110. When user writes 11 to input field and presses -, result field should have value", "99", tulosTekstikentta().getText());
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("200");
miinus.doClick();
}
});
assertEquals("At first result field has value 99. When user writes 200 to input field and presses -, result field should have value", "-101", tulosTekstikentta().getText());
final JButton nollaa = (JButton) varmista("Z", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("200");
nollaa.doClick();
}
});
assertEquals("When result field has value -110 and user presses Z, result field should have value", "0", tulosTekstikentta().getText());
}
// nollausnappi disable, virheiden käsittely
@Points("40.3")
@Test
public void resettingButtonEnabledAndDisabled() {
final JButton nollaa = (JButton) varmista("Z", JButton.class);
assertFalse("At first Z-button should be disabled", nollaa.isEnabled());
final JButton plus = (JButton) varmista("\\+", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("2");
plus.doClick();
}
});
assertTrue("When result field has value which isn't 0, Z-button should be enabled", nollaa.isEnabled());
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("200");
nollaa.doClick();
}
});
assertFalse("After pressing Z-button, the button should be disabled", nollaa.isEnabled());
}
@Points("40.3")
@Test
public void inputFieldGoesEmpty() {
final JButton plus = (JButton) varmista("\\+", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("5");
plus.doClick();
}
});
assertEquals("When pressing +, input field should be cleared", "", editoitavaTekstikentta().getText());
final JButton minus = (JButton) varmista("-", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("2");
minus.doClick();
}
});
assertEquals("Whe pressing -, input field should be cleared", "", editoitavaTekstikentta().getText());
final JButton nollaa = (JButton) varmista("Z", JButton.class);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("2");
nollaa.doClick();
}
});
assertEquals("Whe pressing R, input field should be cleared", "", editoitavaTekstikentta().getText());
}
@Points("40.3")
@Test
public void invalidInputsIgnoredWhenPlussing() {
final JButton plus = (JButton) varmista("\\+", JButton.class);
try {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("xx");
plus.doClick();
}
});
} catch (Exception e) {
fail("When input field has an input which is not a valid number, and user presses +, input field should be cleared and nothing else should happen\n"
+ "now happened "+e);
}
assertEquals("When input field has an input which is not a valid number, and user presses +, input field should be cleared and nothing else should happen\n"
+ "value of the input field", "", editoitavaTekstikentta().getText());
assertEquals("When input field has an input which is not a valid number, and user presses +, input field should be cleared and nothing else should happen\n"
+ "Result field was at first 0 and after invalid input it was", "0", tulosTekstikentta().getText());
}
@Points("40.3")
@Test
public void invalidInputsIgnoredWhenSubstracting() {
final JButton plus = (JButton) varmista("\\-", JButton.class);
try {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() throws Throwable {
editoitavaTekstikentta().setText("xx");
plus.doClick();
}
});
} catch (Exception e) {
fail("When input field has an input which is not a valid number, and user presses -, input field should be cleared and nothing else should happen\n"
+ "now happened "+e);
}
assertEquals("When input field has an input which is not a valid number, and user presses -, input field should be cleared and nothing else should happen\n"
+ "value of the input field", "", editoitavaTekstikentta().getText());
assertEquals("When input field has an input which is not a valid number, and user presses -, input field should be cleared and nothing else should happen\n"
+ "Result field was at first 0 and after invalid input it was", "0", tulosTekstikentta().getText());
}
static class M implements ComponentMatcher {
public final String pattern;
public M(String p) {
pattern = p;
}
@Override
public boolean matches(Component cmpnt) {
if (!(cmpnt instanceof AbstractButton)) {
return false;
}
AbstractButton ab = (AbstractButton) cmpnt;
return ab.getText().matches(pattern);
}
@Override
public String toString() {
return "M{" + "pattern=" + pattern + '}';
}
}
public boolean paneliKunnossa() {
Collection<Component> cs = frame.robot.finder().findAll(new GenericTypeMatcher(JPanel.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
boolean ok = false;
for (Component component : cs) {
JPanel jp = (JPanel) component;
LayoutManager lm = jp.getLayout();
if (lm instanceof GridLayout) {
if (((GridLayout) lm).getRows() == 1 && ((GridLayout) lm).getColumns() == 3) {
ok = true;
break;
}
}
}
return ok;
}
public Collection<JTextField> haeTekstikentat() {
return frame.robot.finder().findAll(new GenericTypeMatcher(JTextField.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
}
public JButton minus() {
Collection<JButton> tk = frame.robot.finder().findAll(new GenericTypeMatcher(JButton.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
for (JButton n : tk) {
if (n.getText().equals("-")) {
return n;
}
}
return null;
}
public JButton reset() {
Collection<JButton> tk = frame.robot.finder().findAll(new GenericTypeMatcher(JButton.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
for (JButton n : tk) {
if (n.getText().equals("Z")) {
return n;
}
}
return null;
}
public JButton plus() {
Collection<JButton> tk = frame.robot.finder().findAll(new GenericTypeMatcher(JButton.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
for (JButton n : tk) {
if (n.getText().equals("+")) {
return n;
}
}
return null;
}
public JTextField editoitavaTekstikentta() {
Collection<JTextField> tk = frame.robot.finder().findAll(new GenericTypeMatcher(JTextField.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
for (JTextField jTextField : tk) {
if (jTextField.isEnabled() == true) {
return jTextField;
}
}
return null;
}
public JTextField tulosTekstikentta() {
Collection<JTextField> tk = frame.robot.finder().findAll(new GenericTypeMatcher(JTextField.class) {
@Override
protected boolean isMatching(Component t) {
return true;
}
});
for (JTextField jTextField : tk) {
if (jTextField.isEnabled() == false) {
return jTextField;
}
}
return null;
}
public Component varmista(String teksti, Class tyyppi) {
Component c = null;
try {
c = frame.robot.finder().find(new CalculatorTest.M("(?i).*" + teksti + ".*"));
} catch (ComponentLookupException e) {
fail("Couldn't find " + tyyppi.toString().replaceAll("class", "") + "-typed component, that reads \"" + teksti + "\".\n\nAdditional information:\n" + e);
}
assertEquals("Component that reads \"" + teksti + "\" isn't of the right type!",
tyyppi,
c.getClass());
return c;
}
}
|
3e1d53fd90736c193f8fe5e3c477e487511a0b7a | 3,361 | java | Java | java/src/com/ibm/streamsx/topology/internal/context/remote/BuildRemoteContext.java | ddebrunner/streamsx.topology | 5006453e915ae3a7945585f63f2082610a824023 | [
"Apache-2.0"
] | 31 | 2015-06-24T06:21:14.000Z | 2020-08-28T21:45:50.000Z | java/src/com/ibm/streamsx/topology/internal/context/remote/BuildRemoteContext.java | ddebrunner/streamsx.topology | 5006453e915ae3a7945585f63f2082610a824023 | [
"Apache-2.0"
] | 1,203 | 2015-06-15T02:11:49.000Z | 2021-03-22T09:47:54.000Z | java/src/com/ibm/streamsx/topology/internal/context/remote/BuildRemoteContext.java | ddebrunner/streamsx.topology | 5006453e915ae3a7945585f63f2082610a824023 | [
"Apache-2.0"
] | 53 | 2015-05-28T21:14:16.000Z | 2021-12-23T12:58:59.000Z | 35.378947 | 101 | 0.70723 | 12,435 | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016, 2019
*/
package com.ibm.streamsx.topology.internal.context.remote;
import static com.ibm.streamsx.topology.internal.context.remote.BuildConfigKeys.KEEP_ARTIFACTS;
import static com.ibm.streamsx.topology.internal.context.remote.BuildConfigKeys.determineBuildConfig;
import static com.ibm.streamsx.topology.internal.context.remote.DeployKeys.deploy;
import static com.ibm.streamsx.topology.internal.context.remote.DeployKeys.keepArtifacts;
import static com.ibm.streamsx.topology.internal.gson.GsonUtilities.object;
import java.io.File;
import java.util.concurrent.Future;
import com.google.gson.JsonObject;
import com.ibm.streamsx.topology.context.remote.RemoteContext;
import com.ibm.streamsx.topology.internal.graph.GraphKeys;
import com.ibm.streamsx.topology.internal.gson.GsonUtilities;
/**
* Create a build archive and submit it to a remote Streams instance or
* Streaming Analytics service (in sub-classes).
*
* @param <C>
* Context type used to maintain connection info.
*/
public abstract class BuildRemoteContext<C> extends ZippedToolkitRemoteContext {
@Override
public Type getType() {
return Type.BUNDLE;
}
@Override
public Future<File> _submit(JsonObject submission) throws Exception {
JsonObject deploy = deploy(submission);
C context = createSubmissionContext(deploy);
JsonObject graph = object(submission, "graph");
// Use the SPL compatible form of the name to ensure
// that any strange characters in the name provided by
// the user are not rejected by the build service.
String buildName = GraphKeys.splAppName(graph);
Future<File> archive = super._submit(submission);
report("Building sab");
File buildArchive = archive.get();
// SPL generation submission can modify the job config overlay
JsonObject jco = DeployKeys.copyJobConfigOverlays(deploy);
try {
JsonObject buildConfig = determineBuildConfig(deploy, submission);
if (keepArtifacts(submission))
buildConfig.addProperty(KEEP_ARTIFACTS, true);
JsonObject submitResult = submitBuildArchive(context, buildArchive,
deploy, jco, buildName, buildConfig);
final JsonObject submissionResult = GsonUtilities
.objectCreate(submission, RemoteContext.SUBMISSION_RESULTS);
GsonUtilities.addAll(submissionResult, submitResult);
} finally {
if (!keepArtifacts(submission))
buildArchive.delete();
}
return archive;
}
/**
* Create context specific exception for the submitBuildArchive.
*
* Separated from submitBuildArchive to allow connection info to be check
* early, before any creation of the build archive.
*/
protected abstract C createSubmissionContext(JsonObject deploy) throws Exception;
/**
* Build the archive returning submission results in the key
* RemoteContext.SUBMISSION_RESULTS in the raw result.
*/
protected abstract JsonObject submitBuildArchive(C context, File buildArchive,
JsonObject deploy, JsonObject jco, String buildName,
JsonObject buildConfig) throws Exception;
}
|
3e1d54020972424eebe6871d2dc646ff94d81bca | 1,759 | java | Java | src/top.chenqwwq/leetcode/topic/backtrack/_1140/Solution.java | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/leetcode/topic/backtrack/_1140/Solution.java | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/leetcode/topic/backtrack/_1140/Solution.java | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | 16.752381 | 100 | 0.550881 | 12,436 | package top.chenqwwq.leetcode.topic.backtrack._1140;
import java.util.Arrays;
/**
* 1140. 石子游戏 II
* 亚历克斯和李继续他们的石子游戏。许多堆石子 排成一行,每堆都有正整数颗石子 piles[i]。游戏以谁手中的石子最多来决出胜负。
* <p>
* 亚历克斯和李轮流进行,亚历克斯先开始。最初,M = 1。
* <p>
* 在每个玩家的回合中,该玩家可以拿走剩下的 前 X 堆的所有石子,其中 1 <= X <= 2M。然后,令 M = max(M, X)。
* <p>
* 游戏一直持续到所有石子都被拿走。
* <p>
* 假设亚历克斯和李都发挥出最佳水平,返回亚历克斯可以得到的最大数量的石头。
* <p>
* <p>
* <p>
* 示例:
* <p>
* 输入:piles = [2,7,9,4,4]
* 输出:10
* 解释:
* 如果亚历克斯在开始时拿走一堆石子,李拿走两堆,接着亚历克斯也拿走两堆。在这种情况下,亚历克斯可以拿到 2 + 4 + 4 = 10 颗石子。
* 如果亚历克斯在开始时拿走两堆石子,那么李就可以拿走剩下全部三堆石子。在这种情况下,亚历克斯可以拿到 2 + 7 = 9 颗石子。
* 所以我们返回更大的 10。
* <p>
* <p>
* 提示:
* <p>
* 1 <= piles.length <= 100
* 1 <= piles[i] <= 10 ^ 4
*
* @author chen
* @date 2021/5/22
**/
public class Solution {
public static void main(String[] args) {
final int i = new Solution().stoneGameII(new int[]{2, 7, 9, 4, 2, 4, 7, 1, 2, 5, 1});
System.out.println(i);
}
// TODO: 记忆化搜索未完成
public int stoneGameII(int[] piles) {
final int n = piles.length;
int[][] memo = new int[n][n + 1];
// 计算前缀和
int[] pre = new int[n + 1];
pre[0] = 0;
for (int i = 0; i < n; i++) {
pre[i + 1] = pre[i] + piles[i];
}
return bt(pre, memo, 1, 1, true);
}
private int bt(int[] pre, int[][] memo, int idx, int cnt, boolean isA) {
if (idx >= pre.length) {
return 0;
}
if (memo[idx][cnt] != 0) {
return memo[idx][cnt];
}
int max = isA ? 0 : Integer.MIN_VALUE;
for (int i = 0; i < cnt && idx + i < pre.length; i++) {
max = Math.max(max, isA
? pre[idx + i] - pre[idx - 1] + bt(pre, memo, idx + i + 1, 2 * Math.max(i + 1, cnt / 2), false)
: -bt(pre, memo, idx + i + 1, 2 * Math.max(i + 1, cnt / 2), true));
}
final int i = isA ? max : -max;
return i;
}
}
|
3e1d541c9b2df693c8106f37a6dd335b8932365b | 1,417 | java | Java | src/main/java/net/canadensys/dataportal/vascan/query/ChecklistQuery.java | Canadensys/vascan | 40e5f14fc82bd48552d993b97ffb1840487284f7 | [
"MIT"
] | 2 | 2019-04-14T03:36:25.000Z | 2020-06-09T19:37:27.000Z | src/main/java/net/canadensys/dataportal/vascan/query/ChecklistQuery.java | Canadensys/vascan | 40e5f14fc82bd48552d993b97ffb1840487284f7 | [
"MIT"
] | 28 | 2015-01-26T21:40:29.000Z | 2021-11-02T13:49:16.000Z | src/main/java/net/canadensys/dataportal/vascan/query/ChecklistQuery.java | Canadensys/vascan | 40e5f14fc82bd48552d993b97ffb1840487284f7 | [
"MIT"
] | 2 | 2019-04-14T03:36:30.000Z | 2019-04-22T13:09:27.000Z | 17.936709 | 66 | 0.711362 | 12,437 | package net.canadensys.dataportal.vascan.query;
import net.canadensys.dataportal.vascan.dao.query.RegionQueryPart;
/**
* Checklist query container object.
* @author cgendreau
*
*/
public class ChecklistQuery {
private RegionQueryPart regionQueryPart;
private String habit;
private int taxonId = -1;
private String[] distributionStatus;
private String[] rank;
private boolean hybrids;
private String sort;
public void setRegionQueryPart(RegionQueryPart regionQueryPart) {
this.regionQueryPart = regionQueryPart;
}
public RegionQueryPart getRegionQueryPart() {
return regionQueryPart;
}
public String getHabit() {
return habit;
}
public void setHabit(String habit) {
this.habit = habit;
}
public int getTaxonId() {
return taxonId;
}
public void setTaxonId(int taxonId) {
this.taxonId = taxonId;
}
public String[] getDistributionStatus() {
return distributionStatus;
}
public void setDistributionStatus(String[] distributionStatus) {
this.distributionStatus = distributionStatus;
}
public String[] getRank() {
return rank;
}
public void setRank(String[] rank) {
this.rank = rank;
}
public boolean isHybrids() {
return hybrids;
}
public void setHybrids(boolean hybrids) {
this.hybrids = hybrids;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
}
|
3e1d548ff6a5781e684aefd6348acc29062f3699 | 10,598 | java | Java | subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/transform/DefaultArtifactTransforms.java | rspieldenner/gradle | 700db5264bc9a55e2df72e80f0756d04c1c1fb90 | [
"Apache-2.0"
] | null | null | null | subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/transform/DefaultArtifactTransforms.java | rspieldenner/gradle | 700db5264bc9a55e2df72e80f0756d04c1c1fb90 | [
"Apache-2.0"
] | null | null | null | subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/transform/DefaultArtifactTransforms.java | rspieldenner/gradle | 700db5264bc9a55e2df72e80f0756d04c1c1fb90 | [
"Apache-2.0"
] | null | null | null | 43.975104 | 180 | 0.671825 | 12,438 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.transform;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.io.Files;
import org.gradle.api.Buildable;
import org.gradle.api.Transformer;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.artifacts.component.ComponentArtifactIdentifier;
import org.gradle.api.attributes.Attribute;
import org.gradle.api.attributes.AttributeContainer;
import org.gradle.api.internal.artifacts.DefaultResolvedArtifact;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactVisitor;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedArtifactSet;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedVariant;
import org.gradle.api.internal.attributes.AttributeContainerInternal;
import org.gradle.api.tasks.TaskDependency;
import org.gradle.internal.Pair;
import org.gradle.internal.component.local.model.ComponentFileArtifactIdentifier;
import org.gradle.internal.component.model.DefaultIvyArtifactName;
import org.gradle.internal.component.model.IvyArtifactName;
import org.gradle.internal.text.TreeFormatter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class DefaultArtifactTransforms implements ArtifactTransforms {
private final VariantAttributeMatchingCache matchingCache;
public DefaultArtifactTransforms(VariantAttributeMatchingCache matchingCache) {
this.matchingCache = matchingCache;
}
public Transformer<ResolvedArtifactSet, Collection<? extends ResolvedVariant>> variantSelector(AttributeContainerInternal requested) {
return new AttributeMatchingVariantSelector(requested.asImmutable());
}
private class AttributeMatchingVariantSelector implements Transformer<ResolvedArtifactSet, Collection<? extends ResolvedVariant>> {
private final AttributeContainerInternal requested;
private AttributeMatchingVariantSelector(AttributeContainerInternal requested) {
this.requested = requested;
}
@Override
public String toString() {
return "Variant selector for " + requested;
}
@Override
public ResolvedArtifactSet transform(Collection<? extends ResolvedVariant> variants) {
List<? extends ResolvedVariant> matches = matchingCache.selectMatches(variants, requested);
if (matches.size() > 0) {
return matches.get(0).getArtifacts();
}
// TODO - fail on ambiguous match
List<Pair<ResolvedVariant, ConsumerVariantMatchResult.ConsumerVariant>> candidates = new ArrayList<Pair<ResolvedVariant, ConsumerVariantMatchResult.ConsumerVariant>>();
for (ResolvedVariant variant : variants) {
AttributeContainerInternal variantAttributes = variant.getAttributes().asImmutable();
ConsumerVariantMatchResult matchResult = new ConsumerVariantMatchResult();
matchingCache.collectConsumerVariants(variantAttributes, requested, matchResult);
for (ConsumerVariantMatchResult.ConsumerVariant consumerVariant : matchResult.getMatches()) {
candidates.add(Pair.of(variant, consumerVariant));
}
}
if (candidates.size() == 1) {
Pair<ResolvedVariant, ConsumerVariantMatchResult.ConsumerVariant> result = candidates.get(0);
return new TransformingArtifactSet(result.getLeft().getArtifacts(), result.getRight().attributes, result.getRight().transformer);
}
if (!candidates.isEmpty()) {
TreeFormatter formatter = new TreeFormatter();
formatter.node("Found multiple transforms that can produce a variant for consumer attributes");
formatter.startChildren();
formatAttributes(formatter, requested);
formatter.endChildren();
formatter.node("Found the following transforms");
formatter.startChildren();
for (Pair<ResolvedVariant, ConsumerVariantMatchResult.ConsumerVariant> candidate : candidates) {
formatter.node("Transform from variant");
formatter.startChildren();
formatAttributes(formatter, candidate.getLeft().getAttributes());
formatter.endChildren();
}
formatter.endChildren();
throw new AmbiguousTransformException(formatter.toString());
}
return ResolvedArtifactSet.EMPTY;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AttributeMatchingVariantSelector)) {
return false;
}
AttributeMatchingVariantSelector that = (AttributeMatchingVariantSelector) o;
return Objects.equal(requested, that.requested);
}
@Override
public int hashCode() {
return Objects.hashCode(requested);
}
}
private void formatAttributes(TreeFormatter formatter, AttributeContainerInternal attributes) {
for (Attribute<?> attribute : Ordering.usingToString().sortedCopy(attributes.keySet())) {
formatter.node(attribute.getName() + " '" + attributes.getAttribute(attribute) + "'");
}
}
private class TransformingArtifactSet implements ResolvedArtifactSet {
private final ResolvedArtifactSet delegate;
private final AttributeContainerInternal target;
private final Transformer<List<File>, File> transform;
TransformingArtifactSet(ResolvedArtifactSet delegate, AttributeContainerInternal target, Transformer<List<File>, File> transform) {
this.delegate = delegate;
this.target = target;
this.transform = transform;
}
@Override
public Set<ResolvedArtifact> getArtifacts() {
throw new UnsupportedOperationException();
}
@Override
public void collectBuildDependencies(Collection<? super TaskDependency> dest) {
delegate.collectBuildDependencies(dest);
}
@Override
public void visit(ArtifactVisitor visitor) {
delegate.visit(new ArtifactTransformingVisitor(visitor, target, transform));
}
}
private class ArtifactTransformingVisitor implements ArtifactVisitor {
private final ArtifactVisitor visitor;
private final AttributeContainerInternal target;
private final Transformer<List<File>, File> transform;
private ArtifactTransformingVisitor(ArtifactVisitor visitor, AttributeContainerInternal target, Transformer<List<File>, File> transform) {
this.visitor = visitor;
this.target = target;
this.transform = transform;
}
@Override
public void visitArtifact(AttributeContainer variant, ResolvedArtifact artifact) {
List<ResolvedArtifact> transformResults = matchingCache.getTransformedArtifacts(artifact, target);
if (transformResults != null) {
for (ResolvedArtifact resolvedArtifact : transformResults) {
visitor.visitArtifact(target, resolvedArtifact);
}
return;
}
List<File> transformedFiles;
try {
transformedFiles = transform.transform(artifact.getFile());
} catch (Throwable t) {
visitor.visitFailure(t);
return;
}
TaskDependency buildDependencies = ((Buildable) artifact).getBuildDependencies();
transformResults = Lists.newArrayListWithCapacity(transformedFiles.size());
for (File output : transformedFiles) {
ComponentArtifactIdentifier newId = new ComponentFileArtifactIdentifier(artifact.getId().getComponentIdentifier(), output.getName());
String extension = Files.getFileExtension(output.getName());
IvyArtifactName artifactName = new DefaultIvyArtifactName(output.getName(), extension, extension);
ResolvedArtifact resolvedArtifact = new DefaultResolvedArtifact(artifact.getModuleVersion().getId(), artifactName, newId, buildDependencies, output);
transformResults.add(resolvedArtifact);
visitor.visitArtifact(target, resolvedArtifact);
}
matchingCache.putTransformedArtifact(artifact, this.target, transformResults);
}
@Override
public void visitFailure(Throwable failure) {
visitor.visitFailure(failure);
}
@Override
public boolean includeFiles() {
return visitor.includeFiles();
}
@Override
public void visitFile(ComponentArtifactIdentifier artifactIdentifier, AttributeContainer variant, File file) {
List<File> result;
try {
result = matchingCache.getTransformedFile(file, target);
if (result == null) {
result = transform.transform(file);
matchingCache.putTransformedFile(file, target, ImmutableList.copyOf(result));
}
} catch (Throwable t) {
visitor.visitFailure(t);
return;
}
if (!result.isEmpty()) {
for (File outputFile : result) {
visitor.visitFile(new ComponentFileArtifactIdentifier(artifactIdentifier.getComponentIdentifier(), outputFile.getName()), target, outputFile);
}
}
}
}
}
|
3e1d555576b7fee0b8122839b6b912e221e3e82d | 15,629 | java | Java | src/main/java/de/fhg/fokus/ims/core/utils/Parser.java | fhg-fokus-nubomedia/nubomedia-ims-connector | a6dac8810f779c75351355cdd03933fedf07a99a | [
"Apache-2.0"
] | 1 | 2017-10-23T04:22:01.000Z | 2017-10-23T04:22:01.000Z | src/main/java/de/fhg/fokus/ims/core/utils/Parser.java | fhg-fokus-nubomedia/nubomedia-ims-connector | a6dac8810f779c75351355cdd03933fedf07a99a | [
"Apache-2.0"
] | null | null | null | src/main/java/de/fhg/fokus/ims/core/utils/Parser.java | fhg-fokus-nubomedia/nubomedia-ims-connector | a6dac8810f779c75351355cdd03933fedf07a99a | [
"Apache-2.0"
] | null | null | null | 34.964206 | 163 | 0.64214 | 12,439 | package de.fhg.fokus.ims.core.utils;
import java.util.Vector;
/**
* Class Parser allows the parsing of String objects.
* <BR> An object Parser is costructed from a String object and provides various methods for parsing the String in a stream oriented manner.
* The class Parser also collects different <b>static</b> methods for parsing non-pre-associated strings.<BR>
* Parser uses the following definitions:<PRE>
* <BR><i>string</i> = any string of chars included between ' ' and '~'
* <BR><i>word</i> = any string of chars without separators
* <BR><i>separators</i> = a vector of chars; e.g. ( ) < > @ , ; : \ " / | [ ] ? = { } HT SP
* <BR><i>alpha</i> = a-z, A-Z
* <BR><i>digit</i> = 0-9
* <BR><i>integer</i> = any <i>digit word</i> parsed by {@link java.lang.Integer Integer.parseInt(String)}
* </PRE>
*/
public class Parser
{
/** The string that is being parsed. */
protected String str;
/** The the current pointer to the next char within the string. */
protected int index;
/** Creates the Parser from the String <i>s</i> and point to the beginning of the string.*/
public Parser(String s)
{ if (s==null) throw (new RuntimeException("Tried to costruct a new Parser with a null String"));
str=s;
index=0;
}
/** Creates the Parser from the String <i>s</i> and point to the position <i>i</i>. */
public Parser(String s, int i)
{ if (s==null) throw (new RuntimeException("Tried to costruct a new Parser with a null String"));
str=s;
index=i;
}
/** Creates the Parser from the StringBuffer <i>sb</i> and point to the beginning of the string.*/
public Parser(StringBuffer sb)
{ if (sb==null) throw (new RuntimeException("Tried to costruct a new Parser with a null StringBuffer"));
str=sb.toString();
index=0;
}
/** Creates the Parser from the StringBuffer <i>sb</i> and point to the position <i>i</i>. */
public Parser(StringBuffer sb, int i)
{ if (sb==null) throw (new RuntimeException("Tried to costruct a new Parser with a null StringBuffer"));
str=sb.toString();
index=i;
}
/** Gets the current index position. */
public int getPos() { return index; }
/** Gets the entire string */
public String getWholeString() { return str; }
/** Gets the rest of the (unparsed) string. */
public String getRemainingString() { return str.substring(index); }
/** Returns a new the Parser of <i>len</i> chars statirng from the current position. */
public Parser subParser(int len) { return new Parser(str.substring(index,index+len)); }
/** Length of unparsed string. */
public int length() { return (str.length()-index); }
/** Whether there are more chars to parse. */
public boolean hasMore() { return length()>0; }
/** Gets the next char and go over */
public char getChar() { return str.charAt(index++); }
/** Gets the char at distance <i>n</i> WITHOUT going over */
public char charAt(int n) { return str.charAt(index+n); }
/** Gets the next char WITHOUT going over */
public char nextChar() { return charAt(0); }
/** Goes to position <i>i</i> */
public Parser setPos(int i) { index= i; return this; }
/** Goes to the next occurence of <i>char c</i> */
public Parser goTo(char c) { index=str.indexOf(c,index); if (index<0) index=str.length(); return this; }
/** Goes to the next occurence of any char of array <i>cc</i> */
public Parser goTo(char[] cc) { index=indexOf(cc); if (index<0) index=str.length(); return this; }
/** Goes to the next occurence of <i>String s</i> */
public Parser goTo(String s) { index=str.indexOf(s,index); if (index<0) index=str.length(); return this; }
/** Goes to the next occurence of any string of array <i>ss</i> */
public Parser goTo(String[] ss) { index=indexOf(ss); if (index<0) index=str.length(); return this; }
/** Goes to the next occurence of <i>String s</i> */
public Parser goToIgnoreCase(String s) { index=indexOfIgnoreCase(s); if (index<0) index=str.length(); return this; }
/** Goes to the next occurence of any string of array <i>ss</i> */
public Parser goToIgnoreCase(String[] ss) { index=indexOfIgnoreCase(ss); if (index<0) index=str.length(); return this; }
/** Goes to the begin of the new line */
public Parser goToNextLine()
{ while (index<str.length() && !isCRLF(str.charAt(index))) index++;
// skip the end of the line (i.e. '\r' OR '\n' OR '\r\n')
if (index<str.length()) { if (str.startsWith("\r\n",index)) index+=2; else index++; }
return this;
}
/** Characters space (SP) and tab (HT). */
public static char[] WSP={' ','\t'};
/** The same as WSP (for legacy) */
public static char[] SPACE=WSP;
/** Characters CR and LF.*/
public static char[] CRLF={'\r','\n'};
/** Characters white-space, tab, CR, and LF. */
public static char[] WSPCRLF={' ','\t','\r','\n'};
/** True if char <i>ch</i> is any char of array <i>ca</i> */
public static boolean isAnyOf(char[] ca, char ch)
{ boolean found=false;
for (int i=0; i<ca.length; i++) if (ca[i]==ch) { found=true; break; }
return found;
}
/** Up alpha */
public static boolean isUpAlpha(char c) { return (c>='A' && c<='Z'); }
/** Low alpha */
public static boolean isLowAlpha(char c) { return (c>='a' && c<='z'); }
/** Alpha */
public static boolean isAlpha(char c) { return (isUpAlpha(c) || isLowAlpha(c)); }
/** Alphanum */
public static boolean isAlphanum(char c){ return (isAlpha(c) || isDigit(c)); }
/** Digit */
public static boolean isDigit(char c) { return (c>='0' && c<='9'); }
/** Valid ASCII char */
public static boolean isChar(char c) { return (c>' ' && c<='~'); }
/** CR */
public static boolean isCR(char c) { return (c=='\r'); }
/** LF */
public static boolean isLF(char c) { return (c=='\n'); }
/** CR or LF */
public static boolean isCRLF(char c) { return isAnyOf(CRLF,c); }
/** HT */
public static boolean isHT(char c) { return (c=='\t'); }
/** SP */
public static boolean isSP(char c) { return (c==' '); }
/** SP or tab */
public static boolean isWSP(char c){ return isAnyOf(WSP,c); }
/** SP, tab, CR, or LF */
public static boolean isWSPCRLF(char c){ return isAnyOf(WSPCRLF,c); }
/** Compares two chars ignoring case */
public static int compareIgnoreCase(char c1, char c2)
{ if (isUpAlpha(c1)) c1+=32;
if (isUpAlpha(c2)) c2+=32;
return c1-c2;
}
/*
private boolean isUpAlpha(int i) { return isUpAlpha(str.charAt(i)); }
private boolean isLowAlpha(int i) { return isLowAlpha(str.charAt(i)); }
private boolean isAlpha(int i) { return isAlpha(str.charAt(i)); }
private boolean isDigit(int i) { return isDigit(str.charAt(i)); }
private boolean isChar(int i) { return isChar(str.charAt(i)); }
private boolean isCR(int i) { return isCR(str.charAt(i)); }
private boolean isLF(int i) { return isLF(str.charAt(i)); }
private boolean isHT(int i) { return isHT(str.charAt(i)); }
private boolean isSP(int i) { return isSP(str.charAt(i)); }
private boolean isCRLF(int i) { return (isCR(str.charAt(i)) && isLF(str.charAt(i+1))); }
private boolean isSeparator(int i) { return isSeparator(str.charAt(i)); }
*/
// ************************ Indexes ************************
/** Gets the index of the first occurence of char <i>c</i> */
public int indexOf(char c)
{ return str.indexOf(c,index);
}
/** Gets the index of the first occurence of any char of array <i>cc</i> within string <i>str</i> starting form <i>begin</i>; return -1 if no occurence is found*/
public int indexOf(char[] cc)
{ boolean found=false;
int begin=index;
while (begin<str.length() && !found)
{ for (int i=0; i<cc.length; i++)
if (str.charAt(begin)==cc[i]) { found=true; break; }
begin++;
}
return (found)? (begin-1) : -1;
}
/** Gets the index of the first occurence of String <i>s</i> */
public int indexOf(String s)
{ return str.indexOf(s,index);
}
/** Gets the index of the first occurence of any string of array <i>ss</i> within string <i>str</i>; return -1 if no occurence is found. */
public int indexOf(String[] ss)
{ boolean found=false;
int begin=index;
while (begin<str.length() && !found)
{ for (int i=0; i<ss.length; i++)
if (str.startsWith(ss[i],begin)) { found=true; break; }
begin++;
}
return (found)? (begin-1) : -1;
}
/** Gets the index of the first occurence of String <i>s</i> ignoring case. */
public int indexOfIgnoreCase(String s)
{ Parser par=new Parser(str,index);
while (par.hasMore())
{ if (par.startsWithIgnoreCase(s)) return par.getPos();
else par.skipChar();
}
return -1;
}
/** Gets the index of the first occurence of any string of array <i>ss</i> ignoring case. */
public int indexOfIgnoreCase(String[] ss)
{ Parser par=new Parser(str,index);
while (par.hasMore())
{ if (par.startsWithIgnoreCase(ss)) return par.getPos();
else par.skipChar();
}
return -1;
}
/** Gets the begin of next line */
public int indexOfNextLine()
{ Parser par=new Parser(str,index);
par.goToNextLine();
int i=par.getPos();
return (i<str.length())? i : -1;
}
// ********************* Starts with *********************
/** Whether next chars equal to a specific String <i>s</i>. */
public boolean startsWith(String s)
{ return str.startsWith(s,index);
}
/** Whether next chars equal to any string of array <i>ss</i>. */
public boolean startsWith(String[] ss)
{ for (int i=0; i<ss.length; i++)
if (str.startsWith(ss[i],index)) return true;
return false;
}
/** Whether next chars equal to a specific String <i>s</i> ignoring case. */
public boolean startsWithIgnoreCase(String s)
{ for (int k=0; k<s.length() && (index+k)<str.length(); k++)
{ if (compareIgnoreCase(s.charAt(k),str.charAt(index+k))!=0) return false;
}
return true;
}
/** Whether next chars equal to any string of array <i>ss</i> ignoring case. */
public boolean startsWithIgnoreCase(String[] ss)
{ for (int i=0; i<ss.length; i++)
{ boolean equal=true;
for (int k=0; k<ss[i].length() && (index+k)<str.length(); k++)
{ if (!(equal=(compareIgnoreCase(ss[i].charAt(k),str.charAt(index+k))==0))) break;
}
if (equal) return true;
}
return false;
}
// ************************ Skips ************************
/** Skips one char */
public Parser skipChar()
{ if(index<str.length()) index++;
return this;
}
/** Skips N chars */
public Parser skipN(int n)
{ index+=n;
if(index>str.length()) index=str.length();
return this;
}
/** Skips all spaces */
public Parser skipWSP()
{ while (index<str.length() && isSP(str.charAt(index))) index++;
return this;
}
/** The same as skipWSP() (for legacy) */
/*public Parser skipSP()
{ return skipWSP();
}*/
/** Skips return lines */
public Parser skipCRLF()
{ while (index<str.length() && isCRLF(str.charAt(index))) index++;
return this;
}
/** Skips white spaces or return lines */
public Parser skipWSPCRLF()
{ while (index<str.length() && isWSPCRLF(str.charAt(index))) index++;
return this;
}
/** Skips any selected chars */
public Parser skipChars(char[] cc)
{ while (index<str.length() && isAnyOf(cc,nextChar())) index++;
return this;
}
/** Skips a continuous string of char and go to the next "blank" char */
public Parser skipString()
{ getString();
return this;
}
// ************************ Gets ************************
/** Gets a continuous string of char and go to the next char */
public String getString()
{ int begin=index;
while (begin<str.length() && !isChar(str.charAt(begin))) begin++;
int end=begin;
while (end<str.length() && isChar(str.charAt(end))) end++;
index=end;
return str.substring(begin,end);
}
/** Gets a string of length <i>len</i> and move over. */
public String getString(int len)
{ int start=index;
index=start+len;
return str.substring(start,index);
}
/** Gets a string of chars separated by any of chars of <i>separators</i> */
public String getWord(char[] separators)
{ int begin=index;
while (begin<str.length() && isAnyOf(separators,str.charAt(begin))) begin++;
int end=begin;
while (end<str.length() && !isAnyOf(separators,str.charAt(end))) end++;
index=end;
return str.substring(begin,end);
}
/** Gets an integer and point to the next char */
public int getInt()
{ return Integer.parseInt(this.getString());
}
/** Gets a double and point to the next char */
public double getDouble()
{ return Double.parseDouble(this.getString());
}
/** Gets all chars until the end of the line (or the end of the parser)
* and go to the next line. */
public String getLine()
{ int end=index;
while (end<str.length() && !isCRLF(str.charAt(end))) end++;
String line=str.substring(index,end);
index=end;
// skip the end of the line (i.e. '\r' OR '\n' OR '\r\n')
if (index<str.length())
{ if (str.startsWith("\r\n",index)) index+=2;
else index++;
}
return line;
}
//********************** Vectors/arrays **********************
/** Gets all string of chars separated by any char belonging to <i>separators</i> */
public Vector getWordVector(char[] separators)
{ Vector list=new Vector();
do { list.addElement(getWord(separators)); } while (hasMore());
return list;
}
/** Gets all string of chars separated by any char belonging to <i>separators</i> */
public String[] getWordArray(char[] separators)
{ Vector list=getWordVector(separators);
String[] array=new String[list.size()];
for (int i=0; i<list.size(); i++) array[i]=(String)list.elementAt(i);
return array;
}
/** Gets all strings */
public Vector getStringVector()
{ Vector list=new Vector();
do { list.addElement(getString()); } while (hasMore());
return list;
}
/** Gets all string */
public String[] getStringArray()
{ Vector list=getStringVector();
String[] array=new String[list.size()];
for (int i=0; i<list.size(); i++) array[i]=(String)list.elementAt(i);
return array;
}
//********************** Quoted Strings **********************
/** Gets a string of chars separated by any of chars in <i>separators</i>
* , skipping any separator inside possible quoted texts. */
public String getWordSkippingQuoted(char[] separators)
{ int begin=index;
while (begin<str.length() && isAnyOf(separators,str.charAt(begin))) begin++;
boolean inside_quoted_string=false;
int end=begin;
while (end<str.length() && (!isAnyOf(separators,str.charAt(end)) || inside_quoted_string))
{ if (str.charAt(end)=='"') inside_quoted_string=!inside_quoted_string;
end++;
}
index=end;
return str.substring(begin,end);
}
/** Gets the first quatable string, that is a normal string, or text in quotes.
* <br>In the latter case, quotes are dropped. */
public String getStringUnquoted()
{ // jump possible "non-chars"
while (index<str.length() && !isChar(str.charAt(index))) index++;
if (index==str.length()) return str.substring(index,index);
// check whether is a quoted string
int next_qmark;
if (str.charAt(index)=='"' && (next_qmark=str.indexOf("\"",index+1))>0)
{ // is quoted text
String qtext=str.substring(index+1,next_qmark);
index=next_qmark+1;
return qtext;
}
else
{ // is not a quoted text
return getString();
}
}
/** Points to the next occurence of <i>char c</i> not in quotes. */
public Parser goToSkippingQuoted(char c)
{ boolean inside_quotes=false;
try
{ while (index<str.length() && (!(nextChar()==c) || inside_quotes))
{ if (nextChar()=='"') inside_quotes=!inside_quotes;
index++;
}
}
catch (RuntimeException e)
{ System.out.println("len= "+str.length());
System.out.println("index= "+index);
throw e;
}
return this;
}
//************************* toString *************************
/** convert the rest of the unparsed chars into a string */
public String toString()
{ return getRemainingString();
}
}
|
3e1d5599906989a039953753a3ff2a981b5f2ec3 | 3,871 | java | Java | MLKit-Sample/module-text/src/main/java/com/mlkit/sample/processor/gcr/passcard/PassCardProcessor.java | everyline/HUAWEI-HMS-MLKit-Sample | a9fea6bf620607882974ba15a299ef30e6990059 | [
"Apache-2.0"
] | 56 | 2020-03-15T09:58:21.000Z | 2021-12-23T12:39:22.000Z | MLKit-Sample/module-text/src/main/java/com/mlkit/sample/processor/gcr/passcard/PassCardProcessor.java | everyline/HUAWEI-HMS-MLKit-Sample | a9fea6bf620607882974ba15a299ef30e6990059 | [
"Apache-2.0"
] | 10 | 2020-03-20T08:05:28.000Z | 2021-01-18T10:28:42.000Z | MLKit-Sample/module-text/src/main/java/com/mlkit/sample/processor/gcr/passcard/PassCardProcessor.java | everyline/HUAWEI-HMS-MLKit-Sample | a9fea6bf620607882974ba15a299ef30e6990059 | [
"Apache-2.0"
] | 30 | 2020-03-14T07:37:35.000Z | 2021-12-29T11:26:15.000Z | 32.258333 | 89 | 0.605528 | 12,440 | /**
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mlkit.sample.processor.gcr.passcard;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.Log;
import com.huawei.hms.mlsdk.text.MLText;
import com.mlkit.sample.activity.entity.BlockItem;
import com.mlkit.sample.activity.entity.GeneralCardResult;
import com.mlkit.sample.processor.gcr.GeneralCardProcessor;
import com.mlkit.sample.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Post processing plug-in of Hong Kong, Macao and Taiwan pass recognition
*
* @since 2020-03-12
*/
public class PassCardProcessor implements GeneralCardProcessor {
private static final String TAG = "PassCardProcessor";
private final MLText text;
public PassCardProcessor(MLText text) {
this.text = text;
}
@Override
public GeneralCardResult getResult() {
List<MLText.Block> blocks = text.getBlocks();
if (blocks.isEmpty()) {
Log.i(TAG, "Result blocks is empty");
return null;
}
ArrayList<BlockItem> originItems = getOriginItems(blocks);
String valid = "";
String number = "";
boolean validFlag = false;
boolean numberFlag = false;
for (BlockItem item : originItems) {
String tempStr = item.text;
if (!validFlag) {
String result = tryGetValidDate(tempStr);
if (!result.isEmpty()) {
valid = result;
validFlag = true;
}
}
if (!numberFlag) {
String result = tryGetCardNumber(tempStr);
if (!result.isEmpty()) {
number = result;
numberFlag = true;
}
}
}
Log.i(TAG, "valid: " + valid);
Log.i(TAG, "number: " + number);
return new GeneralCardResult(valid, number);
}
private String tryGetValidDate(String originStr) {
return StringUtils.getCorrectValidDate(originStr);
}
private String tryGetCardNumber(String originStr) {
String result = StringUtils.getPassCardNumber(originStr);
if (!result.isEmpty()) {
result = result.toUpperCase(Locale.ENGLISH);
result = StringUtils.filterString(result, "[^0-9A-Z<]");
}
return result;
}
private ArrayList<BlockItem> getOriginItems(List<MLText.Block> blocks) {
ArrayList<BlockItem> originItems = new ArrayList<>();
for (MLText.Block block : blocks) {
// Add in behavior units
List<MLText.TextLine> lines = block.getContents();
for (MLText.TextLine line : lines) {
String text = line.getStringValue();
text = StringUtils.filterString(text, "[^a-zA-Z0-9\\.\\-,<\\(\\)\\s]");
Log.d(TAG, "text: " + text);
Point[] points = line.getVertexes();
Rect rect = new Rect(points[0].x, points[0].y, points[2].x, points[2].y);
BlockItem item = new BlockItem(text, rect);
originItems.add(item);
}
}
return originItems;
}
}
|
3e1d569d9e294e8a5692766574728d87ab781fdf | 2,689 | java | Java | src/main/java/com/microsoft/graph/requests/EnrollmentProfileExportMobileConfigRequestBuilder.java | microsoftgraph/msgraph-beta-sdk-java | 2d88d8e031a209cc2152834fd76151e99ea07fad | [
"MIT"
] | 11 | 2020-05-20T08:44:09.000Z | 2022-02-23T21:45:27.000Z | src/main/java/com/microsoft/graph/requests/EnrollmentProfileExportMobileConfigRequestBuilder.java | microsoftgraph/msgraph-beta-sdk-java | 2d88d8e031a209cc2152834fd76151e99ea07fad | [
"MIT"
] | 85 | 2019-12-18T17:57:37.000Z | 2022-03-29T12:49:01.000Z | src/main/java/com/microsoft/graph/requests/EnrollmentProfileExportMobileConfigRequestBuilder.java | microsoftgraph/msgraph-beta-sdk-java | 2d88d8e031a209cc2152834fd76151e99ea07fad | [
"MIT"
] | 7 | 2020-04-30T20:17:37.000Z | 2022-02-10T08:25:26.000Z | 44.816667 | 227 | 0.713276 | 12,441 | // Template Source: BaseMethodRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.requests.EnrollmentProfileExportMobileConfigRequest;
import com.microsoft.graph.models.EnrollmentProfile;
import com.microsoft.graph.http.BaseFunctionRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonElement;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Enrollment Profile Export Mobile Config Request Builder.
*/
public class EnrollmentProfileExportMobileConfigRequestBuilder extends BaseFunctionRequestBuilder<String> {
/**
* The request builder for this EnrollmentProfileExportMobileConfig
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public EnrollmentProfileExportMobileConfigRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* Creates the EnrollmentProfileExportMobileConfigRequest
*
* @param requestOptions the options for the request
* @return the EnrollmentProfileExportMobileConfigRequest instance
*/
@Nonnull
public EnrollmentProfileExportMobileConfigRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the EnrollmentProfileExportMobileConfigRequest with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for the request
* @return the EnrollmentProfileExportMobileConfigRequest instance
*/
@Nonnull
public EnrollmentProfileExportMobileConfigRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
final EnrollmentProfileExportMobileConfigRequest request = new EnrollmentProfileExportMobileConfigRequest(
getRequestUrl(),
getClient(),
requestOptions);
return request;
}
}
|
3e1d59d82da68bd70637824612e86d683b17682a | 1,754 | java | Java | chapter_003/src/main/java/ru/job4j/collections/tree/Tree.java | Istern22/svetlana.ragulina | 67909d47d34383ecbf8599f4b8dc94f7c4f929fd | [
"Apache-2.0"
] | null | null | null | chapter_003/src/main/java/ru/job4j/collections/tree/Tree.java | Istern22/svetlana.ragulina | 67909d47d34383ecbf8599f4b8dc94f7c4f929fd | [
"Apache-2.0"
] | 5 | 2020-07-30T06:14:22.000Z | 2022-02-16T01:10:17.000Z | chapter_003/src/main/java/ru/job4j/collections/tree/Tree.java | Istern22/svetlana.ragulina | 67909d47d34383ecbf8599f4b8dc94f7c4f929fd | [
"Apache-2.0"
] | null | null | null | 25.057143 | 80 | 0.50057 | 12,442 | package ru.job4j.collections.tree;
import java.util.*;
class Tree<E> implements SimpleTree<E>, Iterable {
private final Node<E> root;
Tree(final E root) {
this.root = new Node<>(root);
}
public boolean isBinary() {
var isBinary = true;
var it = iterator();
while (it.hasNext() && isBinary) {
isBinary = it.next().children.size() <= 2;
}
return isBinary;
}
@Override
public boolean add(E parent, E child) {
boolean result = false;
var parentNode = findBy(parent);
var childNode = findBy(child);
if (parentNode.isPresent() && !childNode.isPresent()) {
parentNode.get().children.add(new Node<E>(child));
result = true;
}
return result;
}
@Override
public Optional<Node<E>> findBy(E value) {
Optional<Node<E>> rsl = Optional.empty();
Queue<Node<E>> data = new LinkedList<>();
data.offer(this.root);
while (!data.isEmpty()) {
Node<E> el = data.poll();
if (el.value.equals(value)) {
rsl = Optional.of(el);
break;
}
data.addAll(el.children);
}
return rsl;
}
@Override
public Iterator<Node<E>> iterator() {
return new Iterator() {
private Queue<Node<E>> data = new LinkedList<>(Arrays.asList(root));
@Override
public boolean hasNext() {
return !data.isEmpty();
}
@Override
public Node<E> next() {
var node = data.poll();
data.addAll(node.children);
return node;
}
};
}
}
|
3e1d5a5a72fb519ba568859c5129a9126592e629 | 925 | java | Java | src/main/java/scouter/agent/cubrid/data/HostData.java | hwany7seo/scouter-agent-cubrid | ade45a7a1ec42ce1283b92de475447c59622624a | [
"Apache-2.0"
] | 3 | 2021-09-06T15:01:30.000Z | 2021-09-09T05:55:09.000Z | src/main/java/scouter/agent/cubrid/data/HostData.java | hwany7seo/scouter-agent-cubrid | ade45a7a1ec42ce1283b92de475447c59622624a | [
"Apache-2.0"
] | 2 | 2021-10-12T00:10:38.000Z | 2022-02-21T06:33:33.000Z | src/main/java/scouter/agent/cubrid/data/HostData.java | hwany7seo/scouter-agent-cubrid | ade45a7a1ec42ce1283b92de475447c59622624a | [
"Apache-2.0"
] | null | null | null | 37 | 77 | 0.721081 | 12,443 | /*
* Copyright 2021 the original author or authors.
* @https://github.com/scouter-contrib/scouter-agent-cubrid
*
* 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 scouter.agent.cubrid.data;
import org.json.simple.JSONObject;
public class HostData {
public JSONObject prvHostStatData = new JSONObject();
public JSONObject lastHostStatData = new JSONObject();
}
|
3e1d5a94b75f347dce306c1831e110a5f89adad4 | 4,807 | java | Java | app/src/main/java/com/mfinance/everjoy/app/presenter/LiquidationDetailPresenter.java | ngng1992/EvDemo | 7bb238ca470e59e655da8f3ff4a9ae04614f82bd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/mfinance/everjoy/app/presenter/LiquidationDetailPresenter.java | ngng1992/EvDemo | 7bb238ca470e59e655da8f3ff4a9ae04614f82bd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/mfinance/everjoy/app/presenter/LiquidationDetailPresenter.java | ngng1992/EvDemo | 7bb238ca470e59e655da8f3ff4a9ae04614f82bd | [
"Apache-2.0"
] | null | null | null | 41.8 | 168 | 0.749948 | 12,444 | package com.mfinance.everjoy.app.presenter;
import java.util.Locale;
import android.content.res.Resources;
import android.os.Messenger;
import com.mfinance.everjoy.app.CompanySettings;
import com.mfinance.everjoy.app.BasePopupDetailListener;
import com.mfinance.everjoy.app.MobileTraderApplication;
import com.mfinance.everjoy.app.PopupLiquidationDetailListener;
import com.mfinance.everjoy.app.bo.LiquidationRecord;
import com.mfinance.everjoy.app.util.ColorController;
import com.mfinance.everjoy.app.util.Utility;
public class LiquidationDetailPresenter extends BaseDetailPresenter{
double dMPrice = 0.0;
String sTmp = null;
double[] dBidAsk = null;
LiquidationRecord record ;
public LiquidationDetailPresenter(BasePopupDetailListener view,
Resources res, MobileTraderApplication app, Messenger mService,
Messenger mServiceMessengerHandler) {
super(view, res, app, mService, mServiceMessengerHandler);
}
@Override
public void updateUI() {
if (app.selectedLiquidation != null){
record = app.selectedLiquidation ;
String sBRef = null;
String sBRate = null;
String sBDate = null;
String sSRef = null;
String sSRate = null;
String sSDate = null;
if(!CompanySettings.LIQ_DETAIL_BS_TO_OPEN_LIQ){
sBRef = record.sBRef;
sBRate = record.sBRate;
sBDate = record.sBDate;
sSRef = record.sSRef;
sSRate = record.sSRate;
sSDate = record.sSDate;
}else{
if(record.sBorS.equals("B")){
sBRef = record.sBRef;
sBRate = record.sBRate;
sBDate = record.sBDate;
sSRef = record.sSRef;
sSRate = record.sSRate;
sSDate = record.sSDate;
}else{
sBRef = record.sSRef;
sBRate = record.sSRate;
sBDate = record.sSDate;
sSRef = record.sBRef;
sSRate = record.sBRate;
sSDate = record.sBDate;
}
}
((PopupLiquidationDetailListener)view).getBuyRefField().setText(sBRef);
((PopupLiquidationDetailListener)view).getBuyRateField().setText( sBRate);
((PopupLiquidationDetailListener)view).getBuyDateField().setText( Utility.displayListingDate(sBDate));
((PopupLiquidationDetailListener)view).getSellRefField().setText( sSRef);
((PopupLiquidationDetailListener)view).getSellRateField().setText( sSRate);
((PopupLiquidationDetailListener)view).getSellDateField().setText( Utility.displayListingDate(sSDate));
if(((PopupLiquidationDetailListener)view).getBSField()!=null){
if(CompanySettings.LIQ_DETAIL_BS_TO_OPEN_LIQ)
((PopupLiquidationDetailListener)view).getBSField().setText( record.sBorS.equals("B")?Utility.getStringById("lb_b", res):Utility.getStringById("lb_s", res));
else
((PopupLiquidationDetailListener)view).getBSField().setText( record.sBorS.equals("B")?Utility.getStringById("lb_buy", res):Utility.getStringById("lb_sell", res));
}
if(((PopupLiquidationDetailListener)view).getAmountField()!=null)
((PopupLiquidationDetailListener)view).getAmountField().setText("("+ Utility.formatAmount(record.dAmount)+")");
((PopupLiquidationDetailListener)view).getContractField().setText( record.contract.getContractName(app.locale));
((PopupLiquidationDetailListener)view).getLotField().setText( Utility.formatLot(record.dAmount /record.contract.iContractSize));
if( CompanySettings.Inverse_Commission_Sign == true )
{
((PopupLiquidationDetailListener)view).getCommissionField().setText( Utility.formatValue(-record.dCommission));
ColorController.setNumberColor(res, record.dCommission== (float)0.0 ? null : record.dCommission < 0 , ((PopupLiquidationDetailListener)view).getCommissionField());
}
else
{
((PopupLiquidationDetailListener)view).getCommissionField().setText( Utility.formatValue(record.dCommission));
ColorController.setNumberColor(res, record.dCommission== (float)0.0 ? null : record.dCommission >= 0 , ((PopupLiquidationDetailListener)view).getCommissionField());
}
((PopupLiquidationDetailListener)view).getPLField().setText( Utility.formatValue(record.dPL));
ColorController.setNumberColor(res, record.dPL >= 0 , ((PopupLiquidationDetailListener)view).getPLField());
if(((PopupLiquidationDetailListener)view).getAPLField()!=null){
((PopupLiquidationDetailListener)view).getAPLField().setText( Utility.formatValue(record.getAPL()));
ColorController.setNumberColor(res, record.getAPL() >= 0 , ((PopupLiquidationDetailListener)view).getAPLField());
}
if(((PopupLiquidationDetailListener)view).getRunningPriceField()!=null){
((PopupLiquidationDetailListener)view).getRunningPriceField().setText(record.sRRate);
}
if(((PopupLiquidationDetailListener)view).getInterestField()!=null)
((PopupLiquidationDetailListener)view).getInterestField().setText(Utility.formatValue(record.dFloatInterest));
}
}
}
|
3e1d5aba49a28fd32a5a4878dd053d42ac8a4844 | 7,010 | java | Java | phoenix-core/src/it/java/org/apache/phoenix/end2end/index/txn/RollbackIT.java | gigaclood/phoenix | 1ba9fc5221497ee53b4f0cbc3ee91524f423386c | [
"Apache-2.0"
] | 4 | 2016-06-29T00:54:20.000Z | 2018-03-09T09:13:49.000Z | phoenix-core/src/it/java/org/apache/phoenix/end2end/index/txn/RollbackIT.java | gigaclood/phoenix | 1ba9fc5221497ee53b4f0cbc3ee91524f423386c | [
"Apache-2.0"
] | null | null | null | phoenix-core/src/it/java/org/apache/phoenix/end2end/index/txn/RollbackIT.java | gigaclood/phoenix | 1ba9fc5221497ee53b4f0cbc3ee91524f423386c | [
"Apache-2.0"
] | 1 | 2019-03-14T01:46:42.000Z | 2019-03-14T01:46:42.000Z | 41.47929 | 174 | 0.63495 | 12,445 | /*
* 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.phoenix.end2end.index.txn;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import org.apache.phoenix.end2end.BaseHBaseManagedTimeIT;
import org.apache.phoenix.end2end.Shadower;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.TestUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.Maps;
@RunWith(Parameterized.class)
public class RollbackIT extends BaseHBaseManagedTimeIT {
private final boolean localIndex;
private final boolean mutable;
private final String tableName;
private final String indexName;
private final String fullTableName;
public RollbackIT(boolean localIndex, boolean mutable) {
this.localIndex = localIndex;
this.mutable = mutable;
this.tableName = TestUtil.DEFAULT_DATA_TABLE_NAME;
this.indexName = "IDX";
this.fullTableName = SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, tableName);
}
@BeforeClass
@Shadower(classBeingShadowed = BaseHBaseManagedTimeIT.class)
public static void doSetup() throws Exception {
Map<String,String> props = Maps.newHashMapWithExpectedSize(2);
props.put(QueryServices.DEFAULT_TABLE_ISTRANSACTIONAL_ATTRIB, Boolean.toString(true));
props.put(QueryServices.TRANSACTIONS_ENABLED, Boolean.toString(true));
setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
}
@Parameters(name="localIndex = {0} , mutable = {1}")
public static Collection<Boolean[]> data() {
return Arrays.asList(new Boolean[][] {
{ false, false }, { false, true },
{ true, false }, { true, true }
});
}
@Test
public void testRollbackOfUncommittedKeyValueIndexInsert() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE " + fullTableName + "(k VARCHAR PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)"+(!mutable? " IMMUTABLE_ROWS=true" : ""));
stmt.execute("CREATE "+(localIndex? "LOCAL " : "")+"INDEX " + indexName + " ON " + fullTableName + " (v1) INCLUDE(v2)");
stmt.executeUpdate("upsert into " + fullTableName + " values('x', 'y', 'a')");
//assert values in data table
ResultSet rs = stmt.executeQuery("select /*+ NO_INDEX */ k, v1, v2 from " + fullTableName);
assertTrue(rs.next());
assertEquals("x", rs.getString(1));
assertEquals("y", rs.getString(2));
assertEquals("a", rs.getString(3));
assertFalse(rs.next());
//assert values in index table
rs = stmt.executeQuery("select /*+ INDEX(" + indexName + ")*/ k, v1, v2 from " + fullTableName);
assertTrue(rs.next());
assertEquals("x", rs.getString(1));
assertEquals("y", rs.getString(2));
assertEquals("a", rs.getString(3));
assertFalse(rs.next());
conn.rollback();
//assert values in data table
rs = stmt.executeQuery("select /*+ NO_INDEX */ k, v1, v2 from " + fullTableName);
assertFalse(rs.next());
//assert values in index table
rs = stmt.executeQuery("select /*+ INDEX(" + indexName + ")*/ k, v1, v2 from " + fullTableName);
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testRollbackOfUncommittedRowKeyIndexInsert() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(false);
try {
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE " + fullTableName + "(k VARCHAR, v1 VARCHAR, v2 VARCHAR, CONSTRAINT pk PRIMARY KEY (v1, v2))"+(!mutable? " IMMUTABLE_ROWS=true" : ""));
stmt.execute("CREATE "+(localIndex? "LOCAL " : "")+"INDEX " + indexName + " ON " + fullTableName + "(v1, k)");
stmt.executeUpdate("upsert into " + fullTableName + " values('x', 'y', 'a')");
ResultSet rs = stmt.executeQuery("select /*+ NO_INDEX */ k, v1, v2 from " + fullTableName);
//assert values in data table
assertTrue(rs.next());
assertEquals("x", rs.getString(1));
assertEquals("y", rs.getString(2));
assertEquals("a", rs.getString(3));
assertFalse(rs.next());
//assert values in index table
rs = stmt.executeQuery("select /*+ INDEX(" + indexName + ")*/ k, v1 from " + fullTableName);
assertTrue(rs.next());
assertEquals("x", rs.getString(1));
assertEquals("y", rs.getString(2));
assertFalse(rs.next());
conn.rollback();
//assert values in data table
rs = stmt.executeQuery("select /*+ NO_INDEX */ k, v1, v2 from " + fullTableName);
assertFalse(rs.next());
//assert values in index table
rs = stmt.executeQuery("select /*+ INDEX(" + indexName + ")*/ k, v1 from " + fullTableName);
assertFalse(rs.next());
} finally {
conn.close();
}
}
}
|
3e1d5b172ded5ebf5468b36a1af0b37eb5f83747 | 687 | java | Java | mail-ware/src/main/java/com/range/mail/ware/vo/MemberAddressVo.java | Range17/mail | c69016fa832491f1abe916f41173a493f83512ac | [
"Apache-2.0"
] | null | null | null | mail-ware/src/main/java/com/range/mail/ware/vo/MemberAddressVo.java | Range17/mail | c69016fa832491f1abe916f41173a493f83512ac | [
"Apache-2.0"
] | 1 | 2021-09-20T20:59:38.000Z | 2021-09-20T20:59:38.000Z | mail-ware/src/main/java/com/range/mail/ware/vo/MemberAddressVo.java | Range17/mail | c69016fa832491f1abe916f41173a493f83512ac | [
"Apache-2.0"
] | null | null | null | 13.74 | 34 | 0.484716 | 12,446 | package com.range.mail.ware.vo;
import lombok.Data;
@Data
public class MemberAddressVo {
private Long id;
/**
* member_id
*/
private Long memberId;
/**
* 收货人姓名
*/
private String name;
/**
* 电话
*/
private String phone;
/**
* 邮政编码
*/
private String postCode;
/**
* 省份/直辖市
*/
private String province;
/**
* 城市
*/
private String city;
/**
* 区
*/
private String region;
/**
* 详细地址(街道)
*/
private String detailAddress;
/**
* 省市区代码
*/
private String areacode;
/**
* 是否默认
*/
private Integer defaultStatus;
} |
3e1d5b26f1c420a9e0a42e0284f2a322d15f0233 | 728 | java | Java | src/main/java/net/glowstone/io/entity/BatStore.java | jdkeke142/GlowstonePlusPlus | b6bec956a8e7fa7c0e231677e9f7e2a30a15f9ca | [
"MIT"
] | 1 | 2021-07-29T15:41:20.000Z | 2021-07-29T15:41:20.000Z | src/main/java/net/glowstone/io/entity/BatStore.java | jdkeke142/GlowstonePlusPlus | b6bec956a8e7fa7c0e231677e9f7e2a30a15f9ca | [
"MIT"
] | null | null | null | src/main/java/net/glowstone/io/entity/BatStore.java | jdkeke142/GlowstonePlusPlus | b6bec956a8e7fa7c0e231677e9f7e2a30a15f9ca | [
"MIT"
] | null | null | null | 26 | 74 | 0.677198 | 12,447 | package net.glowstone.io.entity;
import net.glowstone.entity.passive.GlowBat;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.Location;
class BatStore extends LivingEntityStore<GlowBat> {
public BatStore() {
super(GlowBat.class, "Bat");
}
@Override
public GlowBat createEntity(Location location, CompoundTag compound) {
return new GlowBat(location);
}
public void load(GlowBat entity, CompoundTag compound) {
super.load(entity, compound);
entity.setAwake(compound.getByte("BatFlags") == 1);
}
public void save(GlowBat entity, CompoundTag tag) {
super.save(entity, tag);
tag.putByte("BatFlags", entity.isAwake() ? 1 : 0);
}
}
|
3e1d5b83b47dc7c3422a1d87739a9e7d56079d46 | 706 | java | Java | akkad-base/base-utils/src/main/java/xyz/wongs/drunkard/common/annotation/DataScope.java | rothschil/drunkard | 020ce99adaccb390fffc0a56eac09692dfa1c7dd | [
"MIT"
] | 3 | 2021-05-28T05:49:43.000Z | 2021-12-09T06:52:05.000Z | akkad-base/base-utils/src/main/java/xyz/wongs/drunkard/common/annotation/DataScope.java | rothschil/drunkard | 020ce99adaccb390fffc0a56eac09692dfa1c7dd | [
"MIT"
] | 1 | 2021-01-18T09:06:48.000Z | 2021-01-18T09:17:08.000Z | akkad-base/base-utils/src/main/java/xyz/wongs/drunkard/common/annotation/DataScope.java | rothschil/drunkard | 020ce99adaccb390fffc0a56eac09692dfa1c7dd | [
"MIT"
] | 1 | 2022-03-04T08:18:17.000Z | 2022-03-04T08:18:17.000Z | 22.612903 | 47 | 0.67475 | 12,448 | package xyz.wongs.drunkard.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author kenaa@example.com
* @ClassName DataScope
* @Description 数据权限过滤注解
* @Github <a>https://github.com/rothschil</a>
* @date 20/12/9 10:30
* @Version 1.0.0
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope {
/**
* 部门表的别名
*/
public String deptAlias() default "";
/**
* 用户表的别名
*/
public String userAlias() default "";
}
|
3e1d5b944d4608f278571e17a050a1297aa573dc | 1,485 | java | Java | CS108 Demo/BLE.Client.Droid/obj/Debug/100/android/src/crc64a25b61d9f8ee364f/TransitionUtils_MatrixEvaluator.java | trevorcmit/RFID_BT_app | 202e2ee844c7ce60689373642e0ebd1258cef6dc | [
"MIT"
] | 10 | 2020-12-25T16:53:11.000Z | 2021-11-07T01:27:27.000Z | CS108 Demo/BLE.Client.Droid/obj/Debug/100/android/src/crc64a25b61d9f8ee364f/TransitionUtils_MatrixEvaluator.java | trevorcmit/RFID_BT_app | 202e2ee844c7ce60689373642e0ebd1258cef6dc | [
"MIT"
] | 56 | 2020-09-28T22:34:46.000Z | 2021-08-31T21:03:26.000Z | Counter App/Counter App.Android/obj/Debug/120/android/src/crc64a25b61d9f8ee364f/TransitionUtils_MatrixEvaluator.java | Srushanth/Counter | 3bc40dfcbd35429be555e365aea2d9d9fe45b8db | [
"MIT"
] | 16 | 2020-12-30T04:29:17.000Z | 2021-03-01T21:31:25.000Z | 30.306122 | 243 | 0.760943 | 12,449 | package crc64a25b61d9f8ee364f;
public class TransitionUtils_MatrixEvaluator
extends java.lang.Object
implements
mono.android.IGCUserPeer,
android.animation.TypeEvaluator
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_evaluate:(FLjava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;:GetEvaluate_FLjava_lang_Object_Ljava_lang_Object_Handler:Android.Animation.ITypeEvaluatorInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" +
"";
mono.android.Runtime.register ("AndroidX.Transitions.TransitionUtils+MatrixEvaluator, Xamarin.AndroidX.Transition", TransitionUtils_MatrixEvaluator.class, __md_methods);
}
public TransitionUtils_MatrixEvaluator ()
{
super ();
if (getClass () == TransitionUtils_MatrixEvaluator.class)
mono.android.TypeManager.Activate ("AndroidX.Transitions.TransitionUtils+MatrixEvaluator, Xamarin.AndroidX.Transition", "", this, new java.lang.Object[] { });
}
public java.lang.Object evaluate (float p0, java.lang.Object p1, java.lang.Object p2)
{
return n_evaluate (p0, p1, p2);
}
private native java.lang.Object n_evaluate (float p0, java.lang.Object p1, java.lang.Object p2);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.