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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9238fe84dd509774dbfc132c949a2fa40e35e608 | 746 | java | Java | metrics-facade-default-impl/src/main/java/com/ringcentral/platform/metrics/defaultImpl/timer/DefaultTimerImpl.java | ringcentral/metrics-facade | c26ee52e11bbb3603b83c0ac430c8fc9772bd70e | [
"MIT"
] | 9 | 2021-09-23T10:42:15.000Z | 2022-03-06T09:42:48.000Z | metrics-facade-default-impl/src/main/java/com/ringcentral/platform/metrics/defaultImpl/timer/DefaultTimerImpl.java | ringcentral/metrics-facade | c26ee52e11bbb3603b83c0ac430c8fc9772bd70e | [
"MIT"
] | 8 | 2021-09-27T10:24:15.000Z | 2022-03-21T07:15:44.000Z | metrics-facade-default-impl/src/main/java/com/ringcentral/platform/metrics/defaultImpl/timer/DefaultTimerImpl.java | ringcentral/metrics-facade | c26ee52e11bbb3603b83c0ac430c8fc9772bd70e | [
"MIT"
] | 3 | 2021-12-17T10:16:58.000Z | 2022-03-05T09:23:57.000Z | 23.3125 | 76 | 0.697051 | 998,660 | package com.ringcentral.platform.metrics.defaultImpl.timer;
import com.ringcentral.platform.metrics.defaultImpl.histogram.HistogramImpl;
import com.ringcentral.platform.metrics.defaultImpl.rate.RateImpl;
public class DefaultTimerImpl implements TimerImpl {
private final RateImpl rate;
private final HistogramImpl histogram;
public DefaultTimerImpl(RateImpl rate, HistogramImpl histogram) {
this.rate = rate;
this.histogram = histogram;
}
@Override
public void update(long value) {
rate.mark();
histogram.update(value);
}
@Override
public RateImpl rate() {
return rate;
}
@Override
public HistogramImpl histogram() {
return histogram;
}
}
|
9238fe8d633406948bdad687149901ee01ecb151 | 534 | java | Java | src/main/java/com/tim/scientific/portal/back/config/ConfigProperties.java | Mr-Anonim-377/Tim-scientific-portal-back | 5f8f1f47f75472fcee6bd7f748d399b873ad0106 | [
"MIT"
] | null | null | null | src/main/java/com/tim/scientific/portal/back/config/ConfigProperties.java | Mr-Anonim-377/Tim-scientific-portal-back | 5f8f1f47f75472fcee6bd7f748d399b873ad0106 | [
"MIT"
] | 6 | 2020-10-07T23:57:34.000Z | 2020-10-28T00:24:31.000Z | src/main/java/com/tim/scientific/portal/back/config/ConfigProperties.java | Mr-Anonim-377/Tim-scientific-portal_Back | 5f8f1f47f75472fcee6bd7f748d399b873ad0106 | [
"MIT"
] | null | null | null | 25.428571 | 61 | 0.769663 | 998,661 | package com.tim.scientific.portal.back.config;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Deprecated
@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {
private final Environment env;
public ConfigProperties(Environment env) {
this.env = env;
}
public String getConfigValue(String configKey) {
return env.getProperty(configKey);
}
}
|
9238fed210b179d4e6ec74c831710510c0cb0ee4 | 6,618 | java | Java | Plugins/Instantiation/de.uni_hildesheim.sse.easy.instantiatorCore/src/net/ssehub/easy/instantiation/core/model/buildlangModel/ExpressionVersionRestrictionValidator.java | SSEHUB/EASyProducer | 769ebe97f9f83963ea814f5e811a562ded7db5d5 | [
"Apache-2.0"
] | 10 | 2016-02-09T14:55:59.000Z | 2019-06-06T00:23:38.000Z | Plugins/Instantiation/de.uni_hildesheim.sse.easy.instantiatorCore/src/net/ssehub/easy/instantiation/core/model/buildlangModel/ExpressionVersionRestrictionValidator.java | SSEHUB/EASyProducer | 769ebe97f9f83963ea814f5e811a562ded7db5d5 | [
"Apache-2.0"
] | 88 | 2015-09-03T16:06:12.000Z | 2021-05-26T12:10:12.000Z | Plugins/Instantiation/de.uni_hildesheim.sse.easy.instantiatorCore/src/net/ssehub/easy/instantiation/core/model/buildlangModel/ExpressionVersionRestrictionValidator.java | SSEHUB/EASyProducer | 769ebe97f9f83963ea814f5e811a562ded7db5d5 | [
"Apache-2.0"
] | 1 | 2016-03-21T16:12:51.000Z | 2016-03-21T16:12:51.000Z | 36.972067 | 108 | 0.73557 | 998,662 | package net.ssehub.easy.instantiation.core.model.buildlangModel;
import net.ssehub.easy.basics.messages.IMessageHandler;
import net.ssehub.easy.instantiation.core.model.buildlangModel.ruleMatch.ArtifactMatchExpression;
import net.ssehub.easy.instantiation.core.model.buildlangModel.ruleMatch.BooleanMatchExpression;
import net.ssehub.easy.instantiation.core.model.buildlangModel.ruleMatch.CollectionMatchExpression;
import net.ssehub.easy.instantiation.core.model.buildlangModel.ruleMatch.CompoundMatchExpression;
import net.ssehub.easy.instantiation.core.model.buildlangModel.ruleMatch.PathMatchExpression;
import net.ssehub.easy.instantiation.core.model.buildlangModel.ruleMatch.StringMatchExpression;
import net.ssehub.easy.instantiation.core.model.common.Advice;
import net.ssehub.easy.instantiation.core.model.common.Compound;
import net.ssehub.easy.instantiation.core.model.common.ExpressionStatement;
import net.ssehub.easy.instantiation.core.model.common.Typedef;
import net.ssehub.easy.instantiation.core.model.common.VariableDeclaration;
import net.ssehub.easy.instantiation.core.model.common.VilException;
/**
* Implements a VIL expression version restriction validator.
*
* @author Holger Eichelberger
*/
public class ExpressionVersionRestrictionValidator
extends net.ssehub.easy.instantiation.core.model.expressions.ExpressionVersionRestrictionValidator
implements IVisitor {
/**
* Creates the validator with a message handler.
*
* @param handler the message handler (may be <b>null</b> for absent)
*/
public ExpressionVersionRestrictionValidator(IMessageHandler handler) {
super(handler);
}
@Override
public Object visitVariableDeclaration(VariableDeclaration var) throws VilException {
emit("variable declaration is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitAdvice(Advice advice) throws VilException {
emit("advice is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitExpressionStatement(ExpressionStatement statement) throws VilException {
return null; // fallback
}
@Override
public Object visitPathMatchExpression(PathMatchExpression expression) throws VilException {
emit("match expression is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitBooleanMatchExpression(BooleanMatchExpression expression) throws VilException {
emit("match expression is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitStringMatchExpression(StringMatchExpression expression) throws VilException {
emit("match expression is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitArtifactMatchExpression(ArtifactMatchExpression expression) throws VilException {
emit("match expression is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitCollectionMatchExpression(CollectionMatchExpression expression) throws VilException {
emit("match expression is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitScript(Script script) throws VilException {
emit("script is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitLoadProperties(LoadProperties properties) throws VilException {
emit("load properties is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitStrategyCallExpression(StrategyCallExpression call) throws VilException {
emit("strategy call is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitRuleCallExpression(RuleCallExpression ex) throws VilException {
emit("rule call is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitJoinExpression(JoinExpression ex) throws VilException {
emit("join is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitJoinVariableDeclaration(JoinVariableDeclaration decl) throws VilException {
emit("join is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitRule(Rule rule) throws VilException {
emit("rule is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitRule(VtlRule rule) throws VilException {
emit("rule is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitMapExpression(MapExpression map) throws VilException {
emit("map is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitInstantiateExpression(InstantiateExpression inst) throws VilException {
emit("instantiation is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitAlternativeExpression(AlternativeExpression alt) throws VilException {
emit("alternative is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitCompoundMatchExpression(CompoundMatchExpression expression) throws VilException {
emit("match expression is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitTypedef(Typedef typedef) throws VilException {
emit("typedef is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitWhileStatement(WhileStatement stmt) throws VilException {
emit("while is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitForStatement(ForStatement stmt) throws VilException {
emit("for is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
@Override
public Object visitCompound(Compound compound) throws VilException {
emit("compound declaration is not allowed here", true, VilException.ID_SEMANTIC);
return null;
}
}
|
92390019a3a380cbdd116bca41503b896d442694 | 1,193 | java | Java | array/Java/0414-third-maximum-number/src/Solution.java | ljyljy/LeetCode-Solution-in-Good-Style | 0998211d21796868061eb22e2cbb9bcd112cedce | [
"Apache-2.0"
] | 1 | 2021-07-03T11:15:45.000Z | 2021-07-03T11:15:45.000Z | array/Java/0414-third-maximum-number/src/Solution.java | TangMinXuan/LeetCode-Solutions-in-Good-Style | b17bf19b13c9d9f52b7029a732d4d8a8be212dd4 | [
"Apache-2.0"
] | null | null | null | array/Java/0414-third-maximum-number/src/Solution.java | TangMinXuan/LeetCode-Solutions-in-Good-Style | b17bf19b13c9d9f52b7029a732d4d8a8be212dd4 | [
"Apache-2.0"
] | 1 | 2021-06-17T09:21:54.000Z | 2021-06-17T09:21:54.000Z | 22.509434 | 72 | 0.407376 | 998,663 | /**
* @author liweiwei1419
* @date 2019/10/10 6:58 下午
*/
public class Solution {
/**
* 选择排序
*
* @param nums
* @return
*/
public int thirdMax(int[] nums) {
int len = nums.length;
int max1 = nums[0];
for (int i = 1; i < len; i++) {
if (nums[i] > max1) {
max1 = nums[i];
}
}
int max2 = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
if (nums[i] != max1 && nums[i] > max2) {
max2 = nums[i];
}
}
int max3 = Integer.MIN_VALUE;
int counter = 0;
for (int i = 0; i < len; i++) {
// 注意:这里是大于等于
if (nums[i] != max1 && nums[i] != max2 && nums[i] >= max3) {
max3 = nums[i];
counter++;
}
}
// 如果没有第 3 大的数,返回最大的那个数
if (counter == 0) {
return max1;
}
return max3;
}
public static void main(String[] args) {
int[] nums = {1, 2, 2, 5, 3, 5};
Solution solution = new Solution();
int res = solution.thirdMax(nums);
System.out.println(res);
}
}
|
9239031c33f83bcac19baf0700daebb2ff9daa42 | 9,603 | java | Java | weforward-framework/src/main/java/cn/weforward/framework/ext/RpcEndPoint.java | weforward/weforward-parent | 5e62ab49c1050f340ebb6149573a3ec723e869ac | [
"MIT"
] | null | null | null | weforward-framework/src/main/java/cn/weforward/framework/ext/RpcEndPoint.java | weforward/weforward-parent | 5e62ab49c1050f340ebb6149573a3ec723e869ac | [
"MIT"
] | null | null | null | weforward-framework/src/main/java/cn/weforward/framework/ext/RpcEndPoint.java | weforward/weforward-parent | 5e62ab49c1050f340ebb6149573a3ec723e869ac | [
"MIT"
] | null | null | null | 31.382353 | 463 | 0.729876 | 998,664 | /**
* Copyright (c) 2019,2020 honintech
*
* 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 cn.weforward.framework.ext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.weforward.common.util.AntPathPattern;
import cn.weforward.common.util.StringUtil;
import cn.weforward.framework.ApiException;
import cn.weforward.framework.ApiMethod;
import cn.weforward.framework.Authorizer;
import cn.weforward.framework.WeforwardSession;
import cn.weforward.framework.exception.ApiBusinessException;
import cn.weforward.framework.exception.ForwardException;
import cn.weforward.framework.support.AbstractWeforwardEndPoint;
import cn.weforward.framework.util.RequestUtil;
import cn.weforward.metrics.WeforwardMetrics;
import cn.weforward.protocol.Access;
import cn.weforward.protocol.Request;
import cn.weforward.protocol.Response;
import cn.weforward.protocol.datatype.DtBase;
import cn.weforward.protocol.datatype.DtObject;
import cn.weforward.protocol.exception.WeforwardException;
import cn.weforward.protocol.ops.User;
import cn.weforward.protocol.ops.UserService;
import cn.weforward.protocol.ops.trace.SimpleServiceTraceToken;
import cn.weforward.protocol.support.datatype.SimpleDtNumber;
import cn.weforward.protocol.support.datatype.SimpleDtObject;
import cn.weforward.protocol.support.datatype.SimpleDtString;
import cn.weforward.protocol.support.doc.ServiceDocumentVo;
import cn.weforward.trace.ServiceTrace;
import cn.weforward.trace.TraceRegistry;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
/**
* RPC端点
*
* @author daibo
*
*/
public class RpcEndPoint extends AbstractWeforwardEndPoint {
/** 日志记录器 */
private final static Logger _Logger = LoggerFactory.getLogger(RpcEndPoint.class);
/** 调整方法集 */
private HashMap<String, ApiMethod> m_Methods;
/** Ant表达式的Url集合 */
private List<String> m_AntUrls = Collections.emptyList();
/** 项目基本链接 */
private String m_BasePath = "";
/** 后缀 */
private String m_Suffix = "";
/** 验证器 */
private Map<String, Authorizer> m_Authorizers;
/** 文档方法名 */
private String m_DocumentMethodName;
/** 文档方法 */
private DocumentMethod m_DocumentMethod;
/** 调试方法名 */
private String m_DebugMethod;
/** 当前并发数 */
private AtomicInteger m_CurrentRequest;
/** 监控指标 */
private MeterRegistry m_MeterRegistry;
/** 监控追踪 */
private TraceRegistry m_TraceRegistry;
/** 用户服务 */
private UserService m_UserService;
/**
* 构造
*/
public RpcEndPoint() {
m_Methods = new HashMap<>(10);
m_Authorizers = new HashMap<>();
m_CurrentRequest = new AtomicInteger();
}
public String getBasePath() {
return m_BasePath;
}
public void setMeterRegistry(MeterRegistry registry) {
m_MeterRegistry = registry;
if (null != m_MeterRegistry) {
Gauge.builder(WeforwardMetrics.RPC_CURRENT_REQUEST_KEY, m_CurrentRequest, AtomicInteger::doubleValue)
.strongReference(true).register(m_MeterRegistry);
}
}
public MeterRegistry getMeterRegistry() {
return m_MeterRegistry;
}
public void setTraceRegister(TraceRegistry registry) {
m_TraceRegistry = registry;
}
public TraceRegistry getTraceRegistry() {
return m_TraceRegistry;
}
// @Override
protected Logger getLogger() {
return _Logger;
}
/***
* 注册验证器
*
* @param kind 验证器的类型
* @param authorizer 验证器
*/
public void register(String kind, Authorizer authorizer) {
m_Authorizers.put(StringUtil.toString(kind), authorizer);
}
/**
* 项目基本路径
*
* @param path 路径
*/
public void setBasePath(String path) {
m_BasePath = StringUtil.toString(path);
}
/**
* 后缀
*
* @param suffix 后缀
*/
public void setSuffix(String suffix) {
m_Suffix = StringUtil.toString(suffix);
}
protected DtBase handle(Request request, Response response) throws IOException, WeforwardException, ApiException {
long start = System.currentTimeMillis();
int code = 0;
MeterRegistry mr = getMeterRegistry();
TraceRegistry tr = getTraceRegistry();
String traceToken = request.getTraceToken();
Tags tags = Tags.empty();
try {
m_CurrentRequest.incrementAndGet();
String path = RequestUtil.getMethod(request);
if (null != mr) {
tags = WeforwardMetrics.TagHelper.of(WeforwardMetrics.TagHelper.method(path));
}
Access access = request.getAccess();
String kind = null;
if (null != access) {
kind = Access.Helper.getKind(access.getAccessId());
}
SimpleSession session = new SimpleSession(request);
if (null != m_UserService && StringUtil.eq(Access.KIND_USER, kind)) {
User user = m_UserService.getUserByAccess(request.getAccess().getAccessId());
session.bindOperator(user);
}
WeforwardSession.TLS.putSession(session);
Authorizer a = m_Authorizers.get(StringUtil.toString(kind));
if (null != a) {
a.auth(request);
}
return doHandle(kind, path, session, request, response);
} catch (ApiException e) {
code = e.getCode();
throw e;
} catch (ForwardException e) {
code = 0;// 转换算成功吧
throw e;
} catch (RuntimeException e) {
code = ApiException.CODE_INTERNAL_ERROR;
throw e;
} finally {
long end = System.currentTimeMillis();
long amount = end - start;
if (null != mr) {
tags = tags.and(WeforwardMetrics.TagHelper.code(code));
mr.timer(WeforwardMetrics.RPC_REQUEST_KEY, tags).record(amount, TimeUnit.MILLISECONDS);
}
if (null != tr && !StringUtil.isEmpty(traceToken)) {
SimpleServiceTraceToken token = SimpleServiceTraceToken.valueOf(traceToken);
tr.register(ServiceTrace.newTrace(token.getSpanId(), token.getParentId(), token.getTraceId(), start,
amount, tags));
}
m_CurrentRequest.decrementAndGet();
WeforwardSession.TLS.putSession(null);
}
}
/* 注册方法 */
protected void register(ApiMethod method) {
if (null == method) {
return;
}
String key = m_BasePath + method.getName() + m_Suffix;
if (isAntUrl(key)) {
List<String> old = m_AntUrls;
List<String> list;
if (null == old) {
list = Collections.singletonList(key);
} else {
list = new ArrayList<>(old.size() + 1);
list.addAll(old);
list.add(key);
}
m_AntUrls = list;
}
if (method instanceof DocumentMethod) {
m_DocumentMethodName = key;
m_DocumentMethod = (DocumentMethod) method;
}
if (method instanceof DebugMethod) {
m_DebugMethod = key;
}
if (_Logger.isDebugEnabled()) {
_Logger.debug("reigster method " + key);
}
ApiMethod old = m_Methods.put(key, method);
if (null != old) {
_Logger.error("存在同名的方法:" + key + "," + old + "被替换");
}
}
Map<String, ApiMethod> getMethods() {
return m_Methods;
}
String getDocumentMethod() {
return m_DocumentMethodName;
}
ServiceDocumentVo getServiceDocument() {
return null == m_DocumentMethod ? null : m_DocumentMethod.getServiceDocument();
}
String getDebugMethod() {
return m_DebugMethod;
}
private DtBase doHandle(String kind, String path, WeforwardSession session, Request request, Response response)
throws ApiException {
ApiMethod method = m_Methods.get(path);
if (null == method && !m_AntUrls.isEmpty()) {
for (String ant : m_AntUrls) {
if (AntPathPattern.match(ant, path)) {
method = m_Methods.get(ant);
break;
}
}
}
if (null == method) {
throw new ApiException(ApiException.CODE_METHOD_NOT_EXISTS, "[" + path + "(" + kind + ")]方法不存在");
}
String mkind = method.getKind();
if (!StringUtil.isEmpty(mkind) && !StringUtil.eq(mkind, kind)) {
throw ApiException.METHOD_KIND_NO_MATCH;
}
if (!method.isAllow(session)) {
throw ApiException.AUTH_FAILED;
}
DtObject params = RequestUtil.getParams(request);
return method.handle(path, params, request, response);
}
protected static DtObject toResult(ApiException e) {
SimpleDtObject m = new SimpleDtObject();
m.put("code", SimpleDtNumber.valueOf(e.getCode()));
m.put("msg", SimpleDtString.valueOf(e.getMessage()));
if (e instanceof ApiBusinessException) {
m.put("business_code", SimpleDtNumber.valueOf(((ApiBusinessException) e).getBusinessCode()));
}
return m;
}
protected static DtObject toResult(int code, String message, DtBase content) {
SimpleDtObject m = new SimpleDtObject();
m.put("code", SimpleDtNumber.valueOf(code));
m.put("msg", SimpleDtString.valueOf(message));
if (null != content) {
m.put("content", content);
}
return m;
}
}
|
923903ef97bc1e3a743a0b9688750131c06ce8fe | 275 | java | Java | examples/incubator/bitcoin-payment-request-example-application/src/main/java/org/tbk/bitcoin/example/payreq/bitcoin/block/BitcoinBlockService.java | theborakompanioni/bitcoin-spring-boot-starter | 356c01478cea3aa5b75f7e6c397e9668e764f8bc | [
"Apache-2.0"
] | 18 | 2021-04-03T16:16:07.000Z | 2022-03-18T17:56:14.000Z | examples/incubator/bitcoin-payment-request-example-application/src/main/java/org/tbk/bitcoin/example/payreq/bitcoin/block/BitcoinBlockService.java | demining/bitcoin-spring-boot-starter-Google-Colab | b5f77576dd379235d9a3ffb991ba4bb50aa2d880 | [
"Apache-2.0"
] | 16 | 2020-12-14T12:30:19.000Z | 2021-02-28T11:22:32.000Z | examples/incubator/bitcoin-payment-request-example-application/src/main/java/org/tbk/bitcoin/example/payreq/bitcoin/block/BitcoinBlockService.java | demining/bitcoin-spring-boot-starter-Google-Colab | b5f77576dd379235d9a3ffb991ba4bb50aa2d880 | [
"Apache-2.0"
] | 9 | 2022-02-20T11:02:45.000Z | 2022-02-23T21:17:37.000Z | 27.5 | 81 | 0.825455 | 998,665 | package org.tbk.bitcoin.example.payreq.bitcoin.block;
import com.msgilligan.bitcoinj.json.pojo.BlockInfo;
public interface BitcoinBlockService {
void createBlock(BlockInfo blockInfo);
void updatePreviousBlockIfPresent(BitcoinBlock.BitcoinBlockId parentBlockId);
}
|
9239048a8d15ab402e9b0500e93c557473f06271 | 400 | java | Java | arreglos.java | danimc/JavaCourse | c3805fe68a0623770ee66a416f9b80a732232556 | [
"Apache-2.0"
] | null | null | null | arreglos.java | danimc/JavaCourse | c3805fe68a0623770ee66a416f9b80a732232556 | [
"Apache-2.0"
] | null | null | null | arreglos.java | danimc/JavaCourse | c3805fe68a0623770ee66a416f9b80a732232556 | [
"Apache-2.0"
] | null | null | null | 18.181818 | 68 | 0.3225 | 998,666 | public class arreglos {
public static void main(String[] args) {
int a[] = new int[5];
int b[] = new int[5];
int c[] = new int[5];
for(int i = 0; i < 5; i++)
{
a[i] = i+1;
b[i] = i+1;
c[i] = a[i]*b[i];
System.out.println(a[i] + " * " + b[i] + " = " + c[i] );
}
}
}
|
92390541ea366820f49c6f3490ddbe9ca3eac787 | 1,834 | java | Java | Core/src/com/blockwithme/lessobjects/storage/SparseStorage.java | skunkiferous/LessObjects | a31c4442f281eaa8c953688badf914857ed461c4 | [
"Apache-2.0"
] | null | null | null | Core/src/com/blockwithme/lessobjects/storage/SparseStorage.java | skunkiferous/LessObjects | a31c4442f281eaa8c953688badf914857ed461c4 | [
"Apache-2.0"
] | null | null | null | Core/src/com/blockwithme/lessobjects/storage/SparseStorage.java | skunkiferous/LessObjects | a31c4442f281eaa8c953688badf914857ed461c4 | [
"Apache-2.0"
] | null | null | null | 36.68 | 103 | 0.64831 | 998,667 | /*******************************************************************************
* Copyright 2013 Sebastien Diot
*
* 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.blockwithme.lessobjects.storage;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* A Sparse is an automatically resizable storage that can grow or shrink based on the number
* of elements stored. The storage grows when selectStructure method is invoked but space is not
* available in the storage, and shrinks when clear method is invoked. Re-Sizing strategy for a sparse
* storage can be defined by passing an instance of StorageSizingStrategy.
*
* @author tarung
*/
// (tarung) Could we merge this interface into the normal Storage interface ?
// We discussed this and decided that its not needed atm.
@ParametersAreNonnullByDefault
public interface SparseStorage extends Storage {
/**
* Checks if an element index is present in this Storage.
*
* @param theIndex the index
* @return true, if present
*/
boolean contains(final int theIndex);
/**
* The current size of this storage.
*
* @return the current size.
*/
int currentSize();
}
|
9239064b9232170f7bff0bf9401e62429057f88b | 1,507 | java | Java | src/api/web/gw2/mapping/v2/pvp/seasons/PvpSeasonLadderScoring.java | fabricebouye/GW2WebAPIMapping | d4e26f37293b2d96f1fc1d61cb9dd48b5f6d8415 | [
"BSD-3-Clause"
] | null | null | null | src/api/web/gw2/mapping/v2/pvp/seasons/PvpSeasonLadderScoring.java | fabricebouye/GW2WebAPIMapping | d4e26f37293b2d96f1fc1d61cb9dd48b5f6d8415 | [
"BSD-3-Clause"
] | null | null | null | src/api/web/gw2/mapping/v2/pvp/seasons/PvpSeasonLadderScoring.java | fabricebouye/GW2WebAPIMapping | d4e26f37293b2d96f1fc1d61cb9dd48b5f6d8415 | [
"BSD-3-Clause"
] | null | null | null | 27.907407 | 85 | 0.667551 | 998,668 | /*
* Copyright (C) 2015-2019 Fabrice Bouyé
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
package api.web.gw2.mapping.v2.pvp.seasons;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.v2.APIv2;
/**
* Defines a PvP season scoring method to be used in the ladder in the leaderboards.
* @author Fabrice Bouyé
*/
@APIv2(endpoint = "v2/pvp/seasons") // NOI18N.
public interface PvpSeasonLadderScoring {
/**
* Gets the id of this PvP season scoring.
* @return A {@code String} instance, never {@code null}.
*/
@IdValue(flavor = IdValue.Flavor.STRING)
String getId();
/**
* Gets the type of scoring used.
* @return A {@code PvpSeasonLadderScoringType} instance, never {@code null}.
*/
PvpSeasonLadderScoringType getType();
/**
* Gets the i18n description of this scoring.
* @return A {@code String} instance, maybe {@code null}.
*/
@LocalizedResource
String getDescription();
/**
* Gets the i18n name of this scoring.
* @return A {@code String} instance, never {@code null}.
*/
@LocalizedResource
String getName();
/**
* Gets the ordering method used in the scoring.
* @return A {@code PvpSeasonLadderScoringOrdering} instance, never {@code null}.
*/
PvpSeasonLadderScoringOrdering getOrdering();
}
|
9239067d0f730527457881afa58dde00412dafa1 | 808 | java | Java | mldong-sys-parent/mldong-sys-service/src/main/java/com/mldong/modules/sys/service/SysRoleService.java | garethhk/mldong | 4cfe47c80ef418feb4c53d1aef00568b90212a5a | [
"Apache-2.0"
] | null | null | null | mldong-sys-parent/mldong-sys-service/src/main/java/com/mldong/modules/sys/service/SysRoleService.java | garethhk/mldong | 4cfe47c80ef418feb4c53d1aef00568b90212a5a | [
"Apache-2.0"
] | null | null | null | mldong-sys-parent/mldong-sys-service/src/main/java/com/mldong/modules/sys/service/SysRoleService.java | garethhk/mldong | 4cfe47c80ef418feb4c53d1aef00568b90212a5a | [
"Apache-2.0"
] | 1 | 2022-03-31T16:32:43.000Z | 2022-03-31T16:32:43.000Z | 16.833333 | 57 | 0.655941 | 998,669 | package com.mldong.modules.sys.service;
import java.util.List;
import com.mldong.common.base.CommonPage;
import com.mldong.modules.sys.dto.SysRoleParam;
import com.mldong.modules.sys.dto.SysRolePageParam;
import com.mldong.modules.sys.entity.SysRole;
/**
* <p>业务接口层</p>
* <p>角色</p>
*
* @since 2020-06-08 10:26:59
*/
public interface SysRoleService {
/**
* 添加角色
* @param param
* @return
*/
public int save(SysRoleParam param);
/**
* 更新角色
* @param param
* @return
*/
public int update(SysRoleParam param);
/**
* 删除角色
* @param ids
* @return
*/
public int remove(List<Long> ids);
/**
* 查询角色
* @param id
* @return
*/
public SysRole get(Long id);
/**
* 分页查询角色列表
* @param param 分页查询参数
* @return
*/
public CommonPage<SysRole> list(SysRolePageParam param);
}
|
9239072e225bfed1186bdfcc26a438e7eb8681a5 | 3,605 | java | Java | src/main/java/org/sagebionetworks/bridge/redis/InMemoryJedisOps.java | Sage-Bionetworks/BridgeTestUtils | 05b969a8c1733be56e00ae34b463667093705dd2 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sagebionetworks/bridge/redis/InMemoryJedisOps.java | Sage-Bionetworks/BridgeTestUtils | 05b969a8c1733be56e00ae34b463667093705dd2 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sagebionetworks/bridge/redis/InMemoryJedisOps.java | Sage-Bionetworks/BridgeTestUtils | 05b969a8c1733be56e00ae34b463667093705dd2 | [
"Apache-2.0"
] | 2 | 2016-03-01T02:09:52.000Z | 2016-09-20T22:58:48.000Z | 26.703704 | 117 | 0.599723 | 998,670 | package org.sagebionetworks.bridge.redis;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* In-memory mock implementation of Jedis. Uses a map to store everything doesn't actually honor TTL or expiration
* times.
*/
public class InMemoryJedisOps extends JedisOps {
private final Map<String, String> map = new HashMap<>();
public InMemoryJedisOps() {
// We're mocking out everything, so we don't care about the parent constructor. The super() call is only here
// because javac requires it.
super(null);
}
@Override
public Long expire(String key, int seconds) {
if (seconds <= 0) {
map.remove(key);
}
return 1L;
}
@Override
public String set(String key, String value) {
map.put(key, value);
return "OK";
}
@Override
public String setex(String key, int seconds, String value) {
// Contrary to what the parent class documentation says, this does NOT return the value set, but rather "OK"
map.put(key, value);
return "OK";
}
@Override
public Long setnx(String key, String value) {
if (map.containsKey(key)) {
return 0L;
} else {
map.put(key, value);
return 1L;
}
}
@Override
public String get(String key) {
return map.get(key);
}
@Override
public Long del(String... keyVarargs) {
for (String oneKey : keyVarargs) {
map.remove(oneKey);
}
return (long) keyVarargs.length;
}
@Override
public Long ttl(String key) {
if (map.containsKey(key)) {
// We don't honor TTLs. Just return 1;
return 1L;
} else {
return 0L;
}
}
private long getAsLong(String key) {
// The expected behavior is to treat null values as zero.
String str = map.get(key);
if (str == null) {
return 0;
} else {
return Long.parseLong(str);
}
}
@Override
public Long incr(String key) {
long oldValue = getAsLong(key);
long newValue = oldValue + 1;
map.put(key, Long.toString(newValue));
return newValue;
}
@Override
public Long decr(String key) {
long oldValue = getAsLong(key);
long newValue = oldValue - 1;
map.put(key, Long.toString(newValue));
return newValue;
}
@Override
public Long zadd(String key, double score, String member) {
// not used by BridgePF
throw new UnsupportedOperationException("Unsupported operation zadd()");
}
@Override
public Set<String> zrangeByScore(String key, Double min, Double max) {
// not used by BridgePF
throw new UnsupportedOperationException("Unsupported operation zrangeByScore()");
}
@Override
public Long zrank(String key, String member) {
// not used by BridgePF
throw new UnsupportedOperationException("Unsupported operation zrank()");
}
@Override
public Double zscore(String key, String member) {
// not used by BridgePF
throw new UnsupportedOperationException("Unsupported operation zscore()");
}
@Override
public Long zrem(String key, String... members) {
// not used by BridgePF
throw new UnsupportedOperationException("Unsupported operation zrem()");
}
@Override
public JedisTransaction getTransaction(String... keys) {
return new InMemoryJedisTransaction(this);
}
}
|
923907ddc30ee906cca2333bd8784d37d5e919ad | 6,298 | java | Java | src/test/java/com/quasiris/qsf/pipeline/filter/solr/SolrQsfqlQueryTransformerTest.java | quasiris/qsf-integration | 30bd8c3f82a74d382ca9af1834dea97bc086c49b | [
"MIT"
] | 2 | 2019-05-14T19:01:34.000Z | 2019-09-20T13:43:42.000Z | src/test/java/com/quasiris/qsf/pipeline/filter/solr/SolrQsfqlQueryTransformerTest.java | quasiris/qsf-integration | 30bd8c3f82a74d382ca9af1834dea97bc086c49b | [
"MIT"
] | 4 | 2018-05-22T08:11:24.000Z | 2020-10-13T07:19:02.000Z | src/test/java/com/quasiris/qsf/pipeline/filter/solr/SolrQsfqlQueryTransformerTest.java | quasiris/qsf-integration | 30bd8c3f82a74d382ca9af1834dea97bc086c49b | [
"MIT"
] | null | null | null | 41.986667 | 111 | 0.711813 | 998,671 | package com.quasiris.qsf.pipeline.filter.solr;
import com.quasiris.qsf.pipeline.PipelineContainer;
import com.quasiris.qsf.pipeline.filter.qsql.parser.QsfqlParserTestUtil;
import com.quasiris.qsf.query.SearchQuery;
import org.apache.solr.client.solrj.SolrQuery;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Created by mki on 16.01.18.
*/
public class SolrQsfqlQueryTransformerTest {
@Test
public void transformQuery() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
SolrQuery solrQuery = transform(transformer, "q=foo");
assertEquals("foo", solrQuery.getQuery());
}
@Test
public void transformSort() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addSortMapping("name_asc", "nameSort asc");
SolrQuery solrQuery = transform(transformer, "sort=name_asc");
assertEquals("nameSort asc", solrQuery.getParams("sort")[0]);
}
@Test
public void transformFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("brand", "brandSolrField");
SolrQuery solrQuery = transform(transformer, "f.brand=foo");
assertEquals("{!tag=brand}brandSolrField:(foo)", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformMultipleFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("brand", "brandSolrField");
SolrQuery solrQuery = transform(transformer, "f.brand=foo", "f.brand=bar");
assertEquals("{!tag=brand}brandSolrField:(foo AND bar)", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformMultipleAndFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("brand", "brandSolrField");
SolrQuery solrQuery = transform(transformer, "f.brand.and=foo", "f.brand.and=bar");
assertEquals("{!tag=brand}brandSolrField:(foo AND bar)", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformMultipleOrFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("brand", "brandSolrField");
SolrQuery solrQuery = transform(transformer, "f.brand.or=foo", "f.brand.or=bar");
assertEquals("{!tag=brand}brandSolrField:(foo OR bar)", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformRangeFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("price", "priceSolrField");
SolrQuery solrQuery = transform(transformer, "f.price.range=3,5");
assertEquals("{!tag=price}priceSolrField:[3.0 TO 5.0]", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformRangeUpperLowerBoundExcludedFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("price", "priceSolrField");
SolrQuery solrQuery = transform(transformer, "f.price.range={3,5}");
assertEquals("{!tag=price}priceSolrField:{3.0 TO 5.0}", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformRangeUpperLowerBoundIncludedFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("price", "priceSolrField");
SolrQuery solrQuery = transform(transformer, "f.price.range=[3,5]");
assertEquals("{!tag=price}priceSolrField:[3.0 TO 5.0]", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformRangeUpperLowerBoundIncludedExcludedFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("price", "priceSolrField");
SolrQuery solrQuery = transform(transformer, "f.price.range=[3,5}");
assertEquals("{!tag=price}priceSolrField:[3.0 TO 5.0}", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformRangeMinMaxFilter() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
transformer.addFilterMapping("price", "priceSolrField");
SolrQuery solrQuery = transform(transformer, "f.price.range=min,max");
assertEquals("{!tag=price}priceSolrField:[* TO *]", solrQuery.getFilterQueries()[0]);
}
@Test
public void transformPaging() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
SolrQuery solrQuery = transform(transformer, "page=3");
assertEquals(Integer.valueOf(10), solrQuery.getRows());
assertEquals(Integer.valueOf(20), solrQuery.getStart());
}
@Test
public void transformPagingDefault() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
SolrQuery solrQuery = transform(transformer, "q=foo");
assertEquals(Integer.valueOf(10), solrQuery.getRows());
assertEquals(Integer.valueOf(0), solrQuery.getStart());
}
@Test
public void transformPagingWithRows() throws Exception {
SolrQsfqlQueryTransformer transformer = new SolrQsfqlQueryTransformer();
SolrQuery solrQuery = transform(transformer, "q=foo", "rows=5", "page=5");
assertEquals(Integer.valueOf(5), solrQuery.getRows());
assertEquals(Integer.valueOf(20), solrQuery.getStart());
}
private SolrQuery transform(SolrQsfqlQueryTransformer transformer, String... parameters) throws Exception {
SearchQuery searchQuery = QsfqlParserTestUtil.createQuery(parameters);
PipelineContainer pipelineContainer = new PipelineContainer(null, null);
pipelineContainer.setSearchQuery(searchQuery);
transformer.transform(pipelineContainer);
SolrQuery solrQuery = transformer.getSolrQuery();
return solrQuery;
}
} |
923907e788c4d143a7c6db810afb9ca408d195cb | 314 | java | Java | xdubbo/src/main/java/xyz/xiezc/dubbo/provider/apiImpl/GreetingsServiceImpl.java | blanexie/-Yao | cb0f486cde9e392f8e1c0db3780b4b93b050ad36 | [
"MulanPSL-1.0"
] | 5 | 2020-05-14T13:38:31.000Z | 2021-06-21T07:16:53.000Z | xdubbo/src/main/java/xyz/xiezc/dubbo/provider/apiImpl/GreetingsServiceImpl.java | blanexie/-Yao | cb0f486cde9e392f8e1c0db3780b4b93b050ad36 | [
"MulanPSL-1.0"
] | 2 | 2022-01-12T23:06:17.000Z | 2022-02-16T01:13:06.000Z | xdubbo/src/main/java/xyz/xiezc/dubbo/provider/apiImpl/GreetingsServiceImpl.java | blanexie/-Yao | cb0f486cde9e392f8e1c0db3780b4b93b050ad36 | [
"MulanPSL-1.0"
] | null | null | null | 24.153846 | 63 | 0.754777 | 998,672 | package xyz.xiezc.dubbo.provider.apiImpl;
import org.apache.dubbo.config.annotation.DubboService;
import xyz.xiezc.dubbo.api.GreetingsService;
@DubboService
public class GreetingsServiceImpl implements GreetingsService {
@Override
public String sayHi(String name) {
return "hi, " + name;
}
} |
92390a766a8c7e5242eba3cbfc13b72647dff91d | 17,335 | java | Java | asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/feeds/FeedMetadataUtil.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 200 | 2016-06-16T01:01:42.000Z | 2022-03-24T08:16:13.000Z | asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/feeds/FeedMetadataUtil.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 3 | 2018-01-29T21:39:26.000Z | 2021-06-17T20:11:31.000Z | asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/feeds/FeedMetadataUtil.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 112 | 2016-06-12T21:51:05.000Z | 2022-02-05T17:16:33.000Z | 53.668731 | 120 | 0.67505 | 998,673 | /*
* 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.asterix.metadata.feeds;
import static org.apache.asterix.common.utils.IdentifierUtil.dataset;
import java.rmi.RemoteException;
import java.util.Map;
import org.apache.asterix.common.config.DatasetConfig.DatasetType;
import org.apache.asterix.common.dataflow.ICcApplicationContext;
import org.apache.asterix.common.exceptions.ACIDException;
import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.common.exceptions.ErrorCode;
import org.apache.asterix.common.exceptions.MetadataException;
import org.apache.asterix.common.exceptions.NoOpWarningCollector;
import org.apache.asterix.common.external.IDataSourceAdapter;
import org.apache.asterix.common.external.IDataSourceAdapter.AdapterType;
import org.apache.asterix.common.functions.ExternalFunctionLanguage;
import org.apache.asterix.common.metadata.DataverseName;
import org.apache.asterix.external.adapter.factory.ExternalAdapterFactory;
import org.apache.asterix.external.api.ITypedAdapterFactory;
import org.apache.asterix.external.feed.api.IFeed;
import org.apache.asterix.external.feed.policy.FeedPolicyAccessor;
import org.apache.asterix.external.provider.AdapterFactoryProvider;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataUtils;
import org.apache.asterix.formats.nontagged.SerializerDeserializerProvider;
import org.apache.asterix.metadata.MetadataManager;
import org.apache.asterix.metadata.MetadataTransactionContext;
import org.apache.asterix.metadata.declared.MetadataProvider;
import org.apache.asterix.metadata.entities.Dataset;
import org.apache.asterix.metadata.entities.DatasourceAdapter;
import org.apache.asterix.metadata.entities.Datatype;
import org.apache.asterix.metadata.entities.Feed;
import org.apache.asterix.metadata.entities.FeedPolicyEntity;
import org.apache.asterix.metadata.entities.Library;
import org.apache.asterix.metadata.utils.MetadataConstants;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.commons.lang3.StringUtils;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.common.utils.Triple;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.dataflow.value.RecordDescriptor;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.IWarningCollector;
/**
* A utility class for providing helper functions for feeds TODO: Refactor this
* class.
*/
public class FeedMetadataUtil {
private FeedMetadataUtil() {
}
public static Dataset validateIfDatasetExists(MetadataProvider metadataProvider, DataverseName dataverseName,
String datasetName) throws AlgebricksException {
Dataset dataset = metadataProvider.findDataset(dataverseName, datasetName);
if (dataset == null) {
throw new CompilationException("Unknown target " + dataset() + " :" + datasetName);
}
if (!dataset.getDatasetType().equals(DatasetType.INTERNAL)) {
throw new CompilationException("Statement not applicable. " + StringUtils.capitalize(dataset()) + " "
+ datasetName + " is not of required type " + DatasetType.INTERNAL);
}
return dataset;
}
public static Feed validateIfFeedExists(DataverseName dataverseName, String feedName,
MetadataTransactionContext ctx) throws AlgebricksException {
Feed feed = MetadataManager.INSTANCE.getFeed(ctx, dataverseName, feedName);
if (feed == null) {
throw new CompilationException("Unknown source feed: " + feedName);
}
return feed;
}
public static FeedPolicyEntity validateIfPolicyExists(DataverseName dataverseName, String policyName,
MetadataTransactionContext ctx) throws AlgebricksException {
FeedPolicyEntity feedPolicy = MetadataManager.INSTANCE.getFeedPolicy(ctx, dataverseName, policyName);
if (feedPolicy == null) {
feedPolicy =
MetadataManager.INSTANCE.getFeedPolicy(ctx, MetadataConstants.METADATA_DATAVERSE_NAME, policyName);
if (feedPolicy == null) {
throw new CompilationException("Unknown feed policy" + policyName);
}
}
return feedPolicy;
}
public static void validateFeed(Feed feed, MetadataTransactionContext mdTxnCtx, ICcApplicationContext appCtx,
IWarningCollector warningCollector) throws AlgebricksException {
try {
Map<String, String> configuration = feed.getConfiguration();
ARecordType adapterOutputType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_TYPE_NAME));
ARecordType metaType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_META_TYPE_NAME));
ExternalDataUtils.prepareFeed(configuration, feed.getDataverseName(), feed.getFeedName());
// Get adapter from metadata dataset <Metadata dataverse>
String adapterName = configuration.get(ExternalDataConstants.KEY_ADAPTER_NAME);
if (adapterName == null) {
throw new AlgebricksException("cannot find adapter name");
}
DatasourceAdapter adapterEntity = MetadataManager.INSTANCE.getAdapter(mdTxnCtx,
MetadataConstants.METADATA_DATAVERSE_NAME, adapterName);
// Get adapter from metadata dataset <The feed dataverse>
if (adapterEntity == null) {
adapterEntity = MetadataManager.INSTANCE.getAdapter(mdTxnCtx, feed.getDataverseName(), adapterName);
}
AdapterType adapterType;
ITypedAdapterFactory adapterFactory;
if (adapterEntity != null) {
adapterType = adapterEntity.getType();
String adapterFactoryClassname = adapterEntity.getClassname();
switch (adapterType) {
case INTERNAL:
adapterFactory = (ITypedAdapterFactory) Class.forName(adapterFactoryClassname).newInstance();
break;
case EXTERNAL:
adapterFactory = createExternalAdapterFactory(mdTxnCtx, adapterEntity, adapterFactoryClassname);
break;
default:
throw new AsterixException("Unknown Adapter type " + adapterType);
}
} else {
ExternalDataUtils.prepare(adapterName, configuration);
adapterFactory = (ITypedAdapterFactory) appCtx.getAdapterFactoryService().createAdapterFactory();
}
adapterFactory.setOutputType(adapterOutputType);
adapterFactory.setMetaType(metaType);
adapterFactory.configure(appCtx.getServiceContext(), configuration, warningCollector);
if (metaType == null && configuration.containsKey(ExternalDataConstants.KEY_META_TYPE_NAME)) {
metaType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_META_TYPE_NAME));
if (metaType == null) {
throw new AsterixException("Unknown specified feed meta output data type "
+ configuration.get(ExternalDataConstants.KEY_META_TYPE_NAME));
}
}
if (adapterOutputType == null) {
if (!configuration.containsKey(ExternalDataConstants.KEY_TYPE_NAME)) {
throw new AsterixException("Unspecified feed output data type");
}
adapterOutputType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_TYPE_NAME));
if (adapterOutputType == null) {
throw new AsterixException("Unknown specified feed output data type "
+ configuration.get(ExternalDataConstants.KEY_TYPE_NAME));
}
}
} catch (Exception e) {
throw new AsterixException("Invalid feed parameters. Exception Message:" + e.getMessage(), e);
}
}
private static ITypedAdapterFactory createExternalAdapterFactory(MetadataTransactionContext mdTxnCtx,
DatasourceAdapter adapterEntity, String adapterFactoryClassname)
throws AlgebricksException, RemoteException, HyracksDataException {
DataverseName libraryDataverse = adapterEntity.getLibraryDataverseName();
String libraryName = adapterEntity.getLibraryName();
Library library = MetadataManager.INSTANCE.getLibrary(mdTxnCtx, libraryDataverse, libraryName);
if (library == null) {
throw new CompilationException(ErrorCode.UNKNOWN_LIBRARY, libraryName);
}
if (!ExternalFunctionLanguage.JAVA.name().equals(library.getLanguage())) {
throw new HyracksDataException("Unexpected library language: " + library.getLanguage());
}
return new ExternalAdapterFactory(libraryDataverse, libraryName, adapterFactoryClassname);
}
@SuppressWarnings("rawtypes")
public static Triple<ITypedAdapterFactory, RecordDescriptor, AdapterType> getFeedFactoryAndOutput(Feed feed,
FeedPolicyAccessor policyAccessor, MetadataTransactionContext mdTxnCtx, ICcApplicationContext appCtx)
throws AlgebricksException {
// This method needs to be re-visited
String adapterName = null;
DatasourceAdapter adapterEntity = null;
String adapterFactoryClassname = null;
ITypedAdapterFactory adapterFactory = null;
ARecordType adapterOutputType = null;
ARecordType metaType = null;
Triple<ITypedAdapterFactory, RecordDescriptor, IDataSourceAdapter.AdapterType> feedProps = null;
IDataSourceAdapter.AdapterType adapterType = null;
try {
Map<String, String> configuration = feed.getConfiguration();
adapterName = configuration.get(ExternalDataConstants.KEY_ADAPTER_NAME);
configuration.putAll(policyAccessor.getFeedPolicy());
adapterOutputType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_TYPE_NAME));
metaType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_META_TYPE_NAME));
ExternalDataUtils.prepareFeed(configuration, feed.getDataverseName(), feed.getFeedName());
// Get adapter from metadata dataset <Metadata dataverse>
adapterEntity = MetadataManager.INSTANCE.getAdapter(mdTxnCtx, MetadataConstants.METADATA_DATAVERSE_NAME,
adapterName);
// Get adapter from metadata dataset <The feed dataverse>
if (adapterEntity == null) {
adapterEntity = MetadataManager.INSTANCE.getAdapter(mdTxnCtx, feed.getDataverseName(), adapterName);
}
if (adapterEntity != null) {
adapterType = adapterEntity.getType();
adapterFactoryClassname = adapterEntity.getClassname();
switch (adapterType) {
case INTERNAL:
adapterFactory = (ITypedAdapterFactory) Class.forName(adapterFactoryClassname).newInstance();
break;
case EXTERNAL:
adapterFactory = createExternalAdapterFactory(mdTxnCtx, adapterEntity, adapterFactoryClassname);
break;
default:
throw new AsterixException("Unknown Adapter type " + adapterType);
}
adapterFactory.setOutputType(adapterOutputType);
adapterFactory.setMetaType(metaType);
adapterFactory.configure(appCtx.getServiceContext(), configuration, NoOpWarningCollector.INSTANCE);
} else {
adapterFactory = AdapterFactoryProvider.getAdapterFactory(appCtx.getServiceContext(), adapterName,
configuration, adapterOutputType, metaType, NoOpWarningCollector.INSTANCE);
adapterType = IDataSourceAdapter.AdapterType.INTERNAL;
}
if (metaType == null) {
metaType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_META_TYPE_NAME));
}
if (adapterOutputType == null) {
if (!configuration.containsKey(ExternalDataConstants.KEY_TYPE_NAME)) {
throw new AsterixException("Unspecified feed output data type");
}
adapterOutputType = getOutputType(feed, configuration.get(ExternalDataConstants.KEY_TYPE_NAME));
}
int numOfOutputs = 1;
if (metaType != null) {
numOfOutputs++;
}
if (ExternalDataUtils.isChangeFeed(configuration)) {
// get number of PKs
numOfOutputs += ExternalDataUtils.getNumberOfKeys(configuration);
}
ISerializerDeserializer[] serdes = new ISerializerDeserializer[numOfOutputs];
int i = 0;
serdes[i++] = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(adapterOutputType);
if (metaType != null) {
serdes[i++] = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(metaType);
}
if (ExternalDataUtils.isChangeFeed(configuration)) {
getSerdesForPKs(serdes, configuration, metaType, adapterOutputType, i);
}
feedProps = new Triple<>(adapterFactory, new RecordDescriptor(serdes), adapterType);
} catch (Exception e) {
throw new AlgebricksException("unable to create adapter", e);
}
return feedProps;
}
@SuppressWarnings("rawtypes")
private static void getSerdesForPKs(ISerializerDeserializer[] serdes, Map<String, String> configuration,
ARecordType metaType, ARecordType adapterOutputType, int index) throws AlgebricksException {
int[] pkIndexes = ExternalDataUtils.getPKIndexes(configuration);
if (metaType != null) {
int[] pkIndicators = ExternalDataUtils.getPKSourceIndicators(configuration);
for (int j = 0; j < pkIndexes.length; j++) {
int aInt = pkIndexes[j];
if (pkIndicators[j] == 0) {
serdes[index++] = SerializerDeserializerProvider.INSTANCE
.getSerializerDeserializer(adapterOutputType.getFieldTypes()[aInt]);
} else if (pkIndicators[j] == 1) {
serdes[index++] = SerializerDeserializerProvider.INSTANCE
.getSerializerDeserializer(metaType.getFieldTypes()[aInt]);
} else {
throw new AlgebricksException("a key source indicator can only be 0 or 1");
}
}
} else {
for (int aInt : pkIndexes) {
serdes[index++] = SerializerDeserializerProvider.INSTANCE
.getSerializerDeserializer(adapterOutputType.getFieldTypes()[aInt]);
}
}
}
public static ARecordType getOutputType(IFeed feed, String fqOutputType) throws AlgebricksException {
if (fqOutputType == null) {
return null;
}
ARecordType outputType = null;
MetadataTransactionContext ctx = null;
try {
ctx = MetadataManager.INSTANCE.beginTransaction();
Datatype t = MetadataManager.INSTANCE.getDatatype(ctx, feed.getDataverseName(), fqOutputType);
if (t == null || t.getDatatype().getTypeTag() != ATypeTag.OBJECT) {
throw new MetadataException(ErrorCode.FEED_METADATA_UTIL_UNEXPECTED_FEED_DATATYPE, fqOutputType);
}
outputType = (ARecordType) t.getDatatype();
MetadataManager.INSTANCE.commitTransaction(ctx);
} catch (ACIDException | RemoteException e) {
if (ctx != null) {
try {
MetadataManager.INSTANCE.abortTransaction(ctx);
} catch (ACIDException | RemoteException e2) {
e.addSuppressed(e2);
}
throw new MetadataException(ErrorCode.FEED_CREATE_FEED_DATATYPE_ERROR, e, fqOutputType);
}
}
return outputType;
}
}
|
92390bddf29bca19dcfc8cec16f24b927438d362 | 713 | java | Java | carwar/src/main/java/com/moosiki/business/carwar/mvp/ui/activity/SurfacePlayerActivity.java | moosiki/CarWar | fac0da8402873e595ba219de34eace823e475f86 | [
"Apache-2.0"
] | null | null | null | carwar/src/main/java/com/moosiki/business/carwar/mvp/ui/activity/SurfacePlayerActivity.java | moosiki/CarWar | fac0da8402873e595ba219de34eace823e475f86 | [
"Apache-2.0"
] | null | null | null | carwar/src/main/java/com/moosiki/business/carwar/mvp/ui/activity/SurfacePlayerActivity.java | moosiki/CarWar | fac0da8402873e595ba219de34eace823e475f86 | [
"Apache-2.0"
] | null | null | null | 22.28125 | 57 | 0.736325 | 998,674 | package com.moosiki.business.carwar.mvp.ui.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.SurfaceView;
import butterknife.BindView;
import me.jessyan.art.base.BaseActivity;
import me.jessyan.art.mvp.IPresenter;
import me.jessyan.mvpart.carwar.R;
public class SurfacePlayerActivity extends BaseActivity {
@BindView(R.id.sv_player)
SurfaceView playerView;
@Override
public int initView(@Nullable Bundle bundle) {
return R.layout.activity_surface_player;
}
@Override
public void initData(@Nullable Bundle bundle) {
}
@Nullable
@Override
public IPresenter obtainPresenter() {
return null;
}
}
|
92390cbf0dcf238a9571ab27937afa04faf0013e | 1,262 | java | Java | src/Controllers/ItemSectionController.java | hpromero/AdDateManager | 675eb8a4244ed028291ee9acf38180dd149d9fe7 | [
"MIT"
] | null | null | null | src/Controllers/ItemSectionController.java | hpromero/AdDateManager | 675eb8a4244ed028291ee9acf38180dd149d9fe7 | [
"MIT"
] | null | null | null | src/Controllers/ItemSectionController.java | hpromero/AdDateManager | 675eb8a4244ed028291ee9acf38180dd149d9fe7 | [
"MIT"
] | null | null | null | 26.851064 | 72 | 0.672742 | 998,675 | package Controllers;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import models.ObjectForList;
import org.neodatis.odb.OID;
public class ItemSectionController {
@FXML private Label l_text1;
@FXML private Label l_text2;
@FXML private Label l_text3;
@FXML private Label l_text4;
@FXML private Label l_textBox;
@FXML private VBox vColorBox;
private SectionController mController;
private OID oid;
private String model;
private int id;
public void setParentController(SectionController controller) {
this.mController = controller;
}
public void setData(ObjectForList item) {
id = item.getId();
oid = item.getOid();
model = item.getModelObject();
l_text1.setText(item.getText1());
l_text2.setText(item.getText2());
l_text3.setText(item.getText3());
l_text4.setText(item.getText4());
l_textBox.setText(item.getTextBox());
// StrIcon=item.getIcon();
// StrColorItem=item.getColorItem();
vColorBox.setStyle("-fx-background-color: "+item.getColorBox());
}
public void viewDetail() {
mController.openDetail(id, oid,model,l_text1.getText());
}
}
|
92390d0a6dac1b9b179af323b255228f4293558b | 591 | java | Java | Chapter18_Generics_PC/src/GenericInsertationSortDemo.java | Emreyanmis/Java_Projects | 3a0558c0997296d74836065c88eaf8d613391445 | [
"MIT"
] | null | null | null | Chapter18_Generics_PC/src/GenericInsertationSortDemo.java | Emreyanmis/Java_Projects | 3a0558c0997296d74836065c88eaf8d613391445 | [
"MIT"
] | null | null | null | Chapter18_Generics_PC/src/GenericInsertationSortDemo.java | Emreyanmis/Java_Projects | 3a0558c0997296d74836065c88eaf8d613391445 | [
"MIT"
] | null | null | null | 25.695652 | 74 | 0.631134 | 998,676 | public class GenericInsertationSortDemo
{
public static void main(String[] args)
{
String[] names = {"yako","didar","mirac","emre","hasan"};
System.out.println("The unsorted order: ");
for(int i = 0; i < names.length; i++)
System.out.print(names[i] + " ");
System.out.println();
GenericInsertationSortDemo demo = new GenericInsertationSortDemo();
demo.InsertationObjects(names);
System.out.println("The sorted order by insertation sort algorithm: ");
for(int i = 0; i < names.length; i++)
System.out.print(names[i] + " ");
}
}
|
92390d7b910040c893a861cc05adc6e66ddc4e65 | 998 | java | Java | mimosa-core/src/main/java/org/mimosaframework/core/json/serializer/SerializeBeanInfo.java | jianzixing/mimosaframework | c15e2aa1d90ec6431d0e2f6a042e08f1b0388089 | [
"Apache-2.0"
] | 1 | 2019-09-09T03:14:13.000Z | 2019-09-09T03:14:13.000Z | mimosa-core/src/main/java/org/mimosaframework/core/json/serializer/SerializeBeanInfo.java | jianzixing/mimosa | 75c0d6b299b9f81afe84e749960aad8b6fe51600 | [
"Apache-2.0"
] | 8 | 2019-12-10T08:40:16.000Z | 2022-03-31T20:20:38.000Z | mimosa-core/src/main/java/org/mimosaframework/core/json/serializer/SerializeBeanInfo.java | jianzixing/mimosa | 75c0d6b299b9f81afe84e749960aad8b6fe51600 | [
"Apache-2.0"
] | 1 | 2019-12-23T07:36:43.000Z | 2019-12-23T07:36:43.000Z | 30.242424 | 57 | 0.573146 | 998,677 | package org.mimosaframework.core.json.serializer;
import org.mimosaframework.core.json.annotation.JSONType;
import org.mimosaframework.core.json.util.FieldInfo;
public class SerializeBeanInfo {
protected final Class<?> beanType;
protected final String typeName;
protected final JSONType jsonType;
protected final FieldInfo[] fields;
protected final FieldInfo[] sortedFields;
protected int features;
public SerializeBeanInfo(Class<?> beanType, //
JSONType jsonType, //
String typeName, //
int features,
FieldInfo[] fields, //
FieldInfo[] sortedFields
){
this.beanType = beanType;
this.jsonType = jsonType;
this.typeName = typeName;
this.features = features;
this.fields = fields;
this.sortedFields = sortedFields;
}
}
|
92390dcbb04b2b6ac62fe3182771434ea214b3fa | 2,333 | java | Java | bither-android/src/net/bither/receiver/NetworkReceiver.java | abewangm/sample-Android-Wallet | 99c56ec10ffeb597c1516c0e0de1ef62115c6e0e | [
"Apache-2.0"
] | 364 | 2015-01-05T01:02:15.000Z | 2022-03-28T07:55:58.000Z | bither-android/src/net/bither/receiver/NetworkReceiver.java | Crazy-Ann/bither-android-1.7.9 | 008a69d6b5da9a571a40a415d8c5308b3045c3ae | [
"Apache-2.0"
] | 68 | 2015-01-29T18:50:53.000Z | 2022-03-04T12:45:57.000Z | bither-android/src/net/bither/receiver/NetworkReceiver.java | Crazy-Ann/bither-android-1.7.9 | 008a69d6b5da9a571a40a415d8c5308b3045c3ae | [
"Apache-2.0"
] | 162 | 2015-01-09T05:46:53.000Z | 2022-02-11T16:58:05.000Z | 36.453125 | 93 | 0.681097 | 998,678 | /*
* Copyright 2014 http://Bither.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.receiver;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import net.bither.BitherApplication;
import net.bither.BitherSetting;
import net.bither.ChooseModeActivity;
import net.bither.R;
import net.bither.bitherj.BitherjSettings;
import net.bither.preference.AppSharedPreference;
import net.bither.util.LogUtil;
import net.bither.util.NetworkUtil;
import net.bither.util.SystemUtil;
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
LogUtil.d("receiver", action);
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
if (NetworkUtil.isConnected() || NetworkUtil.BluetoothIsConnected()) {
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent2 = new Intent(context, ChooseModeActivity.class);
String title = context.getString(R.string.cold_warning);
String contentText = context
.getString(R.string.safe_your_wallet);
SystemUtil.nmNotifyDefault(nm, context,
BitherSetting.NOTIFICATION_ID_NETWORK_ALERT, intent2,
title, contentText, R.drawable.ic_launcher);
}
} else {
if (NetworkUtil.isConnected()) {
BitherApplication.startBlockchainService();
}
}
}
}
|
92390dd503051c6e6f21c1041f9e6486c5ca0cfc | 1,014 | java | Java | sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/CbsAuthorizationType.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 2 | 2020-12-08T18:36:16.000Z | 2021-10-18T03:32:47.000Z | sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/CbsAuthorizationType.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 306 | 2019-09-27T06:41:56.000Z | 2019-10-14T08:19:57.000Z | sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/CbsAuthorizationType.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 26 | 114 | 0.678501 | 998,679 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.amqp.implementation;
import com.azure.core.amqp.ClaimsBasedSecurityNode;
/**
* An enumeration of supported authorization methods with the {@link ClaimsBasedSecurityNode}.
*/
public enum CbsAuthorizationType {
/**
* Authorize with CBS through a shared access signature.
*/
SHARED_ACCESS_SIGNATURE("servicebus.windows.net:sastoken"),
/**
* Authorize with CBS using a JSON web token.
*
* This is used in the case where Azure Active Directory is used for authentication and the authenticated user
* wants to authorize with Azure Event Hubs.
*/
JSON_WEB_TOKEN("jwt");
private final String scheme;
CbsAuthorizationType(String scheme) {
this.scheme = scheme;
}
/**
* Gets the token type scheme.
*
* @return The token type scheme.
*/
public String getTokenType() {
return scheme;
}
}
|
92390de7a396498411b8ad1917503b9bacbef3a4 | 1,764 | java | Java | bmc-common/src/main/java/com/oracle/bmc/waiter/WaiterConfiguration.java | mkelkarbv/oci-java-sdk | ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2021-04-09T18:17:14.000Z | 2021-04-09T18:17:14.000Z | bmc-common/src/main/java/com/oracle/bmc/waiter/WaiterConfiguration.java | mkelkarbv/oci-java-sdk | ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | bmc-common/src/main/java/com/oracle/bmc/waiter/WaiterConfiguration.java | mkelkarbv/oci-java-sdk | ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | 29.4 | 246 | 0.630385 | 998,680 | /**
* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.waiter;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Configuration used when invoking a waiter loop.
*/
@Getter
@ToString
@RequiredArgsConstructor
public class WaiterConfiguration {
private final TerminationStrategy terminationStrategy;
private final DelayStrategy delayStrategy;
/**
* The context that should be maintained by the wait loop.
*/
@ToString
public static class WaitContext {
/**
* The time the polling starting (ex, System.currentTimeMillis()).
*/
@Getter private final long startTime;
/**
* The number of attempts that have been made so far.
*/
@Getter private int attemptsMade;
/**
* The current time (ex, System.currentTimeMillis()). Exposed for
* tests.
*/
@Getter private long currentTime;
// currentTime = startTime as well
WaitContext(long startTime) {
this.startTime = startTime;
this.attemptsMade = 0;
this.currentTime = startTime;
}
// exposed for tests
void setCurrentTime(long currentTime) {
this.currentTime = currentTime;
}
/**
* Increments the number of attempts made.
*/
void incrementAttempts() {
this.attemptsMade++;
}
}
}
|
92390e62e04e76dab4c4686c3395d2ee6775a48f | 1,216 | java | Java | HypeProjeto/src/br/oltecnologias/hype/dao/UsuarioRepository.java | Odravison/Hype | 1bec393ca8b88e6e1d4ef73cf5302bb9cb6a545d | [
"Apache-2.0"
] | null | null | null | HypeProjeto/src/br/oltecnologias/hype/dao/UsuarioRepository.java | Odravison/Hype | 1bec393ca8b88e6e1d4ef73cf5302bb9cb6a545d | [
"Apache-2.0"
] | null | null | null | HypeProjeto/src/br/oltecnologias/hype/dao/UsuarioRepository.java | Odravison/Hype | 1bec393ca8b88e6e1d4ef73cf5302bb9cb6a545d | [
"Apache-2.0"
] | null | null | null | 32 | 98 | 0.748355 | 998,681 | /*
* 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 br.oltecnologias.hype.dao;
import br.oltecnologias.hype.exception.UsuarioExistenteException;
import br.oltecnologias.hype.exception.UsuarioInexistenteException;
import br.oltecnologias.hype.model.Usuario;
import java.util.List;
/**
*
* @author Odravison
*/
public interface UsuarioRepository {
public void create(Usuario usuario) throws UsuarioExistenteException;
public Usuario findByNickName(String nickName) throws UsuarioInexistenteException;
public boolean existsUsuario(String nickName);
public void removerUsuario(String nickName)throws UsuarioInexistenteException;
public void editarUsuario(Usuario usuario) throws UsuarioInexistenteException;
public List<Usuario> getAllUsuarios();
public boolean validarUsuario(String login, String senha) throws UsuarioInexistenteException;
public boolean isAdministrador(String login) throws UsuarioInexistenteException;
public int getUserCount();
}
|
92390e91907e39927cf52cc4cd3d1b31f505877d | 4,689 | java | Java | clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerRecords.java | vishalbala-nps/kafka | 191511ed68f0c3559c693abba7ba8b35b5af5ae2 | [
"Apache-2.0"
] | 35 | 2016-09-22T22:53:14.000Z | 2020-02-13T15:12:21.000Z | clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerRecords.java | vishalbala-nps/kafka | 191511ed68f0c3559c693abba7ba8b35b5af5ae2 | [
"Apache-2.0"
] | 27 | 2022-02-07T21:53:02.000Z | 2022-03-15T20:38:46.000Z | clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerRecords.java | vishalbala-nps/kafka | 191511ed68f0c3559c693abba7ba8b35b5af5ae2 | [
"Apache-2.0"
] | 88 | 2016-11-27T02:16:11.000Z | 2020-02-28T05:10:26.000Z | 36.069231 | 110 | 0.640648 | 998,682 | /*
* 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.kafka.clients.consumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.utils.AbstractIterator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A container that holds the list {@link ConsumerRecord} per partition for a
* particular topic. There is one {@link ConsumerRecord} list for every topic
* partition returned by a {@link Consumer#poll(java.time.Duration)} operation.
*/
public class ConsumerRecords<K, V> implements Iterable<ConsumerRecord<K, V>> {
public static final ConsumerRecords<Object, Object> EMPTY = new ConsumerRecords<>(Collections.emptyMap());
private final Map<TopicPartition, List<ConsumerRecord<K, V>>> records;
public ConsumerRecords(Map<TopicPartition, List<ConsumerRecord<K, V>>> records) {
this.records = records;
}
/**
* Get just the records for the given partition
*
* @param partition The partition to get records for
*/
public List<ConsumerRecord<K, V>> records(TopicPartition partition) {
List<ConsumerRecord<K, V>> recs = this.records.get(partition);
if (recs == null)
return Collections.emptyList();
else
return Collections.unmodifiableList(recs);
}
/**
* Get just the records for the given topic
*/
public Iterable<ConsumerRecord<K, V>> records(String topic) {
if (topic == null)
throw new IllegalArgumentException("Topic must be non-null.");
List<List<ConsumerRecord<K, V>>> recs = new ArrayList<>();
for (Map.Entry<TopicPartition, List<ConsumerRecord<K, V>>> entry : records.entrySet()) {
if (entry.getKey().topic().equals(topic))
recs.add(entry.getValue());
}
return new ConcatenatedIterable<>(recs);
}
/**
* Get the partitions which have records contained in this record set.
* @return the set of partitions with data in this record set (may be empty if no data was returned)
*/
public Set<TopicPartition> partitions() {
return Collections.unmodifiableSet(records.keySet());
}
@Override
public Iterator<ConsumerRecord<K, V>> iterator() {
return new ConcatenatedIterable<>(records.values()).iterator();
}
/**
* The number of records for all topics
*/
public int count() {
int count = 0;
for (List<ConsumerRecord<K, V>> recs: this.records.values())
count += recs.size();
return count;
}
private static class ConcatenatedIterable<K, V> implements Iterable<ConsumerRecord<K, V>> {
private final Iterable<? extends Iterable<ConsumerRecord<K, V>>> iterables;
public ConcatenatedIterable(Iterable<? extends Iterable<ConsumerRecord<K, V>>> iterables) {
this.iterables = iterables;
}
@Override
public Iterator<ConsumerRecord<K, V>> iterator() {
return new AbstractIterator<ConsumerRecord<K, V>>() {
Iterator<? extends Iterable<ConsumerRecord<K, V>>> iters = iterables.iterator();
Iterator<ConsumerRecord<K, V>> current;
public ConsumerRecord<K, V> makeNext() {
while (current == null || !current.hasNext()) {
if (iters.hasNext())
current = iters.next().iterator();
else
return allDone();
}
return current.next();
}
};
}
}
public boolean isEmpty() {
return records.isEmpty();
}
@SuppressWarnings("unchecked")
public static <K, V> ConsumerRecords<K, V> empty() {
return (ConsumerRecords<K, V>) EMPTY;
}
}
|
92390eb007a1f48c00934607c29a31fb245b5ae5 | 366 | java | Java | app/models/AssignableArk.java | min2ha/w3act | a761771012d6fedb2a616a05493e9b1ce4585917 | [
"Apache-2.0"
] | 11 | 2015-11-02T16:06:58.000Z | 2020-03-31T16:09:24.000Z | app/models/AssignableArk.java | min2ha/w3act | a761771012d6fedb2a616a05493e9b1ce4585917 | [
"Apache-2.0"
] | 461 | 2015-01-05T09:47:03.000Z | 2022-03-31T23:11:19.000Z | app/models/AssignableArk.java | min2ha/w3act | a761771012d6fedb2a616a05493e9b1ce4585917 | [
"Apache-2.0"
] | 5 | 2017-04-24T14:02:35.000Z | 2021-11-09T13:23:22.000Z | 20.333333 | 118 | 0.759563 | 998,683 | package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
@Entity
public class AssignableArk extends Model {
@Id
public String ark;
public static final Model.Finder<String, AssignableArk> find = new Model.Finder<>(String.class, AssignableArk.class);
public AssignableArk(String ark) {
this.ark = ark;
}
} |
92390fb6a05bb1c717331d525bd5ee5943eea649 | 883 | java | Java | online_edu_ssm/src/main/java/com/orznewbie/service/Impl/BannerServiceImpl.java | orznewbie/git-test | 4f094bac837adb851dd8e970b42a546d8439f806 | [
"Apache-2.0"
] | 5 | 2021-03-31T08:57:57.000Z | 2022-01-01T12:48:39.000Z | online_edu_ssm/src/main/java/com/orznewbie/service/Impl/BannerServiceImpl.java | orznewbie/git-test | 4f094bac837adb851dd8e970b42a546d8439f806 | [
"Apache-2.0"
] | null | null | null | online_edu_ssm/src/main/java/com/orznewbie/service/Impl/BannerServiceImpl.java | orznewbie/git-test | 4f094bac837adb851dd8e970b42a546d8439f806 | [
"Apache-2.0"
] | null | null | null | 24.527778 | 64 | 0.740657 | 998,684 | package com.orznewbie.service.Impl;
import com.orznewbie.dao.BannerMapper;
import com.orznewbie.entity.Banner;
import com.orznewbie.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerMapper bannerMapper;
@Transactional
public int delete(Integer id) {
return bannerMapper.delete(id);
}
@Transactional
public int insert(Banner banner) {
return bannerMapper.insert(banner);
}
@Transactional
public int update(Banner banner) {
return bannerMapper.update(banner);
}
public List<Banner> queryAll() {
return bannerMapper.queryAll();
}
}
|
9239105ecb8ffeec2925701722596cac4994d7ea | 1,919 | java | Java | utility/synapse-utilities-common/src/main/java/io/americanexpress/synapse/utilities/common/serialization/TitleCaseStringListSerializer.java | yeikel/synapse | d359e388f633087bb7232b5e0c6d758b3d88f200 | [
"Apache-2.0"
] | null | null | null | utility/synapse-utilities-common/src/main/java/io/americanexpress/synapse/utilities/common/serialization/TitleCaseStringListSerializer.java | yeikel/synapse | d359e388f633087bb7232b5e0c6d758b3d88f200 | [
"Apache-2.0"
] | null | null | null | utility/synapse-utilities-common/src/main/java/io/americanexpress/synapse/utilities/common/serialization/TitleCaseStringListSerializer.java | yeikel/synapse | d359e388f633087bb7232b5e0c6d758b3d88f200 | [
"Apache-2.0"
] | null | null | null | 38.38 | 119 | 0.720167 | 998,685 | /*
* Copyright 2020 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.americanexpress.synapse.utilities.common.serialization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.List;
/**
* TitleCaseStringListSerializer class serializes a list of strings into its title case format.
* e.g. {JOHN X DOE, JANE A SMITH} will be converted into {John X Doe, Jane A Smith}.
*
* @author Paolo Claudio
*/
public class TitleCaseStringListSerializer extends StringListSerializer {
/**
* Convert each string in this list into title case format.
*
* @param list to be converted
* @param generator JSON generator
* @param provider serializer provider
* @throws IOException whenever there's an issue performing the serialization
*/
@Override
public void serialize(List<String> list, JsonGenerator generator, SerializerProvider provider) throws IOException {
TitleCaseStringSerializer titleCaseStringSerializer = new TitleCaseStringSerializer();
String text;
for (int i = 0; i < list.size(); i++) {
text = list.get(i);
text = titleCaseStringSerializer.serialize(text);
list.set(i, text);
}
generator.writeObject(list);
}
}
|
923910984f40dcf8e726f64d8f08eb4c387e0a3a | 5,670 | java | Java | src/main/java/deformablemesh/ringdetection/ContractileRingDetector.java | PaluchLabUCL/DeformingMesh3D-plugin | 34de3b317453bbb24d4b47097b7775ecaf233de8 | [
"MIT"
] | 1 | 2021-07-29T16:21:39.000Z | 2021-07-29T16:21:39.000Z | src/main/java/deformablemesh/ringdetection/ContractileRingDetector.java | PaluchLabUCL/DeformingMesh3D-plugin | 34de3b317453bbb24d4b47097b7775ecaf233de8 | [
"MIT"
] | 5 | 2018-01-12T07:59:00.000Z | 2021-12-23T23:32:46.000Z | src/main/java/deformablemesh/ringdetection/ContractileRingDetector.java | PaluchLabUCL/DeformingMesh3D-plugin | 34de3b317453bbb24d4b47097b7775ecaf233de8 | [
"MIT"
] | 2 | 2022-02-11T14:27:32.000Z | 2022-02-11T14:56:41.000Z | 26.872038 | 116 | 0.606173 | 998,686 | package deformablemesh.ringdetection;
import deformablemesh.MeshImageStack;
import deformablemesh.geometry.DeformableMesh3D;
import deformablemesh.geometry.Furrow3D;
import deformablemesh.gui.GuiTools;
import deformablemesh.util.connectedcomponents.ConnectedComponents2D;
import deformablemesh.util.astar.AStarBasic;
import deformablemesh.util.astar.AStarXY;
import deformablemesh.util.astar.PossiblePath;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* This used to be a way to initialize a contractile ring. It is becoming a tool for
* reviewing segmentations.
*
* It stores a time series of planes.
*
* Created by msmith on 1/20/14.
*/
public class ContractileRingDetector implements Iterable<Integer>{
MeshImageStack stack;
ImageProcessor currentSlice, currentBinary;
int frames;
int slices;
int height;
int width;
public double ALPHA = 1.0;
public double BETA = 1.0;
public double GAMMA = 1000;
public double WEIGHT = 2.0;
public double SIGMA = 3.0;
//Stage stage;
double threshold;
Map<Integer, Furrow3D> furrows;
Furrow3D furrow;
public ContractileRingDetector(){
furrows = new TreeMap<>();
stack = MeshImageStack.getEmptyStack();
}
public void setImageStack(MeshImageStack stack){
this.stack = stack;
frames = stack.getNFrames();
slices = stack.getNSlices();
height = stack.getHeightPx();
width = stack.getWidthPx();
}
public void setThresh(double t){
threshold=t;
}
public void createFurrowSlice(int frame){
if(!furrows.containsKey(frame)) return;
Furrow3D f = furrows.get(frame);
FurrowTransformer transformer = new FurrowTransformer(f, stack);
int xcounts = transformer.getXCounts();
int ycounts = transformer.getYCounts();
if(xcounts<1){xcounts =1;}
if(ycounts<1){ycounts =1;}
ImageProcessor proc = new FloatProcessor(xcounts, ycounts);
double[] pt = new double[2];
for (int i = 0; i < xcounts; i++) {
for (int j = 0; j < ycounts; j++) {
pt[0] = i;
pt[1] = j;
double v = stack.getInterpolatedValue(transformer.getVolumeCoordinates(pt));
try {
proc.setf(i, j, (float) v);
} catch(Exception e){
e.printStackTrace();
}
}
}
currentSlice=proc;
}
public ImageProcessor getFurrowSlice(){
return currentSlice;
}
public ImageProcessor createBinarySlice(){
if(currentSlice==null) return null;
ImageProcessor proc = currentSlice;
ImageProcessor binary = new ShortProcessor(proc.getWidth(), proc.getHeight());
double[] center;
double v;
center = threshAndCenter(proc, binary);
//pruneBinaryBlobs(binary);
currentBinary = binary;
return binary;
}
public List<List<double[]>> mapTo2D(List<List<double[]>> input){
List<List<double[]>> ret = new ArrayList<>();
if(furrow!=null) {
FurrowTransformer transformer = new FurrowTransformer(furrow, stack);
for (List<double[]> curve3d : input) {
ret.add(curve3d.stream().map(i -> transformer.getPlaneCoordinates(i)).collect(Collectors.toList()));
}
}
return ret;
}
/**
* Apply the current threshold to the image and find the center of mass of the successful points.
*
* @param input input intensity values
* @param output where the output should be placed.
* @return {x, y } positions
*/
double[] threshAndCenter(ImageProcessor input, ImageProcessor output){
int w = input.getWidth();
int h = input.getHeight();
int n = w*h;
double count = 0;
double[] center = {0,0};
for(int i = 0; i<n; i++){
float f = input.getf(i);
if(f>threshold){
output.set(i, 255);
center[0] += i%w;
center[1] += i/w;
count++;
} else{
output.set(i, 0);
}
}
if(count>0) {
center[0] = center[0] / count;
center[1] = center[1] / count;
}
return center;
}
public Iterator<Integer> iterator(){
return furrows.keySet().iterator();
}
public Furrow3D getFurrow(int i){
return furrows.get(i);
}
public Furrow3D getFurrow(){
return furrow;
}
public void setFrame(int frame){
if(furrows.containsKey(frame)){
furrow = furrows.get(frame);
createFurrowSlice(frame);
} else{
furrow = null;
}
}
public void putFurrow(int frame, Furrow3D furrow){
furrows.put(frame, furrow);
this.furrow = furrow;
}
public List<double[]> get3DCoordinatesFromFurrowPlane(List<double[]> pts){
if(furrow==null) return Collections.<double[]>emptyList();
FurrowTransformer transformer = new FurrowTransformer(furrow, stack);
return pts.stream().map(transformer::getVolumeCoordinates).collect(Collectors.toList());
}
public Map<Integer, Furrow3D> getFurrows() {
return furrows;
}
}
|
92391115f3e308ec2c6ec4b22c7fe920c36f9519 | 1,914 | java | Java | AL-Game/data/scripts/system/handlers/admincommands/UnBanMac.java | karllgiovany/Aion-Lightning-4.9-SRC | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2019-04-05T22:44:56.000Z | 2019-04-05T22:44:56.000Z | AL-Game/data/scripts/system/handlers/admincommands/UnBanMac.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | null | null | null | AL-Game/data/scripts/system/handlers/admincommands/UnBanMac.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2017-12-28T16:59:47.000Z | 2017-12-28T16:59:47.000Z | 34.8 | 101 | 0.670324 | 998,687 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package admincommands;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.BannedMacManager;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.chathandlers.AdminCommand;
/**
* @author KID
*/
public class UnBanMac extends AdminCommand {
public UnBanMac() {
super("unbanmac");
}
@Override
public void execute(Player player, String... params) {
if (params == null || params.length < 1) {
onFail(player, null);
return;
}
String address = params[0];
boolean result = BannedMacManager.getInstance().unbanAddress(address,
"uban;mac=" + address + ", " + player.getObjectId() + "; admin=" + player.getName());
if (result) {
PacketSendUtility.sendMessage(player, "mac " + address + " has unbanned");
} else {
PacketSendUtility.sendMessage(player, "mac " + address + " is not banned");
}
}
@Override
public void onFail(Player player, String message) {
PacketSendUtility.sendMessage(player, "Syntax: //unbanmac <mac>");
}
}
|
9239113cc256e02eb93e687f2f67fad856f46c6d | 400 | java | Java | app/src/main/java/com/app/qunadai/third/eventbus/EventMe.java | rooney0928/qnd2 | a916bb17b471159964151e1d7f1ce9ccd6460ab6 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/app/qunadai/third/eventbus/EventMe.java | rooney0928/qnd2 | a916bb17b471159964151e1d7f1ce9ccd6460ab6 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/app/qunadai/third/eventbus/EventMe.java | rooney0928/qnd2 | a916bb17b471159964151e1d7f1ce9ccd6460ab6 | [
"Apache-2.0"
] | null | null | null | 16.666667 | 46 | 0.6175 | 998,688 | package com.app.qunadai.third.eventbus;
/**
* Created by wayne on 2017/5/15.
*/
public class EventMe {
private String nickname;
public EventMe(String nickname) {
this.nickname = nickname;
}
public EventMe() {
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
|
923911e89664a0e78cbfec870a17f8663e266ad2 | 2,494 | java | Java | jhaws/swing/src/main/java/org/swingeasy/ExtensionFileFilter.java | jurgendl/jhaws | 9f8c0f0ee64315644bd112426fcec2a135a2cdf2 | [
"MIT"
] | 2 | 2015-03-18T15:04:51.000Z | 2018-10-08T15:43:08.000Z | jhaws/swing/src/main/java/org/swingeasy/ExtensionFileFilter.java | jurgendl/jhaws | 9f8c0f0ee64315644bd112426fcec2a135a2cdf2 | [
"MIT"
] | 11 | 2020-07-01T08:44:17.000Z | 2022-03-30T17:53:42.000Z | jhaws/swing/src/main/java/org/swingeasy/ExtensionFileFilter.java | jurgendl/jhaws | 9f8c0f0ee64315644bd112426fcec2a135a2cdf2 | [
"MIT"
] | null | null | null | 26.252632 | 89 | 0.609463 | 998,689 | package org.swingeasy;
import java.io.File;
import java.util.List;
import javax.swing.filechooser.FileFilter;
/**
* @author Jurgen
*/
public class ExtensionFileFilter extends FileFilter {
protected static String descriptionFromExtensions(String[] exts) {
if (exts == null || exts.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String extension : exts) {
sb.append(extension).append(", ");
}
sb.deleteCharAt(sb.length() - 1);
String string = sb.deleteCharAt(sb.length() - 1).toString();
return string;
}
protected String description;
protected String[] extensions;
public ExtensionFileFilter(final List<String> extensions) {
this.extensions = extensions.toArray(new String[extensions.size()]);
description = ExtensionFileFilter.descriptionFromExtensions(this.extensions);
}
public ExtensionFileFilter(final String description, final List<String> extensions) {
this.extensions = extensions.toArray(new String[extensions.size()]);
this.description = description;
}
public ExtensionFileFilter(final String description, final String... extensions) {
if (extensions.length == 0) {
this.extensions = new String[] { description };
this.description = ExtensionFileFilter.descriptionFromExtensions(extensions);
} else {
this.extensions = extensions;
this.description = description;
}
}
/**
*
* @see javax.swing.filechooser.FileFilter#accept(java.io.File)
*/
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
for (String extension : extensions) {
String _extension = extension.replace("[", "").replace("]", "");
if (f.getName().toLowerCase().endsWith("." + _extension.toLowerCase())) {
return true;
}
}
return false;
}
/**
*
* @see javax.swing.filechooser.FileFilter#getDescription()
*/
@Override
public String getDescription() {
return description;
}
public String[] getExtensions() {
return extensions;
}
public void setDescription(String description) {
this.description = description;
}
public void setExtensions(String[] extensions) {
this.extensions = extensions;
}
}
|
9239127e69b46c983ce8151c34d1639be89f1499 | 5,530 | java | Java | PatternMiner/libraries/spmf/src/main/java/algorithms/sequentialpatterns/spam/Prefix.java | landongw/disease-pattern-miner | e62d7ec76b09330cf95c8dbe9993e41e77cc6cc6 | [
"MIT"
] | 10 | 2018-12-26T13:12:53.000Z | 2021-10-09T15:34:31.000Z | PatternMiner/libraries/spmf/src/main/java/algorithms/sequentialpatterns/spam/Prefix.java | vitaliy-ostapchuk93/disease-pattern-miner | e62d7ec76b09330cf95c8dbe9993e41e77cc6cc6 | [
"MIT"
] | 2 | 2021-08-02T17:25:47.000Z | 2021-08-02T17:25:53.000Z | PatternMiner/libraries/spmf/src/main/java/algorithms/sequentialpatterns/spam/Prefix.java | landongw/disease-pattern-miner | e62d7ec76b09330cf95c8dbe9993e41e77cc6cc6 | [
"MIT"
] | 6 | 2019-04-26T13:58:36.000Z | 2020-12-31T06:35:22.000Z | 28.95288 | 100 | 0.600542 | 998,690 | package algorithms.sequentialpatterns.spam;
/* This file is copyright (c) 2008-2013 Philippe Fournier-Viger
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF 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 3 of the License, or (at your option) any later
* version.
*
* SPMF 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
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*/
import patterns.itemset_list_integers_without_support.Itemset;
import java.util.ArrayList;
import java.util.List;
/**
* Implementation of a sequence as a list of itemsets as used by the SPAM, TKS and CMSPAM algorithm.
* <br/><br/>
* <p>
* Copyright (c) 2013 Philippe Fournier-Viger
* <br/><br/>
* <p>
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
* <br/><br/>
* <p>
* SPMF 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 3 of the License, or (at your option) any later
* version.
* <br/><br/>
* <p>
* SPMF 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.
* <br/><br/>
* <p>
* You should have received a copy of the GNU General Public License along with
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*
* @see AlgoSPAM
* @see AlgoCMSPAM
* @see AlgoTKS
* @see AlgoVMSP
*/
class Prefix {
final List<Itemset> itemsets = new ArrayList<Itemset>();
/**
* Default constructor
*/
public Prefix() {
}
/**
* Add an itemset to that sequence
*
* @param itemset
*/
public void addItemset(Itemset itemset) {
itemsets.add(itemset);
}
/**
* Make a copy of that sequence
*
* @return a copy of that sequence
*/
public Prefix cloneSequence() {
// create a new empty sequence
Prefix sequence = new Prefix();
// for each itemset
for (Itemset itemset : itemsets) {
// copy the itemset
sequence.addItemset(itemset.cloneItemSet());
}
return sequence; // return the sequence
}
/**
* Print this sequence to System.out.
*/
public void print() {
System.out.print(toString());
}
/**
* Return a string representation of this sequence
*/
public String toString() {
// create a StringBuilder
StringBuilder r = new StringBuilder("");
// for each itemset
for (Itemset itemset : itemsets) {
// for each item in the current itemset
for (Integer item : itemset.getItems()) {
// append the item to the StringBuilder
String string = item.toString();
r.append(string);
r.append(' ');
}
// add a right parenthesis to indicate the end of the itemset
r.append("-1 ");
}
return r.toString(); // return the string
}
/**
* Get the list of itemsets in this sequence
*
* @return A list of itemsets.
*/
public List<Itemset> getItemsets() {
return itemsets;
}
/**
* Get the itemset at a given position
*
* @param index the position
* @return the itemset
*/
public Itemset get(int index) {
return itemsets.get(index);
}
/**
* Get the ith item in this sequence (no matter in which itemset)
*
* @param i the position
* @return the item
*/
public Integer getIthItem(int i) {
// make a for loop through all itemset
for (int j = 0; j < itemsets.size(); j++) {
// if the position that we look for is in this itemset
if (i < itemsets.get(j).size()) {
// we return the position in this itemset
return itemsets.get(j).get(i);
}
// otherwise we substract the size of the current itemset
// from the position that we are searching for
i = i - itemsets.get(j).size();
}
return null;
}
/**
* Get the number of elements in this sequence
*
* @return the number of elements.
*/
public int size() {
return itemsets.size();
}
/**
* Return the sum of the total number of items in this sequence
*/
public int getItemOccurencesTotalCount() {
// variable to count
int count = 0;
// for each itemset
for (Itemset itemset : itemsets) {
count += itemset.size(); // add the size of the current itemset
}
return count; // return the total
}
// NEW FOR MAX...
public boolean containsItem(Integer item) {
for (Itemset itemset : itemsets) {
if (itemset.getItems().contains(item)) {
return true;
}
}
return false;
}
}
|
923913f28d89af7d96d029d38f737205b4099932 | 1,824 | java | Java | src/main/java/org/optaplannerdelirium/tsp2018prime/swingui/TspPanel.java | ge0ffrey/traveling-santa-2018-prime | 06bbe9d753bb19e338ccc075d7d1955cae70d703 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/optaplannerdelirium/tsp2018prime/swingui/TspPanel.java | ge0ffrey/traveling-santa-2018-prime | 06bbe9d753bb19e338ccc075d7d1955cae70d703 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/optaplannerdelirium/tsp2018prime/swingui/TspPanel.java | ge0ffrey/traveling-santa-2018-prime | 06bbe9d753bb19e338ccc075d7d1955cae70d703 | [
"Apache-2.0"
] | null | null | null | 30.915254 | 75 | 0.73739 | 998,691 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplannerdelirium.tsp2018prime.swingui;
import java.awt.BorderLayout;
import javax.swing.JTabbedPane;
import org.optaplanner.examples.common.swingui.SolutionPanel;
import org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame;
import org.optaplannerdelirium.tsp2018prime.domain.TspSolution;
public class TspPanel extends SolutionPanel<TspSolution> {
private TspWorldPanel tspWorldPanel;
public TspPanel() {
setLayout(new BorderLayout());
JTabbedPane tabbedPane = new JTabbedPane();
tspWorldPanel = new TspWorldPanel(this);
tspWorldPanel.setPreferredSize(PREFERRED_SCROLLABLE_VIEWPORT_SIZE);
tabbedPane.add("World", tspWorldPanel);
add(tabbedPane, BorderLayout.CENTER);
}
@Override
public boolean isWrapInScrollPane() {
return false;
}
@Override
public void resetPanel(TspSolution tspSolution) {
tspWorldPanel.resetPanel(tspSolution);
}
@Override
public void updatePanel(TspSolution tspSolution) {
tspWorldPanel.updatePanel(tspSolution);
}
public SolverAndPersistenceFrame getWorkflowFrame() {
return solverAndPersistenceFrame;
}
}
|
92391477c2b126c0a3c2593409fac42c6b28e7be | 1,551 | java | Java | microagents/sensor/framework/src/main/java/org/immunizer/microagents/sensor/MethodTransformer.java | oiraqi/immunizer | 1b1c1fb8ebedf9e88de4c3b8c7c8565870603853 | [
"MIT"
] | 2 | 2021-01-08T23:32:35.000Z | 2022-03-27T16:22:39.000Z | microagents/sensor/framework/src/main/java/org/immunizer/microagents/sensor/MethodTransformer.java | oiraqi/immunizer | 1b1c1fb8ebedf9e88de4c3b8c7c8565870603853 | [
"MIT"
] | null | null | null | microagents/sensor/framework/src/main/java/org/immunizer/microagents/sensor/MethodTransformer.java | oiraqi/immunizer | 1b1c1fb8ebedf9e88de4c3b8c7c8565870603853 | [
"MIT"
] | 3 | 2020-01-18T14:30:26.000Z | 2021-02-16T15:18:48.000Z | 39.769231 | 110 | 0.766602 | 998,693 | package org.immunizer.microagents.sensor;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.agent.builder.AgentBuilder.Transformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.matcher.ElementMatcher.Junction;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.*;
class MethodTransformer implements Transformer {
Junction<? super MethodDescription> matcher;
private boolean entry = false;
public MethodTransformer(Junction<? super MethodDescription> matcher) {
this(matcher, false);
}
public MethodTransformer(Junction<? super MethodDescription> matcher, boolean entry) {
ElementMatcher<Iterable<? extends ParameterDescription>> parameterMatcher = parameterDescriptions -> {
return (parameterDescriptions != null && parameterDescriptions.iterator().hasNext());
};
this.matcher = matcher.and(isPublic()).and(hasParameters(parameterMatcher));
this.entry = entry;
}
@Override
public DynamicType.Builder<?> transform(final DynamicType.Builder<?> builder,
final TypeDescription typeDescription, final ClassLoader classLoader, final JavaModule module) {
return builder.method(matcher).intercept(Advice.to(entry? EntryAdvice.class:MethodAdvice.class));
}
}
|
923914aaee31ed262d65b98219f782a543403db2 | 24 | java | Java | spring/spring-security/src/main/java/org/ko/security/package-info.java | le3t/ko-repo | 50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5 | [
"Apache-2.0"
] | 4 | 2018-03-13T09:49:43.000Z | 2018-04-04T11:27:40.000Z | spring/spring-security/src/main/java/org/ko/security/package-info.java | le3t/ko-repo | 50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5 | [
"Apache-2.0"
] | 3 | 2019-08-26T13:41:57.000Z | 2019-08-26T13:44:21.000Z | spring/spring-security/src/main/java/org/ko/security/package-info.java | le3t/ko-repo | 50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5 | [
"Apache-2.0"
] | 1 | 2018-12-07T10:06:42.000Z | 2018-12-07T10:06:42.000Z | 24 | 24 | 0.833333 | 998,694 | package org.ko.security; |
9239160afa34f376ae888796e4acf3644759d671 | 345 | java | Java | rule-engine-web/src/main/java/cn/ruleengine/web/store/manager/RuleEngineGeneralRulePublishManager.java | AaronPiUC/rule-engine | 5a4ca60dace1444e7af25311b876b49fa6d569b9 | [
"Apache-2.0"
] | 8 | 2021-05-31T11:29:57.000Z | 2022-03-25T07:34:25.000Z | rule-engine-web/src/main/java/cn/ruleengine/web/store/manager/RuleEngineGeneralRulePublishManager.java | pipti/rule-engine | 6ecdda4d7d6597dff6a968f4ff2692cdcdd8ae35 | [
"Apache-2.0"
] | null | null | null | rule-engine-web/src/main/java/cn/ruleengine/web/store/manager/RuleEngineGeneralRulePublishManager.java | pipti/rule-engine | 6ecdda4d7d6597dff6a968f4ff2692cdcdd8ae35 | [
"Apache-2.0"
] | 3 | 2021-04-05T05:03:47.000Z | 2022-01-29T06:18:46.000Z | 20.294118 | 101 | 0.771014 | 998,695 | package cn.ruleengine.web.store.manager;
import cn.ruleengine.web.store.entity.RuleEngineGeneralRulePublish;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author dqw
* @since 2020-09-04
*/
public interface RuleEngineGeneralRulePublishManager extends IService<RuleEngineGeneralRulePublish> {
}
|
92391714f3714ba39d09af83663865b3e998baa2 | 9,743 | java | Java | substance-flamingo/src/main/java/org/pushingpixels/substance/flamingo/common/TransitionAwareResizableIcon.java | mtbadi39/swing-effects | a29f7a31c73e13027a7228324b5612768452c155 | [
"BSD-3-Clause"
] | 7 | 2017-12-31T21:19:49.000Z | 2021-05-11T00:20:59.000Z | substance-flamingo/src/main/java/org/pushingpixels/substance/flamingo/common/TransitionAwareResizableIcon.java | mtbadi39/swing-effects | a29f7a31c73e13027a7228324b5612768452c155 | [
"BSD-3-Clause"
] | 1 | 2018-01-07T12:16:36.000Z | 2018-02-22T21:50:23.000Z | substance-flamingo/src/main/java/org/pushingpixels/substance/flamingo/common/TransitionAwareResizableIcon.java | mtbadi39/swing-effects | a29f7a31c73e13027a7228324b5612768452c155 | [
"BSD-3-Clause"
] | null | null | null | 35.429091 | 105 | 0.740532 | 998,696 | /*
* Copyright (c) 2005-2018 Flamingo / Substance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Flamingo Kirill Grouchnikov 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 OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.flamingo.common;
import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Map;
import javax.swing.JComponent;
import org.pushingpixels.flamingo.api.common.AbstractCommandButton;
import org.pushingpixels.flamingo.api.common.icon.ResizableIcon;
import org.pushingpixels.substance.api.ComponentState;
import org.pushingpixels.substance.api.SubstanceSlices.ColorSchemeAssociationKind;
import org.pushingpixels.substance.api.colorscheme.SubstanceColorScheme;
import org.pushingpixels.substance.api.icon.SubstanceIconUIResource;
import org.pushingpixels.substance.internal.animation.StateTransitionTracker;
import org.pushingpixels.substance.internal.utils.HashMapKey;
import org.pushingpixels.substance.internal.utils.LazyResettableHashMap;
import org.pushingpixels.substance.internal.utils.SubstanceColorSchemeUtilities;
import org.pushingpixels.substance.internal.utils.SubstanceCoreUtilities;
import org.pushingpixels.substance.internal.utils.icon.TransitionAware;
/**
* Icon with transition-aware capabilities. Has a delegate that does the actual
* painting based on the transition themes.
*
* @author Kirill Grouchnikov
*/
@TransitionAware
public class TransitionAwareResizableIcon implements ResizableIcon {
/**
* The width of the rendered image.
*/
protected int width;
/**
* The height of the rendered image.
*/
protected int height;
/**
* The delegate needs to implement the method in this interface based on the
* provided theme. The theme is computed based on the transitions that are
* happening on the associated control.
*
* @author Kirill Grouchnikov
*/
public static interface Delegate {
/**
* Returns the icon that matches the specified theme.
*
* @param scheme
* Color scheme.
* @param width
* Icon width.
* @param height
* Icon height.
* @return Icon that matches the specified theme.
*/
public SubstanceIconUIResource getColorSchemeIcon(SubstanceColorScheme scheme, int width,
int height);
}
/**
* The associated component.
*/
private JComponent comp;
private StateTransitionTrackerDelegate stateTransitionTrackerDelegate;
/**
* Delegate to compute the actual icons.
*/
private Delegate delegate;
/**
* Icon cache to speed up the subsequent icon painting. The basic assumption
* is that the {@link #delegate} returns an icon that paints the same for
* the same parameters.
*/
private LazyResettableHashMap<SubstanceIconUIResource> iconMap;
public static interface StateTransitionTrackerDelegate {
public StateTransitionTracker getStateTransitionTracker();
}
/**
* Creates a new transition-aware icon.
*
* @param button
* Associated command button.
* @param buttonModel
* Associated model.
* @param extraModelKey
* Extra model key.
* @param delegate
* Delegate to compute the actual icons.
* @param initialDim
* Initial icon dimension.
*/
public TransitionAwareResizableIcon(AbstractCommandButton button,
StateTransitionTrackerDelegate stateTransitionTrackerDelegate,
Delegate delegate, Dimension initialDim) {
this.comp = button;
this.stateTransitionTrackerDelegate = stateTransitionTrackerDelegate;
this.delegate = delegate;
this.iconMap = new LazyResettableHashMap<SubstanceIconUIResource>(
"TransitionAwareResizableIcon");
this.width = initialDim.width;
this.height = initialDim.height;
}
/**
* Returns the current icon to paint.
*
* @return Icon to paint.
*/
private SubstanceIconUIResource getIconToPaint() {
StateTransitionTracker stateTransitionTracker = this.stateTransitionTrackerDelegate
.getStateTransitionTracker();
StateTransitionTracker.ModelStateInfo modelStateInfo = stateTransitionTracker
.getModelStateInfo();
Map<ComponentState, StateTransitionTracker.StateContributionInfo> activeStates = modelStateInfo
.getStateContributionMap();
ComponentState currState = modelStateInfo.getCurrModelState();
SubstanceColorScheme baseScheme = SubstanceColorSchemeUtilities
.getColorScheme(this.comp, ColorSchemeAssociationKind.MARK,
currState);
float baseAlpha = SubstanceColorSchemeUtilities.getAlpha(this.comp,
currState);
HashMapKey keyBase = SubstanceCoreUtilities.getHashKey(baseScheme
.getDisplayName(), baseAlpha, this.width, this.height);
// System.out.println(key);
SubstanceIconUIResource layerBase = this.iconMap.get(keyBase);
if (layerBase == null) {
SubstanceIconUIResource baseFullOpacity = this.delegate.getColorSchemeIcon(baseScheme,
width, height);
if (baseAlpha == 1.0f) {
layerBase = baseFullOpacity;
iconMap.put(keyBase, layerBase);
} else {
BufferedImage baseImage = SubstanceCoreUtilities.getBlankImage(
baseFullOpacity.getIconWidth(), baseFullOpacity
.getIconHeight());
Graphics2D g2base = baseImage.createGraphics();
g2base.setComposite(AlphaComposite.SrcOver.derive(baseAlpha));
baseFullOpacity.paintIcon(this.comp, g2base, 0, 0);
g2base.dispose();
layerBase = new SubstanceIconUIResource(baseImage);
iconMap.put(keyBase, layerBase);
}
}
if (currState.isDisabled() || (activeStates.size() == 1)) {
return layerBase;
}
BufferedImage result = SubstanceCoreUtilities.getBlankImage(layerBase
.getIconWidth(), layerBase.getIconHeight());
Graphics2D g2d = result.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
// draw the base layer
layerBase.paintIcon(this.comp, g2d, 0, 0);
// draw the other active layers
for (Map.Entry<ComponentState, StateTransitionTracker.StateContributionInfo> activeEntry : activeStates
.entrySet()) {
ComponentState activeState = activeEntry.getKey();
// System.out.println("Painting state " + activeState + "[curr is "
// + currState + "] with " + activeEntry.getValue());
if (activeState == currState)
continue;
float stateContribution = activeEntry.getValue().getContribution();
if (stateContribution > 0.0f) {
g2d.setComposite(AlphaComposite.SrcOver
.derive(stateContribution));
SubstanceColorScheme scheme = SubstanceColorSchemeUtilities
.getColorScheme(this.comp,
ColorSchemeAssociationKind.MARK, activeState);
float alpha = SubstanceColorSchemeUtilities.getAlpha(this.comp,
activeState);
HashMapKey key = SubstanceCoreUtilities.getHashKey(scheme
.getDisplayName(), alpha, this.width, this.height);
SubstanceIconUIResource layer = iconMap.get(key);
if (layer == null) {
SubstanceIconUIResource fullOpacity = this.delegate.getColorSchemeIcon(scheme,
width, height);
if (alpha == 1.0f) {
layer = fullOpacity;
iconMap.put(key, layer);
} else {
BufferedImage image = SubstanceCoreUtilities
.getBlankImage(fullOpacity.getIconWidth(),
fullOpacity.getIconHeight());
Graphics2D g2layer = image.createGraphics();
g2layer.setComposite(AlphaComposite.SrcOver
.derive(alpha));
fullOpacity.paintIcon(this.comp, g2layer, 0, 0);
g2layer.dispose();
layer = new SubstanceIconUIResource(image);
iconMap.put(key, layer);
}
}
layer.paintIcon(this.comp, g2d, 0, 0);
}
}
g2d.dispose();
return new SubstanceIconUIResource(result);
}
/*
* (non-Javadoc)
*
* @see javax.swing.Icon#paintIcon(java.awt.Component, java.awt.Graphics,
* int, int)
*/
public void paintIcon(Component c, Graphics g, int x, int y) {
this.getIconToPaint().paintIcon(c, g, x, y);
}
public void setDimension(Dimension newDimension) {
this.width = newDimension.width;
this.height = newDimension.height;
}
public int getIconHeight() {
return this.height;
}
public int getIconWidth() {
return this.width;
}
}
|
923917623feda122d407d06cebef7587266149f6 | 7,394 | java | Java | protocols/bgp/bgpio/src/main/java/org/onosproject/bgpio/protocol/ver4/BgpRouteRefreshMsgVer4.java | abruno06/onos | cc22546d624e6ee4f83cd12be237939873179ecc | [
"Apache-2.0"
] | 1,091 | 2015-01-06T11:10:40.000Z | 2022-03-30T09:09:05.000Z | protocols/bgp/bgpio/src/main/java/org/onosproject/bgpio/protocol/ver4/BgpRouteRefreshMsgVer4.java | abruno06/onos | cc22546d624e6ee4f83cd12be237939873179ecc | [
"Apache-2.0"
] | 39 | 2015-02-13T19:58:32.000Z | 2022-03-02T02:38:07.000Z | protocols/bgp/bgpio/src/main/java/org/onosproject/bgpio/protocol/ver4/BgpRouteRefreshMsgVer4.java | abruno06/onos | cc22546d624e6ee4f83cd12be237939873179ecc | [
"Apache-2.0"
] | 914 | 2015-01-05T19:42:35.000Z | 2022-03-30T09:25:18.000Z | 34.551402 | 104 | 0.578577 | 998,697 | /*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.protocol.ver4;
import com.google.common.base.MoreObjects;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.bgpio.exceptions.BgpParseException;
import org.onosproject.bgpio.protocol.BgpType;
import org.onosproject.bgpio.types.BgpHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.onosproject.bgpio.protocol.BgpRouteRefreshMsg;
import org.onosproject.bgpio.protocol.BgpMessageReader;
import org.onosproject.bgpio.protocol.BgpMessageWriter;
import org.onosproject.bgpio.protocol.BgpVersion;
import java.util.LinkedList;
import java.util.List;
/**
* Provides BGP Route Refresh message.
*/
public class BgpRouteRefreshMsgVer4 implements BgpRouteRefreshMsg {
/*
<Route Refresh Message>::=
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ +
| Marker |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Length | Type |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| AFI | Reserved | SAFI |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
REFERENCE : RFC 2918
*/
private static final Logger log = LoggerFactory.getLogger(BgpRouteRefreshMsgVer4.class);
public static final byte PACKET_VERSION = 4;
public static final int PACKET_LENGTH = 0x17;
public static final int MARKER_LENGTH = 16;
public static final BgpType MSG_TYPE = BgpType.ROUTE_REFRESH;
private static final byte[] MARKER = new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
private static final BgpHeader DEFAULT_ROUTEREFRESH_HEADER = new BgpHeader(MARKER,
(short) PACKET_LENGTH, BgpType.ROUTE_REFRESH.getType());
private BgpHeader bgpMsgHeader;
private byte version;
private List<AfiSafiValue> afiSafiValues;
public static final BgpRouteRefreshMsgVer4.Reader READER = new Reader();
/**
* Reader class for reading BGP route refresh message from channel buffer.
*/
static class Reader implements BgpMessageReader<BgpRouteRefreshMsg> {
@Override
public BgpRouteRefreshMsgVer4 readFrom(ChannelBuffer cb, BgpHeader bgpHeader)
throws BgpParseException {
Short afi = cb.readShort();
log.debug("AFI read from Route Refresh message = {}", afi);
byte reserved = cb.readByte();
log.debug("Reserved read from Route Refresh message = {}", reserved);
byte safi = cb.readByte();
log.debug("SAFI read from Route Refresh message = {}", safi);
List<AfiSafiValue> afiSafiList = new LinkedList<>();
AfiSafiValue afisafiValue = new AfiSafiValue(afi, reserved, safi);
afiSafiList.add(afisafiValue);
return new BgpRouteRefreshMsgVer4(DEFAULT_ROUTEREFRESH_HEADER, PACKET_VERSION, afiSafiList);
}
}
/**
* Default constructor.
*/
public BgpRouteRefreshMsgVer4() {
this.bgpMsgHeader = null;
this.version = 0;
this.afiSafiValues = null;
}
public BgpRouteRefreshMsgVer4(BgpHeader msgHeader, byte version, List<AfiSafiValue> afiSafiValues) {
this.bgpMsgHeader = msgHeader;
this.version = version;
this.afiSafiValues = afiSafiValues;
}
/**
* Builder class for BGP route refresh message.
*/
static class Builder implements BgpRouteRefreshMsg.Builder {
BgpHeader bgpHeader = null;
boolean isHeaderSet = false;
List<AfiSafiValue> afiSafiList = null;
@Override
public Builder setHeader(BgpHeader bgpMsgHeader) {
this.bgpHeader = bgpMsgHeader;
this.isHeaderSet = true;
return this;
}
@Override
public BgpRouteRefreshMsg.Builder addAfiSafiValue(short afi, byte reserved, byte safi) {
if (afiSafiList == null) {
afiSafiList = new LinkedList<>();
}
AfiSafiValue currentElement = new AfiSafiValue(afi, reserved, safi);
afiSafiList.add(currentElement);
return this;
}
@Override
public BgpRouteRefreshMsg build() {
BgpHeader header = isHeaderSet ? bgpHeader : DEFAULT_ROUTEREFRESH_HEADER;
return new BgpRouteRefreshMsgVer4(header, PACKET_VERSION, afiSafiList);
}
}
@Override
public void writeTo(ChannelBuffer cb) {
WRITER.write(cb, this);
}
static final Writer WRITER = new Writer();
/**
* Writer class for writing the BGP route refresh message to channel buffer.
*/
static class Writer implements BgpMessageWriter<BgpRouteRefreshMsgVer4> {
@Override
public void write(ChannelBuffer cb, BgpRouteRefreshMsgVer4 message) {
//Iterate over the added AFI-SAFI pair and write a new packet for each of those
for (AfiSafiValue element : message.afiSafiValues) {
cb.writeBytes(MARKER, 0, MARKER_LENGTH);
cb.writeShort(PACKET_LENGTH);
cb.writeByte(MSG_TYPE.getType());
cb.writeShort(element.afi);
cb.writeByte(element.reserved);
cb.writeByte(element.safi);
}
}
}
@Override
public BgpVersion getVersion() {
return BgpVersion.BGP_4;
}
@Override
public BgpType getType() {
return MSG_TYPE;
}
@Override
public BgpHeader getHeader() {
return this.bgpMsgHeader;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass()).toString();
}
}
final class AfiSafiValue {
final short afi;
final byte reserved;
final byte safi;
public AfiSafiValue(short afi, byte reserved, byte safi) {
this.afi = afi;
this.reserved = reserved;
this.safi = safi;
}
}
|
923917a0b4f1f6cb225bc033ce7369ead49d25c3 | 1,027 | java | Java | surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java | kalgon/maven-surefire | 2db57079be52fe6dfc0bfd5ad88cd2e2d734d677 | [
"Apache-2.0"
] | 318 | 2015-01-03T06:53:09.000Z | 2022-03-28T17:28:35.000Z | surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java | kalgon/maven-surefire | 2db57079be52fe6dfc0bfd5ad88cd2e2d734d677 | [
"Apache-2.0"
] | 326 | 2015-01-01T15:10:52.000Z | 2022-03-31T16:17:13.000Z | surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java | kalgon/maven-surefire | 2db57079be52fe6dfc0bfd5ad88cd2e2d734d677 | [
"Apache-2.0"
] | 502 | 2015-01-09T02:37:07.000Z | 2022-03-29T16:14:30.000Z | 32.09375 | 63 | 0.727361 | 998,698 | package jiras.surefire1095;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import junit.runner.Version;
import org.junit.Test;
public class SomeTest {
@Test
public void test()
{
System.out.println( "Running JUnit " + Version.id() );
}
}
|
923917ac89de7cdf0e5f8e59ca2a6d9936be1639 | 1,482 | java | Java | Showcase/app/build/tmp/kapt3/stubs/debug/com/scichart/scishowcase/utils/PermissionManager.java | qcuong/Sci-Chart | 552176dc0fa791383af7a0d1863476efffea5944 | [
"MIT"
] | null | null | null | Showcase/app/build/tmp/kapt3/stubs/debug/com/scichart/scishowcase/utils/PermissionManager.java | qcuong/Sci-Chart | 552176dc0fa791383af7a0d1863476efffea5944 | [
"MIT"
] | null | null | null | Showcase/app/build/tmp/kapt3/stubs/debug/com/scichart/scishowcase/utils/PermissionManager.java | qcuong/Sci-Chart | 552176dc0fa791383af7a0d1863476efffea5944 | [
"MIT"
] | 1 | 2018-03-22T09:03:36.000Z | 2018-03-22T09:03:36.000Z | 70.571429 | 896 | 0.731444 | 998,699 | package com.scichart.scishowcase.utils;
@kotlin.Metadata(mv = {1, 1, 6}, bv = {1, 0, 1}, k = 1, d1 = {"\u0000*\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\b\n\u0000\n\u0002\u0010\u000b\n\u0000\n\u0002\u0010\u000e\n\u0000\n\u0002\u0010\u0002\n\u0000\u0018\u00002\u00020\u0001B\r\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u00a2\u0006\u0002\u0010\u0004J\u000e\u0010\u0007\u001a\u00020\b2\u0006\u0010\t\u001a\u00020\nJ\u000e\u0010\u000b\u001a\u00020\f2\u0006\u0010\t\u001a\u00020\nR\u000e\u0010\u0005\u001a\u00020\u0006X\u0082D\u00a2\u0006\u0002\n\u0000R\u000e\u0010\u0002\u001a\u00020\u0003X\u0082\u0004\u00a2\u0006\u0002\n\u0000\u00a8\u0006\r"}, d2 = {"Lcom/scichart/scishowcase/utils/PermissionManager;", "", "activity", "Landroid/app/Activity;", "(Landroid/app/Activity;)V", "SHOWCASE_REQUEST_CODE", "", "hasPermission", "", "permission", "", "requestPermission", "", "app_debug"})
public final class PermissionManager {
private final int SHOWCASE_REQUEST_CODE = 42;
private final android.app.Activity activity = null;
public final boolean hasPermission(@org.jetbrains.annotations.NotNull()
java.lang.String permission) {
return false;
}
public final void requestPermission(@org.jetbrains.annotations.NotNull()
java.lang.String permission) {
}
public PermissionManager(@org.jetbrains.annotations.NotNull()
android.app.Activity activity) {
super();
}
} |
923917cdead3797c699c8f402713257c6497bb99 | 817 | java | Java | src/main/java/com/jbatista/ushort/api/AppBeans.java | jbatistareis/ushort-api | aca42e4bb9ee080fc5954ceb2bad205f54d57a66 | [
"MIT"
] | 2 | 2019-02-03T13:43:04.000Z | 2019-02-08T03:16:08.000Z | src/main/java/com/jbatista/ushort/api/AppBeans.java | jbatistareis/ushort-api | aca42e4bb9ee080fc5954ceb2bad205f54d57a66 | [
"MIT"
] | null | null | null | src/main/java/com/jbatista/ushort/api/AppBeans.java | jbatistareis/ushort-api | aca42e4bb9ee080fc5954ceb2bad205f54d57a66 | [
"MIT"
] | null | null | null | 31.423077 | 88 | 0.779682 | 998,700 | package com.jbatista.ushort.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisKeyValueAdapter.EnableKeyspaceEvents;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)
public class AppBeans {
@Bean
public Logger logger() {
return LoggerFactory.getLogger("U-Short");
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
923917ea8626d48ca3fb66168f6ca233f5867a22 | 646 | java | Java | src/main/java/seedu/pdf/logic/commands/ClearCommand.java | WeiTangLau/main | bce045b93f1277838b0c3dc7195e37e9d66baf97 | [
"MIT"
] | null | null | null | src/main/java/seedu/pdf/logic/commands/ClearCommand.java | WeiTangLau/main | bce045b93f1277838b0c3dc7195e37e9d66baf97 | [
"MIT"
] | 171 | 2019-03-05T11:36:07.000Z | 2020-02-25T09:47:31.000Z | src/main/java/seedu/pdf/logic/commands/ClearCommand.java | ptvrajsk/main | 8c79fb0141338a3513840025c3021e003154f96e | [
"MIT"
] | 6 | 2019-02-10T11:38:38.000Z | 2019-02-20T12:20:34.000Z | 25.84 | 78 | 0.724458 | 998,701 | package seedu.pdf.logic.commands;
import static java.util.Objects.requireNonNull;
import seedu.pdf.logic.CommandHistory;
import seedu.pdf.model.Model;
import seedu.pdf.model.PdfBook;
/**
* Clears the PDF book.
*/
public class ClearCommand extends Command {
public static final String COMMAND_WORD = "clear";
public static final String MESSAGE_SUCCESS = "PDF book has been cleared!";
@Override
public CommandResult execute(Model model, CommandHistory history) {
requireNonNull(model);
model.setPdfBook(new PdfBook());
model.commitPdfBook();
return new CommandResult(MESSAGE_SUCCESS);
}
}
|
9239181d588929b47bedf2e9808338229f2e52e3 | 1,180 | java | Java | src/main/java/com/bitmovin/api/sdk/model/WeightedPredictionPFrames.java | mcherif/bitmovinexp | d4d746794f26c8e9692c834e63d5d19503693bbf | [
"MIT"
] | 7 | 2019-10-03T05:24:47.000Z | 2022-03-04T14:46:15.000Z | src/main/java/com/bitmovin/api/sdk/model/WeightedPredictionPFrames.java | mcherif/bitmovinexp | d4d746794f26c8e9692c834e63d5d19503693bbf | [
"MIT"
] | 3 | 2020-04-15T15:35:45.000Z | 2020-11-09T18:53:38.000Z | src/main/java/com/bitmovin/api/sdk/model/WeightedPredictionPFrames.java | mcherif/bitmovinexp | d4d746794f26c8e9692c834e63d5d19503693bbf | [
"MIT"
] | 2 | 2020-04-21T13:48:56.000Z | 2022-02-14T00:58:09.000Z | 20.701754 | 76 | 0.712712 | 998,702 | package com.bitmovin.api.sdk.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum WeightedPredictionPFrames {
/**
* Do not keep P-frame references
*/
DISABLED("DISABLED"),
/**
* Enable weighted references
*/
SIMPLE("SIMPLE"),
/**
* Enable weighted references and duplicates
*/
SMART("SMART");
private String value;
WeightedPredictionPFrames(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static WeightedPredictionPFrames fromValue(String text) {
for (WeightedPredictionPFrames b : WeightedPredictionPFrames.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
|
923918840329cd758731ff6edacaff9ec714df63 | 236 | java | Java | part3/src/main/java/com/example/part3/Money.java | syukai/tddsandbox | 6bb7423cbfb71cfea25b0109b083a97397de76e5 | [
"MIT"
] | null | null | null | part3/src/main/java/com/example/part3/Money.java | syukai/tddsandbox | 6bb7423cbfb71cfea25b0109b083a97397de76e5 | [
"MIT"
] | null | null | null | part3/src/main/java/com/example/part3/Money.java | syukai/tddsandbox | 6bb7423cbfb71cfea25b0109b083a97397de76e5 | [
"MIT"
] | null | null | null | 15.733333 | 43 | 0.665254 | 998,703 | package com.example.part3;
public class Money {
int value;
Money(int value) {
this.value = value;
}
static Money zero() {
return new Money(0);
}
public Money plus(Money add) {
return new Money(this.value + add.value);
}
}
|
92391907fc3d3be26922e875260c857c8810613f | 11,127 | java | Java | src/test/java/com/amazon/opendistro/elasticsearch/performanceanalyzer/rca/integTests/tests/cache_tuning/RcaItCacheTuning.java | sidheart/performance-analyzer-rca | 67c139e327d23337f204a71d819a181696c75fb3 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/amazon/opendistro/elasticsearch/performanceanalyzer/rca/integTests/tests/cache_tuning/RcaItCacheTuning.java | sidheart/performance-analyzer-rca | 67c139e327d23337f204a71d819a181696c75fb3 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/amazon/opendistro/elasticsearch/performanceanalyzer/rca/integTests/tests/cache_tuning/RcaItCacheTuning.java | sidheart/performance-analyzer-rca | 67c139e327d23337f204a71d819a181696c75fb3 | [
"Apache-2.0"
] | null | null | null | 44.866935 | 134 | 0.680237 | 998,704 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.tests.cache_tuning;
import static com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.tests.cache_tuning.RcaItCacheTuning.INDEX_NAME;
import static com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.tests.cache_tuning.RcaItCacheTuning.SHARD_ID;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.metrics.AllMetrics;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.api.metrics.Cache_FieldData_Eviction;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.api.metrics.Cache_FieldData_Size;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.api.metrics.Cache_Max_Size;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.api.metrics.Cache_Request_Eviction;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.api.metrics.Cache_Request_Hit;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.api.metrics.Cache_Request_Size;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.RcaItMarker;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.AClusterType;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.AErrorPatternIgnored;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.AExpect;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.AMetric;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.ARcaGraph;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.ATable;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.annotations.ATuple;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.configs.ClusterType;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.configs.Consts;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.configs.HostTag;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.framework.runners.RcaItNotEncryptedRunner;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.tests.cache_tuning.validator.FieldDataCacheValidator;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.integTests.tests.cache_tuning.validator.ShardRequestCacheValidator;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.store.ElasticSearchAnalysisGraph;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.store.rca.cluster.FieldDataCacheClusterRca;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.store.rca.cluster.ShardRequestCacheClusterRca;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@Category(RcaItMarker.class)
@RunWith(RcaItNotEncryptedRunner.class)
@AClusterType(ClusterType.MULTI_NODE_CO_LOCATED_MASTER)
@ARcaGraph(ElasticSearchAnalysisGraph.class)
@AMetric(
name = Cache_FieldData_Size.class,
dimensionNames = {
AllMetrics.CommonDimension.Constants.INDEX_NAME_VALUE,
AllMetrics.CommonDimension.Constants.SHARDID_VALUE
},
tables = {
@ATable(
hostTag = HostTag.DATA_0,
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 8500.0, avg = 8500.0, min = 8500.0, max = 8500.0),
}),
@ATable(
hostTag = {HostTag.ELECTED_MASTER},
tuple = {
@ATuple(
dimensionValues = {"Index1", "1"},
sum = 100.0, avg = 100.0, min = 100.0, max = 100.0),
})
})
@AMetric(
name = Cache_FieldData_Eviction.class,
dimensionNames = {
AllMetrics.CommonDimension.Constants.INDEX_NAME_VALUE,
AllMetrics.CommonDimension.Constants.SHARDID_VALUE
},
tables = {
@ATable(
hostTag = HostTag.DATA_0,
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 1.0, avg = 1.0, min = 1.0, max = 1.0),
}),
@ATable(
hostTag = {HostTag.ELECTED_MASTER},
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 0.0, avg = 0.0, min = 0.0, max = 0.0),
})
})
@AMetric(
name = Cache_Request_Size.class,
dimensionNames = {
AllMetrics.CommonDimension.Constants.INDEX_NAME_VALUE,
AllMetrics.CommonDimension.Constants.SHARDID_VALUE
},
tables = {
@ATable(
hostTag = HostTag.DATA_0,
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 100.0, avg = 100.0, min = 100.0, max = 100.0),
}),
@ATable(
hostTag = {HostTag.ELECTED_MASTER},
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 50.0, avg = 50.0, min = 50.0, max = 50.0),
})
})
@AMetric(
name = Cache_Request_Eviction.class,
dimensionNames = {
AllMetrics.CommonDimension.Constants.INDEX_NAME_VALUE,
AllMetrics.CommonDimension.Constants.SHARDID_VALUE
},
tables = {
@ATable(
hostTag = HostTag.DATA_0,
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 1.0, avg = 1.0, min = 1.0, max = 1.0),
}),
@ATable(
hostTag = {HostTag.ELECTED_MASTER},
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 0.0, avg = 0.0, min = 0.0, max = 0.0),
})
})
@AMetric(
name = Cache_Request_Hit.class,
dimensionNames = {
AllMetrics.CommonDimension.Constants.INDEX_NAME_VALUE,
AllMetrics.CommonDimension.Constants.SHARDID_VALUE
},
tables = {
@ATable(
hostTag = HostTag.DATA_0,
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 1.0, avg = 1.0, min = 1.0, max = 1.0),
}),
@ATable(
hostTag = {HostTag.ELECTED_MASTER},
tuple = {
@ATuple(
dimensionValues = {INDEX_NAME, SHARD_ID},
sum = 0.0, avg = 0.0, min = 0.0, max = 0.0),
})
})
@AMetric(
name = Cache_Max_Size.class,
dimensionNames = {AllMetrics.CacheConfigDimension.Constants.TYPE_VALUE},
tables = {
@ATable(
hostTag = HostTag.DATA_0,
tuple = {
@ATuple(
dimensionValues = {AllMetrics.CacheType.Constants.FIELD_DATA_CACHE_NAME},
sum = 10000.0, avg = 10000.0, min = 10000.0, max = 10000.0),
@ATuple(
dimensionValues = {AllMetrics.CacheType.Constants.SHARD_REQUEST_CACHE_NAME},
sum = 100.0, avg = 100.0, min = 100.0, max = 100.0),
@ATuple(
dimensionValues = {AllMetrics.CacheType.Constants.SHARD_REQUEST_CACHE_NAME},
sum = 100.0, avg = 100.0, min = 100.0, max = 100.0)
}),
@ATable(
hostTag = {HostTag.ELECTED_MASTER},
tuple = {
@ATuple(
dimensionValues = {AllMetrics.CacheType.Constants.FIELD_DATA_CACHE_NAME},
sum = 10000.0, avg = 10000.0, min = 10000.0, max = 10000.0),
@ATuple(
dimensionValues = {AllMetrics.CacheType.Constants.SHARD_REQUEST_CACHE_NAME},
sum = 100.0, avg = 100.0, min = 100.0, max = 100.0)
})
})
public class RcaItCacheTuning {
public static final String INDEX_NAME = "MockIndex";
public static final String SHARD_ID = "1";
// Test FieldDataCacheClusterRca.
// This rca should be un-healthy when cache size is higher than threshold with evictions.
// TODO : extend this integ test to cover Decision Maker framework and queue remediation actions
@Test
@AExpect(
what = AExpect.Type.REST_API,
on = HostTag.ELECTED_MASTER,
validator = FieldDataCacheValidator.class,
forRca = FieldDataCacheClusterRca.class,
timeoutSeconds = 700)
@AErrorPatternIgnored(
pattern = "AggregateMetric:gather()",
reason = "CPU metrics are expected to be missing in this integ test")
@AErrorPatternIgnored(
pattern = "Metric:gather()",
reason = "Metrics are expected to be missing in this integ test")
@AErrorPatternIgnored(
pattern = "NodeConfigCacheReaderUtil",
reason = "Node Config Cache are expected to be missing in this integ test.")
@AErrorPatternIgnored(
pattern = "CacheUtil:getCacheMaxSize()",
reason = "Node Config Cache is expected to be missing during startup.")
@AErrorPatternIgnored(
pattern = "ModifyCacheMaxSizeAction:build()",
reason = "Heap metrics is expected to be missing in this integ test.")
public void testFieldDataCacheRca() {}
// Test ShardRequestCacheClusterRca.
// This rca should be un-healthy when cache size is higher than threshold with evictions and hits.
@Test
@AExpect(
what = AExpect.Type.REST_API,
on = HostTag.ELECTED_MASTER,
validator = ShardRequestCacheValidator.class,
forRca = ShardRequestCacheClusterRca.class,
timeoutSeconds = 700)
@AErrorPatternIgnored(
pattern = "AggregateMetric:gather()",
reason = "CPU metrics are expected to be missing in this integ test")
@AErrorPatternIgnored(
pattern = "Metric:gather()",
reason = "Metrics are expected to be missing in this integ test")
@AErrorPatternIgnored(
pattern = "NodeConfigCacheReaderUtil",
reason = "Node config cache metrics are expected to be missing in this integ test.")
@AErrorPatternIgnored(
pattern = "CacheUtil:getCacheMaxSize()",
reason = "Node Config Cache is expected to be missing during startup.")
@AErrorPatternIgnored(
pattern = "ModifyCacheMaxSizeAction:build()",
reason = "Heap metrics is expected to be missing in this integ test.")
public void testShardRequestCacheRca() {}
}
|
9239193f2e43eb7f184e3a9f39accc26ffd04cb3 | 3,206 | java | Java | ibroker/ams-api-gateway/src/main/java/com/intel/iot/ams/entity/HistoricCfgInstance.java | lum1n0us/intel-device-resource-mgt-lib | 0ba77b1095b7427e754f1ec02827ffb4e0bb00bd | [
"Apache-2.0"
] | null | null | null | ibroker/ams-api-gateway/src/main/java/com/intel/iot/ams/entity/HistoricCfgInstance.java | lum1n0us/intel-device-resource-mgt-lib | 0ba77b1095b7427e754f1ec02827ffb4e0bb00bd | [
"Apache-2.0"
] | null | null | null | ibroker/ams-api-gateway/src/main/java/com/intel/iot/ams/entity/HistoricCfgInstance.java | lum1n0us/intel-device-resource-mgt-lib | 0ba77b1095b7427e754f1ec02827ffb4e0bb00bd | [
"Apache-2.0"
] | null | null | null | 18.011236 | 97 | 0.688397 | 998,705 | /*
* Copyright (C) 2020 Intel Corporation. All rights reserved. SPDX-License-Identifier: Apache-2.0
*/
package com.intel.iot.ams.entity;
import java.util.Date;
import javax.persistence.*;
@Entity
@Table(name = "HistoricCfgInstance")
public class HistoricCfgInstance {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true, nullable = false)
private Integer id;
@Column(nullable = false)
private String cfgUuid;
@Column(nullable = false)
private String userName;
@Column(nullable = false)
private String pathName;
@Column(nullable = false)
private String targetType;
@Column(nullable = false)
private Integer instanceId;
@Column(nullable = false)
private String targetId;
@Column(nullable = false)
private Integer contentId;
@Column(nullable = false)
private int contentType;
@Column private String sharedName;
@Lob
@Column(nullable = false)
private byte[] content;
@Column(nullable = false)
private String contentHash;
@Column private String formatId;
@Column private Date startTime;
@Column private Date endTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCfgUuid() {
return cfgUuid;
}
public void setCfgUuid(String cfgUuid) {
this.cfgUuid = cfgUuid;
}
public Integer getInstanceId() {
return instanceId;
}
public void setInstanceId(Integer instanceId) {
this.instanceId = instanceId;
}
public Integer getContentId() {
return contentId;
}
public void setContentId(Integer contentId) {
this.contentId = contentId;
}
public int getContentType() {
return contentType;
}
public void setContentType(int contentType) {
this.contentType = contentType;
}
public String getSharedName() {
return sharedName;
}
public void setSharedName(String sharedName) {
this.sharedName = sharedName;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public String getContentHash() {
return contentHash;
}
public void setContentHash(String contentHash) {
this.contentHash = contentHash;
}
public String getFormatId() {
return formatId;
}
public void setFormatId(String formatId) {
this.formatId = formatId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPathName() {
return pathName;
}
public void setPathName(String pathName) {
this.pathName = pathName;
}
public String getTargetType() {
return targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
public String getTargetId() {
return targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
}
|
9239197945d8791555de1d146560f0dc7ab8ac43 | 989 | java | Java | src/main/java/org/hyperledger/aries/api/ledger/EndpointType.java | pixelschnitzel/acapy-java-client | c0837971c5e387ad06c7649af4b80d78d7bfd134 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2021-06-02T10:24:33.000Z | 2022-03-23T08:20:31.000Z | src/main/java/org/hyperledger/aries/api/ledger/EndpointType.java | pixelschnitzel/acapy-java-client | c0837971c5e387ad06c7649af4b80d78d7bfd134 | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2021-06-21T05:27:27.000Z | 2022-01-19T17:16:34.000Z | src/main/java/org/hyperledger/aries/api/ledger/EndpointType.java | ianco/acapy-java-client | c0d6255098c67c5c378a0582f1b576c20349b2f0 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2021-05-28T09:11:43.000Z | 2022-03-29T08:52:32.000Z | 23 | 80 | 0.695652 | 998,706 | /*
* Copyright (c) 2020-2021 - for information on the respective copyright owner
* see the NOTICE file and/or the repository at
* https://github.com/hyperledger-labs/acapy-java-client
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.aries.api.ledger;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Endpoint request types
*
* @since aca-py 0.5.4
*
*/
@Getter
@AllArgsConstructor
public enum EndpointType {
@SerializedName("Endpoint")
ENDPOINT("endpoint", "Endpoint"),
@SerializedName("Profile")
PROFILE("profile", "Profile"),
@SerializedName("LinkedDomains")
LINKED_DOMAINS("linked_domains", "LinkedDomains")
;
/**
* The name of the endpoint how its written to the ledger
*/
private final String ledgerName;
/**
* The name of the endpoint as it is used in aca-py, same as @SerializedName
*/
private final String acaPyName;
}
|
92391a4b7fe05cfd4828c0babbbc4e2d17dd1323 | 3,035 | java | Java | hibernate/src/test/java/net/sf/beanlib/hibernate5/ByteArrayCopyTest.java | emsouza/beanlib | ac28d0154af1bd67540a4a5b08850c5bd2fe42bd | [
"Apache-2.0"
] | 7 | 2015-01-30T15:10:57.000Z | 2021-03-03T06:51:34.000Z | hibernate/src/test/java/net/sf/beanlib/hibernate5/ByteArrayCopyTest.java | emsouza/beanlib | ac28d0154af1bd67540a4a5b08850c5bd2fe42bd | [
"Apache-2.0"
] | 1 | 2022-01-21T23:26:36.000Z | 2022-01-21T23:26:36.000Z | hibernate/src/test/java/net/sf/beanlib/hibernate5/ByteArrayCopyTest.java | emsouza/beanlib | ac28d0154af1bd67540a4a5b08850c5bd2fe42bd | [
"Apache-2.0"
] | 5 | 2017-01-11T21:25:52.000Z | 2020-07-07T08:27:50.000Z | 26.391304 | 112 | 0.608237 | 998,707 | /*
* Copyright 2007 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 net.sf.beanlib.hibernate5;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator;
import net.sf.beanlib.provider.BeanTransformer;
import net.sf.beanlib.provider.replicator.BeanReplicator;
/**
* @author Joe D. Velopar
*/
@RunWith(JUnit4.class)
public class ByteArrayCopyTest {
private static class P {
private byte[] bytes;
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
}
private static class PArray {
private P[] pa;
public P[] getPa() {
return pa;
}
public void setPa(P[] pa) {
this.pa = pa;
}
}
@Test
public void arrays() {
P p1 = new P();
byte[] bytes = { 1, 2, 3 };
p1.setBytes(bytes);
P p2 = new P();
byte[] bytes2 = { 4, 5, 6 };
p2.setBytes(bytes2);
P[] pa = { p1, p2 };
PArray parray = new PArray();
parray.setPa(pa);
{
PArray parray2 = new BeanReplicator(new BeanTransformer()).replicateBean(parray, parray.getClass());
assertNotSame(parray, parray2);
assertNotSame(parray.getPa(), parray2.getPa());
}
{
PArray parray2 = new Hibernate5BeanReplicator().copy(parray);
assertNotSame(parray, parray2);
assertNotSame(parray.getPa(), parray2.getPa());
}
}
@Test
public void beanReplicator() {
P p1 = new P();
byte[] bytes = { 1, 2, 3 };
p1.setBytes(bytes);
P p2 = new BeanReplicator(new BeanTransformer()).replicateBean(p1, p1.getClass());
assertNotSame(p1, p2);
assertNotSame(p1.getBytes(), p2.getBytes());
assertTrue(Arrays.equals(p1.getBytes(), p2.getBytes()));
}
@Test
public void hibernate3BeanReplicator() {
P p1 = new P();
byte[] bytes = { 1, 2, 3 };
p1.setBytes(bytes);
P p2 = new Hibernate5BeanReplicator().copy(p1);
assertNotSame(p1, p2);
assertNotSame(p1.getBytes(), p2.getBytes());
assertTrue(Arrays.equals(p1.getBytes(), p2.getBytes()));
}
}
|
92391d5a8d98a6bfe9eb82a7bd44349659dba6da | 4,434 | java | Java | src/main/java/lu/uni/adtool/domains/rings/RealG0.java | salman-/MasterThesis | cdda02ab0afcd9535037e2948868bbe9436f454e | [
"MIT"
] | null | null | null | src/main/java/lu/uni/adtool/domains/rings/RealG0.java | salman-/MasterThesis | cdda02ab0afcd9535037e2948868bbe9436f454e | [
"MIT"
] | 6 | 2017-06-02T01:19:06.000Z | 2017-06-04T06:22:47.000Z | src/main/java/lu/uni/adtool/domains/rings/RealG0.java | salman-/A-ADTree | cdda02ab0afcd9535037e2948868bbe9436f454e | [
"MIT"
] | null | null | null | 23.978378 | 79 | 0.6055 | 998,708 | /**
* Author: Piotr Kordy (ychag@example.com <mailto:ychag@example.com>)
* Date: 10/12/2015
* Copyright (c) 2015,2013,2012 University of Luxembourg -- Faculty of Science,
* Technology and Communication FSTC
* All rights reserved.
* Licensed under GNU Affero General Public License 3.0;
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package lu.uni.adtool.domains.rings;
import java.io.Serializable;
/**
* Set of real numbers with maximum value.
*
* @author Piotr Kordy
*/
public class RealG0 implements Serializable, Ring {
/**
* Constructs a new instance.
*/
public RealG0() {
this(0);
}
/**
* Constructs a newly allocated RealG0 object that represents the primitive
* double argument.
*
* @param d
* the value to be represented by the RealG0.
*/
public RealG0(final double d) {
value = d;
checkValue();
}
public Object clone() {
return new RealG0(value);
}
/**
* Set the new value reading from the string
*
*/
public final boolean updateFromString(String s) {
double origValue = this.value;
try {
this.value = Double.parseDouble(s);
}
catch (NumberFormatException e) {
this.value = origValue;
return false;
}
if (!checkValue()) {
this.value = origValue;
return false;
}
return true;
}
/**
* {@inheritDoc}
*
* @see Object#toString()
*/
public final String toString() {
return new Double(getValue()).toString();
}
/**
* Unicode representation of a number.
*
* @return string with unicode representation.
*/
public final String toUnicode() {
if (getValue() == Double.POSITIVE_INFINITY) {
return "\u221E";
}
else {
return new Double(getValue()).toString();
}
}
/**
* Return a minimal number of the two.
*
* @param a
* the first number to be compared.
* @param b
* the second nubmer to be compared.
* @return the smaller of two numbers.
*/
public static final RealG0 min(final RealG0 a, final RealG0 b) {
return new RealG0(Math.min(a.getValue(), b.getValue()));
}
/**
* Return a maximal number of the two.
*
* @param a
* the first number to be compared.
* @param b
* the second nubmer to be compared.
* @return the bigger of two numbers.
*/
public static final RealG0 max(final RealG0 a, final RealG0 b) {
return new RealG0(Math.max(a.getValue(), b.getValue()));
}
/**
* Sums two numbers.
*
* @param a
* the first number to be compared.
* @param b
* the second nubmer to be compared.
* @return the sum of two numbers.
*/
public static final RealG0 sum(final RealG0 a, final RealG0 b) {
return new RealG0(a.getValue() + b.getValue());
}
/**
* Gets the value for this instance.
*
* @return The value.
*/
public double getValue() {
return this.value;
}
public int compareTo(Object o) {
if (o instanceof RealG0) {
double val2 = ((RealG0) o).getValue();
if (value == val2) {
return 0;
}
if (value < val2) {
return -1;
}
if (value > val2) {
return 1;
}
}
if (o instanceof RealZeroOne) {
double val2 = ((RealZeroOne) o).getValue();
if (value == val2) {
return 0;
}
if (value < val2) {
return -1;
}
if (value > val2) {
return 1;
}
}
throw new ClassCastException("Unable to compare RealG0 class with " + o);
}
private boolean checkValue() {
if (value < 0) {
value = 0;
return false;
}
return true;
}
static final long serialVersionUID = 122132278985141212L;
private double value;
}
|
92391ec38c1b5446c49849acb59f5b49b679fce4 | 1,095 | java | Java | components/data-bridge/org.wso2.carbon.databridge.core/src/main/java/org/wso2/carbon/databridge/core/EventConverter.java | kasungayan/CEP-Emailsender | 189c5f7aa613391ae89308309fe10ee3b58990e1 | [
"Apache-2.0"
] | null | null | null | components/data-bridge/org.wso2.carbon.databridge.core/src/main/java/org/wso2/carbon/databridge/core/EventConverter.java | kasungayan/CEP-Emailsender | 189c5f7aa613391ae89308309fe10ee3b58990e1 | [
"Apache-2.0"
] | null | null | null | components/data-bridge/org.wso2.carbon.databridge.core/src/main/java/org/wso2/carbon/databridge/core/EventConverter.java | kasungayan/CEP-Emailsender | 189c5f7aa613391ae89308309fe10ee3b58990e1 | [
"Apache-2.0"
] | null | null | null | 31.285714 | 80 | 0.73242 | 998,709 | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.databridge.core;
import org.wso2.carbon.databridge.commons.Event;
import org.wso2.carbon.databridge.core.Utils.AgentSession;
import java.util.List;
/**
* the util class that converts Events and its definitions in to various forms
*/
public interface EventConverter {
public List<Event> toEventList(Object eventBundle,
StreamTypeHolder streamTypeHolder);
}
|
92392025dadd0f4ecc7d2bd2503896988f39d952 | 1,986 | java | Java | src/main/java/gov/usgs/cida/pubs/domain/ContributorType.java | mbucknell/pubs-services | adcd23a34e91c92756cd38f3f4cf352d7080d1b0 | [
"CC0-1.0"
] | 4 | 2019-10-04T01:28:15.000Z | 2020-08-08T07:28:42.000Z | src/main/java/gov/usgs/cida/pubs/domain/ContributorType.java | mbucknell/pubs-services | adcd23a34e91c92756cd38f3f4cf352d7080d1b0 | [
"CC0-1.0"
] | 131 | 2019-07-31T13:21:53.000Z | 2021-08-03T10:37:39.000Z | src/main/java/gov/usgs/cida/pubs/domain/ContributorType.java | mbucknell/pubs-services | adcd23a34e91c92756cd38f3f4cf352d7080d1b0 | [
"CC0-1.0"
] | 7 | 2019-07-29T18:36:37.000Z | 2020-11-13T15:12:41.000Z | 29.641791 | 86 | 0.774924 | 998,710 | package gov.usgs.cida.pubs.domain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import gov.usgs.cida.pubs.dao.intfc.IDao;
import gov.usgs.cida.pubs.domain.intfc.ILookup;
import io.swagger.v3.oas.annotations.media.Schema;
@Component
public class ContributorType extends BaseDomain<ContributorType> implements ILookup {
public static final Integer AUTHORS = 1;
public static final Integer EDITORS = 2;
public static final Integer COMPILERS = 3;
public static String AUTHOR_KEY = "authors";
public static String EDITOR_KEY = "editors";
public static String COMPILER_KEY = "compilers";
private static IDao<ContributorType> contributorTypeDao;
private String text;
@Override
public String getText() {
return text;
}
public void setText(final String inText) {
text = inText;
}
public static IDao<ContributorType> getDao() {
return contributorTypeDao;
}
@Autowired
@Qualifier("contributorTypeDao")
@Schema(hidden = true)
public void setContributorTypeDao(final IDao<ContributorType> inContributorTypeDao) {
contributorTypeDao = inContributorTypeDao;
}
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
//This code will not be executed until the entire Spring Context is loaded.
try {
AUTHOR_KEY = contributorTypeDao.getById(AUTHORS).getText().toLowerCase();
} catch (NullPointerException e) {
//Leave the default value alone.
}
try {
EDITOR_KEY = contributorTypeDao.getById(EDITORS).getText().toLowerCase();
} catch (NullPointerException e) {
//Leave the default value alone.
}
try {
COMPILER_KEY = contributorTypeDao.getById(COMPILERS).getText().toLowerCase();
} catch (NullPointerException e) {
//Leave the default value alone.
}
}
}
|
923921c5de97fa053ab485747cf4ddbb889ccf22 | 361 | java | Java | src/main/java/edu/fiuba/algo3/infraestructura/IRandomizador.java | szwtomas/algo3_tp2_TEG | b907f29e7fde8f00d3bc9f697a8b3d8e68e51fbd | [
"MIT"
] | null | null | null | src/main/java/edu/fiuba/algo3/infraestructura/IRandomizador.java | szwtomas/algo3_tp2_TEG | b907f29e7fde8f00d3bc9f697a8b3d8e68e51fbd | [
"MIT"
] | null | null | null | src/main/java/edu/fiuba/algo3/infraestructura/IRandomizador.java | szwtomas/algo3_tp2_TEG | b907f29e7fde8f00d3bc9f697a8b3d8e68e51fbd | [
"MIT"
] | null | null | null | 24.066667 | 53 | 0.775623 | 998,711 | package edu.fiuba.algo3.infraestructura;
import java.util.ArrayList;
import java.util.Collections;
import edu.fiuba.algo3.modelo.general.*;
import edu.fiuba.algo3.modelo.jugador.Objetivo;
public interface IRandomizador {
int generar(int low, int high);
void shuffle(ArrayList<Tarjeta> lista);
void mezclarObjetivos(ArrayList<Objetivo> lista);
}
|
923922c3d5b4ff34b20e6952a281a644c0c1ec43 | 901 | java | Java | src/java/dskt/model/Carrinho.java | hebertpazian/debug-skate-app | 2c1f324ecb59d5746ba8ecc134d2fe85e0c8cbf6 | [
"MIT"
] | null | null | null | src/java/dskt/model/Carrinho.java | hebertpazian/debug-skate-app | 2c1f324ecb59d5746ba8ecc134d2fe85e0c8cbf6 | [
"MIT"
] | null | null | null | src/java/dskt/model/Carrinho.java | hebertpazian/debug-skate-app | 2c1f324ecb59d5746ba8ecc134d2fe85e0c8cbf6 | [
"MIT"
] | 1 | 2020-11-06T12:55:01.000Z | 2020-11-06T12:55:01.000Z | 18.387755 | 48 | 0.601554 | 998,712 | package dskt.model;
import java.util.ArrayList;
import java.util.List;
public class Carrinho {
private Integer id;
private List<Skate> skates;
//MÉTODOs CONSTRUTORES
public Carrinho() {
this.skates = new ArrayList<Skate>();
}
public Skate getSkatePosition(Integer pos) {
return this.getSkates().get(pos);
}
public void setSkatePosition(Skate skate) {
this.skates.set(skate.getId(), skate);
}
public void addSkate(Skate skate) {
this.skates.add(skate);
}
public void removeSkate(Skate skate) {
this.skates.remove(skate);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Skate> getSkates() {
return skates;
}
public void setSkates(List<Skate> skates) {
this.skates = skates;
}
}
|
92392309b793273efddc6d37fa8cb3e13672aa5b | 457 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/TestBase.java | Yeskella/java_pft | 9e90279ff47768ed31c39bef250c97dbca22ff87 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/TestBase.java | Yeskella/java_pft | 9e90279ff47768ed31c39bef250c97dbca22ff87 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/TestBase.java | Yeskella/java_pft | 9e90279ff47768ed31c39bef250c97dbca22ff87 | [
"Apache-2.0"
] | null | null | null | 17.576923 | 83 | 0.746171 | 998,713 | package ru.stqa.pft.addressbook.tests;
import org.openqa.selenium.remote.BrowserType;
import org.testng.annotations.*;
import ru.stqa.pft.addressbook.appmanager.ApplicationManager;
public class TestBase {
public final ApplicationManager app = new ApplicationManager(BrowserType.CHROME);
@BeforeMethod
public void setUp() throws Exception {
app.init();
}
@AfterMethod
public void tearDown() throws Exception {
app.stop();
}
}
|
923923dd5706c5006ee02e47c759f20c3f58b4b5 | 1,590 | java | Java | src/main/java/com/analytics/controller/AnalyticsController.java | TuranSoyuer/perfanalytics-api | 23d23bab4ce4c322c61134dfcc857cdc34e7fbac | [
"MIT"
] | null | null | null | src/main/java/com/analytics/controller/AnalyticsController.java | TuranSoyuer/perfanalytics-api | 23d23bab4ce4c322c61134dfcc857cdc34e7fbac | [
"MIT"
] | null | null | null | src/main/java/com/analytics/controller/AnalyticsController.java | TuranSoyuer/perfanalytics-api | 23d23bab4ce4c322c61134dfcc857cdc34e7fbac | [
"MIT"
] | null | null | null | 36.136364 | 98 | 0.784906 | 998,714 | package com.analytics.controller;
import com.analytics.controller.input.AnalyticInput;
import com.analytics.repository.AnalyticItem;
import com.analytics.service.AnalyticsService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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 java.util.List;
@Log
@RestController
@RequestMapping("/api")
public class AnalyticsController {
private final AnalyticsService analyticsService;
@Autowired
public AnalyticsController(AnalyticsService analyticsService) {
this.analyticsService = analyticsService;
}
@PostMapping("/analytics")
public ResponseEntity<AnalyticItem> createAnalytic(@RequestBody AnalyticInput analyticInput) {
AnalyticItem item = this.analyticsService.createAnalytic(analyticInput);
return ResponseEntity.ok(item);
}
@GetMapping("/analytics")
public ResponseEntity<List<AnalyticItem>> getAnalytic(
@RequestParam(value = "startDate", required = false) Long startDate,
@RequestParam(value = "endDate", required = false) Long endDate) {
return ResponseEntity.ok(analyticsService.getAnalytics(startDate, endDate));
}
}
|
9239247a2cb9e7ff8603b7b994262fca53827c2e | 6,286 | java | Java | src/main/java/walkingkooka/tree/search/SearchQuery.java | mP1/walkingkooka-tree-search | f6ed015d162be6cd0ac6c3c27faf94a98b2f162a | [
"Apache-2.0"
] | null | null | null | src/main/java/walkingkooka/tree/search/SearchQuery.java | mP1/walkingkooka-tree-search | f6ed015d162be6cd0ac6c3c27faf94a98b2f162a | [
"Apache-2.0"
] | 3 | 2019-10-29T00:27:53.000Z | 2020-11-04T23:31:36.000Z | src/main/java/walkingkooka/tree/search/SearchQuery.java | mP1/walkingkooka-tree-search | f6ed015d162be6cd0ac6c3c27faf94a98b2f162a | [
"Apache-2.0"
] | null | null | null | 39.043478 | 203 | 0.746102 | 998,715 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package walkingkooka.tree.search;
import walkingkooka.Cast;
import walkingkooka.text.CaseSensitivity;
import java.util.Objects;
/**
* A query that may be used to search {@link SearchNode} for matches.
*/
public abstract class SearchQuery {
private static SearchQueryParentBinaryAnd and(final SearchQuery left,
final SearchQuery right) {
return SearchQueryParentBinaryAnd.with(left, right);
}
/**
* {@see SearchQueryLeafAttributeValueContains}
*/
static SearchQueryLeafAttributeValueContains attributeValueContains(final TextSearchQueryValue value, final SearchNodeAttributeName attributeName, final CaseSensitivity caseSensitivity) {
return SearchQueryLeafAttributeValueContains.with(value, attributeName, caseSensitivity);
}
/**
* {@see SearchQueryLeafAttributeValueDoesntContains}
*/
static SearchQueryLeafAttributeValueDoesntContains attributeValueDoesntContains(final TextSearchQueryValue value, final SearchNodeAttributeName attributeName, final CaseSensitivity caseSensitivity) {
return SearchQueryLeafAttributeValueDoesntContains.with(value, attributeName, caseSensitivity);
}
/**
* {@see SearchQueryLeafAttributeValueEquals}
*/
static SearchQueryLeafAttributeValueEquals attributeValueEquals(final TextSearchQueryValue value, final SearchNodeAttributeName attributeName, final CaseSensitivity caseSensitivity) {
return SearchQueryLeafAttributeValueEquals.with(value, attributeName, caseSensitivity);
}
/**
* {@see SearchQueryLeafAttributeValueNotEquals}
*/
static SearchQueryLeafAttributeValueNotEquals attributeValueNotEquals(final TextSearchQueryValue value, final SearchNodeAttributeName attributeName, final CaseSensitivity caseSensitivity) {
return SearchQueryLeafAttributeValueNotEquals.with(value, attributeName, caseSensitivity);
}
static SearchQueryLeafValueContains contains(final TextSearchQueryValue value, final CaseSensitivity caseSensitivity) {
return SearchQueryLeafValueContains.with(value, caseSensitivity);
}
static SearchQueryLeafValueEquals equalsQuery(final SearchQueryValue value, final SearchQueryTester tester) {
return SearchQueryLeafValueEquals.with(value, tester);
}
static SearchQueryLeafValueGreaterThanEquals greaterThanEquals(final SearchQueryValue value, final SearchQueryTester tester) {
return SearchQueryLeafValueGreaterThanEquals.with(value, tester);
}
static SearchQueryLeafValueGreaterThan greaterThan(final SearchQueryValue value, final SearchQueryTester tester) {
return SearchQueryLeafValueGreaterThan.with(value, tester);
}
static SearchQueryLeafValueLessThanEquals lessThanEquals(final SearchQueryValue value, final SearchQueryTester tester) {
return SearchQueryLeafValueLessThanEquals.with(value, tester);
}
static SearchQueryLeafValueLessThan lessThan(final SearchQueryValue value, final SearchQueryTester tester) {
return SearchQueryLeafValueLessThan.with(value, tester);
}
static SearchQueryParentUnaryNot not(final SearchQuery query) {
return SearchQueryParentUnaryNot.with(query);
}
static SearchQueryLeafValueNotEquals notEquals(final SearchQueryValue value, final SearchQueryTester tester) {
return SearchQueryLeafValueNotEquals.with(value, tester);
}
private static SearchQueryParentBinaryOr or(final SearchQuery left,
final SearchQuery right) {
return SearchQueryParentBinaryOr.with(left, right);
}
/**
* Package private to limit sub classing.
*/
SearchQuery() {
super();
}
public final SearchQuery and(final SearchQuery query) {
return and(this, query);
}
public final SearchQuery or(final SearchQuery query) {
return or(this, query);
}
public abstract SearchQuery not();
/**
* Searches the nodes starting at {@link SearchNode} using this query returning a new nodes with {@link SelectSearchNode} to select matches.
*/
public final SearchNode select(final SearchNode node) {
Objects.requireNonNull(node, "node");
final SearchQueryContext context = SearchQueryContext2.with(node);
node.select(this, context);
return context.finish();
}
abstract void visit(final BigDecimalSearchNode node, final SearchQueryContext context);
abstract void visit(final BigIntegerSearchNode node, final SearchQueryContext context);
abstract void visit(final DoubleSearchNode node, final SearchQueryContext context);
abstract void visit(final LocalDateSearchNode node, final SearchQueryContext context);
abstract void visit(final LocalDateTimeSearchNode node, final SearchQueryContext context);
abstract void visit(final LocalTimeSearchNode node, final SearchQueryContext context);
abstract void visit(final LongSearchNode node, final SearchQueryContext context);
abstract void visit(final MetaSearchNode node, final SearchQueryContext context);
abstract void visit(final TextSearchNode node, final SearchQueryContext context);
@Override
abstract public int hashCode();
@Override
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
public final boolean equals(final Object other) {
return this == other ||
this.canBeEqual(other) &&
this.equals0(Cast.to(other));
}
abstract boolean canBeEqual(final Object other);
abstract boolean equals0(final SearchQuery other);
}
|
9239256d1a06dd541da566442eb809a7784e8c4b | 2,305 | java | Java | Presentation/src/org/joeffice/presentation/actions/PreviousSlideAction.java | japplis/Joeffice | b34bcbf3f51b1bc4a70a8e29d1067b33ef2d4c3c | [
"Apache-2.0"
] | 5 | 2021-04-10T16:10:19.000Z | 2022-01-11T23:57:23.000Z | Presentation/src/org/joeffice/presentation/actions/PreviousSlideAction.java | japplis/Joeffice | b34bcbf3f51b1bc4a70a8e29d1067b33ef2d4c3c | [
"Apache-2.0"
] | null | null | null | Presentation/src/org/joeffice/presentation/actions/PreviousSlideAction.java | japplis/Joeffice | b34bcbf3f51b1bc4a70a8e29d1067b33ef2d4c3c | [
"Apache-2.0"
] | 6 | 2021-04-02T15:46:33.000Z | 2022-01-15T10:15:10.000Z | 34.402985 | 115 | 0.722777 | 998,716 | /*
* Copyright 2013 Japplis.
*
* 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.joeffice.presentation.actions;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.joeffice.desktop.ui.OfficeTopComponent;
import org.joeffice.presentation.SlidesTopComponent;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
/**
* Moves to the previous slides.
* Beep if the current slides is the first slide.
*
* @author Anthony Goubard - Japplis
*/
@ActionID(
category = "View/Office/Presentation",
id = "org.joeffice.presentation.actions.PreviousSlideAction")
@ActionRegistration(
iconBase = "org/joeffice/presentation/actions/arrow_left.png",
displayName = "#CTL_PreviousSlideAction")
@ActionReferences(value = {
@ActionReference(path = "Office/Presentation/Toolbar", position = 100),
@ActionReference(path = "Shortcuts", name = "Page_Up")
})
@Messages("CTL_PreviousSlideAction=Previous Slide")
public class PreviousSlideAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
previousSlide();
}
public void previousSlide() {
SlidesTopComponent currentTopComponent = OfficeTopComponent.getSelectedComponent(SlidesTopComponent.class);
if (currentTopComponent != null) {
int currentSlide = currentTopComponent.getSelectedSlideIndex();
if (currentSlide > 0) {
currentTopComponent.setSelectedSlideIndex(currentSlide - 1);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
|
923926f49820d3332d8e8ee592e93f975882b03d | 378 | java | Java | integration-tests/main/src/test/java/io/quarkiverse/googlecloudservices/it/NativeGoogleServicesResourcesIT.java | maxandersen/quarkus-google-cloud-services | a7958fdb04a5740b6394d50608c53eb44e9305d3 | [
"Apache-2.0"
] | 311 | 2021-01-19T08:31:25.000Z | 2022-03-31T05:03:25.000Z | integration-tests/main/src/test/java/io/quarkiverse/googlecloudservices/it/NativeGoogleServicesResourcesIT.java | maxandersen/quarkus-google-cloud-services | a7958fdb04a5740b6394d50608c53eb44e9305d3 | [
"Apache-2.0"
] | 92 | 2021-01-23T19:48:44.000Z | 2022-03-31T05:20:07.000Z | integration-tests/main/src/test/java/io/quarkiverse/googlecloudservices/it/NativeGoogleServicesResourcesIT.java | maxandersen/quarkus-google-cloud-services | a7958fdb04a5740b6394d50608c53eb44e9305d3 | [
"Apache-2.0"
] | 9 | 2021-01-24T22:37:39.000Z | 2022-01-09T08:27:55.000Z | 31.5 | 82 | 0.820106 | 998,717 | package io.quarkiverse.googlecloudservices.it;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import io.quarkus.test.junit.NativeImageTest;
@NativeImageTest
@EnabledIfSystemProperty(named = "gcloud.test", matches = "true")
public class NativeGoogleServicesResourcesIT extends GoogleServicesResourcesTest {
// Execute the same tests but in native mode.
}
|
9239276025893c160ccd5c87d70a6a2d18d66c66 | 1,288 | java | Java | test/src/test/java/hudson/ExceptionTest.java | Sayanta66/jenkins | b5e5d0e8eb18cff50d82daa12562648391f705d2 | [
"MIT"
] | 17,275 | 2015-01-01T21:08:25.000Z | 2022-03-31T17:26:18.000Z | test/src/test/java/hudson/ExceptionTest.java | Sayanta66/jenkins | b5e5d0e8eb18cff50d82daa12562648391f705d2 | [
"MIT"
] | 4,230 | 2015-01-01T14:07:24.000Z | 2022-03-31T22:58:42.000Z | test/src/test/java/hudson/ExceptionTest.java | Sayanta66/jenkins | b5e5d0e8eb18cff50d82daa12562648391f705d2 | [
"MIT"
] | 7,471 | 2015-01-01T03:11:41.000Z | 2022-03-31T21:01:51.000Z | 29.953488 | 106 | 0.723602 | 998,718 | package hudson;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClientUtil;
import hudson.model.InvisibleAction;
import hudson.model.RootAction;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.TestExtension;
/**
* @author Kohsuke Kawaguchi
*/
public class ExceptionTest {
@Rule public JenkinsRule j = new JenkinsRule();
/**
* Makes sure that an AJAX handler error results in a fatal problem in the unit test.
*/
@Test
public void testAjaxError() throws Exception {
WebClient webClient = j.createWebClient();
WebClientUtil.ExceptionListener exceptionListener = WebClientUtil.addExceptionListener(webClient);
webClient.goTo("self/ajaxError");
// Check for the error.
ScriptException e = exceptionListener.getExpectedScriptException();
Assert.assertTrue(e.getMessage().contains("simulated error"));
}
@TestExtension
public static final class RootActionImpl extends InvisibleAction implements RootAction {
@Override
public String getUrlName() {
return "self";
}
}
}
|
923927724b0c84334df776a12dc7f9bdec9c89b6 | 10,059 | java | Java | httpclient/HTTPClient.java | amravazzi/HTTPClient | 0eb402898c35b7bbe9b7eac92cdd29df3299bce7 | [
"MIT"
] | null | null | null | httpclient/HTTPClient.java | amravazzi/HTTPClient | 0eb402898c35b7bbe9b7eac92cdd29df3299bce7 | [
"MIT"
] | null | null | null | httpclient/HTTPClient.java | amravazzi/HTTPClient | 0eb402898c35b7bbe9b7eac92cdd29df3299bce7 | [
"MIT"
] | null | null | null | 30.855828 | 101 | 0.464161 | 998,719 | package httpclient;
/**
*
* @author amravazzi
*/
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HTTPClient
{
private final String USER_AGENT = "Java";
public static void main(String[] args) throws Exception
{
HTTPClient http = new HTTPClient();
String method = args[0];
String url = args[1];
if ("HEAD".equals(method))
{
http.headMethod(url);
}
else if ("GET".equals(method))
{
http.getMethod(url);
}
else if ("PUT".equals(method))
{
http.putMethod(url);
}
else if ("POST".equals(method))
{
http.postMethod(url);
}
else if ("DELETE".equals(method))
{
http.deleteMethod(url);
}
else if ("TRACE".equals(method))
{
http.traceMethod(url);
} else {
System.out.println("Invalid argument");
}
}
// HTTP HEAD request
private void headMethod(String url) throws Exception
{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
// Set default to method
conn.setRequestMethod("HEAD");
//add request header
conn.setRequestProperty("User-Agent", USER_AGENT);
int i = 0;
while(conn.getHeaderField(i) != null)
{
if(conn.getHeaderFieldKey(i) == null)
{
System.out.println(conn.getHeaderField(i));
} else {
System.out.println(conn.getHeaderFieldKey(i)+" : "+conn.getHeaderField(i));
}
if(conn.getHeaderField(i+1) == null) System.out.println(" ");
i++;
}
}
// HTTP GET request
private void getMethod(String url) throws Exception
{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
// Set default method
conn.setRequestMethod("GET");
//add request header
conn.setRequestProperty("User-Agent", USER_AGENT);
int i = 0;
while(conn.getHeaderField(i) != null)
{
if(conn.getHeaderFieldKey(i) == null)
{
System.out.println(conn.getHeaderField(i));
} else {
System.out.println(conn.getHeaderFieldKey(i)+" : "+conn.getHeaderField(i));
}
if(conn.getHeaderField(i+1) == null) System.out.println(" ");
i++;
}
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(" ");
}
}
// HTTP POST request
private void postMethod(String url) throws Exception
{
URL obj = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
// Set default method
conn.setRequestMethod("POST");
//add request header
conn.setRequestProperty("User-Agent", USER_AGENT);
// Send post request
conn.setDoOutput(true);
DataOutputStream dout = new DataOutputStream(conn.getOutputStream());
dout.writeBytes("some parameter");
dout.flush();
dout.close();
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(" ");
}
}
// HTTP PUT request
private void putMethod(String url) throws Exception
{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
// Set default method
conn.setRequestMethod("PUT");
//add request header
conn.setRequestProperty("User-Agent", USER_AGENT);
try {
// Write data
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write("TESTE CONTENT");
// Print Header
int i = 0;
while(conn.getHeaderField(i) != null)
{
if(conn.getHeaderFieldKey(i) == null)
{
System.out.println(conn.getHeaderField(i));
} else {
System.out.println(conn.getHeaderFieldKey(i)+" : "+conn.getHeaderField(i));
}
if(conn.getHeaderField(i+1) == null) System.out.println(" ");
i++;
}
// Print body
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getCause());
}
}
// HTTP DELETE request
private void deleteMethod(String url) throws Exception
{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
// Set default method
conn.setRequestMethod("DELETE");
//add request header
conn.setRequestProperty("User-Agent", USER_AGENT);
try {
// Print Header
int i = 0;
while(conn.getHeaderField(i) != null)
{
if(conn.getHeaderFieldKey(i) == null)
{
System.out.println(conn.getHeaderField(i));
} else {
System.out.println(conn.getHeaderFieldKey(i)+" : "+conn.getHeaderField(i));
}
if(conn.getHeaderField(i+1) == null) System.out.println(" ");
i++;
}
// Print body
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getCause());
}
}
// HTTP TRACE request
private void traceMethod(String url) throws Exception
{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
// Set default method
conn.setRequestMethod("TRACE");
//add request header
conn.setRequestProperty("User-Agent", USER_AGENT);
try {
// Print Header
int i = 0;
while(conn.getHeaderField(i) != null)
{
if(conn.getHeaderFieldKey(i) == null)
{
System.out.println(conn.getHeaderField(i));
} else {
System.out.println(conn.getHeaderFieldKey(i)+" : "+conn.getHeaderField(i));
}
if(conn.getHeaderField(i+1) == null) System.out.println(" ");
i++;
}
// Print body
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getCause());
}
}
}
|
92392785c9015900595567e8030d204135b9e838 | 2,070 | java | Java | core/src/com/projet5001/game/listeners/ContainerListener.java | macmata/projet5001-java | 34e040bde7240d0e40549e7d3f4d09d5a4c99781 | [
"MIT"
] | 1 | 2017-04-20T21:34:29.000Z | 2017-04-20T21:34:29.000Z | core/src/com/projet5001/game/listeners/ContainerListener.java | macmata/projet5001-java | 34e040bde7240d0e40549e7d3f4d09d5a4c99781 | [
"MIT"
] | 2 | 2016-03-08T23:33:30.000Z | 2016-03-08T23:33:35.000Z | core/src/com/projet5001/game/listeners/ContainerListener.java | macmata/projet5001-java | 34e040bde7240d0e40549e7d3f4d09d5a4c99781 | [
"MIT"
] | null | null | null | 33.387097 | 81 | 0.708213 | 998,720 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alexandre Leblanc
*
* 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 com.projet5001.game.listeners;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.projet5001.game.events.ActorEvent;
/**
* Permet d'implanter les nouveau type de eventListener
*/
public class ContainerListener implements EventListener {
ActorEvent actorEvent;
@Override
public boolean handle(Event e) {
if (!(e instanceof ActorEvent)) {
return false;
}
actorEvent = (ActorEvent) e;
switch (actorEvent.getType()) {
case SimpleContainer:
return simpleContainer(actorEvent);
case collision:
return collision(actorEvent);
}
return false;
}
public boolean simpleContainer(ActorEvent actorEvent) {
return false;
}
public boolean collision(ActorEvent actorEvent) {
return false;
}
}
|
923927a5a70a032cf00e76a7e7a1e1233d772f1d | 8,005 | java | Java | oak-core/src/main/java/org/apache/jackrabbit/oak/core/SecureNodeState.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 288 | 2015-01-11T04:09:03.000Z | 2022-03-28T22:20:09.000Z | oak-core/src/main/java/org/apache/jackrabbit/oak/core/SecureNodeState.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 154 | 2016-10-30T11:31:04.000Z | 2022-03-31T14:20:52.000Z | oak-core/src/main/java/org/apache/jackrabbit/oak/core/SecureNodeState.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 405 | 2015-01-15T16:15:56.000Z | 2022-03-24T08:27:08.000Z | 37.232558 | 94 | 0.6406 | 998,721 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.core;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.plugins.memory.MemoryChildNodeEntry;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeBuilder;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.TreePermission;
import org.apache.jackrabbit.oak.spi.state.AbstractNodeState;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static java.util.Collections.emptyList;
class SecureNodeState extends AbstractNodeState {
/**
* Underlying node state.
*/
private final NodeState state;
/**
* Tree permissions of this subtree.
*/
private final TreePermission treePermission;
private long childNodeCount = -1;
private long propertyCount = -1;
SecureNodeState(@NotNull NodeState state, @NotNull TreePermission treePermission) {
this.state = checkNotNull(state);
this.treePermission = checkNotNull(treePermission);
}
@Override
public boolean exists() {
return treePermission.canRead();
}
@Override @Nullable
public PropertyState getProperty(@NotNull String name) {
PropertyState property = state.getProperty(name);
if (property != null && treePermission.canRead(property)) {
return property;
} else {
return null;
}
}
@Override
public synchronized long getPropertyCount() {
if (propertyCount == -1) {
if (treePermission.canReadProperties()) {
propertyCount = state.getPropertyCount();
} else {
propertyCount = count(filter(
state.getProperties(),
new ReadablePropertyPredicate()));
}
}
return propertyCount;
}
@Override @NotNull
public Iterable<? extends PropertyState> getProperties() {
if (treePermission.canReadProperties()) {
return state.getProperties();
} else {
return filter(
state.getProperties(),
new ReadablePropertyPredicate());
}
}
@Override
public boolean hasChildNode(@NotNull String name) {
if (!state.hasChildNode(name)) {
return false;
} else if (treePermission.canReadAll()) {
return true;
} else {
NodeState child = state.getChildNode(name);
return treePermission.getChildPermission(name, child).canRead();
}
}
@NotNull
@Override
public NodeState getChildNode(@NotNull String name) {
NodeState child = state.getChildNode(name);
if (child.exists() && !treePermission.canReadAll()) {
ChildNodeEntry entry = new MemoryChildNodeEntry(name, child);
return new WrapChildEntryFunction().apply(entry).getNodeState();
} else {
return child;
}
}
@Override
public synchronized long getChildNodeCount(long max) {
if (childNodeCount == -1) {
long count;
if (treePermission.canReadAll()) {
count = state.getChildNodeCount(max);
} else {
count = super.getChildNodeCount(max);
}
if (count == Long.MAX_VALUE) {
return count;
}
childNodeCount = count;
}
return childNodeCount;
}
@Override @NotNull
public Iterable<? extends ChildNodeEntry> getChildNodeEntries() {
if (treePermission.canReadAll()) {
// everything is readable including ac-content -> no secure wrapper needed
return state.getChildNodeEntries();
} else if (treePermission.canRead()) {
Iterable<ChildNodeEntry> readable = transform(
state.getChildNodeEntries(),
new WrapChildEntryFunction());
return filter(readable, new IterableNodePredicate());
} else {
return emptyList();
}
}
@Override @NotNull
public NodeBuilder builder() {
return new MemoryNodeBuilder(this);
}
//------------------------------------------------------< inner classes >---
/**
* Predicate for testing whether a given property is readable.
*/
private class ReadablePropertyPredicate implements Predicate<PropertyState> {
@Override
public boolean apply(@Nullable PropertyState property) {
return property != null && treePermission.canRead(property);
}
}
/**
* Predicate for testing whether the node state in a child node entry is iterable.
*/
private static class IterableNodePredicate implements Predicate<ChildNodeEntry> {
@Override
public boolean apply(@Nullable ChildNodeEntry input) {
return input != null && input.getNodeState().exists();
}
}
/**
* Function that that adds a security wrapper to node states from
* in child node entries. The {@link IterableNodePredicate} predicate should be
* used on the result to filter out non-existing/iterable child nodes.
* <p>
* Note that the SecureNodeState wrapper is needed only when the child
* or any of its descendants has read access restrictions. Otherwise
* we can optimize access by skipping the security wrapper entirely.
*/
private class WrapChildEntryFunction implements Function<ChildNodeEntry, ChildNodeEntry> {
@NotNull
@Override
public ChildNodeEntry apply(@NotNull ChildNodeEntry input) {
String name = input.getName();
NodeState child = input.getNodeState();
TreePermission childContext = treePermission.getChildPermission(name, child);
SecureNodeState secureChild = new SecureNodeState(child, childContext);
if (child.getChildNodeCount(1) == 0
&& secureChild.treePermission.canRead()
&& secureChild.treePermission.canReadProperties()) {
// Since this is an accessible leaf node whose all properties
// are readable, we don't need the SecureNodeState wrapper
// TODO: A further optimization would be to return the raw
// underlying node state even for non-leaf nodes if we can
// tell in advance that the full subtree is readable. Then
// we also wouldn't need the above getChildNodeCount() call
// that's somewhat expensive on the DocumentMK.
return input;
} else {
return new MemoryChildNodeEntry(name, secureChild);
}
}
}
}
|
923927b5fe5002fea41f8d67812e7dcee86e4c0c | 503 | java | Java | mobile_app1/module205/src/main/java/module205packageJava0/Foo24.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 70 | 2021-01-22T16:48:06.000Z | 2022-02-16T10:37:33.000Z | mobile_app1/module205/src/main/java/module205packageJava0/Foo24.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 16 | 2021-01-22T20:52:52.000Z | 2021-08-09T17:51:24.000Z | mobile_app1/module205/src/main/java/module205packageJava0/Foo24.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 5 | 2021-01-26T13:53:49.000Z | 2021-08-11T20:10:57.000Z | 10.934783 | 45 | 0.560636 | 998,722 | package module205packageJava0;
import java.lang.Integer;
public class Foo24 {
Integer int0;
Integer int1;
Integer int2;
Integer int3;
public void foo0() {
new module205packageJava0.Foo23().foo7();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
public void foo6() {
foo5();
}
public void foo7() {
foo6();
}
}
|
92392a318caa22fe8fd09f0b26a47266da07ad55 | 1,706 | java | Java | src/Player.java | PeaTea/Evade | f31c2854b7dee31b85293e468d8ac69e36526018 | [
"MIT"
] | 1 | 2018-05-13T12:42:28.000Z | 2018-05-13T12:42:28.000Z | src/Player.java | peterkain/Evade | f31c2854b7dee31b85293e468d8ac69e36526018 | [
"MIT"
] | null | null | null | src/Player.java | peterkain/Evade | f31c2854b7dee31b85293e468d8ac69e36526018 | [
"MIT"
] | null | null | null | 24.371429 | 119 | 0.583236 | 998,723 | package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class Player extends GameObject {
Handler handler;
public Player(int x, int y, ID id, Handler handler) {
super(x, y, id);
this.handler = handler;
}
@Override
public void tick() {
x += vx;
y += vy;
x = Game.clamp(x, 0, Game.WIDTH - 38);
y = Game.clamp(y, 0, Game.HEIGHT - 60);
handler.addObject(new TrailFade(x, y, 32, 32, 0.2f, ID.Player, Color.BLACK, handler));
collide();
}
private void collide() {
for(GameObject object : handler.objects) {
if(object.getId() == ID.BasicEnemy || object.getId() == ID.HorizontalEnemy || object.getId() == ID.VerticalEnemy ||
object.getId() == ID.Pursuer) {
if(getBounds().intersects(object.getBounds())) {
HUD.HEALTH -= 2;
}
} if(object.getId() == ID.Boss1) {
if(getBounds().intersects(object.getBounds())) {
HUD.HEALTH -= 9999;
}
} if(object.getId() == ID.Boss1Bullet) {
if(getBounds().intersects(object.getBounds())) {
HUD.HEALTH -= 5;
}
} if(object.getId() == ID.Boss1LaserBeam) {
if(getBounds().intersects(object.getBounds())) {
HUD.HEALTH -= 30;
}
} if(object.getId() == ID.Wall) {
x = Game.clamp(x, 0, Game.WIDTH - Game.WIDTH / 5 + 1);
} if(object.getId() == ID.Boss2) {
if(getBounds().intersects(object.getBounds())) {
HUD.HEALTH -= 40;
}
}
}
}
@Override
public void render(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect((int)x, (int)y, 32, 32);
}
@Override
public Rectangle getBounds() {
return new Rectangle((int)x, (int)y, 32, 32);
}
}
|
92392a71396b16876dcf872156e2920ea9a5db02 | 498 | java | Java | shared/validation/src/main/java/com/eshop/validation/CardExpirationDateValidator.java | velinovskav/e-shop-1 | 16646131ab3a4d12898d7a5170e6f0e1ab65c2b7 | [
"MIT"
] | 31 | 2021-08-17T09:09:22.000Z | 2022-03-26T00:36:15.000Z | shared/validation/src/main/java/com/eshop/validation/CardExpirationDateValidator.java | velinovskav/e-shop-1 | 16646131ab3a4d12898d7a5170e6f0e1ab65c2b7 | [
"MIT"
] | 1 | 2022-01-04T08:13:43.000Z | 2022-01-04T19:36:23.000Z | shared/validation/src/main/java/com/eshop/validation/CardExpirationDateValidator.java | velinovskav/e-shop-1 | 16646131ab3a4d12898d7a5170e6f0e1ab65c2b7 | [
"MIT"
] | 18 | 2021-08-06T06:43:32.000Z | 2022-02-25T17:26:53.000Z | 31.125 | 104 | 0.831325 | 998,724 | package com.eshop.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;
import static java.util.Objects.nonNull;
public class CardExpirationDateValidator implements ConstraintValidator<CardExpirationDate, LocalDate> {
@Override
public boolean isValid(LocalDate expiration, ConstraintValidatorContext constraintValidatorContext) {
return nonNull(expiration) && expiration.isAfter(LocalDate.now());
}
}
|
92392b27d9f9eb408964285f198b11af2012cc3e | 431 | java | Java | src/main/java/be/feelio/mollie/data/common/Locale.java | dhouthoo/mollie | db513b4b7a793c1827b8f938951fe3a1c61681af | [
"Apache-2.0"
] | null | null | null | src/main/java/be/feelio/mollie/data/common/Locale.java | dhouthoo/mollie | db513b4b7a793c1827b8f938951fe3a1c61681af | [
"Apache-2.0"
] | null | null | null | src/main/java/be/feelio/mollie/data/common/Locale.java | dhouthoo/mollie | db513b4b7a793c1827b8f938951fe3a1c61681af | [
"Apache-2.0"
] | null | null | null | 12.676471 | 50 | 0.563805 | 998,725 | package be.feelio.mollie.data.common;
import com.fasterxml.jackson.annotation.JsonValue;
public enum Locale {
en_US,
nl_NL,
nl_BE,
fr_FR,
fr_BE,
de_DE,
de_AT,
de_CH,
es_ES,
ca_ES,
pt_PT,
it_IT,
nb_NO,
sv_SE,
fi_FI,
da_DK,
is_IS,
hu_HU,
pl_PL,
lv_LV,
lt_LT;
@JsonValue
public String getJsonValue() {
return this.name();
}
}
|
92392b4641c325e449ce13740ff564d62ff831bb | 2,681 | java | Java | code/languages/org.iets3.opensource/languages/org.iets3.req.core/source_gen/org/iets3/req/core/constraints/ConstraintsAspectDescriptor.java | levilucio/CoolingControllerReqsDash | 1fc970683191f44861bbeeaa8b3766d87b01f576 | [
"Apache-2.0"
] | null | null | null | code/languages/org.iets3.opensource/languages/org.iets3.req.core/source_gen/org/iets3/req/core/constraints/ConstraintsAspectDescriptor.java | levilucio/CoolingControllerReqsDash | 1fc970683191f44861bbeeaa8b3766d87b01f576 | [
"Apache-2.0"
] | null | null | null | code/languages/org.iets3.opensource/languages/org.iets3.req.core/source_gen/org/iets3/req/core/constraints/ConstraintsAspectDescriptor.java | levilucio/CoolingControllerReqsDash | 1fc970683191f44861bbeeaa8b3766d87b01f576 | [
"Apache-2.0"
] | null | null | null | 41.246154 | 812 | 0.712794 | 998,726 | package org.iets3.req.core.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.BaseConstraintsAspectDescriptor;
import jetbrains.mps.smodel.runtime.ConstraintsDescriptor;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import java.util.Map;
import java.util.HashMap;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class ConstraintsAspectDescriptor extends BaseConstraintsAspectDescriptor {
public ConstraintsAspectDescriptor() {
}
@Override
public ConstraintsDescriptor getConstraints(SAbstractConcept concept) {
{
SAbstractConcept cncpt = concept;
Integer preIndex = indices_2qnle6_a0c.get(cncpt);
int switchIndex = (preIndex == null ? -1 : preIndex);
switch (switchIndex) {
case 0:
if (true) {
return new AbstractRequirement_Constraints();
}
break;
case 1:
if (true) {
return new DefaultRequirement_Constraints();
}
break;
case 2:
if (true) {
return new HeaderRequirement_Constraints();
}
break;
case 3:
if (true) {
return new ReqRef_Constraints();
}
break;
case 4:
if (true) {
return new RequirementsDocSection_Constraints();
}
break;
default:
// default
}
}
return new BaseConstraintsDescriptor(concept);
}
private static Map<SAbstractConcept, Integer> buildConceptIndices(SAbstractConcept... concepts) {
HashMap<SAbstractConcept, Integer> res = new HashMap<SAbstractConcept, Integer>();
int counter = 0;
for (SAbstractConcept c : concepts) {
res.put(c, counter++);
}
return res;
}
private static final Map<SAbstractConcept, Integer> indices_2qnle6_a0c = buildConceptIndices(MetaAdapterFactory.getConcept(0xa3c6f64241b744cbL, 0x951b463b8427a245L, 0x477d8ab2bc8195aeL, "org.iets3.req.core.structure.AbstractRequirement"), MetaAdapterFactory.getConcept(0xa3c6f64241b744cbL, 0x951b463b8427a245L, 0x477d8ab2bc8195b9L, "org.iets3.req.core.structure.DefaultRequirement"), MetaAdapterFactory.getConcept(0xa3c6f64241b744cbL, 0x951b463b8427a245L, 0x3ab49e14c25e58e6L, "org.iets3.req.core.structure.HeaderRequirement"), MetaAdapterFactory.getConcept(0xa3c6f64241b744cbL, 0x951b463b8427a245L, 0x5fd70b0af6e37818L, "org.iets3.req.core.structure.ReqRef"), MetaAdapterFactory.getConcept(0xa3c6f64241b744cbL, 0x951b463b8427a245L, 0x477d8ab2bc883be3L, "org.iets3.req.core.structure.RequirementsDocSection"));
}
|
92392d0607ff622aa56196310f10d13795af632d | 1,793 | java | Java | ifs-web-service/ifs-competition-mgt-service/src/main/java/org/innovateuk/ifs/management/competition/setup/application/populator/AbstractFormInputQuestionFormPopulator.java | tied/innovation-funding-service | ee7b5328faf4dec698874ab0920d434c40c53fcd | [
"MIT"
] | 40 | 2017-03-29T13:58:42.000Z | 2021-07-04T22:13:12.000Z | ifs-web-service/ifs-competition-mgt-service/src/main/java/org/innovateuk/ifs/management/competition/setup/application/populator/AbstractFormInputQuestionFormPopulator.java | tied/innovation-funding-service | ee7b5328faf4dec698874ab0920d434c40c53fcd | [
"MIT"
] | 19 | 2017-09-30T11:57:32.000Z | 2022-02-13T18:38:48.000Z | ifs-web-service/ifs-competition-mgt-service/src/main/java/org/innovateuk/ifs/management/competition/setup/application/populator/AbstractFormInputQuestionFormPopulator.java | tied/innovation-funding-service | ee7b5328faf4dec698874ab0920d434c40c53fcd | [
"MIT"
] | 20 | 2017-04-05T11:34:30.000Z | 2022-03-22T14:42:08.000Z | 47.184211 | 143 | 0.711656 | 998,727 | package org.innovateuk.ifs.management.competition.setup.application.populator;
import org.innovateuk.ifs.competition.resource.CompetitionSetupQuestionResource;
import org.innovateuk.ifs.form.resource.MultipleChoiceOptionResource;
import org.innovateuk.ifs.management.competition.setup.application.form.AbstractQuestionForm;
import org.innovateuk.ifs.management.competition.setup.application.form.AbstractQuestionForm.TypeOfQuestion;
/**
* Form populator for the application form competition setup section.
*/
public abstract class AbstractFormInputQuestionFormPopulator {
public void populateCommon(CompetitionSetupQuestionResource questionResource, AbstractQuestionForm competitionSetupForm) {
if (questionResource.getTextArea() != null && questionResource.getMultipleChoice() != null) {
competitionSetupForm.setTypeOfQuestion(questionResource.getTextArea() ? TypeOfQuestion.FREE_TEXT : TypeOfQuestion.MULTIPLE_CHOICE);
}
if (questionResource.getMultipleChoice() != null) {
if (questionResource.getChoices().size() == 0) {
questionResource.getChoices().add(new MultipleChoiceOptionResource());
}
if (questionResource.getChoices().size() == 1) {
questionResource.getChoices().add(new MultipleChoiceOptionResource());
}
}
if (questionResource.getNumberOfUploads() != null) {
if (questionResource.getNumberOfUploads() == 0) {
competitionSetupForm.setNumberOfUploads(0);
questionResource.setAppendix(false);
} else {
competitionSetupForm.setNumberOfUploads(questionResource.getNumberOfUploads());
questionResource.setAppendix(true);
}
}
}
}
|
92392d4c9a4ddb97e4a6bf33b33d3614b34caadb | 2,891 | java | Java | ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserSalaryServiceImpl.java | 12138-java/rouyi-springboot | 4b7de3ea5cde70c83557982c7f7da9bac22f479e | [
"MIT"
] | 2 | 2020-11-23T09:06:37.000Z | 2021-01-29T12:55:04.000Z | ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserSalaryServiceImpl.java | 12138-java/rouyi-springboot | 4b7de3ea5cde70c83557982c7f7da9bac22f479e | [
"MIT"
] | null | null | null | ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserSalaryServiceImpl.java | 12138-java/rouyi-springboot | 4b7de3ea5cde70c83557982c7f7da9bac22f479e | [
"MIT"
] | null | null | null | 28.91 | 92 | 0.764441 | 998,728 | package com.ruoyi.system.service.impl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserSalary;
import com.ruoyi.common.core.domain.entity.SysUserSalaryExample;
import com.ruoyi.common.core.domain.req.ReqUserSalary;
import com.ruoyi.common.core.domain.resp.RespUserSalary;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.mapper.SysUserSalaryMapper;
import com.ruoyi.system.service.ISysUserSalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @auther:caishihao
* @Creation time:2020/11/17 16:59
* @description:
*/
@Service
public class SysUserSalaryServiceImpl implements ISysUserSalaryService {
@Autowired
private SysUserSalaryMapper sysUserSalaryMapper;
public long countByExample(SysUserSalaryExample example) {
return sysUserSalaryMapper.countByExample(example);
}
public int deleteByExample(SysUserSalaryExample example) {
return sysUserSalaryMapper.deleteByExample(example);
}
public int deleteByPrimaryKey(Long id) {
return sysUserSalaryMapper.deleteByPrimaryKey(id);
}
public int insert(SysUserSalary record) {
return sysUserSalaryMapper.insert(record);
}
public int insertSelective(SysUserSalary record) {
return sysUserSalaryMapper.insertSelective(record);
}
public List<SysUserSalary> selectByExample(SysUserSalaryExample example) {
return sysUserSalaryMapper.selectByExample(example);
}
@Override
public List<RespUserSalary> selectByExampleResp(SysUserSalaryExample example) {
return sysUserSalaryMapper.selectByExampleResp(example);
}
public SysUserSalary selectByPrimaryKey(Long id) {
return sysUserSalaryMapper.selectByPrimaryKey(id);
}
@Override
public List<RespUserSalary> selectByCondition(ReqUserSalary reqUserSalary) {
return sysUserSalaryMapper.selectByCondition(reqUserSalary);
}
public int updateByExampleSelective(SysUserSalary record,SysUserSalaryExample example) {
return sysUserSalaryMapper.updateByExampleSelective(record,example);
}
public int updateByExample(SysUserSalary record,SysUserSalaryExample example) {
return sysUserSalaryMapper.updateByExample(record,example);
}
public int updateByPrimaryKeySelective(SysUserSalary record) {
return sysUserSalaryMapper.updateByPrimaryKeySelective(record);
}
@Override
public int deleteUserByIds(String ids) {
Long[] salaryIds = Convert.toLongArray(ids);
return sysUserSalaryMapper.deleteUserByIds(salaryIds);
}
public int updateByPrimaryKey(SysUserSalary record) {
return sysUserSalaryMapper.updateByPrimaryKey(record);
}
}
|
92392dc32722c3c51f40c0505b08629242ebc220 | 5,160 | java | Java | ex3/vaccine/java-LinkedList/RnaData.java | gmkazel/pl1-ntua | d3e071644c85e83b50616c60b2e3f59767ddcdbc | [
"MIT"
] | null | null | null | ex3/vaccine/java-LinkedList/RnaData.java | gmkazel/pl1-ntua | d3e071644c85e83b50616c60b2e3f59767ddcdbc | [
"MIT"
] | null | null | null | ex3/vaccine/java-LinkedList/RnaData.java | gmkazel/pl1-ntua | d3e071644c85e83b50616c60b2e3f59767ddcdbc | [
"MIT"
] | null | null | null | 31.463415 | 108 | 0.584884 | 998,729 | import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class RnaData {
LinkedList<Character> initial_rna_sequence;
LinkedList<Character> final_rna_sequence;
RnaData previous;
Character correction;
int initial_rna_size;
public RnaData(LinkedList<Character> initial_rna_sequence, LinkedList<Character> final_rna_sequence,
RnaData previous, Character correction, int initial_rna_size) {
this.initial_rna_sequence = initial_rna_sequence;
this.final_rna_sequence = final_rna_sequence;
this.previous = previous;
this.correction = correction;
this.initial_rna_size = initial_rna_size;
}
public RnaData(String initial_rna_sequence) {
this.initial_rna_sequence = new LinkedList<>();
for (int i = 0; i < initial_rna_sequence.length(); i++) {
this.initial_rna_sequence.add(initial_rna_sequence.charAt(i));
}
this.initial_rna_size = this.initial_rna_sequence.size();
this.final_rna_sequence = new LinkedList<>();
this.previous = null;
this.correction = null;
}
private void push() {
if (this.initial_rna_size == 0) {
return;
}
Character base = this.initial_rna_sequence.removeLast();
this.final_rna_sequence.add(base);
this.initial_rna_size--;
}
private void complement() {
for (int i = 0; i < this.initial_rna_size; i++) {
Character base = this.initial_rna_sequence.get(i);
if (base == 'A') {
this.initial_rna_sequence.set(i, 'U');
}
if (base == 'U') {
this.initial_rna_sequence.set(i, 'A');
}
if (base == 'G') {
this.initial_rna_sequence.set(i, 'C');
}
if (base == 'C') {
this.initial_rna_sequence.set(i, 'G');
}
}
}
private void reverse() {
Collections.reverse(this.final_rna_sequence);
}
public Boolean is_valid() {
if (this.final_rna_sequence.isEmpty())
return true;
Set<Character> found = new HashSet<>();
Character previous = null;
for (Character character : this.final_rna_sequence) {
if (!found.contains(character)) {
found.add(character);
previous = character;
} else if (previous != character) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
public RnaData[] next() {
RnaData[] returnList = { null, null, null };
if (!this.final_rna_sequence.isEmpty()) {
if (this.correction != 'r') {
LinkedList<Character> list2 = new LinkedList<>();
list2 = (LinkedList<Character>) this.final_rna_sequence.clone();
RnaData r = new RnaData(this.initial_rna_sequence, list2, this, 'r', this.initial_rna_size);
r.reverse();
returnList[2] = r;
}
}
if (!this.initial_rna_sequence.isEmpty()) {
LinkedList<Character> list1 = new LinkedList<>();
list1 = (LinkedList<Character>) this.initial_rna_sequence.clone();
LinkedList<Character> list2 = new LinkedList<>();
list2 = (LinkedList<Character>) this.final_rna_sequence.clone();
RnaData p = new RnaData(list1, list2, this, 'p', this.initial_rna_size);
p.push();
returnList[1] = p;
if (p != null && !p.is_valid()) {
returnList[1] = null;
}
}
if (this.correction == null || this.correction != 'c') {
LinkedList<Character> list1 = new LinkedList<>();
list1 = (LinkedList<Character>) this.initial_rna_sequence.clone();
RnaData c = new RnaData(list1, this.final_rna_sequence, this, 'c', this.initial_rna_size);
c.complement();
returnList[0] = c;
}
return returnList;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof RnaData)) {
return false;
}
RnaData rnaData = (RnaData) o;
return Objects.equals(initial_rna_sequence, rnaData.initial_rna_sequence)
&& Objects.equals(final_rna_sequence, rnaData.final_rna_sequence);
}
@Override
public int hashCode() {
return Objects.hash(initial_rna_sequence, final_rna_sequence);
}
public LinkedList<Character> getInitial_rna_sequence() {
return this.initial_rna_sequence;
}
public LinkedList<Character> getFinal_rna_sequence() {
return this.final_rna_sequence;
}
public RnaData getPrevious() {
return this.previous;
}
public Character getCorrection() {
return this.correction;
}
public int getInitial_rna_size() {
return this.initial_rna_size;
}
}
|
92392e8c6bb9675d109f0bd4908567caf0a485d8 | 1,977 | java | Java | yumall-ware/src/main/java/com/wyx/yumall/ware/controller/WareOrderTaskController.java | wangyuxiang985/xiaoyu_mall | adb4412ee2f4818236651d7183279df0f4213314 | [
"Apache-2.0"
] | null | null | null | yumall-ware/src/main/java/com/wyx/yumall/ware/controller/WareOrderTaskController.java | wangyuxiang985/xiaoyu_mall | adb4412ee2f4818236651d7183279df0f4213314 | [
"Apache-2.0"
] | null | null | null | yumall-ware/src/main/java/com/wyx/yumall/ware/controller/WareOrderTaskController.java | wangyuxiang985/xiaoyu_mall | adb4412ee2f4818236651d7183279df0f4213314 | [
"Apache-2.0"
] | null | null | null | 23.034884 | 71 | 0.695608 | 998,730 | package com.wyx.yumall.ware.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.wyx.yumall.ware.entity.WareOrderTaskEntity;
import com.wyx.yumall.ware.service.WareOrderTaskService;
import com.wyx.common.utils.PageUtils;
import com.wyx.common.utils.R;
/**
* 库存工作单
*
* @author wyx
* @email nnheo@example.com
* @date 2021-12-09 23:23:18
*/
@RestController
@RequestMapping("ware/wareordertask")
public class WareOrderTaskController {
@Autowired
private WareOrderTaskService wareOrderTaskService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = wareOrderTaskService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
WareOrderTaskEntity wareOrderTask = wareOrderTaskService.getById(id);
return R.ok().put("wareOrderTask", wareOrderTask);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody WareOrderTaskEntity wareOrderTask){
wareOrderTaskService.save(wareOrderTask);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody WareOrderTaskEntity wareOrderTask){
wareOrderTaskService.updateById(wareOrderTask);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
wareOrderTaskService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
92392eace05e0cabe307581ac9f5ee7d4d54fff2 | 1,379 | java | Java | crm-back/src/main/java/tech/becoming/meditech/crm/procedure/ProcedureMapper.java | becoming/meditech | 03df312748133a1f6c4c09b99b64cf10ccef4e38 | [
"MIT"
] | 1 | 2021-12-26T08:40:12.000Z | 2021-12-26T08:40:12.000Z | crm-back/src/main/java/tech/becoming/meditech/crm/procedure/ProcedureMapper.java | becoming/meditech | 03df312748133a1f6c4c09b99b64cf10ccef4e38 | [
"MIT"
] | 4 | 2021-12-21T15:32:21.000Z | 2022-01-30T12:39:50.000Z | crm-back/src/main/java/tech/becoming/meditech/crm/procedure/ProcedureMapper.java | becoming/meditech | 03df312748133a1f6c4c09b99b64cf10ccef4e38 | [
"MIT"
] | null | null | null | 30.644444 | 86 | 0.729514 | 998,731 | package tech.becoming.meditech.crm.procedure;
import org.mapstruct.Mapper;
import org.springframework.data.domain.Page;
import tech.becoming.meditech.crm.procedure.dto.NewProcedureDTO;
import tech.becoming.meditech.crm.procedure.dto.ProcedureDTO;
import tech.becoming.meditech.crm.procedure.entity.MedicalProcedureEntity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
//https://www.baeldung.com/mapstruct#1-modify-the-mapper
//https://www.baeldung.com/mapstruct-custom-mapper#custom-mapper-annotation
//https://www.baeldung.com/mapstruct-ignore-unmapped-properties#ignore-specific-fields
//https://stackoverflow.com/a/62548185/1107450
@Mapper
public interface ProcedureMapper {
default List<ProcedureDTO> toDto(Page<MedicalProcedureEntity> v) {
return v.map(this::toDto)
.getContent();
}
ProcedureDTO toDto(MedicalProcedureEntity v);
default UUID toUUID(String v) {
return v != null ? UUID.fromString(v) : null;
}
default String toString(UUID v) {
return v != null ? v.toString() : null;
}
default Set<ProcedureDTO> toDto(Iterable<MedicalProcedureEntity> v) {
var result = new HashSet<ProcedureDTO>();
v.forEach(item -> result.add(toDto(item)));
return result;
}
MedicalProcedureEntity toEntity(NewProcedureDTO v);
}
|
92392edfc8b0e983ddbdfa93e7fe6dd2bc435861 | 2,676 | java | Java | xmpbox/src/test/java/org/apache/xmpbox/schema/TestExifXmp.java | AlexanderScherbatiy/pdfbox | e43559ab865071ff6cbe40b8ea73a9f11de949c0 | [
"Apache-2.0"
] | 1,605 | 2015-01-01T05:54:51.000Z | 2022-03-31T05:45:16.000Z | xmpbox/src/test/java/org/apache/xmpbox/schema/TestExifXmp.java | AlexanderScherbatiy/pdfbox | e43559ab865071ff6cbe40b8ea73a9f11de949c0 | [
"Apache-2.0"
] | 87 | 2015-02-25T20:19:34.000Z | 2022-03-24T19:23:04.000Z | xmpbox/src/test/java/org/apache/xmpbox/schema/TestExifXmp.java | AlexanderScherbatiy/pdfbox | e43559ab865071ff6cbe40b8ea73a9f11de949c0 | [
"Apache-2.0"
] | 772 | 2015-01-06T15:37:49.000Z | 2022-03-25T13:58:38.000Z | 37.690141 | 110 | 0.689462 | 998,732 | /*****************************************************************************
*
* 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.xmpbox.schema;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayOutputStream;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.type.OECFType;
import org.apache.xmpbox.type.TextType;
import org.apache.xmpbox.type.TypeMapping;
import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpSerializer;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
class TestExifXmp
{
@Test
void testNonStrict() throws Exception
{
InputStream is = this.getClass().getResourceAsStream("/validxmp/exif.xmp");
DomXmpParser builder = new DomXmpParser();
builder.setStrictParsing(false);
XMPMetadata rxmp = builder.parse(is);
ExifSchema schema = (ExifSchema)rxmp.getSchema(ExifSchema.class);
TextType ss = (TextType)schema.getProperty(ExifSchema.SPECTRAL_SENSITIVITY);
assertNotNull(ss);
assertEquals("spectral sens value",ss.getValue());
}
@Test
void testGenerate() throws Exception
{
XMPMetadata metadata = XMPMetadata.createXMPMetadata();
TypeMapping tmapping = metadata.getTypeMapping();
ExifSchema exif = new ExifSchema(metadata);
metadata.addSchema(exif);
OECFType oecf = new OECFType(metadata);
oecf.addProperty(tmapping.createInteger(oecf.getNamespace(), oecf.getPrefix(), OECFType.COLUMNS, 14));
oecf.setPropertyName(ExifSchema.OECF);
exif.addProperty(oecf);
XmpSerializer serializer = new XmpSerializer();
serializer.serialize(metadata, new ByteArrayOutputStream(), false);
}
}
|
92392f3075e7867fae6d5578b6444e9647140c50 | 2,452 | java | Java | webapp/cloud-application/src/main/java/com/neu/pojo/Transaction.java | singh-harsh/cloud-infrastructure-networking | dccf68176109af95ca4cc5dcd523c3395f7cfd1d | [
"Apache-2.0"
] | null | null | null | webapp/cloud-application/src/main/java/com/neu/pojo/Transaction.java | singh-harsh/cloud-infrastructure-networking | dccf68176109af95ca4cc5dcd523c3395f7cfd1d | [
"Apache-2.0"
] | null | null | null | webapp/cloud-application/src/main/java/com/neu/pojo/Transaction.java | singh-harsh/cloud-infrastructure-networking | dccf68176109af95ca4cc5dcd523c3395f7cfd1d | [
"Apache-2.0"
] | null | null | null | 20.098361 | 62 | 0.618271 | 998,733 | package com.neu.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
@Entity
public class Transaction {
@Id
private String id;
@Column(nullable = false)
@NotNull
private String description;
@Column(nullable = false)
@NotNull
private String merchant;
@Column(nullable = false)
@NotNull
private String amount;
@DateTimeFormat(pattern = "mm/dd/yyyy")
@NotNull
private String date;
@Column(nullable = false)
@NotNull
private String category;
@JsonIgnore
@ManyToOne
private Account account;
@OneToMany
private List<Attachment> attachments;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public static boolean isEmpty(Transaction trans) {
if (trans.getAmount().isEmpty())
return true;
else if (trans.getCategory().isEmpty())
return true;
else if (trans.getDate().isEmpty())
return true;
else if (trans.getDescription().isEmpty())
return true;
else if (trans.getMerchant().isEmpty())
return true;
return false;
}
}
|
923930cb7ab5eb9066491e29cfdc4f6cbecc7c73 | 3,820 | java | Java | wire-runtime/src/test/proto-java/com/google/protobuf/EnumValueDescriptorProto.java | fangzhzh/wire | 6ccef1645dcc5610afa44931bd71f6ccf48b642c | [
"Apache-2.0"
] | 1 | 2016-07-27T05:21:16.000Z | 2016-07-27T05:21:16.000Z | wire-runtime/src/test/proto-java/com/google/protobuf/EnumValueDescriptorProto.java | fangzhzh/wire | 6ccef1645dcc5610afa44931bd71f6ccf48b642c | [
"Apache-2.0"
] | null | null | null | wire-runtime/src/test/proto-java/com/google/protobuf/EnumValueDescriptorProto.java | fangzhzh/wire | 6ccef1645dcc5610afa44931bd71f6ccf48b642c | [
"Apache-2.0"
] | null | null | null | 26.713287 | 134 | 0.668848 | 998,734 | // Code generated by Wire protocol buffer compiler, do not edit.
// Source file: ../wire-runtime/src/test/proto/google/protobuf/descriptor.proto at 178:1
package com.google.protobuf;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.TagMap;
import com.squareup.wire.WireField;
import java.lang.Integer;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
/**
* Describes a value within an enum.
*/
public final class EnumValueDescriptorProto extends Message<EnumValueDescriptorProto> {
public static final ProtoAdapter<EnumValueDescriptorProto> ADAPTER = ProtoAdapter.newMessageAdapter(EnumValueDescriptorProto.class);
private static final long serialVersionUID = 0L;
public static final String DEFAULT_NAME = "";
public static final String DEFAULT_DOC = "";
public static final Integer DEFAULT_NUMBER = 0;
@WireField(
tag = 1,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String name;
/**
* Doc string for generated code.
*/
@WireField(
tag = 4,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String doc;
@WireField(
tag = 2,
adapter = "com.squareup.wire.ProtoAdapter#INT32"
)
public final Integer number;
@WireField(
tag = 3,
adapter = "com.google.protobuf.EnumValueOptions#ADAPTER"
)
public final EnumValueOptions options;
public EnumValueDescriptorProto(String name, String doc, Integer number, EnumValueOptions options) {
this(name, doc, number, options, TagMap.EMPTY);
}
public EnumValueDescriptorProto(String name, String doc, Integer number, EnumValueOptions options, TagMap tagMap) {
super(tagMap);
this.name = name;
this.doc = doc;
this.number = number;
this.options = options;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof EnumValueDescriptorProto)) return false;
EnumValueDescriptorProto o = (EnumValueDescriptorProto) other;
return equals(tagMap(), o.tagMap())
&& equals(name, o.name)
&& equals(doc, o.doc)
&& equals(number, o.number)
&& equals(options, o.options);
}
@Override
public int hashCode() {
int result = super.hashCode;
if (result == 0) {
result = tagMap().hashCode();
result = result * 37 + (name != null ? name.hashCode() : 0);
result = result * 37 + (doc != null ? doc.hashCode() : 0);
result = result * 37 + (number != null ? number.hashCode() : 0);
result = result * 37 + (options != null ? options.hashCode() : 0);
super.hashCode = result;
}
return result;
}
public static final class Builder extends com.squareup.wire.Message.Builder<EnumValueDescriptorProto, Builder> {
public String name;
public String doc;
public Integer number;
public EnumValueOptions options;
public Builder() {
}
public Builder(EnumValueDescriptorProto message) {
super(message);
if (message == null) return;
this.name = message.name;
this.doc = message.doc;
this.number = message.number;
this.options = message.options;
}
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Doc string for generated code.
*/
public Builder doc(String doc) {
this.doc = doc;
return this;
}
public Builder number(Integer number) {
this.number = number;
return this;
}
public Builder options(EnumValueOptions options) {
this.options = options;
return this;
}
@Override
public EnumValueDescriptorProto build() {
return new EnumValueDescriptorProto(name, doc, number, options, buildTagMap());
}
}
}
|
92393162db4e4f1eba0807fd40aaee50fbefee07 | 782 | java | Java | snapshot-matcher-example/src/main/java/com/zenika/snapshotmatcherexample/starwars/StarWarsService.java | ibi-group/java-snapshot-matcher | 357be2d0792ec5d4922a8c8d2ba53a5b819e7fc0 | [
"Apache-2.0"
] | 13 | 2018-01-25T15:55:20.000Z | 2021-12-30T10:20:41.000Z | snapshot-matcher-example/src/main/java/com/zenika/snapshotmatcherexample/starwars/StarWarsService.java | ibi-group/java-snapshot-matcher | 357be2d0792ec5d4922a8c8d2ba53a5b819e7fc0 | [
"Apache-2.0"
] | 9 | 2018-01-24T14:57:35.000Z | 2020-01-23T17:27:49.000Z | snapshot-matcher-example/src/main/java/com/zenika/snapshotmatcherexample/starwars/StarWarsService.java | ibi-group/java-snapshot-matcher | 357be2d0792ec5d4922a8c8d2ba53a5b819e7fc0 | [
"Apache-2.0"
] | 5 | 2018-10-26T19:08:19.000Z | 2022-02-21T13:24:16.000Z | 28.962963 | 101 | 0.799233 | 998,735 | package com.zenika.snapshotmatcherexample.starwars;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.zenika.snapshotmatcherexample.starwars.dtos.PlanetDTO;
import com.zenika.snapshotmatcherexample.starwars.entities.Planet;
@Service
public class StarWarsService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private PlanetConverter planetConverter;
@Value("${endpoints.planets}")
private String endpoint;
public PlanetDTO getPlanet(Long id){
return planetConverter.convertPlanet(restTemplate.getForObject(endpoint + id, Planet.class));
}
}
|
9239316c83e640f68ac7742f8365f90941d06236 | 221 | java | Java | src/ui/authoring/delegates/ActorEditorDelegate.java | ab546/GameSalad | 27426f03a9675f5dde1e305380d250463c429e2c | [
"MIT"
] | 1 | 2017-06-29T05:24:13.000Z | 2017-06-29T05:24:13.000Z | src/ui/authoring/delegates/ActorEditorDelegate.java | ab546/GameSalad | 27426f03a9675f5dde1e305380d250463c429e2c | [
"MIT"
] | null | null | null | src/ui/authoring/delegates/ActorEditorDelegate.java | ab546/GameSalad | 27426f03a9675f5dde1e305380d250463c429e2c | [
"MIT"
] | null | null | null | 24.555556 | 72 | 0.837104 | 998,736 | package ui.authoring.delegates;
import gamedata.ActorData;
import util.Location;
public interface ActorEditorDelegate extends PopViewDelegate {
public abstract void addActorToBase(ActorData data, Location mouseLoc);
}
|
923931796f3b763d3354feff8e26340c56ae823a | 4,777 | java | Java | src/main/java/org/jamplate/glucose/spec/parameter/extension/GetterSpec.java | jamplate/processor | 9e5f16679f0eaf9c0d367be167e0c5df8842ee66 | [
"Apache-2.0"
] | 8 | 2021-07-11T08:13:44.000Z | 2022-01-10T02:21:55.000Z | src/main/java/org/jamplate/glucose/spec/parameter/extension/GetterSpec.java | jamplate/processor | 9e5f16679f0eaf9c0d367be167e0c5df8842ee66 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/jamplate/glucose/spec/parameter/extension/GetterSpec.java | jamplate/processor | 9e5f16679f0eaf9c0d367be167e0c5df8842ee66 | [
"Apache-2.0"
] | 1 | 2021-04-03T12:52:22.000Z | 2021-04-03T12:52:22.000Z | 26.392265 | 86 | 0.661084 | 998,737 | /*
* Copyright 2021 Cufy
*
* 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.jamplate.glucose.spec.parameter.extension;
import org.jamplate.unit.Spec;
import org.jamplate.function.Analyzer;
import org.jamplate.function.Compiler;
import org.jamplate.glucose.instruction.memory.resource.IPushConst;
import org.jamplate.glucose.instruction.operator.struct.IGet;
import org.jamplate.glucose.spec.element.ParameterSpec;
import org.jamplate.glucose.spec.standard.ExtensionSpec;
import org.jamplate.glucose.spec.syntax.enclosure.BracketsSpec;
import org.jamplate.impl.instruction.Block;
import org.jamplate.model.CompileException;
import org.jamplate.model.Instruction;
import org.jamplate.model.Sketch;
import org.jamplate.model.Tree;
import org.jetbrains.annotations.NotNull;
import static org.jamplate.glucose.internal.util.Values.number;
import static org.jamplate.impl.analyzer.FilterAnalyzer.filter;
import static org.jamplate.impl.analyzer.HierarchyAnalyzer.hierarchy;
import static org.jamplate.impl.compiler.FilterCompiler.filter;
import static org.jamplate.glucose.internal.analyzer.UnaryExtensionAnalyzer.extension;
import static org.jamplate.util.Functions.analyzer;
import static org.jamplate.util.Functions.compiler;
import static org.jamplate.util.Query.*;
import static org.jamplate.util.Source.read;
/**
* Getter extension specifications.
*
* @author LSafer
* @version 0.3.0
* @since 0.3.0 ~2021.06.20
*/
public class GetterSpec implements Spec {
/**
* An instance of this spec.
*
* @since 0.3.0 ~2021.06.21
*/
@NotNull
public static final GetterSpec INSTANCE = new GetterSpec();
/**
* The kind of a getter extension context.
*
* @since 0.3.0 ~2021.06.22
*/
@NotNull
public static final String KIND = "extension:getter";
/**
* The qualified name of this spec.
*
* @since 0.3.0 ~2021.06.22
*/
@NotNull
public static final String NAME = GetterSpec.class.getSimpleName();
@NotNull
@Override
public Analyzer getAnalyzer() {
return analyzer(
//search in the whole hierarchy
a -> hierarchy(a),
//target valid non processed trees
a -> filter(a, and(
//target brackets symbols
is(BracketsSpec.KIND),
//skip if already wrapped
parent(not(GetterSpec.KIND))
)),
//analyze
a -> extension(
true,
//context wrapper constructor
(d, r) -> new Tree(
d,
r,
new Sketch(GetterSpec.KIND),
ExtensionSpec.WEIGHT
),
//extension constructor
(w, t) -> w.getSketch().set(
ExtensionSpec.KEY_SIGN,
t.getSketch()
),
//left-side wrapper constructor
(w, r) -> w.offer(new Tree(
w.getDocument(),
r,
w.getSketch()
.get(ExtensionSpec.KEY_TARGET)
.setKind(ParameterSpec.KIND),
ParameterSpec.WEIGHT
))
)
);
}
@NotNull
@Override
public Compiler getCompiler() {
return compiler(
//target getter context
c -> filter(c, is(GetterSpec.KIND)),
//compile
c -> (compiler, compilation, tree) -> {
Tree targetT = tree.getSketch().get(ExtensionSpec.KEY_TARGET).getTree();
Tree signT = tree.getSketch().get(ExtensionSpec.KEY_SIGN).getTree();
if (targetT == null || signT == null)
throw new CompileException(
"Extension GETTER is missing some components",
tree
);
Instruction targetI = compiler.compile(
compiler,
compilation,
targetT
);
Instruction signI = compiler.compile(
compiler,
compilation,
signT
);
if (targetI == null || signI == null)
throw new CompileException(
"The extension GETTER cannot be applied to <" +
read(targetT) +
"> with <" +
read(signT) +
">",
tree
);
return new Block(
tree,
//run the target
targetI,
//key sandbox
new Block(
tree,
//run the sign
signI,
//push `0` to access the key
new IPushConst(tree, number(0)),
//get the key
new IGet(tree)
),
//get
new IGet(tree)
);
}
);
}
@NotNull
@Override
public String getQualifiedName() {
return GetterSpec.NAME;
}
}
|
9239319b4ca1d871b43d73d96474a35ef6284e24 | 1,237 | java | Java | src/main/java/com/avanza/gs/test/PuApp.java | AvanzaBank/gs-test | caf8ba96dead299f0ef5f6d3148ac169c5a0b87c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/avanza/gs/test/PuApp.java | AvanzaBank/gs-test | caf8ba96dead299f0ef5f6d3148ac169c5a0b87c | [
"Apache-2.0"
] | 12 | 2020-07-01T07:28:14.000Z | 2022-02-16T15:47:55.000Z | src/main/java/com/avanza/gs/test/PuApp.java | AvanzaBank/gs-test | caf8ba96dead299f0ef5f6d3148ac169c5a0b87c | [
"Apache-2.0"
] | 3 | 2016-02-02T07:38:01.000Z | 2018-12-03T15:22:55.000Z | 25.244898 | 75 | 0.725141 | 998,738 | /*
* Copyright 2017 Avanza Bank AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.avanza.gs.test;
import java.io.IOException;
public class PuApp {
private PartitionedPu partitionedPu;
private PuApp(String puXmlPath) {
partitionedPu = new PartitionedPu(PuConfigurers
.partitionedPu(puXmlPath).numberOfPrimaries(1)
.numberOfBackups(0));
}
public static PuApp run(String puXmlPath) {
try {
PuApp puApp = new PuApp(puXmlPath);
puApp.start();
return puApp;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void start() throws IOException {
this.partitionedPu.run();
}
public void stop() throws IOException {
this.partitionedPu.shutdown();
}
}
|
923931ec4c4dd42ff467a47005b0a0802f60c501 | 1,319 | java | Java | dbconnection/src/test/java/org/josfranmc/db/DbConnectionTest.java | josfranmc/Demo-Java | fd2cb36ce130277ddb14bc481cc317782b1b3262 | [
"MIT"
] | null | null | null | dbconnection/src/test/java/org/josfranmc/db/DbConnectionTest.java | josfranmc/Demo-Java | fd2cb36ce130277ddb14bc481cc317782b1b3262 | [
"MIT"
] | null | null | null | dbconnection/src/test/java/org/josfranmc/db/DbConnectionTest.java | josfranmc/Demo-Java | fd2cb36ce130277ddb14bc481cc317782b1b3262 | [
"MIT"
] | null | null | null | 24.886792 | 80 | 0.741471 | 998,739 | package org.josfranmc.db;
import static org.junit.Assert.assertNotNull;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class DbConnectionTest {
@Test
public void dbConnectionDefaultConstructorTest() {
DbConnection dbConnection = new DbConnection();
try {
assertNotNull(dbConnection.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void dbConnectionStringConstructorTest() {
DbConnection dbConnection = new DbConnection("db/DbConnectionAlt.properties");
try {
assertNotNull(dbConnection.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void dbConnectionPropertiesConstructorTest() {
Properties properties = new Properties();
properties.setProperty("databaseDriver", "org.hsqldb.jdbcDriver");
properties.setProperty("url", "jdbc:hsqldb:mem:tempdbAlt2");
properties.setProperty("user", "SA");
properties.setProperty("password", "");
DbConnection dbConnection = new DbConnection();
try {
assertNotNull(dbConnection.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test(expected=IllegalArgumentException.class)
public void dbConnectionStringConstructorTest2() {
new DbConnection("db/BadFile.properties");
}
}
|
9239334cf715a1ae34eeab0940d711b540606a8e | 7,061 | java | Java | src/main/java/com/mithion/griefguardian/util/RenderUtils.java | HoldYourWaffle2/GriefGuardian | 80e78824fdabe23a602f22553ac0cdf7be44ae12 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/mithion/griefguardian/util/RenderUtils.java | HoldYourWaffle2/GriefGuardian | 80e78824fdabe23a602f22553ac0cdf7be44ae12 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/mithion/griefguardian/util/RenderUtils.java | HoldYourWaffle2/GriefGuardian | 80e78824fdabe23a602f22553ac0cdf7be44ae12 | [
"CC0-1.0"
] | null | null | null | 56.039683 | 116 | 0.720011 | 998,740 | package com.mithion.griefguardian.util;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
public class RenderUtils {
public static void renderBoundingBox(AxisAlignedBB boundingBox, int boxColor, int outlineColor){
Tessellator tessellator = Tessellator.getInstance();
WorldRenderer worldrenderer = tessellator.getWorldRenderer();
int alpha = 60;
double XOffset = 0.5;
double YOffset = 0.5;
double ZOffset = 0.5;
boundingBox = boundingBox.contract(0.01, 0.01, 0.01);
GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_LIGHTING);
//GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
//box
if (outlineColor != -1)
{
worldrenderer.func_178974_a(boxColor, alpha);
}
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
tessellator.draw();
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopAttrib();
//outline
worldrenderer.startDrawing(3);
if (outlineColor != -1)
{
worldrenderer.func_178991_c(outlineColor);
}
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
tessellator.draw();
worldrenderer.startDrawing(3);
if (outlineColor != -1)
{
worldrenderer.func_178991_c(outlineColor);
}
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
tessellator.draw();
worldrenderer.startDrawing(1);
if (outlineColor != -1)
{
worldrenderer.func_178991_c(outlineColor);
}
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.minZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.maxX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.minY + YOffset, boundingBox.maxZ + ZOffset);
worldrenderer.addVertex(boundingBox.minX + XOffset, boundingBox.maxY - YOffset, boundingBox.maxZ + ZOffset);
tessellator.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_LIGHTING);
//GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(true);
}
}
|
9239338c8d22dfb19107a7b2e763f9616740cf45 | 1,087 | java | Java | whistleblower/workflows-java/src/main/java/net/corda/examples/whistleblower/flows/BlowWhistleFlowResponder.java | HDBISG/cordappFTI | cccd2d3ec74f378d1f6ec51c4a14b34a49efcd07 | [
"Apache-2.0"
] | null | null | null | whistleblower/workflows-java/src/main/java/net/corda/examples/whistleblower/flows/BlowWhistleFlowResponder.java | HDBISG/cordappFTI | cccd2d3ec74f378d1f6ec51c4a14b34a49efcd07 | [
"Apache-2.0"
] | null | null | null | whistleblower/workflows-java/src/main/java/net/corda/examples/whistleblower/flows/BlowWhistleFlowResponder.java | HDBISG/cordappFTI | cccd2d3ec74f378d1f6ec51c4a14b34a49efcd07 | [
"Apache-2.0"
] | null | null | null | 33.96875 | 98 | 0.735971 | 998,741 | package net.corda.examples.whistleblower.flows;
import co.paralleluniverse.fibers.Suspendable;
import net.corda.confidential.SwapIdentitiesFlow;
import net.corda.core.flows.*;
import net.corda.core.transactions.SignedTransaction;
import org.jetbrains.annotations.NotNull;
@InitiatedBy(BlowWhistleFlow.class)
public class BlowWhistleFlowResponder extends FlowLogic<Void> {
private final FlowSession counterpartySession;
public BlowWhistleFlowResponder(FlowSession counterpartySession) {
this.counterpartySession = counterpartySession;
}
@Suspendable
@Override
public Void call() throws FlowException {
subFlow(new SwapIdentitiesFlow(counterpartySession));
SignedTransaction stx = subFlow(new SignTransactionFlow(counterpartySession) {
@Override
protected void checkTransaction(@NotNull SignedTransaction stx) throws FlowException {
// No checking need to be done.
}
});
subFlow(new ReceiveFinalityFlow(counterpartySession, stx.getId()));
return null;
}
}
|
923934f1ee69b67934daf4203943f6c72adf2e3b | 201 | java | Java | plugins/stream-debugger/testData/streamex/src/concatenate/AppendNone.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | plugins/stream-debugger/testData/streamex/src/concatenate/AppendNone.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | plugins/stream-debugger/testData/streamex/src/concatenate/AppendNone.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | 18.272727 | 48 | 0.666667 | 998,742 | package concatenate;
import one.util.streamex.StreamEx;
public class AppendNone {
public static void main(String[] args) {
// Breakpoint!
StreamEx.of(1, 2).append().forEach(x -> {});
}
}
|
923935e94549929ce7ed2aa30754af5d8307bed4 | 4,205 | java | Java | myDemo/Android/ViewPagerDemo-0/MyBigImageview/app/src/main/java/com/updayup/yuchance/mybigimageview/EasePhotoView.java | yuchange/myDemoGather | 7cc59f7c943fceb8728278b3fea743be49ed64bd | [
"MIT"
] | null | null | null | myDemo/Android/ViewPagerDemo-0/MyBigImageview/app/src/main/java/com/updayup/yuchance/mybigimageview/EasePhotoView.java | yuchange/myDemoGather | 7cc59f7c943fceb8728278b3fea743be49ed64bd | [
"MIT"
] | null | null | null | myDemo/Android/ViewPagerDemo-0/MyBigImageview/app/src/main/java/com/updayup/yuchance/mybigimageview/EasePhotoView.java | yuchange/myDemoGather | 7cc59f7c943fceb8728278b3fea743be49ed64bd | [
"MIT"
] | null | null | null | 25.029762 | 95 | 0.669679 | 998,743 | package com.updayup.yuchance.mybigimageview;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.updayup.yuchance.mybigimageview.PhotoViewAttacher.OnMatrixChangedListener;
import com.updayup.yuchance.mybigimageview.PhotoViewAttacher.OnPhotoTapListener;
import com.updayup.yuchance.mybigimageview.PhotoViewAttacher.OnViewTapListener;
/**
* Created by liuhangf on 2017/9/19.
*/
public class EasePhotoView extends ImageView implements IPhotoView{
private final PhotoViewAttacher mAttacher;
private ImageView.ScaleType mPendingScaleType;
public EasePhotoView(Context context) {
this(context, null);
}
public EasePhotoView(Context context, AttributeSet attr) {
this(context, attr, 0);
}
public EasePhotoView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
super.setScaleType(ImageView.ScaleType.MATRIX);
mAttacher = new PhotoViewAttacher(this);
if (null != mPendingScaleType) {
setScaleType(mPendingScaleType);
mPendingScaleType = null;
}
}
@Override
public boolean canZoom() {
return mAttacher.canZoom();
}
@Override
public RectF getDisplayRect() {
return mAttacher.getDisplayRect();
}
@Override
public float getMinScale() {
return mAttacher.getMinScale();
}
@Override
public float getMidScale() {
return mAttacher.getMidScale();
}
@Override
public float getMaxScale() {
return mAttacher.getMaxScale();
}
@Override
public float getScale() {
return mAttacher.getScale();
}
@Override
public ImageView.ScaleType getScaleType() {
return mAttacher.getScaleType();
}
@Override
public void setAllowParentInterceptOnEdge(boolean allow) {
mAttacher.setAllowParentInterceptOnEdge(allow);
}
@Override
public void setMinScale(float minScale) {
mAttacher.setMinScale(minScale);
}
@Override
public void setMidScale(float midScale) {
mAttacher.setMidScale(midScale);
}
@Override
public void setMaxScale(float maxScale) {
mAttacher.setMaxScale(maxScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override
public void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener) {
mAttacher.setOnViewTapListener(listener);
}
@Override
public void setScaleType(ImageView.ScaleType scaleType) {
if (null != mAttacher) {
mAttacher.setScaleType(scaleType);
} else {
mPendingScaleType = scaleType;
}
}
@Override
public void setZoomable(boolean zoomable) {
mAttacher.setZoomable(zoomable);
}
@Override
public void zoomTo(float scale, float focalX, float focalY) {
mAttacher.zoomTo(scale, focalX, focalY);
}
@Override
protected void onDetachedFromWindow() {
mAttacher.cleanup();
super.onDetachedFromWindow();
}
}
|
923936372e7b293953a1580e7c5d6532662483fe | 1,341 | java | Java | spring-aot/src/test/java/org/springframework/aot/factories/TypeSystemTest.java | making/spring-native | ded5ae6b876ea1f0619bb4947a52b054cc75e828 | [
"Apache-2.0"
] | 507 | 2020-05-18T12:12:41.000Z | 2021-01-06T00:24:45.000Z | spring-aot/src/test/java/org/springframework/aot/factories/TypeSystemTest.java | wycm/spring-native | 376e1c8b2c310e9dbfee736e50c8a94b05d8c483 | [
"Apache-2.0"
] | 302 | 2020-05-18T09:42:56.000Z | 2021-01-05T19:35:56.000Z | spring-aot/src/test/java/org/springframework/aot/factories/TypeSystemTest.java | wycm/spring-native | 376e1c8b2c310e9dbfee736e50c8a94b05d8c483 | [
"Apache-2.0"
] | 67 | 2020-05-22T16:54:47.000Z | 2021-01-05T08:22:23.000Z | 33.525 | 119 | 0.785981 | 998,744 | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.factories;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.aot.TypeSystemExtension;
import org.springframework.core.type.classreading.ClassDescriptor;
import org.springframework.core.type.classreading.TypeSystem;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Brian Clozel
*/
@ExtendWith(TypeSystemExtension.class)
public class TypeSystemTest {
@Test
void checkThatEnableAutoConfigurationIsInClaspath(TypeSystem typeSystem) {
ClassDescriptor resolved = typeSystem.resolveClass("org.springframework.boot.autoconfigure.EnableAutoConfiguration");
assertThat(resolved).isNotNull();
}
}
|
92393691b57255a0fdf9383d1de9ef33f8453dfa | 282 | java | Java | src/main/java/fi/bytecraft/spock/review/ReviewRepository.java | bytecraftoy/spock-specifications | d677c9fca04d7fb82f919437dc17c0727fd89921 | [
"CC0-1.0"
] | null | null | null | src/main/java/fi/bytecraft/spock/review/ReviewRepository.java | bytecraftoy/spock-specifications | d677c9fca04d7fb82f919437dc17c0727fd89921 | [
"CC0-1.0"
] | null | null | null | src/main/java/fi/bytecraft/spock/review/ReviewRepository.java | bytecraftoy/spock-specifications | d677c9fca04d7fb82f919437dc17c0727fd89921 | [
"CC0-1.0"
] | null | null | null | 25.636364 | 72 | 0.840426 | 998,745 | package fi.bytecraft.spock.review;
import fi.bytecraft.spock.review.models.Review;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ReviewRepository extends CrudRepository<Review, Long> {
}
|
923937bb057c20cbee973fc1607bb188855a0451 | 12,987 | java | Java | Main.java | sandycho/fragments_reassemble | 2ef50a9a7f833f077d21ecc408c56a56ecdc425d | [
"MIT"
] | null | null | null | Main.java | sandycho/fragments_reassemble | 2ef50a9a7f833f077d21ecc408c56a56ecdc425d | [
"MIT"
] | null | null | null | Main.java | sandycho/fragments_reassemble | 2ef50a9a7f833f077d21ecc408c56a56ecdc425d | [
"MIT"
] | null | null | null | 41.228571 | 190 | 0.424732 | 998,746 | package fragment.submissions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
try ( BufferedReader in = new BufferedReader( new FileReader( args[0] ) ) ) {
in.lines().map(Reassembler::reassemble).forEach(System.out::println);
}catch( Exception e ){
}
}
public static class Reassembler {
private static int MIN_CHARS_TO_MATCH = 2;
/**
* Rebuilds a text from a bunch of pieces of text.
*
* @param fragments concats by ";" char
* @return a string with the reassembled text
*/
public static String reassemble( String fragments ){
String result = null, currentFrag = null, matchFrag = null;
Set fragmentsSet = new HashSet();
HashMap<Integer, HashMap> map = new HashMap<>();;
HashMap newMatch = null, fragMatchStruct = null;
HashMap tempStruct = null, tempNewMatchInv = null, tempNewMatchRev = null, tempNewMatchCon = null;
int index = 0;
try{
ArrayList<String> fragList = new ArrayList<>( Arrays.asList( fragments.split( ";" ) ) );
// iterates the list matching fragments until to get a unique chain with the reassembled text
while( fragList.size() > 1 ){
tempStruct = null;
// gets the current fragment to compare to the list
currentFrag = fragList.get( index );
fragMatchStruct = map.get(index);
// iterates over the fragment list keeping every match in the current fragment matches structure in a map
// the followin lines show the struct after the first iteration
// wns a clown;owns ;He owns a
// map = {
// 0 = {
// matchInv = { chain="wns a clowns", overlap="3", fragId="1" },
// matchRev = { chain="He owns a clown", overlap="5", fragId="2" },
// matchCon = null,
// },
// 1 = {
// matchInv = { chain="owns a clown", overlap="4", fragId="0" },
// matchRev = { chain="wns a clowns ", overlap="3", fragId="0" },
// matchCon = { chain="He owns a", overlap="5", fragId="2" },
// },
// 2 = {
// matchInv = null
// matchRev = { chain="He owns a clown", overlap="5", fragId="1" },
// matchCon = { chain="He owns a", overlap="5", fragId="2" },
// },
// }
for( int j = 0; j < fragList.size(); j++ ){
if( j != index ) {
matchFrag = fragList.get(j);
//
newMatch = match(String.valueOf(j), currentFrag, matchFrag);
if (newMatch != null) {
if ( fragMatchStruct != null ) {
// compare number of match chars
//
if ( fragMatchStruct != null ) tempStruct = (HashMap) fragMatchStruct.get("matchInv");
tempNewMatchInv = (HashMap) newMatch.get("matchInv");
if ( ( tempStruct != null ) || tempNewMatchInv != null && tempStruct != null && (int) tempStruct.get("overlap") < (int) tempNewMatchInv.get("overlap") ) {
fragMatchStruct.put("matchInv", tempNewMatchInv);
}
//
if ( fragMatchStruct != null ) tempStruct = (HashMap) fragMatchStruct.get("matchRev");
tempNewMatchRev = (HashMap) newMatch.get("matchRev");
if ( ( tempStruct != null ) || tempNewMatchRev != null && tempStruct != null && (int) tempStruct.get("overlap") < (int) tempNewMatchRev.get("overlap") ) {
fragMatchStruct.put("matchRev", tempNewMatchRev);
}
//
if ( fragMatchStruct != null ) tempStruct = (HashMap) fragMatchStruct.get("matchCon");
tempNewMatchCon = (HashMap) newMatch.get("matchCon");
if ( ( tempStruct != null ) || tempNewMatchCon != null && tempStruct != null && (int) tempStruct.get("overlap") < (int) tempNewMatchCon.get("overlap") ) {
fragMatchStruct.put("matchCon", tempNewMatchCon);
}
map.replace( index, fragMatchStruct );
} else {
map.put( index, newMatch );
}
}
}
}
// after the first iteration it build a new list of fragment with the best matches, if a match is ambigus
// the fragment is proccesed again, and duplicates are deleted
// listFrag = ["He owns a clown", "He owns a"]
if ( index == fragList.size() - 1 ) {
fragmentsSet.clear();
int k = 0;
HashMap elem = null;
HashMap eInv = null, eRev = null, eCon = null;
HashMap concatResult = null;
Set keys = map.keySet();
Iterator itr = keys.iterator();
while ( itr.hasNext() ) {
elem = map.get( itr.next() );
eInv = (HashMap) elem.get( "matchInv" );
eRev = (HashMap) elem.get( "matchRev" );
eCon = (HashMap) elem.get( "matchCon" );
if ( eRev != null && eCon != null && eInv == null ) {
if ( eRev.get( "fragId" ) != eCon.get( "fragId" ) ) {
concatResult = concat( (String) eRev.get( "chain" ), (String) eCon.get( "chain" ) );
fragmentsSet.add( (String) concatResult.get( "chain" ) );
}else {
fragmentsSet.add( (String) fragList.get( k ) );
}
} else if ( eInv != null && eCon != null && eRev == null ) {
if ( eInv.get( "fragId" ) != eCon.get( "fragId" ) ) {
concatResult = concat( (String) eInv.get( "chain" ), (String) eCon.get( "chain" ) );
fragmentsSet.add( (String) concatResult.get( "chain" ) );
}else {
fragmentsSet.add( (String) fragList.get( k ) );
}
} else if ( eInv != null && eRev != null && eCon == null ) {
if ( eInv.get( "fragId" ) != eRev.get( "fragId" ) ) {
concatResult = concat( (String) eInv.get( "chain" ), (String) eRev.get( "chain" ) );
fragmentsSet.add( (String) concatResult.get( "chain" ) );
}else {
fragmentsSet.add( (String) fragList.get( k ) );
}
} else if ( eInv != null ){
fragmentsSet.add( (String) eInv.get( "chain" ) );
} else if ( eRev != null ){
fragmentsSet.add( (String) eRev.get( "chain" ) );
} else if ( eCon != null ) {
fragmentsSet.add( (String) eCon.get( "chain" ) );
}
k++;
}
fragList = new ArrayList( Arrays.asList( fragmentsSet.toArray() ) );
map = new HashMap();
index = 0;
}else{
index++;
}
}
result = fragList.get(0);
}catch ( Exception e ){
result = null;
}finally {
}
return result;
}
/**
* Returns a new string which contains the fragments parameter.
*
* @param frag1
* @param frag2
* @return the string fragment that contains the small fragment or a new string of the concatenated fragments, null in other case.
*/
private static HashMap match(String fragId, String frag1, String frag2){
HashMap result = new HashMap();
HashMap resultContained = null;
HashMap resultInv = null;
HashMap resultRev = null;
String temp = null;
StringBuilder b_frag_small = null, b_frag_large = null;
String frag_small = frag1;
String frag_large = frag2;
try{
if ( frag1.length() > frag2.length() ){
temp = frag_large;
frag_large = frag_small;
frag_small = temp;
}
if ( frag_large.contains( frag_small ) ){
resultContained = new HashMap();
resultContained.put( "chain", frag_large );
resultContained.put( "overlap", frag_small.length() );
resultContained.put( "fragId", fragId );
} else {
b_frag_small = new StringBuilder( frag_small );
b_frag_large = new StringBuilder( frag_large );
// checks if the large fragment ends with the smaller
resultInv = concat( frag_large, frag_small );
if( resultInv != null) resultInv.put( "fragId", fragId );
// checks if the small fragment ends with the larger
resultRev = concat( b_frag_large.reverse().toString(), b_frag_small.reverse().toString() );
if( resultRev != null ) {
resultRev.replace( "chain", new StringBuilder( resultRev.get( "chain" ).toString() ).reverse().toString() );
resultRev.put( "fragId", fragId );
}
}
if( resultInv != null) result.put( "matchInv", resultInv );
if( resultRev != null) result.put( "matchRev", resultRev );
if( resultContained != null) result.put( "matchCon", resultContained );
if ( result.size() == 0 ) result = null;
}catch ( Exception e ){
result = null;
}
return result;
}
/**
* Returns a new string concatenated by the match area
*
* @param start
* @param end
* @return
*/
private static HashMap concat( String start, String end ) {
HashMap result = null;
int indexOcurrence = -1, overlap = -1;
boolean isSuffix = false;
try {
int endOffset = end.length();
int startOffset = start.length() - end.length();
while ( endOffset > MIN_CHARS_TO_MATCH ) {
--endOffset;
startOffset++;
isSuffix = start.regionMatches(false, startOffset, end, 0, endOffset);
if ( isSuffix ) {
// get the index where the chains match
indexOcurrence = start.lastIndexOf( end.substring( 0, endOffset ) );
overlap = endOffset;
// end the while loop
endOffset = -1;
}
}
if ( indexOcurrence > -1 ) {
result = new HashMap();
result.put( "chain", start.substring( 0, indexOcurrence ).concat( end ) );
result.put( "overlap", overlap );
}
}catch ( Exception e ){
result = null;
}
return result;
}
}
}
|
9239398277e31074204b07876112322eea9af4c1 | 2,620 | java | Java | projects/control-service/projects/pipelines_control_service/src/test/java/com/vmware/taurus/service/graphql/strategy/datajob/JobFieldStrategyBySourceUrlTest.java | alod83/versatile-data-kit | 9ca672d3929eb3dc6fe5c677e8c8a75e2a0d2be8 | [
"Apache-2.0"
] | 100 | 2021-10-04T09:32:04.000Z | 2022-03-30T11:23:53.000Z | projects/control-service/projects/pipelines_control_service/src/test/java/com/vmware/taurus/service/graphql/strategy/datajob/JobFieldStrategyBySourceUrlTest.java | alod83/versatile-data-kit | 9ca672d3929eb3dc6fe5c677e8c8a75e2a0d2be8 | [
"Apache-2.0"
] | 208 | 2021-10-04T16:56:40.000Z | 2022-03-31T10:41:44.000Z | projects/control-service/projects/pipelines_control_service/src/test/java/com/vmware/taurus/service/graphql/strategy/datajob/JobFieldStrategyBySourceUrlTest.java | alod83/versatile-data-kit | 9ca672d3929eb3dc6fe5c677e8c8a75e2a0d2be8 | [
"Apache-2.0"
] | 14 | 2021-10-11T14:15:13.000Z | 2022-03-11T13:39:17.000Z | 38.529412 | 147 | 0.775191 | 998,747 | /*
* Copyright 2021 VMware, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package com.vmware.taurus.service.graphql.strategy.datajob;
import com.vmware.taurus.service.graphql.model.Criteria;
import com.vmware.taurus.service.graphql.model.V2DataJob;
import com.vmware.taurus.service.graphql.model.V2DataJobConfig;
import org.junit.jupiter.api.Test;
import java.util.Comparator;
import java.util.Objects;
import java.util.function.Predicate;
import static org.assertj.core.api.Assertions.assertThat;
class JobFieldStrategyBySourceUrlTest {
private static final String GIT_REPO_URL_RAW = "gitlab.com/taurus/jobs.git";
private static final String GIT_REPO_URL_FORMATTED = "https://gitlab.com/taurus/jobs";
private static final String GIT_REPO_BRANCH = "main";
private final JobFieldStrategyBySourceUrl strategyBySourceUrl = new JobFieldStrategyBySourceUrl(GIT_REPO_URL_RAW, GIT_REPO_BRANCH, true);
@Test
void testJobSourceUrlStrategy_whenGettingStrategyName_shouldBeSpecific() {
assertThat(strategyBySourceUrl.getStrategyName()).isEqualTo(JobFieldStrategyBy.SOURCE_URL);
}
@Test
void testJobSourceUrlStrategy_whenAlteringFieldData_shouldModifyState() {
String jobName = "sample-job";
V2DataJob dataJob = createDummyJob(jobName);
strategyBySourceUrl.alterFieldData(dataJob);
assertThat(dataJob.getConfig().getSourceUrl()).isEqualTo(String.format("%s/-/tree/%s/%s", GIT_REPO_URL_FORMATTED, GIT_REPO_BRANCH, jobName));
}
@Test
void testJobSourceUrlStrategy_whenComputingValidCriteriaWithoutFilter_shouldReturnTheSameCriteria() {
Criteria<V2DataJob> baseCriteria = new Criteria<>(Objects::nonNull, Comparator.comparing(dataJob -> dataJob.getConfig().getDescription()));
Criteria<V2DataJob> v2DataJobCriteria = strategyBySourceUrl.computeFilterCriteria(baseCriteria, null);
assertThat(v2DataJobCriteria.getPredicate()).isEqualTo(baseCriteria.getPredicate());
assertThat(v2DataJobCriteria.getComparator()).isEqualTo(baseCriteria.getComparator());
}
@Test
void testJobSourceUrlStrategy_whenComputingValidSearchProvided_shouldReturnValidPredicate() {
Predicate<V2DataJob> predicate = strategyBySourceUrl.computeSearchCriteria("sample-job");
V2DataJob a = createDummyJob("sample-job");
assertThat(predicate.test(a)).isFalse(); // always false cause its empty
}
private V2DataJob createDummyJob(String jobName) {
V2DataJob job = new V2DataJob();
job.setJobName(jobName);
V2DataJobConfig config = new V2DataJobConfig();
job.setConfig(config);
return job;
}
}
|
92393a07f1ef4b994de0719ba737c3086c054703 | 16,532 | java | Java | backend/manager/modules/extensions-manager/src/main/java/org/ovirt/engine/core/extensions/mgr/ExtensionsManager.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 347 | 2015-01-20T14:13:21.000Z | 2022-03-31T17:53:11.000Z | backend/manager/modules/extensions-manager/src/main/java/org/ovirt/engine/core/extensions/mgr/ExtensionsManager.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 128 | 2015-05-22T19:14:32.000Z | 2022-03-31T08:11:18.000Z | backend/manager/modules/extensions-manager/src/main/java/org/ovirt/engine/core/extensions/mgr/ExtensionsManager.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 202 | 2015-01-04T06:20:49.000Z | 2022-03-08T15:30:08.000Z | 42.829016 | 200 | 0.567445 | 998,748 | package org.ovirt.engine.core.extensions.mgr;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is responsible for loading the required {@code Configuration} in order to create an extension. It holds
* the logic of ordering and solving conflicts during loading the configuration
*/
public class ExtensionsManager extends Observable {
private static final Logger log = LoggerFactory.getLogger(ExtensionsManager.class);
private static final Logger traceLog = LoggerFactory.getLogger(ExtensionsManager.class.getName() + ".trace");
public static final ExtKey TRACE_LOG_CONTEXT_KEY = new ExtKey("EXTENSION_MANAGER_TRACE_LOG",
Logger.class,
"863db666-3ea7-4751-9695-918a3197ad83");
public static final ExtKey CAUSE_OUTPUT_KEY = new ExtKey("EXTENSION_MANAGER_CAUSE_OUTPUT_KEY", Throwable.class, "894e1c86-518b-40a2-a92b-29ea1eb0403d");
private static interface BindingsLoader {
ExtensionProxy load(Properties props) throws Exception;
}
private static class JBossBindingsLoader implements BindingsLoader {
private Map<String, Module> loadedModules = new HashMap<>();
private Module loadModule(String moduleSpec) {
// If the module was not already loaded, load it
try {
Module module = loadedModules.get(moduleSpec);
if (module == null) {
ModuleLoader loader = ModuleLoader.forClass(this.getClass());
if (loader == null) {
throw new ConfigurationException(String.format("The module '%1$s' cannot be loaded as the module system isn't enabled.",
moduleSpec));
}
module = loader.loadModule(ModuleIdentifier.fromString(moduleSpec));
loadedModules.put(moduleSpec, module);
}
return module;
} catch (ModuleLoadException exception) {
throw new ConfigurationException(String.format("The module '%1$s' cannot be loaded: %2$s", moduleSpec, exception.getMessage()),
exception);
}
}
private <T extends Class> T lookupService(Module module, T serviceInterface, String serviceClassName) {
T serviceClass = null;
for (Object service : module.loadService(serviceInterface)) {
if (service.getClass().getName().equals(serviceClassName)) {
serviceClass = (T)service.getClass();
break;
}
}
if (serviceClass == null) {
throw new ConfigurationException(String.format("The module '%1$s' does not contain the service '%2$s'.",
module.getIdentifier().getName(),
serviceClassName));
}
return serviceClass;
}
public ExtensionProxy load(Properties props) throws Exception {
Module module = loadModule(
props.getProperty(Base.ConfigKeys.BINDINGS_JBOSSMODULE_MODULE)
);
return new ExtensionProxy(
module.getClassLoader(),
lookupService(
module,
Extension.class,
props.getProperty(Base.ConfigKeys.BINDINGS_JBOSSMODULE_CLASS)
).newInstance()
);
}
}
private static class ExtensionEntry {
private static int extensionNameIndex = 0;
private String name;
private File file;
private boolean enabled;
private boolean initialized;
private ExtensionProxy extension;
private ExtensionEntry(Properties props, File file) {
this.file = file;
this.name = props.getProperty(
Base.ConfigKeys.NAME,
String.format("__unamed_%1$03d__", extensionNameIndex++)
);
this.enabled = Boolean.valueOf(props.getProperty(Base.ConfigKeys.ENABLED, "true"));
}
private String getFileName() {
return file != null ? file.getAbsolutePath() : "N/A";
}
}
private static final Map<String, BindingsLoader> bindingsLoaders = new HashMap<>();
static {
bindingsLoaders.put(Base.ConfigBindingsMethods.JBOSSMODULE, new JBossBindingsLoader());
}
private ConcurrentMap<String, ExtensionEntry> loadedEntries = new ConcurrentHashMap<>();
private ConcurrentMap<String, ExtensionEntry> initializedEntries = new ConcurrentHashMap<>();
private final ExtMap globalContext = new ExtMap().mput(Base.GlobalContextKeys.EXTENSIONS, new ArrayList<ExtMap>());
public String load(Properties configuration) {
return loadImpl(configuration, null);
}
public String load(File file) {
try (
InputStream is = new FileInputStream(file);
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)
) {
Properties props = new Properties();
props.load(reader);
return loadImpl(props, file);
} catch (IOException exception) {
throw new ConfigurationException(String.format("Can't load object configuration file '%1$s': %2$s",
file.getAbsolutePath(), exception.getMessage()), exception);
}
}
private void dumpConfig(ExtensionProxy extension) {
Logger traceLogger = extension.getContext().get(TRACE_LOG_CONTEXT_KEY);
if (traceLogger.isDebugEnabled()) {
Collection sensitive = extension.getContext().get(Base.ContextKeys.CONFIGURATION_SENSITIVE_KEYS);
traceLogger.debug("Config BEGIN");
for (Map.Entry<Object, Object> entry : extension.getContext().<Properties>get(Base.ContextKeys.CONFIGURATION).entrySet()) {
traceLogger.debug(
String.format(
"%s: %s",
entry.getKey(),
sensitive.contains(entry.getKey()) ? "***" : entry.getValue()
)
);
}
traceLogger.debug("Config END");
}
}
private Collection<String> splitString(String s) {
return new ArrayList<>(Arrays.asList(s.trim().split("\\s*,\\s*", 0)));
}
private synchronized String loadImpl(Properties props, File confFile) {
ExtensionEntry entry = new ExtensionEntry(props, confFile);
if (!entry.enabled) {
return null;
}
ExtensionEntry alreadyLoadedEntry = loadedEntries.get(entry.name);
if (alreadyLoadedEntry != null) {
throw new ConfigurationException(String.format(
"Could not load the configuration '%1$s' from file %2$s. A configuration with the same name was already loaded from file %3$s",
entry.name,
entry.getFileName(),
alreadyLoadedEntry.getFileName()
));
}
try {
entry.extension = loadExtension(props);
entry.extension.getContext().mput(
Base.ContextKeys.GLOBAL_CONTEXT,
globalContext
).mput(
TRACE_LOG_CONTEXT_KEY,
traceLog
).mput(
Base.ContextKeys.INTERFACE_VERSION_MIN,
0
).mput(
Base.ContextKeys.INTERFACE_VERSION_MAX,
Base.INTERFACE_VERSION_CURRENT
).mput(
Base.ContextKeys.LOCALE,
Locale.getDefault().toString()
).mput(
Base.ContextKeys.CONFIGURATION_FILE,
entry.file == null ? null : entry.file.getAbsolutePath()
).mput(
Base.ContextKeys.CONFIGURATION,
props
).mput(
Base.ContextKeys.CONFIGURATION_SENSITIVE_KEYS,
splitString(props.getProperty(Base.ConfigKeys.SENSITIVE_KEYS, ""))
).mput(
Base.ContextKeys.INSTANCE_NAME,
entry.name
).mput(
Base.ContextKeys.PROVIDES,
splitString(props.getProperty(Base.ConfigKeys.PROVIDES, ""))
);
log.info("Loading extension '{}'", entry.name);
ExtMap output = entry.extension.invoke(
new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Base.InvokeCommands.LOAD
)
);
log.info("Extension '{}' loaded", entry.name);
entry.extension.getContext().put(
TRACE_LOG_CONTEXT_KEY,
LoggerFactory.getLogger(
String.format(
"%1$s.%2$s.%3$s",
traceLog.getName(),
entry.extension.getContext().get(Base.ContextKeys.EXTENSION_NAME),
entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME)
)
)
);
if (output.<Integer>get(Base.InvokeKeys.RESULT) != Base.InvokeResult.SUCCESS) {
throw new RuntimeException(
String.format("Invoke of LOAD returned with error code: %1$s",
output.<Integer>get(Base.InvokeKeys.RESULT)
)
);
}
} catch (Exception e) {
throw new RuntimeException(String.format("Error loading extension '%1$s': %2$s", entry.name, e.getMessage()), e);
}
loadedEntries.put(entry.name, entry);
dumpConfig(entry.extension);
setChanged();
notifyObservers();
return entry.name;
}
public ExtMap getGlobalContext() {
return globalContext;
}
public List<ExtensionProxy> getExtensionsByService(String provides) {
List<ExtensionProxy> results = new ArrayList<>();
for (ExtensionEntry entry : initializedEntries.values()) {
if (entry.extension.getContext().<Collection<String>> get(Base.ContextKeys.PROVIDES).contains(provides)) {
results.add(entry.extension);
}
}
return results;
}
public ExtensionProxy getExtensionByName(String name) throws ConfigurationException {
if (name == null) {
throw new ConfigurationException("Extension was not specified");
}
ExtensionEntry entry = initializedEntries.get(name);
if (entry == null) {
throw new ConfigurationException(String.format("Extension %1$s could not be found", name));
}
return entry.extension;
}
public List<ExtensionProxy> getLoadedExtensions() {
List<ExtensionProxy> results = new ArrayList<>(loadedEntries.size());
for (ExtensionEntry entry : loadedEntries.values()) {
results.add(entry.extension);
}
return results;
}
public List<ExtensionProxy> getExtensions() {
List<ExtensionProxy> results = new ArrayList<>(initializedEntries.size());
for (ExtensionEntry entry : initializedEntries.values()) {
results.add(entry.extension);
}
return results;
}
public ExtensionProxy initialize(String extensionName) {
ExtensionEntry entry = loadedEntries.get(extensionName);
if (entry == null) {
throw new RuntimeException(String.format("No extensioned with instance name %1$s could be found",
extensionName));
}
try {
log.info("Initializing extension '{}'", entry.name);
entry.extension.invoke(new ExtMap().mput(Base.InvokeKeys.COMMAND, Base.InvokeCommands.INITIALIZE));
log.info("Extension '{}' initialized", entry.name);
} catch (Exception ex) {
log.error("Error in activating extension '{}': {}", entry.name, ex.getMessage());
if (log.isDebugEnabled()) {
log.debug(ex.toString(), ex);
}
throw new RuntimeException(ex);
}
entry.initialized = true;
initializedEntries.put(extensionName, entry);
synchronized (globalContext) {
globalContext.<Collection<ExtMap>> get(Base.GlobalContextKeys.EXTENSIONS).add(
new ExtMap().mput(
Base.ExtensionRecord.INSTANCE_NAME,
entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME)
).mput(
Base.ExtensionRecord.PROVIDES,
entry.extension.getContext().get(Base.ContextKeys.PROVIDES)
).mput(
Base.ExtensionRecord.CLASS_LOADER,
entry.extension.getClassLoader()
).mput(
Base.ExtensionRecord.EXTENSION,
entry.extension.getExtension()
).mput(
Base.ExtensionRecord.CONTEXT,
entry.extension.getContext()
)
);
}
setChanged();
notifyObservers();
return entry.extension;
}
private ExtensionProxy loadExtension(Properties props) throws Exception {
BindingsLoader loader = bindingsLoaders.get(props.getProperty(Base.ConfigKeys.BINDINGS_METHOD));
if (loader == null) {
throw new ConfigurationException(String.format("Invalid binding method '%1$s'.",
props.getProperty(Base.ConfigKeys.BINDINGS_METHOD)));
}
return loader.load(props);
}
public void dump() {
log.info("Start of enabled extensions list");
for (ExtensionEntry entry : loadedEntries.values()) {
if (entry.extension != null) {
ExtMap context = entry.extension.getContext();
log.info("Instance name: '{}', Extension name: '{}', Version: '{}', Notes: '{}', License: '{}', Home: '{}', Author '{}', Build interface Version: '{}', File: '{}', Initialized: '{}'",
emptyIfNull(context.get(Base.ContextKeys.INSTANCE_NAME)),
emptyIfNull(context.get(Base.ContextKeys.EXTENSION_NAME)),
emptyIfNull(context.get(Base.ContextKeys.VERSION)),
emptyIfNull(context.get(Base.ContextKeys.EXTENSION_NOTES)),
emptyIfNull(context.get(Base.ContextKeys.LICENSE)),
emptyIfNull(context.get(Base.ContextKeys.HOME_URL)),
emptyIfNull(context.get(Base.ContextKeys.AUTHOR)),
emptyIfNull(context.get(Base.ContextKeys.BUILD_INTERFACE_VERSION)),
entry.getFileName(),
entry.initialized
);
}
}
log.info("End of enabled extensions list");
}
private Object emptyIfNull(Object value) {
return value == null ? "" : value;
}
}
|
92393a89510e5d85b19590178583ceda6444ce78 | 48,543 | java | Java | sdk/mediaservices/azure-resourcemanager-mediaservices/src/main/java/com/azure/resourcemanager/mediaservices/implementation/StreamingPoliciesClientImpl.java | alexbuckgit/azure-sdk-for-java | 622f39c5b5dea4a26ffcf3d9ea0b46ae6b8e809a | [
"MIT"
] | 1 | 2022-01-08T06:43:30.000Z | 2022-01-08T06:43:30.000Z | sdk/mediaservices/azure-resourcemanager-mediaservices/src/main/java/com/azure/resourcemanager/mediaservices/implementation/StreamingPoliciesClientImpl.java | alexbuckgit/azure-sdk-for-java | 622f39c5b5dea4a26ffcf3d9ea0b46ae6b8e809a | [
"MIT"
] | null | null | null | sdk/mediaservices/azure-resourcemanager-mediaservices/src/main/java/com/azure/resourcemanager/mediaservices/implementation/StreamingPoliciesClientImpl.java | alexbuckgit/azure-sdk-for-java | 622f39c5b5dea4a26ffcf3d9ea0b46ae6b8e809a | [
"MIT"
] | null | null | null | 50.147727 | 120 | 0.649074 | 998,749 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.mediaservices.implementation;
import com.azure.core.annotation.BodyParam;
import com.azure.core.annotation.Delete;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.Put;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.resourcemanager.mediaservices.fluent.StreamingPoliciesClient;
import com.azure.resourcemanager.mediaservices.fluent.models.StreamingPolicyInner;
import com.azure.resourcemanager.mediaservices.models.StreamingPolicyCollection;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in StreamingPoliciesClient. */
public final class StreamingPoliciesClientImpl implements StreamingPoliciesClient {
/** The proxy service used to perform REST calls. */
private final StreamingPoliciesService service;
/** The service client containing this operation class. */
private final AzureMediaServicesImpl client;
/**
* Initializes an instance of StreamingPoliciesClientImpl.
*
* @param client the instance of the service client containing this operation class.
*/
StreamingPoliciesClientImpl(AzureMediaServicesImpl client) {
this.service =
RestProxy.create(StreamingPoliciesService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for AzureMediaServicesStreamingPolicies to be used by the proxy service
* to perform REST calls.
*/
@Host("{$host}")
@ServiceInterface(name = "AzureMediaServicesSt")
private interface StreamingPoliciesService {
@Headers({"Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices"
+ "/{accountName}/streamingPolicies")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<StreamingPolicyCollection>> list(
@HostParam("$host") String endpoint,
@PathParam("subscriptionId") String subscriptionId,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("accountName") String accountName,
@QueryParam("api-version") String apiVersion,
@QueryParam("$filter") String filter,
@QueryParam("$top") Integer top,
@QueryParam("$orderby") String orderby,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices"
+ "/{accountName}/streamingPolicies/{streamingPolicyName}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<StreamingPolicyInner>> get(
@HostParam("$host") String endpoint,
@PathParam("subscriptionId") String subscriptionId,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("accountName") String accountName,
@PathParam("streamingPolicyName") String streamingPolicyName,
@QueryParam("api-version") String apiVersion,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Put(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices"
+ "/{accountName}/streamingPolicies/{streamingPolicyName}")
@ExpectedResponses({201})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<StreamingPolicyInner>> create(
@HostParam("$host") String endpoint,
@PathParam("subscriptionId") String subscriptionId,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("accountName") String accountName,
@PathParam("streamingPolicyName") String streamingPolicyName,
@QueryParam("api-version") String apiVersion,
@BodyParam("application/json") StreamingPolicyInner parameters,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Delete(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices"
+ "/{accountName}/streamingPolicies/{streamingPolicyName}")
@ExpectedResponses({200, 204})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Void>> delete(
@HostParam("$host") String endpoint,
@PathParam("subscriptionId") String subscriptionId,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("accountName") String accountName,
@PathParam("streamingPolicyName") String streamingPolicyName,
@QueryParam("api-version") String apiVersion,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<StreamingPolicyCollection>> listNext(
@PathParam(value = "nextLink", encoded = true) String nextLink,
@HostParam("$host") String endpoint,
@HeaderParam("Accept") String accept,
Context context);
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param filter Restricts the set of items returned.
* @param top Specifies a non-negative integer n that limits the number of items returned from a collection. The
* service returns the number of available items up to but not greater than the specified value n.
* @param orderby Specifies the key by which the result collection should be ordered.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items along with {@link PagedResponse} on successful completion of {@link
* Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<StreamingPolicyInner>> listSinglePageAsync(
String resourceGroupName, String accountName, String filter, Integer top, String orderby) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.list(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
apiVersion,
filter,
top,
orderby,
accept,
context))
.<PagedResponse<StreamingPolicyInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().odataNextLink(),
null))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param filter Restricts the set of items returned.
* @param top Specifies a non-negative integer n that limits the number of items returned from a collection. The
* service returns the number of available items up to but not greater than the specified value n.
* @param orderby Specifies the key by which the result collection should be ordered.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items along with {@link PagedResponse} on successful completion of {@link
* Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<StreamingPolicyInner>> listSinglePageAsync(
String resourceGroupName, String accountName, String filter, Integer top, String orderby, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.list(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
apiVersion,
filter,
top,
orderby,
accept,
context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().odataNextLink(),
null));
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param filter Restricts the set of items returned.
* @param top Specifies a non-negative integer n that limits the number of items returned from a collection. The
* service returns the number of available items up to but not greater than the specified value n.
* @param orderby Specifies the key by which the result collection should be ordered.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items as paginated response with {@link PagedFlux}.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<StreamingPolicyInner> listAsync(
String resourceGroupName, String accountName, String filter, Integer top, String orderby) {
return new PagedFlux<>(
() -> listSinglePageAsync(resourceGroupName, accountName, filter, top, orderby),
nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items as paginated response with {@link PagedFlux}.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<StreamingPolicyInner> listAsync(String resourceGroupName, String accountName) {
final String filter = null;
final Integer top = null;
final String orderby = null;
return new PagedFlux<>(
() -> listSinglePageAsync(resourceGroupName, accountName, filter, top, orderby),
nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param filter Restricts the set of items returned.
* @param top Specifies a non-negative integer n that limits the number of items returned from a collection. The
* service returns the number of available items up to but not greater than the specified value n.
* @param orderby Specifies the key by which the result collection should be ordered.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items as paginated response with {@link PagedFlux}.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<StreamingPolicyInner> listAsync(
String resourceGroupName, String accountName, String filter, Integer top, String orderby, Context context) {
return new PagedFlux<>(
() -> listSinglePageAsync(resourceGroupName, accountName, filter, top, orderby, context),
nextLink -> listNextSinglePageAsync(nextLink, context));
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items as paginated response with {@link PagedIterable}.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<StreamingPolicyInner> list(String resourceGroupName, String accountName) {
final String filter = null;
final Integer top = null;
final String orderby = null;
return new PagedIterable<>(listAsync(resourceGroupName, accountName, filter, top, orderby));
}
/**
* Lists the Streaming Policies in the account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param filter Restricts the set of items returned.
* @param top Specifies a non-negative integer n that limits the number of items returned from a collection. The
* service returns the number of available items up to but not greater than the specified value n.
* @param orderby Specifies the key by which the result collection should be ordered.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items as paginated response with {@link PagedIterable}.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<StreamingPolicyInner> list(
String resourceGroupName, String accountName, String filter, Integer top, String orderby, Context context) {
return new PagedIterable<>(listAsync(resourceGroupName, accountName, filter, top, orderby, context));
}
/**
* Get the details of a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the details of a Streaming Policy in the Media Services account along with {@link Response} on successful
* completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<StreamingPolicyInner>> getWithResponseAsync(
String resourceGroupName, String accountName, String streamingPolicyName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
if (streamingPolicyName == null) {
return Mono
.error(new IllegalArgumentException("Parameter streamingPolicyName is required and cannot be null."));
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.get(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
streamingPolicyName,
apiVersion,
accept,
context))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Get the details of a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the details of a Streaming Policy in the Media Services account along with {@link Response} on successful
* completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<StreamingPolicyInner>> getWithResponseAsync(
String resourceGroupName, String accountName, String streamingPolicyName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
if (streamingPolicyName == null) {
return Mono
.error(new IllegalArgumentException("Parameter streamingPolicyName is required and cannot be null."));
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.get(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
streamingPolicyName,
apiVersion,
accept,
context);
}
/**
* Get the details of a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the details of a Streaming Policy in the Media Services account on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<StreamingPolicyInner> getAsync(
String resourceGroupName, String accountName, String streamingPolicyName) {
return getWithResponseAsync(resourceGroupName, accountName, streamingPolicyName)
.flatMap(
(Response<StreamingPolicyInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Get the details of a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the details of a Streaming Policy in the Media Services account.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public StreamingPolicyInner get(String resourceGroupName, String accountName, String streamingPolicyName) {
return getAsync(resourceGroupName, accountName, streamingPolicyName).block();
}
/**
* Get the details of a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the details of a Streaming Policy in the Media Services account along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<StreamingPolicyInner> getWithResponse(
String resourceGroupName, String accountName, String streamingPolicyName, Context context) {
return getWithResponseAsync(resourceGroupName, accountName, streamingPolicyName, context).block();
}
/**
* Create a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param parameters The request parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a Streaming Policy resource along with {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<StreamingPolicyInner>> createWithResponseAsync(
String resourceGroupName, String accountName, String streamingPolicyName, StreamingPolicyInner parameters) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
if (streamingPolicyName == null) {
return Mono
.error(new IllegalArgumentException("Parameter streamingPolicyName is required and cannot be null."));
}
if (parameters == null) {
return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
} else {
parameters.validate();
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.create(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
streamingPolicyName,
apiVersion,
parameters,
accept,
context))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Create a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param parameters The request parameters.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a Streaming Policy resource along with {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<StreamingPolicyInner>> createWithResponseAsync(
String resourceGroupName,
String accountName,
String streamingPolicyName,
StreamingPolicyInner parameters,
Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
if (streamingPolicyName == null) {
return Mono
.error(new IllegalArgumentException("Parameter streamingPolicyName is required and cannot be null."));
}
if (parameters == null) {
return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
} else {
parameters.validate();
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.create(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
streamingPolicyName,
apiVersion,
parameters,
accept,
context);
}
/**
* Create a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param parameters The request parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a Streaming Policy resource on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<StreamingPolicyInner> createAsync(
String resourceGroupName, String accountName, String streamingPolicyName, StreamingPolicyInner parameters) {
return createWithResponseAsync(resourceGroupName, accountName, streamingPolicyName, parameters)
.flatMap(
(Response<StreamingPolicyInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Create a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param parameters The request parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a Streaming Policy resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public StreamingPolicyInner create(
String resourceGroupName, String accountName, String streamingPolicyName, StreamingPolicyInner parameters) {
return createAsync(resourceGroupName, accountName, streamingPolicyName, parameters).block();
}
/**
* Create a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param parameters The request parameters.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a Streaming Policy resource along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<StreamingPolicyInner> createWithResponse(
String resourceGroupName,
String accountName,
String streamingPolicyName,
StreamingPolicyInner parameters,
Context context) {
return createWithResponseAsync(resourceGroupName, accountName, streamingPolicyName, parameters, context)
.block();
}
/**
* Deletes a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Void>> deleteWithResponseAsync(
String resourceGroupName, String accountName, String streamingPolicyName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
if (streamingPolicyName == null) {
return Mono
.error(new IllegalArgumentException("Parameter streamingPolicyName is required and cannot be null."));
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.delete(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
streamingPolicyName,
apiVersion,
accept,
context))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Deletes a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Void>> deleteWithResponseAsync(
String resourceGroupName, String accountName, String streamingPolicyName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (accountName == null) {
return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));
}
if (streamingPolicyName == null) {
return Mono
.error(new IllegalArgumentException("Parameter streamingPolicyName is required and cannot be null."));
}
final String apiVersion = "2021-11-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.delete(
this.client.getEndpoint(),
this.client.getSubscriptionId(),
resourceGroupName,
accountName,
streamingPolicyName,
apiVersion,
accept,
context);
}
/**
* Deletes a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return A {@link Mono} that completes when a successful response is received.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Void> deleteAsync(String resourceGroupName, String accountName, String streamingPolicyName) {
return deleteWithResponseAsync(resourceGroupName, accountName, streamingPolicyName)
.flatMap((Response<Void> res) -> Mono.empty());
}
/**
* Deletes a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(String resourceGroupName, String accountName, String streamingPolicyName) {
deleteAsync(resourceGroupName, accountName, streamingPolicyName).block();
}
/**
* Deletes a Streaming Policy in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param streamingPolicyName The Streaming Policy name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> deleteWithResponse(
String resourceGroupName, String accountName, String streamingPolicyName, Context context) {
return deleteWithResponseAsync(resourceGroupName, accountName, streamingPolicyName, context).block();
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items along with {@link PagedResponse} on successful completion of {@link
* Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<StreamingPolicyInner>> listNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context))
.<PagedResponse<StreamingPolicyInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().odataNextLink(),
null))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of StreamingPolicy items along with {@link PagedResponse} on successful completion of {@link
* Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<StreamingPolicyInner>> listNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.listNext(nextLink, this.client.getEndpoint(), accept, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().odataNextLink(),
null));
}
}
|
92393a8c05844296de87229e14f00dfea2f1ad71 | 2,485 | java | Java | src/main/java/com/dotcms/system/event/local/business/LocalSystemEventsAPI.java | ncodeitbharath/gradle | e1b40495088d0233933756b788bb0ea98a347d70 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/dotcms/system/event/local/business/LocalSystemEventsAPI.java | ncodeitbharath/gradle | e1b40495088d0233933756b788bb0ea98a347d70 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/dotcms/system/event/local/business/LocalSystemEventsAPI.java | ncodeitbharath/gradle | e1b40495088d0233933756b788bb0ea98a347d70 | [
"Apache-2.0"
] | null | null | null | 32.272727 | 131 | 0.692555 | 998,750 | package com.dotcms.system.event.local.business;
import com.dotcms.system.event.local.model.DefaultOrphanEventSubscriber;
import com.dotcms.system.event.local.model.EventSubscriber;
import com.dotcms.system.event.local.type.OrphanEvent;
/**
* A local system event allows to add classes, annotated by Subscriber annotation.
* The method must have just one parameter that will be the Event Type, when this event type is notified, all class subscribed will
* be triggered.
* @author jsanca
*/
public interface LocalSystemEventsAPI {
/**
* Do the subscription of all methods annotated with Subscriber.
* The method must have just one parameter which is the event to be received when the notification is triggered.
* @param subscriber
*/
void subscribe (Object subscriber);
/**
* Do the subscription for an event
* @param eventType {@link Class} eventType
* @param subscriber {@link EventSubscriber}
*/
void subscribe(Class<?> eventType, EventSubscriber subscriber);
/**
* Unsubscribes all the {@link EventSubscriber} related to eventType.
* @param eventType {@link Class}
*/
boolean unsubscribe (Class<?> eventType);
/**
* Unsubscribes all methods annotated with Subscriber.
* @param subscriber {@link Object}
*/
boolean unsubscribe (Object subscriber);
/**
* Unsubscribes a specific subscriber
* @param eventType {@link Class}
* @param subscriberId {@link String}
*/
boolean unsubscribe (final Class<?> eventType, String subscriberId);
/**
* Creates an async notification to all registered handlers
* @param event {@link Object}
*/
void asyncNotify (Object event);
/**
* Creates a sync notification to all registered handlers.
* @param event
*/
public void notify(final Object event);
/**
* Finds the subscriber
* @param eventType {@link Class}
* @param subscriberId {@link String}
* @return EventSubscriber
*/
EventSubscriber findSubscriber (final Class<?> eventType, String subscriberId);
/**
* Sets the Event Subscriber for the Orphan Events (events with not subscriber associated)
* By default the subscriber is {@link DefaultOrphanEventSubscriber}
*
* @param orphanEventSubscriber {@link EventSubscriber}
*/
void setOrphanEventSubscriber (EventSubscriber<OrphanEvent> orphanEventSubscriber);
} // E:O:F:LocalSystemEventsAPI.
|
92393b73761a0c6608d92b13bb6c9b90640f6244 | 2,033 | java | Java | Source/Plugins/Core/com.equella.serverbase/src/com/tle/core/dao/AbstractTreeDao.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 14 | 2019-10-09T23:59:32.000Z | 2022-03-01T08:34:56.000Z | Source/Plugins/Core/com.equella.serverbase/src/com/tle/core/dao/AbstractTreeDao.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 1,549 | 2019-08-16T01:07:16.000Z | 2022-03-31T23:57:34.000Z | Source/Plugins/Core/com.equella.serverbase/src/com/tle/core/dao/AbstractTreeDao.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 24 | 2019-09-05T00:09:35.000Z | 2021-10-19T05:10:39.000Z | 33.327869 | 98 | 0.747664 | 998,751 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.core.dao;
import com.tle.common.institution.TreeNodeInterface;
import com.tle.core.hibernate.dao.GenericDao;
import java.util.List;
/** @author Nicholas Read */
public interface AbstractTreeDao<T extends TreeNodeInterface<T>> extends GenericDao<T, Long> {
void updateWithNoParentChange(T entity);
void delete(T node, DeleteAction<T> action);
List<T> getRootNodes(String orderBy);
List<T> getChildrenForNode(T node, String orderBy);
List<Long> getChildrenIdsForNodeId(long nodeId, String orderBy);
List<T> getAllSubnodeForNode(T node);
int countRootNodes();
int countSubnodesForNode(T node);
List<T> listAll();
/**
* Lists node IDs in top-down order. The only ordering guarantee is that a node is guaranteed to
* show before any node with more parents. For example, all the root nodes are guaranteed to be
* before any of the first level nodes, which are all guaranteed to be before any second level
* nodes, and so on. Nodes at the same depth but from different parents may be mixed together.
*/
List<Long> listIdsInOrder();
List<Long> enumerateIdsInOrder();
void deleteInOrder(Long node);
interface DeleteAction<T> {
void beforeDelete(T node);
}
}
|
92393bcd674b3f11fcd1149723e09127920068e3 | 847 | java | Java | akkad-war3/war3-web/src/main/java/xyz/wongs/weathertop/war3/system/entity/SysMenu.java | rothschil/Shumer | ccabb5bca4f2f67fae51c0e6d48fcf56b6a6e25d | [
"MIT"
] | 262 | 2019-11-11T10:54:05.000Z | 2022-03-20T13:18:34.000Z | akkad-war3/war3-web/src/main/java/xyz/wongs/weathertop/war3/system/entity/SysMenu.java | rothschil/Shumer | ccabb5bca4f2f67fae51c0e6d48fcf56b6a6e25d | [
"MIT"
] | 4 | 2020-01-14T03:03:35.000Z | 2021-04-23T01:53:56.000Z | akkad-war3/war3-web/src/main/java/xyz/wongs/weathertop/war3/system/entity/SysMenu.java | rothschil/Shumer | ccabb5bca4f2f67fae51c0e6d48fcf56b6a6e25d | [
"MIT"
] | 179 | 2019-10-31T11:47:16.000Z | 2022-03-18T06:18:46.000Z | 17.285714 | 71 | 0.711924 | 998,752 | package xyz.wongs.weathertop.war3.system.entity;
import lombok.Data;
import xyz.wongs.weathertop.base.persistence.mybatis.entity.BaseEntity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Data
public class SysMenu extends BaseEntity<Long> {
private Long id;
private String menuName;
/** 父菜单名称 */
private String parentName;
private Long parentId;
private Integer orderNum;
private String url;
private String target;
private String menuType;
private String visible;
private String perms;
private String icon;
private String createBy;
private Date createTime;
private String updateBy;
private Date updateTime;
private String remark;
/** 子菜单 */
private List<SysMenu> children = new ArrayList<SysMenu>();
} |
92393c1bdd42e2a8290dd71197ab5986f8d8b887 | 1,178 | java | Java | chapter_002/src/main/java/ru/avelikorechin/chess/figures/Figure.java | Mofin52/java_education | 299782a34a89f199b148d204efc233a963589a8b | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/avelikorechin/chess/figures/Figure.java | Mofin52/java_education | 299782a34a89f199b148d204efc233a963589a8b | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/avelikorechin/chess/figures/Figure.java | Mofin52/java_education | 299782a34a89f199b148d204efc233a963589a8b | [
"Apache-2.0"
] | null | null | null | 24.541667 | 74 | 0.651952 | 998,753 | package ru.avelikorechin.chess.figures;
import ru.avelikorechin.chess.Cell;
import ru.avelikorechin.chess.exceptions.ImpossibleMoveException;
/**
* Abstract figure for chess game.
* @author Alexander Velikorechin
* @since 08.04.2017
*/
public abstract class Figure {
/**
* Initial position of figure.
*/
private final Cell position;
/**
* Constructor for figure.
* @param position initial position of figure.
*/
public Figure(Cell position) {
this.position = position;
}
/**
* Method checks whether figure can move along the given path.
* @param dist designated point
* @return array of cells figure must pass to arrive the destination
* @throws ImpossibleMoveException if figure cant' go along this way
*/
public abstract Cell[] way(Cell dist) throws ImpossibleMoveException;
/**
* Writes figure to the new cell.
* @param dist new cell
* @return new figure on new cell
*/
public abstract Figure clone(Cell dist);
/**
* Getter for position.
* @return position
*/
public Cell getPosition() {
return this.position;
}
}
|
92393c2e2df2136fec6b311d3870728091dfef24 | 449 | java | Java | subprojects/docs/src/snippets/plugins/readOnlyManagedProperty/groovy/buildSrc/src/main/java/Download.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 19 | 2020-06-04T07:46:20.000Z | 2022-03-23T01:46:40.000Z | subprojects/docs/src/snippets/plugins/readOnlyManagedProperty/groovy/buildSrc/src/main/java/Download.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 15 | 2020-06-11T09:38:15.000Z | 2022-01-04T16:04:53.000Z | subprojects/docs/src/snippets/plugins/readOnlyManagedProperty/groovy/buildSrc/src/main/java/Download.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 4 | 2020-11-24T11:03:19.000Z | 2022-02-28T07:21:23.000Z | 23.631579 | 60 | 0.690423 | 998,754 | import org.gradle.api.DefaultTask;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import java.net.URI;
public abstract class Download extends DefaultTask {
// Use an abstract getter method
@Input
abstract Property<URI> getUri();
@TaskAction
void run() {
// Use the `uri` property
System.out.println("Downloading " + getUri().get());
}
}
|
92393ce074f8a43b82015305e67bd8fee0c2a302 | 692 | java | Java | experimental/coach/ideal/showcase/coach/forms/html_text.java | mishadynin/ideal | a512796201e6e26ea750e31561e4c709b55cf268 | [
"BSD-3-Clause"
] | null | null | null | experimental/coach/ideal/showcase/coach/forms/html_text.java | mishadynin/ideal | a512796201e6e26ea750e31561e4c709b55cf268 | [
"BSD-3-Clause"
] | null | null | null | experimental/coach/ideal/showcase/coach/forms/html_text.java | mishadynin/ideal | a512796201e6e26ea750e31561e4c709b55cf268 | [
"BSD-3-Clause"
] | null | null | null | 25.62963 | 62 | 0.74711 | 998,755 | /*
* Copyright 2014-2020 The Ideal Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
package ideal.showcase.coach.forms;
import ideal.library.elements.*;
import ideal.library.texts.*;
import ideal.runtime.elements.*;
import ideal.runtime.reflections.*;
public class html_text implements widget {
public final text_fragment the_text;
public html_text(text_fragment the_text) {
this.the_text = the_text;
}
@Override
public <R> R accept(widget_visitor<R> the_visitor) {
return the_visitor.visit_html_text(this);
}
}
|
92393e81210125d874981f5daed02d22a31f9aa7 | 274 | java | Java | autodata-compiler/src/test/resources/builder/inputs/Empty.java | evant/autodata | 2bf0e149ee0f10d4fb9da6dcf620c58bdcc45777 | [
"Apache-2.0"
] | 2 | 2015-05-02T12:58:56.000Z | 2016-03-05T15:31:06.000Z | autodata-compiler/src/test/resources/builder/inputs/Empty.java | evant/autodata | 2bf0e149ee0f10d4fb9da6dcf620c58bdcc45777 | [
"Apache-2.0"
] | 9 | 2015-04-22T03:06:08.000Z | 2015-05-06T00:28:26.000Z | autodata-compiler/src/test/resources/builder/inputs/Empty.java | evant/autodata | 2bf0e149ee0f10d4fb9da6dcf620c58bdcc45777 | [
"Apache-2.0"
] | null | null | null | 22.833333 | 47 | 0.740876 | 998,756 | import me.tatarka.autodata.base.AutoData;
import me.tatarka.autodata.plugins.AutoBuilder;
@AutoData(defaults = false)
@AutoBuilder
public abstract class Empty {
@AutoData.Builder
public static abstract class Builder {
public abstract Empty build();
}
}
|
92393f7ec5d72204f4101aac7af75b988a93c50c | 5,816 | java | Java | ledgers-middleware/ledgers-middleware-rest-server/src/main/java/de/adorsys/ledgers/middleware/rest/resource/AdminResource.java | golden-dimension/ledgers | 9aa685c57ae9ffd35e7679bea7a1e13e40c9e086 | [
"Apache-2.0"
] | 25 | 2018-11-14T14:22:24.000Z | 2022-03-24T14:02:37.000Z | ledgers-middleware/ledgers-middleware-rest-server/src/main/java/de/adorsys/ledgers/middleware/rest/resource/AdminResource.java | golden-dimension/ledgers | 9aa685c57ae9ffd35e7679bea7a1e13e40c9e086 | [
"Apache-2.0"
] | 7 | 2019-07-02T17:24:34.000Z | 2021-07-20T11:42:44.000Z | ledgers-middleware/ledgers-middleware-rest-server/src/main/java/de/adorsys/ledgers/middleware/rest/resource/AdminResource.java | golden-dimension/ledgers | 9aa685c57ae9ffd35e7679bea7a1e13e40c9e086 | [
"Apache-2.0"
] | 12 | 2018-11-14T22:33:26.000Z | 2021-12-06T10:56:44.000Z | 48.466667 | 194 | 0.748796 | 998,757 | package de.adorsys.ledgers.middleware.rest.resource;
import de.adorsys.ledgers.middleware.api.domain.account.AccountDetailsExtendedTO;
import de.adorsys.ledgers.middleware.api.domain.um.UserExtendedTO;
import de.adorsys.ledgers.middleware.api.domain.um.UserRoleTO;
import de.adorsys.ledgers.middleware.api.domain.um.UserTO;
import de.adorsys.ledgers.middleware.api.exception.MiddlewareErrorCode;
import de.adorsys.ledgers.middleware.api.exception.MiddlewareModuleException;
import de.adorsys.ledgers.middleware.api.service.AppManagementService;
import de.adorsys.ledgers.middleware.api.service.MiddlewareAccountManagementService;
import de.adorsys.ledgers.middleware.api.service.MiddlewareUserManagementService;
import de.adorsys.ledgers.middleware.impl.converter.UserMapper;
import de.adorsys.ledgers.middleware.rest.annotation.MiddlewareResetResource;
import de.adorsys.ledgers.um.api.domain.UserBO;
import de.adorsys.ledgers.um.api.service.UserService;
import de.adorsys.ledgers.util.domain.CustomPageImpl;
import de.adorsys.ledgers.util.domain.CustomPageableImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static de.adorsys.ledgers.middleware.api.domain.um.UserRoleTO.*;
@RestController
@MiddlewareResetResource
@RequiredArgsConstructor
@RequestMapping(AdminResourceAPI.BASE_PATH)
public class AdminResource implements AdminResourceAPI {
private final MiddlewareUserManagementService middlewareUserService;
private final MiddlewareAccountManagementService accountManagementService;
private final AppManagementService appManagementService;
private final UserService userService;
private final UserMapper userMapper;
@Override
@PreAuthorize("hasAnyRole('SYSTEM')")
public ResponseEntity<List<UserTO>> getAllUsers() {
return ResponseEntity.ok(middlewareUserService.listUsers(0, Integer.MAX_VALUE));
}
@Override
@PreAuthorize("hasRole('SYSTEM')")
public ResponseEntity<CustomPageImpl<UserExtendedTO>> users(String countryCode, String branchId, String branchLogin, String userLogin, UserRoleTO role, Boolean blocked, int page, int size) {
CustomPageableImpl pageable = new CustomPageableImpl(page, size);
List<UserRoleTO> roles = Optional.ofNullable(role).map(Collections::singletonList).orElseGet(() -> Arrays.asList(STAFF, CUSTOMER));
return ResponseEntity.ok(middlewareUserService.getUsersByBranchAndRolesExtended(countryCode, branchId, branchLogin, userLogin, roles, blocked, pageable));
}
@Override
@PreAuthorize("hasRole('SYSTEM')")
public ResponseEntity<CustomPageImpl<UserTO>> admins(int page, int size) {
CustomPageableImpl pageable = new CustomPageableImpl(page, size);
return ResponseEntity.ok(middlewareUserService.getUsersByRoles(Collections.singletonList(SYSTEM), pageable));
}
@Override
@PreAuthorize("hasRole('SYSTEM')")
public ResponseEntity<CustomPageImpl<AccountDetailsExtendedTO>> accounts(String countryCode, String branchId, String branchLogin, String iban, Boolean blocked, int page, int size) {
CustomPageableImpl pageable = new CustomPageableImpl(page, size);
return ResponseEntity.ok(accountManagementService.getAccountsByBranchAndMultipleParams(countryCode, branchId, branchLogin, iban, blocked, pageable));
}
@Override
@PreAuthorize("hasRole('SYSTEM')")
public ResponseEntity<Void> updatePassword(String branchId, String password) {
middlewareUserService.updatePasswordById(branchId, password);
return ResponseEntity.accepted().build();
}
@Override
@PreAuthorize("hasRole('SYSTEM')")
public ResponseEntity<Boolean> changeStatus(String userId) {
return ResponseEntity.ok(appManagementService.changeBlockedStatus(userId, false));
}
@Override
@PreAuthorize("hasRole('SYSTEM')")
public ResponseEntity<UserTO> register(UserTO user) {
UserTO createdUser = middlewareUserService.create(user);
createdUser.setPin(null);
return ResponseEntity.ok(createdUser);
}
@Override
@PreAuthorize("hasRole('SYSTEM') and isEnabledUser(#user.id)")
public ResponseEntity<Void> user(UserTO user) {
checkUpdateData(user);
middlewareUserService.updateUser(user.getBranch(), user);
return ResponseEntity.accepted().build();
}
@SuppressWarnings("PMD.CyclomaticComplexity")
private void checkUpdateData(UserTO user) { //TODO move to validation filter
UserBO userStored = userService.findById(user.getId());
if (!userStored.getUserRoles().containsAll(userMapper.toUserBO(user).getUserRoles())) {
throw MiddlewareModuleException.builder()
.errorCode(MiddlewareErrorCode.INSUFFICIENT_PERMISSION)
.devMsg("You are not allowed to modify users roles!")
.build();
}
if (!StringUtils.equals(userStored.getBranch(), user.getBranch())
|| user.getUserRoles().contains(STAFF) && !StringUtils.equals(user.getBranch(), user.getId())
|| !StringUtils.equals(user.getId(), userStored.getId())) {
throw MiddlewareModuleException.builder()
.errorCode(MiddlewareErrorCode.INSUFFICIENT_PERMISSION)
.devMsg("User are not allowed to modify users TPP relation!")
.build();
}
}
}
|
92393fcc11ec2daae20f54fdb3cb6f746b167c4f | 2,403 | java | Java | src/main/java/saver/DEMSaver.java | annaeg/PET2EcoBuilder4DEMO | e9c199175cfbd959ae58c8ab23c05be14dee91b2 | [
"Apache-2.0"
] | null | null | null | src/main/java/saver/DEMSaver.java | annaeg/PET2EcoBuilder4DEMO | e9c199175cfbd959ae58c8ab23c05be14dee91b2 | [
"Apache-2.0"
] | null | null | null | src/main/java/saver/DEMSaver.java | annaeg/PET2EcoBuilder4DEMO | e9c199175cfbd959ae58c8ab23c05be14dee91b2 | [
"Apache-2.0"
] | null | null | null | 41.431034 | 118 | 0.73325 | 998,758 | /*
* Copyright 2016 Anna Eggers - Göttingen State and University Library
* The work has been developed in the PERICLES Project by Members of the PERICLES Consortium.
* This project has received funding from the European Union’s Seventh Framework Programme for research, technological
* development and demonstration under grant agreement no FP7- 601138 PERICLES.
* <p>
* 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, including without
* limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTIBITLY, or FITNESS FOR A PARTICULAR
* PURPOSE. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law or agreed to in writing, shall any Contributor be liable for damages, including
* any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this
* License or out of the use or inability to use the Work.
* See the License for the specific language governing permissions and limitation under the License.
*/
package saver;
import ecoBuilder.EcoBuilder;
import models.AbstractModel;
import models.DEM;
import java.io.File;
/**
* Saves the abstract DEM models.
*/
public class DEMSaver extends AbstractSaver {
public DEMSaver(EcoBuilder gui) {
super(gui, "DEM_Ontology");
}
/**
* Saves all abstract DEM sub ontologies.
*/
@Override
public File save() {
saveSubOntology(DEM.CORE_MODEL);
saveSubOntology(DEM.POLICY_MODEL);
saveSubOntology(DEM.PROCESS_MODEL);
saveSubOntology(DEM.ANALYSIS_MODEL);
saveSubOntology(DEM.INFRASTRUCTURE_MODEL);
saveSubOntology(DEM.PRESERVATION_POLICY_MODEL);
return null;
}
/**
* Saves the sub ontology model in xml as well as in turtle format.
*
* @param model The model to be saved
*/
private void saveSubOntology(AbstractModel model) {
saveModel(model.model, model.prefix + "-");
}
}
|
92393fee92a8549c70d3e78a29c47fed3660162b | 2,407 | java | Java | collectors/scm/gitlab/src/main/java/com/capitalone/dashboard/model/GitlabGitRepo.java | aamol/Hygieia | 235c88a35f9043017e754fa42198f38be8a3fa63 | [
"Apache-2.0"
] | 4 | 2018-02-26T16:41:57.000Z | 2020-11-07T03:52:42.000Z | collectors/scm/gitlab/src/main/java/com/capitalone/dashboard/model/GitlabGitRepo.java | aamol/Hygieia | 235c88a35f9043017e754fa42198f38be8a3fa63 | [
"Apache-2.0"
] | 164 | 2019-02-13T17:00:04.000Z | 2019-02-22T16:56:45.000Z | collectors/scm/gitlab/src/main/java/com/capitalone/dashboard/model/GitlabGitRepo.java | aamol/Hygieia | 235c88a35f9043017e754fa42198f38be8a3fa63 | [
"Apache-2.0"
] | 16 | 2019-08-06T16:33:37.000Z | 2021-02-22T08:38:52.000Z | 24.07 | 63 | 0.640631 | 998,759 | package com.capitalone.dashboard.model;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.Date;
/**
* Created by benathmane on 20/06/16.
*/
/**
* CollectorItem extension to store the gitlab repo url
*/
public class GitlabGitRepo extends CollectorItem {
public static final String REPO_URL = "url";
public static final String BRANCH = "branch";
public static final String USER_ID = "userID";
public static final String PASSWORD = "password";
public static final String LAST_UPDATE_TIME = "lastUpdate";
public String getUserId() {
return (String) getOptions().get(USER_ID);
}
public void setUserId(String userId) {
getOptions().put(USER_ID, userId);
}
public String getPassword() {
return (String) getOptions().get(PASSWORD);
}
public void setPassword(String password) {
getOptions().put(PASSWORD, password);
}
public String getRepoUrl() {
return (String) getOptions().get(REPO_URL);
}
public void setRepoUrl(String instanceUrl) {
getOptions().put(REPO_URL, instanceUrl);
}
public String getBranch() {
return (String) getOptions().get(BRANCH);
}
public void setBranch(String branch) {
getOptions().put(BRANCH, branch);
}
public Date getLastUpdateTime() {
Object latest = getOptions().get(LAST_UPDATE_TIME);
return (Date) latest;
}
public void setLastUpdateTime(Date date) {
getOptions().put(LAST_UPDATE_TIME, date);
}
public void removeLastUpdateDate() {
getOptions().remove(LAST_UPDATE_TIME);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
GitlabGitRepo rhs = (GitlabGitRepo) obj;
return new EqualsBuilder()
.append(getRepoUrl(), rhs.getRepoUrl())
.append(getBranch(), rhs.getBranch())
.append(getUserId(), rhs.getUserId())
.append(getPassword(), rhs.getPassword())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(11, 17)
.append(getRepoUrl())
.append(getBranch())
.append(getUserId())
.append(getPassword())
.toHashCode();
}
}
|
9239403a5d603effb557ffd8e742e26942dd66ec | 733 | java | Java | plugins/javac/src/test/java/ristretto/compiler/plugin/JavacPluginTest.java | tprado/ristretto | 0cbdb72565cb0da6743620f229c5fb6bf0a0533b | [
"MIT"
] | null | null | null | plugins/javac/src/test/java/ristretto/compiler/plugin/JavacPluginTest.java | tprado/ristretto | 0cbdb72565cb0da6743620f229c5fb6bf0a0533b | [
"MIT"
] | null | null | null | plugins/javac/src/test/java/ristretto/compiler/plugin/JavacPluginTest.java | tprado/ristretto | 0cbdb72565cb0da6743620f229c5fb6bf0a0533b | [
"MIT"
] | null | null | null | 24.433333 | 120 | 0.637108 | 998,760 | package ristretto.compiler.plugin;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class JavacPluginTest extends JavacPluginBaseTest {
@Test
void ignores_specified_package() {
var code = TestCompiler.SourceCode.of(
"package ristretto.test;",
"",
"public class TestSample {",
"",
" public static String test(String parameter) {",
" parameter += \":value\";",
" return parameter;",
" }",
"",
"}"
);
var result = compile(code, "--ignore-packages=ristretto.test").invoke("ristretto.test.TestSample", "test", "value");
assertThat(result, is("value:value"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.