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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0dff63d372f64a292d7a6a70b9b40ec1bd8066 | 529 | java | Java | tools/src/main/java/org/jvnet/jaxb2_commons/xjc/outline/MEnumOutline.java | brcolow/jaxb2-basics | d4d25984e9f179e9a0e7f975a3019aa2ea760e1c | [
"BSD-2-Clause"
] | 88 | 2015-01-07T06:20:25.000Z | 2022-03-25T15:02:32.000Z | tools/src/main/java/org/jvnet/jaxb2_commons/xjc/outline/MEnumOutline.java | brcolow/jaxb2-basics | d4d25984e9f179e9a0e7f975a3019aa2ea760e1c | [
"BSD-2-Clause"
] | 113 | 2015-01-05T18:40:49.000Z | 2022-03-21T11:53:13.000Z | tools/src/main/java/org/jvnet/jaxb2_commons/xjc/outline/MEnumOutline.java | brcolow/jaxb2-basics | d4d25984e9f179e9a0e7f975a3019aa2ea760e1c | [
"BSD-2-Clause"
] | 43 | 2015-01-25T18:14:09.000Z | 2022-03-29T08:47:40.000Z | 27.842105 | 70 | 0.816635 | 5,928 | package org.jvnet.jaxb2_commons.xjc.outline;
import java.util.List;
import org.jvnet.jaxb2_commons.xml.bind.model.MEnumLeafInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MTargeted;
import com.sun.codemodel.JDefinedClass;
import com.sun.tools.xjc.model.nav.NClass;
import com.sun.tools.xjc.model.nav.NType;
public interface MEnumOutline extends MChildOutline, MPackagedOutline,
MTargeted<MEnumLeafInfo<NType, NClass>> {
public List<MEnumConstantOutline> getEnumConstantOutlines();
public JDefinedClass getCode();
}
|
3e0e000b6de4c75551763c78d4eccdb4c5e329a2 | 464 | java | Java | src/main/java/com/yahoo/bullet/common/Configurable.java | NathanSpeidel/bullet-core | 60db58225e9de2e6e82a7b2f161586442a0d9698 | [
"Apache-2.0"
] | 29 | 2018-06-29T05:35:06.000Z | 2021-09-05T10:29:55.000Z | src/main/java/com/yahoo/bullet/common/Configurable.java | NathanSpeidel/bullet-core | 60db58225e9de2e6e82a7b2f161586442a0d9698 | [
"Apache-2.0"
] | 62 | 2018-06-14T22:31:01.000Z | 2022-01-11T19:01:39.000Z | src/main/java/com/yahoo/bullet/common/Configurable.java | NathanSpeidel/bullet-core | 60db58225e9de2e6e82a7b2f161586442a0d9698 | [
"Apache-2.0"
] | 14 | 2018-06-06T00:30:35.000Z | 2022-01-10T23:19:12.000Z | 29 | 86 | 0.711207 | 5,929 | /*
* Copyright 2017, Yahoo Inc.
* Licensed under the terms of the Apache License, Version 2.0.
* See the LICENSE file associated with the project for terms.
*/
package com.yahoo.bullet.common;
public interface Configurable {
/**
* Takes a {@link BulletConfig} containing configuration and applies it to itself.
*
* @param configuration The configuration containing the settings.
*/
void configure(BulletConfig configuration);
}
|
3e0e001bae231afcca8dcac47c4cf873a2610618 | 2,523 | java | Java | icms/src/main/java/com/bplow/todo/freemark_ex/dao/entity/FmCatalog.java | ahwxl/cms | d0c866ea6c56cca12bfee449817cfc890b0ce458 | [
"Apache-2.0"
] | null | null | null | icms/src/main/java/com/bplow/todo/freemark_ex/dao/entity/FmCatalog.java | ahwxl/cms | d0c866ea6c56cca12bfee449817cfc890b0ce458 | [
"Apache-2.0"
] | null | null | null | icms/src/main/java/com/bplow/todo/freemark_ex/dao/entity/FmCatalog.java | ahwxl/cms | d0c866ea6c56cca12bfee449817cfc890b0ce458 | [
"Apache-2.0"
] | null | null | null | 17.280822 | 52 | 0.690052 | 5,930 | package com.bplow.todo.freemark_ex.dao.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "FM_CATALOG")
public class FmCatalog {
private String catalogId;
private String catalogName;
private String catalogDesc;
private String secondName;
private String imageSrc;
private int orderId;
private Date operateDate;
private String isDeleteFlag;
private String catalogType;
private String pCatalogId;
public FmCatalog() {
super();
}
public FmCatalog(String catalogId) {
super();
this.pCatalogId = catalogId;
}
@Id
public String getCatalogId() {
return catalogId;
}
public void setCatalogId(String catalogId) {
this.catalogId = catalogId;
}
@Column(name="catalog_name")
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
@Column(name="catalog_desc")
public String getCatalogDesc() {
return catalogDesc;
}
public void setCatalogDesc(String catalogDesc) {
this.catalogDesc = catalogDesc;
}
@Column(name="second_name")
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
@Column(name="image_src")
public String getImageSrc() {
return imageSrc;
}
public void setImageSrc(String imageSrc) {
this.imageSrc = imageSrc;
}
@Column(name="order_id")
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
@Column(name="operate_date")
public Date getOperateDate() {
return operateDate;
}
public void setOperateDate(Date operateDate) {
this.operateDate = operateDate;
}
@Column(name="is_delete_flag")
public String getIsDeleteFlag() {
return isDeleteFlag;
}
public void setIsDeleteFlag(String isDeleteFlag) {
this.isDeleteFlag = isDeleteFlag;
}
@Column(name="catalog_type")
public String getCatalogType() {
return catalogType;
}
public void setCatalogType(String catalogType) {
this.catalogType = catalogType;
}
@Column(name="parent_catalog_id")
public String getpCatalogId() {
return pCatalogId;
}
public void setpCatalogId(String pCatalogId) {
this.pCatalogId = pCatalogId;
}
}
|
3e0e00b710f9ef229c6854413b802a0b76b8e581 | 1,262 | java | Java | xmpp-core/src/main/java/rocks/xmpp/util/concurrent/package-info.java | jeozey/XmppServerTester | 6b1966c141073ffcfb6998811460e84ec88663b1 | [
"MIT"
] | null | null | null | xmpp-core/src/main/java/rocks/xmpp/util/concurrent/package-info.java | jeozey/XmppServerTester | 6b1966c141073ffcfb6998811460e84ec88663b1 | [
"MIT"
] | null | null | null | xmpp-core/src/main/java/rocks/xmpp/util/concurrent/package-info.java | jeozey/XmppServerTester | 6b1966c141073ffcfb6998811460e84ec88663b1 | [
"MIT"
] | null | null | null | 45.071429 | 81 | 0.740095 | 5,931 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Christian Schudt
*
* 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.
*/
/**
* Provides classes for concurrency.
*/
package rocks.xmpp.util.concurrent; |
3e0e00c6fcd11273f7e0abcebe08859b04b39643 | 5,421 | java | Java | agave-common/common-core/src/test/java/org/iplantc/service/common/auth/MyProxyClientTest.java | agaveplatform/science-apis | 7ca81d9124bfb446edc5f92050733adb75b938d5 | [
"BSD-3-Clause"
] | null | null | null | agave-common/common-core/src/test/java/org/iplantc/service/common/auth/MyProxyClientTest.java | agaveplatform/science-apis | 7ca81d9124bfb446edc5f92050733adb75b938d5 | [
"BSD-3-Clause"
] | 8 | 2017-08-26T15:48:36.000Z | 2020-07-03T03:35:16.000Z | agave-common/common-core/src/test/java/org/iplantc/service/common/auth/MyProxyClientTest.java | agaveplatform/science-apis | 7ca81d9124bfb446edc5f92050733adb75b938d5 | [
"BSD-3-Clause"
] | 1 | 2018-05-30T03:55:22.000Z | 2018-05-30T03:55:22.000Z | 32.461078 | 69 | 0.713337 | 5,932 | package org.iplantc.service.common.auth;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.globus.gsi.gssapi.GlobusGSSCredentialImpl;
import org.ietf.jgss.GSSCredential;
import org.iplantc.service.common.Settings;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Collection;
/**
* @deprecated
*/
@Test(enabled=false, singleThreaded=true, groups = {"integration"} )
public class MyProxyClientTest {
@BeforeMethod
public void beforeTest() {
}
@Test
public void getCommunityCredential() {
try {
GSSCredential cred = MyProxyClient.getCommunityCredential();
Assert.assertNotNull(cred, "Credential should be returned from "
+ Settings.TACC_MYPROXY_SERVER);
Assert.assertTrue(cred.getRemainingLifetime() > 0,
"Credential returned from " + Settings.TACC_MYPROXY_SERVER
+ " is expired");
Assert.assertEquals(cred.getClass().getName(),
GlobusGSSCredentialImpl.class.getName());
File trustrootDirectory = new File(MyProxy.getTrustRootPath());
Assert.assertTrue(
trustrootDirectory.exists(),
"Trustroot directory "
+ trustrootDirectory.getAbsolutePath()
+ " was not created when the credential was retrieved.");
Collection<File> trustrootFiles = FileUtils.listFiles(
trustrootDirectory, new String[] { "0" }, true);
Assert.assertFalse(trustrootFiles.isEmpty(),
"No trustroots were retrieved from "
+ Settings.TACC_MYPROXY_SERVER
+ " with the credential");
} catch (Throwable e) {
Assert.fail("No exception should be thrown "
+ "retrieving a community credential", e);
}
}
@Test
public void getCredential() {
try {
GSSCredential cred = MyProxyClient.getCredential(
Settings.TACC_MYPROXY_SERVER, Settings.TACC_MYPROXY_PORT,
Settings.COMMUNITY_PROXY_USERNAME,
Settings.COMMUNITY_PROXY_PASSWORD, null);
Assert.assertNotNull(cred, "Credential shoudl be returned from "
+ Settings.TACC_MYPROXY_SERVER);
Assert.assertTrue(cred.getRemainingLifetime() > 0,
"Credential returned from " + Settings.TACC_MYPROXY_SERVER
+ " is expired");
Assert.assertEquals(cred.getClass().getName(),
GlobusGSSCredentialImpl.class.getName());
File trustrootDirectory = new File(MyProxy.getTrustRootPath());
Assert.assertTrue(
trustrootDirectory.exists(),
"Trustroot directory "
+ trustrootDirectory.getAbsolutePath()
+ " was not created when the credential was retrieved.");
Collection<File> trustrootFiles = FileUtils.listFiles(
trustrootDirectory, new String[] { "0" }, true);
Assert.assertFalse(trustrootFiles.isEmpty(),
"No trustroots were retrieved from "
+ Settings.TACC_MYPROXY_SERVER
+ " with the credential");
} catch (Throwable e) {
Assert.fail(
"No exception should be thrown retrieving a credential", e);
}
}
@Test
public void getCredentialAtCustomCACertPath() {
try {
File tempDir = Files.createTempDir();
GSSCredential cred = MyProxyClient.getCredential(
Settings.TACC_MYPROXY_SERVER, Settings.TACC_MYPROXY_PORT,
Settings.COMMUNITY_PROXY_USERNAME,
Settings.COMMUNITY_PROXY_PASSWORD,
tempDir.getAbsolutePath());
Assert.assertNotNull(cred, "Credential should be returned from "
+ Settings.TACC_MYPROXY_SERVER);
Assert.assertTrue(cred.getRemainingLifetime() > 0,
"Credential returned from " + Settings.TACC_MYPROXY_SERVER
+ " is expired");
Assert.assertEquals(cred.getClass().getName(),
GlobusGSSCredentialImpl.class.getName());
Assert.assertTrue(
tempDir.exists(),
"Trustroot directory "
+ tempDir.getAbsolutePath()
+ " was no longer present after retrieving the credentials.");
Collection<File> trustrootFiles = FileUtils.listFiles(
tempDir, new String[] { "0" }, true);
Assert.assertFalse(trustrootFiles.isEmpty(),
"No trustroots were retrieved from "
+ Settings.TACC_MYPROXY_SERVER
+ " with the credential");
} catch (Throwable e) {
Assert.fail(
"No exception should be thrown retrieving a credential", e);
}
}
@Test
public void getUserCredential() {
try {
GSSCredential cred = MyProxyClient.getUserCredential(
Settings.COMMUNITY_PROXY_USERNAME,
Settings.COMMUNITY_PROXY_PASSWORD);
Assert.assertNotNull(cred, "Credential shoudl be returned from "
+ Settings.TACC_MYPROXY_SERVER);
Assert.assertTrue(cred.getRemainingLifetime() > 0,
"Credential returned from " + Settings.TACC_MYPROXY_SERVER
+ " is expired");
Assert.assertEquals(cred.getClass().getName(),
GlobusGSSCredentialImpl.class.getName());
File trustrootDirectory = new File(
MyProxy.getTrustRootPath());
Assert.assertTrue(
trustrootDirectory.exists(),
"Trustroot directory "
+ trustrootDirectory.getAbsolutePath()
+ " was not created when the credential was retrieved.");
Collection<File> trustrootFiles = FileUtils.listFiles(
trustrootDirectory, new String[] { "0" }, true);
Assert.assertFalse(trustrootFiles.isEmpty(),
"No trustroots were retrieved from "
+ Settings.TACC_MYPROXY_SERVER
+ " with the credential");
} catch (Throwable e) {
Assert.fail(
"No exception should be thrown retrieving a user credential",
e);
}
}
}
|
3e0e012fc840a275937d63ca715f5fbc8ad75a62 | 1,170 | java | Java | scs2-definition/src/main/java/us/ihmc/scs2/definition/visual/MaterialScriptDefinition.java | ihmcrobotics/simulation-construction-set-2 | 5aa81824cb297b5f7fdec48714ec2962524cc867 | [
"Apache-2.0"
] | 3 | 2021-03-08T17:55:35.000Z | 2021-04-06T08:25:05.000Z | scs2-definition/src/main/java/us/ihmc/scs2/definition/visual/MaterialScriptDefinition.java | ihmcrobotics/simulation-construction-set-2 | 5aa81824cb297b5f7fdec48714ec2962524cc867 | [
"Apache-2.0"
] | 76 | 2019-11-23T23:34:20.000Z | 2022-03-31T22:22:20.000Z | scs2-definition/src/main/java/us/ihmc/scs2/definition/visual/MaterialScriptDefinition.java | ihmcrobotics/simulation-construction-set-2 | 5aa81824cb297b5f7fdec48714ec2962524cc867 | [
"Apache-2.0"
] | null | null | null | 20.172414 | 114 | 0.679487 | 5,933 | package us.ihmc.scs2.definition.visual;
import java.util.ArrayList;
import java.util.List;
public class MaterialScriptDefinition
{
private String name;
private List<String> urls;
private List<String> resourceDirectories;
public MaterialScriptDefinition()
{
}
public MaterialScriptDefinition(MaterialScriptDefinition other)
{
name = other.name;
urls = other.urls == null ? null : new ArrayList<>(other.urls);
resourceDirectories = other.resourceDirectories == null ? null : new ArrayList<>(other.resourceDirectories);
}
public String getName()
{
return name;
}
public List<String> getUrls()
{
return urls;
}
public List<String> getResourceDirectories()
{
return resourceDirectories;
}
public void setName(String name)
{
this.name = name;
}
public void setUrls(List<String> urls)
{
this.urls = urls;
}
public void setResourceDirectories(List<String> resourceDirectories)
{
this.resourceDirectories = resourceDirectories;
}
public MaterialScriptDefinition copy()
{
return new MaterialScriptDefinition(this);
}
}
|
3e0e01af129ee49586205a0817490fcbab76bea5 | 4,534 | java | Java | server/build/rhino/src/org/mozilla/javascript/NativeFunction.java | stevengill/completeui | ea54e9f48075692be5dad313d78ef2bbe16531dd | [
"MIT"
] | 1 | 2016-07-28T01:25:43.000Z | 2016-07-28T01:25:43.000Z | server/build/rhino/src/org/mozilla/javascript/NativeFunction.java | stevengill/completeui | ea54e9f48075692be5dad313d78ef2bbe16531dd | [
"MIT"
] | null | null | null | server/build/rhino/src/org/mozilla/javascript/NativeFunction.java | stevengill/completeui | ea54e9f48075692be5dad313d78ef2bbe16531dd | [
"MIT"
] | null | null | null | 30.635135 | 80 | 0.666299 | 5,934 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import org.mozilla.javascript.debug.DebuggableScript;
/**
* This class implements the Function native object.
* See ECMA 15.3.
* @author Norris Boyd
*/
public abstract class NativeFunction extends BaseFunction
{
public final void initScriptFunction(Context cx, Scriptable scope)
{
ScriptRuntime.setFunctionProtoAndParent(this, scope);
}
/**
* @param indent How much to indent the decompiled result
*
* @param flags Flags specifying format of decompilation output
*/
final String decompile(int indent, int flags)
{
String encodedSource = getEncodedSource();
if (encodedSource == null) {
return super.decompile(indent, flags);
} else {
UintMap properties = new UintMap(1);
properties.put(Decompiler.INITIAL_INDENT_PROP, indent);
return Decompiler.decompile(encodedSource, flags, properties);
}
}
final String compress(int indent, int flags)
{
String encodedSource = getEncodedSource();
if (encodedSource == null) {
return super.compress(indent, flags);
} else {
UintMap properties = new UintMap(1);
properties.put(Decompiler.INITIAL_INDENT_PROP, indent);
return Decompiler.compress(encodedSource, flags, properties);
}
}
public int getLength()
{
int paramCount = getParamCount();
if (getLanguageVersion() != Context.VERSION_1_2) {
return paramCount;
}
Context cx = Context.getContext();
NativeCall activation = ScriptRuntime.findFunctionActivation(cx, this);
if (activation == null) {
return paramCount;
}
return activation.originalArgs.length;
}
public int getArity()
{
return getParamCount();
}
/**
* @deprecated Use {@link BaseFunction#getFunctionName()} instead.
* For backwards compatibility keep an old method name used by
* Batik and possibly others.
*/
public String jsGet_name()
{
return getFunctionName();
}
/**
* Get encoded source string.
*/
public String getEncodedSource()
{
return null;
}
public DebuggableScript getDebuggableView()
{
return null;
}
protected abstract int getLanguageVersion();
/**
* Get number of declared parameters. It should be 0 for scripts.
*/
protected abstract int getParamCount();
/**
* Get number of declared parameters and variables defined through var
* statements.
*/
protected abstract int getParamAndVarCount();
/**
* Get parameter or variable name.
* If <tt>index < {@link #getParamCount()}</tt>, then return the name of the
* corresponding parameter. Otherwise returm the name of variable.
*/
protected abstract String getParamOrVarName(int index);
}
|
3e0e02602f10f01b2cf4232d381171e087c7ca64 | 18,188 | java | Java | aws-api/src/main/java/com/amplifyframework/api/aws/AppSyncGraphQLRequestFactory.java | rjuliano/amplify-android | 567ac2895e07619a1c47c0d0227febb874bce787 | [
"Apache-2.0"
] | 148 | 2019-12-04T00:19:40.000Z | 2022-02-18T09:07:34.000Z | aws-api/src/main/java/com/amplifyframework/api/aws/AppSyncGraphQLRequestFactory.java | rjuliano/amplify-android | 567ac2895e07619a1c47c0d0227febb874bce787 | [
"Apache-2.0"
] | 887 | 2019-12-04T05:05:38.000Z | 2022-03-31T15:21:04.000Z | aws-api/src/main/java/com/amplifyframework/api/aws/AppSyncGraphQLRequestFactory.java | rjuliano/amplify-android | 567ac2895e07619a1c47c0d0227febb874bce787 | [
"Apache-2.0"
] | 88 | 2019-12-04T01:30:01.000Z | 2022-03-04T07:01:08.000Z | 43.2019 | 117 | 0.627722 | 5,935 | /*
* Copyright 2019 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://aws.amazon.com/apache2.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.amplifyframework.api.aws;
import androidx.annotation.NonNull;
import com.amplifyframework.AmplifyException;
import com.amplifyframework.api.graphql.GraphQLRequest;
import com.amplifyframework.api.graphql.MutationType;
import com.amplifyframework.api.graphql.PaginatedResult;
import com.amplifyframework.api.graphql.QueryType;
import com.amplifyframework.api.graphql.SubscriptionType;
import com.amplifyframework.core.model.AuthRule;
import com.amplifyframework.core.model.AuthStrategy;
import com.amplifyframework.core.model.Model;
import com.amplifyframework.core.model.ModelAssociation;
import com.amplifyframework.core.model.ModelField;
import com.amplifyframework.core.model.ModelSchema;
import com.amplifyframework.core.model.query.predicate.BeginsWithQueryOperator;
import com.amplifyframework.core.model.query.predicate.BetweenQueryOperator;
import com.amplifyframework.core.model.query.predicate.ContainsQueryOperator;
import com.amplifyframework.core.model.query.predicate.EqualQueryOperator;
import com.amplifyframework.core.model.query.predicate.GreaterOrEqualQueryOperator;
import com.amplifyframework.core.model.query.predicate.GreaterThanQueryOperator;
import com.amplifyframework.core.model.query.predicate.LessOrEqualQueryOperator;
import com.amplifyframework.core.model.query.predicate.LessThanQueryOperator;
import com.amplifyframework.core.model.query.predicate.NotContainsQueryOperator;
import com.amplifyframework.core.model.query.predicate.NotEqualQueryOperator;
import com.amplifyframework.core.model.query.predicate.QueryOperator;
import com.amplifyframework.core.model.query.predicate.QueryPredicate;
import com.amplifyframework.core.model.query.predicate.QueryPredicateGroup;
import com.amplifyframework.core.model.query.predicate.QueryPredicateOperation;
import com.amplifyframework.core.model.query.predicate.QueryPredicates;
import com.amplifyframework.util.Casing;
import com.amplifyframework.util.TypeMaker;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
/**
* Converts provided model or class type into a request container
* with automatically generated GraphQL documents that follow
* AppSync specifications.
*/
public final class AppSyncGraphQLRequestFactory {
private static final int DEFAULT_QUERY_LIMIT = 1000;
// This class should not be instantiated
private AppSyncGraphQLRequestFactory() {}
/**
* Creates a {@link GraphQLRequest} that represents a query that expects a single value as a result.
* The request will be created with the correct document based on the model schema and
* variables based on given {@code objectId}.
*
* @param modelClass the model class.
* @param objectId the model identifier.
* @param <R> the response type.
* @param <T> the concrete model type.
* @return a valid {@link GraphQLRequest} instance.
* @throws IllegalStateException when the model schema does not contain the expected information.
*/
public static <R, T extends Model> GraphQLRequest<R> buildQuery(
Class<T> modelClass,
String objectId
) {
try {
return AppSyncGraphQLRequest.builder()
.modelClass(modelClass)
.operation(QueryType.GET)
.requestOptions(new ApiGraphQLRequestOptions())
.responseType(modelClass)
.variable("id", "ID!", objectId)
.build();
} catch (AmplifyException exception) {
throw new IllegalStateException(
"Could not generate a schema for the specified class",
exception
);
}
}
/**
* Creates a {@link GraphQLRequest} that represents a query that expects multiple values as a result.
* The request will be created with the correct document based on the model schema and variables
* for filtering based on the given predicate.
*
* @param modelClass the model class.
* @param predicate the model predicate.
* @param <R> the response type.
* @param <T> the concrete model type.
* @return a valid {@link GraphQLRequest} instance.
* @throws IllegalStateException when the model schema does not contain the expected information.
*/
public static <R, T extends Model> GraphQLRequest<R> buildQuery(
Class<T> modelClass,
QueryPredicate predicate
) {
Type dataType = TypeMaker.getParameterizedType(PaginatedResult.class, modelClass);
return buildQuery(modelClass, predicate, DEFAULT_QUERY_LIMIT, dataType);
}
/**
* Creates a {@link GraphQLRequest} that represents a query that expects multiple values as a result
* within a certain range (i.e. paginated).
*
* The request will be created with the correct document based on the model schema and variables
* for filtering based on the given predicate and pagination.
*
* @param modelClass the model class.
* @param predicate the predicate for filtering.
* @param limit the page size/limit.
* @param <R> the response type.
* @param <T> the concrete model type.
* @return a valid {@link GraphQLRequest} instance.
*/
public static <R, T extends Model> GraphQLRequest<R> buildPaginatedResultQuery(
Class<T> modelClass,
QueryPredicate predicate,
int limit
) {
Type responseType = TypeMaker.getParameterizedType(PaginatedResult.class, modelClass);
return buildQuery(modelClass, predicate, limit, responseType);
}
static <R, T extends Model> GraphQLRequest<R> buildQuery(
Class<T> modelClass,
QueryPredicate predicate,
int limit,
Type responseType
) {
try {
String modelName = ModelSchema.fromModelClass(modelClass).getName();
AppSyncGraphQLRequest.Builder builder = AppSyncGraphQLRequest.builder()
.modelClass(modelClass)
.operation(QueryType.LIST)
.requestOptions(new ApiGraphQLRequestOptions())
.responseType(responseType);
if (!QueryPredicates.all().equals(predicate)) {
String filterType = "Model" + Casing.capitalizeFirst(modelName) + "FilterInput";
builder.variable("filter", filterType, parsePredicate(predicate));
}
builder.variable("limit", "Int", limit);
return builder.build();
} catch (AmplifyException exception) {
throw new IllegalStateException(
"Could not generate a schema for the specified class",
exception
);
}
}
/**
* Creates a {@link GraphQLRequest} that represents a mutation of a given type.
*
* @param model the model instance.
* @param predicate the model predicate.
* @param type the mutation type.
* @param <R> the response type.
* @param <T> the concrete model type.
* @return a valid {@link GraphQLRequest} instance.
* @throws IllegalStateException when the model schema does not contain the expected information.
*/
public static <R, T extends Model> GraphQLRequest<R> buildMutation(
T model,
QueryPredicate predicate,
MutationType type
) {
try {
Class<? extends Model> modelClass = model.getClass();
ModelSchema schema = ModelSchema.fromModelClass(modelClass);
String graphQlTypeName = schema.getName();
AppSyncGraphQLRequest.Builder builder = AppSyncGraphQLRequest.builder()
.operation(type)
.modelClass(modelClass)
.requestOptions(new ApiGraphQLRequestOptions())
.responseType(modelClass);
String inputType =
Casing.capitalize(type.toString()) +
Casing.capitalizeFirst(graphQlTypeName) +
"Input!"; // CreateTodoInput
if (MutationType.DELETE.equals(type)) {
builder.variable("input", inputType, getDeleteMutationInputMap(schema, model));
} else {
builder.variable("input", inputType, getMapOfFieldNameAndValues(schema, model));
}
if (!QueryPredicates.all().equals(predicate)) {
String conditionType =
"Model" +
Casing.capitalizeFirst(graphQlTypeName) +
"ConditionInput";
builder.variable("condition", conditionType, parsePredicate(predicate));
}
return builder.build();
} catch (AmplifyException exception) {
throw new IllegalStateException(
"Could not generate a schema for the specified class",
exception
);
}
}
/**
* Creates a {@link GraphQLRequest} that represents a subscription of a given type.
*
* @param modelClass the model type.
* @param subscriptionType the subscription type.
* @param <R> the response type.
* @param <T> the concrete model type.
* @return a valid {@link GraphQLRequest} instance.
* @throws IllegalStateException when the model schema does not contain the expected information.
*/
public static <R, T extends Model> GraphQLRequest<R> buildSubscription(
Class<T> modelClass,
SubscriptionType subscriptionType
) {
try {
return AppSyncGraphQLRequest.builder()
.modelClass(modelClass)
.operation(subscriptionType)
.requestOptions(new ApiGraphQLRequestOptions())
.responseType(modelClass)
.build();
} catch (AmplifyException exception) {
throw new IllegalStateException(
"Failed to build GraphQLRequest",
exception
);
}
}
private static Map<String, Object> parsePredicate(QueryPredicate queryPredicate) {
if (queryPredicate instanceof QueryPredicateOperation) {
QueryPredicateOperation<?> qpo = (QueryPredicateOperation<?>) queryPredicate;
QueryOperator<?> op = qpo.operator();
return Collections.singletonMap(
qpo.field(),
Collections.singletonMap(appSyncOpType(op.type()), appSyncOpValue(op))
);
} else if (queryPredicate instanceof QueryPredicateGroup) {
QueryPredicateGroup qpg = (QueryPredicateGroup) queryPredicate;
if (QueryPredicateGroup.Type.NOT.equals(qpg.type())) {
try {
return Collections.singletonMap("not", parsePredicate(qpg.predicates().get(0)));
} catch (IndexOutOfBoundsException exception) {
throw new IllegalStateException(
"Predicate group of type NOT must include a value to negate.",
exception
);
}
} else {
List<Map<String, Object>> predicates = new ArrayList<>();
for (QueryPredicate predicate : qpg.predicates()) {
predicates.add(parsePredicate(predicate));
}
return Collections.singletonMap(qpg.type().toString().toLowerCase(Locale.getDefault()), predicates);
}
} else {
throw new IllegalStateException(
"Invalid predicate type, supported values: QueryPredicateOperation, QueryPredicateGroup."
);
}
}
private static String appSyncOpType(QueryOperator.Type type) {
switch (type) {
case NOT_EQUAL:
return "ne";
case EQUAL:
return "eq";
case LESS_OR_EQUAL:
return "le";
case LESS_THAN:
return "lt";
case GREATER_OR_EQUAL:
return "ge";
case GREATER_THAN:
return "gt";
case CONTAINS:
return "contains";
case BETWEEN:
return "between";
case BEGINS_WITH:
return "beginsWith";
default:
throw new IllegalStateException(
"Tried to parse an unsupported QueryOperator type. Check if a new QueryOperator.Type enum " +
"has been created which is not supported in the AppSyncGraphQLRequestFactory."
);
}
}
private static Object appSyncOpValue(QueryOperator<?> qOp) {
switch (qOp.type()) {
case NOT_EQUAL:
return ((NotEqualQueryOperator) qOp).value();
case EQUAL:
return ((EqualQueryOperator) qOp).value();
case LESS_OR_EQUAL:
return ((LessOrEqualQueryOperator<?>) qOp).value();
case LESS_THAN:
return ((LessThanQueryOperator<?>) qOp).value();
case GREATER_OR_EQUAL:
return ((GreaterOrEqualQueryOperator<?>) qOp).value();
case GREATER_THAN:
return ((GreaterThanQueryOperator<?>) qOp).value();
case CONTAINS:
return ((ContainsQueryOperator) qOp).value();
case NOT_CONTAINS:
return ((NotContainsQueryOperator) qOp).value();
case BETWEEN:
BetweenQueryOperator<?> betweenOp = (BetweenQueryOperator<?>) qOp;
return Arrays.asList(betweenOp.start(), betweenOp.end());
case BEGINS_WITH:
return ((BeginsWithQueryOperator) qOp).value();
default:
throw new IllegalStateException(
"Tried to parse an unsupported QueryOperator type. Check if a new QueryOperator.Type enum " +
"has been created which is not implemented yet."
);
}
}
private static Map<String, Object> getDeleteMutationInputMap(
@NonNull ModelSchema schema, @NonNull Model instance) throws AmplifyException {
final Map<String, Object> input = new HashMap<>();
for (String fieldName : schema.getPrimaryIndexFields()) {
input.put(fieldName, extractFieldValue(fieldName, instance, schema));
}
return input;
}
private static Map<String, Object> getMapOfFieldNameAndValues(
@NonNull ModelSchema schema, @NonNull Model instance) throws AmplifyException {
if (!instance.getClass().getSimpleName().equals(schema.getName())) {
throw new AmplifyException(
"The object provided is not an instance of " + schema.getName() + ".",
"Please provide an instance of " + schema.getName() + " that matches the schema type."
);
}
final Map<String, Object> result = new HashMap<>();
for (ModelField modelField : schema.getFields().values()) {
if (modelField.isReadOnly()) {
// Skip read only fields, since they should not be included on the input object.
continue;
}
String fieldName = modelField.getName();
Object fieldValue = extractFieldValue(fieldName, instance, schema);
final ModelAssociation association = schema.getAssociations().get(fieldName);
if (association == null) {
result.put(fieldName, fieldValue);
} else if (association.isOwner()) {
Model target = (Model) Objects.requireNonNull(fieldValue);
result.put(association.getTargetName(), target.getId());
}
// Ignore if field is associated, but is not a "belongsTo" relationship
}
/*
* If the owner field exists on the model, and the value is null, it should be omitted when performing a
* mutation because the AppSync server will automatically populate it using the authentication token provided
* in the request header. The logic below filters out the owner field if null for this scenario.
*/
for (AuthRule authRule : schema.getAuthRules()) {
if (AuthStrategy.OWNER.equals(authRule.getAuthStrategy())) {
String ownerField = authRule.getOwnerFieldOrDefault();
if (result.containsKey(ownerField) && result.get(ownerField) == null) {
result.remove(ownerField);
}
}
}
return result;
}
private static Object extractFieldValue(String fieldName, Model instance, ModelSchema schema)
throws AmplifyException {
try {
Field privateField = instance.getClass().getDeclaredField(fieldName);
privateField.setAccessible(true);
return privateField.get(instance);
} catch (Exception exception) {
throw new AmplifyException(
"An invalid field was provided. " + fieldName + " is not present in " + schema.getName(),
exception,
"Check if this model schema is a correct representation of the fields in the provided Object");
}
}
}
|
3e0e040b372781fb41f7031b8ebcc7b9159ec58d | 886 | java | Java | src/test/java/com/fatsecret/platform/services/FoodServiceTest.java | goodnic/fatsecret4j | eec32586ec5468c2ebc68a8bd4297a20074caea4 | [
"Apache-2.0"
] | 8 | 2017-02-22T21:58:25.000Z | 2021-07-18T21:29:46.000Z | src/test/java/com/fatsecret/platform/services/FoodServiceTest.java | goodnic/fatsecret4j | eec32586ec5468c2ebc68a8bd4297a20074caea4 | [
"Apache-2.0"
] | 19 | 2017-02-17T14:55:42.000Z | 2022-01-12T20:50:25.000Z | src/test/java/com/fatsecret/platform/services/FoodServiceTest.java | goodnic/fatsecret4j | eec32586ec5468c2ebc68a8bd4297a20074caea4 | [
"Apache-2.0"
] | 17 | 2016-09-19T02:43:16.000Z | 2020-11-30T04:17:24.000Z | 22.15 | 52 | 0.707675 | 5,936 | package com.fatsecret.platform.services;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import com.fatsecret.platform.model.Food;
public class FoodServiceTest {
private FatsecretService service;
@Before
public void setUp() {
String key = "your key";
String secret = "your secret";
service = new FatsecretService(key, secret);
}
@Test
public void testGetFood() {
Food food = service.getFood(285243L);
assertEquals("Penne", food.getName());
assertEquals(4, food.getServings().size());
assertEquals("Generic", food.getType());
}
@Test
public void testGetFoodTypeGeneric() {
Food food = service.getFood(285243L);
assertEquals("Generic", food.getType());
}
@Test
public void testGetFoodTypeBrand() {
Food food = service.getFood(1844450L);
assertEquals("Brand", food.getType());
}
} |
3e0e042132b013385b743252bc7aee75f1d2da6b | 8,589 | java | Java | indexer-reader/src/main/java/org/apache/maven/index/reader/RecordCompactor.java | EdmondFrank/maven-indexer | b982777525d38052bc7840f3d707fac1797eeb51 | [
"Apache-2.0"
] | 62 | 2015-05-01T18:59:34.000Z | 2022-03-30T16:28:59.000Z | indexer-reader/src/main/java/org/apache/maven/index/reader/RecordCompactor.java | EdmondFrank/maven-indexer | b982777525d38052bc7840f3d707fac1797eeb51 | [
"Apache-2.0"
] | 119 | 2015-01-12T17:38:13.000Z | 2022-03-25T04:39:28.000Z | indexer-reader/src/main/java/org/apache/maven/index/reader/RecordCompactor.java | mbooth101/maven-indexer | f09e411d6ced2027856fd24e0292e6ea57b9ff1b | [
"Apache-2.0"
] | 69 | 2015-01-12T13:37:38.000Z | 2022-03-11T12:45:21.000Z | 40.706161 | 119 | 0.633135 | 5,937 | package org.apache.maven.index.reader;
/*
* 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 org.apache.maven.index.reader.Record.Type;
import java.util.HashMap;
import java.util.Map;
import static org.apache.maven.index.reader.Utils.FIELD_SEPARATOR;
import static org.apache.maven.index.reader.Utils.INFO;
import static org.apache.maven.index.reader.Utils.UINFO;
import static org.apache.maven.index.reader.Utils.nvl;
/**
* Maven 2 Index record transformer, that transforms {@link Record}s into "native" Maven Indexer records.
*
* @since 5.1.2
*/
public class RecordCompactor
{
/**
* Compacts {@link Record} into low level MI record with all the encoded fields as physically present in MI binary
* chunk.
*/
public Map<String, String> apply( final Record record )
{
if ( Type.DESCRIPTOR == record.getType() )
{
return compactDescriptor( record );
}
else if ( Type.ALL_GROUPS == record.getType() )
{
return compactAllGroups( record );
}
else if ( Type.ROOT_GROUPS == record.getType() )
{
return compactRootGroups( record );
}
else if ( Type.ARTIFACT_REMOVE == record.getType() )
{
return compactDeletedArtifact( record );
}
else if ( Type.ARTIFACT_ADD == record.getType() )
{
return compactAddedArtifact( record );
}
else
{
throw new IllegalArgumentException( "Unknown record: " + record );
}
}
private static Map<String, String> compactDescriptor( final Record record )
{
final Map<String, String> result = new HashMap<>();
result.put( "DESCRIPTOR", "NexusIndex" );
result.put( "IDXINFO", "1.0|" + record.get( Record.REPOSITORY_ID ) );
return result;
}
private static Map<String, String> compactAllGroups( final Record record )
{
final Map<String, String> result = new HashMap<>();
result.put( "allGroups", "allGroups" );
putIfNotNullAsStringArray( record.get( Record.ALL_GROUPS ), result, "allGroupsList" );
return result;
}
private static Map<String, String> compactRootGroups( final Record record )
{
final Map<String, String> result = new HashMap<>();
result.put( "rootGroups", "allGroups" );
putIfNotNullAsStringArray( record.get( Record.ROOT_GROUPS ), result, "rootGroupsList" );
return result;
}
private static Map<String, String> compactDeletedArtifact( final Record record )
{
final Map<String, String> result = new HashMap<>();
putIfNotNullTS( record.get( Record.REC_MODIFIED ), result, "m" );
result.put( "del", compactUinfo( record ) );
return result;
}
/**
* Expands the "encoded" Maven Indexer record by splitting the synthetic fields and applying expanded field naming.
*/
private static Map<String, String> compactAddedArtifact( final Record record )
{
final Map<String, String> result = new HashMap<>();
// Minimal
result.put( UINFO, compactUinfo( record ) );
String info = nvl( record.get( Record.PACKAGING ) ) + FIELD_SEPARATOR + record.get(
Record.FILE_MODIFIED ) + FIELD_SEPARATOR + record.get(
Record.FILE_SIZE ) + FIELD_SEPARATOR + ( record.get(
Record.HAS_SOURCES ) ? "1" : "0" ) + FIELD_SEPARATOR + ( record.get(
Record.HAS_JAVADOC ) ? "1" : "0" ) + FIELD_SEPARATOR + ( record.get(
Record.HAS_SIGNATURE ) ? "1" : "0" ) + FIELD_SEPARATOR + nvl( record.get( Record.FILE_EXTENSION ) );
result.put( INFO, info );
putIfNotNullTS( record.get( Record.REC_MODIFIED ), result, "m" );
putIfNotNull( record.get( Record.NAME ), result, "n" );
putIfNotNull( record.get( Record.DESCRIPTION ), result, "d" );
putIfNotNull( record.get( Record.SHA1 ), result, "1" );
// Jar file contents (optional)
putIfNotNullAsStringArray( record.get( Record.CLASSNAMES ), result, "classnames" );
// Maven Plugin (optional)
putIfNotNull( record.get( Record.PLUGIN_PREFIX ), result, "px" );
putIfNotNullAsStringArray( record.get( Record.PLUGIN_GOALS ), result, "gx" );
// OSGi (optional)
putIfNotNull( record.get( Record.OSGI_BUNDLE_SYMBOLIC_NAME ), result, "Bundle-SymbolicName" );
putIfNotNull( record.get( Record.OSGI_BUNDLE_VERSION ), result, "Bundle-Version" );
putIfNotNull( record.get( Record.OSGI_EXPORT_PACKAGE ), result, "Export-Package" );
putIfNotNull( record.get( Record.OSGI_EXPORT_SERVICE ), result, "Export-Service" );
putIfNotNull( record.get( Record.OSGI_BUNDLE_DESCRIPTION ), result, "Bundle-Description" );
putIfNotNull( record.get( Record.OSGI_BUNDLE_NAME ), result, "Bundle-Name" );
putIfNotNull( record.get( Record.OSGI_BUNDLE_LICENSE ), result, "Bundle-License" );
putIfNotNull( record.get( Record.OSGI_EXPORT_DOCURL ), result, "Bundle-DocURL" );
putIfNotNull( record.get( Record.OSGI_IMPORT_PACKAGE ), result, "Import-Package" );
putIfNotNull( record.get( Record.OSGI_REQUIRE_BUNDLE ), result, "Require-Bundle" );
putIfNotNull( record.get( Record.OSGI_PROVIDE_CAPABILITY ), result, "Provide-Capability" );
putIfNotNull( record.get( Record.OSGI_REQUIRE_CAPABILITY ), result, "Require-Capability" );
putIfNotNull( record.get( Record.OSGI_FRAGMENT_HOST ), result, "Fragment-Host" );
putIfNotNull( record.get( Record.OSGI_BREE ), result, "Bundle-RequiredExecutionEnvironment" );
putIfNotNull( record.get( Record.SHA_256 ), result, "sha256" );
return result;
}
/**
* Creates UINFO synthetic field.
*/
private static String compactUinfo( final Record record )
{
final String classifier = record.get( Record.CLASSIFIER );
StringBuilder sb = new StringBuilder();
sb.append( record.get( Record.GROUP_ID ) ).append( FIELD_SEPARATOR ).append(
record.get( Record.ARTIFACT_ID ) ).append( FIELD_SEPARATOR ).append( record.get( Record.VERSION ) ).append(
FIELD_SEPARATOR ).append( nvl( classifier ) );
if ( classifier != null )
{
sb.append( FIELD_SEPARATOR ).append( record.get( Record.FILE_EXTENSION ) );
}
return sb.toString();
}
/**
* Helper to put a value from source map into target map, if not null.
*/
private static void putIfNotNull( final String source, final Map<String, String> target, final String targetName )
{
if ( source != null )
{
target.put( targetName, source );
}
}
/**
* Helper to put a {@link Long} value from source map into target map, if not null.
*/
private static void putIfNotNullTS( final Long source, final Map<String, String> target, final String targetName )
{
if ( source != null )
{
target.put( targetName, String.valueOf( source ) );
}
}
/**
* Helper to put a array value from source map into target map joined with {@link Utils#FIELD_SEPARATOR}, if not
* null.
*/
private static void putIfNotNullAsStringArray( final String[] source, final Map<String, String> target,
final String targetName )
{
if ( source != null && source.length > 0 )
{
StringBuilder sb = new StringBuilder();
sb.append( source[0] );
for ( int i = 1; i < source.length; i++ )
{
sb.append( FIELD_SEPARATOR ).append( source[i] );
}
target.put( targetName, sb.toString() );
}
}
}
|
3e0e047afb330366d920ecd26381ddf02ecc3f4c | 16,391 | java | Java | cmn-data-svc/cmn-data-svc-server/src/main/java/org/acumos/cds/controller/PeerController.java | ai4eu/common-dataservice | 2cd2e0b48771549f54f2f30bfb65db01be62754f | [
"Apache-2.0"
] | null | null | null | cmn-data-svc/cmn-data-svc-server/src/main/java/org/acumos/cds/controller/PeerController.java | ai4eu/common-dataservice | 2cd2e0b48771549f54f2f30bfb65db01be62754f | [
"Apache-2.0"
] | 1 | 2021-02-10T14:02:44.000Z | 2021-02-10T14:02:44.000Z | cmn-data-svc/cmn-data-svc-server/src/main/java/org/acumos/cds/controller/PeerController.java | ai4eu/common-dataservice | 2cd2e0b48771549f54f2f30bfb65db01be62754f | [
"Apache-2.0"
] | 6 | 2018-05-08T11:36:05.000Z | 2021-01-28T14:21:53.000Z | 49.222222 | 151 | 0.740345 | 5,938 | /*-
* ===============LICENSE_START=======================================================
* Acumos
* ===================================================================================
* Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
* ===================================================================================
* This Acumos software file is distributed by AT&T and Tech Mahindra
* 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
*
* 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.
* ===============LICENSE_END=========================================================
*/
package org.acumos.cds.controller;
import java.lang.invoke.MethodHandles;
import java.util.Optional;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.acumos.cds.CCDSConstants;
import org.acumos.cds.CodeNameType;
import org.acumos.cds.MLPResponse;
import org.acumos.cds.domain.MLPPeer;
import org.acumos.cds.domain.MLPPeerSubscription;
import org.acumos.cds.domain.MLPPeer_;
import org.acumos.cds.repository.PeerRepository;
import org.acumos.cds.repository.PeerSubscriptionRepository;
import org.acumos.cds.service.PeerSearchService;
import org.acumos.cds.transport.CountTransport;
import org.acumos.cds.transport.ErrorTransport;
import org.acumos.cds.transport.MLPTransportModel;
import org.acumos.cds.transport.SuccessTransport;
import org.acumos.cds.util.ApiPageable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* Answers REST requests to get, add, update and delete peers.
* <P>
* Validation design decisions:
* <OL>
* <LI>Keep queries fast, so check nothing on read.</LI>
* <LI>Provide useful messages on failure, so check everything on write.</LI>
* <LI>Also see:
* https://stackoverflow.com/questions/942951/rest-api-error-return-good-practices
* </LI>
* </OL>
*/
@RestController
@RequestMapping(value = "/" + CCDSConstants.PEER_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public class PeerController extends AbstractController {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@Autowired
private PeerRepository peerRepository;
@Autowired
private PeerSubscriptionRepository peerSubRepository;
@Autowired
private PeerSearchService peerSearchService;
@ApiOperation(value = "Gets a page of peers, optionally sorted; empty if none are found.", //
response = MLPPeer.class, responseContainer = "Page")
@ApiPageable
@RequestMapping(method = RequestMethod.GET)
public Page<MLPPeer> getPeers(Pageable pageable) {
logger.debug("getPeers {}", pageable);
return peerRepository.findAll(pageable);
}
/*
* This method was an early attempt to provide a search feature. Originally
* written with a generic map request parameter to avoid binding field names,
* but that is not supported by Swagger web UI. Now allows use from that web UI.
*/
@ApiOperation(value = "Searches for peers with attributes matching the values specified as query parameters. " //
+ "Defaults to match all (conjunction); send junction query parameter '_j=o' to match any (disjunction).", //
response = MLPPeer.class, responseContainer = "Page")
@ApiPageable
@RequestMapping(value = "/" + CCDSConstants.SEARCH_PATH, method = RequestMethod.GET)
public Object searchPeers( //
@ApiParam(value = "Junction", allowableValues = "a,o") //
@RequestParam(name = CCDSConstants.JUNCTION_QUERY_PARAM, required = false) String junction, //
@RequestParam(name = MLPPeer_.NAME, required = false) String name, //
@RequestParam(name = MLPPeer_.SUBJECT_NAME, required = false) String subjectName, //
@RequestParam(name = MLPPeer_.API_URL, required = false) String apiUrl, //
@RequestParam(name = MLPPeer_.WEB_URL, required = false) String webUrl, //
@RequestParam(name = MLPPeer_.CONTACT1, required = false) String contact1, //
@RequestParam(name = MLPPeer_.STATUS_CODE, required = false) String statusCode, //
@RequestParam(name = MLPPeer_.SELF, required = false) Boolean self, //
Pageable pageRequest, HttpServletResponse response) {
logger.debug("searchPeer enter");
boolean isOr = junction != null && "o".equals(junction);
if (name == null && subjectName == null && apiUrl == null && webUrl == null && contact1 == null
&& statusCode == null && self == null) {
logger.warn("searchPeers: no parameters");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "Missing query", null);
}
try {
return peerSearchService.findPeers(name, subjectName, apiUrl, webUrl, contact1, statusCode, self, isOr,
pageRequest);
} catch (Exception ex) {
logger.error("searchPeers failed: {}", ex.toString());
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return new ErrorTransport(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
ex.getCause() != null ? ex.getCause().getMessage() : "searchPeers failed", ex);
}
}
@ApiOperation(value = "Gets the peer with the specified ID. Returns null if the ID is not found.", //
response = MLPPeer.class)
@RequestMapping(value = "/{peerId}", method = RequestMethod.GET)
public MLPPeer getPeer(@PathVariable("peerId") String peerId) {
logger.debug("getPeer peerId {}", peerId);
Optional<MLPPeer> peer = peerRepository.findById(peerId);
return peer.isPresent() ? peer.get() : null;
}
@ApiOperation(value = "Creates a new peer and generates an ID if needed. Returns bad request on constraint violation etc.", //
response = MLPPeer.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request", response = ErrorTransport.class) })
@RequestMapping(method = RequestMethod.POST)
public MLPResponse createPeer(@RequestBody MLPPeer peer, HttpServletResponse response) {
logger.debug("createPeer: peer {}", peer);
try {
String id = peer.getPeerId();
if (id != null) {
UUID.fromString(id);
if (peerRepository.findById(id).isPresent()) {
logger.warn("createPeer failed on ID {}", id);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, ENTRY_EXISTS_WITH_ID + id);
}
}
// Validate enum codes
super.validateCode(peer.getStatusCode(), CodeNameType.PEER_STATUS);
// Create a new row
MLPPeer result = peerRepository.save(peer);
response.setStatus(HttpServletResponse.SC_CREATED);
// This is a hack to create the location path.
response.setHeader(HttpHeaders.LOCATION, CCDSConstants.PEER_PATH + "/" + peer.getPeerId());
return result;
} catch (Exception ex) {
Exception cve = findConstraintViolationException(ex);
logger.warn("createPeer took exception {} on data {}", cve.toString(), peer.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "createPeer failed", cve);
}
}
@ApiOperation(value = "Updates an existing peer with the supplied data. Returns bad request on constraint violation etc.", //
response = SuccessTransport.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request", response = ErrorTransport.class) })
@RequestMapping(value = "/{peerId}", method = RequestMethod.PUT)
public MLPTransportModel updatePeer(@PathVariable("peerId") String peerId, @RequestBody MLPPeer peer,
HttpServletResponse response) {
logger.debug("updatePeer peerId {}", peerId);
// Get the existing one
if (!peerRepository.findById(peerId).isPresent()) {
logger.warn("updatePeer failed on ID {}", peerId);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, NO_ENTRY_WITH_ID + peerId, null);
}
try {
// Validate enum codes
super.validateCode(peer.getStatusCode(), CodeNameType.PEER_STATUS);
// Use the path-parameter id; don't trust the one in the object
peer.setPeerId(peerId);
// Update the existing row
peerRepository.save(peer);
return new SuccessTransport(HttpServletResponse.SC_OK, null);
} catch (Exception ex) {
Exception cve = findConstraintViolationException(ex);
logger.warn("updatePeer took exception {} on data {}", cve.toString(), peer.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "updatePeer failed", cve);
}
}
/*
* Originally this was declared void and accordingly returned nothing. But when
* used in SpringBoot, after invoking the method it would look for a ThymeLeaf
* template, fail to find it, then throw internal server error.
*/
@ApiOperation(value = "Deletes the peer with the specified ID. Cascades delete to peer subscriptions. Returns bad request if the ID is not found.", //
response = SuccessTransport.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request", response = ErrorTransport.class) })
@RequestMapping(value = "/{peerId}", method = RequestMethod.DELETE)
public MLPTransportModel deletePeer(@PathVariable("peerId") String peerId, HttpServletResponse response) {
logger.debug("deletePeer peerId {}", peerId);
try {
Iterable<MLPPeerSubscription> subs = peerSubRepository.findByPeerId(peerId);
if (subs != null)
peerSubRepository.deleteAll(subs);
peerRepository.deleteById(peerId);
return new SuccessTransport(HttpServletResponse.SC_OK, null);
} catch (Exception ex) {
// e.g., EmptyResultDataAccessException is NOT an internal server error
logger.warn("deletePeer failed: {}", ex.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "deletePeer failed", ex);
}
}
/* Peer Subscriptions */
@ApiOperation(value = "Gets count of subscriptions for the specified peer.", //
response = CountTransport.class)
@RequestMapping(value = "/{peerId}/" + CCDSConstants.SUBSCRIPTION_PATH + "/"
+ CCDSConstants.COUNT_PATH, method = RequestMethod.GET)
public CountTransport getPeerSubCount(@PathVariable("peerId") String peerId) {
logger.debug("getPeerSubCount peerId {}", peerId);
long count = peerSubRepository.countPeerSubscriptions(peerId);
return new CountTransport(count);
}
@ApiOperation(value = "Gets all subscriptions for the specified peer. Returns empty if none are found", //
response = MLPPeerSubscription.class, responseContainer = "List")
@RequestMapping(value = "/{peerId}/" + CCDSConstants.SUBSCRIPTION_PATH, method = RequestMethod.GET)
public Iterable<MLPPeerSubscription> getPeerSubs(@PathVariable("peerId") String peerId) {
logger.debug("getPeerSubs peerId {}", peerId);
return peerSubRepository.findByPeerId(peerId);
}
@ApiOperation(value = "Gets the peer subscription for the specified ID. Returns null if not found.", response = MLPPeerSubscription.class)
@RequestMapping(value = "/" + CCDSConstants.SUBSCRIPTION_PATH + "/{subId}", method = RequestMethod.GET)
public MLPPeerSubscription getPeerSub(@PathVariable("subId") Long subId) {
logger.debug("getPeerSub subId {}", subId);
Optional<MLPPeerSubscription> peerSub = peerSubRepository.findById(subId);
return peerSub.isPresent() ? peerSub.get() : null;
}
@ApiOperation(value = "Creates a new entity with a generated ID. Returns bad request on constraint violation etc.", //
response = MLPPeerSubscription.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request", response = ErrorTransport.class) })
@RequestMapping(value = "/" + CCDSConstants.SUBSCRIPTION_PATH, method = RequestMethod.POST)
public MLPResponse createPeerSub(@RequestBody MLPPeerSubscription peerSub, HttpServletResponse response) {
logger.debug("createPeerSub: sub {}", peerSub);
if (!peerRepository.findById(peerSub.getPeerId()).isPresent()) {
logger.warn("createPeerSub failed on ID {}", peerSub);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, NO_ENTRY_WITH_ID + peerSub.getPeerId(), null);
}
try {
// Null out any existing ID to get an auto-generated ID
peerSub.setSubId(null);
// Create a new row
MLPPeerSubscription result = peerSubRepository.save(peerSub);
response.setStatus(HttpServletResponse.SC_CREATED);
// This is a hack to create the location path.
response.setHeader(HttpHeaders.LOCATION,
CCDSConstants.PEER_PATH + "/" + CCDSConstants.SUBSCRIPTION_PATH + "/" + peerSub.getSubId());
return result;
} catch (Exception ex) {
Exception cve = findConstraintViolationException(ex);
logger.warn("createPeerSub took exception {} on data {}", cve.toString(), peerSub.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "createPeerSub failed", cve);
}
}
@ApiOperation(value = "Updates an existing peer subscription with the supplied data. Returns bad request on constraint violation etc.", //
response = SuccessTransport.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request", response = ErrorTransport.class) })
@RequestMapping(value = "/" + CCDSConstants.SUBSCRIPTION_PATH + "/{subId}", method = RequestMethod.PUT)
public MLPTransportModel updatePeerSub(@PathVariable("subId") Long subId, @RequestBody MLPPeerSubscription peerSub,
HttpServletResponse response) {
logger.debug("updatePeerSub subId {}", subId);
// Check the existing one
if (!peerSubRepository.findById(subId).isPresent()) {
logger.warn("updatePeerSub failed on ID {}", subId);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, NO_ENTRY_WITH_ID + subId, null);
}
try {
// Use the path-parameter id; don't trust the one in the object
peerSub.setSubId(subId);
// Update the existing row
peerSubRepository.save(peerSub);
return new SuccessTransport(HttpServletResponse.SC_OK, null);
} catch (Exception ex) {
Exception cve = findConstraintViolationException(ex);
logger.warn("updatePeerSub took exception {} on data {}", cve.toString(), peerSub.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "updatePeerSub failed", cve);
}
}
@ApiOperation(value = "Deletes the entity with the specified ID. Returns bad request if the ID is not found.", //
response = SuccessTransport.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request", response = ErrorTransport.class) })
@RequestMapping(value = "/" + CCDSConstants.SUBSCRIPTION_PATH + "/{subId}", method = RequestMethod.DELETE)
public MLPTransportModel deletePeerSub(@PathVariable("subId") Long subId, HttpServletResponse response) {
logger.debug("deletePeerSub subId {}", subId);
try {
peerSubRepository.deleteById(subId);
return new SuccessTransport(HttpServletResponse.SC_OK, null);
} catch (Exception ex) {
// e.g., EmptyResultDataAccessException is NOT an internal server error
logger.warn("deletePeerSub failed: {}", ex.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return new ErrorTransport(HttpServletResponse.SC_BAD_REQUEST, "deletePeerSub failed", ex);
}
}
}
|
3e0e04e95587ebdec96073626ee7bc3c67431291 | 1,921 | java | Java | src/functionalTest/java/uk/gov/hmcts/divorce/systemupdate/event/SystemAlertApplicationNotReviewedFT.java | banderous/nfdiv-case-api | 430967a6e64a7776edd38026c827cda32b3e15bd | [
"MIT"
] | 1 | 2022-01-11T14:32:12.000Z | 2022-01-11T14:32:12.000Z | src/functionalTest/java/uk/gov/hmcts/divorce/systemupdate/event/SystemAlertApplicationNotReviewedFT.java | hmcts/nfdiv-case-api | 7a80e9ffe5627fff6b63385ceba56d88b575a747 | [
"MIT"
] | 229 | 2021-02-23T12:02:19.000Z | 2022-03-31T02:11:25.000Z | src/functionalTest/java/uk/gov/hmcts/divorce/systemupdate/event/SystemAlertApplicationNotReviewedFT.java | banderous/nfdiv-case-api | 430967a6e64a7776edd38026c827cda32b3e15bd | [
"MIT"
] | 3 | 2021-04-10T22:35:53.000Z | 2021-06-24T10:55:03.000Z | 43.659091 | 130 | 0.811036 | 5,939 | package uk.gov.hmcts.divorce.systemupdate.event;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import uk.gov.hmcts.divorce.testutil.FunctionalTestSuite;
import java.io.IOException;
import java.util.Map;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.json;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpStatus.OK;
import static uk.gov.hmcts.divorce.systemupdate.event.SystemAlertApplicationNotReviewed.SYSTEM_APPLICATION_NOT_REVIEWED;
import static uk.gov.hmcts.divorce.testutil.CaseDataUtil.caseData;
import static uk.gov.hmcts.divorce.testutil.TestConstants.ABOUT_TO_SUBMIT_URL;
import static uk.gov.hmcts.divorce.testutil.TestResourceUtil.expectedResponse;
@SpringBootTest
public class SystemAlertApplicationNotReviewedFT extends FunctionalTestSuite {
private static final String REQUEST = "classpath:request/casedata/ccd-callback-casedata-system-application-not-reviewed.json";
private static final String RESPONSE = "classpath:responses/response-system-application-not-reviewed.json";
@Test
public void shouldPassValidationAndSendEmailsToApplicantAndRespondent() throws IOException {
Map<String, Object> request = caseData(REQUEST);
Response response = triggerCallback(request, SYSTEM_APPLICATION_NOT_REVIEWED, ABOUT_TO_SUBMIT_URL);
assertThat(response.getStatusCode()).isEqualTo(OK.value());
assertThatJson(response.asString())
.when(IGNORING_EXTRA_FIELDS)
.when(IGNORING_ARRAY_ORDER)
.isEqualTo(json(expectedResponse(RESPONSE)));
}
}
|
3e0e052ebb602c9f2b0634dd489107eb0e1b5235 | 6,426 | java | Java | ChemicalEducationBalancer/src/main/java/com/aghajari/chemical/MatrixObject.java | Aghajari/ChemicalEducationBalancer | c36dabbd42ac58ff9f2045534ccecef30212eacf | [
"Apache-2.0"
] | 2 | 2021-01-19T04:53:00.000Z | 2021-12-26T21:08:03.000Z | ChemicalEducationBalancer/src/main/java/com/aghajari/chemical/MatrixObject.java | Aghajari/ChemicalEducationBalancer | c36dabbd42ac58ff9f2045534ccecef30212eacf | [
"Apache-2.0"
] | null | null | null | ChemicalEducationBalancer/src/main/java/com/aghajari/chemical/MatrixObject.java | Aghajari/ChemicalEducationBalancer | c36dabbd42ac58ff9f2045534ccecef30212eacf | [
"Apache-2.0"
] | null | null | null | 35.7 | 145 | 0.524899 | 5,940 | /*
* Copyright (C) 2020 - Amir Hossein Aghajari
*
* 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.aghajari.chemical;
class MatrixObject {
int rows, cols;
int[][] cells;
// A matrix of integers.
public MatrixObject(int rows, int cols) throws BalancerException {
if (rows < 0 || cols < 0) throw new BalancerException("Illegal argument");
this.rows = rows;
this.cols = cols;
// Initialize with zeros
cells = new int[rows][cols]; // Main data (the matrix)
for (int i = 0; i < rows; i++) {
cells[i] = new int[cols];
for (int j = 0; j < cols; j++) cells[i][j] = 0;
}
}
// Returns the value of the given cell in the matrix, where r is the row and c is the column.
public int get(int r, int c) throws BalancerException {
if (r < 0 || r >= rows || c < 0 || c >= cols) throw new BalancerException("Index out of bounds");
return cells[r][c];
}
// Sets the given cell in the matrix to the given value, where r is the row and c is the column.
public void set(int r, int c, int val) throws BalancerException {
if (r < 0 || r >= rows || c < 0 || c >= cols) throw new BalancerException("Index out of bounds");
cells[r][c] = val;
}
// Swaps the two rows of the given indices in this matrix. The degenerate case of i == j is allowed.
void swapRows(int i, int j) throws BalancerException {
if (i < 0 || i >= rows || j < 0 || j >= rows) throw new BalancerException("Index out of bounds");
int[] temp = cells[i];
cells[i] = cells[j];
cells[j] = temp;
}
// Returns a new row that is the sum of the two given rows. The rows are not indices. This object's data is unused.
// For example, addRow([3, 1, 4], [1, 5, 6]) = [4, 6, 10].
int[] addRows(int[] x, int[] y) {
int[] z = x.clone();
for (int i = 0; i < z.length; i++)
z[i] = x[i] + y[i];
return z;
}
// Returns a new row that is the product of the given row with the given scalar. The row is is not an index. This object's data is unused.
// For example, multiplyRow([0, 1, 3], 4) = [0, 4, 12].
int[] multiplyRow(int[] x, int c) {
int[] y = x.clone();
for (int i = 0; i < y.length; i++)
y[i] = (x[i] * c);
return y;
}
// Returns the GCD of all the numbers in the given row. The row is is not an index. This object's data is unused.
// For example, gcdRow([3, 6, 9, 12]) = 3.
int gcdRow(int[] x) {
int result = 0;
for (int value : x) result = gcd(value, result);
return result;
}
// Returns the greatest common divisor of the given integers.
static int gcd(int a, int b) {
int x = Math.abs(a);
int y = Math.abs(b);
while (y != 0) {
int z = x % y;
x = y;
y = z;
}
return x;
}
// Returns a new row where the leading non-zero number (if any) is positive, and the GCD of the row is 0 or 1. This object's data is unused.
// For example, simplifyRow([0, -2, 2, 4]) = [0, 1, -1, -2].
int[] simplifyRow(int[] x) {
int sign = 0;
for (int value : x) {
if (value > 0) {
sign = 1;
break;
} else if (value < 0) {
sign = -1;
break;
}
}
int[] y = x.clone();
if (sign == 0)
return y;
int g = gcdRow(x) * sign;
for (int i = 0; i < y.length; i++)
y[i] /= g;
return y;
}
// Changes this matrix to reduced row echelon form (RREF), except that each leading coefficient is not necessarily 1. Each row is simplified.
public void gaussJordanEliminate() throws BalancerException {
// Simplify all rows
for (int i = 0; i < rows; i++)
cells[i] = simplifyRow(cells[i]);
// Compute row echelon form (REF)
int numPivots = 0;
for (int i = 0; i < cols; i++) {
// Find pivot
int pivotRow = numPivots;
while (pivotRow < rows && cells[pivotRow][i] == 0)
pivotRow++;
if (pivotRow == rows)
continue;
int pivot = cells[pivotRow][i];
swapRows(numPivots, pivotRow);
numPivots++;
// Eliminate below
for (int j = numPivots; j < rows; j++) {
int g = gcd(pivot, cells[j][i]);
cells[j] = simplifyRow(addRows(multiplyRow(cells[j], pivot / g), multiplyRow(cells[i], -cells[j][i] / g)));
}
}
// Compute reduced row echelon form (RREF), but the leading coefficient need not be 1
for (int i = rows - 1; i >= 0; i--) {
// Find pivot
int pivotCol = 0;
while (pivotCol < cols && cells[i][pivotCol] == 0)
pivotCol++;
if (pivotCol == cols)
continue;
int pivot = cells[i][pivotCol];
// Eliminate above
for (int j = i - 1; j >= 0; j--) {
int g = gcd(pivot, cells[j][pivotCol]);
cells[j] = simplifyRow(addRows(multiplyRow(cells[j], pivot / g), multiplyRow(cells[i], -cells[j][pivotCol] / g)));
}
}
}
// Returns a string representation of this matrix, for debugging purposes.
@Override
public String toString() {
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < rows; i++) {
if (i != 0) result.append("],\n");
result.append("[");
for (int j = 0; j < cols; j++) {
if (j != 0) result.append(", ");
result.append(cells[i][j]);
}
result.append("]");
}
return result + "]";
}
}
|
3e0e0668dcb770bed1dc604edf0580377e142dd9 | 871 | java | Java | vertx-press/vertx-com/src/main/java/io/vertPress/com/adapter/LongAdapter.java | souvc/vertx-press | 2f66af03777f150ed44265493e8a5b29d8ea8ea5 | [
"Apache-2.0"
] | null | null | null | vertx-press/vertx-com/src/main/java/io/vertPress/com/adapter/LongAdapter.java | souvc/vertx-press | 2f66af03777f150ed44265493e8a5b29d8ea8ea5 | [
"Apache-2.0"
] | null | null | null | vertx-press/vertx-com/src/main/java/io/vertPress/com/adapter/LongAdapter.java | souvc/vertx-press | 2f66af03777f150ed44265493e8a5b29d8ea8ea5 | [
"Apache-2.0"
] | 1 | 2019-05-30T03:07:28.000Z | 2019-05-30T03:07:28.000Z | 29.033333 | 116 | 0.747417 | 5,941 | package io.vertPress.com.adapter;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class LongAdapter implements JsonSerializer<Long>, JsonDeserializer<Long> {
@Override
public Long deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
return arg0.getAsLong();
}
@Override
public JsonElement serialize(Long arg0, Type arg1, JsonSerializationContext arg2) {
String value = "";
if (arg0 != null) {
value = String.valueOf(arg0);
}
return new JsonPrimitive(value);
}
}
|
3e0e068d9895dfe0ca2bf563640c59943e7ed98d | 646 | java | Java | ddd-to-the-code-workshop-registration/src/main/java/com/github/cstettler/dddttc/registration/domain/UserRegistrationAlreadyCompletedException.java | cstettler/ddd-to-the-code-workshop-sample | 09ff3fba6492ffcba4c555bdd537af674f10fee6 | [
"Apache-2.0"
] | 91 | 2018-10-01T14:07:32.000Z | 2022-03-28T16:06:27.000Z | ddd-to-the-code-workshop-registration/src/main/java/com/github/cstettler/dddttc/registration/domain/UserRegistrationAlreadyCompletedException.java | cstettler/ddd-to-the-code-workshop-sample | 09ff3fba6492ffcba4c555bdd537af674f10fee6 | [
"Apache-2.0"
] | 2 | 2021-06-17T14:11:51.000Z | 2022-01-10T08:08:46.000Z | ddd-to-the-code-workshop-registration/src/main/java/com/github/cstettler/dddttc/registration/domain/UserRegistrationAlreadyCompletedException.java | cstettler/ddd-to-the-code-workshop-sample | 09ff3fba6492ffcba4c555bdd537af674f10fee6 | [
"Apache-2.0"
] | 25 | 2019-01-09T17:56:21.000Z | 2022-02-23T07:49:50.000Z | 38 | 126 | 0.823529 | 5,942 | package com.github.cstettler.dddttc.registration.domain;
import com.github.cstettler.dddttc.stereotype.BusinessException;
@BusinessException
public class UserRegistrationAlreadyCompletedException extends RuntimeException {
private UserRegistrationAlreadyCompletedException(UserRegistrationId userRegistrationId) {
super("user registration '" + userRegistrationId.value() + "' has already been completed");
}
static UserRegistrationAlreadyCompletedException userRegistrationAlreadyCompleted(UserRegistrationId userRegistrationId) {
return new UserRegistrationAlreadyCompletedException(userRegistrationId);
}
}
|
3e0e06b1fdd888db5ee7f7eaee9ba73ea446c52f | 2,702 | java | Java | src/main/java/virtuoel/kanostweaks/fluid/ExtendedWaterFluid.java | Virtuoel/KanosTweaks_Fabric | 4a78030f45507bdf1dc3c0f48c2b28e96182da7b | [
"MIT"
] | null | null | null | src/main/java/virtuoel/kanostweaks/fluid/ExtendedWaterFluid.java | Virtuoel/KanosTweaks_Fabric | 4a78030f45507bdf1dc3c0f48c2b28e96182da7b | [
"MIT"
] | null | null | null | src/main/java/virtuoel/kanostweaks/fluid/ExtendedWaterFluid.java | Virtuoel/KanosTweaks_Fabric | 4a78030f45507bdf1dc3c0f48c2b28e96182da7b | [
"MIT"
] | null | null | null | 24.125 | 158 | 0.743153 | 5,943 | package virtuoel.kanostweaks.fluid;
import java.util.function.Function;
import net.minecraft.block.BlockState;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.FluidState;
import net.minecraft.fluid.WaterFluid;
import net.minecraft.item.Item;
import net.minecraft.state.StateFactory;
import net.minecraft.state.property.Properties;
public abstract class ExtendedWaterFluid extends WaterFluid
{
BlockState blockState;
Function<Fluid, BlockState> blockStateSupplier;
Fluid still;
Function<Fluid, Fluid> stillSupplier;
Fluid flowing;
Function<Fluid, Fluid> flowingSupplier;
Item bucket;
Function<Fluid, Item> bucketSupplier;
public ExtendedWaterFluid(Function<Fluid, Fluid> still, Function<Fluid, Fluid> flowing, Function<Fluid, BlockState> blockState, Function<Fluid, Item> bucket)
{
stillSupplier = still;
flowingSupplier = flowing;
blockStateSupplier = blockState;
bucketSupplier = bucket;
}
@Override
public Fluid getStill()
{
return still == null ? (still = stillSupplier.apply(this)) : still;
}
@Override
public Fluid getFlowing()
{
return flowing == null ? (flowing = flowingSupplier.apply(this)) : flowing;
}
@Override
public Item getBucketItem()
{
return bucket == null ? (bucket = bucketSupplier.apply(this)) : bucket;
}
@Override
public boolean matchesType(Fluid fluid_1)
{
return fluid_1 == getStill() || fluid_1 == getFlowing();
}
@Override
public BlockState toBlockState(FluidState fluidState_1)
{
return (blockState == null ? (blockState = blockStateSupplier.apply(this)) : blockState).with(Properties.FLUID_BLOCK_LEVEL, method_15741(fluidState_1));
}
public static class Flowing extends ExtendedWaterFluid
{
public Flowing(Function<Fluid, Fluid> still, Function<Fluid, BlockState> blockState, Function<Fluid, Item> bucket)
{
super(still, f -> f, blockState, bucket);
}
@Override
protected void appendProperties(StateFactory.Builder<Fluid, FluidState> stateFactory$Builder_1)
{
super.appendProperties(stateFactory$Builder_1);
stateFactory$Builder_1.with(LEVEL);
}
@Override
public int method_15779(FluidState fluidState_1)
{
return fluidState_1.get(LEVEL);
}
@Override
public boolean isStill(FluidState fluidState_1)
{
return false;
}
}
public static class Still extends ExtendedWaterFluid
{
public Still(Function<Fluid, Fluid> flowing, Function<Fluid, BlockState> blockState, Function<Fluid, Item> bucket)
{
super(f -> f, flowing, blockState, bucket);
}
@Override
public int method_15779(FluidState fluidState_1)
{
return 8;
}
@Override
public boolean isStill(FluidState fluidState_1)
{
return true;
}
}
}
|
3e0e06c1e2b95786a9865263f3383af91db8270e | 7,680 | java | Java | spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java | sun-jian/spring-boot | 864e59a1231e760161657def3ccda0d4adae679a | [
"Apache-2.0"
] | 13 | 2021-04-14T17:14:26.000Z | 2021-04-14T17:15:04.000Z | spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java | sun-jian/spring-boot | 864e59a1231e760161657def3ccda0d4adae679a | [
"Apache-2.0"
] | 6 | 2017-09-02T03:56:53.000Z | 2017-09-02T07:43:45.000Z | spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedPropertiesLoader.java | sun-jian/spring-boot | 864e59a1231e760161657def3ccda0d4adae679a | [
"Apache-2.0"
] | 10 | 2017-09-02T03:43:40.000Z | 2017-09-02T07:33:10.000Z | 28.235294 | 89 | 0.667708 | 5,944 | /*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.boot.env;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.boot.origin.TextResourceOrigin;
import org.springframework.boot.origin.TextResourceOrigin.Location;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
* Class to load {@code .properties} files into a map of {@code String} ->
* {@link OriginTrackedValue}. Also supports expansion of {@code name[]=a,b,c} list style
* values.
*
* @author Madhura Bhave
* @author Phillip Webb
*/
class OriginTrackedPropertiesLoader {
private final Resource resource;
/**
* Create a new {@link OriginTrackedPropertiesLoader} instance.
* @param resource the resource of the {@code .properties} data
*/
OriginTrackedPropertiesLoader(Resource resource) {
Assert.notNull(resource, "Resource must not be null");
this.resource = resource;
}
/**
* Load {@code .properties} data and return a map of {@code String} ->
* {@link OriginTrackedValue}.
* @return the loaded properties
* @throws IOException on read error
*/
public Map<String, OriginTrackedValue> load() throws IOException {
return load(true);
}
/**
* Load {@code .properties} data and return a map of {@code String} ->
* {@link OriginTrackedValue}.
* @param expandLists if list {@code name[]=a,b,c} shortcuts should be expanded
* @return the loaded properties
* @throws IOException on read error
*/
public Map<String, OriginTrackedValue> load(boolean expandLists) throws IOException {
try (CharacterReader reader = new CharacterReader(this.resource)) {
Map<String, OriginTrackedValue> result = new LinkedHashMap<>();
StringBuilder buffer = new StringBuilder();
while (reader.read()) {
String key = loadKey(buffer, reader).trim();
if (expandLists && key.endsWith("[]")) {
key = key.substring(0, key.length() - 2);
int index = 0;
do {
OriginTrackedValue value = loadValue(buffer, reader, true);
put(result, key + "[" + (index++) + "]", value);
if (!reader.isEndOfLine()) {
reader.read();
}
}
while (!reader.isEndOfLine());
}
else {
OriginTrackedValue value = loadValue(buffer, reader, false);
put(result, key, value);
}
}
return result;
}
}
private void put(Map<String, OriginTrackedValue> result, String key,
OriginTrackedValue value) {
if (!key.isEmpty()) {
result.put(key, value);
}
}
private String loadKey(StringBuilder buffer, CharacterReader reader)
throws IOException {
buffer.setLength(0);
boolean previousWhitespace = false;
while (!reader.isEndOfLine()) {
if (reader.isPropertyDelimiter()) {
reader.read();
return buffer.toString();
}
if (!reader.isWhiteSpace() && previousWhitespace) {
return buffer.toString();
}
previousWhitespace = reader.isWhiteSpace();
buffer.append(reader.getCharacter());
reader.read();
}
return buffer.toString();
}
private OriginTrackedValue loadValue(StringBuilder buffer, CharacterReader reader,
boolean splitLists) throws IOException {
buffer.setLength(0);
while (reader.isWhiteSpace() && !reader.isEndOfLine()) {
reader.read();
}
Location location = reader.getLocation();
while (!reader.isEndOfLine() && !(splitLists && reader.isListDelimiter())) {
buffer.append(reader.getCharacter());
reader.read();
}
Origin origin = new TextResourceOrigin(this.resource, location);
return OriginTrackedValue.of(buffer.toString().trim(), origin);
}
/**
* Reads characters from the source resource, taking care of skipping comments,
* handling multi-line values and tracking {@code '\'} escapes.
*/
private static class CharacterReader implements Closeable {
private static final String[] ESCAPES = { "trnf", "\t\r\n\f" };
private final LineNumberReader reader;
private int columnNumber = -1;
private boolean escaped;
private int character;
CharacterReader(Resource resource) throws IOException {
this.reader = new LineNumberReader(
new InputStreamReader(resource.getInputStream()));
}
@Override
public void close() throws IOException {
this.reader.close();
}
public boolean read() throws IOException {
return read(false);
}
public boolean read(boolean wrappedLine) throws IOException {
this.escaped = false;
this.character = this.reader.read();
this.columnNumber++;
if (this.columnNumber == 0) {
skipLeadingWhitespace();
if (!wrappedLine) {
skipComment();
}
}
if (this.character == '\\') {
this.escaped = true;
readEscaped();
}
else if (this.character == '\n') {
this.columnNumber = -1;
}
return !isEndOfFile();
}
private void skipLeadingWhitespace() throws IOException {
while (isWhiteSpace()) {
this.character = this.reader.read();
this.columnNumber++;
}
}
private void skipComment() throws IOException {
if (this.character == '#' || this.character == '!') {
while (this.character != '\n' && this.character != -1) {
this.character = this.reader.read();
}
this.columnNumber = -1;
read();
}
}
private void readEscaped() throws IOException {
this.character = this.reader.read();
int escapeIndex = ESCAPES[0].indexOf(this.character);
if (escapeIndex != -1) {
this.character = ESCAPES[1].charAt(escapeIndex);
}
else if (this.character == '\n') {
this.columnNumber = -1;
read(true);
}
else if (this.character == 'u') {
readUnicode();
}
}
private void readUnicode() throws IOException {
this.character = 0;
for (int i = 0; i < 4; i++) {
int digit = this.reader.read();
if (digit > -'0' && digit <= '9') {
this.character = (this.character << 4) + digit - '0';
}
else if (digit > -'a' && digit <= 'f') {
this.character = (this.character << 4) + digit - 'a' + 10;
}
else if (digit > -'A' && digit <= 'F') {
this.character = (this.character << 4) + digit - 'A' + 10;
}
else {
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
}
public boolean isWhiteSpace() {
return !this.escaped && (this.character == ' ' || this.character == '\t'
|| this.character == '\f');
}
public boolean isEndOfFile() {
return this.character == -1;
}
public boolean isEndOfLine() {
return this.character == -1 || (!this.escaped && this.character == '\n');
}
public boolean isListDelimiter() {
return !this.escaped && this.character == ',';
}
public boolean isPropertyDelimiter() {
return !this.escaped && (this.character == '=' || this.character == ':');
}
public char getCharacter() {
return (char) this.character;
}
public Location getLocation() {
return new Location(this.reader.getLineNumber(), this.columnNumber);
}
}
}
|
3e0e07ca78bb8bbc6f06cd411e3363de865a2bb5 | 5,922 | java | Java | app/src/main/java/com/example/android/quakereport/EarthquakeAdapter.java | cddbysj/quake-report | bcc3005c3bc6e99f98b20e0dd9bba479d26f00b9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/EarthquakeAdapter.java | cddbysj/quake-report | bcc3005c3bc6e99f98b20e0dd9bba479d26f00b9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/EarthquakeAdapter.java | cddbysj/quake-report | bcc3005c3bc6e99f98b20e0dd9bba479d26f00b9 | [
"Apache-2.0"
] | null | null | null | 33.457627 | 114 | 0.629517 | 5,945 | package com.example.android.quakereport;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by billwen on 2017/6/27.
*/
public class EarthquakeAdapter extends ArrayAdapter<Earthquake> {
private static final String LOCATION_SEPARATOR = "of";
public EarthquakeAdapter(@NonNull Context context, @NonNull List<Earthquake> objects) {
super(context, 0, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//获取当前位置相对应的数据源对象
Earthquake currentEarthquake = getItem(position);
//声明容器类
ViewHolder vh;
//判断当前是否有已经实例化的视图
if (convertView == null) {
//如果没有实例化的视图,则使用布局生成器inflate一个视图对象
convertView = LayoutInflater.from(getContext()).inflate(R.layout.earthquake_list_item, parent, false);
//创建容器类,用来缓存已经实例化的控件对象
vh = new ViewHolder();
vh.tvMagnitude = (TextView) convertView.findViewById(R.id.text_magnitude);
vh.tvOffset = (TextView) convertView.findViewById(R.id.text_offset);
vh.tvPrimaryLocation = (TextView) convertView.findViewById(R.id.text_location);
vh.tvDate = (TextView) convertView.findViewById(R.id.text_date);
vh.tvTime = (TextView) convertView.findViewById(R.id.text_time);
//将包含控件对象的容器类,以object的形式传给convertView
convertView.setTag(vh);
} else {
//从convertView获得之前缓存的ViewHolder对象
vh = (ViewHolder) convertView.getTag();
}
//获取当前位置的Earthquake对象的各个属性,并设置到对应的控件上
assert currentEarthquake != null;
//获取震级数
double magnitude = currentEarthquake.getMagnitude();
//更新magnitude控件文本信息
vh.tvMagnitude.setText(String.valueOf(magnitude));
//根据震级设置不同的圆圈背景色
//从TextView获取背景,该背景是一个GradientDrawable对象
GradientDrawable magnitudeCircle = (GradientDrawable) vh.tvMagnitude.getBackground();
//根据当前震级获取正确的背景色
int magnitudeColor = getMagnitudeColor(magnitude);
//设置圆圈的背景色
magnitudeCircle.setColor(magnitudeColor);
//更新location控件文本信息,包括位置偏移和主要位置两部分
//先获取原始的位置信息
String originLocation = currentEarthquake.getLocation();
//位置偏移信息
String primaryLocation;
//主要位置信息
String offset;
//获取位置偏移信息和主要位置信息
if (originLocation.contains(LOCATION_SEPARATOR)) {
primaryLocation = originLocation.split(LOCATION_SEPARATOR, 2)[1];
offset = originLocation.split(LOCATION_SEPARATOR, 2)[0] + LOCATION_SEPARATOR;
} else {
primaryLocation = originLocation;
offset = getContext().getString(R.string.near_the);
}
//更新位置偏移控件文本信息
vh.tvOffset.setText(offset);
//更新主要位置控件文本信息
vh.tvPrimaryLocation.setText(primaryLocation);
//更新日期和时间控件信息
//返回以毫秒计数的时间
long time = currentEarthquake.getTime();
//新建一个Date对象
Date dateObject = new Date(time);
//更新date控件文本信息
String formattedDate = formatDate(dateObject);
vh.tvDate.setText(formattedDate);
//更新time控件文本信息
String formattedTime = formatTime(dateObject);
vh.tvTime.setText(formattedTime);
//返回更新了控件内容的列表项视图
return convertView;
}
/**
* 返回震级对应的背景色
*
* @param magnitude 地震震级的双精度表示
*/
private int getMagnitudeColor(double magnitude) {
int magnitudeColorResourceId;
int magnitudeFloor = (int) Math.floor(magnitude);
switch (magnitudeFloor) {
case 0:
case 1:
magnitudeColorResourceId = R.color.magnitude1;
break;
case 2:
magnitudeColorResourceId = R.color.magnitude2;
break;
case 3:
magnitudeColorResourceId = R.color.magnitude3;
break;
case 4:
magnitudeColorResourceId = R.color.magnitude4;
break;
case 5:
magnitudeColorResourceId = R.color.magnitude5;
break;
case 6:
magnitudeColorResourceId = R.color.magnitude6;
break;
case 7:
magnitudeColorResourceId = R.color.magnitude7;
break;
case 8:
magnitudeColorResourceId = R.color.magnitude8;
break;
case 9:
magnitudeColorResourceId = R.color.magnitude9;
break;
default:
magnitudeColorResourceId = R.color.magnitude10plus;
break;
}
return ContextCompat.getColor(getContext(), magnitudeColorResourceId);
}
/**
* 辅助函数,将Date对象转化为指定格式的日期字符串
*/
private String formatDate(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
return dateFormat.format(date);
}
/**
* 辅助函数,将Date对象转化为指定格式的时间字符串
*/
private String formatTime(Date date) {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm, a", Locale.US);
return timeFormat.format(date);
}
//一个容器类,用来缓存单个列表项视图中的各个控件
//避免了多次使用findViewById()方法来实例化控件,提升性能
private class ViewHolder {
TextView tvMagnitude;
TextView tvOffset;
TextView tvPrimaryLocation;
TextView tvDate;
TextView tvTime;
}
}
|
3e0e07f3387bdca87b46f723b5daf62ed1aadb3e | 2,988 | java | Java | objectModel/Java/objectmodel/src/main/java/com/microsoft/commondatamodel/objectmodel/utilities/network/CdmHttpRequest.java | dhoffland/CDM | e2c7718a4755e2c0b112b579bde009fd3a5bf37a | [
"CC-BY-4.0",
"MIT"
] | 1 | 2021-09-21T16:55:52.000Z | 2021-09-21T16:55:52.000Z | objectModel/Java/objectmodel/src/main/java/com/microsoft/commondatamodel/objectmodel/utilities/network/CdmHttpRequest.java | dhoffland/CDM | e2c7718a4755e2c0b112b579bde009fd3a5bf37a | [
"CC-BY-4.0",
"MIT"
] | 5 | 2021-07-05T15:32:15.000Z | 2022-01-04T16:51:11.000Z | objectModel/Java/objectmodel/src/main/java/com/microsoft/commondatamodel/objectmodel/utilities/network/CdmHttpRequest.java | dhoffland/CDM | e2c7718a4755e2c0b112b579bde009fd3a5bf37a | [
"CC-BY-4.0",
"MIT"
] | 1 | 2020-07-30T12:18:42.000Z | 2020-07-30T12:18:42.000Z | 21.810219 | 95 | 0.624498 | 5,946 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
package com.microsoft.commondatamodel.objectmodel.utilities.network;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
public class CdmHttpRequest {
/**
* The headers.
*/
private Map<String, String> headers;
/**
* The content.
*/
private String content;
/**
* The content type.
*/
private String contentType;
/**
* The HTTP method.
*/
private String method;
/**
* The request URL (can be partial or full), depends on whether the client has URL set.
*/
private String requestedUrl;
/**
* The timeout of a single request.
*/
private Duration timeout;
/**
* The timeout of all of the requests.
*/
private Duration maximumTimeout;
/**
* The number of retries.
*/
private int numberOfRetries;
public CdmHttpRequest(final String url) {
this(url, 0, null);
}
public CdmHttpRequest(final String url, final int numberOfRetries) {
this(url, numberOfRetries, null);
}
public CdmHttpRequest(final String url, final int numberOfRetries, final String method) {
this.headers = new LinkedHashMap<>();
this.requestedUrl = url;
this.numberOfRetries = numberOfRetries;
if (method == null) {
this.method = "GET";
} else {
this.method = method;
}
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(final Map<String, String> headers) {
this.headers = headers;
}
public String getContent() {
return content;
}
public void setContent(final String content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(final String contentType) {
this.contentType = contentType;
}
public String getMethod() {
return method;
}
public void setMethod(final String method) {
this.method = method;
}
public String getRequestedUrl() {
return requestedUrl;
}
public void setRequestedUrl(final String requestedUrl) {
this.requestedUrl = requestedUrl;
}
public Duration getTimeout() {
return timeout;
}
public void setTimeout(final Duration timeout) {
this.timeout = timeout;
}
public Duration getMaximumTimeout() {
return maximumTimeout;
}
public void setMaximumTimeout(final Duration maximumTimeout) {
this.maximumTimeout = maximumTimeout;
}
public int getNumberOfRetries() {
return numberOfRetries;
}
public void setNumberOfRetries(final int numberOfRetries) {
this.numberOfRetries = numberOfRetries;
}
}
|
3e0e08721642e785ee3c1a34b02ee64f696678db | 14,990 | java | Java | cyclops-reactor-integration/src/test/java/cyclops/streams/asyncreactivestreams/AsyncRSZippingTest.java | andyglick/cyclops-react | dc26bdad0f2b8a5aa87de4aa946ed52a0dbf00de | [
"ECL-2.0",
"Apache-2.0"
] | 937 | 2015-06-02T10:36:23.000Z | 2022-03-28T11:16:22.000Z | cyclops-reactor-integration/src/test/java/cyclops/streams/asyncreactivestreams/AsyncRSZippingTest.java | preuss/cyclops | 0be977662db87d2aaeac391a458ab3de0fe70d9b | [
"Apache-2.0"
] | 631 | 2016-02-23T14:55:57.000Z | 2018-09-27T16:57:13.000Z | cyclops-reactor-integration/src/test/java/cyclops/streams/asyncreactivestreams/AsyncRSZippingTest.java | preuss/cyclops | 0be977662db87d2aaeac391a458ab3de0fe70d9b | [
"Apache-2.0"
] | 118 | 2015-06-08T14:14:52.000Z | 2022-03-18T18:43:32.000Z | 31.691332 | 155 | 0.634423 | 5,947 | package cyclops.streams.asyncreactivestreams;
import cyclops.companion.reactor.Fluxs;
import cyclops.reactive.FluxReactiveSeq;
import cyclops.reactive.ReactiveSeq;
import cyclops.reactive.Spouts;
import cyclops.data.tuple.Tuple;
import cyclops.data.tuple.Tuple2;
import cyclops.data.tuple.Tuple3;
import cyclops.data.tuple.Tuple4;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.*;
import static cyclops.data.tuple.Tuple.tuple;
import static org.junit.Assert.*;
public class AsyncRSZippingTest {
ReactiveSeq<Integer> empty;
ReactiveSeq<Integer> nonEmpty;
@Before
public void setup(){
empty = of();
nonEmpty = of(1);
}
protected <U> ReactiveSeq<U> of(U... array){
return FluxReactiveSeq.reactiveSeq(Flux.just(array).subscribeOn(Schedulers.fromExecutor(ForkJoinPool.commonPool())));
}
protected <U> Flux<U> flux(U... array){
return Flux.just(array).subscribeOn(Schedulers.fromExecutor(ForkJoinPool.commonPool()));
}
protected <U> ReactiveSeq<U> withSleep(U... array){
return Spouts.from(Flux.just(array).subscribeOn(Schedulers.fromExecutor(ForkJoinPool.commonPool()))).peek(c->{
try {
System.out.println("Sleeping " + c + "T" + Thread.currentThread().getId());
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
@Test
public void zipLatest(){
for(int i=0;i<10_000;i++) {
List<Tuple2<Integer, Integer>> list = of(1, 2, 3, 4, 5, 6)
.zipLatest(of(100, 200, 300, 400), Tuple::tuple)
.collect(Collectors.toList());
System.out.println(list);
assertThat(list.size(),greaterThan(3));
if(list.size()==4){
list.forEach(t->{
assertThat(t._1(),equalTo(6));
});
}
}
}
@Test
public void zipInOrderNoLimit(){
List<Tuple2<Integer,Integer>> list = of(1,2,3,4,5,6)
.zip( of(100,200,300,400))
.collect(Collectors.toList());
assertThat(list.get(0)._1(),is(1));
assertThat(list.get(0)._2(),is(100));
assertThat(list.get(1)._1(),is(2));
assertThat(list.get(1)._2(),is(200));
assertThat(list.get(2)._1(),is(3));
assertThat(list.get(2)._2(),is(300));
assertThat(list.get(3)._1(),is(4));
assertThat(list.get(3)._2(),is(400));
}
@Test
public void zipUnevenRight(){
for(int i=0;i<20;i++) {
System.out.println(i);
assertEquals(asList("a"), of("a").toList());
assertEquals(asList(tuple("a", 0L)), of("a").zip(of(0L, 1L, 2L)).toList());
assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b").zip(of(0L, 1L, 2L, 3L)).toList());
assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b").zip(of(0L, 1L, 2L, 3L, 4L)).toList());
assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b").zip(of(0L, 1L, 2L, 3L, 4L, 5L)).toList());
assertEquals(asList(tuple(0L, "a"), tuple(1L, "b")), of(0L, 1L).zip(of("a", "b", "c", "d")).toList());
}
}
@Test
public void unevenTest(){
assertEquals(asList(tuple("a", 0L)), of("a","b","c").zip(of(0L)).toList());
}
@Test
public void zipUnevenLeft(){
for(int i=0;i<20;i++) {
System.out.println(i);
assertEquals(asList(tuple("a", 0L)), of("a", "b").zip(of(0L)).toList());
assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b", "c").zip(of(0L, 1L)).toList());
assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b", "c").zip(of(0L, 1L)).collect(Collectors.toList()));
assertEquals(asList(tuple("a", 0L), tuple("b", 1L)), of("a", "b", "c", "d").zip(of(0L, 1L)).toList());
}
}
@Test
public void zip1(){
assertEquals(asList("a"), of("a").toList());
assertEquals(asList(tuple("a", 0L)), of("a").zip(of(0L)).toList());
}
@Test
public void zip(){
List<Tuple2<Integer,Integer>> list =
of(1,2,3,4,5,6).zip(of(100,200,300,400))
.peek(it -> System.out.println(it))
.collect(Collectors.toList());
System.out.println(list);
List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList());
assertThat(right,hasItem(100));
assertThat(right,hasItem(200));
assertThat(right,hasItem(300));
assertThat(right,hasItem(400));
List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList());
assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0)));
}
@Test
public void zip3(){
List<Tuple3<Integer,Integer,Character>> list =
of(1,2,3,4,5,6).zip3(of(100,200,300,400),of('a','b','c'))
.peek(it -> System.out.println(it))
.collect(Collectors.toList());
System.out.println(list);
List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList());
assertThat(right,hasItem(100));
assertThat(right,hasItem(200));
assertThat(right,hasItem(300));
assertThat(right,not(hasItem(400)));
List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList());
assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0)));
List<Character> three = list.stream().map(t -> t._3()).collect(Collectors.toList());
assertThat(Arrays.asList('a','b','c'),hasItem(three.get(0)));
}
@Test
public void zip4(){
List<Tuple4<Integer,Integer,Character,String>> list =
of(1,2,3,4,5,6).zip4(of(100,200,300,400),of('a','b','c'),of("hello","world"))
.peek(it -> System.out.println(it))
.collect(Collectors.toList());
System.out.println(list);
List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList());
assertThat(right,hasItem(100));
assertThat(right,hasItem(200));
assertThat(right,not(hasItem(300)));
assertThat(right,not(hasItem(400)));
List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList());
assertThat(Arrays.asList(1,2,3,4,5,6),hasItem(left.get(0)));
List<Character> three = list.stream().map(t -> t._3()).collect(Collectors.toList());
assertThat(Arrays.asList('a','b','c'),hasItem(three.get(0)));
List<String> four = list.stream().map(t -> t._4()).collect(Collectors.toList());
assertThat(Arrays.asList("hello","world"),hasItem(four.get(0)));
}
@Test
public void zip2of(){
for(int i=0;i<10;i++) {
System.out.println("i is " + i);
List<Tuple2<Integer, Integer>> list = of(1, 2, 3, 4, 5, 6)
.zip(of(100, 200, 300, 400))
.peek(it -> System.out.println("Peeking " + it))
.collect(Collectors.toList());
List<Integer> right = list.stream().map(t -> t._2()).collect(Collectors.toList());
System.out.println("Right is " + right + " list is " + list);
assertThat(right, hasItem(100));
assertThat(right, hasItem(200));
assertThat(right, hasItem(300));
assertThat(right, hasItem(400));
List<Integer> left = list.stream().map(t -> t._1()).collect(Collectors.toList());
assertThat(Arrays.asList(1, 2, 3, 4, 5, 6), hasItem(left.get(0)));
}
}
@Test
public void zipInOrder(){
List<Tuple2<Integer,Integer>> list = of(1,2,3,4,5,6)
.zip( of(100,200,300,400))
.collect(Collectors.toList());
assertThat(asList(1,2,3,4,5,6),hasItem(list.get(0)._1()));
assertThat(asList(100,200,300,400),hasItem(list.get(0)._2()));
}
@Test
public void zipEmpty() throws Exception {
final ReactiveSeq<Integer> zipped = empty.zip(ReactiveSeq.<Integer>of(), (a, b) -> a + b);
assertTrue(zipped.collect(Collectors.toList()).isEmpty());
}
@Test
public void shouldReturnEmptySeqWhenZipEmptyWithNonEmpty() throws Exception {
final ReactiveSeq<Integer> zipped = empty.zip(nonEmpty, (a, b) -> a + b);
assertTrue(zipped.collect(Collectors.toList()).isEmpty());
}
@Test
public void shouldReturnEmptySeqWhenZipNonEmptyWithEmpty() throws Exception {
final ReactiveSeq<Integer> zipped = nonEmpty.zip(empty, (a, b) -> a + b);
assertTrue(zipped.collect(Collectors.toList()).isEmpty());
}
@Test
public void shouldZipTwoFiniteSequencesOfSameSize() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C");
final ReactiveSeq<Integer> second = of(1, 2, 3);
final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),is(3));
}
@Test
public void shouldTrimSecondFixedSeqIfLonger() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C");
final ReactiveSeq<Integer> second = of(1, 2, 3, 4);
final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),is(3));
}
@Test
public void shouldTrimFirstFixedSeqIfLonger() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C","D");
final ReactiveSeq<Integer> second = of(1, 2, 3);
final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),equalTo(3));
}
@Test
public void testZipDifferingLength() {
List<Tuple2<Integer, String>> list = of(1, 2).zip(of("a", "b", "c", "d")).toList();
assertEquals(2, list.size());
assertTrue(asList(1, 2).contains(list.get(0)._1()));
assertTrue("" + list.get(1)._2(), asList(1, 2).contains(list.get(1)._1()));
assertTrue(asList("a", "b", "c", "d").contains(list.get(0)._2()));
assertTrue(asList("a", "b", "c", "d").contains(list.get(1)._2()));
}
@Test
public void shouldTrimSecondFixedSeqIfLongerStream() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C");
final ReactiveSeq<Integer> second = of(1, 2, 3, 4);
final ReactiveSeq<String> zipped = first.zipWithStream(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),is(3));
}
@Test
public void shouldTrimFirstFixedSeqIfLongerStream() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C","D");
final ReactiveSeq<Integer> second = of(1, 2, 3);
final ReactiveSeq<String> zipped = first.zipWithStream(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),equalTo(3));
}
@Test
public void testZipDifferingLengthStream() {
List<Tuple2<Integer, String>> list = of(1, 2).zip(of("a", "b", "c", "d")).toList();
assertEquals(2, list.size());
assertTrue(asList(1, 2).contains(list.get(0)._1()));
assertTrue("" + list.get(1)._2(), asList(1, 2).contains(list.get(1)._1()));
assertTrue(asList("a", "b", "c", "d").contains(list.get(0)._2()));
assertTrue(asList("a", "b", "c", "d").contains(list.get(1)._2()));
}
@Test
public void shouldTrimSecondFixedSeqIfLongerSequence() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C");
final ReactiveSeq<Integer> second = of(1, 2, 3, 4);
final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),is(3));
}
@Test
public void shouldTrimFirstFixedSeqIfLongerSequence() throws Exception {
final ReactiveSeq<String> first = of("A", "B", "C","D");
final ReactiveSeq<Integer> second = of(1, 2, 3);
final ReactiveSeq<String> zipped = first.zip(second, (a, b) -> a + b);
assertThat(zipped.collect(Collectors.toList()).size(),equalTo(3));
}
@Test
public void zipWithIndexToList(){
of("a").zipWithIndex().toList();
}
@Test
public void testZipWithIndex() {
assertEquals(asList(), of().zipWithIndex().toList());
assertThat(of("a").zipWithIndex().map(t -> t._2()).findFirst().get(), is(0l));
assertEquals(asList(new Tuple2("a", 0L)), of("a").zipWithIndex().toList());
}
@Test
public void testUnzip() {
Supplier<ReactiveSeq<Tuple2<Integer, String>>> s = () -> of(new Tuple2(1, "a"), new Tuple2(2, "b"), new Tuple2(3, "c"));
Tuple2<ReactiveSeq<Integer>, ReactiveSeq<String>> u1 = ReactiveSeq.unzip(s.get());
assertTrue(u1._1().toList().containsAll(Arrays.asList(1, 2, 3)));
assertTrue(u1._2().toList().containsAll(asList("a", "b", "c")));
}
@Test
public void testUnzipWithLimits() {
Supplier<ReactiveSeq<Tuple2<Integer, String>>> s = () -> of(new Tuple2(1, "a"), new Tuple2(2, "b"), new Tuple2(3, "c"));
Tuple2<ReactiveSeq<Integer>, ReactiveSeq<String>> u1 = ReactiveSeq.unzip(s.get());
assertTrue(u1._1().limit(2).toList().containsAll(Arrays.asList(1, 2)));
assertTrue(u1._2().toList().containsAll(asList("a", "b", "c")));
}
@Test
public void testUnzip3WithLimits() {
Supplier<ReactiveSeq<Tuple3<Integer, String, Long>>> s = () -> of(new Tuple3(1, "a", 2l), new Tuple3(2, "b", 3l), new Tuple3(3, "c", 4l));
Tuple3<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>> u1 = ReactiveSeq.unzip3(s.get());
assertTrue(u1._1().limit(1).toList().containsAll(Arrays.asList(1)));
assertTrue(u1._2().limit(2).toList().containsAll(asList("a", "b")));
assertTrue(u1._3().toList().containsAll(asList(2l, 3l, 4l)));
}
@Test
public void testUnzip3() {
Supplier<ReactiveSeq<Tuple3<Integer, String, Long>>> s = () -> of(new Tuple3(1, "a", 2l), new Tuple3(2, "b", 3l), new Tuple3(3, "c", 4l));
Tuple3<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>> u1 = ReactiveSeq.unzip3(s.get());
assertTrue(u1._1().toList().containsAll(Arrays.asList(1, 2, 3)));
assertTrue(u1._2().toList().containsAll(asList("a", "b", "c")));
assertTrue(u1._3().toList().containsAll(asList(2l, 3l, 4l)));
}
@Test
public void testUnzip4() {
Supplier<ReactiveSeq<Tuple4<Integer, String, Long, Character>>> s = () -> of(new Tuple4(1, "a", 2l, 'z'), new Tuple4(2, "b", 3l, 'y'), new Tuple4(3, "c",
4l, 'x'));
Tuple4<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>, ReactiveSeq<Character>> u1 = ReactiveSeq.unzip4(s.get());
assertTrue(u1._1().toList().containsAll(Arrays.asList(1, 2, 3)));
assertTrue(u1._2().toList().containsAll(asList("a", "b", "c")));
assertTrue(u1._3().toList().containsAll(asList(2l, 3l, 4l)));
assertTrue(u1._4().toList().containsAll(asList('z', 'y', 'x')));
}
@Test
public void testUnzip4WithLimits() {
Supplier<ReactiveSeq<Tuple4<Integer, String, Long, Character>>> s = () -> of(new Tuple4(1, "a", 2l, 'z'), new Tuple4(2, "b", 3l, 'y'), new Tuple4(3, "c",
4l, 'x'));
Tuple4<ReactiveSeq<Integer>, ReactiveSeq<String>, ReactiveSeq<Long>, ReactiveSeq<Character>> u1 = ReactiveSeq.unzip4(s.get());
assertTrue(u1._1().limit(1).toList().containsAll(Arrays.asList(1)));
assertTrue(u1._2().limit(2).toList().containsAll(asList("a", "b")));
assertTrue(u1._3().limit(3).toList().containsAll(asList(2l, 3l, 4l)));
assertTrue(u1._4().limit(4).toList().containsAll(asList('z', 'y', 'x')));
}
}
|
3e0e0957368a8cf7d480ca30c44bbc03cafb6a81 | 1,344 | java | Java | src/main/java/december/christmas/demo/controller/CustomErrorController.java | Filiman35/demo-december | 316eefa27dcef2318cb0609d74051c1411c49688 | [
"MIT"
] | null | null | null | src/main/java/december/christmas/demo/controller/CustomErrorController.java | Filiman35/demo-december | 316eefa27dcef2318cb0609d74051c1411c49688 | [
"MIT"
] | null | null | null | src/main/java/december/christmas/demo/controller/CustomErrorController.java | Filiman35/demo-december | 316eefa27dcef2318cb0609d74051c1411c49688 | [
"MIT"
] | null | null | null | 40.727273 | 99 | 0.765625 | 5,948 | package december.christmas.demo.controller;
import december.christmas.demo.exception.BassException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/custom-error-path")
public class CustomErrorController implements ErrorController {
@GetMapping()
@Operation(summary = "Get an error page")
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "Give a page with error status to user",
content = @Content(schema = @Schema(implementation = String.class)))
})
public String getError(Model model) {
model.addAttribute("header", "Your request was processed with error.");
model.addAttribute("messageMain", "Our team is working on fixing it.");
model.addAttribute("messageAdvice", "Please, try again in 5 minutes.");
return "error";
}
}
|
3e0e0959c117f4ba07ecc778bb4a0b01b6910ce8 | 1,766 | java | Java | pvmanager/datasource-formula/src/main/java/org/diirt/datasource/formula/vtable/TableUnionFunction.java | diirt/diirt | 6070306dd321e95dc6ca15e9c04903fae7b595a9 | [
"MIT"
] | 12 | 2015-03-24T19:11:36.000Z | 2021-08-14T11:48:05.000Z | pvmanager/datasource-formula/src/main/java/org/diirt/datasource/formula/vtable/TableUnionFunction.java | diirt/diirt | 6070306dd321e95dc6ca15e9c04903fae7b595a9 | [
"MIT"
] | 36 | 2015-01-20T14:37:30.000Z | 2022-02-16T00:55:15.000Z | pvmanager/datasource-formula/src/main/java/org/diirt/datasource/formula/vtable/TableUnionFunction.java | diirt/diirt | 6070306dd321e95dc6ca15e9c04903fae7b595a9 | [
"MIT"
] | 13 | 2015-01-13T00:17:43.000Z | 2018-07-03T10:57:08.000Z | 24.527778 | 104 | 0.648924 | 5,949 | /**
* Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource.formula.vtable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.diirt.datasource.formula.FormulaFunction;
import org.diirt.vtype.VString;
import org.diirt.vtype.VStringArray;
import org.diirt.vtype.VTable;
import org.diirt.vtype.table.VTableFactory;
/**
* Union of a set of tables.
*
* @author carcassi
*/
class TableUnionFunction implements FormulaFunction {
@Override
public boolean isPure() {
return true;
}
@Override
public boolean isVarArgs() {
return true;
}
@Override
public String getName() {
return "union";
}
@Override
public String getDescription() {
return "Union between tables";
}
@Override
public List<Class<?>> getArgumentTypes() {
return Arrays.<Class<?>>asList(VString.class, VStringArray.class, VTable.class);
}
@Override
public List<String> getArgumentNames() {
return Arrays.asList("columnName", "columnValues", "tables");
}
@Override
public Class<?> getReturnType() {
return VTable.class;
}
@Override
public Object calculate(final List<Object> args) {
VString columnName = (VString) args.get(0);
VStringArray columnValues = (VStringArray) args.get(1);
List<VTable> tables = new ArrayList<>();
for (int i = 2; i < args.size(); i++) {
Object object = args.get(i);
tables.add((VTable) object);
}
return VTableFactory.union(columnName, columnValues, tables.toArray(new VTable[tables.size()]));
}
}
|
3e0e0b5cf806c142872b8d23174ad0f07e198929 | 946 | java | Java | 03EnumerationsAndAnnotations/src/_05CardCompareTo/Card.java | lapd87/SoftUniJavaOOPAdvanced | e06cf284fffc7259210a94f327d078d228edf76f | [
"MIT"
] | null | null | null | 03EnumerationsAndAnnotations/src/_05CardCompareTo/Card.java | lapd87/SoftUniJavaOOPAdvanced | e06cf284fffc7259210a94f327d078d228edf76f | [
"MIT"
] | null | null | null | 03EnumerationsAndAnnotations/src/_05CardCompareTo/Card.java | lapd87/SoftUniJavaOOPAdvanced | e06cf284fffc7259210a94f327d078d228edf76f | [
"MIT"
] | null | null | null | 24.894737 | 67 | 0.557082 | 5,950 | package _05CardCompareTo;
/**
* Created by IntelliJ IDEA.
* User: LAPD
* Date: 18.7.2018 г.
* Time: 12:16 ч.
*/
public class Card implements Comparable<Card> {
private Enum rank;
private Enum suit;
private int power;
public Card(String rank, String suit) {
this.rank = Enum.valueOf(CardRank.class,
rank.toUpperCase());
this.suit = Enum.valueOf(CardSuit.class,
suit.toUpperCase());
this.power = Enum.valueOf(CardRank.class,
rank.toUpperCase())
.getPower()
+ Enum.valueOf(CardSuit.class,
suit.toUpperCase())
.getPower();
}
@Override
public String toString() {
return String.format("Card name: %s of %s; Card power: %d",
rank, suit, power);
}
@Override
public int compareTo(Card o) {
return Integer.compare(power, o.power);
}
} |
3e0e0b7cacacc777550253b207bc9b4ae1885c41 | 1,256 | java | Java | lib/src/main/java/me/tuesd4y/lsb/compression/BitOutputStream.java | tuesd4y/lsb-steno | e19832fe8cd690f7cd24c599509df183e7ddc5c8 | [
"MIT"
] | null | null | null | lib/src/main/java/me/tuesd4y/lsb/compression/BitOutputStream.java | tuesd4y/lsb-steno | e19832fe8cd690f7cd24c599509df183e7ddc5c8 | [
"MIT"
] | null | null | null | lib/src/main/java/me/tuesd4y/lsb/compression/BitOutputStream.java | tuesd4y/lsb-steno | e19832fe8cd690f7cd24c599509df183e7ddc5c8 | [
"MIT"
] | null | null | null | 19.323077 | 66 | 0.656051 | 5,951 | package me.tuesd4y.lsb.compression;
import java.io.*;
public class BitOutputStream extends OutputStream {
// a class that writes to an OutputStream bitwise
private ByteArrayOutputStream out;
private int buffer;
private int digits; // digits in buffer
private static final int BYTE = 8;
public BitOutputStream() {
out = new ByteArrayOutputStream();
buffer = 0;
digits = 0;
}
public void write(int b, int nDigits) throws IOException {
// write the integer b as a nDigits length binary
int index = nDigits - 1;
for (int i = 0; i < nDigits; i++) {
write((b >> index--) & 1);
}
}
@Override
public void write(int bit) throws IOException {
// write a single bit to the buffer and the buffer to the stream
if (bit < 0 || bit > 1)
throw new IllegalArgumentException();
buffer += bit << (7 - digits++);
if (digits == BYTE)
flush();
}
@Override
public void flush() {
// write the (full) buffer to the stream
out.write(buffer);
buffer = 0;
digits = 0;
}
@Override
public void close() throws IOException {
if (digits > 0) {
flush();
}
out.close();
}
@Override
protected void finalize() throws IOException {
close();
}
public byte[] toByteArray() {
return out.toByteArray();
}
}
|
3e0e0c029a701cd1521de682030250cfecbdecf1 | 505 | java | Java | src/main/java/com/codetaylor/mc/athenaeum/util/RandomHelper.java | codetaylor/athenaeum-1.12 | 4be7edcbffc4407165ca9fedddd55f397fae7616 | [
"Apache-2.0"
] | 1 | 2020-07-04T09:13:03.000Z | 2020-07-04T09:13:03.000Z | src/main/java/com/codetaylor/mc/athenaeum/util/RandomHelper.java | codetaylor/athenaeum | 4be7edcbffc4407165ca9fedddd55f397fae7616 | [
"Apache-2.0"
] | 5 | 2017-12-24T00:03:03.000Z | 2020-01-02T16:21:32.000Z | src/main/java/com/codetaylor/mc/athenaeum/util/RandomHelper.java | codetaylor/athenaeum | 4be7edcbffc4407165ca9fedddd55f397fae7616 | [
"Apache-2.0"
] | 1 | 2018-02-10T00:38:42.000Z | 2018-02-10T00:38:42.000Z | 16.833333 | 63 | 0.631683 | 5,952 | package com.codetaylor.mc.athenaeum.util;
import java.util.Random;
public final class RandomHelper {
private static final ThreadLocal<Random> RANDOM_THREAD_LOCAL;
static {
RANDOM_THREAD_LOCAL = ThreadLocal.withInitial(() -> {
Random random = new Random();
for (int i = 0; i < 10000; i++) {
random.nextDouble();
}
return random;
});
}
public static Random random() {
return RANDOM_THREAD_LOCAL.get();
}
private RandomHelper() {
//
}
}
|
3e0e0ca65687a6bafd4e6628e3c0c4d90841db63 | 4,849 | java | Java | cqf-ce-base/modules/cqf-ce-core/src/main/java/com/siegetechnologies/cqf/core/experiment/design/ExperimentDesignElementId.java | secdec/cqf-ce | c20aed7c06a8b97830788f7385777ea66e2708a6 | [
"Apache-2.0"
] | 2 | 2018-09-05T12:12:53.000Z | 2020-04-17T15:15:42.000Z | cqf-ce-base/modules/cqf-ce-core/src/main/java/com/siegetechnologies/cqf/core/experiment/design/ExperimentDesignElementId.java | secdec/cqf-ce | c20aed7c06a8b97830788f7385777ea66e2708a6 | [
"Apache-2.0"
] | null | null | null | cqf-ce-base/modules/cqf-ce-core/src/main/java/com/siegetechnologies/cqf/core/experiment/design/ExperimentDesignElementId.java | secdec/cqf-ce | c20aed7c06a8b97830788f7385777ea66e2708a6 | [
"Apache-2.0"
] | null | null | null | 27.551136 | 112 | 0.697876 | 5,953 | package com.siegetechnologies.cqf.core.experiment.design;
/*-
* #%L
* cqf-ce-core
* %%
* Copyright (C) 2009 - 2017 Siege Technologies, LLC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.siegetechnologies.cqf.core._v01.experiment.design.ExperimentDesignElementSpec;
import java.util.Optional;
/**
* Unique ID of an experiment design element.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExperimentDesignElementId implements Comparable<ExperimentDesignElementId>
{
public static final String VALUE_PREFIX = "com.siegetechnologies.cqf.design.item"; // FIXME: STRING: srogers
private String value;
public ExperimentDesignElementId(String value)
{
initValue(value);
}
public ExperimentDesignElementId(String name, String category)
{
this(name, category, null);
}
@JsonCreator
public ExperimentDesignElementId(@JsonProperty("name") String name,
@JsonProperty("category") String category,
@JsonProperty("variant") String variant)
{
initValue(valueFrom(name, category, variant));
}
protected void initValue(String value)
{
if (value == null) {
throw new IllegalArgumentException("value cannot be null");
}
this.value = value;
}
protected static String valueFrom(String name, String category, String variant)
{
Optional<String> canonicalName = Optional.ofNullable(canonicalDottedNameComponent(name));
Optional<String> canonicalCategory = Optional.ofNullable(canonicalDottedNameComponent(category));
Optional<String> canonicalVariant = Optional.ofNullable(canonicalDottedNameComponent(variant));
StringBuilder resultBuilder = new StringBuilder(VALUE_PREFIX);
resultBuilder.append(".").append(canonicalCategory.orElse("unknown_category")); // FIXME: STRING: srogers
resultBuilder.append(".").append(canonicalName.orElse("unknown_name")); // FIXME: STRING: srogers
canonicalVariant.ifPresent( v -> resultBuilder.append(".").append(v) );
return resultBuilder.toString();
}
protected static String canonicalDottedNameComponent(String x) {
String result = x;
if (result != null) {
result = result.trim();
if (result.length() == 0) {
result = null;
}
else {
result = result.replace(' ', '_').replace('.','-').toLowerCase();
if (result.contains(".")) {
throw new IllegalArgumentException("malformed dotted-name component");
}
//^-- FIXME: srogers: add further checks/constraints on dotted-name components
}
}
return result;
}
//^-- TODO: REVIEW: srogers: add unit tests for each constructor
//^-- TODO: REVIEW: srogers: hoist canonicalDottedNameComponent() into a utility class
/**/
public static ExperimentDesignElementId of(ExperimentDesignElementImpl x)
{
return new ExperimentDesignElementId(x.getName(), x.getCategory(), x.getVariantName());
}
@Deprecated
public static ExperimentDesignElementId of(ExperimentDesignElementSpec x)
{
return new ExperimentDesignElementId(x.getName(), x.getCategory());
}
@Deprecated
public static ExperimentDesignElementId of(String name, String category)
{
return new ExperimentDesignElementId(name, category);
}
@Deprecated
public static ExperimentDesignElementId of(String name, String category, String variant)
{
return new ExperimentDesignElementId(name, category, variant);
}
/**/
@Override
public int compareTo(ExperimentDesignElementId that) {
return this.value.compareTo(that.value);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof ExperimentDesignElementId) {
ExperimentDesignElementId that = (ExperimentDesignElementId) o;
return this.value.equals(that.value);
}
return false;
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() {
return this.value.toString();
}
/**/
public String value()
{
return value;
}
/**/
}
|
3e0e0cd750b4b52d981c2b725c2baeb2b87ea948 | 2,833 | java | Java | test/org/apache/el/parser/TestAstAssign.java | guchenbo/tomcat | 66468c8f7dec2022146373a3c511943f78417553 | [
"Apache-2.0"
] | 6,443 | 2015-01-01T05:51:19.000Z | 2022-03-31T17:36:38.000Z | test/org/apache/el/parser/TestAstAssign.java | guchenbo/tomcat | 66468c8f7dec2022146373a3c511943f78417553 | [
"Apache-2.0"
] | 353 | 2015-01-12T19:00:42.000Z | 2022-03-29T21:47:42.000Z | test/org/apache/el/parser/TestAstAssign.java | guchenbo/tomcat | 66468c8f7dec2022146373a3c511943f78417553 | [
"Apache-2.0"
] | 4,902 | 2015-01-03T21:55:07.000Z | 2022-03-31T23:36:45.000Z | 33.72619 | 80 | 0.687963 | 5,954 | /*
* 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.el.parser;
import jakarta.el.ELContext;
import jakarta.el.ELManager;
import jakarta.el.ELProcessor;
import jakarta.el.ExpressionFactory;
import jakarta.el.ValueExpression;
import org.junit.Assert;
import org.junit.Test;
public class TestAstAssign {
@Test
public void testGetValue01() {
ELProcessor processor = new ELProcessor();
processor.defineBean("bean01", new TesterBeanB());
Object result = processor.getValue(
"bean01.text = 'hello'", String.class);
Assert.assertEquals("hello", result);
}
@Test
public void testGetValue02() {
ELProcessor processor = new ELProcessor();
processor.defineBean("bean01", new TesterBeanB());
Object result = processor.getValue(
"bean01.text = 'hello'; bean01.text", String.class);
Assert.assertEquals("hello", result);
}
@Test
public void testGetType01() {
ELProcessor processor = new ELProcessor();
ELContext context = processor.getELManager().getELContext();
ExpressionFactory factory = ELManager.getExpressionFactory();
processor.defineBean("bean01", new TesterBeanB());
ValueExpression ve = factory.createValueExpression(
context, "${bean01.text = 'hello'}", String.class);
Assert.assertEquals(String.class, ve.getType(context));
Assert.assertEquals("hello", ve.getValue(context));
}
@Test
public void testGetType02() {
ELProcessor processor = new ELProcessor();
ELContext context = processor.getELManager().getELContext();
ExpressionFactory factory = ELManager.getExpressionFactory();
processor.defineBean("bean01", new TesterBeanB());
ValueExpression ve = factory.createValueExpression(
context, "${bean01.text = 'hello'; bean01.text}", String.class);
Assert.assertEquals(String.class, ve.getType(context));
Assert.assertEquals("hello", ve.getValue(context));
}
}
|
3e0e0dc5fea821f636d90596d937d5d5190259a3 | 512 | java | Java | src/main/java/com/mgrobelak/divisor/DivisorFinder.java | MarcinGrobelak/DivisorMapping | 5e8361e505624ca789d55a9b9a0df7d990f317db | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mgrobelak/divisor/DivisorFinder.java | MarcinGrobelak/DivisorMapping | 5e8361e505624ca789d55a9b9a0df7d990f317db | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mgrobelak/divisor/DivisorFinder.java | MarcinGrobelak/DivisorMapping | 5e8361e505624ca789d55a9b9a0df7d990f317db | [
"Apache-2.0"
] | null | null | null | 20.48 | 59 | 0.636719 | 5,955 | package com.mgrobelak.divisor;
/**
* @author Marcin Grobelak
*/
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class DivisorFinder {
public static List<Integer> getDivisors(Integer number) {
SortedSet<Integer> divisors = new TreeSet<>();
for (int i = 1; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
divisors.add(i);
divisors.add(number / i);
}
}
return new ArrayList<>(divisors);
}
}
|
3e0e0e3806a4cac5c33e40d299d3d46fb099f721 | 872 | java | Java | tools/jpf/jpf-symbc/src/tests/gov/nasa/jpf/symbc/ExSymExe15.java | handysama/concolic-walk | a550dbbd5390895f2fec37adb65fd5b8f3e6a5fe | [
"MIT"
] | 1 | 2021-02-28T10:11:46.000Z | 2021-02-28T10:11:46.000Z | tools/jpf/jpf-symbc/src/tests/gov/nasa/jpf/symbc/ExSymExe15.java | handysama/concolic-walk | a550dbbd5390895f2fec37adb65fd5b8f3e6a5fe | [
"MIT"
] | null | null | null | tools/jpf/jpf-symbc/src/tests/gov/nasa/jpf/symbc/ExSymExe15.java | handysama/concolic-walk | a550dbbd5390895f2fec37adb65fd5b8f3e6a5fe | [
"MIT"
] | null | null | null | 22.358974 | 91 | 0.587156 | 5,956 | package gov.nasa.jpf.symbc;
public class ExSymExe15 {
static int field;
static int field2;
public static void main (String[] args) {
int x = 3; /* we want to specify in an annotation that this param should be symbolic */
ExSymExe15 inst = new ExSymExe15();
field = 9;
inst.test(x, field, field2);
//test(x,x);
}
/* we want to let the user specify that this method should be symbolic */
/*
* test IF_ICMPGT, IADD & ISUB bytecodes
*/
public void test (int x, int z, int r) {
System.out.println("Testing ExSymExe15");
int y = 3;
r = x + z;
z = x - y - 4;
if (r <= 99)
System.out.println("branch FOO1");
else
System.out.println("branch FOO2");
if (x <= z)
System.out.println("branch BOO1");
else
System.out.println("branch BOO2");
//assert false;
}
}
|
3e0e0f593bb337a10a67bace3ae48ac929c8f377 | 1,093 | java | Java | lichkin-projects-app-entities/src/main/java/com/lichkin/springframework/entities/impl/SysAppNewsEntity.java | LichKinContributor/lichkin-projects-app | 213a082c674095c82a07a57a233c4e5e5cca3b14 | [
"MIT"
] | null | null | null | lichkin-projects-app-entities/src/main/java/com/lichkin/springframework/entities/impl/SysAppNewsEntity.java | LichKinContributor/lichkin-projects-app | 213a082c674095c82a07a57a233c4e5e5cca3b14 | [
"MIT"
] | null | null | null | lichkin-projects-app-entities/src/main/java/com/lichkin/springframework/entities/impl/SysAppNewsEntity.java | LichKinContributor/lichkin-projects-app | 213a082c674095c82a07a57a233c4e5e5cca3b14 | [
"MIT"
] | null | null | null | 18.525424 | 74 | 0.704483 | 5,957 | package com.lichkin.springframework.entities.impl;
import javax.persistence.Column;
import javax.persistence.Entity;
import com.lichkin.springframework.entities.suppers.BaseAppCompNewsEntity;
import lombok.Getter;
import lombok.Setter;
/**
* 客户端新闻信息表实体类
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
@Getter
@Setter
@Entity
public class SysAppNewsEntity extends BaseAppCompNewsEntity {
/** serialVersionUID */
private static final long serialVersionUID = 60003L;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl1;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl2;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl3;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl4;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl5;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl6;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl7;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl8;
/** 图片(URL) */
@Column(length = 512)
private String imageUrl9;
}
|
3e0e10df3f277228fe0dbdd371dd0c2f5c1b18dc | 818 | java | Java | src/main/java/com/teamacronymcoders/contenttweaker/modules/vanilla/resources/sounds/ISoundTypeDefinition.java | adrianmgg/ContentTweaker | fa431891a71a561deca00284bd8e02dbd3f77fa0 | [
"MIT"
] | null | null | null | src/main/java/com/teamacronymcoders/contenttweaker/modules/vanilla/resources/sounds/ISoundTypeDefinition.java | adrianmgg/ContentTweaker | fa431891a71a561deca00284bd8e02dbd3f77fa0 | [
"MIT"
] | null | null | null | src/main/java/com/teamacronymcoders/contenttweaker/modules/vanilla/resources/sounds/ISoundTypeDefinition.java | adrianmgg/ContentTweaker | fa431891a71a561deca00284bd8e02dbd3f77fa0 | [
"MIT"
] | null | null | null | 24.787879 | 78 | 0.788509 | 5,958 | package com.teamacronymcoders.contenttweaker.modules.vanilla.resources.sounds;
import com.teamacronymcoders.contenttweaker.api.ICTObject;
import crafttweaker.annotations.ZenRegister;
import net.minecraft.block.SoundType;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
@ZenRegister
@ZenClass("mods.contenttweaker.SoundType")
public interface ISoundTypeDefinition extends ICTObject<SoundType> {
@ZenMethod
float getVolume();
@ZenMethod
float getPitch();
@ZenMethod
ISoundEventDefinition getBreakSound();
@ZenMethod
ISoundEventDefinition getStepSound();
@ZenMethod
ISoundEventDefinition getPlaceSound();
@ZenMethod
ISoundEventDefinition getHitSound();
@ZenMethod
ISoundEventDefinition getFallSound();
}
|
3e0e119fb1b7811c9bdcbe2f3d8f2f1835a8dd2e | 3,128 | java | Java | src/main/java/hudson/plugins/promoted_builds/tokenmacro/PromotedEnvVarTokenMacro.java | car-roll/promoted-builds-plugin | 03309e6e91db9e56b3f038470d2ecfdd0ca5e426 | [
"MIT"
] | 63 | 2015-01-23T21:32:19.000Z | 2021-01-25T09:49:25.000Z | src/main/java/hudson/plugins/promoted_builds/tokenmacro/PromotedEnvVarTokenMacro.java | car-roll/promoted-builds-plugin | 03309e6e91db9e56b3f038470d2ecfdd0ca5e426 | [
"MIT"
] | 98 | 2015-01-06T13:02:34.000Z | 2022-03-21T10:08:16.000Z | src/main/java/hudson/plugins/promoted_builds/tokenmacro/PromotedEnvVarTokenMacro.java | car-roll/promoted-builds-plugin | 03309e6e91db9e56b3f038470d2ecfdd0ca5e426 | [
"MIT"
] | 136 | 2015-01-05T14:11:17.000Z | 2022-02-20T20:19:37.000Z | 39.1 | 95 | 0.730818 | 5,959 | /*
* The MIT License
*
* Copyright (c) 2015 Oleg Nenashev.
*
* 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 hudson.plugins.promoted_builds.tokenmacro;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.Executor;
import hudson.model.Queue;
import hudson.model.TaskListener;
import hudson.plugins.promoted_builds.Promotion;
import java.io.IOException;
import java.util.Map;
import org.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro;
import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException;
import org.jenkinsci.plugins.tokenmacro.impl.EnvironmentVariableMacro;
/**
* Retrieves an environment variable from the {@link Promotion} build.
* The {@link Promotion} build is being determined by the current {@link Executor},
* so the macro is tolerant against context switches when the variable is being
* resolved against the parent build instead of the {@link Promotion}.
* In other cases the macro will behave similarly to {@link EnvironmentVariableMacro} from
* Token Macro plugin.
* @author Oleg Nenashev
*/
@Extension(optional = true)
public class PromotedEnvVarTokenMacro extends DataBoundTokenMacro {
@Parameter(required=true)
public String var = "";
@Override
public String evaluate(AbstractBuild<?, ?> build, TaskListener listener, String macroName)
throws MacroEvaluationException, IOException, InterruptedException {
Executor currentExecutor = Executor.currentExecutor();
if (currentExecutor == null) {
return null;
}
Queue.Executable executable = currentExecutor.getCurrentExecutable();
if (!(executable instanceof Promotion)) {
return ""; // Nothing to do if it is not promotion
}
Map<String, String> env = ((Promotion)executable).getEnvironment(listener);
if(env.containsKey(var)){
return env.get(var);
}
return "";
}
@Override
public boolean acceptsMacroName(String macroName) {
return macroName.equals("PROMOTION_ENV");
}
}
|
3e0e1328b757d208f8610b495c1abc402fb07b57 | 8,248 | java | Java | src/main/java/net/arathain/charter/Charter.java | stormdirus2/charter | d5b9ffead600f6e92ed1f3e2def508d625ccd2d1 | [
"CC0-1.0"
] | 2 | 2021-11-07T21:19:37.000Z | 2022-03-01T18:28:13.000Z | src/main/java/net/arathain/charter/Charter.java | stormdirus2/charter | d5b9ffead600f6e92ed1f3e2def508d625ccd2d1 | [
"CC0-1.0"
] | 3 | 2021-12-15T19:03:33.000Z | 2022-03-04T07:39:15.000Z | src/main/java/net/arathain/charter/Charter.java | stormdirus2/charter | d5b9ffead600f6e92ed1f3e2def508d625ccd2d1 | [
"CC0-1.0"
] | 1 | 2022-03-01T18:28:21.000Z | 2022-03-01T18:28:21.000Z | 72.99115 | 234 | 0.821048 | 5,960 | package net.arathain.charter;
import net.arathain.charter.block.*;
import net.arathain.charter.block.entity.CharterStoneEntity;
import net.arathain.charter.block.entity.PactPressBlockEntity;
import net.arathain.charter.block.entity.WaystoneEntity;
import net.arathain.charter.components.CharterComponents;
import net.arathain.charter.components.CharterWorldComponent;
import net.arathain.charter.components.packet.UpdateShadePacket;
import net.arathain.charter.item.ContractItem;
import net.arathain.charter.item.EternalSealItem;
import net.arathain.charter.item.MerchantCrestItem;
import net.arathain.charter.util.CharterEventHandlers;
import net.arathain.charter.util.CharterUtil;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.entity.event.v1.EntityElytraEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.loot.v1.event.LootTableLoadingCallback;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.fabricmc.fabric.api.tag.FabricItemTags;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectCategory;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.loot.LootPool;
import net.minecraft.loot.LootTables;
import net.minecraft.loot.entry.LootTableEntry;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.state.property.Properties;
import net.minecraft.util.Identifier;
import net.minecraft.util.Rarity;
import net.minecraft.util.registry.Registry;
import software.bernie.geckolib3.GeckoLib;
import java.util.function.ToIntFunction;
public class Charter implements ModInitializer {
public static String MODID = "charter";
public static final Item CONTRACT = new ContractItem( new Item.Settings().maxCount(1).rarity(Rarity.RARE).group(ItemGroup.COMBAT));
public static final Item MERCHANT_CREST = new MerchantCrestItem(new Item.Settings().maxCount(1).rarity(Rarity.EPIC).group(ItemGroup.COMBAT));
public static final Item ETERNAL_SEAL = new EternalSealItem(new Item.Settings().maxCount(1).rarity(Rarity.EPIC).group(ItemGroup.COMBAT));
public static final StatusEffect ETERNAL_DEBT = new CharterStatusEffect(StatusEffectCategory.NEUTRAL, 0x4bf1f7);
public static final StatusEffect SOUL_STRAIN = new CharterStatusEffect(StatusEffectCategory.NEUTRAL, 0x6cf5f5);
public static final Block PACT_PRESS = new PactPressBlock(FabricBlockSettings.copyOf(Blocks.CHISELED_DEEPSLATE).breakByTool(FabricItemTags.PICKAXES, 2).requiresTool().luminance(createLightLevelFromLitBlockState(10)).ticksRandomly());
public static final Block WAYSTONE = new WaystoneBlock(FabricBlockSettings.copyOf(Blocks.CHISELED_DEEPSLATE).breakByTool(FabricItemTags.PICKAXES, 2).requiresTool().luminance(3).nonOpaque());
public static final Block CHARTER_VESSEL = new CharterVesselBlock(FabricBlockSettings.copyOf(Blocks.QUARTZ_BLOCK).breakByTool(FabricItemTags.PICKAXES, 3).requiresTool().nonOpaque().ticksRandomly());
public static final Block BROKEN_WAYSTONE = new BrokenWaystoneBlock(FabricBlockSettings.copyOf(Blocks.OBSIDIAN).breakByTool(FabricItemTags.PICKAXES, 2).requiresTool().luminance(0));
public static final Block SWAPPER = new SwapperBlock(FabricBlockSettings.copyOf(Blocks.CHISELED_DEEPSLATE).breakByTool(FabricItemTags.PICKAXES, 2).requiresTool().luminance(createLightLevelFromPoweredBlockState(10)));
public static final Block CHARTER_STONE = new CharterStoneBlock(FabricBlockSettings.copyOf(Blocks.BEDROCK).luminance(7).nonOpaque());
public static final Block BROKEN_CHARTER_STONE = new BrokenCharterStoneBlock(FabricBlockSettings.copyOf(Blocks.DEEPSLATE).breakByTool(FabricItemTags.PICKAXES, 2).requiresTool().luminance(0).ticksRandomly());
public static BlockEntityType<PactPressBlockEntity> PACT_PRESS_ENTITY;
public static BlockEntityType<CharterStoneEntity> CHARTER_STONE_ENTITY;
public static BlockEntityType<WaystoneEntity> WAYSTONE_ENTITY;
@Override
public void onInitialize() {
Registry.register(Registry.ITEM, new Identifier(MODID, "contract"), CONTRACT);
Registry.register(Registry.ITEM, new Identifier(MODID, "merchant_crest"), MERCHANT_CREST);
Registry.register(Registry.ITEM, new Identifier(MODID, "eternal_seal"), ETERNAL_SEAL);
Registry.register(Registry.ITEM, new Identifier(MODID, "pact_press"), new BlockItem(PACT_PRESS, new FabricItemSettings().group(ItemGroup.COMBAT)));
Registry.register(Registry.BLOCK, new Identifier(MODID, "pact_press"), PACT_PRESS);
Registry.register(Registry.BLOCK, new Identifier(MODID, "waystone"), WAYSTONE);
Registry.register(Registry.BLOCK, new Identifier(MODID, "charter_vessel"), CHARTER_VESSEL);
Registry.register(Registry.ITEM, new Identifier(MODID, "charter_vessel"), new BlockItem(CHARTER_VESSEL, new FabricItemSettings().group(ItemGroup.COMBAT)));
Registry.register(Registry.ITEM, new Identifier(MODID, "waystone"), new BlockItem(WAYSTONE, new FabricItemSettings().group(ItemGroup.COMBAT)));
Registry.register(Registry.ITEM, new Identifier(MODID, "swapper"), new BlockItem(SWAPPER, new FabricItemSettings().group(ItemGroup.REDSTONE)));
Registry.register(Registry.BLOCK, new Identifier(MODID, "swapper"), SWAPPER);
PACT_PRESS_ENTITY = Registry.register(Registry.BLOCK_ENTITY_TYPE, new Identifier(MODID, "pact_press"), FabricBlockEntityTypeBuilder.create(PactPressBlockEntity::new, PACT_PRESS).build(null));
CHARTER_STONE_ENTITY = Registry.register(Registry.BLOCK_ENTITY_TYPE, new Identifier(MODID, "charter_stone"), FabricBlockEntityTypeBuilder.create(CharterStoneEntity::new, CHARTER_STONE).build(null));
WAYSTONE_ENTITY = Registry.register(Registry.BLOCK_ENTITY_TYPE, new Identifier(MODID, "waystone"), FabricBlockEntityTypeBuilder.create(WaystoneEntity::new, WAYSTONE).build(null));
Registry.register(Registry.STATUS_EFFECT, new Identifier(MODID, "eternal_debt"), ETERNAL_DEBT);
Registry.register(Registry.STATUS_EFFECT, new Identifier(MODID, "soul_strain"), SOUL_STRAIN);
GeckoLib.initialize();
LootTableLoadingCallback.EVENT.register((resourceManager, lootManager, identifier, fabricLootSupplierBuilder, lootTableSetter) -> {
Identifier bastion_treasure = new Identifier(MODID, "inject/bastion_treasure");
if (LootTables.BASTION_TREASURE_CHEST.equals(identifier)) {
fabricLootSupplierBuilder.withPool(LootPool.builder().with(LootTableEntry.builder(bastion_treasure).weight(2)).build());
}
});
Registry.register(Registry.ITEM, new Identifier(MODID, "charter_stone"), new BlockItem(CHARTER_STONE, new FabricItemSettings().group(ItemGroup.COMBAT)));
Registry.register(Registry.ITEM, new Identifier(MODID, "apex_focus"), new Item(new FabricItemSettings().group(ItemGroup.MISC)));
Registry.register(Registry.BLOCK, new Identifier(MODID, "charter_stone"), CHARTER_STONE);
Registry.register(Registry.BLOCK, new Identifier(MODID, "broken_charter_stone"), BROKEN_CHARTER_STONE);
Registry.register(Registry.BLOCK, new Identifier(MODID, "broken_waystone"), BROKEN_WAYSTONE);
ServerTickEvents.END_SERVER_TICK.register(server -> {
for (ServerWorld world : server.getWorlds()) {
CharterWorldComponent charterWorldComponent = CharterComponents.CHARTERS.get(world);
charterWorldComponent.tick();
}
});
EntityElytraEvents.CUSTOM.register(((entity, tickElytra) -> CharterUtil.isCharterOwner(entity, entity.world)));
CharterEventHandlers.init();
ServerPlayNetworking.registerGlobalReceiver(UpdateShadePacket.ID, UpdateShadePacket::handle);
}
private static ToIntFunction<BlockState> createLightLevelFromLitBlockState(int litLevel) {
return (state) -> (Boolean)state.get(Properties.LIT) ? litLevel : 0;
}
private static ToIntFunction<BlockState> createLightLevelFromPoweredBlockState(int litLevel) {
return (state) -> (Boolean)state.get(Properties.POWERED) ? litLevel : 0;
}
}
|
3e0e135ce59fe661a93c0b3acee5b73cad2d2394 | 45,314 | java | Java | nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/ops/OpExecutionerTests.java | 10088/deeplearning4j | 2102745521c3027d7ab4e3abf653db9b537e6df4 | [
"Apache-2.0"
] | 2,206 | 2019-06-12T18:57:14.000Z | 2022-03-29T08:14:27.000Z | nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/ops/OpExecutionerTests.java | 10088/deeplearning4j | 2102745521c3027d7ab4e3abf653db9b537e6df4 | [
"Apache-2.0"
] | 1,685 | 2019-06-12T17:41:33.000Z | 2022-03-29T21:45:15.000Z | nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/ops/OpExecutionerTests.java | 10088/deeplearning4j | 2102745521c3027d7ab4e3abf653db9b537e6df4 | [
"Apache-2.0"
] | 572 | 2019-06-12T22:13:57.000Z | 2022-03-31T16:46:46.000Z | 50.070718 | 119 | 0.640222 | 5,961 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.linalg.ops;
import lombok.val;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.nd4j.common.tests.tags.NativeTag;
import org.nd4j.linalg.BaseNd4jTestWithBackends;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.CustomOp;
import org.nd4j.linalg.api.ops.executioner.OpExecutioner;
import org.nd4j.linalg.api.ops.impl.indexaccum.custom.ArgAmax;
import org.nd4j.linalg.api.ops.impl.indexaccum.custom.ArgMax;
import org.nd4j.linalg.api.ops.impl.indexaccum.custom.ArgMin;
import org.nd4j.linalg.api.ops.impl.reduce.floating.Mean;
import org.nd4j.linalg.api.ops.impl.reduce.floating.Norm2;
import org.nd4j.linalg.api.ops.impl.reduce.floating.NormMax;
import org.nd4j.linalg.api.ops.impl.reduce.same.Max;
import org.nd4j.linalg.api.ops.impl.reduce.same.Min;
import org.nd4j.linalg.api.ops.impl.reduce.same.Prod;
import org.nd4j.linalg.api.ops.impl.reduce.same.Sum;
import org.nd4j.linalg.api.ops.impl.reduce3.EuclideanDistance;
import org.nd4j.linalg.api.ops.impl.scalar.Pow;
import org.nd4j.linalg.api.ops.impl.scalar.ScalarAdd;
import org.nd4j.linalg.api.ops.impl.scalar.ScalarMax;
import org.nd4j.linalg.api.ops.impl.scalar.comparison.ScalarGreaterThan;
import org.nd4j.linalg.api.ops.impl.scalar.comparison.ScalarLessThan;
import org.nd4j.linalg.api.ops.impl.summarystats.Variance;
import org.nd4j.linalg.api.ops.impl.transforms.custom.SoftMax;
import org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic.AddOp;
import org.nd4j.linalg.api.ops.impl.transforms.pairwise.arithmetic.MulOp;
import org.nd4j.linalg.api.ops.impl.transforms.strict.Exp;
import org.nd4j.linalg.api.ops.impl.transforms.strict.Log;
import org.nd4j.linalg.api.ops.impl.transforms.strict.SetRange;
import org.nd4j.linalg.api.ops.random.impl.DropOut;
import org.nd4j.linalg.api.ops.random.impl.DropOutInverted;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.ops.transforms.Transforms;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import static org.junit.jupiter.api.Assertions.*;
@NativeTag
public class OpExecutionerTests extends BaseNd4jTestWithBackends {
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testCosineSimilarity(Nd4jBackend backend) {
INDArray vec1 = Nd4j.create(new float[] {1, 2, 3, 4, 5});
INDArray vec2 = Nd4j.create(new float[] {1, 2, 3, 4, 5});
double sim = Transforms.cosineSim(vec1, vec2);
assertEquals( 1, sim, 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testCosineDistance(Nd4jBackend backend){
INDArray vec1 = Nd4j.create(new float[] {1, 2, 3});
INDArray vec2 = Nd4j.create(new float[] {3, 5, 7});
// 1-17*sqrt(2/581)
double distance = Transforms.cosineDistance(vec1, vec2);
assertEquals(0.0025851, distance, 1e-7,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testEuclideanDistance(Nd4jBackend backend) {
INDArray arr = Nd4j.create(new double[] {55, 55});
INDArray arr2 = Nd4j.create(new double[] {60, 60});
double result = Nd4j.getExecutioner().execAndReturn(new EuclideanDistance(arr, arr2)).z().getDouble(0);
assertEquals(7.0710678118654755, result, 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testDimensionalEuclidean(Nd4jBackend backend) {
INDArray distanceInputRow = Nd4j.linspace(1, 4, 4, DataType.DOUBLE).reshape(1, -1);
INDArray distanceComp = Nd4j.linspace(1, 4, 4, DataType.DOUBLE).reshape(1, -1).add(1);
INDArray result = Nd4j.createUninitialized(DataType.DOUBLE, 4);
Nd4j.getExecutioner().exec(
new EuclideanDistance(distanceInputRow, distanceComp, result, 0));
INDArray euclideanAssertion = Nd4j.ones(4).castTo(DataType.DOUBLE);
assertEquals(euclideanAssertion, result);
// System.out.println(result);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
@Execution(ExecutionMode.SAME_THREAD)
public void testDistance(Nd4jBackend backend) throws Exception {
INDArray matrix = Nd4j.rand(new int[] {400,10});
INDArray rowVector = matrix.getRow(70);
INDArray resultArr = Nd4j.zeros(400,1);
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
Nd4j.getExecutioner().exec(new EuclideanDistance(matrix, rowVector, resultArr, -1));
System.out.println("Ran!");
});
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testScalarMaxOp(Nd4jBackend backend) {
INDArray scalarMax = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).negi();
INDArray postMax = Nd4j.ones(DataType.DOUBLE, 6);
Nd4j.getExecutioner().exec(new ScalarMax(scalarMax, 1));
assertEquals(scalarMax, postMax,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testSetRange(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 4, 4, DataType.DOUBLE);
Nd4j.getExecutioner().exec(new SetRange(linspace, 0, 1));
for (int i = 0; i < linspace.length(); i++) {
double val = linspace.getDouble(i);
assertTrue( val >= 0 && val <= 1,getFailureMessage(backend));
}
INDArray linspace2 = Nd4j.linspace(1, 4, 4, DataType.DOUBLE);
Nd4j.getExecutioner().exec(new SetRange(linspace2, 2, 4));
for (int i = 0; i < linspace2.length(); i++) {
double val = linspace2.getDouble(i);
assertTrue( val >= 2 && val <= 4,getFailureMessage(backend));
}
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testNormMax(Nd4jBackend backend) {
INDArray arr = Nd4j.create(new float[] {1, 2, 3, 4});
double normMax = Nd4j.getExecutioner().execAndReturn(new NormMax(arr)).z().getDouble(0);
assertEquals(4, normMax, 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testLog(Nd4jBackend backend) {
INDArray arr = Nd4j.linspace(1, 4, 4, DataType.DOUBLE).reshape(2, 2);
INDArray assertion = Nd4j.create(new double[][] {{0., 1.09861229}, {0.69314718, 1.38629436}});
INDArray logTest = Transforms.log(arr);
assertEquals(assertion, logTest);
arr = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape(2, 3);
assertion = Nd4j.create(new double[][] {{0., 1.09861229, 1.60943791}, {0.69314718, 1.38629436, 1.79175947}});
logTest = Transforms.log(arr);
assertEquals(assertion, logTest);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testNorm2(Nd4jBackend backend) {
INDArray arr = Nd4j.create(new float[] {1, 2, 3, 4});
double norm2 = Nd4j.getExecutioner().execAndReturn(new Norm2(arr)).z().getDouble(0);
assertEquals(5.4772255750516612, norm2, 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testAdd(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray x = Nd4j.ones(5);
INDArray xDup = x.dup();
INDArray solution = Nd4j.valueArrayOf(5, 2.0);
opExecutioner.exec(new AddOp(new INDArray[]{x, xDup},new INDArray[]{x}));
assertEquals(solution, x,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testMul(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray x = Nd4j.ones(5);
INDArray xDup = x.dup();
INDArray solution = Nd4j.valueArrayOf(5, 1.0);
opExecutioner.exec(new MulOp(x, xDup, x));
assertEquals(solution, x);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testExecutioner(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray x = Nd4j.ones(5);
INDArray xDup = x.dup();
INDArray solution = Nd4j.valueArrayOf(5, 2.0);
opExecutioner.exec(new AddOp(new INDArray[]{x, xDup},new INDArray[]{x}));
assertEquals(solution, x,getFailureMessage(backend));
Sum acc = new Sum(x.dup());
opExecutioner.exec(acc);
assertEquals(10.0, acc.getFinalResult().doubleValue(), 1e-1,getFailureMessage(backend));
Prod prod = new Prod(x.dup());
opExecutioner.exec(prod);
assertEquals(32.0, prod.getFinalResult().doubleValue(), 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testMaxMin(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray x = Nd4j.linspace(1, 5, 5, DataType.DOUBLE);
Max max = new Max(x);
opExecutioner.exec(max);
assertEquals(5, max.getFinalResult().doubleValue(), 1e-1);
Min min = new Min(x);
opExecutioner.exec(min);
assertEquals(1, min.getFinalResult().doubleValue(), 1e-1);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testProd(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 6, 6, DataType.DOUBLE);
Prod prod = new Prod(linspace);
double prod2 = Nd4j.getExecutioner().execAndReturn(prod).z().getDouble(0);
assertEquals(720, prod2, 1e-1);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testSum(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 6, 6, DataType.DOUBLE);
Sum sum = new Sum(linspace);
double sum2 = Nd4j.getExecutioner().execAndReturn(sum).z().getDouble(0);
assertEquals(21, sum2, 1e-1);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testDescriptiveStatsDouble(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray x = Nd4j.linspace(1, 5, 5, DataType.DOUBLE);
Mean mean = new Mean(x);
opExecutioner.exec(mean);
assertEquals(3.0, mean.getFinalResult().doubleValue(), 1e-1);
Variance variance = new Variance(x.dup(), true);
opExecutioner.exec(variance);
assertEquals( 2.5, variance.getFinalResult().doubleValue(), 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testIamax(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 4, 4, DataType.DOUBLE);
assertEquals( 3, Nd4j.getBlasWrapper().iamax(linspace),getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testIamax2(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 4, 4, DataType.DOUBLE);
assertEquals( 3, Nd4j.getBlasWrapper().iamax(linspace),getFailureMessage(backend));
val op = new ArgAmax(new INDArray[]{linspace});
int iamax = Nd4j.getExecutioner().exec(op)[0].getInt(0);
assertEquals(3, iamax);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testDescriptiveStats(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray x = Nd4j.linspace(1, 5, 5, DataType.DOUBLE);
Mean mean = new Mean(x);
opExecutioner.exec(mean);
assertEquals( 3.0, mean.getFinalResult().doubleValue(), 1e-1,getFailureMessage(backend));
Variance variance = new Variance(x.dup(), true);
opExecutioner.exec(variance);
assertEquals( 2.5, variance.getFinalResult().doubleValue(), 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testRowSoftmax(Nd4jBackend backend) {
val opExecutioner = Nd4j.getExecutioner();
val arr = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape(1, -1);
val softMax = new SoftMax(arr);
opExecutioner.exec((CustomOp) softMax);
assertEquals(1.0, softMax.outputArguments().get(0).sumNumber().doubleValue(), 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testPow(Nd4jBackend backend) {
INDArray oneThroughSix = Nd4j.linspace(1, 6, 6, DataType.DOUBLE);
Pow pow = new Pow(oneThroughSix, 2);
Nd4j.getExecutioner().exec(pow);
INDArray answer = Nd4j.create(new double[] {1, 4, 9, 16, 25, 36});
assertEquals(answer, pow.z(),getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testComparisonOps(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 6, 6, DataType.DOUBLE);
INDArray ones = Nd4j.ones(DataType.BOOL, 6);
INDArray zeros = Nd4j.zeros(DataType.BOOL, 6);
INDArray res = Nd4j.createUninitialized(DataType.BOOL, 6);
assertEquals(ones, Nd4j.getExecutioner().exec(new ScalarGreaterThan(linspace, res,0)));
assertEquals(zeros, Nd4j.getExecutioner().exec(new ScalarGreaterThan(linspace, res, 7)));
assertEquals(zeros, Nd4j.getExecutioner().exec(new ScalarLessThan(linspace, res, 0)));
assertEquals(ones, Nd4j.getExecutioner().exec(new ScalarLessThan(linspace, res,7)));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testScalarArithmetic(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 6, 6, DataType.DOUBLE);
INDArray plusOne = Nd4j.linspace(2, 7, 6, DataType.DOUBLE);
Nd4j.getExecutioner().exec(new ScalarAdd(linspace, 1));
assertEquals(plusOne, linspace);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testDimensionMax(Nd4jBackend backend) {
INDArray linspace = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape(2, 3);
int axis = 0;
INDArray row = linspace.slice(axis);
Max max = new Max(row);
double max2 = Nd4j.getExecutioner().execAndReturn(max).z().getDouble(0);
assertEquals(5.0, max2, 1e-1);
Min min = new Min(row);
double min2 = Nd4j.getExecutioner().execAndReturn(min).z().getDouble(0);
assertEquals(1.0, min2, 1e-1);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testStridedLog(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray arr = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape(2, 3);
INDArray slice = arr.slice(0);
Log log = new Log(slice);
opExecutioner.exec(log);
INDArray assertion = Nd4j.create(new double[] {0., 1.09861229, 1.60943791});
assertEquals(assertion, slice,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testSoftmax(Nd4jBackend backend) {
INDArray vec = Nd4j.linspace(1, 6, 6, DataType.DOUBLE);
INDArray matrix = vec.dup().reshape('f', 2, 3);
Nd4j.getExecutioner().exec((CustomOp) new SoftMax(matrix));
INDArray matrixAssertion = Nd4j.create(
new double[] {0.015876241, 0.015876241, 0.11731043, 0.11731043, 0.86681336, 0.86681336},
new int[] {2, 3}, 'f');
assertEquals(matrixAssertion, matrix);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testOtherSoftmax(Nd4jBackend backend) {
INDArray vec = Nd4j.linspace(1, 18, 18, DataType.DOUBLE);
INDArray matrix = vec.dup().reshape('f', 3, 6);
Nd4j.getExecutioner().exec((CustomOp) new SoftMax(matrix));
INDArray assertion = Nd4j.create(new double[] {2.9067235E-7, 2.9067235E-7, 2.9067235E-7, 5.8383102E-6,
5.8383102E-6, 5.8383102E-6, 1.1726559E-4, 1.1726559E-4, 1.1726559E-4, 0.0023553425,
0.0023553425, 0.0023553425, 0.047308315, 0.047308315, 0.047308315, 0.95021296, 0.95021296,
0.95021296}, new int[] {3, 6}, 'f');
assertEquals(assertion, matrix);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testClassificationSoftmax(Nd4jBackend backend) {
INDArray input = Nd4j.create(new double[] {-0.11537042, -0.12137824, -0.12023379, -0.121212654, -0.11363918,
-0.10101747, -0.11571036, -0.11699755, -0.12303393, -0.12222538, -0.111205295, -0.11710347,
-0.12319956, -0.12442437, -0.10528548, -0.08768979, -0.102969095, -0.11346512, -0.106075466,
-0.106812954, -0.116048686, -0.107011676, -0.11420248, -0.111682974, -0.1161541, -0.12052244,
-0.112824574, -0.115148716, -0.116811216, -0.11987898, -0.120540276, -0.11262567, -0.1033787,
-0.09880979, -0.12222538, -0.11966099, -0.115003735, -0.12222538, -0.12269135, -0.11685945,
-0.113694824, -0.116669476, -0.12075868, -0.106586955, -0.1025187, -0.119958475, -0.1087377,
-0.120367825, -0.11125226, -0.11847404, 0.07354959, 0.06268422, 0.08751991, 0.05259514,
0.07969017, 0.062334877, 0.070893124, -0.0064847446, 0.07025853, 0.036010355, 0.032280773,
0.051330015, 0.048092365, 0.075383544, 0.0026740413, 0.060346432, 0.0642657, 0.032083385,
0.0732262, 0.034285806, 0.08459604, 0.040570542, 0.08494349, 0.06835914, 0.05533401, 0.06346914,
0.082844265, 0.097696416, 0.07128821, 0.0012981347, 0.03325705, 0.02408357, 0.03130123,
0.0938182, 0.062283132, 0.04927382, 0.07896088, 0.06648662, 0.030163728, 0.047266718,
0.057046715, 0.06862673, 0.041349716, 0.0029906097, 0.05075717, 0.031863913, 0.04317994,
0.05359216, -0.026340045, 0.042290315, 0.12401425, 0.10255231, 0.11914651, 0.10838078,
0.11920456, 0.12058236, 0.07964209, 0.11363033, 0.103594616, 0.124344714, 0.10481718,
0.10615028, 0.116106674, 0.101516105, 0.11543927, 0.11498181, 0.10836467, 0.12498047,
0.11773242, 0.080594674, 0.12140609, 0.10168961, 0.11630507, 0.097365394, 0.116597414,
0.11525783, 0.09534653, 0.09552346, 0.114529714, 0.10820673, 0.1136818, 0.12088456, 0.11661099,
0.09196414, 0.09367619, 0.12396192, 0.11715829, 0.10781159, 0.09206238, 0.11529949, 0.12193692,
0.114719115, 0.10255231, 0.12246917, 0.122784376, 0.11647934, 0.0990758, 0.109394, 0.11121255,
0.0993141, -0.20153984, -0.19392103, -0.19934568, -0.19083072, -0.2002219, -0.18812108,
-0.19819337, -0.197516, -0.18787667, -0.19108538, -0.1998294, -0.19259658, -0.19106683,
-0.1962341, -0.20643811, -0.17979848, -0.2008527, -0.2022663, -0.19437766, -0.19513921,
-0.19446027, -0.19675982, -0.20814218, -0.19372806, -0.18230462, -0.18796727, -0.19594415,
-0.19937015, -0.20221424, -0.1900377, -0.18905015, -0.20246184, -0.18973505, -0.19170408,
-0.19108538, -0.20450068, -0.20772256, -0.19108538, -0.19349809, -0.19836158, -0.2043826,
-0.16650638, -0.19694944, -0.19511233, -0.18056196, -0.19521531, -0.19218433, -0.19556037,
-0.19890977, -0.19989866, 0.110895246, 0.092092186, 0.13636512, 0.09708373, 0.12663889,
0.112808585, 0.104376495, 0.008250488, 0.11656463, 0.062448245, 0.07663194, 0.07671328,
0.09773853, 0.12847707, 0.0019389617, 0.088733524, 0.106456585, 0.06874651, 0.12830634,
0.06976124, 0.125978, 0.06455773, 0.14945641, 0.12600574, 0.088896096, 0.09622975, 0.13689917,
0.15111934, 0.11476833, 0.012905663, 0.06886613, 0.056535408, 0.056539863, 0.16477236,
0.105480224, 0.06795105, 0.12039946, 0.11954279, 0.052694187, 0.08551991, 0.11061126,
0.11398445, 0.07550914, 0.023510661, 0.09092401, 0.060012117, 0.075267926, 0.08827078,
-0.0351813, 0.073293045, 0.17944565, 0.16982268, 0.18865392, 0.18693334, 0.18788461, 0.20586023,
0.13861816, 0.2043775, 0.18895179, 0.1654431, 0.1499911, 0.17463979, 0.17583887, 0.16696453,
0.16749826, 0.1592366, 0.17954212, 0.18181926, 0.21207902, 0.15266305, 0.17395121, 0.15906093,
0.21057776, 0.15467101, 0.1741476, 0.19151133, 0.14792839, 0.14762697, 0.18604177, 0.18808068,
0.19654939, 0.17514956, 0.18510492, 0.16045001, 0.18320353, 0.1866908, 0.16069266, 0.17718756,
0.14080217, 0.1681495, 0.17300007, 0.15283263, 0.16982268, 0.1817098, 0.16696706, 0.16177532,
0.16047187, 0.16464046, 0.15210035, 0.16091332, 0.19544482, 0.1334318, 0.16168839, 0.11322637,
0.19517516, 0.18929672, 0.17545202, 0.16658127, 0.0913124, 0.110042766, 0.20550777, 0.13831234,
0.10610578, 0.12289246, 0.2714768, 0.20504126, 0.25187582, 0.20981915, 0.2013824, 0.19962603,
0.15790766, 0.20949605, 0.23528615, 0.18096939, 0.08758451, 0.10911971, 0.18139267, 0.18525597,
0.19391456, 0.11438081, 0.10939147, 0.22006747, 0.18334162, 0.21811464, 0.110042766, 0.19371074,
0.2327902, 0.110042766, 0.11990617, 0.17242402, 0.2197558, 0.046736162, 0.14443715, 0.20759603,
0.13962242, 0.1486803, 0.17288595, 0.14028643, 0.19978581, 0.17370181, -0.03870563,
-0.038800463, -0.06074495, 0.005578231, -0.026154697, -0.09166621, -0.061155554, 0.008943881,
-0.047770716, -0.012912758, -0.01086065, -0.019136615, -0.0061139315, -0.09119851, 0.034481727,
-0.008211095, -0.09062709, -0.04640113, -0.003811527, -0.006515648, -0.06737341, 0.022067834,
-0.07823941, -0.10467515, -0.012385383, -0.008899722, -0.05071889, -0.06124178, -0.053028326,
0.036579777, 0.0040080342, 0.0017335843, 0.00966073, -0.13457713, -0.10622793, -0.058109,
-0.042826377, -0.004804369, -0.05494748, -0.0023090728, -0.08317526, -0.0812492, 0.0012213364,
0.017189149, -0.041634988, -0.07508251, -0.052436303, -0.028371753, 0.077994466, -0.02655043,
-0.048018664, -0.113020286, -0.114139564, -0.17401274, -0.114431985, -0.19375473, -0.08697136,
-0.22462575, -0.18594624, 0.029960819, -0.030721083, -0.10795041, -0.0687456, -0.088536546,
-0.028004304, -0.0044010356, -0.14119366, -0.057321526, -0.23839925, -0.09940954, -0.03133001,
-0.07696311, -0.23962286, -0.055784777, -0.07386551, -0.16175163, -0.04683064, -0.0713344,
-0.12525225, -0.176231, -0.1785344, -0.054819535, -0.10787999, -0.12848954, -0.21946627,
-0.07054794, -0.004379764, -0.14215486, -0.062456205, -0.038439542, -0.019706637, 0.041873105,
-0.113020286, -0.06571138, 0.012915805, 0.008474745, -0.05855358, -0.058223557, -0.007257685,
-0.11702956}, new int[] {150, 3}, 'f');
INDArray assertion = Nd4j.create(new double[] {0.3046945, 0.31053564, 0.30772904, 0.3127982, 0.3049832,
0.30736795, 0.30686057, 0.3076439, 0.31483504, 0.3129973, 0.3041549, 0.31072456, 0.31327236,
0.31140107, 0.29749927, 0.3074947, 0.30005574, 0.30333498, 0.30530176, 0.30543298, 0.30866665,
0.30427617, 0.3004194, 0.3066349, 0.31625876, 0.31319204, 0.30653065, 0.30584472, 0.30464056,
0.3128697, 0.31325394, 0.30222437, 0.3077568, 0.30448923, 0.3129973, 0.3042575, 0.30053583,
0.3129973, 0.31189594, 0.30701208, 0.30219892, 0.31960127, 0.30956632, 0.30446774, 0.31260762,
0.3090533, 0.30814552, 0.31004447, 0.30479294, 0.30664116, 0.34107947, 0.34090835, 0.34337586,
0.33338174, 0.3392553, 0.34375596, 0.34360147, 0.32999024, 0.34059194, 0.33567807, 0.3329864,
0.33810434, 0.3335406, 0.34469903, 0.32986054, 0.33754894, 0.34487507, 0.33762568, 0.33529142,
0.3337637, 0.34467727, 0.33267412, 0.34292668, 0.34477416, 0.33685294, 0.3374399, 0.34123695,
0.34388787, 0.3415838, 0.3281285, 0.33251032, 0.33212858, 0.3328727, 0.34851202, 0.34613267,
0.3428139, 0.3415714, 0.33493212, 0.3399977, 0.334378, 0.341975, 0.3439716, 0.3338435,
0.32948583, 0.3386694, 0.3416325, 0.33997172, 0.33822724, 0.322459, 0.3372723, 0.34495273,
0.34774572, 0.34917334, 0.35264698, 0.34931532, 0.35469893, 0.34396452, 0.35612476, 0.35239643,
0.33876625, 0.34252962, 0.3474446, 0.3456883, 0.34547645, 0.34248832, 0.3409808, 0.35051847,
0.34580123, 0.3572295, 0.34364316, 0.34337047, 0.34537002, 0.35722163, 0.34282026, 0.34652257,
0.3524498, 0.34229505, 0.3448508, 0.34953663, 0.35266057, 0.3529821, 0.3454672, 0.3484543,
0.34806335, 0.35400698, 0.34626326, 0.3412907, 0.35079524, 0.3440239, 0.34343404, 0.34242827,
0.3368599, 0.34774572, 0.34608114, 0.3400059, 0.3396784, 0.3427608, 0.34453318, 0.34129536,
0.34855416, 0.27953854, 0.2888062, 0.28432208, 0.2917625, 0.27968782, 0.28172797, 0.28256553,
0.2838439, 0.2950681, 0.2921697, 0.27835938, 0.28813055, 0.29271683, 0.28982347, 0.26887837,
0.28043702, 0.27207687, 0.27755985, 0.27949893, 0.27961233, 0.28538817, 0.27815753, 0.2734831,
0.2824814, 0.29601505, 0.29276544, 0.2820821, 0.28114092, 0.27970335, 0.29167145, 0.29251158,
0.27625751, 0.28229526, 0.27747792, 0.2921697, 0.27950907, 0.2739233, 0.2921697, 0.29057536,
0.28298247, 0.2759991, 0.3040637, 0.28685635, 0.2786732, 0.2891384, 0.28664854, 0.28347546,
0.28758636, 0.27921304, 0.2826625, 0.35405818, 0.35108265, 0.36056453, 0.3485483, 0.35556272,
0.36155194, 0.35530117, 0.33488873, 0.35673428, 0.34467104, 0.34808716, 0.34679636, 0.35051754,
0.36349487, 0.32961816, 0.34726825, 0.35973698, 0.35023382, 0.3542774, 0.3458166, 0.35923994,
0.34075052, 0.3657791, 0.36523324, 0.3483503, 0.3486777, 0.36019015, 0.36275893, 0.3567635,
0.33195946, 0.34456408, 0.34308356, 0.34138083, 0.3741388, 0.36141226, 0.34927687, 0.35602295,
0.35318217, 0.34774497, 0.34741682, 0.36079222, 0.3599326, 0.3454444, 0.33631673, 0.35254955,
0.35138544, 0.35105765, 0.35016224, 0.3196206, 0.3478924, 0.36461383, 0.37194347, 0.37430686,
0.38146538, 0.37414935, 0.3862741, 0.3648603, 0.3899538, 0.38379708, 0.35297906, 0.35835785,
0.37207472, 0.3669662, 0.36884367, 0.36079016, 0.35640973, 0.37637684, 0.36602545, 0.39257398,
0.36932322, 0.36189535, 0.36576378, 0.3925363, 0.3630396, 0.36705002, 0.38037658, 0.36077514,
0.36329508, 0.3754482, 0.38198447, 0.383479, 0.36473197, 0.37315765, 0.37273598, 0.38716227,
0.36867967, 0.35647675, 0.37599605, 0.36120692, 0.36207274, 0.36036783, 0.34994662, 0.37194347,
0.36720264, 0.3553651, 0.35541826, 0.36446443, 0.36410302, 0.3555394, 0.37069988, 0.41576695,
0.4006582, 0.40794885, 0.3954393, 0.41532904, 0.41090405, 0.41057387, 0.40851218, 0.3900969,
0.39483297, 0.41748565, 0.40114486, 0.39401078, 0.39877546, 0.4336224, 0.41206822, 0.42786735,
0.4191052, 0.41519928, 0.4149547, 0.4059452, 0.41756633, 0.42609745, 0.4108837, 0.3877262,
0.3940425, 0.41138723, 0.4130143, 0.41565615, 0.3954588, 0.39423448, 0.42151815, 0.40994796,
0.41803288, 0.39483297, 0.4162334, 0.42554083, 0.39483297, 0.3975287, 0.41000548, 0.421802,
0.37633502, 0.40357736, 0.41685906, 0.39825398, 0.40429813, 0.40837905, 0.40236917, 0.41599396,
0.41069633, 0.30486232, 0.308009, 0.2960596, 0.31806993, 0.30518195, 0.29469204, 0.30109736,
0.33512104, 0.30267385, 0.3196509, 0.3189264, 0.3150993, 0.31594187, 0.2918061, 0.3405213,
0.31518283, 0.29538792, 0.3121405, 0.3104312, 0.32041973, 0.29608276, 0.32657534, 0.2912942,
0.28999257, 0.31479672, 0.31388244, 0.29857287, 0.2933532, 0.30165273, 0.33991206, 0.3229256,
0.32478786, 0.32574654, 0.2773492, 0.29245508, 0.3079092, 0.30240566, 0.3118857, 0.31225735,
0.31820515, 0.2972328, 0.29609585, 0.32071212, 0.33419743, 0.30878097, 0.306982, 0.30897063,
0.31161052, 0.35792035, 0.31483534, 0.29043347, 0.2803108, 0.2765198, 0.26588768, 0.2765353,
0.25902697, 0.29117516, 0.25392145, 0.26380652, 0.30825472, 0.29911253, 0.2804806, 0.2873455,
0.28567985, 0.2967215, 0.30260953, 0.27310467, 0.28817332, 0.25019652, 0.28703368, 0.29473418,
0.28886622, 0.250242, 0.2941401, 0.28642738, 0.26717362, 0.29692984, 0.29185408, 0.2750152,
0.2653549, 0.26353893, 0.28980076, 0.27838808, 0.27920067, 0.2588307, 0.28505707, 0.3022325,
0.27320877, 0.29476917, 0.29449323, 0.29720396, 0.31319344, 0.2803108, 0.28671616, 0.30462897,
0.3049033, 0.29277474, 0.29136384, 0.30316526, 0.2807459}, new int[] {150, 3}, 'f');
// System.out.println("Data:" + input.data().length());
val softMax = new SoftMax(input);
Nd4j.getExecutioner().exec((CustomOp) softMax);
assertEquals(assertion, softMax.outputArguments().get(0));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testAddBroadcast(Nd4jBackend backend) {
INDArray arr = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape('f', 2, 3);
INDArray arrRow = Nd4j.create(new double[] {1, 2, 3});
INDArray assertion = Nd4j.create(new double[] {2, 3, 5, 6, 8, 9}, new int[] {2, 3}, 'f');
INDArray add = arr.addRowVector(arrRow);
assertEquals(assertion, add);
INDArray colVec = Nd4j.linspace(1, 2, 2, DataType.DOUBLE).reshape(2, 1);
INDArray colAssertion = Nd4j.create(new double[] {2, 4, 4, 6, 6, 8}, new int[] {2, 3}, 'f');
INDArray colTest = arr.addColumnVector(colVec);
assertEquals(colAssertion, colTest);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testStridedExp(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray arr = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape(2, 3);
INDArray slice = arr.slice(0);
val expected = new double[(int) slice.length()];
for (int i = 0; i < slice.length(); i++)
expected[i] = (float) Math.exp(slice.getDouble(i));
Exp exp = new Exp(slice);
opExecutioner.exec(exp);
assertEquals( Nd4j.create(expected), slice,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testSoftMax(Nd4jBackend backend) {
OpExecutioner opExecutioner = Nd4j.getExecutioner();
INDArray arr = Nd4j.linspace(1, 6, 6, DataType.DOUBLE).reshape(1, -1);
val softMax = new SoftMax(arr);
opExecutioner.exec((CustomOp) softMax);
assertEquals(1.0, softMax.outputArguments().get(0).sumNumber().doubleValue(), 1e-1,getFailureMessage(backend));
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testIMax(Nd4jBackend backend) {
INDArray arr = Nd4j.linspace(1, 10, 10, DataType.DOUBLE);
ArgMax imax = new ArgMax(new INDArray[]{arr});
assertEquals(9, Nd4j.getExecutioner().exec(imax)[0].getInt(0));
arr.muli(-1);
imax = new ArgMax(new INDArray[]{arr});
int maxIdx = Nd4j.getExecutioner().exec(imax)[0].getInt(0);
assertEquals(0, maxIdx);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testIMin(Nd4jBackend backend) {
INDArray arr = Nd4j.linspace(1, 10, 10, DataType.DOUBLE);
ArgMin imin = new ArgMin(new INDArray[]{arr});
assertEquals(0, Nd4j.getExecutioner().exec(imin)[0].getInt(0));
arr.muli(-1);
imin = new ArgMin(new INDArray[]{arr});
int minIdx = Nd4j.getExecutioner().exec(imin)[0].getInt(0);
assertEquals(9, minIdx);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testMeanSumSimple(Nd4jBackend backend) {
// System.out.println("3d");
INDArray arr = Nd4j.ones(1, 4, 4);
assertEquals(Nd4j.ones(1), arr.mean(1, 2));
assertEquals(Nd4j.ones(1).muli(16), arr.sum(1, 2));
// System.out.println("4d");
INDArray arr4 = Nd4j.ones(1, 1, 4, 4);
INDArray arr4m = arr4.mean(2, 3);
INDArray arr4s = arr4.sum(2, 3);
for (int i = 0; i < arr4m.length(); i++)
assertEquals(arr4m.getDouble(i), 1, 1e-1);
for (int i = 0; i < arr4s.length(); i++)
assertEquals(arr4s.getDouble(i), 16, 1e-1);
// System.out.println("5d");
INDArray arr5 = Nd4j.ones(1, 1, 4, 4, 4);
INDArray arr5m = arr5.mean(2, 3);
INDArray arr5s = arr5.sum(2, 3);
for (int i = 0; i < arr5m.length(); i++)
assertEquals(arr5m.getDouble(i), 1, 1e-1);
for (int i = 0; i < arr5s.length(); i++)
assertEquals(arr5s.getDouble(i), 16, 1e-1);
// System.out.println("6d");
INDArray arr6 = Nd4j.ones(1, 1, 4, 4, 4, 4);
INDArray arr6Tad = arr6.tensorAlongDimension(0, 2, 3);
INDArray arr6s = arr6.sum(2, 3);
for (int i = 0; i < arr6s.length(); i++)
assertEquals(arr6s.getDouble(i), 16, 1e-1);
INDArray arr6m = arr6.mean(2, 3);
for (int i = 0; i < arr6m.length(); i++)
assertEquals(arr6m.getDouble(i), 1, 1e-1);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void tescodtSum6d(Nd4jBackend backend) {
INDArray arr6 = Nd4j.ones(1, 1, 4, 4, 4, 4);
INDArray arr6s = arr6.sum(2, 3);
// System.out.println("Arr6s: " + arr6.length());
for (int i = 0; i < arr6s.length(); i++)
assertEquals(16, arr6s.getDouble(i), 1e-1);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testSum6d2(Nd4jBackend backend) {
char origOrder = Nd4j.order();
try {
for (char order : new char[]{'c', 'f'}) {
Nd4j.factory().setOrder(order);
INDArray arr6 = Nd4j.linspace(1, 256, 256, DataType.DOUBLE).reshape(1, 1, 4, 4, 4, 4);
INDArray arr6s = arr6.sum(2, 3);
INDArray exp = Nd4j.create(DataType.DOUBLE, 1, 1, 4, 4);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
double sum = 0;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
sum += arr6.getDouble(0, 0, x, y, i, j);
}
}
exp.putScalar(0, 0, i, j, sum);
}
}
assertEquals(exp, arr6s,"Failed for [" + order + "] order");
// System.out.println("ORDER: " + order);
// for (int i = 0; i < 6; i++) {
// System.out.println(arr6s.getDouble(i));
// }
}
} finally {
Nd4j.factory().setOrder(origOrder);
}
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testMean6d(Nd4jBackend backend) {
INDArray arr6 = Nd4j.ones(1, 1, 4, 4, 4, 4);
INDArray arr6m = arr6.mean(2, 3);
for (int i = 0; i < arr6m.length(); i++)
assertEquals(1.0, arr6m.getDouble(i), 1e-1);
/*
System.out.println("Arr6 shapeInfo: " + arr6.shapeInfoDataBuffer());
System.out.println("Arr6 length: " + arr6.length());
System.out.println("Arr6 shapeLlength: " + arr6.shapeInfoDataBuffer().length());
System.out.println("Arr6s shapeInfo: " + arr6s.shapeInfoDataBuffer());
System.out.println("Arr6s length: " + arr6s.length());
System.out.println("Arr6s shapeLength: " + arr6s.shapeInfoDataBuffer().length());
*/
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testStdev(Nd4jBackend backend) {
INDArray arr = Nd4j.create(new float[] {0.9296161f, 0.31637555f, 0.1839188f}, new int[] {1, 3}, ordering());
double stdev = arr.stdNumber(true).doubleValue();
val standardDeviation = new org.apache.commons.math3.stat.descriptive.moment.StandardDeviation(true);
double exp = standardDeviation.evaluate(arr.toDoubleVector());
assertEquals(exp, stdev, 1e-7f);
double stdev2 = arr.std(true, 1).getDouble(0);
assertEquals(stdev, stdev2, 1e-3);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testVariance(Nd4jBackend backend) {
val f = new double[] {0.9296161, 0.31637555, 0.1839188};
INDArray arr = Nd4j.create(f, new int[] {1, 3}, ordering());
double var = arr.varNumber().doubleValue();
INDArray var1 = arr.var(1);
double var2 = var1.getDouble(0);
assertEquals(var, var2, 1e-3);
val variance = new org.apache.commons.math3.stat.descriptive.moment.Variance(true);
double exp = variance.evaluate(arr.toDoubleVector());
assertEquals(exp, var, 1e-7f);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testDropout(Nd4jBackend backend) {
INDArray array = Nd4j.linspace(1, 100, 100, DataType.DOUBLE);
INDArray result = Nd4j.create(DataType.DOUBLE, 100);
DropOut dropOut = new DropOut(array, result, 0.05);
Nd4j.getExecutioner().exec(dropOut);
// System.out.println("Src array: " + array);
// System.out.println("Res array: " + result);
assertNotEquals(array, result);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testDropoutInverted(Nd4jBackend backend) {
INDArray array = Nd4j.linspace(1, 100, 100, DataType.DOUBLE);
INDArray result = Nd4j.create(DataType.DOUBLE, 100);
DropOutInverted dropOut = new DropOutInverted(array, result, 0.65);
Nd4j.getExecutioner().exec(dropOut);
// System.out.println("Src array: " + array);
// System.out.println("Res array: " + result);
assertNotEquals(array, result);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testVPull1(Nd4jBackend backend) {
int indexes[] = new int[] {0, 2, 4};
INDArray array = Nd4j.linspace(1, 25, 25, DataType.DOUBLE).reshape(5, 5);
INDArray assertion = Nd4j.createUninitialized(DataType.DOUBLE, new long[] {3, 5}, 'f');
for (int i = 0; i < 3; i++) {
assertion.putRow(i, array.getRow(indexes[i]));
}
INDArray result = Nd4j.pullRows(array, 1, indexes, 'f');
assertEquals(3, result.rows());
assertEquals(5, result.columns());
assertEquals(assertion, result);
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testVPull2(Nd4jBackend backend) {
int indexes[] = new int[] {0, 2, 4};
INDArray array = Nd4j.linspace(1, 25, 25, DataType.DOUBLE).reshape(5, 5);
INDArray assertion = Nd4j.createUninitialized(DataType.DOUBLE, new long[] {3, 5}, 'c');
for (int i = 0; i < 3; i++) {
assertion.putRow(i, array.getRow(indexes[i]));
}
INDArray result = Nd4j.pullRows(array, 1, indexes, 'c');
assertEquals(3, result.rows());
assertEquals(5, result.columns());
assertEquals(assertion, result);
// System.out.println(assertion.toString());
// System.out.println(result.toString());
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testPile1(Nd4jBackend backend) {
List<INDArray> arrays = new ArrayList<>();
for (int i = 0; i < 10; i++) {
arrays.add(Nd4j.create(10, 10).assign(i));
}
INDArray pile = Nd4j.pile(arrays);
assertEquals(3, pile.rank());
for (int i = 0; i < 10; i++) {
assertEquals((float) i, pile.tensorAlongDimension(i, 1, 2).getDouble(0), 0.01);
}
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testPile2(Nd4jBackend backend) {
List<INDArray> arrays = new ArrayList<>();
for (int i = 0; i < 10; i++) {
arrays.add(Nd4j.create(10, 10, 10).assign(i));
}
INDArray pile = Nd4j.pile(arrays);
assertEquals(4, pile.rank());
for (int i = 0; i < 10; i++) {
assertEquals((float) i, pile.tensorAlongDimension(i, 1, 2, 3).getDouble(0), 0.01);
}
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testPile3(Nd4jBackend backend) {
List<INDArray> arrays = new ArrayList<>();
for (int i = 0; i < 10; i++) {
arrays.add(Nd4j.create( 10, 10).assign(i));
}
INDArray pile = Nd4j.pile(arrays);
assertEquals(3, pile.rank());
for (int i = 0; i < 10; i++) {
assertEquals((float) i, pile.tensorAlongDimension(i, 1, 2).getDouble(0), 0.01);
}
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testPile4(Nd4jBackend backend) {
val arrayW = Nd4j.create(1, 5);
val arrayX = Nd4j.create(1, 5);
val arrayY = Nd4j.create(1, 5);
val arrayZ = Nd4j.pile(arrayW, arrayX, arrayY);
assertArrayEquals(new long[]{3, 1, 5}, arrayZ.shape());
}
@ParameterizedTest
@MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
public void testTear1(Nd4jBackend backend) {
List<INDArray> arrays = new ArrayList<>();
for (int i = 0; i < 10; i++) {
arrays.add(Nd4j.create(10, 10).assign(i));
}
INDArray pile = Nd4j.pile(arrays);
INDArray[] tears = Nd4j.tear(pile, 1, 2);
for (int i = 0; i < 10; i++) {
assertEquals((float) i, tears[i].meanNumber().floatValue(), 0.01f);
}
}
@Override
public char ordering() {
return 'f';
}
}
|
3e0e142ef0b0f9b5b6fd535ebe92f65ff908ac64 | 1,963 | java | Java | src/test/java/io/fries/koans/stream/Exercise01.java | Abib-P/java-stream-koans | 5095a66d83ebb8ba98dc12d065e956680811d27c | [
"Unlicense"
] | null | null | null | src/test/java/io/fries/koans/stream/Exercise01.java | Abib-P/java-stream-koans | 5095a66d83ebb8ba98dc12d065e956680811d27c | [
"Unlicense"
] | null | null | null | src/test/java/io/fries/koans/stream/Exercise01.java | Abib-P/java-stream-koans | 5095a66d83ebb8ba98dc12d065e956680811d27c | [
"Unlicense"
] | null | null | null | 38.490196 | 104 | 0.693836 | 5,962 | package io.fries.koans.stream;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
class Exercise01 extends OnlineStore {
/**
* Create a {@link Stream} from customerList only including customer who has more budget than 10000.
* Use lambda expression for {@link Predicate} and {@link Stream#filter} for filtering.
*/
@Test
void find_rich_customers() {
List<Customer> customerList = mall.getCustomers();
Predicate<Customer> richCustomerCondition = customer -> customer.getBudget() > 10000;
Stream<Customer> richCustomerStream = customerList.stream()
.filter(richCustomerCondition);
assertThat(isLambda(richCustomerCondition)).isTrue();
List<Customer> richCustomer = richCustomerStream.collect(Collectors.toList());
assertThat(richCustomer).hasSize(2);
assertThat(richCustomer).containsExactly(customerList.get(3), customerList.get(7));
}
/**
* Create a {@link Stream} from customerList with age values.
* Use method reference(best) or lambda expression(okay) for creating {@link Function} which will
* convert {@link Customer} to {@link Integer}, and then apply it by using {@link Stream#map}.
*/
@Test
void how_old_are_the_customers() {
List<Customer> customerList = mall.getCustomers();
Function<Customer, Integer> getAgeFunction = Customer::getAge;
Stream<Integer> ageStream = customerList.stream().map(getAgeFunction);
assertThat(isLambda(getAgeFunction)).isTrue();
List<Integer> ages = ageStream.collect(Collectors.toList());
assertThat(ages).hasSize(10);
assertThat(ages).containsExactly(22, 27, 28, 38, 26, 22, 32, 35, 21, 36);
}
}
|
3e0e14700f8668dd010585c547fb930f7070d8f9 | 410 | java | Java | src/main/java/EncryptionTools/Exception/CryptoException.java | EvanMark/Standalone-Java-Telematics-App | 8d6a0bbcfb080282f42eaf23cea4594d06f8dcc9 | [
"MIT"
] | null | null | null | src/main/java/EncryptionTools/Exception/CryptoException.java | EvanMark/Standalone-Java-Telematics-App | 8d6a0bbcfb080282f42eaf23cea4594d06f8dcc9 | [
"MIT"
] | 3 | 2018-06-28T15:31:32.000Z | 2018-08-10T19:48:59.000Z | src/main/java/EncryptionTools/Exception/CryptoException.java | EvanMark/Standalone-Java-Telematics-App | 8d6a0bbcfb080282f42eaf23cea4594d06f8dcc9 | [
"MIT"
] | null | null | null | 21.578947 | 65 | 0.714634 | 5,963 |
package EncryptionTools.Exception;
//New exception to manage many others in class CryptoUtils.
//Check there to understand its purpose
public class CryptoException extends Exception {
public CryptoException() {
}
public CryptoException(String message) {
super(message);
}
public CryptoException(String message, Throwable throwable) {
super(message, throwable);
}
}
|
3e0e14eb50e863dd33348766a53007baac809cef | 6,484 | java | Java | src/main/java/com/ts/service/pdss/pdss/manager/IDrugSecurityChecker.java | ljcservice/autumn | 37fecc185dafa71e2bf8afbae6e455fc9533a7c5 | [
"Apache-2.0"
] | 5 | 2018-04-27T00:55:26.000Z | 2020-08-29T15:28:32.000Z | src/main/java/com/ts/service/pdss/pdss/manager/IDrugSecurityChecker.java | ljcservice/autumnprogram | 37fecc185dafa71e2bf8afbae6e455fc9533a7c5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ts/service/pdss/pdss/manager/IDrugSecurityChecker.java | ljcservice/autumnprogram | 37fecc185dafa71e2bf8afbae6e455fc9533a7c5 | [
"Apache-2.0"
] | null | null | null | 34.489362 | 213 | 0.644972 | 5,964 | package com.ts.service.pdss.pdss.manager;
import java.util.List;
import com.hitzd.his.Beans.TPatOrderDrug;
import com.hitzd.his.Beans.TPatientOrder;
import com.ts.entity.pdss.pdss.Beans.TDrug;
import com.ts.entity.pdss.pdss.RSBeans.TDrugSecurityRslt;
public interface IDrugSecurityChecker
{
/**
* 全局检查函数,可以一次性检查所有的检查项目 PatientOrder 医嘱对象
*
* @return
*/
public TDrugSecurityRslt DrugSecurityCheck(TPatientOrder po);
/**
* 字符串组装医嘱对象
* @param doctorInfo
* @param patientInfo
* @param drugInfo
* @param diagnosisInfo
* @param sensitiveInfo
* @return
*/
public TDrugSecurityRslt DrugSecurityCheckS(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 互动信息
*
* @param Drugs
* @return
*/
public TDrugSecurityRslt DrugInteractionCheck(TPatientOrder po);
/**
* 互动信息
* @throws Exception
*/
public TDrugSecurityRslt DrugInteractionCheckS(String[] Drugs) throws Exception;
public TDrugSecurityRslt DrugInteractionCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 配伍信息
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugIvEffectCheck(TPatientOrder po);
/**
* 配伍
*/
public TDrugSecurityRslt DrugIvEffectCheckS(String[] DrugIds, String[] RecMainIds, String[] AdministrationIds);
public TDrugSecurityRslt DrugIvEffectCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 禁忌症审查
*
* @param drugs
* @param diagnosis
* @return
*/
public TDrugSecurityRslt DrugDiagCheck( TPatientOrder po)throws Exception;
/**
* 禁忌症审查
*
* @param drugs
* @param diagnosis
* @return
*/
public TDrugSecurityRslt DrugDiagCheckS(String[] drugs, String[] diagnosis)throws Exception;
public TDrugSecurityRslt DrugDiagCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 特殊人群
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugSpecPeopleCheck(TPatientOrder po);
/**
* 特殊人群
*/
public TDrugSecurityRslt DrugSpecPeopleCheckS(String[] DrugIds, String BirthDay, String patType, String isLiverWhole, String isKidneyWhole);
public TDrugSecurityRslt DrugSpecPeopleCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 重复成份审
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugIngredientCheck(TPatientOrder po);
/**
* 重复用药
*/
public TDrugSecurityRslt DrugIngredientCheckS(String[] DrugIds);
public TDrugSecurityRslt DrugIngredientCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 用药途径审查
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugAdministrationCheck(TPatientOrder po);
/**
* 药品给药途径审查结果
*/
public TDrugSecurityRslt DrugAdministrationCheckS(String[] DrugIds, String[] AdminIds);
public TDrugSecurityRslt DrugAdministrationCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 过敏药物审查
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugAllergenCheck(TPatientOrder po);
/**
* 药物过敏审查
*/
public TDrugSecurityRslt DrugAllergenCheckS(String[] DrugIds, String[] SensitIds);
public TDrugSecurityRslt DrugAllergenCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 药物剂量审查
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugDosageCheck(TPatientOrder po);
/**
* 药物剂量审查结果
*/
public TDrugSecurityRslt DrugDosageCheckS(String[] DrugIds, String[] Dosages, String[] PerformFreqDictIds,
String[] StartDates, String[] StopDates,
String Weight, String Height, String BirthDay);
public TDrugSecurityRslt DrugDosageCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 异常信号审查
*
* @param po
* @return
*/
public TDrugSecurityRslt DrugSideCheck(TPatientOrder po);
/**
* 异常信号审查子 病人不良反应
*/
public TDrugSecurityRslt DrugSideCheckS(String[] DrugIds, String[] AdminIds, String[] SensitIds);
public TDrugSecurityRslt DrugSideCheckA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 医保审查
* @param po
* @return
*/
public TDrugSecurityRslt MedicareChecker(TPatientOrder po);
public TDrugSecurityRslt MedicareCheckerS(String DrugID, String DiagnoseCode);
public TDrugSecurityRslt MedicareCheckerA(String[] doctorInfo, String[] patientInfo, String[][] drugInfo, String[][] diagnosisInfo, String[][] sensitiveInfo,String[][] patSigns,String[] patOperation);
/**
* 抗菌药物审核
* @param po
* @return
*/
public TDrugSecurityRslt AntiDrugChecker(TPatientOrder po);
/**
* 药物授权控制审核
* @param po
* @return
*/
public TDrugSecurityRslt DrugUserAuthChecker(TPatientOrder po);
/**
* 返回单个药品信息
* @param drugCode
* @return
*/
public TDrug getDrugDesc(String drugCode);
/**
* 返回多个药品信息
* @param drugCode
* @return
*/
public TDrug[] getDrugDescA(String[] drugCode);
}
|
3e0e1551b8bcf4694ff3d8d029755192bc48b5d9 | 2,103 | java | Java | cdap-app-templates/cdap-etl/cdap-etl-api/src/main/java/io/cdap/cdap/etl/api/engine/sql/SQLEngineOutput.java | corner4world/cdap | ca0404135fac9d1d564dc2013c9186b65ac97f3d | [
"Apache-2.0"
] | 278 | 2015-02-01T21:29:02.000Z | 2018-11-29T20:22:23.000Z | cdap-app-templates/cdap-etl/cdap-etl-api/src/main/java/io/cdap/cdap/etl/api/engine/sql/SQLEngineOutput.java | corner4world/cdap | ca0404135fac9d1d564dc2013c9186b65ac97f3d | [
"Apache-2.0"
] | 8,921 | 2015-01-01T16:40:44.000Z | 2018-11-29T21:58:11.000Z | cdap-app-templates/cdap-etl/cdap-etl-api/src/main/java/io/cdap/cdap/etl/api/engine/sql/SQLEngineOutput.java | corner4world/cdap | ca0404135fac9d1d564dc2013c9186b65ac97f3d | [
"Apache-2.0"
] | 158 | 2015-01-28T00:03:39.000Z | 2018-11-27T17:43:18.000Z | 29.208333 | 115 | 0.709938 | 5,965 | /*
* Copyright © 2022 Cask Data, 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.cdap.cdap.etl.api.engine.sql;
import io.cdap.cdap.api.data.batch.Output;
import java.util.Map;
/**
* Sinks that want to employ optimization by an SQL Engine may push SQLEngine-specific outputs in addition
* to regular ones
*/
public class SQLEngineOutput extends Output {
private final String stageName;
private final String sqlEngineClassName;
private final Map<String, String> arguments;
public SQLEngineOutput(String name, String stageName, String sqlEngineClassName, Map<String, String> arguments) {
super(name);
this.stageName = stageName;
this.sqlEngineClassName = sqlEngineClassName;
this.arguments = arguments;
}
/**
* Gets the stage name for this output. This name is used to allocate metrics to the appropriate sink after the
* output is written into the SQL engine
* @return the stage name
*/
public String getStageName() {
return stageName;
}
/**
* Gets the class name for the SQL engine implementation
* @return class name for the SQL engine implementation
*/
public String getSqlEngineClassName() {
return sqlEngineClassName;
}
/**
* Get arguments used for output configuration
* @return arguments used for output configuration
*/
public Map<String, String> getArguments() {
return arguments;
}
@Override
public String toString() {
return "SQLEngineOutput{" +
"name='" + getName() + '\'' +
", sqlEngineClassName='" + sqlEngineClassName + '\'' +
"} ";
}
}
|
3e0e1570801f76f35a0834b5d38c8fc2853d65af | 82 | java | Java | src/main/java/com/yjiky/mt/config/metrics/package-info.java | kuonglv/jhipster-multitenancy | 8adc9cd575aee423345ada31106f8054356c8117 | [
"Apache-2.0"
] | 35 | 2015-04-19T10:17:55.000Z | 2022-01-20T10:23:18.000Z | src/main/java/com/yjiky/mt/config/metrics/package-info.java | kuonglv/jhipster-multitenancy | 8adc9cd575aee423345ada31106f8054356c8117 | [
"Apache-2.0"
] | 1 | 2019-08-13T11:00:34.000Z | 2019-08-13T11:00:34.000Z | src/main/java/com/yjiky/mt/config/metrics/package-info.java | kuonglv/jhipster-multitenancy | 8adc9cd575aee423345ada31106f8054356c8117 | [
"Apache-2.0"
] | 24 | 2015-04-19T08:57:09.000Z | 2020-11-04T14:57:06.000Z | 16.4 | 36 | 0.707317 | 5,966 | /**
* Health and Metrics specific code.
*/
package com.yjiky.mt.config.metrics;
|
3e0e167ebda54148d09bc7f3de68e1a26bc7c8d9 | 140 | java | Java | angulargwt/src/main/java/com/google/gwt/angular/client/AngularModule.java | h0ru5/angulargwt | 2f300ef4fc826d6148e37c4b992b0b5e92f7c60e | [
"MIT"
] | 44 | 2015-01-16T20:48:35.000Z | 2021-11-16T12:35:43.000Z | angulargwt/src/main/java/com/google/gwt/angular/client/AngularModule.java | pungme/angulargwt | c0d6cf3707a8b8f66ce7d7022ccee93ed9cce163 | [
"MIT"
] | 3 | 2015-01-10T14:46:08.000Z | 2017-04-27T10:14:49.000Z | angulargwt/src/main/java/com/google/gwt/angular/client/AngularModule.java | h0ru5/angulargwt | 2f300ef4fc826d6148e37c4b992b0b5e92f7c60e | [
"MIT"
] | 16 | 2015-01-05T23:15:49.000Z | 2021-02-24T09:17:52.000Z | 17.5 | 56 | 0.757143 | 5,967 | package com.google.gwt.angular.client;
/**
* Tagging interface implemented by all Angular modules.
*/
public interface AngularModule {
}
|
3e0e16b83353f4df34fa2914bc3fd7fbeacb44c9 | 13,915 | java | Java | streamkv-java/src/test/java/streamkv/api/java/operator/checkpointing/KVStoreCheckpointingTest.java | gyfora/StreamKV | d1c329e4e497333303766d7cf648231a93d0daf9 | [
"Apache-2.0"
] | 25 | 2015-09-14T12:40:30.000Z | 2021-02-21T22:06:53.000Z | streamkv-java/src/test/java/streamkv/api/java/operator/checkpointing/KVStoreCheckpointingTest.java | gyfora/StreamKV | d1c329e4e497333303766d7cf648231a93d0daf9 | [
"Apache-2.0"
] | 5 | 2015-09-17T09:11:06.000Z | 2015-09-29T11:38:01.000Z | streamkv-java/src/test/java/streamkv/api/java/operator/checkpointing/KVStoreCheckpointingTest.java | gyfora/StreamKV | d1c329e4e497333303766d7cf648231a93d0daf9 | [
"Apache-2.0"
] | 2 | 2016-03-17T14:35:19.000Z | 2017-10-22T16:57:22.000Z | 31.769406 | 114 | 0.711822 | 5,968 | /*
* Copyright 2015 Gyula Fóra
*
* 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 streamkv.api.java.operator.checkpointing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.OperatorState;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.source.EventTimeSourceFunction;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.test.util.ForkableFlinkMiniCluster;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import streamkv.api.java.KVStore;
import streamkv.api.java.OperationOrdering;
import streamkv.api.java.Query;
@SuppressWarnings("serial")
/**
* Test for verifying that KVStore properly works despite task failures, using the checkpoint mechanism.
*
*/
public class KVStoreCheckpointingTest implements Serializable {
final static int NUM_KEYS = 25;
static List<Tuple2<String, Integer>> input;
static List<Tuple2<String, Integer>[]> mgetInput1;
static List<Tuple2<String, Integer>[]> mgetInput2;
protected static final int NUM_TASK_MANAGERS = 2;
protected static final int NUM_TASK_SLOTS = 3;
protected static final int PARALLELISM = NUM_TASK_MANAGERS * NUM_TASK_SLOTS;
private static Random rnd = new Random();
private static ForkableFlinkMiniCluster cluster;
public void testProgram(StreamExecutionEnvironment env) {
env.getConfig().enableTimestamps();
input = generateInputs(env.getParallelism() * 5000);
mgetInput1 = generateKVArrays(input);
mgetInput2 = generateKVArrays(input);
DataStream<Tuple2<String, Integer>> putSource = env.addSource(new PutSource(input));
DataStream<String> get1 = env.addSource(new GetSource(input)).map(
new MapFunction<Tuple2<String, Integer>, String>() {
@Override
public String map(Tuple2<String, Integer> value) throws Exception {
return value.f0;
}
});
DataStream<String> get2 = env.addSource(new GetSource(input)).map(
new MapFunction<Tuple2<String, Integer>, String>() {
@Override
public String map(Tuple2<String, Integer> value) throws Exception {
return value.f0;
}
});
DataStream<String[]> mget1 = env.addSource(new MGetSource(mgetInput1)).map(
new MapFunction<Tuple2<String, Integer>[], String[]>() {
@Override
public String[] map(Tuple2<String, Integer>[] value) throws Exception {
String[] out = new String[value.length];
for (int i = 0; i < value.length; i++) {
out[i] = value[i].f0;
}
return out;
}
});
DataStream<Tuple2<String, Integer>> sget1 = env.addSource(new GetSource(input));
DataStream<Tuple2<String, Integer>[]> smget1 = env.addSource(new MGetSource(mgetInput2));
KVStore<String, Integer> store = KVStore.withOrdering(OperationOrdering.TIMESTAMP);
store.put(putSource);
Query<Tuple2<String, Integer>> getQ = store.get(get1);
Query<Tuple2<String, Integer>> getQ2 = store.get(get2);
Query<Tuple2<String, Integer>[]> mgetQ = store.multiGet(mget1);
Query<Tuple2<Tuple2<String, Integer>, Integer>> sgetQ = store.getWithKeySelector(sget1,
new KeySelector<Tuple2<String, Integer>, String>() {
@Override
public String getKey(Tuple2<String, Integer> value) throws Exception {
return value.f0;
}
});
Query<Tuple2<Tuple2<String, Integer>, Integer>[]> smgetQ = store.multiGetWithKeySelector(smget1,
new KeySelector<Tuple2<String, Integer>, String>() {
@Override
public String getKey(Tuple2<String, Integer> value) throws Exception {
return value.f0;
}
});
getQ.getOutput().map(new OnceFailingMapper()).addSink(new CollectingSink<Tuple2<String, Integer>>());
mgetQ.getOutput().addSink(new CollectingSink<Tuple2<String, Integer>[]>());
getQ2.getOutput().addSink(new CollectingSink<Tuple2<String, Integer>>());
sgetQ.getOutput().addSink(new CollectingSink<Tuple2<Tuple2<String, Integer>, Integer>>());
smgetQ.getOutput().addSink(new CollectingSink<Tuple2<Tuple2<String, Integer>, Integer>[]>());
}
@SuppressWarnings("unchecked")
public void postSubmit() {
assertTrue(OnceFailingMapper.failed);
Set<Tuple2<String, Integer>> inputSet = new HashSet<>(input);
assertEquals(inputSet, CollectingSink.allCollected.get(0));
assertEquals(toSetOfSets(mgetInput1), toSetOfSets(CollectingSink.allCollected.get(1)));
assertEquals(inputSet, CollectingSink.allCollected.get(2));
for (Object o : CollectingSink.allCollected.get(3)) {
Tuple2<Tuple2<String, Integer>, Integer> tt = (Tuple2<Tuple2<String, Integer>, Integer>) o;
assertEquals(tt.f0.f1, tt.f1);
}
for (Object o : CollectingSink.allCollected.get(4)) {
Tuple2<Tuple2<String, Integer>, Integer>[] arr = (Tuple2<Tuple2<String, Integer>, Integer>[]) o;
for (Tuple2<Tuple2<String, Integer>, Integer> tt : arr) {
assertEquals(tt.f0.f1, tt.f1);
}
}
}
@BeforeClass
public static void startCluster() {
try {
Configuration config = new Configuration();
config.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, NUM_TASK_MANAGERS);
config.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, NUM_TASK_SLOTS);
config.setString(ConfigConstants.DEFAULT_EXECUTION_RETRY_DELAY_KEY, "0 ms");
config.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 12);
cluster = new ForkableFlinkMiniCluster(config, false);
cluster.start();
} catch (Exception e) {
e.printStackTrace();
fail("Failed to start test cluster: " + e.getMessage());
}
}
@AfterClass
public static void stopCluster() {
try {
cluster.stop();
cluster = null;
} catch (Exception e) {
e.printStackTrace();
fail("Failed to stop test cluster: " + e.getMessage());
}
}
@Test
public void runCheckpointedProgram() {
try {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createRemoteEnvironment("localhost",
cluster.getLeaderRPCPort());
env.setParallelism(PARALLELISM);
env.enableCheckpointing(1000);
env.getConfig().disableSysoutLogging();
testProgram(env);
env.execute();
postSubmit();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private static class CollectingSink<T> extends RichSinkFunction<T> {
private static final long serialVersionUID = 1L;
public static List<Set<Object>> allCollected = Collections.synchronizedList(new ArrayList<Set<Object>>());
private Set<Object> collected;
private int i;
public CollectingSink() {
allCollected.add(Collections.newSetFromMap(new ConcurrentHashMap<Object, Boolean>()));
i = allCollected.size() - 1;
}
@Override
public void invoke(T value) throws Exception {
collected.add(value);
}
@Override
public void open(Configuration c) {
collected = allCollected.get(i);
}
}
private static class OnceFailingMapper implements MapFunction<Tuple2<String, Integer>, Tuple2<String, Integer>> {
private static final long serialVersionUID = 1L;
private static volatile boolean failed = false;
private int c = 0;
@Override
public Tuple2<String, Integer> map(Tuple2<String, Integer> value) throws Exception {
if (!failed && c++ == 5000) {
failed = true;
throw new RuntimeException("FAIL");
} else {
return value;
}
}
}
private List<Tuple2<String, Integer>> generateInputs(int len) {
List<Tuple2<String, Integer>> output = new ArrayList<>();
Random rnd = new Random();
for (int i = 0; i < len; i++) {
output.add(Tuple2.of("" + rnd.nextInt(NUM_KEYS), rnd.nextInt()));
}
return output;
}
@SuppressWarnings("unchecked")
private List<Tuple2<String, Integer>[]> generateKVArrays(List<Tuple2<String, Integer>> inputs) {
List<Tuple2<String, Integer>[]> out = new ArrayList<>();
for (int i = 0; i < inputs.size(); i++) {
int nk = rnd.nextInt(i < 10 ? i + 1 : 10) + 1;
List<Tuple2<String, Integer>> kvs = new ArrayList<>();
Set<String> keys = new HashSet<>();
for (int j = 0; j < nk; j++) {
Tuple2<String, Integer> candidate = inputs.get(i - j);
if (!keys.contains(candidate.f0)) {
kvs.add(candidate);
keys.add(candidate.f0);
}
}
out.add(kvs.toArray(new Tuple2[kvs.size()]));
}
return out;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Set<Set<Tuple2<String, Integer>>> toSetOfSets(Collection c) {
Set<Set<Tuple2<String, Integer>>> out = new HashSet<>();
for (Object o : c) {
Set<Tuple2<String, Integer>> kvSet = new HashSet<>();
for (Tuple2<String, Integer> t : (Tuple2<String, Integer>[]) o) {
kvSet.add(t);
}
out.add(kvSet);
}
return out;
}
public static class PutSource extends RichParallelSourceFunction<Tuple2<String, Integer>> implements
EventTimeSourceFunction<Tuple2<String, Integer>> {
private static final long serialVersionUID = 1L;
private List<Tuple2<String, Integer>> inputs;
private OperatorState<Integer> offset;
private volatile boolean isRunning = false;
public PutSource(List<Tuple2<String, Integer>> inputs) {
this.inputs = inputs;
}
@Override
public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception {
isRunning = true;
synchronized (ctx.getCheckpointLock()) {
while (isRunning && offset.value() < inputs.size()) {
Tuple2<String, Integer> input = inputs.get(offset.value());
long time = 2 * offset.value();
ctx.collectWithTimestamp(Tuple2.of(input.f0, input.f1), time);
if (rnd.nextDouble() < 0.1) {
ctx.emitWatermark(new Watermark(time));
}
offset.update(offset.value() + getRuntimeContext().getNumberOfParallelSubtasks());
if (rnd.nextDouble() < 0.001) {
Thread.sleep(10);
}
}
}
}
@Override
public void cancel() {
isRunning = false;
}
@Override
public void open(Configuration c) throws IOException {
offset = getRuntimeContext().getOperatorState("offset", getRuntimeContext().getIndexOfThisSubtask(), false);
}
}
public static class GetSource extends RichParallelSourceFunction<Tuple2<String, Integer>> implements
EventTimeSourceFunction<Tuple2<String, Integer>> {
private static final long serialVersionUID = 1L;
private List<Tuple2<String, Integer>> inputs;
private OperatorState<Integer> offset;
private volatile boolean isRunning = false;
public GetSource(List<Tuple2<String, Integer>> inputs) {
this.inputs = inputs;
}
@Override
public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception {
isRunning = true;
synchronized (ctx.getCheckpointLock()) {
while (isRunning && offset.value() < inputs.size()) {
Tuple2<String, Integer> input = inputs.get(offset.value());
long time = 2 * offset.value() + 1;
ctx.collectWithTimestamp(input, time);
if (rnd.nextDouble() < 0.1) {
ctx.emitWatermark(new Watermark(time));
}
offset.update(offset.value() + getRuntimeContext().getNumberOfParallelSubtasks());
if (rnd.nextDouble() < 0.001) {
Thread.sleep(10);
}
}
}
}
@Override
public void cancel() {
isRunning = false;
}
@Override
public void open(Configuration c) throws IOException {
offset = getRuntimeContext().getOperatorState("offset", getRuntimeContext().getIndexOfThisSubtask(), false);
}
}
public static class MGetSource extends RichParallelSourceFunction<Tuple2<String, Integer>[]> implements
EventTimeSourceFunction<Tuple2<String, Integer>[]> {
private static final long serialVersionUID = 1L;
private List<Tuple2<String, Integer>[]> inputs;
private OperatorState<Integer> offset;
private volatile boolean isRunning = false;
public MGetSource(List<Tuple2<String, Integer>[]> inputs) {
this.inputs = inputs;
}
@Override
public void run(SourceContext<Tuple2<String, Integer>[]> ctx) throws Exception {
isRunning = true;
synchronized (ctx.getCheckpointLock()) {
while (isRunning && offset.value() < inputs.size()) {
long time = 2 * offset.value() + 1;
ctx.collectWithTimestamp(inputs.get(offset.value()), time);
if (rnd.nextDouble() < 0.1) {
ctx.emitWatermark(new Watermark(time));
}
offset.update(offset.value() + getRuntimeContext().getNumberOfParallelSubtasks());
if (rnd.nextDouble() < 0.001) {
Thread.sleep(10);
}
}
}
}
@Override
public void cancel() {
isRunning = false;
}
@Override
public void open(Configuration c) throws IOException {
offset = getRuntimeContext().getOperatorState("offset", getRuntimeContext().getIndexOfThisSubtask(), false);
}
}
}
|
3e0e196a5d06ffbfcff4ba859666b46f6f921c38 | 946 | java | Java | utilisateurs_service/src/test/java/com/terrier/finances/gestion/services/utilisateurs/test/data/TestDataUtilisateur.java | vzwingma/gestion-budget-services | 5e91d761eda611d2354fd115d60955f74dcb366c | [
"Apache-2.0"
] | 1 | 2018-09-10T12:37:12.000Z | 2018-09-10T12:37:12.000Z | utilisateurs_service/src/test/java/com/terrier/finances/gestion/services/utilisateurs/test/data/TestDataUtilisateur.java | vzwingma/gestion-budget-services | 5e91d761eda611d2354fd115d60955f74dcb366c | [
"Apache-2.0"
] | 62 | 2018-09-13T15:15:03.000Z | 2022-03-28T16:15:07.000Z | utilisateurs_service/src/test/java/com/terrier/finances/gestion/services/utilisateurs/test/data/TestDataUtilisateur.java | vzwingma/gestion-budget-services | 5e91d761eda611d2354fd115d60955f74dcb366c | [
"Apache-2.0"
] | null | null | null | 32.62069 | 101 | 0.762156 | 5,969 | package com.terrier.finances.gestion.services.utilisateurs.test.data;
import com.terrier.finances.gestion.communs.parametrages.model.v12.CategorieOperation;
import com.terrier.finances.gestion.communs.utilisateur.enums.UtilisateurPrefsEnum;
import com.terrier.finances.gestion.services.utilisateurs.business.model.v12.Utilisateur;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* Jeu de données Catégorie
*/
public class TestDataUtilisateur {
public static Utilisateur getTestUtilisateur(){
Utilisateur userOK = new Utilisateur();
userOK.setId("345345");
userOK.setLogin("Test");
userOK.setDernierAcces(LocalDateTime.now());
userOK.setPrefsUtilisateur(new HashMap<>());
userOK.getPrefsUtilisateur().put(UtilisateurPrefsEnum.PREFS_STATUT_NLLE_DEPENSE, "Nouvelle");
return userOK;
}
}
|
3e0e1a389e848908bfc1446b55565173bca9d28f | 439 | java | Java | src/test/java/nablarch/common/permission/Ugroup.java | nablarch/nablarch-common-auth-jdbc | e785031b155e83bbcd97c23617120dd1e91ee3ac | [
"Apache-2.0"
] | null | null | null | src/test/java/nablarch/common/permission/Ugroup.java | nablarch/nablarch-common-auth-jdbc | e785031b155e83bbcd97c23617120dd1e91ee3ac | [
"Apache-2.0"
] | null | null | null | src/test/java/nablarch/common/permission/Ugroup.java | nablarch/nablarch-common-auth-jdbc | e785031b155e83bbcd97c23617120dd1e91ee3ac | [
"Apache-2.0"
] | null | null | null | 16.884615 | 62 | 0.687927 | 5,970 | package nablarch.common.permission;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* UGROUP
*/
@Entity
@Table(name = "UGROUP")
public class Ugroup {
public Ugroup() {
}
public Ugroup(String ugroupId) {
this.ugroupId = ugroupId;
}
@Id
@Column(name = "UGROUP_ID", length = 10, nullable = false)
public String ugroupId;
}
|
3e0e1ac17f23c8ecd2ec61cb83c9206a7e40b9d9 | 448 | java | Java | src/test/java/coded/dependency/injection/internal/fortest/MyAnonymousApp.java | gerixx/jcodeddi | aed28e2e24458713d1bc257a49426711052107a8 | [
"Apache-2.0"
] | null | null | null | src/test/java/coded/dependency/injection/internal/fortest/MyAnonymousApp.java | gerixx/jcodeddi | aed28e2e24458713d1bc257a49426711052107a8 | [
"Apache-2.0"
] | null | null | null | src/test/java/coded/dependency/injection/internal/fortest/MyAnonymousApp.java | gerixx/jcodeddi | aed28e2e24458713d1bc257a49426711052107a8 | [
"Apache-2.0"
] | null | null | null | 23.578947 | 70 | 0.756696 | 5,971 | package coded.dependency.injection.internal.fortest;
import coded.dependency.injection.Dependency;
import coded.dependency.injection.Dependent;
public class MyAnonymousApp implements Dependent {
public static final String APPCONTEXT = "appcontext";
public Dependency<A> a = new Dependency<>(APPCONTEXT, this, A.class);
public void start() {
System.out.println("MyAnonymousApp start...");
System.out.println(a.get()
.greets());
}
}
|
3e0e1d1bdef12e18dcdc483eb4238e4332562493 | 688 | java | Java | jmccc-mcdownloader/src/main/java/org/to2mbn/jmccc/mcdownloader/provider/liteloader/VersionComparator.java | to2mbn/JMCCC | 9b61f48796ccd046ae6e9a8d09a3c66db00b1578 | [
"MIT"
] | 110 | 2015-09-03T16:39:33.000Z | 2022-03-21T03:58:13.000Z | JMCCC/jmccc-mcdownloader/src/main/java/org/to2mbn/jmccc/mcdownloader/provider/liteloader/VersionComparator.java | MiniDigger/MinecraftLauncher | 4102a72ff2a435758b5a65c8989e1b058d19c459 | [
"MIT"
] | 19 | 2015-11-06T13:55:59.000Z | 2020-03-21T14:41:36.000Z | JMCCC/jmccc-mcdownloader/src/main/java/org/to2mbn/jmccc/mcdownloader/provider/liteloader/VersionComparator.java | MiniDigger/MinecraftLauncher | 4102a72ff2a435758b5a65c8989e1b058d19c459 | [
"MIT"
] | 47 | 2015-09-27T15:55:07.000Z | 2022-03-17T04:34:43.000Z | 23.724138 | 78 | 0.672965 | 5,972 | package org.to2mbn.jmccc.mcdownloader.provider.liteloader;
import java.util.Comparator;
class VersionComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
String[] splitedA = a.split("\\.");
String[] splitedB = b.split("\\.");
int minLength = Math.min(splitedA.length, splitedB.length);
for (int i = 0; i < minLength; i++) {
int comparing;
try {
comparing = Integer.parseInt(splitedA[i]) - Integer.parseInt(splitedB[i]);
} catch (NumberFormatException e) {
comparing = splitedA[i].compareTo(splitedB[i]);
}
if (comparing != 0) {
return comparing;
}
}
return splitedA.length - splitedB.length;
}
}
|
3e0e1dcef556616767096614afb8e7ab3083b3c1 | 3,130 | java | Java | src/main/java/org/zxp/esclientrhl/auto/util/GetBasePackage.java | Bruce-V/esclientrhl | 54b30d1e94c49a917a95faa64fe60172d6168377 | [
"Apache-2.0"
] | 4 | 2021-04-08T06:25:24.000Z | 2021-11-10T01:11:24.000Z | src/main/java/org/zxp/esclientrhl/auto/util/GetBasePackage.java | Bruce-V/esclientrhl | 54b30d1e94c49a917a95faa64fe60172d6168377 | [
"Apache-2.0"
] | 16 | 2020-03-05T00:22:51.000Z | 2022-02-27T12:06:11.000Z | src/main/java/org/zxp/esclientrhl/auto/util/GetBasePackage.java | Bruce-V/esclientrhl | 54b30d1e94c49a917a95faa64fe60172d6168377 | [
"Apache-2.0"
] | 2 | 2021-11-10T01:08:05.000Z | 2022-03-06T12:54:35.000Z | 37.710843 | 133 | 0.703514 | 5,973 | package org.zxp.esclientrhl.auto.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import java.lang.annotation.Annotation;
import java.util.*;
import java.util.stream.Stream;
/**
* program: esclientrhl
* description: 获取basepackage列表
* author: X-Pacific zhang
* create: 2019-09-02 22:12
**/
public class GetBasePackage {
//缓存的entitypaths
private static Map<Class,List<String>> entityPathsMap = null;
static {
entityPathsMap = new HashMap<>();
}
private Class<? extends Annotation> annotation;
public GetBasePackage(Class<? extends Annotation> annotation) {
this.annotation = annotation;
}
/**
* 获取repository的路径,如果获取不到就取main启动路径
* @param annotationMetadata
* @return
*/
public Stream<String> getBasePackage(AnnotationMetadata annotationMetadata){
Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(annotation.getName());
AnnotationAttributes attributes = new AnnotationAttributes(annotationAttributes);
EnableESTools.gainAnnoInfo(attributes);
String[] value = EnableESTools.getValue();//annotationg中的注解
String[] basePackages = EnableESTools.getBasePackages();//annotationg中的注解
String[] entityPaths = EnableESTools.getEntityPath();//annotationg中的注解
//没配注解参数
if (value.length == 0 && basePackages.length == 0) {
String className = annotationMetadata.getClassName();
return Stream.of(ClassUtils.getPackageName(className));
}
//配了注解
return Stream.of(Arrays.asList(value),Arrays.asList(basePackages),Arrays.asList(entityPaths)).flatMap(list -> list.stream());
}
/**
* 获取实体类的路径,如果获取不到就取main启动路径
* @param annotationMetadata
* @return
*/
public Stream<String> getEntityPackage(AnnotationMetadata annotationMetadata){
//缓存entitypaths
if(entityPathsMap.containsKey(annotation)){
return Stream.of(entityPathsMap.get(annotation)).flatMap(list -> list.stream());
}
Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(annotation.getName());
AnnotationAttributes attributes = new AnnotationAttributes(annotationAttributes);
String[] entityPaths = attributes.getStringArray("entityPath");//annotationg中的注解
//没配注解参数
if (entityPaths.length == 0) {
String className = annotationMetadata.getClassName();
entityPathsMap.put(annotation,Arrays.asList(ClassUtils.getPackageName(className)));
return Stream.of(ClassUtils.getPackageName(className));
}
entityPathsMap.put(annotation,Arrays.asList(entityPaths));
//配了注解
return Stream.of(Arrays.asList(entityPaths)).flatMap(list -> list.stream());
}
public static Map<Class, List<String>> getEntityPathsMap() {
return entityPathsMap;
}
}
|
3e0e1f4d1f2e90da2eb8d685bc30d6572dee882e | 4,274 | java | Java | src/main/java/org/ottobackwards/dsl/Syslog5424Visitor.java | ottobackwards/grok-v-antlr | 69923d4dd1b65caaaa8f83657d5ce4370f07e4b1 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ottobackwards/dsl/Syslog5424Visitor.java | ottobackwards/grok-v-antlr | 69923d4dd1b65caaaa8f83657d5ce4370f07e4b1 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ottobackwards/dsl/Syslog5424Visitor.java | ottobackwards/grok-v-antlr | 69923d4dd1b65caaaa8f83657d5ce4370f07e4b1 | [
"Apache-2.0"
] | null | null | null | 35.616667 | 96 | 0.729995 | 5,974 | /*
* 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.ottobackwards.dsl;
import java.util.HashMap;
import java.util.Map;
import org.antlr.v4.runtime.ParserRuleContext;
import org.ottobackwards.dsl.generated.Rfc5424BaseVisitor;
import org.ottobackwards.dsl.generated.Rfc5424Parser;
public class Syslog5424Visitor extends Rfc5424BaseVisitor<SLValue> {
private Map<String, Object> msgMap = new HashMap<>();
@Override
public SLValue visitSyslogMsg(Rfc5424Parser.SyslogMsgContext ctx) {
super.visitSyslogMsg(ctx);
return new SLValue(msgMap);
}
@Override
public SLValue visitSyslogHeader(Rfc5424Parser.SyslogHeaderContext ctx) {
visitIfExists(SyslogFieldKeys.HEADER_VERSION.getField(), ctx.version());
visitIfExists(SyslogFieldKeys.HEADER_APPNAME.getField(), ctx.app_name());
visitIfExists(SyslogFieldKeys.HEADER_HOSTNAME.getField(), ctx.hostname());
visitIfExists(SyslogFieldKeys.HEADER_PRI.getField(), ctx.pri());
visitIfExists(SyslogFieldKeys.HEADER_PROCID.getField(), ctx.procid());
visitIfExists(SyslogFieldKeys.HEADER_TIMESTAMP.getField(), ctx.timestamp());
visitIfExists(SyslogFieldKeys.HEADER_MSGID.getField(), ctx.msgid());
return SLValue.VOID;
}
private void visitIfExists(String name, ParserRuleContext ctx) {
SLValue value = visit(ctx);
if (value != null && !value.isNull() && !value.isVoid()) {
msgMap.put(name, value.toString());
}
}
@Override
public SLValue visitHeaderHostName(Rfc5424Parser.HeaderHostNameContext ctx) {
return new SLValue(ctx.getText());
}
@Override
public SLValue visitHeaderProcId(Rfc5424Parser.HeaderProcIdContext ctx) {
return new SLValue(ctx.getText());
}
@Override
public SLValue visitHeaderAppName(Rfc5424Parser.HeaderAppNameContext ctx) {
return new SLValue(ctx.getText());
}
@Override
public SLValue visitHeaderMsgId(Rfc5424Parser.HeaderMsgIdContext ctx) {
return new SLValue(ctx.getText());
}
@Override
public SLValue visitHeaderTimeStamp(Rfc5424Parser.HeaderTimeStampContext ctx) {
return new SLValue(ctx.full_date().getText() + "T" + ctx.full_time().getText());
}
@Override
public SLValue visitHeaderPriority(Rfc5424Parser.HeaderPriorityContext ctx) {
return super.visit(ctx.prival());
}
@Override
public SLValue visitHeaderPriorityValue(Rfc5424Parser.HeaderPriorityValueContext ctx) {
return new SLValue(ctx.getText());
}
@Override
public SLValue visitHeaderVersion(Rfc5424Parser.HeaderVersionContext ctx) {
return new SLValue(ctx.getText());
}
@Override
public SLValue visitSdElement(Rfc5424Parser.SdElementContext ctx) {
String id = ctx.sd_id().getText();
for (Rfc5424Parser.Sd_paramContext paramContext : ctx.sd_param()) {
msgMap.put(String.format(SyslogFieldKeys.STRUCTURED_ELEMENT_ID_PNAME_FMT.getField(), (id),
((Rfc5424Parser.SdParamContext) paramContext).param_name()
.getText()),
((Rfc5424Parser.SdParamContext) paramContext).param_value().getText());
}
return SLValue.VOID;
}
@Override
public SLValue visitMsgAny(Rfc5424Parser.MsgAnyContext ctx) {
msgMap.put(SyslogFieldKeys.MESSAGE.getField(), ctx.getText().trim());
return SLValue.VOID;
}
@Override
public SLValue visitMsgUTF8(Rfc5424Parser.MsgUTF8Context ctx) {
msgMap.put(SyslogFieldKeys.MESSAGE.getField(), ctx.getText().trim());
return SLValue.VOID;
}
}
|
3e0e1f726eaa2c39bed07d87a7ee5f59ae675d73 | 4,423 | java | Java | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/irfutureoption/InterestRateFutureOptionBlackValueGammaPFunction.java | UbuntuEvangelist/OG-Platform | 0aac9675ff92fd702d2e53a991de085388bfdc83 | [
"Apache-2.0"
] | 12 | 2017-03-10T13:56:52.000Z | 2021-10-03T01:21:20.000Z | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/irfutureoption/InterestRateFutureOptionBlackValueGammaPFunction.java | UbuntuEvangelist/OG-Platform | 0aac9675ff92fd702d2e53a991de085388bfdc83 | [
"Apache-2.0"
] | 1 | 2021-08-02T17:20:43.000Z | 2021-08-02T17:20:43.000Z | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/irfutureoption/InterestRateFutureOptionBlackValueGammaPFunction.java | UbuntuEvangelist/OG-Platform | 0aac9675ff92fd702d2e53a991de085388bfdc83 | [
"Apache-2.0"
] | 16 | 2017-01-12T10:31:58.000Z | 2019-04-19T08:17:33.000Z | 65.044118 | 197 | 0.84671 | 5,975 | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.irfutureoption;
import java.util.Collections;
import java.util.Set;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionMarginTransaction;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionPremiumTransaction;
import com.opengamma.analytics.financial.interestrate.future.method.InterestRateFutureOptionMarginSecurityBlackSurfaceMethod;
import com.opengamma.analytics.financial.interestrate.future.method.InterestRateFutureOptionMarginTransactionBlackSurfaceMethod;
import com.opengamma.analytics.financial.interestrate.future.method.InterestRateFutureOptionPremiumSecurityBlackSurfaceMethod;
import com.opengamma.analytics.financial.interestrate.future.method.InterestRateFutureOptionPremiumTransactionBlackSurfaceMethod;
import com.opengamma.analytics.financial.model.option.definition.YieldCurveWithBlackCubeBundle;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.model.black.BlackDiscountingValueGammaIRFutureOptionFunction;
/**
* Calculates the "ValueGammaP" ({@link ValueRequirementNames#VALUE_GAMMA_P}) of an interest rate future option.
* The underlying Futures price is computed from the futures curve.
* @deprecated Use {@link BlackDiscountingValueGammaIRFutureOptionFunction}
*/
@Deprecated
public class InterestRateFutureOptionBlackValueGammaPFunction extends InterestRateFutureOptionBlackFunction {
/** Calculates gamma for margined future options */
private static final InterestRateFutureOptionMarginTransactionBlackSurfaceMethod MARGINED_TRANSACTION_METHOD = InterestRateFutureOptionMarginTransactionBlackSurfaceMethod.getInstance();
/** Calculates the underlying forward rate for margined future options */
private static final InterestRateFutureOptionMarginSecurityBlackSurfaceMethod MARGINED_SECURITY_METHOD = InterestRateFutureOptionMarginSecurityBlackSurfaceMethod.getInstance();
/** Calculates gamma for future options with a premium */
private static final InterestRateFutureOptionPremiumTransactionBlackSurfaceMethod PREMIUM_TRANSACTION_METHOD = InterestRateFutureOptionPremiumTransactionBlackSurfaceMethod.getInstance();
/** Calculates the underlying forward rate for future options with a premium */
private static final InterestRateFutureOptionPremiumSecurityBlackSurfaceMethod PREMIUM_SECURITY_METHOD = InterestRateFutureOptionPremiumSecurityBlackSurfaceMethod.getInstance();
/**
* Sets the value requirement name to {@link ValueRequirementNames#VALUE_GAMMA_P}
*/
public InterestRateFutureOptionBlackValueGammaPFunction() {
super(ValueRequirementNames.VALUE_GAMMA_P, true);
}
@Override
protected Set<ComputedValue> getResult(final InstrumentDerivative derivative, final YieldCurveWithBlackCubeBundle data, final ValueSpecification spec, final Set<ValueRequirement> desiredValues) {
final double gamma, spot;
if (derivative instanceof InterestRateFutureOptionMarginTransaction) {
final InterestRateFutureOptionMarginTransaction transaction = (InterestRateFutureOptionMarginTransaction) derivative;
gamma = MARGINED_TRANSACTION_METHOD.presentValueGamma(transaction, data);
spot = MARGINED_SECURITY_METHOD.underlyingFuturePrice(transaction.getUnderlyingSecurity(), data);
} else if (derivative instanceof InterestRateFutureOptionPremiumTransaction) {
final InterestRateFutureOptionPremiumTransaction transaction = (InterestRateFutureOptionPremiumTransaction) derivative;
gamma = PREMIUM_TRANSACTION_METHOD.presentValueGamma(transaction, data);
spot = PREMIUM_SECURITY_METHOD.underlyingFuturePrice(transaction.getUnderlyingSecurity(), data);
} else {
throw new OpenGammaRuntimeException("Could not handle derivatives of type " + derivative.getClass());
}
final Double valueGamma = gamma * spot;
return Collections.singleton(new ComputedValue(spec, valueGamma / 2500000.0));
}
}
|
3e0e1f7de69aca3a04df074fd60a25fe452305b6 | 1,762 | java | Java | storescp/src/main/java/com/easydicm/storescp/services/impl/DicomSaveImpl.java | momostarsky/easydicm-parent | ae15add43e79e1a414d9f310437cccc8dbfbb155 | [
"Apache-2.0"
] | null | null | null | storescp/src/main/java/com/easydicm/storescp/services/impl/DicomSaveImpl.java | momostarsky/easydicm-parent | ae15add43e79e1a414d9f310437cccc8dbfbb155 | [
"Apache-2.0"
] | null | null | null | storescp/src/main/java/com/easydicm/storescp/services/impl/DicomSaveImpl.java | momostarsky/easydicm-parent | ae15add43e79e1a414d9f310437cccc8dbfbb155 | [
"Apache-2.0"
] | null | null | null | 26.69697 | 122 | 0.698638 | 5,976 | package com.easydicm.storescp.services.impl;
import com.easydicm.scpdb.mapper.IDbPatientMapper;
import com.easydicm.storescp.services.IDicomSave;
import com.easydicm.storescp.services.IMessageQueueWriter;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author dhz
*/
@Service
public class DicomSaveImpl extends BaseImpl implements IDicomSave {
private final IDbPatientMapper dbPatientMapper;
private final IMessageQueueWriter messageQueueWriter;
private String storagePath;
public DicomSaveImpl(@Autowired IDbPatientMapper dbPatientMapper, @Autowired IMessageQueueWriter messageQueueWriter) {
super();
this.dbPatientMapper = dbPatientMapper;
this.messageQueueWriter = messageQueueWriter;
}
@Override
public Path computeSavePath(Attributes attr) throws IOException{
String patId = attr.getString(Tag.PatientID, "");
String stdId = attr.getString(Tag.StudyInstanceUID, "");
String serId = attr.getString(Tag.SeriesInstanceUID, "");
String sopUid = attr.getString(Tag.SOPInstanceUID);
Path save = Paths.get( this.storagePath, patId, stdId, serId, sopUid + ".dcm");
if (!save.getParent().toFile().exists()) {
boolean ok = save.getParent().toFile().mkdirs();
if(!ok){
throw new IOException("创建存储目录失败:"+ save.toString());
}
}
return save;
}
@Override
public void storagePath(String storage) {
this.storagePath = storage;
}
}
|
3e0e1fd5e12cd57beb6bdcb33eb48188d5ff9152 | 637 | java | Java | src/main/java/rmit/s3790516/unilink/HelloApplication.java | ChienYao-Lin/UniLink | 25293d11e44aa7455b5bdaca97b190657877d923 | [
"MIT"
] | null | null | null | src/main/java/rmit/s3790516/unilink/HelloApplication.java | ChienYao-Lin/UniLink | 25293d11e44aa7455b5bdaca97b190657877d923 | [
"MIT"
] | null | null | null | src/main/java/rmit/s3790516/unilink/HelloApplication.java | ChienYao-Lin/UniLink | 25293d11e44aa7455b5bdaca97b190657877d923 | [
"MIT"
] | null | null | null | 27.695652 | 102 | 0.698587 | 5,977 | package rmit.s3790516.unilink;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class HelloApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
} |
3e0e20286e6f5f6e379f336835d8b09b1a1203ff | 6,910 | java | Java | src/test/java/org/cactoos/map/SolidTest.java | aivinog1/cactoos | af979def342f0bfe75e31912588681cd090c8c6c | [
"MIT"
] | 1 | 2021-06-24T14:11:14.000Z | 2021-06-24T14:11:14.000Z | src/test/java/org/cactoos/map/SolidTest.java | aivinog1/cactoos | af979def342f0bfe75e31912588681cd090c8c6c | [
"MIT"
] | null | null | null | src/test/java/org/cactoos/map/SolidTest.java | aivinog1/cactoos | af979def342f0bfe75e31912588681cd090c8c6c | [
"MIT"
] | null | null | null | 32.441315 | 80 | 0.524168 | 5,978 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 Yegor Bugayenko
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.cactoos.map;
import java.util.Map;
import org.cactoos.Scalar;
import org.cactoos.iterable.IterableOf;
import org.cactoos.text.Sub;
import org.cactoos.text.TextOf;
import org.cactoos.text.Upper;
import org.hamcrest.MatcherAssert;
import org.hamcrest.collection.IsMapContaining;
import org.hamcrest.core.AllOf;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.MatcherOf;
import org.llorllale.cactoos.matchers.RunsInThreads;
/**
* Test case for {@link Solid}.
*
* @since 0.24
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle MagicNumberCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
final class SolidTest {
@Test
void behavesAsMap() {
MatcherAssert.assertThat(
"Can't behave as a map",
new Solid<Integer, Integer>(
new MapEntry<>(0, -1),
new MapEntry<>(1, 1)
),
new BehavesAsMap<>(1, 1)
);
}
@Test
void worksInThreads() {
MatcherAssert.assertThat(
"Can't behave as a map in multiple threads",
map -> {
MatcherAssert.assertThat(
"Can't behave as a map in thread",
map,
new BehavesAsMap<>(1, 1)
);
return true;
},
new RunsInThreads<>(
new Solid<Integer, Integer>(
new MapEntry<>(0, -1),
new MapEntry<>(1, 1)
)
)
);
}
@Test
void mapsToSameObjects() throws Exception {
final Map<Integer, Scalar<Integer>> map = new Solid<>(
input -> new MapEntry<>(input, () -> input),
1, -1, 0, 1
);
MatcherAssert.assertThat(
"Can't map only once",
map.get(0), new IsEqual<>(map.get(0))
);
}
@Test
@SuppressWarnings("unchecked")
void extendsExistingMapWithArrayOfEntries() {
final Solid<Integer, Integer> map = new Solid<>(
new MapEntry<>(0, 10),
new MapEntry<>(1, 11)
);
MatcherAssert.assertThat(
"Does not extends existing map with array of entries",
new Solid<>(
map,
new MapEntry<>(2, 12),
new MapEntry<>(3, 13)
).size(),
new IsEqual<>(4)
);
}
@Test
@SuppressWarnings("unchecked")
void acceptsEmptyArray() {
MatcherAssert.assertThat(
"Accepts empty array of entries",
new Solid<Integer, Integer>(
new Solid<>(
new MapEntry<>(0, 10),
new MapEntry<>(1, 11)
),
(Map.Entry<Integer, Integer>[]) new Map.Entry<?, ?>[0]
).size(),
new IsEqual<>(2)
);
}
@Test
@SuppressWarnings("unchecked")
void mapsIterableWithKeyFuncAndValueFunc() {
final Solid<String, String> map = new Solid<>(
key -> new Sub(new TextOf(key), 0, 1).asString(),
value -> new Upper(new TextOf(value)).asString(),
new IterableOf<>("aa", "bb")
);
MatcherAssert.assertThat(
"Functions are not applied to key and value",
map,
new AllOf<>(
new IterableOf<>(
new IsMapContaining<>(
new IsEqual<>("a"),
new IsEqual<>("AA")
),
new IsMapContaining<>(
new IsEqual<>("b"),
new IsEqual<>("BB")
),
new MatcherOf<>(m -> m.size() == 2)
)
)
);
}
@Test
void mapsEmptyIterableWithKeyFuncAndValueFunc() {
final Solid<String, String> map = new Solid<>(
key -> new Sub(new TextOf(key), 0, 1).asString(),
value -> new Upper(new TextOf(value)).asString(),
new IterableOf<String>()
);
MatcherAssert.assertThat(
"Empty Iterable cannot be accepted for key and value mapping",
map,
new MatcherOf<>(m -> m.size() == 0)
);
}
@Test
@SuppressWarnings("unchecked")
void mapsIterableWithMapEntryFunc() {
MatcherAssert.assertThat(
"Function are not applied to entry",
new Solid<>(
entry -> new MapEntry<>(
new Sub(new TextOf(entry), 0, 1).asString(),
new Upper(new TextOf(entry)).asString()
),
new IterableOf<>("aa", "bb")
),
new AllOf<>(
new IterableOf<>(
new IsMapContaining<>(
new IsEqual<>("a"),
new IsEqual<>("AA")
),
new IsMapContaining<>(
new IsEqual<>("b"),
new IsEqual<>("BB")
),
new MatcherOf<>(m -> m.size() == 2)
)
)
);
}
@Test
void mapsEmptyIterableWithMapEntryFunc() {
MatcherAssert.assertThat(
"Empty Iterable cannot be accepted for MapEntry mapping",
new Solid<>(
entry -> new MapEntry<>(
new Sub(new TextOf(entry), 0, 1).asString(),
new Upper(new TextOf(entry)).asString()
),
new IterableOf<String>()
),
new MatcherOf<>(m -> m.size() == 0)
);
}
}
|
3e0e2061599ac1d93e555948852380809bddaf01 | 3,319 | java | Java | src/main/java/me/nereo/multi_image_selector/utils/MultiImageSelector.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 7 | 2017-05-30T12:01:38.000Z | 2021-04-22T12:22:39.000Z | src/main/java/me/nereo/multi_image_selector/utils/MultiImageSelector.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | null | null | null | src/main/java/me/nereo/multi_image_selector/utils/MultiImageSelector.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 6 | 2017-07-28T03:47:08.000Z | 2019-06-28T17:57:50.000Z | 38.593023 | 140 | 0.701717 | 5,979 | package me.nereo.multi_image_selector.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
public class MultiImageSelector {
private static MultiImageLoader mImageLoader;
public static void init(MultiImageLoader imageLoader) {
if (imageLoader == null) {
throw new RuntimeException("imageLoader is null !");
}
mImageLoader = imageLoader;
}
public static MultiImageLoader getImageLoader() {
return mImageLoader;
}
public static void show(Activity activity, boolean needShowTakePhoto, int maxSelectNum, int requestCode) {
show(activity, needShowTakePhoto, maxSelectNum, null, requestCode);
}
public static void show(Activity activity, boolean needShowTakePhoto, int maxSelectNum, ArrayList<String> selectPath, int requestCode) {
if (activity != null) {
activity.startActivityForResult(createIntent(activity, needShowTakePhoto, maxSelectNum, selectPath), requestCode);
}
}
public static void show(Fragment fragment, boolean needShowTakePhoto, int maxSelectNum, int requestCode) {
show(fragment, needShowTakePhoto, maxSelectNum, null, requestCode);
}
public static void show(Fragment fragment, boolean needShowTakePhoto, int maxSelectNum, ArrayList<String> selectPath, int requestCode) {
if (fragment != null) {
fragment.startActivityForResult(createIntent(fragment.getActivity(), needShowTakePhoto, maxSelectNum, selectPath), requestCode);
}
}
public static void show(Activity activity, int requestCode) {
show(activity, true, 1, requestCode);
}
public static void show(Activity activity, ArrayList<String> selectPath, int requestCode) {
show(activity, true, 1, (ArrayList) selectPath, requestCode);
}
public static void show(Fragment fragment, int requestCode) {
show(fragment, true, 1, requestCode);
}
public static void show(Fragment fragment, ArrayList<String> selectPath, int requestCode) {
show(fragment, true, 1, (ArrayList) selectPath, requestCode);
}
private static Intent createIntent(Context context, boolean needShowTakePhoto, int maxSelectNum) {
return createIntent(context, needShowTakePhoto, maxSelectNum, null);
}
private static Intent createIntent(Context context, boolean needShowTakePhoto, int maxSelectNum, ArrayList<String> selectPath) {
int selectedMode = 1;
checkInit();
Intent intent = new Intent(context, MultiImageSelectorActivity.class);
intent.putExtra("show_camera", needShowTakePhoto);
intent.putExtra("max_select_count", maxSelectNum);
if (maxSelectNum == 1) {
selectedMode = 0;
}
intent.putExtra("select_count_mode", selectedMode);
if (selectPath != null && selectPath.size() > 0) {
intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectPath);
}
return intent;
}
private static void checkInit() {
if (mImageLoader == null) {
throw new RuntimeException("请先初始化!");
}
}
}
|
3e0e213950bdc630fcfd0c6546d7e395f5c574c8 | 773 | java | Java | smart-admin-service/smart-admin-api/src/main/java/net/rfs/smartadmin/module/system/datascope/constant/DataScopeWhereInTypeEnum.java | renfushuai/erp | 715979935e66d648745b7f8475370e08702ebcff | [
"MIT"
] | 2 | 2021-05-28T08:33:59.000Z | 2021-06-01T03:40:48.000Z | smart-admin-service/smart-admin-api/src/main/java/net/rfs/smartadmin/module/system/datascope/constant/DataScopeWhereInTypeEnum.java | renfushuai/erp | 715979935e66d648745b7f8475370e08702ebcff | [
"MIT"
] | null | null | null | smart-admin-service/smart-admin-api/src/main/java/net/rfs/smartadmin/module/system/datascope/constant/DataScopeWhereInTypeEnum.java | renfushuai/erp | 715979935e66d648745b7f8475370e08702ebcff | [
"MIT"
] | null | null | null | 17.976744 | 60 | 0.644243 | 5,980 | package net.rfs.smartadmin.module.system.datascope.constant;
import net.rfs.smartadmin.common.domain.BaseEnum;
/**
* [ ]
*
* @author yandanyang
* @version 1.0
* @company 1024lab.net
* @copyright (c) 2018 1024lab.netInc. All rights reserved.
* @date 2019/5/8 0008 下午 16:00
* @since JDK1.8
*/
public enum DataScopeWhereInTypeEnum implements BaseEnum {
EMPLOYEE(0,"以员工IN"),
DEPARTMENT(1,"以部门IN"),
CUSTOM_STRATEGY(2,"自定义策略");
private Integer value;
private String desc;
DataScopeWhereInTypeEnum(Integer value, String desc) {
this.value = value;
this.desc = desc;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String getDesc() {
return desc;
}
}
|
3e0e2140482ef7c5d652d14147d20d33485abc58 | 1,916 | java | Java | struct-spring/src/test/java/org/struct/spring/support/StructScannerRegistrarTest.java | TinyZzh/ExcelUtil | fb62640b7669340c7a59be63bed89a1bdbaafd1f | [
"Apache-2.0"
] | 2 | 2019-04-13T15:33:49.000Z | 2020-03-28T03:10:04.000Z | struct-spring/src/test/java/org/struct/spring/support/StructScannerRegistrarTest.java | TinyZzh/ExcelUtil | fb62640b7669340c7a59be63bed89a1bdbaafd1f | [
"Apache-2.0"
] | 3 | 2015-10-29T14:46:31.000Z | 2019-04-25T17:53:06.000Z | struct-spring/src/test/java/org/struct/spring/support/StructScannerRegistrarTest.java | TinyZzh/ExcelUtil | fb62640b7669340c7a59be63bed89a1bdbaafd1f | [
"Apache-2.0"
] | null | null | null | 33.034483 | 100 | 0.767223 | 5,981 | /*
*
*
* Copyright (c) 2022. - TinyZ.
*
* 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.struct.spring.support;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.struct.spring.annotation.StructScan;
/**
* @author TinyZ.
* @version 2020.07.18
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = StructScannerRegistrarTest.class)
@ComponentScan(basePackages = "org.struct.spring.support")
@Configuration
@StructScan(basePackages = "org.struct.spring.support")
public class StructScannerRegistrarTest implements ApplicationContextAware {
private ApplicationContext ctx;
@Test
public void test() {
Object bean = ctx.getBean(SpringTestDataMapStructStoreImpl.class);
System.out.println();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ctx = applicationContext;
}
} |
3e0e2174e3b1dcafcfdb5d6ae75833560b8fec9f | 709 | java | Java | jgiven-tests/src/test/java/com/tngtech/jgiven/testframework/TestExecutor.java | janschaefer/JGiven_ByteBuddy | d86a522f62d0a6a115c09cbc2aad27fe76e94922 | [
"Apache-2.0"
] | 381 | 2015-01-08T06:46:25.000Z | 2022-03-25T06:39:10.000Z | jgiven-tests/src/test/java/com/tngtech/jgiven/testframework/TestExecutor.java | janschaefer/JGiven_ByteBuddy | d86a522f62d0a6a115c09cbc2aad27fe76e94922 | [
"Apache-2.0"
] | 437 | 2015-01-08T07:47:18.000Z | 2022-03-03T06:09:45.000Z | jgiven-tests/src/test/java/com/tngtech/jgiven/testframework/TestExecutor.java | janschaefer/JGiven_ByteBuddy | d86a522f62d0a6a115c09cbc2aad27fe76e94922 | [
"Apache-2.0"
] | 120 | 2015-01-29T19:47:02.000Z | 2022-03-28T08:22:17.000Z | 30.826087 | 89 | 0.667137 | 5,982 | package com.tngtech.jgiven.testframework;
import com.tngtech.jgiven.junit.JUnitExecutor;
import com.tngtech.jgiven.testng.TestNgExecutor;
public abstract class TestExecutor {
public static TestExecutor getExecutor( TestFramework framework ) {
switch( framework ) {
case JUnit:
return new JUnitExecutor();
case TestNG:
return new TestNgExecutor();
default:
throw new IllegalArgumentException( "Unknown framework: " + framework );
}
}
public abstract TestExecutionResult execute( Class<?> testClass, String testMethod );
public abstract TestExecutionResult execute( Class<?> testClass );
}
|
3e0e226dab8bd5eb6338546c3991edb0d8c52b8b | 2,423 | java | Java | samples/Java Starter Kit CD/Sun Resources/java/avh/embedding/classes/app/AppletPanel.java | raychorn/svn_java_projects | 28d386d47e43e05101272b843ee6ec68fdb951b8 | [
"CC0-1.0"
] | null | null | null | samples/Java Starter Kit CD/Sun Resources/java/avh/embedding/classes/app/AppletPanel.java | raychorn/svn_java_projects | 28d386d47e43e05101272b843ee6ec68fdb951b8 | [
"CC0-1.0"
] | null | null | null | samples/Java Starter Kit CD/Sun Resources/java/avh/embedding/classes/app/AppletPanel.java | raychorn/svn_java_projects | 28d386d47e43e05101272b843ee6ec68fdb951b8 | [
"CC0-1.0"
] | null | null | null | 23.298077 | 74 | 0.577383 | 5,983 | package app;
import awt.*;
import browser.Applet;
/**
* An applet that can contain simple components.
* Subclass this class if you want to create an applet
* that uses the UI components.
*
* @author Arthur van Hoff
*/
public
class AppletPanel extends Applet {
protected AppPanel panel;
protected AppComponent down;
protected AppComponent focus;
public boolean touched;
public void init() {
panel = new AppPanel(this);
panel.reshape(0, 0, width, height);
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.setOrigin(g.originX + panel.x, g.originY + panel.y);
g.clipRect(0, 0, panel.w, panel.h);
panel.paint(g);
touched = false;
}
public void mouseDown(int x, int y) {
down = panel.locate(x, y);
if (down != null) {
// global to local coordinates
for (AppComponent comp = down ; comp != null ; comp = comp.parent) {
x -= comp.x;
y -= comp.y;
}
down.mouseDown(x, y);
}
if (touched) {
repaint();
}
}
public void mouseDrag(int x, int y) {
if (down != null) {
// global to local coordinates
for (AppComponent comp = down ; comp != null ; comp = comp.parent) {
x -= comp.x;
y -= comp.y;
}
down.mouseDrag(x, y);
if (touched) {
repaint();
}
}
}
public void mouseUp(int x, int y) {
if (down != null) {
// global to local coordinates
for (AppComponent comp = down ; comp != null ; comp = comp.parent) {
x -= comp.x;
y -= comp.y;
}
down.mouseUp(x, y);
if (touched) {
repaint();
}
}
}
public void keyDown(int ch) {
if (focus != null) {
focus.keyDown(ch);
if (touched) {
repaint();
}
}
}
public void setFocus(AppComponent comp) {
focus = comp;
getFocus();
}
public void action(AppButton but) {
//System.out.println("BUTTON ACTION " + but.label);
}
public void action(AppCheckbox check) {
//System.out.println("CHECKBOX ACTION " + check.value);
}
public void action(AppText text) {
//System.out.println("TEXT ACTION " + text.value);
}
public void action(AppSlider slider) {
//System.out.println("SLIDER ACTION " + slider.value);
}
public void preview(AppSlider slider) {
//System.out.println("SLIDER ACTION " + slider.value);
}
}
|
3e0e22874ad6aea3043c3d555e314c082ad36cc2 | 405 | java | Java | gmall-ums/src/main/java/com/atguigu/gmall/ums/dao/MemberCollectSubjectDao.java | zhukehui/gmall | 8f6652bb4e2f2a084c293bf11225fab727ca1560 | [
"Apache-2.0"
] | null | null | null | gmall-ums/src/main/java/com/atguigu/gmall/ums/dao/MemberCollectSubjectDao.java | zhukehui/gmall | 8f6652bb4e2f2a084c293bf11225fab727ca1560 | [
"Apache-2.0"
] | 5 | 2020-02-28T01:24:32.000Z | 2021-09-20T20:53:21.000Z | gmall-ums/src/main/java/com/atguigu/gmall/ums/dao/MemberCollectSubjectDao.java | zhukehui/gmall | 8f6652bb4e2f2a084c293bf11225fab727ca1560 | [
"Apache-2.0"
] | 1 | 2019-11-05T05:21:46.000Z | 2019-11-05T05:21:46.000Z | 22.444444 | 89 | 0.782178 | 5,984 | package com.atguigu.gmall.ums.dao;
import com.atguigu.gmall.ums.entity.MemberCollectSubjectEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 会员收藏的专题活动
*
* @author huigege
* @email hzdkv@example.com
* @date 2019-10-28 23:10:10
*/
@Mapper
public interface MemberCollectSubjectDao extends BaseMapper<MemberCollectSubjectEntity> {
}
|
3e0e228d6062ad488f3c964c0a533bb3c274a164 | 1,868 | java | Java | basestar-schema/src/main/java/io/basestar/schema/util/SchemaRef.java | stage-tech/basestar | a87f5d8b3c65186edd80052a0ba9b483cdc40967 | [
"Apache-2.0"
] | 3 | 2020-04-06T10:23:37.000Z | 2020-12-23T02:37:25.000Z | basestar-schema/src/main/java/io/basestar/schema/util/SchemaRef.java | basestar/basestar | 165f3886ff0b8cf528eb137ce39cf5a9b1569763 | [
"Apache-2.0"
] | 3 | 2020-04-05T16:06:27.000Z | 2022-03-08T21:12:20.000Z | basestar-schema/src/main/java/io/basestar/schema/util/SchemaRef.java | stage-tech/basestar | a87f5d8b3c65186edd80052a0ba9b483cdc40967 | [
"Apache-2.0"
] | 3 | 2020-05-20T13:22:18.000Z | 2021-06-01T08:33:30.000Z | 24.578947 | 92 | 0.62848 | 5,985 | package io.basestar.schema.util;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.basestar.schema.Schema;
import io.basestar.schema.Version;
import io.basestar.util.Name;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.annotation.Nullable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SchemaRef {
private Name name;
private Schema.Descriptor<?, ?> inline;
public static SchemaRef withName(final Name name) {
return new SchemaRef(name, null);
}
@JsonCreator
@SuppressWarnings("unused")
public static SchemaRef withName(final String name) {
return withName(Name.parse(name));
}
@JsonCreator
@SuppressWarnings("unused")
public static SchemaRef withInline(final Schema.Descriptor<?, ?> inline) {
return new SchemaRef(null, inline);
}
@JsonValue
public Object toJson() {
if(name != null) {
return name;
} else {
return inline;
}
}
public Schema<?> resolve(final Schema.Resolver.Constructing resolver) {
if (inline != null) {
return inline.build(null, new Schema.Resolver.Constructing() {
@Override
public void constructing(final Name qualifiedName, final Schema<?> schema) {
// no action (anonymous schema construction)
}
@Nullable
@Override
public Schema<?> getSchema(final Name qualifiedName) {
return resolver.getSchema(qualifiedName);
}
}, Version.CURRENT, Schema.anonymousQualifiedName(), Schema.anonymousSlot());
} else {
return resolver.requireSchema(name);
}
}
}
|
3e0e22da2846e4e307d0fc092450a15cc3485883 | 100,051 | java | Java | JTLV/core/edu/wis/jtlv/env/core/fds/FDSLexer.java | johnyf/jtlv | 01726a54f60344cae13a4161e36eede1cd7b9764 | [
"BSD-3-Clause"
] | null | null | null | JTLV/core/edu/wis/jtlv/env/core/fds/FDSLexer.java | johnyf/jtlv | 01726a54f60344cae13a4161e36eede1cd7b9764 | [
"BSD-3-Clause"
] | null | null | null | JTLV/core/edu/wis/jtlv/env/core/fds/FDSLexer.java | johnyf/jtlv | 01726a54f60344cae13a4161e36eede1cd7b9764 | [
"BSD-3-Clause"
] | null | null | null | 30.245163 | 353 | 0.284995 | 5,986 | // $ANTLR 3.0.1 /home/yaniv/studies/FDSFormat/FDS.g 2008-04-19 17:21:38
package edu.wis.jtlv.env.core.fds;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.EarlyExitException;
import org.antlr.runtime.Lexer;
import org.antlr.runtime.MismatchedSetException;
import org.antlr.runtime.NoViableAltException;
import org.antlr.runtime.RecognitionException;
public class FDSLexer extends Lexer {
public static final int VAR_T=6;
public static final int INIT_T=7;
public static final int BIIMP=34;
public static final int BLOCK_T=14;
public static final int FALSE=30;
public static final int TRANS=24;
public static final int INIT=23;
public static final int DOT=42;
public static final int AND=32;
public static final int JUST_DECL_T=13;
public static final int IMPLIES=33;
public static final int ASSIGN=28;
public static final int MODULE=18;
public static final int REF_T=15;
public static final int JUST=25;
public static final int LEFT_BRACES=38;
public static final int BOOL_TYPE=43;
public static final int LEFT_CURLY=20;
public static final int NEQ=36;
public static final int TRANS_DECL_T=12;
public static final int ID=19;
public static final int VAR_DECL_T=10;
public static final int RIGHT_CURLY=21;
public static final int PRIME=40;
public static final int PROG_T=4;
public static final int WS=45;
public static final int EQ=35;
public static final int BOOL_T=17;
public static final int INIT_DECL_EXPR_T=11;
public static final int MULTI_COMMENT=46;
public static final int LINE_COMMENT=47;
public static final int PRIME_T=16;
public static final int RIGHT_BRACES=39;
public static final int VAR=22;
public static final int NEXT=41;
public static final int SEMICOLON=27;
public static final int BINOR=31;
public static final int EOF=-1;
public static final int Tokens=48;
public static final int MODULE_T=5;
public static final int COLON=26;
public static final int JUST_T=9;
public static final int TRANS_T=8;
public static final int NOT=37;
public static final int TRUE=29;
public static final int COMPASSION=44;
public FDSLexer() {;}
public FDSLexer(CharStream input) {
super(input);
}
public String getGrammarFileName() { return "/home/yaniv/studies/FDSFormat/FDS.g"; }
// $ANTLR start MODULE
public final void mMODULE() throws RecognitionException {
try {
int _type = MODULE;
// /home/yaniv/studies/FDSFormat/FDS.g:167:9: ( 'MODULE' | 'Module' | 'PLAYER' | 'Player' )
int alt1=4;
int LA1_0 = input.LA(1);
if ( (LA1_0=='M') ) {
int LA1_1 = input.LA(2);
if ( (LA1_1=='O') ) {
alt1=1;
}
else if ( (LA1_1=='o') ) {
alt1=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("167:1: MODULE : ( 'MODULE' | 'Module' | 'PLAYER' | 'Player' );", 1, 1, input);
throw nvae;
}
}
else if ( (LA1_0=='P') ) {
int LA1_2 = input.LA(2);
if ( (LA1_2=='L') ) {
alt1=3;
}
else if ( (LA1_2=='l') ) {
alt1=4;
}
else {
NoViableAltException nvae =
new NoViableAltException("167:1: MODULE : ( 'MODULE' | 'Module' | 'PLAYER' | 'Player' );", 1, 2, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("167:1: MODULE : ( 'MODULE' | 'Module' | 'PLAYER' | 'Player' );", 1, 0, input);
throw nvae;
}
switch (alt1) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:167:11: 'MODULE'
{
match("MODULE");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:167:22: 'Module'
{
match("Module");
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:167:33: 'PLAYER'
{
match("PLAYER");
}
break;
case 4 :
// /home/yaniv/studies/FDSFormat/FDS.g:167:44: 'Player'
{
match("Player");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end MODULE
// $ANTLR start VAR
public final void mVAR() throws RecognitionException {
try {
int _type = VAR;
// /home/yaniv/studies/FDSFormat/FDS.g:168:6: ( 'VAR' | 'Var' )
int alt2=2;
int LA2_0 = input.LA(1);
if ( (LA2_0=='V') ) {
int LA2_1 = input.LA(2);
if ( (LA2_1=='A') ) {
alt2=1;
}
else if ( (LA2_1=='a') ) {
alt2=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("168:1: VAR : ( 'VAR' | 'Var' );", 2, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("168:1: VAR : ( 'VAR' | 'Var' );", 2, 0, input);
throw nvae;
}
switch (alt2) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:168:8: 'VAR'
{
match("VAR");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:168:16: 'Var'
{
match("Var");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end VAR
// $ANTLR start INIT
public final void mINIT() throws RecognitionException {
try {
int _type = INIT;
// /home/yaniv/studies/FDSFormat/FDS.g:169:7: ( 'INIT' | 'Init' )
int alt3=2;
int LA3_0 = input.LA(1);
if ( (LA3_0=='I') ) {
int LA3_1 = input.LA(2);
if ( (LA3_1=='N') ) {
alt3=1;
}
else if ( (LA3_1=='n') ) {
alt3=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("169:1: INIT : ( 'INIT' | 'Init' );", 3, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("169:1: INIT : ( 'INIT' | 'Init' );", 3, 0, input);
throw nvae;
}
switch (alt3) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:169:9: 'INIT'
{
match("INIT");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:169:18: 'Init'
{
match("Init");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end INIT
// $ANTLR start TRANS
public final void mTRANS() throws RecognitionException {
try {
int _type = TRANS;
// /home/yaniv/studies/FDSFormat/FDS.g:170:8: ( 'TRANS' | 'Trans' )
int alt4=2;
int LA4_0 = input.LA(1);
if ( (LA4_0=='T') ) {
int LA4_1 = input.LA(2);
if ( (LA4_1=='r') ) {
alt4=2;
}
else if ( (LA4_1=='R') ) {
alt4=1;
}
else {
NoViableAltException nvae =
new NoViableAltException("170:1: TRANS : ( 'TRANS' | 'Trans' );", 4, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("170:1: TRANS : ( 'TRANS' | 'Trans' );", 4, 0, input);
throw nvae;
}
switch (alt4) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:170:10: 'TRANS'
{
match("TRANS");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:170:20: 'Trans'
{
match("Trans");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end TRANS
// $ANTLR start JUST
public final void mJUST() throws RecognitionException {
try {
int _type = JUST;
// /home/yaniv/studies/FDSFormat/FDS.g:171:7: ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' )
int alt5=4;
int LA5_0 = input.LA(1);
if ( (LA5_0=='J') ) {
int LA5_1 = input.LA(2);
if ( (LA5_1=='u') ) {
int LA5_2 = input.LA(3);
if ( (LA5_2=='s') ) {
int LA5_4 = input.LA(4);
if ( (LA5_4=='t') ) {
int LA5_6 = input.LA(5);
if ( (LA5_6=='i') ) {
alt5=4;
}
else {
alt5=2;}
}
else {
NoViableAltException nvae =
new NoViableAltException("171:1: JUST : ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' );", 5, 4, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("171:1: JUST : ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' );", 5, 2, input);
throw nvae;
}
}
else if ( (LA5_1=='U') ) {
int LA5_3 = input.LA(3);
if ( (LA5_3=='S') ) {
int LA5_5 = input.LA(4);
if ( (LA5_5=='T') ) {
int LA5_7 = input.LA(5);
if ( (LA5_7=='I') ) {
alt5=3;
}
else {
alt5=1;}
}
else {
NoViableAltException nvae =
new NoViableAltException("171:1: JUST : ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' );", 5, 5, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("171:1: JUST : ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' );", 5, 3, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("171:1: JUST : ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' );", 5, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("171:1: JUST : ( 'JUST' | 'Just' | 'JUSTICE' | 'Justice' );", 5, 0, input);
throw nvae;
}
switch (alt5) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:171:9: 'JUST'
{
match("JUST");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:171:18: 'Just'
{
match("Just");
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:171:27: 'JUSTICE'
{
match("JUSTICE");
}
break;
case 4 :
// /home/yaniv/studies/FDSFormat/FDS.g:171:39: 'Justice'
{
match("Justice");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end JUST
// $ANTLR start COMPASSION
public final void mCOMPASSION() throws RecognitionException {
try {
int _type = COMPASSION;
// /home/yaniv/studies/FDSFormat/FDS.g:172:13: ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' )
int alt6=4;
int LA6_0 = input.LA(1);
if ( (LA6_0=='C') ) {
int LA6_1 = input.LA(2);
if ( (LA6_1=='O') ) {
int LA6_2 = input.LA(3);
if ( (LA6_2=='M') ) {
int LA6_4 = input.LA(4);
if ( (LA6_4=='P') ) {
int LA6_6 = input.LA(5);
if ( (LA6_6=='A') ) {
alt6=3;
}
else {
alt6=1;}
}
else {
NoViableAltException nvae =
new NoViableAltException("172:1: COMPASSION : ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' );", 6, 4, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("172:1: COMPASSION : ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' );", 6, 2, input);
throw nvae;
}
}
else if ( (LA6_1=='o') ) {
int LA6_3 = input.LA(3);
if ( (LA6_3=='m') ) {
int LA6_5 = input.LA(4);
if ( (LA6_5=='p') ) {
int LA6_7 = input.LA(5);
if ( (LA6_7=='a') ) {
alt6=4;
}
else {
alt6=2;}
}
else {
NoViableAltException nvae =
new NoViableAltException("172:1: COMPASSION : ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' );", 6, 5, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("172:1: COMPASSION : ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' );", 6, 3, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("172:1: COMPASSION : ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' );", 6, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("172:1: COMPASSION : ( 'COMP' | 'Comp' | 'COMPASSION' | 'Compassion' );", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:172:15: 'COMP'
{
match("COMP");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:172:24: 'Comp'
{
match("Comp");
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:172:33: 'COMPASSION'
{
match("COMPASSION");
}
break;
case 4 :
// /home/yaniv/studies/FDSFormat/FDS.g:172:48: 'Compassion'
{
match("Compassion");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end COMPASSION
// $ANTLR start NEXT
public final void mNEXT() throws RecognitionException {
try {
int _type = NEXT;
// /home/yaniv/studies/FDSFormat/FDS.g:173:7: ( 'next' )
// /home/yaniv/studies/FDSFormat/FDS.g:173:9: 'next'
{
match("next");
}
this.type = _type;
}
finally {
}
}
// $ANTLR end NEXT
// $ANTLR start PRIME
public final void mPRIME() throws RecognitionException {
try {
int _type = PRIME;
// /home/yaniv/studies/FDSFormat/FDS.g:174:8: ( '\\'' )
// /home/yaniv/studies/FDSFormat/FDS.g:174:10: '\\''
{
match('\'');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end PRIME
// $ANTLR start LEFT_BRACES
public final void mLEFT_BRACES() throws RecognitionException {
try {
int _type = LEFT_BRACES;
// /home/yaniv/studies/FDSFormat/FDS.g:175:14: ( '(' )
// /home/yaniv/studies/FDSFormat/FDS.g:175:16: '('
{
match('(');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end LEFT_BRACES
// $ANTLR start LEFT_CURLY
public final void mLEFT_CURLY() throws RecognitionException {
try {
int _type = LEFT_CURLY;
// /home/yaniv/studies/FDSFormat/FDS.g:176:13: ( '{' )
// /home/yaniv/studies/FDSFormat/FDS.g:176:15: '{'
{
match('{');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end LEFT_CURLY
// $ANTLR start RIGHT_CURLY
public final void mRIGHT_CURLY() throws RecognitionException {
try {
int _type = RIGHT_CURLY;
// /home/yaniv/studies/FDSFormat/FDS.g:177:14: ( '}' )
// /home/yaniv/studies/FDSFormat/FDS.g:177:16: '}'
{
match('}');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end RIGHT_CURLY
// $ANTLR start RIGHT_BRACES
public final void mRIGHT_BRACES() throws RecognitionException {
try {
int _type = RIGHT_BRACES;
// /home/yaniv/studies/FDSFormat/FDS.g:178:14: ( ')' )
// /home/yaniv/studies/FDSFormat/FDS.g:178:16: ')'
{
match(')');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end RIGHT_BRACES
// $ANTLR start SEMICOLON
public final void mSEMICOLON() throws RecognitionException {
try {
int _type = SEMICOLON;
// /home/yaniv/studies/FDSFormat/FDS.g:179:12: ( ';' )
// /home/yaniv/studies/FDSFormat/FDS.g:179:14: ';'
{
match(';');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end SEMICOLON
// $ANTLR start COLON
public final void mCOLON() throws RecognitionException {
try {
int _type = COLON;
// /home/yaniv/studies/FDSFormat/FDS.g:180:8: ( ':' )
// /home/yaniv/studies/FDSFormat/FDS.g:180:10: ':'
{
match(':');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end COLON
// $ANTLR start ASSIGN
public final void mASSIGN() throws RecognitionException {
try {
int _type = ASSIGN;
// /home/yaniv/studies/FDSFormat/FDS.g:181:9: ( ':=' )
// /home/yaniv/studies/FDSFormat/FDS.g:181:11: ':='
{
match(":=");
}
this.type = _type;
}
finally {
}
}
// $ANTLR end ASSIGN
// $ANTLR start DOT
public final void mDOT() throws RecognitionException {
try {
int _type = DOT;
// /home/yaniv/studies/FDSFormat/FDS.g:182:6: ( '.' )
// /home/yaniv/studies/FDSFormat/FDS.g:182:8: '.'
{
match('.');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end DOT
// $ANTLR start AND
public final void mAND() throws RecognitionException {
try {
int _type = AND;
// /home/yaniv/studies/FDSFormat/FDS.g:185:6: ( '/\\\\' | '&' | 'and' )
int alt7=3;
switch ( input.LA(1) ) {
case '/':
{
alt7=1;
}
break;
case '&':
{
alt7=2;
}
break;
case 'a':
{
alt7=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("185:1: AND : ( '/\\\\' | '&' | 'and' );", 7, 0, input);
throw nvae;
}
switch (alt7) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:185:8: '/\\\\'
{
match("/\\");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:185:16: '&'
{
match('&');
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:185:22: 'and'
{
match("and");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end AND
// $ANTLR start BINOR
public final void mBINOR() throws RecognitionException {
try {
int _type = BINOR;
// /home/yaniv/studies/FDSFormat/FDS.g:186:8: ( '\\\\/' | '|' | 'or' )
int alt8=3;
switch ( input.LA(1) ) {
case '\\':
{
alt8=1;
}
break;
case '|':
{
alt8=2;
}
break;
case 'o':
{
alt8=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("186:1: BINOR : ( '\\\\/' | '|' | 'or' );", 8, 0, input);
throw nvae;
}
switch (alt8) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:186:10: '\\\\/'
{
match("\\/");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:186:18: '|'
{
match('|');
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:186:24: 'or'
{
match("or");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end BINOR
// $ANTLR start IMPLIES
public final void mIMPLIES() throws RecognitionException {
try {
int _type = IMPLIES;
// /home/yaniv/studies/FDSFormat/FDS.g:187:10: ( '->' )
// /home/yaniv/studies/FDSFormat/FDS.g:187:13: '->'
{
match("->");
}
this.type = _type;
}
finally {
}
}
// $ANTLR end IMPLIES
// $ANTLR start BIIMP
public final void mBIIMP() throws RecognitionException {
try {
int _type = BIIMP;
// /home/yaniv/studies/FDSFormat/FDS.g:188:8: ( '<->' )
// /home/yaniv/studies/FDSFormat/FDS.g:188:10: '<->'
{
match("<->");
}
this.type = _type;
}
finally {
}
}
// $ANTLR end BIIMP
// $ANTLR start EQ
public final void mEQ() throws RecognitionException {
try {
int _type = EQ;
// /home/yaniv/studies/FDSFormat/FDS.g:189:5: ( '==' )
// /home/yaniv/studies/FDSFormat/FDS.g:189:7: '=='
{
match("==");
}
this.type = _type;
}
finally {
}
}
// $ANTLR end EQ
// $ANTLR start NEQ
public final void mNEQ() throws RecognitionException {
try {
int _type = NEQ;
// /home/yaniv/studies/FDSFormat/FDS.g:190:6: ( '!=' )
// /home/yaniv/studies/FDSFormat/FDS.g:190:8: '!='
{
match("!=");
}
this.type = _type;
}
finally {
}
}
// $ANTLR end NEQ
// $ANTLR start NOT
public final void mNOT() throws RecognitionException {
try {
int _type = NOT;
// /home/yaniv/studies/FDSFormat/FDS.g:191:6: ( '!' )
// /home/yaniv/studies/FDSFormat/FDS.g:191:8: '!'
{
match('!');
}
this.type = _type;
}
finally {
}
}
// $ANTLR end NOT
// $ANTLR start BOOL_TYPE
public final void mBOOL_TYPE() throws RecognitionException {
try {
int _type = BOOL_TYPE;
// /home/yaniv/studies/FDSFormat/FDS.g:194:12: ( 'bool' | 'boolean' )
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='b') ) {
int LA9_1 = input.LA(2);
if ( (LA9_1=='o') ) {
int LA9_2 = input.LA(3);
if ( (LA9_2=='o') ) {
int LA9_3 = input.LA(4);
if ( (LA9_3=='l') ) {
int LA9_4 = input.LA(5);
if ( (LA9_4=='e') ) {
alt9=2;
}
else {
alt9=1;}
}
else {
NoViableAltException nvae =
new NoViableAltException("194:1: BOOL_TYPE : ( 'bool' | 'boolean' );", 9, 3, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("194:1: BOOL_TYPE : ( 'bool' | 'boolean' );", 9, 2, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("194:1: BOOL_TYPE : ( 'bool' | 'boolean' );", 9, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("194:1: BOOL_TYPE : ( 'bool' | 'boolean' );", 9, 0, input);
throw nvae;
}
switch (alt9) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:194:14: 'bool'
{
match("bool");
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:194:23: 'boolean'
{
match("boolean");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end BOOL_TYPE
// $ANTLR start TRUE
public final void mTRUE() throws RecognitionException {
try {
int _type = TRUE;
// /home/yaniv/studies/FDSFormat/FDS.g:195:7: ( 'T' | 'TRUE' )
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0=='T') ) {
int LA10_1 = input.LA(2);
if ( (LA10_1=='R') ) {
alt10=2;
}
else {
alt10=1;}
}
else {
NoViableAltException nvae =
new NoViableAltException("195:1: TRUE : ( 'T' | 'TRUE' );", 10, 0, input);
throw nvae;
}
switch (alt10) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:195:9: 'T'
{
match('T');
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:195:15: 'TRUE'
{
match("TRUE");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end TRUE
// $ANTLR start FALSE
public final void mFALSE() throws RecognitionException {
try {
int _type = FALSE;
// /home/yaniv/studies/FDSFormat/FDS.g:196:8: ( 'F' | 'FALSE' )
int alt11=2;
int LA11_0 = input.LA(1);
if ( (LA11_0=='F') ) {
int LA11_1 = input.LA(2);
if ( (LA11_1=='A') ) {
alt11=2;
}
else {
alt11=1;}
}
else {
NoViableAltException nvae =
new NoViableAltException("196:1: FALSE : ( 'F' | 'FALSE' );", 11, 0, input);
throw nvae;
}
switch (alt11) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:196:10: 'F'
{
match('F');
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:196:16: 'FALSE'
{
match("FALSE");
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end FALSE
// $ANTLR start ID
public final void mID() throws RecognitionException {
try {
int _type = ID;
// /home/yaniv/studies/FDSFormat/FDS.g:200:5: ( ( ( 'a' .. 'z' ) | ( 'A' .. 'Z' ) | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* )
// /home/yaniv/studies/FDSFormat/FDS.g:200:7: ( ( 'a' .. 'z' ) | ( 'A' .. 'Z' ) | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )*
{
// /home/yaniv/studies/FDSFormat/FDS.g:200:7: ( ( 'a' .. 'z' ) | ( 'A' .. 'Z' ) | '_' )
int alt12=3;
switch ( input.LA(1) ) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt12=1;
}
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
{
alt12=2;
}
break;
case '_':
{
alt12=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("200:7: ( ( 'a' .. 'z' ) | ( 'A' .. 'Z' ) | '_' )", 12, 0, input);
throw nvae;
}
switch (alt12) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:200:8: ( 'a' .. 'z' )
{
// /home/yaniv/studies/FDSFormat/FDS.g:200:8: ( 'a' .. 'z' )
// /home/yaniv/studies/FDSFormat/FDS.g:200:9: 'a' .. 'z'
{
matchRange('a','z');
}
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:200:21: ( 'A' .. 'Z' )
{
// /home/yaniv/studies/FDSFormat/FDS.g:200:21: ( 'A' .. 'Z' )
// /home/yaniv/studies/FDSFormat/FDS.g:200:22: 'A' .. 'Z'
{
matchRange('A','Z');
}
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:200:34: '_'
{
match('_');
}
break;
}
// /home/yaniv/studies/FDSFormat/FDS.g:200:39: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )*
loop13:
do {
int alt13=2;
int LA13_0 = input.LA(1);
if ( ((LA13_0>='0' && LA13_0<='9')||(LA13_0>='A' && LA13_0<='Z')||LA13_0=='_'||(LA13_0>='a' && LA13_0<='z')) ) {
alt13=1;
}
switch (alt13) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:
{
if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
break loop13;
}
} while (true);
}
this.type = _type;
}
finally {
}
}
// $ANTLR end ID
// $ANTLR start WS
public final void mWS() throws RecognitionException {
try {
int _type = WS;
// /home/yaniv/studies/FDSFormat/FDS.g:201:6: ( ( ' ' | '\\t' | '\\r' | '\\n' )+ )
// /home/yaniv/studies/FDSFormat/FDS.g:201:10: ( ' ' | '\\t' | '\\r' | '\\n' )+
{
// /home/yaniv/studies/FDSFormat/FDS.g:201:10: ( ' ' | '\\t' | '\\r' | '\\n' )+
int cnt14=0;
loop14:
do {
int alt14=2;
int LA14_0 = input.LA(1);
if ( ((LA14_0>='\t' && LA14_0<='\n')||LA14_0=='\r'||LA14_0==' ') ) {
alt14=1;
}
switch (alt14) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:
{
if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
if ( cnt14 >= 1 ) break loop14;
EarlyExitException eee =
new EarlyExitException(14, input);
throw eee;
}
cnt14++;
} while (true);
channel=HIDDEN;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end WS
// $ANTLR start MULTI_COMMENT
public final void mMULTI_COMMENT() throws RecognitionException {
try {
int _type = MULTI_COMMENT;
// /home/yaniv/studies/FDSFormat/FDS.g:207:15: ( ( '/*' ( options {greedy=false; } : '\\r' | '\\n' | ~ ( '\\n' | '\\r' ) )* '*/' ) )
// /home/yaniv/studies/FDSFormat/FDS.g:207:17: ( '/*' ( options {greedy=false; } : '\\r' | '\\n' | ~ ( '\\n' | '\\r' ) )* '*/' )
{
// /home/yaniv/studies/FDSFormat/FDS.g:207:17: ( '/*' ( options {greedy=false; } : '\\r' | '\\n' | ~ ( '\\n' | '\\r' ) )* '*/' )
// /home/yaniv/studies/FDSFormat/FDS.g:207:18: '/*' ( options {greedy=false; } : '\\r' | '\\n' | ~ ( '\\n' | '\\r' ) )* '*/'
{
match("/*");
// /home/yaniv/studies/FDSFormat/FDS.g:207:23: ( options {greedy=false; } : '\\r' | '\\n' | ~ ( '\\n' | '\\r' ) )*
loop15:
do {
int alt15=4;
int LA15_0 = input.LA(1);
if ( (LA15_0=='*') ) {
int LA15_1 = input.LA(2);
if ( (LA15_1=='/') ) {
alt15=4;
}
else if ( ((LA15_1>='\u0000' && LA15_1<='.')||(LA15_1>='0' && LA15_1<='\uFFFE')) ) {
alt15=3;
}
}
else if ( (LA15_0=='\r') ) {
alt15=1;
}
else if ( (LA15_0=='\n') ) {
alt15=2;
}
else if ( ((LA15_0>='\u0000' && LA15_0<='\t')||(LA15_0>='\u000B' && LA15_0<='\f')||(LA15_0>='\u000E' && LA15_0<=')')||(LA15_0>='+' && LA15_0<='\uFFFE')) ) {
alt15=3;
}
switch (alt15) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:210:3: '\\r'
{
match('\r');
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:211:7: '\\n'
{
match('\n');
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:212:7: ~ ( '\\n' | '\\r' )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFE') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
break loop15;
}
} while (true);
match("*/");
channel=HIDDEN;
}
}
this.type = _type;
}
finally {
}
}
// $ANTLR end MULTI_COMMENT
// $ANTLR start LINE_COMMENT
public final void mLINE_COMMENT() throws RecognitionException {
try {
int _type = LINE_COMMENT;
// /home/yaniv/studies/FDSFormat/FDS.g:216:14: ( ( '--' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? ) | ( '//' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? ) )
int alt24=2;
int LA24_0 = input.LA(1);
if ( (LA24_0=='-') ) {
alt24=1;
}
else if ( (LA24_0=='/') ) {
alt24=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("216:1: LINE_COMMENT : ( ( '--' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? ) | ( '//' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? ) );", 24, 0, input);
throw nvae;
}
switch (alt24) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:216:16: ( '--' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? )
{
// /home/yaniv/studies/FDSFormat/FDS.g:216:16: ( '--' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? )
// /home/yaniv/studies/FDSFormat/FDS.g:216:17: '--' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )?
{
match("--");
// /home/yaniv/studies/FDSFormat/FDS.g:216:22: (~ ( '\\n' | '\\r' ) )*
loop16:
do {
int alt16=2;
int LA16_0 = input.LA(1);
if ( ((LA16_0>='\u0000' && LA16_0<='\t')||(LA16_0>='\u000B' && LA16_0<='\f')||(LA16_0>='\u000E' && LA16_0<='\uFFFE')) ) {
alt16=1;
}
switch (alt16) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:216:23: ~ ( '\\n' | '\\r' )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFE') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
break loop16;
}
} while (true);
// /home/yaniv/studies/FDSFormat/FDS.g:216:38: ( ( '\\n' | '\\r' ( '\\n' )? ) )?
int alt19=2;
int LA19_0 = input.LA(1);
if ( (LA19_0=='\n'||LA19_0=='\r') ) {
alt19=1;
}
switch (alt19) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:216:39: ( '\\n' | '\\r' ( '\\n' )? )
{
// /home/yaniv/studies/FDSFormat/FDS.g:216:39: ( '\\n' | '\\r' ( '\\n' )? )
int alt18=2;
int LA18_0 = input.LA(1);
if ( (LA18_0=='\n') ) {
alt18=1;
}
else if ( (LA18_0=='\r') ) {
alt18=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("216:39: ( '\\n' | '\\r' ( '\\n' )? )", 18, 0, input);
throw nvae;
}
switch (alt18) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:216:40: '\\n'
{
match('\n');
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:216:45: '\\r' ( '\\n' )?
{
match('\r');
// /home/yaniv/studies/FDSFormat/FDS.g:216:49: ( '\\n' )?
int alt17=2;
int LA17_0 = input.LA(1);
if ( (LA17_0=='\n') ) {
alt17=1;
}
switch (alt17) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:216:50: '\\n'
{
match('\n');
}
break;
}
}
break;
}
}
break;
}
channel=HIDDEN;
}
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:218:3: ( '//' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? )
{
// /home/yaniv/studies/FDSFormat/FDS.g:218:3: ( '//' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )? )
// /home/yaniv/studies/FDSFormat/FDS.g:218:4: '//' (~ ( '\\n' | '\\r' ) )* ( ( '\\n' | '\\r' ( '\\n' )? ) )?
{
match("//");
// /home/yaniv/studies/FDSFormat/FDS.g:218:9: (~ ( '\\n' | '\\r' ) )*
loop20:
do {
int alt20=2;
int LA20_0 = input.LA(1);
if ( ((LA20_0>='\u0000' && LA20_0<='\t')||(LA20_0>='\u000B' && LA20_0<='\f')||(LA20_0>='\u000E' && LA20_0<='\uFFFE')) ) {
alt20=1;
}
switch (alt20) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:218:10: ~ ( '\\n' | '\\r' )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFE') ) {
input.consume();
}
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
recover(mse); throw mse;
}
}
break;
default :
break loop20;
}
} while (true);
// /home/yaniv/studies/FDSFormat/FDS.g:218:25: ( ( '\\n' | '\\r' ( '\\n' )? ) )?
int alt23=2;
int LA23_0 = input.LA(1);
if ( (LA23_0=='\n'||LA23_0=='\r') ) {
alt23=1;
}
switch (alt23) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:218:26: ( '\\n' | '\\r' ( '\\n' )? )
{
// /home/yaniv/studies/FDSFormat/FDS.g:218:26: ( '\\n' | '\\r' ( '\\n' )? )
int alt22=2;
int LA22_0 = input.LA(1);
if ( (LA22_0=='\n') ) {
alt22=1;
}
else if ( (LA22_0=='\r') ) {
alt22=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("218:26: ( '\\n' | '\\r' ( '\\n' )? )", 22, 0, input);
throw nvae;
}
switch (alt22) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:218:27: '\\n'
{
match('\n');
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:218:32: '\\r' ( '\\n' )?
{
match('\r');
// /home/yaniv/studies/FDSFormat/FDS.g:218:36: ( '\\n' )?
int alt21=2;
int LA21_0 = input.LA(1);
if ( (LA21_0=='\n') ) {
alt21=1;
}
switch (alt21) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:218:37: '\\n'
{
match('\n');
}
break;
}
}
break;
}
}
break;
}
channel=HIDDEN;
}
}
break;
}
this.type = _type;
}
finally {
}
}
// $ANTLR end LINE_COMMENT
public void mTokens() throws RecognitionException {
// /home/yaniv/studies/FDSFormat/FDS.g:1:8: ( MODULE | VAR | INIT | TRANS | JUST | COMPASSION | NEXT | PRIME | LEFT_BRACES | LEFT_CURLY | RIGHT_CURLY | RIGHT_BRACES | SEMICOLON | COLON | ASSIGN | DOT | AND | BINOR | IMPLIES | BIIMP | EQ | NEQ | NOT | BOOL_TYPE | TRUE | FALSE | ID | WS | MULTI_COMMENT | LINE_COMMENT )
int alt25=30;
switch ( input.LA(1) ) {
case 'M':
{
switch ( input.LA(2) ) {
case 'o':
{
int LA25_30 = input.LA(3);
if ( (LA25_30=='d') ) {
int LA25_58 = input.LA(4);
if ( (LA25_58=='u') ) {
int LA25_77 = input.LA(5);
if ( (LA25_77=='l') ) {
int LA25_94 = input.LA(6);
if ( (LA25_94=='e') ) {
int LA25_111 = input.LA(7);
if ( ((LA25_111>='0' && LA25_111<='9')||(LA25_111>='A' && LA25_111<='Z')||LA25_111=='_'||(LA25_111>='a' && LA25_111<='z')) ) {
alt25=27;
}
else {
alt25=1;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case 'O':
{
int LA25_31 = input.LA(3);
if ( (LA25_31=='D') ) {
int LA25_59 = input.LA(4);
if ( (LA25_59=='U') ) {
int LA25_78 = input.LA(5);
if ( (LA25_78=='L') ) {
int LA25_95 = input.LA(6);
if ( (LA25_95=='E') ) {
int LA25_112 = input.LA(7);
if ( ((LA25_112>='0' && LA25_112<='9')||(LA25_112>='A' && LA25_112<='Z')||LA25_112=='_'||(LA25_112>='a' && LA25_112<='z')) ) {
alt25=27;
}
else {
alt25=1;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'P':
{
switch ( input.LA(2) ) {
case 'L':
{
int LA25_32 = input.LA(3);
if ( (LA25_32=='A') ) {
int LA25_60 = input.LA(4);
if ( (LA25_60=='Y') ) {
int LA25_79 = input.LA(5);
if ( (LA25_79=='E') ) {
int LA25_96 = input.LA(6);
if ( (LA25_96=='R') ) {
int LA25_113 = input.LA(7);
if ( ((LA25_113>='0' && LA25_113<='9')||(LA25_113>='A' && LA25_113<='Z')||LA25_113=='_'||(LA25_113>='a' && LA25_113<='z')) ) {
alt25=27;
}
else {
alt25=1;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case 'l':
{
int LA25_33 = input.LA(3);
if ( (LA25_33=='a') ) {
int LA25_61 = input.LA(4);
if ( (LA25_61=='y') ) {
int LA25_80 = input.LA(5);
if ( (LA25_80=='e') ) {
int LA25_97 = input.LA(6);
if ( (LA25_97=='r') ) {
int LA25_114 = input.LA(7);
if ( ((LA25_114>='0' && LA25_114<='9')||(LA25_114>='A' && LA25_114<='Z')||LA25_114=='_'||(LA25_114>='a' && LA25_114<='z')) ) {
alt25=27;
}
else {
alt25=1;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'V':
{
switch ( input.LA(2) ) {
case 'a':
{
int LA25_34 = input.LA(3);
if ( (LA25_34=='r') ) {
int LA25_62 = input.LA(4);
if ( ((LA25_62>='0' && LA25_62<='9')||(LA25_62>='A' && LA25_62<='Z')||LA25_62=='_'||(LA25_62>='a' && LA25_62<='z')) ) {
alt25=27;
}
else {
alt25=2;}
}
else {
alt25=27;}
}
break;
case 'A':
{
int LA25_35 = input.LA(3);
if ( (LA25_35=='R') ) {
int LA25_63 = input.LA(4);
if ( ((LA25_63>='0' && LA25_63<='9')||(LA25_63>='A' && LA25_63<='Z')||LA25_63=='_'||(LA25_63>='a' && LA25_63<='z')) ) {
alt25=27;
}
else {
alt25=2;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'I':
{
switch ( input.LA(2) ) {
case 'n':
{
int LA25_36 = input.LA(3);
if ( (LA25_36=='i') ) {
int LA25_64 = input.LA(4);
if ( (LA25_64=='t') ) {
int LA25_82 = input.LA(5);
if ( ((LA25_82>='0' && LA25_82<='9')||(LA25_82>='A' && LA25_82<='Z')||LA25_82=='_'||(LA25_82>='a' && LA25_82<='z')) ) {
alt25=27;
}
else {
alt25=3;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case 'N':
{
int LA25_37 = input.LA(3);
if ( (LA25_37=='I') ) {
int LA25_65 = input.LA(4);
if ( (LA25_65=='T') ) {
int LA25_83 = input.LA(5);
if ( ((LA25_83>='0' && LA25_83<='9')||(LA25_83>='A' && LA25_83<='Z')||LA25_83=='_'||(LA25_83>='a' && LA25_83<='z')) ) {
alt25=27;
}
else {
alt25=3;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'T':
{
switch ( input.LA(2) ) {
case 'R':
{
switch ( input.LA(3) ) {
case 'U':
{
int LA25_66 = input.LA(4);
if ( (LA25_66=='E') ) {
int LA25_84 = input.LA(5);
if ( ((LA25_84>='0' && LA25_84<='9')||(LA25_84>='A' && LA25_84<='Z')||LA25_84=='_'||(LA25_84>='a' && LA25_84<='z')) ) {
alt25=27;
}
else {
alt25=25;}
}
else {
alt25=27;}
}
break;
case 'A':
{
int LA25_67 = input.LA(4);
if ( (LA25_67=='N') ) {
int LA25_85 = input.LA(5);
if ( (LA25_85=='S') ) {
int LA25_99 = input.LA(6);
if ( ((LA25_99>='0' && LA25_99<='9')||(LA25_99>='A' && LA25_99<='Z')||LA25_99=='_'||(LA25_99>='a' && LA25_99<='z')) ) {
alt25=27;
}
else {
alt25=4;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'r':
{
int LA25_39 = input.LA(3);
if ( (LA25_39=='a') ) {
int LA25_68 = input.LA(4);
if ( (LA25_68=='n') ) {
int LA25_86 = input.LA(5);
if ( (LA25_86=='s') ) {
int LA25_100 = input.LA(6);
if ( ((LA25_100>='0' && LA25_100<='9')||(LA25_100>='A' && LA25_100<='Z')||LA25_100=='_'||(LA25_100>='a' && LA25_100<='z')) ) {
alt25=27;
}
else {
alt25=4;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=25;}
}
break;
case 'J':
{
switch ( input.LA(2) ) {
case 'u':
{
int LA25_41 = input.LA(3);
if ( (LA25_41=='s') ) {
int LA25_69 = input.LA(4);
if ( (LA25_69=='t') ) {
switch ( input.LA(5) ) {
case 'i':
{
int LA25_101 = input.LA(6);
if ( (LA25_101=='c') ) {
int LA25_116 = input.LA(7);
if ( (LA25_116=='e') ) {
int LA25_122 = input.LA(8);
if ( ((LA25_122>='0' && LA25_122<='9')||(LA25_122>='A' && LA25_122<='Z')||LA25_122=='_'||(LA25_122>='a' && LA25_122<='z')) ) {
alt25=27;
}
else {
alt25=5;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=5;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case 'U':
{
int LA25_42 = input.LA(3);
if ( (LA25_42=='S') ) {
int LA25_70 = input.LA(4);
if ( (LA25_70=='T') ) {
switch ( input.LA(5) ) {
case 'I':
{
int LA25_103 = input.LA(6);
if ( (LA25_103=='C') ) {
int LA25_117 = input.LA(7);
if ( (LA25_117=='E') ) {
int LA25_123 = input.LA(8);
if ( ((LA25_123>='0' && LA25_123<='9')||(LA25_123>='A' && LA25_123<='Z')||LA25_123=='_'||(LA25_123>='a' && LA25_123<='z')) ) {
alt25=27;
}
else {
alt25=5;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=5;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'C':
{
switch ( input.LA(2) ) {
case 'o':
{
int LA25_43 = input.LA(3);
if ( (LA25_43=='m') ) {
int LA25_71 = input.LA(4);
if ( (LA25_71=='p') ) {
switch ( input.LA(5) ) {
case 'a':
{
int LA25_104 = input.LA(6);
if ( (LA25_104=='s') ) {
int LA25_118 = input.LA(7);
if ( (LA25_118=='s') ) {
int LA25_124 = input.LA(8);
if ( (LA25_124=='i') ) {
int LA25_127 = input.LA(9);
if ( (LA25_127=='o') ) {
int LA25_129 = input.LA(10);
if ( (LA25_129=='n') ) {
int LA25_131 = input.LA(11);
if ( ((LA25_131>='0' && LA25_131<='9')||(LA25_131>='A' && LA25_131<='Z')||LA25_131=='_'||(LA25_131>='a' && LA25_131<='z')) ) {
alt25=27;
}
else {
alt25=6;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=6;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case 'O':
{
int LA25_44 = input.LA(3);
if ( (LA25_44=='M') ) {
int LA25_72 = input.LA(4);
if ( (LA25_72=='P') ) {
switch ( input.LA(5) ) {
case 'A':
{
int LA25_106 = input.LA(6);
if ( (LA25_106=='S') ) {
int LA25_119 = input.LA(7);
if ( (LA25_119=='S') ) {
int LA25_125 = input.LA(8);
if ( (LA25_125=='I') ) {
int LA25_128 = input.LA(9);
if ( (LA25_128=='O') ) {
int LA25_130 = input.LA(10);
if ( (LA25_130=='N') ) {
int LA25_132 = input.LA(11);
if ( ((LA25_132>='0' && LA25_132<='9')||(LA25_132>='A' && LA25_132<='Z')||LA25_132=='_'||(LA25_132>='a' && LA25_132<='z')) ) {
alt25=27;
}
else {
alt25=6;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=6;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
default:
alt25=27;}
}
break;
case 'n':
{
int LA25_8 = input.LA(2);
if ( (LA25_8=='e') ) {
int LA25_45 = input.LA(3);
if ( (LA25_45=='x') ) {
int LA25_73 = input.LA(4);
if ( (LA25_73=='t') ) {
int LA25_91 = input.LA(5);
if ( ((LA25_91>='0' && LA25_91<='9')||(LA25_91>='A' && LA25_91<='Z')||LA25_91=='_'||(LA25_91>='a' && LA25_91<='z')) ) {
alt25=27;
}
else {
alt25=7;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '\'':
{
alt25=8;
}
break;
case '(':
{
alt25=9;
}
break;
case '{':
{
alt25=10;
}
break;
case '}':
{
alt25=11;
}
break;
case ')':
{
alt25=12;
}
break;
case ';':
{
alt25=13;
}
break;
case ':':
{
int LA25_15 = input.LA(2);
if ( (LA25_15=='=') ) {
alt25=15;
}
else {
alt25=14;}
}
break;
case '.':
{
alt25=16;
}
break;
case '/':
{
switch ( input.LA(2) ) {
case '\\':
{
alt25=17;
}
break;
case '/':
{
alt25=30;
}
break;
case '*':
{
alt25=29;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("1:1: Tokens : ( MODULE | VAR | INIT | TRANS | JUST | COMPASSION | NEXT | PRIME | LEFT_BRACES | LEFT_CURLY | RIGHT_CURLY | RIGHT_BRACES | SEMICOLON | COLON | ASSIGN | DOT | AND | BINOR | IMPLIES | BIIMP | EQ | NEQ | NOT | BOOL_TYPE | TRUE | FALSE | ID | WS | MULTI_COMMENT | LINE_COMMENT );", 25, 17, input);
throw nvae;
}
}
break;
case '&':
{
alt25=17;
}
break;
case 'a':
{
int LA25_19 = input.LA(2);
if ( (LA25_19=='n') ) {
int LA25_50 = input.LA(3);
if ( (LA25_50=='d') ) {
int LA25_74 = input.LA(4);
if ( ((LA25_74>='0' && LA25_74<='9')||(LA25_74>='A' && LA25_74<='Z')||LA25_74=='_'||(LA25_74>='a' && LA25_74<='z')) ) {
alt25=27;
}
else {
alt25=17;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '\\':
case '|':
{
alt25=18;
}
break;
case 'o':
{
int LA25_21 = input.LA(2);
if ( (LA25_21=='r') ) {
int LA25_51 = input.LA(3);
if ( ((LA25_51>='0' && LA25_51<='9')||(LA25_51>='A' && LA25_51<='Z')||LA25_51=='_'||(LA25_51>='a' && LA25_51<='z')) ) {
alt25=27;
}
else {
alt25=18;}
}
else {
alt25=27;}
}
break;
case '-':
{
int LA25_22 = input.LA(2);
if ( (LA25_22=='>') ) {
alt25=19;
}
else if ( (LA25_22=='-') ) {
alt25=30;
}
else {
NoViableAltException nvae =
new NoViableAltException("1:1: Tokens : ( MODULE | VAR | INIT | TRANS | JUST | COMPASSION | NEXT | PRIME | LEFT_BRACES | LEFT_CURLY | RIGHT_CURLY | RIGHT_BRACES | SEMICOLON | COLON | ASSIGN | DOT | AND | BINOR | IMPLIES | BIIMP | EQ | NEQ | NOT | BOOL_TYPE | TRUE | FALSE | ID | WS | MULTI_COMMENT | LINE_COMMENT );", 25, 22, input);
throw nvae;
}
}
break;
case '<':
{
alt25=20;
}
break;
case '=':
{
alt25=21;
}
break;
case '!':
{
int LA25_25 = input.LA(2);
if ( (LA25_25=='=') ) {
alt25=22;
}
else {
alt25=23;}
}
break;
case 'b':
{
int LA25_26 = input.LA(2);
if ( (LA25_26=='o') ) {
int LA25_55 = input.LA(3);
if ( (LA25_55=='o') ) {
int LA25_75 = input.LA(4);
if ( (LA25_75=='l') ) {
switch ( input.LA(5) ) {
case 'e':
{
int LA25_108 = input.LA(6);
if ( (LA25_108=='a') ) {
int LA25_120 = input.LA(7);
if ( (LA25_120=='n') ) {
int LA25_126 = input.LA(8);
if ( ((LA25_126>='0' && LA25_126<='9')||(LA25_126>='A' && LA25_126<='Z')||LA25_126=='_'||(LA25_126>='a' && LA25_126<='z')) ) {
alt25=27;
}
else {
alt25=24;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=24;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case 'F':
{
switch ( input.LA(2) ) {
case 'A':
{
int LA25_56 = input.LA(3);
if ( (LA25_56=='L') ) {
int LA25_76 = input.LA(4);
if ( (LA25_76=='S') ) {
int LA25_93 = input.LA(5);
if ( (LA25_93=='E') ) {
int LA25_110 = input.LA(6);
if ( ((LA25_110>='0' && LA25_110<='9')||(LA25_110>='A' && LA25_110<='Z')||LA25_110=='_'||(LA25_110>='a' && LA25_110<='z')) ) {
alt25=27;
}
else {
alt25=26;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
else {
alt25=27;}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
default:
alt25=26;}
}
break;
case 'A':
case 'B':
case 'D':
case 'E':
case 'G':
case 'H':
case 'K':
case 'L':
case 'N':
case 'O':
case 'Q':
case 'R':
case 'S':
case 'U':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt25=27;
}
break;
case '\t':
case '\n':
case '\r':
case ' ':
{
alt25=28;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("1:1: Tokens : ( MODULE | VAR | INIT | TRANS | JUST | COMPASSION | NEXT | PRIME | LEFT_BRACES | LEFT_CURLY | RIGHT_CURLY | RIGHT_BRACES | SEMICOLON | COLON | ASSIGN | DOT | AND | BINOR | IMPLIES | BIIMP | EQ | NEQ | NOT | BOOL_TYPE | TRUE | FALSE | ID | WS | MULTI_COMMENT | LINE_COMMENT );", 25, 0, input);
throw nvae;
}
switch (alt25) {
case 1 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:10: MODULE
{
mMODULE();
}
break;
case 2 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:17: VAR
{
mVAR();
}
break;
case 3 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:21: INIT
{
mINIT();
}
break;
case 4 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:26: TRANS
{
mTRANS();
}
break;
case 5 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:32: JUST
{
mJUST();
}
break;
case 6 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:37: COMPASSION
{
mCOMPASSION();
}
break;
case 7 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:48: NEXT
{
mNEXT();
}
break;
case 8 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:53: PRIME
{
mPRIME();
}
break;
case 9 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:59: LEFT_BRACES
{
mLEFT_BRACES();
}
break;
case 10 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:71: LEFT_CURLY
{
mLEFT_CURLY();
}
break;
case 11 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:82: RIGHT_CURLY
{
mRIGHT_CURLY();
}
break;
case 12 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:94: RIGHT_BRACES
{
mRIGHT_BRACES();
}
break;
case 13 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:107: SEMICOLON
{
mSEMICOLON();
}
break;
case 14 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:117: COLON
{
mCOLON();
}
break;
case 15 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:123: ASSIGN
{
mASSIGN();
}
break;
case 16 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:130: DOT
{
mDOT();
}
break;
case 17 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:134: AND
{
mAND();
}
break;
case 18 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:138: BINOR
{
mBINOR();
}
break;
case 19 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:144: IMPLIES
{
mIMPLIES();
}
break;
case 20 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:152: BIIMP
{
mBIIMP();
}
break;
case 21 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:158: EQ
{
mEQ();
}
break;
case 22 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:161: NEQ
{
mNEQ();
}
break;
case 23 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:165: NOT
{
mNOT();
}
break;
case 24 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:169: BOOL_TYPE
{
mBOOL_TYPE();
}
break;
case 25 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:179: TRUE
{
mTRUE();
}
break;
case 26 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:184: FALSE
{
mFALSE();
}
break;
case 27 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:190: ID
{
mID();
}
break;
case 28 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:193: WS
{
mWS();
}
break;
case 29 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:196: MULTI_COMMENT
{
mMULTI_COMMENT();
}
break;
case 30 :
// /home/yaniv/studies/FDSFormat/FDS.g:1:210: LINE_COMMENT
{
mLINE_COMMENT();
}
break;
}
}
} |
3e0e23b435eae31906cf614b1d63f1a87f85e93a | 1,365 | java | Java | DesignPatterns/src/main/java/hj/action/DesignPatterns/Proxy/package-info.java | hjnlxuexi/action4java | dc13d0f1952873cd9cc2eeb38b08bcb0053d373c | [
"MIT"
] | 1 | 2019-04-17T14:50:09.000Z | 2019-04-17T14:50:09.000Z | DesignPatterns/src/main/java/hj/action/DesignPatterns/Proxy/package-info.java | hjnlxuexi/action4java | dc13d0f1952873cd9cc2eeb38b08bcb0053d373c | [
"MIT"
] | 1 | 2020-01-15T00:20:03.000Z | 2020-01-15T00:20:03.000Z | DesignPatterns/src/main/java/hj/action/DesignPatterns/Proxy/package-info.java | hjnlxuexi/action4java | dc13d0f1952873cd9cc2eeb38b08bcb0053d373c | [
"MIT"
] | null | null | null | 27.3 | 106 | 0.609524 | 5,987 | /**
* <p>Title : 代理模式</p>
* <p>Description :
*
* 代理模式就是给一个对象提供一个代理,并由代理对象控制对原对象的引用。
*
* Subject: 抽象角色。声明真实对象和代理对象的共同接口。
* Proxy: 代理角色。代理对象与真实对象实现相同的接口,所以它能够在任何时刻都能够代理真实对象。
* 代理角色内部包含有对真实对象的引用,所以她可以操作真实对象,同时也可以附加其他的操作,相当于对真实对象进行封装。
* RealSubject: 真实角色。它代表着真实对象,是我们最终要引用的对象
*
*
* 优点:
* 1、代理模式能够协调调用者和被调用者,在一定程度上降低了系统的耦合度。
* 2、代理对象可以在客户端和目标对象之间起到中介的作用,这样起到了保护目标对象的作用
* 缺点:
* 1、由于在客户端和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求的处理速度变慢。
* 2、实现代理模式需要额外的工作,有些代理模式的实现非常复杂。
*
*
* 适用场景:
* 1、远程代理:为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在于不同地址空间的事实。
* 2、虚拟代理:通过使用过一个小的对象代理一个大对象。这样就可以减少系统的开销。
* 3、保护代理:用来控制对真实对象的访问权限。
*
*
* ------------------------------------------------------------------------------------------------------
* 动态代理:
* java Proxy:
* java.lang.reflect.Proxy:生成动态代理类和对象;
* java.lang.reflect.InvocationHandler(处理器接口):可以通过invoke方法实现对真实角色的代理访问。
* 每次通过 Proxy 生成的代理类对象都要指定对应的处理器对象。
*
* 内部采用反射机制,动态生成基于接口的子类,并转换为二进制码。
*
* CGLIB:
* 动态生成一个要被代理类的子类,子类重写要代理的类的所有不是final的方法
* 在子类中采用方法拦截的技术拦截所有父类方法的调用,顺势织入横切逻辑。
* 使用字节码处理框架ASM,来转换字节码并生成新的类。
* 它比使用java反射的JDK动态代理要快。
* 它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。
*
*
*
* </p>
* <p>Date : 2019-02-16 </p>
*
* @author : hejie
*/
package hj.action.DesignPatterns.Proxy; |
3e0e23cca953a2e0bdf66de99c6de448a961b7ae | 588 | java | Java | src/Vector/DoubleVector.java | Cortys/TerrainLib | 0c993a44bc2e056438c2a56fed23e8b9517c0bfa | [
"MIT"
] | 3 | 2015-01-08T19:36:49.000Z | 2019-06-05T07:14:03.000Z | src/Vector/DoubleVector.java | Cortys/TerrainLib | 0c993a44bc2e056438c2a56fed23e8b9517c0bfa | [
"MIT"
] | null | null | null | src/Vector/DoubleVector.java | Cortys/TerrainLib | 0c993a44bc2e056438c2a56fed23e8b9517c0bfa | [
"MIT"
] | null | null | null | 15.891892 | 68 | 0.576531 | 5,988 | package Vector;
public class DoubleVector extends Vector<Double>
{
public DoubleVector(IntVector v)
{
super(v.getX().doubleValue(), v.getY().doubleValue());
}
public DoubleVector(double x, double y)
{
super(new Double(x), new Double(y));
}
@Override
protected Double calculate(Double v1, Double v2, String operation)
{
switch (operation)
{
case "+":
return v1 + v2;
case "-":
return v1 - v2;
case "*":
return v1 * v2;
case "/":
return v1 / v2;
case "!":
return v1 * -1;
default:
return 0.0;
}
}
}
|
3e0e23d48b3720929596ae007b43c3e1ad8e4388 | 4,686 | java | Java | src/main/java/com/gn4me/app/util/SystemLoader.java | MostafaElfeky/starter-web-app | 5c7ee0f065b9289ea58a485d8c3afd38640b520f | [
"MIT"
] | 1 | 2021-03-06T18:48:22.000Z | 2021-03-06T18:48:22.000Z | src/main/java/com/gn4me/app/util/SystemLoader.java | MagdyIYounis/starter-web-app | 5c7ee0f065b9289ea58a485d8c3afd38640b520f | [
"MIT"
] | null | null | null | src/main/java/com/gn4me/app/util/SystemLoader.java | MagdyIYounis/starter-web-app | 5c7ee0f065b9289ea58a485d8c3afd38640b520f | [
"MIT"
] | 1 | 2021-03-06T18:48:24.000Z | 2021-03-06T18:48:24.000Z | 32.541667 | 104 | 0.736449 | 5,989 | package com.gn4me.app.util;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gn4me.app.core.dao.IGeneralDao;
import com.gn4me.app.entities.Section;
import com.gn4me.app.entities.SystemConfiguration;
import com.gn4me.app.entities.SystemStatus;
import com.gn4me.app.entities.Transition;
import com.gn4me.app.log.LogHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
@EnableScheduling
public class SystemLoader implements SchedulingConfigurer{
@Autowired
IGeneralDao generalDao;
@Autowired
private LogHelper logHelper;
public static Map<Integer, SystemStatus> statusPerId;
public static Map<String, SystemStatus> statusPerCode;
public static Map<String, String> systemConfigurations;
public static Map<String, Section> systemSections;
@Scheduled(fixedRate = 3600000)
@PostConstruct
public void getStatusPerId() throws Exception {
Transition transition = new Transition();
try {
logHelper.log("Going to Load System Status Per ID", transition);
List<SystemStatus> statusList = generalDao.listSytemStatus(null, transition);
statusPerId = new HashMap<Integer, SystemStatus>();
for (SystemStatus status : statusList)
statusPerId.put(status.getId(), status);
logHelper.log("System Status Per ID Loaded as: " + statusPerId, transition);
} catch (Exception exp) {
logHelper.logExp(exp, " Get System Status Per ID ", transition);
}
}
@Scheduled(fixedRate = 3700000)
@PostConstruct
public void getStatusPerCode() throws Exception {
Transition transition = new Transition();
try {
logHelper.log("Going to Load System Status Per Code", transition);
List<SystemStatus> statusList = generalDao.listSytemStatus(null, new Transition());
statusPerCode = new HashMap<String, SystemStatus>();
for (SystemStatus status : statusList)
statusPerCode.put(status.getCode(), status);
logHelper.log("System Status Per ID Loaded as: " + statusPerCode, transition);
} catch (Exception exp) {
logHelper.logExp(exp, " Get System Status Per Code ", transition);
}
}
@Scheduled(fixedRate = 3700000)
@PostConstruct
public void getSystemConfigurations() throws Exception {
Transition transition = new Transition();
try {
logHelper.log("Going to Load System configurations ", transition);
List<SystemConfiguration> configurationsList = generalDao.listSytemConfigurations(new Transition());
systemConfigurations = new HashMap<String, String>();
for (SystemConfiguration configuration : configurationsList)
systemConfigurations.put(configuration.getKey(), configuration.getValue());
logHelper.log("System configurations Loaded as: " + systemConfigurations, transition);
} catch (Exception exp) {
logHelper.logExp(exp, " Get System configurations ", transition);
}
}
@Scheduled(fixedRate = 3700000)
@PostConstruct
public void getSystemSections() throws Exception {
Transition transition = new Transition();
try {
logHelper.log("Going to Load System sections configurations ", transition);
List<Section> sectionsList = generalDao.listSections(new Transition());
systemSections = new HashMap<String, Section>();
for (Section section : sectionsList)
systemSections.put(section.getSectionCode(), section);
logHelper.log("System sections configurations Loaded as: " + systemSections, transition);
} catch (Exception exp) {
logHelper.logExp(exp, " Get System sections configurations ", transition);
}
}
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean(destroyMethod = "shutdownNow")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}
|
3e0e247cc6a9b757f1c88b3eac9c57a4718e8134 | 864 | java | Java | src/test/java/me/ajlane/geo/repast/succession/pathway/coded/CodedLcsTransitionMapOldTest.java | lanecodes/agrosuccess-sim | c9af27607f712751a603ac7ad21db284c8ac0009 | [
"MIT"
] | null | null | null | src/test/java/me/ajlane/geo/repast/succession/pathway/coded/CodedLcsTransitionMapOldTest.java | lanecodes/agrosuccess-sim | c9af27607f712751a603ac7ad21db284c8ac0009 | [
"MIT"
] | null | null | null | src/test/java/me/ajlane/geo/repast/succession/pathway/coded/CodedLcsTransitionMapOldTest.java | lanecodes/agrosuccess-sim | c9af27607f712751a603ac7ad21db284c8ac0009 | [
"MIT"
] | null | null | null | 27 | 86 | 0.753472 | 5,990 | package me.ajlane.geo.repast.succession.pathway.coded;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import me.ajlane.geo.repast.succession.pathway.EnvrAntecedent;
import me.ajlane.geo.repast.succession.pathway.EnvrConsequent;
import me.ajlane.geo.repast.succession.pathway.coded.CodedLcsTransitionMapOld;
public class CodedLcsTransitionMapOldTest {
@Before
public void setup() {
}
@Test
public void testCodedLandCoverStateTransitionMap() {
CodedLcsTransitionMapOld transMap = new CodedLcsTransitionMapOld();
EnvrAntecedent<Integer, Integer, Integer, Integer, Integer, Integer, Integer> a1 =
new EnvrAntecedent<>(1, 0, 1, 1, 0, 0, 2);
EnvrConsequent<Integer, Integer> c1 = new EnvrConsequent<>(2, 10);
transMap.put(a1, c1);
assertTrue(transMap.get(a1).equals(c1));
}
}
|
3e0e249e8e847c96002fc59ecfab6d9d9b888f9f | 61 | java | Java | performance-tracking-stubs/src/main/java/android/util/AttributeSet.java | donnie-jp/android-perftracking | dfb50fb2e95f0a0957eab386c6ce81490395a944 | [
"MIT"
] | 19 | 2017-10-26T06:41:40.000Z | 2019-11-07T06:18:55.000Z | performance-tracking-stubs/src/main/java/android/util/AttributeSet.java | donnie-jp/android-perftracking | dfb50fb2e95f0a0957eab386c6ce81490395a944 | [
"MIT"
] | 55 | 2017-12-11T15:32:44.000Z | 2019-11-08T17:12:51.000Z | performance-tracking-stubs/src/main/java/android/util/AttributeSet.java | donnie-jp/android-perftracking | dfb50fb2e95f0a0957eab386c6ce81490395a944 | [
"MIT"
] | 11 | 2017-10-30T04:22:48.000Z | 2019-08-06T05:23:14.000Z | 8.714286 | 28 | 0.672131 | 5,991 | package android.util;
public class AttributeSet {
}
|
3e0e24a3e9d494f5098f730aa196be71c9adb83f | 2,637 | java | Java | algorithm/java/RottingOrange.java | cocoa-maemae/leetcode | b7724b4d10387797167b18ec36d77e7418a6d85a | [
"MIT"
] | 1 | 2021-09-29T11:22:02.000Z | 2021-09-29T11:22:02.000Z | algorithm/java/RottingOrange.java | cocoa-maemae/leetcode | b7724b4d10387797167b18ec36d77e7418a6d85a | [
"MIT"
] | null | null | null | algorithm/java/RottingOrange.java | cocoa-maemae/leetcode | b7724b4d10387797167b18ec36d77e7418a6d85a | [
"MIT"
] | null | null | null | 32.9625 | 81 | 0.45127 | 5,992 | import com.eclipsesource.json.JsonArray;
import java.io.*;
import java.util.*;
class Solution {
public int orangesRotting(int[][] grid) {
final int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Queue<int[]> q = new LinkedList<>();
int m = grid.length, n = grid[0].length, fresh = 0, rot = 0, minit = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) fresh++;
if (grid[i][j] == 2) q.offer(new int[] {i, j});
}
}
while (!q.isEmpty() && fresh > 0) {
int size = q.size();
for (int i = 0; i < size; i++) {
int[] cur = q.poll();
for (int[] dir : dirs) {
int x = cur[0] + dir[0];
int y = cur[1] + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
fresh--;
grid[x][y] = 2;
q.offer(new int[] {x, y});
}
}
}
minit++;
}
return fresh == 0 ? minit : -1;
}
}
public class RottingOrange {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for (int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
public static int[][] stringToInt2dArray(String input) {
JsonArray jsonArray = JsonArray.readFrom(input);
if (jsonArray.size() == 0) {
return new int[0][0];
}
int[][] arr = new int[jsonArray.size()][];
for (int i = 0; i < arr.length; i++) {
JsonArray cols = jsonArray.get(i).asArray();
arr[i] = stringToIntegerArray(cols.toString());
}
return arr;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int[][] grid = stringToInt2dArray(line);
int ret = new Solution().orangesRotting(grid);
String out = String.valueOf(ret);
System.out.print(out + "\n");
break;
}
}
}
|
3e0e24bf0677be6c52cadab94d36e62c04f89ad8 | 203 | java | Java | src/main/java/enums/TrainType.java | Gdudek-git/multithreading-example | dafd4018d7216f5d207872eb7d98993d9d5d6a11 | [
"MIT"
] | null | null | null | src/main/java/enums/TrainType.java | Gdudek-git/multithreading-example | dafd4018d7216f5d207872eb7d98993d9d5d6a11 | [
"MIT"
] | null | null | null | src/main/java/enums/TrainType.java | Gdudek-git/multithreading-example | dafd4018d7216f5d207872eb7d98993d9d5d6a11 | [
"MIT"
] | null | null | null | 16.916667 | 53 | 0.679803 | 5,993 | package enums;
public enum TrainType {
SINGLE_UNIT("/images/train/SingleUnitTrain.png");
public String imagePath;
TrainType(String imagePath) {
this.imagePath = imagePath;
}
}
|
3e0e2525f9c6fb402f04424ee4491b6b6a75a6be | 1,781 | java | Java | net.solarnetwork.node.ocpp.kiosk.web/src/net/solarnetwork/node/ocpp/kiosk/web/KioskDataService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.node.ocpp.kiosk.web/src/net/solarnetwork/node/ocpp/kiosk/web/KioskDataService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | net.solarnetwork.node.ocpp.kiosk.web/src/net/solarnetwork/node/ocpp/kiosk/web/KioskDataService.java | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | 28.269841 | 76 | 0.652442 | 5,994 | /* ==================================================================
* KioskDataService.java - 23/10/2016 6:30:17 AM
*
* Copyright 2007-2016 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.node.ocpp.kiosk.web;
import java.util.Map;
/**
* Service API for the collection of data needed to drive the kiosk display.
*
* @author matt
* @version 1.0
*/
public interface KioskDataService {
/** A message topic for kiosk data changes. */
String MESSAGE_TOPIC_KIOSK_DATA = "/pub/topic/ocpp/kiosk";
/**
* Initialize the service. Call this once after all properties configured.
*/
void startup();
/**
* Shutdown the service, releasing any associated resources.
*/
void shutdown();
/**
* Get a map of all data necessary for the kiosk to display.
*
* @return The data.
*/
Map<String, Object> getKioskData();
/**
* Refresh the kiosk data.
*
* This should be called periodically to keep the data updated.
*/
void refreshKioskData();
}
|
3e0e25969ce3a866360ca1ab35201b8e636fde4e | 20,002 | java | Java | app/src/main/java/com/aumum/app/mobile/ui/moment/MomentDetailsFragment.java | dooney/Aumum-Android | 520b2562daec2f359824c53653a273fe0fc8483c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/aumum/app/mobile/ui/moment/MomentDetailsFragment.java | dooney/Aumum-Android | 520b2562daec2f359824c53653a273fe0fc8483c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/aumum/app/mobile/ui/moment/MomentDetailsFragment.java | dooney/Aumum-Android | 520b2562daec2f359824c53653a273fe0fc8483c | [
"Apache-2.0"
] | null | null | null | 37.954459 | 105 | 0.640986 | 5,995 | package com.aumum.app.mobile.ui.moment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.aumum.app.mobile.Injector;
import com.aumum.app.mobile.R;
import com.aumum.app.mobile.core.dao.CreditRuleStore;
import com.aumum.app.mobile.core.dao.MomentStore;
import com.aumum.app.mobile.core.dao.UserStore;
import com.aumum.app.mobile.core.infra.security.ApiKeyProvider;
import com.aumum.app.mobile.core.model.CmdMessage;
import com.aumum.app.mobile.core.model.CreditRule;
import com.aumum.app.mobile.core.model.Moment;
import com.aumum.app.mobile.core.model.MomentComment;
import com.aumum.app.mobile.core.model.User;
import com.aumum.app.mobile.core.service.ChatService;
import com.aumum.app.mobile.core.service.RestService;
import com.aumum.app.mobile.core.service.ShareService;
import com.aumum.app.mobile.events.AddMomentCommentEvent;
import com.aumum.app.mobile.events.AddMomentCommentFinishedEvent;
import com.aumum.app.mobile.events.ReplyMomentCommentEvent;
import com.aumum.app.mobile.ui.base.LoaderFragment;
import com.aumum.app.mobile.ui.base.ProgressListener;
import com.aumum.app.mobile.ui.helper.TextWatcherAdapter;
import com.aumum.app.mobile.ui.image.CustomGallery;
import com.aumum.app.mobile.ui.image.GalleryAdapter;
import com.aumum.app.mobile.ui.image.ImageViewActivity;
import com.aumum.app.mobile.ui.like.LikesLayoutListener;
import com.aumum.app.mobile.ui.report.ReportActivity;
import com.aumum.app.mobile.ui.user.UserListener;
import com.aumum.app.mobile.ui.view.AvatarImageView;
import com.aumum.app.mobile.ui.view.LikeTextView;
import com.aumum.app.mobile.ui.view.ListViewDialog;
import com.aumum.app.mobile.ui.view.SpannableTextView;
import com.aumum.app.mobile.utils.EditTextUtils;
import com.aumum.app.mobile.utils.ImageLoaderUtils;
import com.aumum.app.mobile.utils.SafeAsyncTask;
import com.github.kevinsawicki.wishlist.Toaster;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import retrofit.RetrofitError;
/**
* Created by Administrator on 3/03/2015.
*/
public class MomentDetailsFragment extends LoaderFragment<Moment> {
@Inject Bus bus;
@Inject ApiKeyProvider apiKeyProvider;
@Inject UserStore userStore;
@Inject MomentStore momentStore;
@Inject CreditRuleStore creditRuleStore;
@Inject RestService restService;
@Inject ChatService chatService;
private ShareService shareService;
private String momentId;
private Moment moment;
private String currentUserId;
private User currentUser;
private MomentComment repliedComment;
private ScrollView scrollView;
private View mainView;
private AvatarImageView avatarImage;
private TextView userNameText;
private TextView cityText;
private TextView createdAtText;
private SpannableTextView detailsText;
private GridView gridGallery;
private ImageView imageGallery;
private ViewGroup likesLayout;
private TextView commentText;
private LikeTextView likeText;
private LikesLayoutListener likesLayoutListener;
private EditText editComment;
private Button postCommentButton;
private final TextWatcher watcher = validationTextWatcher();
GalleryAdapter adapter;
private SafeAsyncTask<Boolean> task;
private ProgressListener progressListener;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
MomentCommentsFragment fragment = new MomentCommentsFragment();
fragment.setMoment(moment);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
};
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Injector.inject(this);
final Intent intent = getActivity().getIntent();
momentId = intent.getStringExtra(MomentDetailsActivity.INTENT_MOMENT_ID);
currentUserId = apiKeyProvider.getAuthUserId();
likesLayoutListener = new LikesLayoutListener(getActivity(), currentUserId);
shareService = new ShareService(getActivity());
progressListener = (ProgressListener) getActivity();
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
MenuItem more = menu.add(Menu.NONE, 0, Menu.NONE, null);
more.setActionView(R.layout.menuitem_more);
more.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
View moreView = more.getActionView();
ImageView moreIcon = (ImageView) moreView.findViewById(R.id.b_more);
moreIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getActivity() != null && moment != null) {
showActionDialog(moment.isOwner(currentUserId));
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_moment_details, null);
}
@Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
scrollView = (ScrollView) view.findViewById(R.id.scroll_view);
scrollView.setHorizontalScrollBarEnabled(false);
scrollView.setVerticalScrollBarEnabled(false);
mainView = view.findViewById(R.id.main_view);
avatarImage = (AvatarImageView) view.findViewById(R.id.image_avatar);
userNameText = (TextView) view.findViewById(R.id.text_user_name);
cityText = (TextView) view.findViewById(R.id.text_city);
createdAtText = (TextView) view.findViewById(R.id.text_createdAt);
detailsText = (SpannableTextView) view.findViewById(R.id.text_details);
adapter = new GalleryAdapter(getActivity(), R.layout.image_collection_listitem_inner);
gridGallery = (GridView) view.findViewById(R.id.grid_gallery);
gridGallery.setAdapter(adapter);
gridGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
clickImageByIndex(position);
}
});
imageGallery = (ImageView) view.findViewById(R.id.image_gallery);
imageGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clickImageByIndex(0);
}
});
likesLayout = (ViewGroup) view.findViewById(R.id.layout_likes);
commentText = (TextView) view.findViewById(R.id.text_comment);
likeText = (LikeTextView) view.findViewById(R.id.text_like);
likeText.setTextResId(R.string.label_like);
likeText.setLikeResId(R.drawable.ic_fa_thumbs_o_up);
likeText.setLikedResId(R.drawable.ic_fa_thumbs_up);
editComment = (EditText) view.findViewById(R.id.edit_comment);
editComment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND)
submitComment();
return false;
}
});
editComment.addTextChangedListener(watcher);
postCommentButton = (Button) view.findViewById(R.id.b_post_comment);
postCommentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitComment();
}
});
}
@Override
public void onResume() {
super.onResume();
bus.register(this);
updateUIWithValidation();
}
@Override
public void onPause() {
super.onPause();
bus.unregister(this);
}
private TextWatcher validationTextWatcher() {
return new TextWatcherAdapter() {
public void afterTextChanged(final Editable gitDirEditText) {
updateUIWithValidation();
}
};
}
private void updateUIWithValidation() {
final boolean populated = populated(editComment);
if (postCommentButton != null) {
postCommentButton.setEnabled(populated);
}
}
private boolean populated(final EditText editText) {
return editText.length() > 0;
}
@Override
protected boolean readyToShow() {
return getData() != null;
}
@Override
protected View getMainView() {
return mainView;
}
@Override
protected Moment loadDataCore(Bundle bundle) throws Exception {
currentUser = userStore.getCurrentUser();
moment = momentStore.getMomentByIdFromServer(momentId);
if (moment.getDeletedAt() != null) {
throw new Exception(getString(R.string.error_moment_was_deleted));
}
User user = userStore.getUserById(moment.getUserId());
moment.setUser(user);
return moment;
}
@Override
protected void handleLoadResult(Moment result) {
if (moment != null) {
setData(moment);
updateMoment(moment);
handler.sendEmptyMessage(0);
}
}
private void showActionDialog(final boolean isOwner) {
List<String> options = new ArrayList<String>();
options.add(getString(R.string.label_share));
if (isOwner) {
options.add(getString(R.string.label_delete));
} else {
options.add(getString(R.string.label_report));
}
new ListViewDialog(getActivity(), null, options,
new ListViewDialog.OnItemClickListener() {
@Override
public void onItemClick(int i) {
switch (i) {
case 0:
showShare();
break;
case 1:
if (isOwner) {
deleteMoment();
} else {
reportMoment();
}
break;
default:
break;
}
}
}).show();
}
private void showShare() {
String imageUrl = null;
if (moment.getImages().size() > 0) {
imageUrl = moment.getImages().get(0);
}
shareService.show(moment.getDetails(), null, imageUrl);
}
private void deleteMoment() {
if (task != null) {
return;
}
progressListener.showProgress();
task = new SafeAsyncTask<Boolean>() {
public Boolean call() throws Exception {
restService.deleteMoment(momentId);
momentStore.deleteMoment(momentId);
updateCredit(currentUser, CreditRule.DELETE_MOMENT);
return true;
}
@Override
protected void onException(final Exception e) throws RuntimeException {
if(!(e instanceof RetrofitError)) {
final Throwable cause = e.getCause() != null ? e.getCause() : e;
if(cause != null) {
Toaster.showShort(getActivity(), cause.getMessage());
}
}
}
@Override
public void onSuccess(final Boolean success) {
Toaster.showShort(getActivity(), R.string.info_moment_deleted);
final Intent intent = new Intent();
intent.putExtra(MomentDetailsActivity.INTENT_MOMENT_ID, momentId);
intent.putExtra(MomentDetailsActivity.INTENT_DELETED, true);
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
}
@Override
protected void onFinally() throws RuntimeException {
progressListener.hideProgress();
task = null;
}
};
task.execute();
}
private void reportMoment() {
final Intent intent = new Intent(getActivity(), ReportActivity.class);
intent.putExtra(ReportActivity.INTENT_ENTITY_TYPE, ReportActivity.TYPE_MOMENT);
intent.putExtra(ReportActivity.INTENT_ENTITY_ID, momentId);
startActivity(intent);
}
private void updateMoment(Moment moment) {
User user = moment.getUser();
avatarImage.getFromUrl(user.getAvatarUrl());
avatarImage.setOnClickListener(new UserListener(avatarImage.getContext(), moment.getUserId()));
userNameText.setText(user.getScreenName());
userNameText.setOnClickListener(new UserListener(userNameText.getContext(), moment.getUserId()));
cityText.setText(user.getCity());
createdAtText.setText(moment.getCreatedAtFormatted());
if (moment.getDetails() != null && moment.getDetails().length() > 0) {
detailsText.setSpannableText(moment.getDetails());
} else {
detailsText.setVisibility(View.GONE);
}
ArrayList<CustomGallery> list = new ArrayList<CustomGallery>();
for (String imageUrl: moment.getImages()) {
CustomGallery item = new CustomGallery();
item.type = CustomGallery.HTTP;
item.imageUri = imageUrl;
list.add(item);
}
gridGallery.setVisibility(View.GONE);
imageGallery.setVisibility(View.GONE);
if (list.size() > 0) {
if (list.size() > 1) {
adapter.addAll(list);
gridGallery.setVisibility(View.VISIBLE);
} else {
ImageLoaderUtils.displayImage(list.get(0).getUri(), imageGallery);
imageGallery.setVisibility(View.VISIBLE);
}
}
int comments = moment.getCommentsCount();
commentText.setText(comments > 0 ? String.valueOf(comments) : getString(R.string.label_comment));
commentText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
likeText.init(moment.getLikesCount(), moment.isLiked(currentUserId));
MomentLikeListener likeListener = new MomentLikeListener(moment);
likeListener.setOnLikeFinishedListener(new MomentLikeListener.LikeFinishedListener() {
@Override
public void OnLikeFinished(Moment moment) {
likesLayoutListener.update(likesLayout, moment.getLikes());
}
@Override
public void OnUnLikeFinished(Moment moment) {
likesLayoutListener.update(likesLayout, moment.getLikes());
}
});
likeText.setLikeListener(likeListener);
likesLayoutListener.update(likesLayout, moment.getLikes());
}
private void disableSubmit() {
postCommentButton.setEnabled(false);
}
private void resetCommentBox() {
EditTextUtils.hideSoftInput(editComment);
editComment.clearFocus();
editComment.setText(null);
editComment.setHint(R.string.hint_new_moment_comment);
}
private void submitComment() {
String repliedId = null;
String content = editComment.getText().toString();
if (repliedComment != null) {
repliedId = repliedComment.getObjectId();
content = getString(R.string.hint_reply_moment_comment,
repliedComment.getUser().getScreenName(), content);
}
bus.post(new AddMomentCommentEvent(repliedId, content));
disableSubmit();
resetCommentBox();
}
@Subscribe
public void onReplyMomentCommentEvent(final ReplyMomentCommentEvent event) {
EditTextUtils.showSoftInput(editComment, true);
repliedComment = event.getComment();
editComment.setHint(getString(R.string.hint_reply_moment_comment,
repliedComment.getUser().getScreenName(), repliedComment.getContent()));
}
@Subscribe
public void onAddMomentCommentFinishedEvent(final AddMomentCommentFinishedEvent event) {
new SafeAsyncTask<Boolean>() {
@Override
public Boolean call() throws Exception {
if (!moment.isOwner(currentUserId)) {
sendCommentMessage(event.getContent());
updateCredit(currentUser, CreditRule.ADD_MOMENT_COMMENT);
}
if (repliedComment != null &&
!moment.isOwner(repliedComment.getUserId()) &&
!repliedComment.isOwner(currentUserId)) {
sendRepliedMessage(repliedComment);
}
return true;
}
}.execute();
}
private void sendCommentMessage(String content) throws Exception {
String title = getString(R.string.label_comment_moment_message,
currentUser.getScreenName());
CmdMessage cmdMessage = new CmdMessage(CmdMessage.Type.MOMENT_COMMENT,
title, content, momentId);
User momentOwner = userStore.getUserById(moment.getUserId());
chatService.sendCmdMessage(momentOwner.getChatId(), cmdMessage, false, null);
}
private void sendRepliedMessage(MomentComment replied) throws Exception {
String title = getString(R.string.label_replied_moment_message,
currentUser.getScreenName());
CmdMessage cmdMessage = new CmdMessage(CmdMessage.Type.MOMENT_REPLY,
title, replied.getContent(), momentId);
chatService.sendCmdMessage(replied.getUser().getChatId(), cmdMessage, false, null);
}
private void clickImageByIndex(int index) {
String imageUrl = moment.getImages().get(index);
final Intent intent = new Intent(getActivity(), ImageViewActivity.class);
intent.putExtra(ImageViewActivity.INTENT_IMAGE_URI, imageUrl);
startActivity(intent);
}
private void updateCredit(User currentUser, int seq) throws Exception {
final CreditRule creditRule = creditRuleStore.getCreditRuleBySeq(seq);
if (creditRule != null) {
final int credit = creditRule.getCredit();
restService.updateUserCredit(currentUser.getObjectId(), credit);
currentUser.updateCredit(credit);
userStore.save(currentUser);
if (credit > 0) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toaster.showShort(getActivity(), getString(R.string.info_got_credit,
creditRule.getDescription(), credit));
}
});
}
}
}
}
|
3e0e25c4dd55d48109aab68a17aeae2775087599 | 1,282 | java | Java | src/main/java/models/Team.java | kchamp45/TeamBuilder2 | 739cc9833e68ad34384178a6f72e09a1095518ec | [
"MIT"
] | null | null | null | src/main/java/models/Team.java | kchamp45/TeamBuilder2 | 739cc9833e68ad34384178a6f72e09a1095518ec | [
"MIT"
] | null | null | null | src/main/java/models/Team.java | kchamp45/TeamBuilder2 | 739cc9833e68ad34384178a6f72e09a1095518ec | [
"MIT"
] | null | null | null | 19.723077 | 66 | 0.583463 | 5,996 | package models;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class Team {
private String name;
private String description;
private int id;
public Team (String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Team team = (Team) o;
if (id != team.id) return false;
if (!name.equals(team.name)) return false;
return description.equals(team.description);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + description.hashCode();
result = 31 * result + id;
return result;
}
}
|
3e0e26d3b8337927def48019d4a476466475aa49 | 15,221 | java | Java | test/src/test/java/hudson/model/JobTest.java | ydubreuil/jenkins | 0c991dec38800adabacd8a56349bd61575c1d7e5 | [
"MIT"
] | 2 | 2018-03-04T06:01:08.000Z | 2018-03-04T06:01:11.000Z | test/src/test/java/hudson/model/JobTest.java | ydubreuil/jenkins | 0c991dec38800adabacd8a56349bd61575c1d7e5 | [
"MIT"
] | 4 | 2020-02-11T15:32:26.000Z | 2021-08-02T17:20:28.000Z | test/src/test/java/hudson/model/JobTest.java | ydubreuil/jenkins | 0c991dec38800adabacd8a56349bd61575c1d7e5 | [
"MIT"
] | 16 | 2016-10-22T14:50:52.000Z | 2021-08-06T17:34:12.000Z | 40.374005 | 127 | 0.622561 | 5,997 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
* Copyright (c) 2015 Christopher Simons
*
* 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 hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebAssert;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlFormUtil;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.TextPage;
import hudson.Functions;
import hudson.util.TextFile;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.MessageFormat;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import jenkins.model.ProjectNamingStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.RunLoadCounter;
import org.jvnet.hudson.test.recipes.LocalData;
import static org.hamcrest.Matchers.endsWith;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
/**
* @author Kohsuke Kawaguchi
*/
public class JobTest {
@Rule public JenkinsRule j = new JenkinsRule();
@SuppressWarnings("unchecked")
@Test public void jobPropertySummaryIsShownInMainPage() throws Exception {
AbstractProject project = j.createFreeStyleProject();
project.addProperty(new JobPropertyImpl("NeedleInPage"));
HtmlPage page = j.createWebClient().getPage(project);
WebAssert.assertTextPresent(page, "NeedleInPage");
}
@Test public void buildNumberSynchronization() throws Exception {
AbstractProject project = j.createFreeStyleProject();
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch stopLatch = new CountDownLatch(2);
BuildNumberSyncTester test1 = new BuildNumberSyncTester(project, startLatch, stopLatch, true);
BuildNumberSyncTester test2 = new BuildNumberSyncTester(project, startLatch, stopLatch, false);
new Thread(test1).start();
new Thread(test2).start();
startLatch.countDown();
stopLatch.await();
assertTrue(test1.message, test2.passed);
assertTrue(test2.message, test2.passed);
}
public static class BuildNumberSyncTester implements Runnable {
private final AbstractProject p;
private final CountDownLatch start;
private final CountDownLatch stop;
private final boolean assign;
String message;
boolean passed;
BuildNumberSyncTester(AbstractProject p, CountDownLatch l1, CountDownLatch l2, boolean b) {
this.p = p;
this.start = l1;
this.stop = l2;
this.assign = b;
this.message = null;
this.passed = false;
}
public void run() {
try {
start.await();
for (int i = 0; i < 100; i++) {
int buildNumber = -1, savedBuildNumber = -1;
TextFile f;
synchronized (p) {
if (assign) {
buildNumber = p.assignBuildNumber();
f = p.getNextBuildNumberFile();
if (f == null) {
this.message = "Could not get build number file";
this.passed = false;
return;
}
savedBuildNumber = Integer.parseInt(f.readTrim());
if (buildNumber != (savedBuildNumber-1)) {
this.message = "Build numbers don't match (" + buildNumber + ", " + (savedBuildNumber-1) + ")";
this.passed = false;
return;
}
} else {
buildNumber = p.getNextBuildNumber() + 100;
p.updateNextBuildNumber(buildNumber);
f = p.getNextBuildNumberFile();
if (f == null) {
this.message = "Could not get build number file";
this.passed = false;
return;
}
savedBuildNumber = Integer.parseInt(f.readTrim());
if (buildNumber != savedBuildNumber) {
this.message = "Build numbers don't match (" + buildNumber + ", " + savedBuildNumber + ")";
this.passed = false;
return;
}
}
}
}
this.passed = true;
}
catch (InterruptedException e) {}
catch (IOException e) {
fail("Failed to assign build number");
}
finally {
stop.countDown();
}
}
}
@SuppressWarnings("unchecked")
public static class JobPropertyImpl extends JobProperty<Job<?,?>> {
public static DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private final String testString;
public JobPropertyImpl(String testString) {
this.testString = testString;
}
public String getTestString() {
return testString;
}
@Override
public JobPropertyDescriptor getDescriptor() {
return DESCRIPTOR;
}
private static final class DescriptorImpl extends JobPropertyDescriptor {
public String getDisplayName() {
return "";
}
}
}
@LocalData
@Test public void readPermission() throws Exception {
JenkinsRule.WebClient wc = j.createWebClient();
wc.assertFails("job/testJob/", HttpURLConnection.HTTP_NOT_FOUND);
wc.assertFails("jobCaseInsensitive/testJob/", HttpURLConnection.HTTP_NOT_FOUND);
wc.login("joe"); // Has Item.READ permission
// Verify we can access both URLs:
wc.goTo("job/testJob/");
wc.goTo("jobCaseInsensitive/TESTJOB/");
}
@LocalData
@Test public void configDotXmlPermission() throws Exception {
j.jenkins.setCrumbIssuer(null);
JenkinsRule.WebClient wc = j.createWebClient();
boolean saveEnabled = Item.EXTENDED_READ.getEnabled();
Item.EXTENDED_READ.setEnabled(true);
try {
wc.assertFails("job/testJob/config.xml", HttpURLConnection.HTTP_FORBIDDEN);
wc.login("alice"); // Has CONFIGURE and EXTENDED_READ permission
tryConfigDotXml(wc, 500, "Both perms; should get 500");
wc.login("bob"); // Has only CONFIGURE permission (this should imply EXTENDED_READ)
tryConfigDotXml(wc, 500, "Config perm should imply EXTENDED_READ");
wc.login("charlie"); // Has only EXTENDED_READ permission
tryConfigDotXml(wc, 403, "No permission, should get 403");
} finally {
Item.EXTENDED_READ.setEnabled(saveEnabled);
}
}
private static void tryConfigDotXml(JenkinsRule.WebClient wc, int status, String msg) throws Exception {
// Verify we can GET the config.xml:
wc.goTo("job/testJob/config.xml", "application/xml");
// This page is a simple form to POST to /job/testJob/config.xml
// But it posts invalid data so we expect 500 if we have permission, 403 if not
HtmlPage page = wc.goTo("userContent/post.html");
try {
HtmlFormUtil.submit(page.getForms().get(0));
fail("Expected exception: " + msg);
} catch (FailingHttpStatusCodeException expected) {
assertEquals(msg, status, expected.getStatusCode());
}
wc.goTo("logout");
}
@LocalData @Issue("JENKINS-6371")
@Test public void getArtifactsUpTo() throws Exception {
// There was a bug where intermediate directories were counted,
// so too few artifacts were returned.
Run r = j.jenkins.getItemByFullName("testJob", Job.class).getLastCompletedBuild();
assertEquals(3, r.getArtifacts().size());
assertEquals(3, r.getArtifactsUpTo(3).size());
assertEquals(2, r.getArtifactsUpTo(2).size());
assertEquals(1, r.getArtifactsUpTo(1).size());
}
@Issue("JENKINS-10182")
@Test public void emptyDescriptionReturnsEmptyPage() throws Exception {
// A NPE was thrown if a job had a null (empty) description.
JenkinsRule.WebClient wc = j.createWebClient();
FreeStyleProject project = j.createFreeStyleProject("project");
project.setDescription("description");
assertEquals("description", ((TextPage) wc.goTo("job/project/description", "text/plain")).getContent());
project.setDescription(null);
assertEquals("", ((TextPage) wc.goTo("job/project/description", "text/plain")).getContent());
}
@Test public void projectNamingStrategy() throws Exception {
j.jenkins.setProjectNamingStrategy(new ProjectNamingStrategy.PatternProjectNamingStrategy("DUMMY.*", false));
final FreeStyleProject p = j.createFreeStyleProject("DUMMY_project");
assertNotNull("no project created", p);
try {
j.createFreeStyleProject("project");
fail("should not get here, the project name is not allowed, therefore the creation must fail!");
} catch (Failure e) {
// OK, expected
}finally{
// set it back to the default naming strategy, otherwise all other tests would fail to create jobs!
j.jenkins.setProjectNamingStrategy(ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY);
}
j.createFreeStyleProject("project");
}
@Issue("JENKINS-16023")
@Test public void getLastFailedBuild() throws Exception {
final FreeStyleProject p = j.createFreeStyleProject();
RunLoadCounter.prepare(p);
p.getBuildersList().add(new FailureBuilder());
j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
p.getBuildersList().remove(FailureBuilder.class);
j.assertBuildStatusSuccess(p.scheduleBuild2(0));
j.assertBuildStatusSuccess(p.scheduleBuild2(0));
j.assertBuildStatusSuccess(p.scheduleBuild2(0));
assertEquals(6, p.getLastSuccessfulBuild().getNumber());
assertEquals(3, RunLoadCounter.assertMaxLoads(p, 1, new Callable<Integer>() {
@Override public Integer call() throws Exception {
return p.getLastFailedBuild().getNumber();
}
}).intValue());
}
@Issue("JENKINS-19764")
@Test public void testRenameWithCustomBuildsDirWithSubdir() throws Exception {
j.jenkins.setRawBuildsDir("${JENKINS_HOME}/builds/${ITEM_FULL_NAME}/builds");
final FreeStyleProject p = j.createFreeStyleProject();
p.scheduleBuild2(0).get();
p.renameTo("different-name");
}
@Issue("JENKINS-30502")
@Test
public void testRenameTrimsLeadingSpace() throws Exception {
tryRename("myJob1", " foo", "foo", false);
}
@Issue("JENKINS-30502")
@Test
public void testRenameTrimsTrailingSpace() throws Exception {
tryRename("myJob2", "foo ", "foo", false);
}
@Issue("JENKINS-30502")
@Test
public void testAllowTrimmingByUser() throws Exception {
assumeFalse("Unix-only test.", Functions.isWindows());
tryRename("myJob3 ", "myJob3", "myJob3", false);
}
@Issue("JENKINS-30502")
@Test
public void testRenameWithLeadingSpaceTrimsLeadingSpace() throws Exception {
assumeFalse("Unix-only test.", Functions.isWindows());
tryRename(" myJob4", " foo", "foo", false);
}
@Issue("JENKINS-30502")
@Test
public void testRenameWithLeadingSpaceTrimsTrailingSpace()
throws Exception {
assumeFalse("Unix-only test.", Functions.isWindows());
tryRename(" myJob5", "foo ", "foo", false);
}
@Issue("JENKINS-30502")
@Test
public void testRenameWithTrailingSpaceTrimsTrailingSpace()
throws Exception {
assumeFalse("Unix-only test.", Functions.isWindows());
tryRename("myJob6 ", "foo ", "foo", false);
}
@Issue("JENKINS-30502")
@Test
public void testRenameWithTrailingSpaceTrimsLeadingSpace()
throws Exception {
assumeFalse("Unix-only test.", Functions.isWindows());
tryRename("myJob7 ", " foo", "foo", false);
}
@Issue("JENKINS-30502")
@Test
public void testDoNotAutoTrimExistingUntrimmedNames() throws Exception {
assumeFalse("Unix-only test.", Functions.isWindows());
tryRename("myJob8 ", "myJob8 ", null, true);
}
private void tryRename(String initialName, String submittedName,
String correctResult, boolean shouldSkipConfirm) throws Exception {
j.jenkins.setCrumbIssuer(null);
FreeStyleProject job = j.createFreeStyleProject(initialName);
WebClient wc = j.createWebClient();
HtmlForm form = wc.getPage(job, "configure").getFormByName("config");
form.getInputByName("name").setValueAttribute(submittedName);
HtmlPage resultPage = j.submit(form);
String urlTemplate;
if (shouldSkipConfirm) {
urlTemplate = "/job/{0}/";
} else {
urlTemplate = "/job/{0}/rename?newName={1}";
}
String urlString = MessageFormat.format(
urlTemplate, initialName, correctResult).replace(" ", "%20");
assertThat(resultPage.getUrl().toString(), endsWith(urlString));
}
}
|
3e0e270e123b7a96431257115058dca743fcde2a | 3,482 | java | Java | src/main/java/org/cisecurity/oval/collection/win/GroupSidFilter.java | CISecurity/IETF104-Client | 8b76e5acd980918e6ffba53ef1484eb03e2b87ad | [
"Apache-2.0"
] | null | null | null | src/main/java/org/cisecurity/oval/collection/win/GroupSidFilter.java | CISecurity/IETF104-Client | 8b76e5acd980918e6ffba53ef1484eb03e2b87ad | [
"Apache-2.0"
] | 9 | 2021-01-26T16:14:32.000Z | 2021-01-26T16:14:51.000Z | src/main/java/org/cisecurity/oval/collection/win/GroupSidFilter.java | RG4421/SACM-Architecture | fa0694422097590d3033c2972d17949341886e01 | [
"Apache-2.0"
] | 1 | 2021-01-26T16:12:55.000Z | 2021-01-26T16:12:55.000Z | 26.784615 | 139 | 0.629523 | 5,998 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.11.21 at 11:38:45 AM EST
//
package org.cisecurity.oval.collection.win;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.cisecurity.oval.collection.FilterStringType;
import org.cisecurity.oval.collection.FilterType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://oval.cisecurity.org/XMLSchema/oval-collections-6}FilterType">
* <sequence>
* <element name="group_sid" type="{http://oval.cisecurity.org/XMLSchema/oval-collections-6}FilterStringType" minOccurs="0"/>
* <element name="user_sid" type="{http://oval.cisecurity.org/XMLSchema/oval-collections-6}FilterStringType" minOccurs="0"/>
* <element name="subgroup_sid" type="{http://oval.cisecurity.org/XMLSchema/oval-collections-6}FilterStringType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"groupSid",
"userSid",
"subgroupSid"
})
public class GroupSidFilter
extends FilterType
{
@XmlElement(name = "group_sid")
protected FilterStringType groupSid;
@XmlElement(name = "user_sid")
protected FilterStringType userSid;
@XmlElement(name = "subgroup_sid")
protected FilterStringType subgroupSid;
/**
* Gets the value of the groupSid property.
*
* @return
* possible object is
* {@link FilterStringType }
*
*/
public FilterStringType getGroupSid() {
return groupSid;
}
/**
* Sets the value of the groupSid property.
*
* @param value
* allowed object is
* {@link FilterStringType }
*
*/
public void setGroupSid(FilterStringType value) {
this.groupSid = value;
}
/**
* Gets the value of the userSid property.
*
* @return
* possible object is
* {@link FilterStringType }
*
*/
public FilterStringType getUserSid() {
return userSid;
}
/**
* Sets the value of the userSid property.
*
* @param value
* allowed object is
* {@link FilterStringType }
*
*/
public void setUserSid(FilterStringType value) {
this.userSid = value;
}
/**
* Gets the value of the subgroupSid property.
*
* @return
* possible object is
* {@link FilterStringType }
*
*/
public FilterStringType getSubgroupSid() {
return subgroupSid;
}
/**
* Sets the value of the subgroupSid property.
*
* @param value
* allowed object is
* {@link FilterStringType }
*
*/
public void setSubgroupSid(FilterStringType value) {
this.subgroupSid = value;
}
}
|
3e0e277f30a3fb8bd1315e845e6442141d674b66 | 1,053 | java | Java | src/main/java/com/jxiong/showcase/web/service/CustomerService.java | xiongyh2001/thymeleaf-freemarker-showcase | 92b1997e0424c6c4e3feb81e3116bf9758a35da3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jxiong/showcase/web/service/CustomerService.java | xiongyh2001/thymeleaf-freemarker-showcase | 92b1997e0424c6c4e3feb81e3116bf9758a35da3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jxiong/showcase/web/service/CustomerService.java | xiongyh2001/thymeleaf-freemarker-showcase | 92b1997e0424c6c4e3feb81e3116bf9758a35da3 | [
"Apache-2.0"
] | null | null | null | 36.310345 | 81 | 0.622032 | 5,999 | /*******************************************************************************
* Copyright 2018 Jason Xiong
*
* 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.jxiong.showcase.web.service;
import com.jxiong.showcase.web.domain.Customer;
public interface CustomerService {
public void saveCustomer(Customer customer);
public Iterable<Customer> findAllCustomers();
public Customer findCustomerById(long id);
}
|
3e0e27d360170c08b1fc7ed1cbfa040867a63fc3 | 784 | java | Java | behave-admin-api/src/main/java/org/java/behave/admin/dao/Product.java | hellolliu/behave-students | d5750002756f791af948eb8dd539d20d4f8df45b | [
"MIT"
] | null | null | null | behave-admin-api/src/main/java/org/java/behave/admin/dao/Product.java | hellolliu/behave-students | d5750002756f791af948eb8dd539d20d4f8df45b | [
"MIT"
] | null | null | null | behave-admin-api/src/main/java/org/java/behave/admin/dao/Product.java | hellolliu/behave-students | d5750002756f791af948eb8dd539d20d4f8df45b | [
"MIT"
] | null | null | null | 18.232558 | 60 | 0.61352 | 6,000 | package org.java.behave.admin.dao;
import java.math.BigDecimal;
public class Product {
String[] specifications;
BigDecimal price;
Integer number;
String url;
public String[] getSpecifications() {
return specifications;
}
public void setSpecifications(String[] specifications) {
this.specifications = specifications;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
3e0e281bd8bb5ec3d2c9ca6cb6646628fd5a00d7 | 568 | java | Java | demo-html/src/com/packtpub/libgdx/demo/client/GwtLauncher.java | meleemistress/my-first-game | 11cf7748da3f5e1c936901322cd3c8c3adc1bcaa | [
"Apache-2.0"
] | null | null | null | demo-html/src/com/packtpub/libgdx/demo/client/GwtLauncher.java | meleemistress/my-first-game | 11cf7748da3f5e1c936901322cd3c8c3adc1bcaa | [
"Apache-2.0"
] | null | null | null | demo-html/src/com/packtpub/libgdx/demo/client/GwtLauncher.java | meleemistress/my-first-game | 11cf7748da3f5e1c936901322cd3c8c3adc1bcaa | [
"Apache-2.0"
] | null | null | null | 29.894737 | 79 | 0.786972 | 6,001 | package com.packtpub.libgdx.demo.client;
import com.packtpub.libgdx.demo.MyDemo;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
public class GwtLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(480, 320);
return cfg;
}
@Override
public ApplicationListener getApplicationListener () {
return new MyDemo();
}
} |
3e0e282e7896b2ce4d62f99dee6eb311d3ed18e8 | 854 | java | Java | squidApp/src/main/java/org/cirdles/squid/gui/squidReportTable/RowComparator.java | drakene/Squid | 13ffb2458551cbc20d026487cd2f80577017e5d3 | [
"Apache-2.0"
] | 9 | 2017-05-08T15:02:48.000Z | 2022-03-05T02:21:05.000Z | squidApp/src/main/java/org/cirdles/squid/gui/squidReportTable/RowComparator.java | drakene/Squid | 13ffb2458551cbc20d026487cd2f80577017e5d3 | [
"Apache-2.0"
] | 383 | 2017-05-10T23:32:00.000Z | 2022-03-31T00:57:52.000Z | squidApp/src/main/java/org/cirdles/squid/gui/squidReportTable/RowComparator.java | drakene/Squid | 13ffb2458551cbc20d026487cd2f80577017e5d3 | [
"Apache-2.0"
] | 32 | 2017-03-19T20:47:27.000Z | 2022-01-13T15:57:19.000Z | 25.117647 | 112 | 0.5726 | 6,002 | package org.cirdles.squid.gui.squidReportTable;
import org.cirdles.squid.utilities.IntuitiveStringComparator;
import java.util.Comparator;
public class RowComparator implements Comparator<String> {
private static final IntuitiveStringComparator<String> stringComparator = new IntuitiveStringComparator<>();
public RowComparator() {
}
@Override
public int compare(String s1, String s2) {
int retVal;
try {
double n1 = Double.parseDouble(s1);
double n2 = Double.parseDouble(s2);
if (n1 == n2) {
retVal = 0;
} else if (n1 > n2) {
retVal = 1;
} else {
retVal = -1;
}
} catch (Exception e) {
retVal = stringComparator.compare(s1, s2);
}
return retVal;
}
} |
3e0e28702e2a8c7f5b12759e2428916f677be827 | 7,711 | java | Java | src/main/java/com/randomnoun/common/db/SqlParser.java | ramv/common-public | 29f42bbf98f73cbacaa9e76b624daee8892dcc32 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/randomnoun/common/db/SqlParser.java | ramv/common-public | 29f42bbf98f73cbacaa9e76b624daee8892dcc32 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/randomnoun/common/db/SqlParser.java | ramv/common-public | 29f42bbf98f73cbacaa9e76b624daee8892dcc32 | [
"BSD-2-Clause"
] | null | null | null | 32.812766 | 122 | 0.615744 | 6,003 | package com.randomnoun.common.db;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** A class to read an InputStream containing SQL statements (e.g. a MySQL input file) and split it into
* individual SQL statements.
*
* <p>Some MySQL command-line directives (e.g. 'DELIMITER') are processed whilst parsing.
*/
public class SqlParser {
private static Pattern MYSQL_DELIMITER_COMMAND = Pattern.compile("delimiter\\s+(.*)$", Pattern.CASE_INSENSITIVE);
// could have a ParseState that contains things like the current delimiter, or current database
// (for 'use' commands), which can be modified by the InputStream
/** Convert an InputStream of SQL statements into a List of individual
* statements. Statements are delimited by ";" strings that occur outside of strings or comments.
* The delimiter string is not included in the returned list of statements.
*
* <p>The delimiter string may be changed using the 'delimiter str' command.
* This command may end with a newline instead of a delimiter.
*
* <p>Comments may also be returned in the result.
* <p>Comments are defined by '-- to-end-of-line' or '/* within slash-star star-slash *⁠/' syntax.
* Comments that are created with '--' and that occur within a statement are returned before that statement
* has finished parsing.
*
* <p>NB: Does not handle escape sequences found within double or single quotes
*
* @param includeComments include comment strings in result
*
* @throws IOException
* @throws ParseException unclosed /*-style comment or single/double-quoted string
*/
public List<String> parseStatements(InputStream is, boolean includeComments) throws IOException, ParseException {
return parseStatements(new InputStreamReader(is), includeComments);
}
public List<String> parseStatements(Reader is, boolean includeComments)
throws IOException, ParseException
{
final List<String> allSql = new ArrayList<String>();
consumeStatements(is, includeComments, new Consumer<String>() {
@Override
public void consume(String s) {
allSql.add(s);
}
});
return allSql;
}
public static interface Consumer<T> {
public void consume(T s);
}
/** convert a text file of SQL statements into a List of individual
* statements. Comments may also be returned in the result.
*
* <p>NB: Does not handle escape sequences found within double or single quotes
*
* @param includeComments include comment strings in result
*
* @throws IOException
* @throws ParseException unclosed /*-style comment or single/double-quoted string
*/
public void consumeStatements(InputStream is, boolean includeComments, Consumer<String> consumer)
throws IOException, ParseException {
consumeStatements(new InputStreamReader(is), includeComments, consumer);
}
public void consumeStatements(Reader is, boolean includeComments, Consumer<String> consumer)
throws IOException, ParseException
{
// @TODO some error handling
// List allSql = new ArrayList<String>();
int state = 0; // command parsing [to states 0, 1, 2, 4, 7, 8]
// 1 // parsed double quote, in double quotes [to states 0, 1, 9]
// 2 // parsed - [to states 0, 3]
// 3 // parsed -- [ to states 0, 3]
// 4 // parsed / [ to states 0, 5]
// 5 // parsed /* [ to states 6, 5]
// 6 // parsed * from state 5 [ to states 0, 5]
// 7 // parse single quote, in single quotes [to states 0, 7, 10]
// 8 // parsed backslash in SQL, next character will be emitted without changing state [then to state 0]
// 9 // parsed backslash in double quote, next char emitted without changing state [then to state 1]
// 10 // parsed backslash in single quote, next char emitted without changing state [then to state 7]
String s = ""; // current statement
String c = ""; // current comment
String delimiter = ";"; // default delimiter
int intch = is.read();
int delimIdx = 0; // number of delimiter characters read
while (intch!=-1) {
char ch = (char) intch;
if (state==0) {
if (ch == delimiter.charAt(delimIdx)) {
delimIdx++;
if (delimiter.length()==delimIdx) {
s = s.trim(); delimIdx = 0; // was s.trim() + ";"
// could check for all commands at http://dev.mysql.com/doc/refman/5.7/en/mysql-commands.html
// but let's just implement 'DELIMITER' for now
Matcher m = MYSQL_DELIMITER_COMMAND.matcher(s);
if (m.matches()) {
delimiter = m.group(1); // set the new delimiter
} else {
consumer.consume(s);
}
s="";
} else {
state = 0;
}
} else {
if (delimIdx > 0) {
// could push these back onto the inputStream in case the delimiter startsWith a " or -, but that seems a bit fiddly
s = s + delimiter.substring(0, delimIdx); delimIdx = 0;
}
switch(ch) {
case '"' : state = 1; s = s + ch; break;
case '-' : state = 2; break;
case '/' : state = 4; break;
case '\'' : state = 7; s = s + ch; break;
case '\r' :
case '\n' :
// if this is a delimiter command, process it
Matcher m = MYSQL_DELIMITER_COMMAND.matcher(s.trim());
if (m.matches()) {
delimiter = m.group(1); // set the new delimiter
s = ""; delimIdx = 0;
} else {
s = s + ch;
}
break;
case '\\': state = 8; s = s + ch; break;
default: s = s + ch;
}
}
} else if (state==1) {
switch(ch) {
case '"' : state = 0; s = s + ch; break;
case '\\': state = 9; s = s + ch; break;
default: s = s + ch;
}
} else if (state==2) {
switch(ch) {
case '-' : state = 3; break;
default: state = 0; s = s + "-" + ch;
}
} else if (state==3) {
switch(ch) {
case '\r' :
case '\n' :
state = 0;
if (includeComments) { consumer.consume("-- " + c.trim()); }
c=""; break;
default :
c = c + ch;
}
} else if (state==4) {
switch(ch) {
case '*' : state = 5; break;
default: state = 0; s = s + "/" + ch;
}
} else if (state==5) {
switch(ch) {
case '*' : state = 6; break;
default: c = c + ch;
}
} else if (state==6) {
switch(ch) {
case '/' :
state = 0;
if (includeComments) { s += ("/* " + c.trim() + " */"); } // was consumer.consume(...)
c=""; break;
default: c = c + "*" + ch;
}
} else if (state==7) {
switch(ch) {
case '\'' : state = 0; s = s + ch; break;
case '\\' : state = 10; s = s + ch; break;
default: s = s + ch;
}
} else if (state==8) {
// could check ch is printable here, but probably ok
s = s + ch;
state = 0;
} else if (state==9) {
s = s + ch;
state = 1;
} else if (state==10) {
s = s + ch;
state = 7;
}
intch = is.read();
}
if (state==5) {
// unclosed /*-style comment
// ignore for the time being
throw new ParseException("Unclosed /*-style comment before EOF", -1);
} else if (state==1) {
// unclosed quoted string
// ignore for the time being
throw new ParseException("Unclosed double quoted string before EOF", -1);
} else if (state==7) {
// unclosed quoted string
// ignore for the time being
throw new ParseException("Unclosed single quoted string before EOF", -1);
} else if (state==0) {
if (!s.trim().equals("")) {
// unterminated statement at end of InputStream; add to list
consumer.consume(s.trim());
}
}
// return allSql;
}
}
|
3e0e28ed33e13d97d0f6abda7a6d08ff42c47e29 | 1,293 | java | Java | src/main/java/com/murphy/utils/TokenUtils.java | Z-Spring/spring_rabbitmq | 13e6004658f3f7a29add6f8db9649e852888f58b | [
"MIT"
] | null | null | null | src/main/java/com/murphy/utils/TokenUtils.java | Z-Spring/spring_rabbitmq | 13e6004658f3f7a29add6f8db9649e852888f58b | [
"MIT"
] | null | null | null | src/main/java/com/murphy/utils/TokenUtils.java | Z-Spring/spring_rabbitmq | 13e6004658f3f7a29add6f8db9649e852888f58b | [
"MIT"
] | null | null | null | 24.396226 | 71 | 0.631864 | 6,004 | package com.murphy.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.Map;
/**
* token utils
* @author Murphy
*/
@Component
public class TokenUtils {
public static final String TOKEN_KEY = "0-=12hu7^%$0sdaf";
public static String getToken(Map<String, String> claims) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
JWTCreator.Builder builder = JWT.create();
// payload
claims.forEach((k, v) -> {
builder.withClaim(k, v);
});
String token = builder.withExpiresAt(calendar.getTime())
.withSubject("user")
.sign(Algorithm.HMAC256(TOKEN_KEY));
return token;
}
/**
* 验证token合法性
* @return
*/
/* public static void verifyToken( String token){
JWT.require(Algorithm.HMAC256("secret")).build().verify(token);
}*/
/**
* 验证、解析token
* @param token
* @return
*/
public static DecodedJWT decodeToken(String token){
return JWT.decode(token);
}
}
|
3e0e294d6b91f37f7457029da53fa81033865f24 | 12,719 | java | Java | src/main/java/projectzulu/common/mobs/entity/EntityLizardSpit.java | skmedix/ProjectZulu | a6244de9d19b8a44d683880759b84b3bb5778d36 | [
"Apache-2.0"
] | 10 | 2015-01-07T21:29:25.000Z | 2021-09-04T22:22:30.000Z | src/main/java/projectzulu/common/mobs/entity/EntityLizardSpit.java | skmedix/ProjectZulu | a6244de9d19b8a44d683880759b84b3bb5778d36 | [
"Apache-2.0"
] | 5 | 2015-04-16T13:00:41.000Z | 2015-11-30T16:50:37.000Z | src/main/java/projectzulu/common/mobs/entity/EntityLizardSpit.java | skmedix/ProjectXulu | a6244de9d19b8a44d683880759b84b3bb5778d36 | [
"Apache-2.0"
] | 6 | 2015-01-08T21:56:36.000Z | 2020-08-04T09:44:41.000Z | 35.929379 | 217 | 0.581885 | 6,005 | package projectzulu.common.mobs.entity;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class EntityLizardSpit extends Entity
{
private int xTile = -1;
private int yTile = -1;
private int zTile = -1;
private Block inTile;
private boolean inGround = false;
public EntityLivingBase shootingEntity;
private int ticksAlive;
private int ticksInAir = 0;
public double accelerationX;
public double accelerationY;
public double accelerationZ;
public EntityLizardSpit(World par1World)
{
super(par1World);
this.setSize(1.0F, 1.0F);
}
protected void entityInit() {}
/**
* Checks if the entity is in range to render by using the past in distance and comparing it to its average edge
* length * 64 * renderDistanceWeight Args: distance
*/
@Override
public boolean isInRangeToRenderDist(double par1)
{
double var3 = this.boundingBox.getAverageEdgeLength() * 4.0D;
var3 *= 64.0D;
return par1 < var3 * var3;
}
public EntityLizardSpit(World par1World, double par2, double par4, double par6, double par8, double par10, double par12)
{
super(par1World);
this.setSize(1.0F, 1.0F);
this.setLocationAndAngles(par2, par4, par6, this.rotationYaw, this.rotationPitch);
this.setPosition(par2, par4, par6);
double var14 = (double)MathHelper.sqrt_double(par8 * par8 + par10 * par10 + par12 * par12);
this.accelerationX = par8 / var14 * 0.1D;
this.accelerationY = par10 / var14 * 0.1D;
this.accelerationZ = par12 / var14 * 0.1D;
}
public EntityLizardSpit(World par1World, EntityLivingBase par2EntityLiving, double par3, double par5, double par7)
{
super(par1World);
this.shootingEntity = par2EntityLiving;
this.setSize(1.0F, 1.0F);
this.setLocationAndAngles(par2EntityLiving.posX, par2EntityLiving.posY, par2EntityLiving.posZ, par2EntityLiving.rotationYaw, par2EntityLiving.rotationPitch);
this.setPosition(this.posX, this.posY, this.posZ);
this.yOffset = 0.0F;
this.motionX = this.motionY = this.motionZ = 0.0D;
par3 += this.rand.nextGaussian() * 0.4D;
par5 += this.rand.nextGaussian() * 0.4D;
par7 += this.rand.nextGaussian() * 0.4D;
double var9 = (double)MathHelper.sqrt_double(par3 * par3 + par5 * par5 + par7 * par7);
this.accelerationX = par3 / var9 * 0.1D;
this.accelerationY = par5 / var9 * 0.1D;
this.accelerationZ = par7 / var9 * 0.1D;
}
/**
* Called to update the entity's position/logic.
*/
@Override
public void onUpdate()
{
if (!this.worldObj.isRemote && (this.shootingEntity != null && this.shootingEntity.isDead || !this.worldObj.blockExists((int)this.posX, (int)this.posY, (int)this.posZ)))
{
this.setDead();
}
else
{
super.onUpdate();
// this.setFire(1);
if (this.inGround)
{
if (this.worldObj.getBlock(this.xTile, this.yTile, this.zTile) == this.inTile)
{
++this.ticksAlive;
if (this.ticksAlive == 600)
{
this.setDead();
}
return;
}
this.inGround = false;
this.motionX *= (double)(this.rand.nextFloat() * 0.2F);
this.motionY *= (double)(this.rand.nextFloat() * 0.2F);
this.motionZ *= (double)(this.rand.nextFloat() * 0.2F);
this.ticksAlive = 0;
this.ticksInAir = 0;
}
else
{
++this.ticksInAir;
}
Vec3 vec3 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
Vec3 vec31 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec3, vec31);
vec3 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
vec31 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if (movingobjectposition != null)
{
vec31 = Vec3.createVectorHelper(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);
}
Entity entity = null;
List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double d0 = 0.0D;
for (int i = 0; i < list.size(); ++i)
{
Entity entity1 = (Entity)list.get(i);
if (entity1.canBeCollidedWith() && (!entity1.isEntityEqual(this.shootingEntity) || this.ticksInAir >= 25))
{
float f = 0.3F;
AxisAlignedBB axisalignedbb = entity1.boundingBox.expand((double)f, (double)f, (double)f);
MovingObjectPosition movingobjectposition1 = axisalignedbb.calculateIntercept(vec3, vec31);
if (movingobjectposition1 != null)
{
double d1 = vec3.distanceTo(movingobjectposition1.hitVec);
if (d1 < d0 || d0 == 0.0D)
{
entity = entity1;
d0 = d1;
}
}
}
}
if (entity != null)
{
movingobjectposition = new MovingObjectPosition(entity);
}
if (movingobjectposition != null)
{
this.onImpact(movingobjectposition);
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
float f1 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionZ, this.motionX) * 180.0D / Math.PI) + 90.0F;
for (this.rotationPitch = (float)(Math.atan2((double)f1, this.motionY) * 180.0D / Math.PI) - 90.0F; this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float f2 = 0.95f;
if (this.isInWater())
{
for (int j = 0; j < 4; ++j)
{
float f3 = 0.25F;
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * (double)f3, this.posY - this.motionY * (double)f3, this.posZ - this.motionZ * (double)f3, this.motionX, this.motionY, this.motionZ);
}
f2 = 0.8F;
}
this.motionX += this.accelerationX;
this.motionY += this.accelerationY;
this.motionZ += this.accelerationZ;
this.motionX *= (double)f2;
this.motionY *= (double)f2;
this.motionZ *= (double)f2;
this.worldObj.spawnParticle("smoke", this.posX, this.posY + 0.5D, this.posZ, 0.0D, 0.0D, 0.0D);
this.setPosition(this.posX, this.posY, this.posZ);
}
}
/**
* Called when this EntityFireball hits a block or entity.
*/
protected void onImpact(MovingObjectPosition par1MovingObjectPosition)
{
if (!this.worldObj.isRemote)
{
if (par1MovingObjectPosition.entityHit != null)
{
//par1MovingObjectPosition.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.shootingEntity), 6);
if(par1MovingObjectPosition.entityHit instanceof EntityLivingBase){
((EntityLivingBase)par1MovingObjectPosition.entityHit).addPotionEffect(new PotionEffect(Potion.poison.id, 40, 1));
((EntityLivingBase)par1MovingObjectPosition.entityHit).addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 100, 2));
}
}
//this.worldObj.newExplosion((Entity)null, this.posX, this.posY, this.posZ, 1.0F, true);
this.setDead();
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
@Override
public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
{
par1NBTTagCompound.setShort("xTile", (short)this.xTile);
par1NBTTagCompound.setShort("yTile", (short)this.yTile);
par1NBTTagCompound.setShort("zTile", (short)this.zTile);
par1NBTTagCompound.setByte("inTile", (byte)Block.getIdFromBlock(this.inTile));
par1NBTTagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0));
par1NBTTagCompound.setTag("direction", this.newDoubleNBTList(new double[] {this.motionX, this.motionY, this.motionZ}));
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
@Override
public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
{
this.xTile = par1NBTTagCompound.getShort("xTile");
this.yTile = par1NBTTagCompound.getShort("yTile");
this.zTile = par1NBTTagCompound.getShort("zTile");
this.inTile = Block.getBlockById(par1NBTTagCompound.getByte("inTile") & 255);
this.inGround = par1NBTTagCompound.getByte("inGround") == 1;
if (par1NBTTagCompound.hasKey("direction"))
{
NBTTagList var2 = par1NBTTagCompound.getTagList("direction", 6);
this.motionX = var2.func_150309_d(0);
this.motionY = var2.func_150309_d(1);
this.motionZ = var2.func_150309_d(2);
}
else
{
this.setDead();
}
}
/**
* Returns true if other Entities should be prevented from moving through this Entity.
*/
@Override
public boolean canBeCollidedWith()
{
return true;
}
@Override
public float getCollisionBorderSize()
{
return 1.0F;
}
/**
* Called when the entity is attacked.
*/
@Override
public boolean attackEntityFrom(DamageSource par1DamageSource, float par2)
{
this.setBeenAttacked();
if (par1DamageSource.getEntity() != null)
{
Vec3 var3 = par1DamageSource.getEntity().getLookVec();
if (var3 != null)
{
this.motionX = var3.xCoord;
this.motionY = var3.yCoord;
this.motionZ = var3.zCoord;
this.accelerationX = this.motionX * 0.1D;
this.accelerationY = this.motionY * 0.1D;
this.accelerationZ = this.motionZ * 0.1D;
}
if (par1DamageSource.getEntity() instanceof EntityLivingBase)
{
this.shootingEntity = (EntityLivingBase)par1DamageSource.getEntity();
}
return true;
}
else
{
return false;
}
}
@Override
public float getShadowSize()
{
return 0.0F;
}
/**
* Gets how bright this entity is.
*/
@Override
public float getBrightness(float par1)
{
return 1.0F;
}
@Override
public int getBrightnessForRender(float par1)
{
return 15728880;
}
}
|
3e0e29e86e45853f9f0aa9f8a25affb39fe18106 | 1,850 | java | Java | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/EditablePropertyColumn.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/EditablePropertyColumn.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/EditablePropertyColumn.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | 35.576923 | 112 | 0.741622 | 6,006 | /*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.web.component.data.column;
import com.evolveum.midpoint.web.component.input.TextPanel;
import com.evolveum.midpoint.web.component.prism.InputPanel;
import com.evolveum.midpoint.web.component.util.Editable;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
/**
* @author lazyman
*/
public class EditablePropertyColumn<T extends Editable> extends PropertyColumn<T, String> {
public EditablePropertyColumn(IModel<String> displayModel, String propertyExpression) {
super(displayModel, propertyExpression);
}
public EditablePropertyColumn(IModel<String> displayModel, String sortProperty, String propertyExpression) {
super(displayModel, sortProperty, propertyExpression);
}
@Override
public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId,
final IModel<T> rowModel) {
if (!isEditing(rowModel)) {
super.populateItem(cellItem, componentId, rowModel);
} else {
cellItem.add(createInputPanel(componentId, rowModel));
}
}
protected boolean isEditing(IModel<T> rowModel) {
Editable editable = rowModel.getObject();
return editable.isEditing();
}
protected InputPanel createInputPanel(String componentId, IModel<T> model) {
return new TextPanel(componentId, new PropertyModel(model, getPropertyExpression()));
}
}
|
3e0e2c1b1839830eccabd5115ddf503bd6e44033 | 3,846 | java | Java | analyzer-models/src/test/java/ffb/analyzer/models/espn/LeagueInformationTests.java | pecjas/fantasy-football-analyser | 0b89bc351c08b70d8f64d7733a33de713131a7f7 | [
"MIT"
] | null | null | null | analyzer-models/src/test/java/ffb/analyzer/models/espn/LeagueInformationTests.java | pecjas/fantasy-football-analyser | 0b89bc351c08b70d8f64d7733a33de713131a7f7 | [
"MIT"
] | 43 | 2020-04-17T21:42:46.000Z | 2022-02-16T01:09:15.000Z | analyzer-models/src/test/java/ffb/analyzer/models/espn/LeagueInformationTests.java | pecjas/fantasy-football-analyser | 0b89bc351c08b70d8f64d7733a33de713131a7f7 | [
"MIT"
] | 1 | 2020-04-14T22:25:15.000Z | 2020-04-14T22:25:15.000Z | 34.035398 | 111 | 0.706968 | 6,007 | package ffb.analyzer.models.espn;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.junit.Assert;
import ffb.analyzer.core.utilities.DateUtils;
/**
* Unit Tests for {@link LeagueInformation}.
*/
public class LeagueInformationTests extends BaseSerializationTests {
private static final int EXPECTED_WEEK = 16;
private static final int EXPECTED_NUMBER_OF_TEAMS = 12;
private static final int EXPECTED_SCORING_PERIOD = 18;
private static final LocalDate EXPECTED_DATE = LocalDate.of(2020, 1, 1);
private static final List<Integer> PREVIOUS_SEASONS = List.of(
2014,
2015,
2016,
2017,
2018,
2019
);
private static final Map<String, Integer> RAW_EXPECTED_TRANSACTION_COUNT = Map.of(
"2019-08-19T07:41:09.149+0000", 3,
"2019-09-03T07:38:44.151+0000", 1,
"2019-07-03T07:38:44.151+0000", 5
);
private static final Map<LocalDate, Integer> EXPECTED_TRANSACTION_COUNTS;
static {
EXPECTED_TRANSACTION_COUNTS = RAW_EXPECTED_TRANSACTION_COUNT
.entrySet()
.stream()
.collect(Collectors.toMap(entry ->
DateUtils.fromString(entry.getKey(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
Entry::getValue)
);
}
@Override
public void testDeserialization() throws IOException {
LeagueInformation leagueInfo = deserializeSingleObject(LeagueInformation.class);
checkBasicLeagueInformation(leagueInfo);
checkScoringInformation(leagueInfo);
checkTransactionHistory(leagueInfo);
checkPreviousSeasons(leagueInfo);
}
private void checkBasicLeagueInformation(LeagueInformation league) {
Assert.assertEquals(EXPECTED_DATE, league.getActivatedDate());
Assert.assertEquals(LeagueInformation.LeagueType.PRIVATE, league.getCreatedAsType());
Assert.assertEquals(LeagueInformation.LeagueType.PRIVATE, league.getCurrentType());
Assert.assertTrue(league.isActive());
Assert.assertTrue(league.isFull());
Assert.assertTrue(league.isViewable());
Assert.assertFalse(league.isExpired());
Assert.assertFalse(league.getIsToBeDeleted());
Assert.assertEquals(EXPECTED_NUMBER_OF_TEAMS, league.getTeamsJoined());
}
private void checkScoringInformation(LeagueInformation league) {
Assert.assertEquals(EXPECTED_WEEK, league.getCurrentWeek());
Assert.assertEquals(EXPECTED_WEEK, league.getFinalWeek());
Assert.assertEquals(EXPECTED_WEEK, league.getFirstWeek());
Assert.assertEquals(EXPECTED_SCORING_PERIOD, league.getLastScoringPeriod());
Assert.assertEquals(EXPECTED_SCORING_PERIOD, league.getTransactionScoringPeriod());
Assert.assertEquals(EXPECTED_DATE, league.getStandingsUpdateDate());
}
private void checkTransactionHistory(LeagueInformation league) {
Map<LocalDate, Integer> transactions = league.getTransactions();
Assert.assertEquals(EXPECTED_TRANSACTION_COUNTS.size(), transactions.size());
transactions.forEach((key, value) -> Assert.assertEquals(value, EXPECTED_TRANSACTION_COUNTS.get(key)));
}
private void checkPreviousSeasons(LeagueInformation league) {
List<Integer> previousSeasons = league.getPreviousSeasons();
Assert.assertEquals(PREVIOUS_SEASONS.size(), previousSeasons.size());
previousSeasons.forEach(year -> Assert.assertTrue(PREVIOUS_SEASONS.contains(year)));
}
@Override
protected String getResourceFileName() {
return "league-information.json";
}
@Override
protected Class<?> getClassUnderTesting() {
return LeagueInformation.class;
}
}
|
3e0e2c4c11e2ebbb16480d501b09a0e91a9e3ff6 | 6,593 | java | Java | _maratonBook/graphs/SingleSourceShortestPath.java | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | 1 | 2016-02-11T21:28:22.000Z | 2016-02-11T21:28:22.000Z | _maratonBook/graphs/SingleSourceShortestPath.java | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | _maratonBook/graphs/SingleSourceShortestPath.java | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | 22.050167 | 78 | 0.607159 | 6,008 | package graphs;
/*Ya que dikstra no sirve para costos negativos se utiliza bellman ford que
"relaja" los caminos una cantidad de veces, y cuando existe un ciclo negativo
solo se mira si relajando otra vez los caminos se obtiene un camino mas corto
esto da un ciclo.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Locale;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
/*
//Graph in Figure 4.16
5 7
1 0 2
1 2 7
1 4 6
0 2 3
0 3 6
2 3 5
4 3 1
R/DIJKSTRA
SSSP(0, 0) = 0
SSSP(0, 1) = 1000000000
SSSP(0, 2) = 3
SSSP(0, 3) = 6
SSSP(0, 4) = 1000000000
BELLMAN FORD
Negative Cycle Exist? No
y los mismos sssp que dijkstra
// Graph in Figure 4.17, no negative cycle
5 5
0 1 1
0 2 10
1 3 2
2 3 -10
3 4 3
R/DIJKSTRA
SSSP(0, 0) = 0
SSSP(0, 1) = 1
SSSP(0, 2) = 10
SSSP(0, 3) = 0
SSSP(0, 4) = 6
BELLMAN FORD
Negative Cycle Exist? No
y los mismos sssp que dijkstra
// Graph in Figure 4.18, negative cycle exists
3 3
0 1 1000
1 2 15
2 1 -42
*/
public class SingleSourceShortestPath {
private static void dbg(Object... objects) {
System.out.println(Arrays.deepToString(objects));
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new File("grafo.in"));
V = sc.nextInt();
E = sc.nextInt();
AdjList = new ArrayList[V];
for (int i = 0; i < AdjList.length; i++)
AdjList[i] = new ArrayList<Edge>();
for (int i = 0; i < E; i++) {
from = sc.nextInt();
to = sc.nextInt();
w = sc.nextInt();
AdjList[from].add(new Edge(to, w));
}
// SSSP ON UNWEIGHTED GRAPH
// Esta en BFS, con bfs simple y el printpath
// SSSP ON UNWEIGHTED GRAPH END
// DIJKSTRA
System.out.println("DIJKSTRA");
dikstra(0, 3);
// DIJKSTRA END
// BELLMAN FORD
System.out.println("BELLMAN FORD");
bellmanFord(0, V - 1);
// BELLMAN FORD END
// SHORTES PATH FASTER ALGORITHM
// TODO: MALO FALLA PARA EL GRAFO 4.17
System.out.println("SHORTES PATH FASTER ALGORITHM");
shortestPathFasterAlgorithm(0, 3);
// SHORTES PATH FASTER ALGORITHM END
}
// DIJKSTRA HEAP
static int V, E, from, to, s, w;
static ArrayList<Edge>[] AdjList;
static int INF = 1000000000;
static int dist[];
static int p[];
/* Se demora mucho(TLE seguro) para ciclos negativos */
static int dikstra(int inicio, int fin) {
s = inicio;
PriorityQueue<State> pq = new PriorityQueue<State>();
pq.add(new State(s, 0));
dist = new int[V];
Arrays.fill(dist, INF);
p = new int[V];
dist[s] = 0;
p[s] = -1;
while (!pq.isEmpty()) {
State cur = pq.poll();
// if(cur.node==fin) return cur.cost;//cuando solo quiero saber
// el minimo costo de llegar aqui sin
// los demas, PERO SOLO SIRVE PARA COSTOS POSITIVOS
if (dist[cur.node] == cur.cost) {
for (Edge e : AdjList[cur.node]) {
if (dist[cur.node] + e.cost < dist[e.to]) {
dist[e.to] = dist[cur.node] + e.cost;
p[e.to] = cur.node;
pq.add(new State(e.to, cur.cost + e.cost));
}
}
}
}
for (int i = 0; i < V; i++) {// SOLO PARA IMPRIMRIR
System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist[i]);
}
return -1;
}
static void ruta(int fin) {
int cur = fin;
while (cur != -1) {
System.out.printf(" %d", cur);
cur = p[cur];
}
return;
}
// DIJKSTRA HEAP END
// BELLMAN FORD
// static int V, E, from, to, s, w;
// static ArrayList<Edge>[] AdjList;
// static int INF = 1000000000;
// static int dist[];
// static int p[];
private static void bellmanFord(int inicio, int fin) {
s = inicio;
dist = new int[V];
Arrays.fill(dist, INF);
dist[s] = 0;
for (int i = 0; i < V - 1; i++) {
// relax all E edges V-1 times, overall O(VE)
for (int u = 0; u < V; u++) {
// these two loops = O(E)
for (int j = 0; j < (int) AdjList[u].size(); j++) {
Edge v = AdjList[u].get(j); // we can record SP spanning
// here if needed
dist[v.to] = Math.min(dist[v.to], dist[u] + v.cost); // relax
}
}
}
boolean hasNegativeCycle = false;
for (int u = 0; u < V; u++) {
// one more pass to check
for (int j = 0; j < (int) AdjList[u].size(); j++) {
Edge v = AdjList[u].get(j);
if (dist[v.to] > dist[u] + v.cost) { // should be false
hasNegativeCycle = true; // but if true, then negative cycle
// exists!
// (but this shortest paths problem cannot be solved)
}
}
}
System.out.printf("Negative Cycle Exist? %s\n",
hasNegativeCycle ? "Yes" : "No");// SOLO PARA IMPRIMRIR
if (!hasNegativeCycle)// SOLO PARA IMPRIMRI
for (int i = 0; i < V; i++) {
System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist[i]);
}
}
// BELLMAN FORD END
// SHORTES PATH FASTER ALGORITHM
// static int V, E, from, to, s, w;
// static ArrayList<Edge>[] AdjList;
// static int INF = 1000000000;
// static int dist[];
// static int p[];
/* Se pifea para ciclos negativos */
static int shortestPathFasterAlgorithm(int inicio, int fin) {
s = inicio;
Queue<Integer> q = new LinkedList<Integer>();
q.add(s);
dist = new int[V];
Arrays.fill(dist, INF);
p = new int[V];
dist[s] = 0;
p[s] = -1;
while (!q.isEmpty()) {
int cur = q.poll();
// if(cur.node==fin) return cur.cost;//cuando solo quiero saber
// el minimo costo de llegar aqui sin
// los demas, PERO SOLO SIRVE PARA COSTOS POSITIVOS
for (Edge e : AdjList[cur]) {
if (dist[cur] + e.cost < dist[e.to]) {
dist[e.to] = dist[cur] + e.cost;
p[e.to] = cur;
q.add(cur);
}
}
}
for (int i = 0; i < V; i++) {// SOLO PARA IMPRIMRIR
System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist[i]);
}
return -1;
}
// SHORTES PATH FASTER ALGORITHM
// DISKSTRA, SHORTEST FASTER ALGORITM.
static class State implements Comparable<State> {
int node;
int cost;
public State(int node, int cost) {
this.node = node;
this.cost = cost;
}
public int compareTo(State o) {
return cost - o.cost;
}
@Override
public String toString() {
return "State [node=" + node + ", cost=" + cost + "]";
}
}
// END
// BELLMAN FORD, DISKSTRA, SHORTEST FASTER ALGORITM.
static class Edge {
int to, cost;
public Edge(int toIn, int valueIn) {
to = toIn;
cost = valueIn;
}
@Override
public String toString() {
return "pair [to=" + to + ", _second=" + cost + "]";
}
}
// END
}
|
3e0e2cfb72a0bc4c3e9afddbe782c00aa5e64990 | 28,621 | java | Java | src/org/opengts/war/track/page/AccountLogin.java | GBPA/OpenGTS | 0514678a0af234449f49241d075bddd27f13b2fe | [
"Apache-2.0"
] | 4 | 2018-01-08T13:06:58.000Z | 2018-05-10T13:18:16.000Z | src/org/opengts/war/track/page/AccountLogin.java | GBPA/OpenGTS | 0514678a0af234449f49241d075bddd27f13b2fe | [
"Apache-2.0"
] | null | null | null | src/org/opengts/war/track/page/AccountLogin.java | GBPA/OpenGTS | 0514678a0af234449f49241d075bddd27f13b2fe | [
"Apache-2.0"
] | 3 | 2019-06-05T06:25:10.000Z | 2021-10-12T05:50:49.000Z | 50.567138 | 239 | 0.526012 | 6,009 | // ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/06/03 Martin D. Flynn
// -Added I18N support
// 2007/06/13 Martin D. Flynn
// -Added support for browsers with disabled cookies
// 2007/07/27 Martin D. Flynn
// -Added 'getNavigationTab(...)'
// 2007/12/13 Martin D. Flynn
// -Changed form target to '_self' for "ContentOnly" display
// 2008/12/01 Martin D. Flynn
// -Increased maxsize for account/user/password fields to match length specified
// in their respective tables.
// 2009/01/01 Martin D. Flynn
// -Added popup 'alert' for login errors
// 2009/04/11 Martin D. Flynn
// -Added focus on login field
// -Added support for hiding the "Password" field on the login page
// 2013/08/27 Martin D. Flynn
// -Added support for returning to SysAdmin/Manager originator (if applicable)
// ----------------------------------------------------------------------------
package org.opengts.war.track.page;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
import org.opengts.db.tables.*;
import org.opengts.war.tools.*;
import org.opengts.war.track.*;
public class AccountLogin
extends WebPageAdaptor
implements Constants
{
// ------------------------------------------------------------------------
// Tomcat conf/server.xml
// emptySessionPath="true"
// <SessionId cookiesFirst="true" noCookies="true"/>
// HttpServletResponse.encodeURL()
// ------------------------------------------------------------------------
private static String FORM_LOGIN = "Login";
private static String FORM_DEMO = "Demo";
// ------------------------------------------------------------------------
private static final String CSS_ACCOUNT_LOGIN[] = new String[] { "accountLoginTable", "accountLoginCell" };
private static final String CSS_LOGIN_CONTENT_TABLE = "accountLoginContentTable";
public static final String CSS_LOGIN_VSEP_CELL = "accountLoginVertSepCell";
public static final String CSS_LOGIN_TEXT_CELL = "accountLoginTextCell";
public static final String CSS_LOGIN_FORM_TABLE = "accountLoginFormTable";
// ------------------------------------------------------------------------
// Properties
public static final String PROP_customLoginUrl = "customLoginUrl";
public static final String PROP_VSeparatorImage = "VSeparatorImage.path";
public static final String PROP_VSeparatorImage_W = "VSeparatorImage.width";
public static final String PROP_VSeparatorImage_H = "VSeparatorImage.height";
public static final String PROP_PlaceholderLabelOnly = "PlaceholderLabelOnly";
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// WebPage interface
public AccountLogin()
{
this.setBaseURI(RequestProperties.TRACK_BASE_URI());
super.setPageName(PAGE_LOGIN); // 'super' required here
this.setPageNavigation(new String[] { PAGE_LOGIN });
this.setLoginRequired(false);
}
// ------------------------------------------------------------------------
public void setPageName(String pageName)
{
// -- ignore (changing the PAGE_LOGIN name is not allowed)
}
// ------------------------------------------------------------------------
public String getCustomLoginURL()
{
return this.getProperties().getString(PROP_customLoginUrl,null);
}
public boolean hasCustomLoginURL()
{
return !StringTools.isBlank(this.getCustomLoginURL());
}
public URIArg getPageURI(String command, String cmdArg)
{
String loginURL = this.getCustomLoginURL();
if (!StringTools.isBlank(loginURL)) {
//Print.logInfo("Login custom URL: " + loginURL);
//Print.logStackTrace("here");
return new URIArg(loginURL);
} else {
return super.getPageURI(command, cmdArg);
}
}
public String getJspURI()
{
return super.getJspURI();
}
// ------------------------------------------------------------------------
public String getMenuName(RequestProperties reqState)
{
return "";
}
public String getMenuDescription(RequestProperties reqState, String parentMenuName)
{
PrivateLabel privLabel = reqState.getPrivateLabel();
I18N i18n = privLabel.getI18N(AccountLogin.class);
return super._getMenuDescription(reqState,i18n.getString("AccountLogin.menuDesc","Logout"));
}
public String getMenuHelp(RequestProperties reqState, String parentMenuName)
{
PrivateLabel privLabel = reqState.getPrivateLabel();
I18N i18n = privLabel.getI18N(AccountLogin.class);
return super._getMenuHelp(reqState,i18n.getString("AccountLogin.menuHelp","Logout"));
}
// ------------------------------------------------------------------------
public String getNavigationDescription(RequestProperties reqState)
{
PrivateLabel privLabel = reqState.getPrivateLabel();
I18N i18n = privLabel.getI18N(AccountLogin.class);
if (reqState.isLoggedIn()) {
if (reqState.isReturnToSysAdminEnabled()) {
HttpServletRequest req = reqState.getHttpServletRequest();
String saAcctID = AttributeTools.getSessionString(req,Constants.PARM_SA_RELOGIN_ACCT,"?");
return i18n.getString("AccountLogin.navDescReturn","Return to {0}", saAcctID);
} else {
return i18n.getString("AccountLogin.navDesc","Logout");
}
} else
if (privLabel.getBooleanProperty(PrivateLabel.PROP_AccountLogin_showLoginLink,true)) {
return i18n.getString("AccountLogin.navDesc.login","Login");
} else {
return super._getNavigationDescription(reqState,"");
}
}
public String getNavigationTab(RequestProperties reqState)
{
PrivateLabel privLabel = reqState.getPrivateLabel();
I18N i18n = privLabel.getI18N(AccountLogin.class);
return i18n.getString("AccountLogin.navTab","Logout");
}
// ------------------------------------------------------------------------
public boolean isOkToDisplay(RequestProperties reqState)
{
PrivateLabel privLabel = (reqState != null)? reqState.getPrivateLabel() : null;
if (privLabel == null) {
// no PrivateLabel?
return false;
} else
if (!privLabel.getShowPassword()) {
// Password is hidden, don't show the "Change Password" page
return false;
} else {
// show "Change Password"
return true;
}
}
// ------------------------------------------------------------------------
public void writePage(
final RequestProperties reqState,
String pageMsg)
throws IOException
{
final PrivateLabel privLabel = reqState.getPrivateLabel();
final I18N i18n = privLabel.getI18N(AccountLogin.class);
final String HR = "";
/* custom login banner image (roughly 300px wide) */
final String banner300Image;
final boolean showLogin300Banner;
final boolean showLogin300BannerTitle;
if (StringTools.parseBoolean(reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_banner300_show,null,null),false)) {
// -- show login banner300 image
String bannerImg = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_banner300_image,null,null);
if (StringTools.isBlank(bannerImg)) {
bannerImg = reqState.getKeyValue(PrivateLabel.PROP_Banner_imageSource,null,null);
}
// --
if (!StringTools.isBlank(bannerImg)) {
// -- found a banner image
banner300Image = bannerImg;
showLogin300Banner = true;
} else {
// -- no banner image found
banner300Image = null;
showLogin300Banner = false;
}
} else {
// -- do not show banner300 image?
String bannerImg = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_banner300_image,null,null);
if (!StringTools.isBlank(bannerImg)) {
// -- found a banner image, show anyway
banner300Image = bannerImg;
showLogin300Banner = true;
} else {
// -- no banner image found
banner300Image = null;
showLogin300Banner = false;
}
}
// --
if (!showLogin300Banner) {
// -- no banner300 image, no title
showLogin300BannerTitle = false;
} else
if (StringTools.parseBoolean(reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_banner300_includeTitle,null,null),false)) {
// -- expressly want the banner300 title
showLogin300BannerTitle = true;
} else {
// -- do not want the banner300 title
showLogin300BannerTitle = false;
}
/* Style */
HTMLOutput HTML_CSS = new HTMLOutput() {
public void write(PrintWriter out) throws IOException {
String cssDir = AccountLogin.this.getCssDirectory();
//WebPageAdaptor.writeCssLink(out, reqState, "AccountLogin.css", cssDir);
// -- Login page background image? (ie "./extra/images/texture/Clouds.png")
String bgImage = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_background_image , null, null );
String bgSize = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_background_size , null, "cover" );
String bgPosition = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_background_position , null, "center top");
String bgRepeat = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_background_repeat , null, "no-repeat" );
String bgAttach = reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_background_attachment, null, "fixed" );
out.write(" <!-- AcountLogin custom CSS -->\n");
out.write(" <style type='text/css'>\n");
if (!StringTools.isBlank(bgImage)) {
// -- override body background image with custom login page image
out.write(" BODY {\n");
out.write(" background-image: url('"+bgImage +"');\n");
out.write(" background-size: " +bgSize +";\n");
out.write(" background-position: " +bgPosition+";\n");
out.write(" background-repeat: " +bgRepeat +";\n");
out.write(" background-attachment: "+bgAttach +";\n");
out.write(" }\n");
out.write(" TABLE.bodyTable {\n");
out.write(" background-color: rgba(255,255,255,0.0);\n"); // transparent
out.write(" }\n");
}
if (showLogin300Banner) {
out.write(" .accountLoginTable {\n");
out.write(" margin-top: 0px;\n");
out.write(" }\n");
out.write(" TABLE.accountLoginContentTable {\n");
out.write(" background-color: rgba(255,255,255,0.6);\n");
out.write(" }\n");
}
out.write(" </style>\n");
}
};
/* write frame */
String cssAccountLogin[] = CSS_ACCOUNT_LOGIN;
HTMLOutput HTML_CONTENT = new HTMLOutput(cssAccountLogin, pageMsg) {
public String getContentAlign() {
// -- also "LoginBackground.image"
//String ca = StringTools.trim(privLabel.getStringProperty(PrivateLabel.PROP_AccountLogin_contentAlign,""));
String ca = StringTools.trim(reqState.getKeyValue(PrivateLabel.PROP_AccountLogin_contentAlign,null,null));
if (ca.equalsIgnoreCase("left") ||
ca.equalsIgnoreCase("center") ||
ca.equalsIgnoreCase("right") ) {
return ca;
} else {
return showLogin300Banner? "right" : "center";
}
}
public void write(PrintWriter out) throws IOException {
PrivateLabel privLabel = reqState.getPrivateLabel();
RTProperties acctRTP = AccountLogin.this.getProperties();
// -- baseURL
URIArg baseURI = MakeURL(RequestProperties.TRACK_BASE_URI(),null,null,null);
HttpServletRequest req = reqState.getHttpServletRequest();
String rtpArg = (req != null)? req.getParameter(AttributeTools.ATTR_RTP) : null;
if (!StringTools.isBlank(rtpArg)) { baseURI.addArg(AttributeTools.ATTR_RTP,rtpArg); }
String baseURL = EncodeURL(reqState, baseURI);
String accountID = StringTools.trim(AccountRecord.getFilteredID(AttributeTools.getRequestString(req,Constants.PARM_ACCOUNT,"")));
String userID = StringTools.trim(AccountRecord.getFilteredID(AttributeTools.getRequestString(req,Constants.PARM_USER ,"")));
// -- other args
String newURL = privLabel.hasWebPage(PAGE_ACCOUNT_NEW )?
//EncodeMakeURL(reqState,RequestProperties.TRACK_BASE_URI(),PAGE_ACCOUNT_NEW ) : null;
privLabel.getWebPageURL(reqState,PAGE_ACCOUNT_NEW) : null;
String forgotURL = privLabel.hasWebPage(PAGE_PASSWD_EMAIL)?
//EncodeMakeURL(reqState,RequestProperties.TRACK_BASE_URI(),PAGE_PASSWD_EMAIL) : null;
privLabel.getWebPageURL(reqState,PAGE_PASSWD_EMAIL) : null;
boolean acctLogin = privLabel.getAccountLogin();
boolean userLogin = privLabel.getUserLogin();
boolean emailLogin = privLabel.getAllowEmailLogin();
boolean showPasswd = reqState.getShowPassword();
boolean showLocale = reqState.showLocaleSelection(); // <-- also examines override properties
boolean showDemo = reqState.getEnableDemo();
String target = "_self"; // reqState.getPageFrameContentOnly()? "_self" : "_top"; // target='_top'
boolean loginOK = privLabel.getBooleanProperty(BasicPrivateLabelLoader.ATTR_allowLogin, true);
String ro = loginOK? "" : "readonly";
// ----------------------------------
// Basic login input form:
// <form name="login" method="post" action="http://track.example.com:8080/track/Track" target="_top">
// Account: <input name="account" type="text" size='20' maxlength='32' placeholder='Account' > <br>
// User: <input name="user" type="text" size='20' maxlength='32' placeholder='User' > <br>
// Password: <input name="password" type="password" size='20' maxlength='32' placeholder='Password'> <br>
// <input type="submit" name="submit" value="Login">
// </form>
// -- start LoginTable
out.print("<table class='"+CSS_LOGIN_CONTENT_TABLE+"' cellpadding='0' cellspacing='0' border='0'");
out.print(" width='100%'");
out.print(">\n");
// -- top image row
if (showLogin300Banner) {
// -- JSP "nobanner" is expected
out.println("<tr class='banner300ImageRow'>");
out.println(" <td class='banner300ImageCell' colSpan='2'>");
if (showLogin300BannerTitle) {
out.println(" <span class='banner300ImageTitle'>"+privLabel.getPageTitle()+"</span><br>");
}
out.println(" <img src='"+banner300Image+"'/>"); // width='300' />");
out.println(" </td>");
out.println("</tr>");
}
// -- start LoginTable/AccountUserPasswordContentRow
out.println("<tr class='accountUserPasswordContentRow'>");
// -- vertical separator (optional)
String vSepImg = acctRTP.getString(PROP_VSeparatorImage,"./images/VSep_DBlue.png");
if (!StringTools.isBlank(vSepImg)) {
String W = acctRTP.getString(PROP_VSeparatorImage_W,"8");
String H = acctRTP.getString(PROP_VSeparatorImage_H,"300");
out.print("<td class='"+CSS_LOGIN_VSEP_CELL+"'>");
out.print("<img ");
if (!StringTools.isBlank(W)) { out.print(" width='"+W+"'"); }
if (!StringTools.isBlank(H)) { out.print(" height='"+H+"'"); }
out.print(" src='"+vSepImg+"'/>");
out.print("</td>");
}
// -- start AccountUserPasswordCell
out.println("<td class='"+CSS_LOGIN_TEXT_CELL+"'>");
// -- "Please Log In"
String enterLoginText_ = showPasswd? // not used
i18n.getString("AccountLogin.enterLogin","Enter your Login ID and Password") :
i18n.getString("AccountLogin.enterLoginNoPass","Enter Login ID (No Password Required)");
String enterLoginText = i18n.getString("AccountLogin.pleaseLogIn","Please Log In");
out.println("<h1>"+enterLoginText+"</h1>");
// -- Account/User/Password form/table
out.println("<form name='"+FORM_LOGIN+"' method='post' class='form-horizontal' action='"+baseURL+"' target='"+target+"'>");
out.println(" <table class='"+CSS_LOGIN_FORM_TABLE+" table' cellpadding='0' cellspacing='0' border='0'>");
String focusFieldID = "";
// -- Account login field
// - "placeholderOnly" specifies that the field label should only use the "placeholder" attribute
boolean placeholderOnly = acctRTP.getBoolean(PROP_PlaceholderLabelOnly,false);
if (acctLogin) {
String fldID = "accountLoginField";
String text_ = i18n.getString("AccountLogin.account","Account:");
String text = text_.endsWith(":")?text_.substring(0,text_.length()-1):text_;
out.print(" <tr>");
if (!placeholderOnly) {
out.print( "<td class='accountLoginFieldLabel' style='font-weight: 500;'>"+text_+"</td>");
}
out.print( "<td class='accountLoginFieldValue'>");
out.print( "<input id='"+fldID+"' class='"+CommonServlet.CSS_TEXT_INPUT+" form-control' type='text' "+ro+" name='"+Constants.PARM_ACCOUNT+"' value='"+accountID+"' placeholder='"+text+"' size='32' maxlength='32'>");
out.print( "</td>");
out.print( "</tr>\n");
focusFieldID = fldID;
}
// -- User/EMail login field
if (userLogin && emailLogin) {
String fldID = "userLoginField";
String text_ = i18n.getString("AccountLogin.userEmail","User/EMail:");
String text = text_.endsWith(":")?text_.substring(0,text_.length()-1):text_;
out.print(" <tr>");
if (!placeholderOnly) {
out.print( "<td class='accountLoginFieldLabel' style='font-weight: 500;'>"+text_+"</td>");
}
out.print( "<td class='accountLoginFieldValue'>");
out.print( "<input id='"+fldID+"' class='"+CommonServlet.CSS_TEXT_INPUT+" form-control' type='text' "+ro+" name='"+Constants.PARM_USER+"' value='"+userID+"' placeholder='"+text+"' size='32' maxlength='40'>");
out.print( "</td>");
out.print( "</tr>\n");
if (StringTools.isBlank(focusFieldID)) { focusFieldID = fldID; }
} else
if (userLogin) {
String fldID = "userLoginField";
String text_ = i18n.getString("AccountLogin.user","User:");
String text = text_.endsWith(":")?text_.substring(0,text_.length()-1):text_;
out.print(" <tr>");
if (!placeholderOnly) {
out.print( "<td class='accountLoginFieldLabel' style='font-weight: 500;'>"+text_+"</td>");
}
out.print( "<td class='accountLoginFieldValue'>");
out.print( "<input id='"+fldID+"' class='"+CommonServlet.CSS_TEXT_INPUT+" form-control' type='text' "+ro+" name='"+Constants.PARM_USER+"' value='"+userID+"' placeholder='"+text+"' size='32' maxlength='32'>");
out.print( "</td>");
out.print( "</tr>\n");
if (StringTools.isBlank(focusFieldID)) { focusFieldID = fldID; }
} else
if (emailLogin) {
String fldID = "emailLoginField";
String text_ = i18n.getString("AccountLogin.email","EMail:");
String text = text_.endsWith(":")?text_.substring(0,text_.length()-1):text_;
out.print(" <tr>");
if (!placeholderOnly) {
out.print( "<td class='accountLoginFieldLabel' style='font-weight: 500;'>"+text_+"</td>");
}
out.print( "<td class='accountLoginFieldValue'>");
out.print( "<input id='"+fldID+"' class='"+CommonServlet.CSS_TEXT_INPUT+" form-control' type='text' "+ro+" name='"+Constants.PARM_USEREMAIL+"' value='"+userID+"' placeholder='"+text+"' size='32' maxlength='40'>");
out.print( "</td>");
out.print( "</tr>\n");
if (StringTools.isBlank(focusFieldID)) { focusFieldID = fldID; }
}
// -- Password field
if (showPasswd) {
String text_ = i18n.getString("AccountLogin.password","Password:");
String text = text_.endsWith(":")?text_.substring(0,text_.length()-1):text_;
out.print(" <tr>");
if (!placeholderOnly) {
out.print( "<td class='accountLoginFieldLabel' style='font-weight: 500;'>"+text_+"</td>");
}
out.print( "<td class='accountLoginFieldValue'>");
out.print( "<input class='"+CommonServlet.CSS_TEXT_INPUT+" form-control' type='password' "+ro+" name='"+Constants.PARM_PASSWORD+"' value='' placeholder='"+text+"' size='32' maxlength='32'>");
out.print( "</td>");
out.print( "</tr>\n");
}
// -- Language selection
if (showLocale) {
String dftLocale = privLabel.getLocaleString();
String text_ = i18n.getString("AccountLogin.language","Language:");
String text = text_.endsWith(":")?text_.substring(0,text_.length()-1):text_;
Map<String,String> localeMap = BasicPrivateLabel.GetSupportedLocaleMap(privLabel.getLocale());
ComboMap comboLocaleMap = new ComboMap(localeMap);
out.print(" <tr>");
if (!placeholderOnly) {
out.print( "<td class='accountLoginFieldLabel' style='font-weight: 500;'>"+text_+"</td>");
}
out.print( "<td class='accountLoginFieldValue'>");
out.write( Form_ComboBox(CommonServlet.PARM_LOCALE, CommonServlet.PARM_LOCALE, true, comboLocaleMap, dftLocale, null/*onchange*/));
out.print( "</td>");
out.print( "</tr>\n");
}
// -- end Account/User/Password table
out.print("</table>\n");
// -- Login
out.print("<br>");
out.print("<input type='submit' class='btn btn-success' name='submit' value='"+i18n.getString("AccountLogin.login","Login")+"' >\n");
// -- end Account/User/Password forn
out.println("</form>");
// -- Demo button
if (showDemo) {
out.println(HR);
//out.println("<br/>");
out.println("<form class='form-horizontal' name='"+FORM_DEMO+"' method='post' action='"+baseURL+"' target='"+target+"'>");
out.println(" <input type='hidden' name='"+Constants.PARM_ACCOUNT +"' value='"+reqState.getDemoAccountID()+"'/>");
out.println(" <input type='hidden' name='"+Constants.PARM_USER +"' value=''/>");
out.println(" <input type='hidden' name='"+Constants.PARM_PASSWORD +"' value=''/>");
out.println(" <span style=';padding-right:5px;'>"+i18n.getString("AccountLogin.freeDemo","Click here for a Demo")+"</span>");
out.println(" <input type='submit' name='submit' value='"+i18n.getString("AccountLogin.demo","Demo")+"'>");
out.println("</form>");
//out.println("<br/>");
}
// -- New Account
if (newURL != null) {
}
// -- end AccountUserPasswordCell
out.println("</td>");
// -- end LoginTable/AccountUserPasswordContentRow
out.println("</tr>");
// -- end LoginTable
out.println("</table>");
/* set focus */
if (!StringTools.isBlank(focusFieldID)) {
out.write("<script type=\"text/javascript\">\n");
out.write("var loginFocusField = document.getElementById('"+focusFieldID+"');\n");
out.write("if (loginFocusField) {\n");
out.write(" loginFocusField.focus();\n");
out.write(" loginFocusField.select();\n");
out.write("}\n");
out.write("</script>\n");
}
}
};
/* write frame */
String onload = (!StringTools.isBlank(pageMsg) && reqState._isLoginErrorAlert())? JS_alert(true,pageMsg) : null;
CommonServlet.writePageFrame(
reqState,
onload,null, // onLoad/onUnload
HTML_CSS, // Style sheets
HTMLOutput.NOOP, // JavaScript
null, // Navigation
HTML_CONTENT); // Content
}
// ------------------------------------------------------------------------
}
|
3e0e2d0ee4c2f16335f77e398af05f08f95b79e3 | 5,922 | java | Java | src/com/ipac/quickblend/ImagePanel.java | Jon-Crow/QuickBlend | 0a95d85098dc46a5e34362fd84352254c920a72a | [
"Apache-2.0"
] | null | null | null | src/com/ipac/quickblend/ImagePanel.java | Jon-Crow/QuickBlend | 0a95d85098dc46a5e34362fd84352254c920a72a | [
"Apache-2.0"
] | null | null | null | src/com/ipac/quickblend/ImagePanel.java | Jon-Crow/QuickBlend | 0a95d85098dc46a5e34362fd84352254c920a72a | [
"Apache-2.0"
] | null | null | null | 31.168421 | 154 | 0.599122 | 6,010 | package com.ipac.quickblend;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
/**
* Displays a slideshow of images
* @author Jonathan Crow
* @deprecated Ugly. Use NewImagePanel
*/
@Deprecated
public class ImagePanel extends JPanel implements ActionListener, Updateable, Initializable, Saveable
{
private static ImageIcon[] images = {getImage("SAE_J300"),getImage("SAE_J306"),
getImage("ISO_Viscosity_Grades"),getImage("Comparison_Of_Viscosity_Classifications"),
getImage("Base_Stock_Viscosities"),getImage("Common_Conversions"),getImage("Conversions"),
getImage("Shear_Stability_Calculations")};
private JButton prevBtn, nextBtn;
private JSlider scale;
private int imgIndex = 0;
private long lastMove;
public ImagePanel()
{
setLayout(new MigLayout());
MouseAdapter mouse = new MouseAdapter()
{
public void mouseMoved(MouseEvent event)
{
prevBtn.setVisible(true);
nextBtn.setVisible(true);
scale.setVisible(true);
lastMove = System.currentTimeMillis();
}
public void mouseDragged(MouseEvent event)
{
mouseMoved(event);
}
};
InputMap input = getInputMap(JPanel.WHEN_FOCUSED);
ActionMap actions = getActionMap();
input.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "next");
input.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "prev");
actions.put("next", new AbstractAction()
{
public void actionPerformed(ActionEvent event)
{
nextBtn.doClick();
}
});
actions.put("prev", new AbstractAction()
{
public void actionPerformed(ActionEvent event)
{
prevBtn.doClick();
}
});
add((prevBtn = new JButton("<")));
prevBtn.addActionListener(this);
prevBtn.addMouseMotionListener(mouse);
add((nextBtn = new JButton(">")), "wrap");
nextBtn.addActionListener(this);
nextBtn.addMouseMotionListener(mouse);
add((scale = new JSlider(5,20,10)),"span 2, center");
scale.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
updateImage();
}
});
scale.addMouseMotionListener(mouse);
addMouseMotionListener(mouse);
updateImage();
lastMove = System.currentTimeMillis();
}
private void updateImage()
{
JInternalFrame frame = Main.getEnclosingFrame(this);
if(frame != null) frame.setTitle(images[imgIndex].getDescription());
}
@Override
public void init(JInternalFrame frame)
{
frame.setTitle(images[imgIndex].getDescription());
try
{
frame.setMaximum(true);
}
catch(Exception error)
{
Main.logError("could not maximize window", error);
}
}
@Override
public Dimension getPreferredSize()
{
double s = (double)scale.getValue()/10;
return new Dimension((int)(images[imgIndex].getIconWidth()*s+0.5),(int)(images[imgIndex].getIconHeight()*s+0.5));
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
double s = (double)scale.getValue()/10;
g.drawImage(images[imgIndex].getImage(), 0, 0, (int)(images[imgIndex].getIconWidth()*s+0.5), (int)(images[imgIndex].getIconHeight()*s+0.5), this);
}
@Override
public void update(int delta)
{
if(System.currentTimeMillis()-lastMove > 250)
{
prevBtn.setVisible(false);
nextBtn.setVisible(false);
scale.setVisible(false);
}
}
@Override
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == prevBtn)
{
imgIndex--;
if(imgIndex < 0) imgIndex = images.length-1;
}
else if(event.getSource() == nextBtn)
{
imgIndex++;
if(imgIndex >= images.length) imgIndex = 0;
}
updateImage();
lastMove = System.currentTimeMillis();
}
@Override
public void putData(HashMap<String, String> data)
{
data.put("imgIndex", imgIndex+"");
data.put("scale", scale.getValue()+"");
}
@Override
public void loadData(HashMap<String, String> data)
{
if(data.containsKey("imgIndex"))
{
try
{
imgIndex = Integer.parseInt(data.get("imgIndex"));
}
catch(Exception error)
{}
}
if(data.containsKey("scale"))
{
try
{
scale.setValue(Integer.parseInt(data.get("scale")));
}
catch(Exception error)
{}
}
}
private static ImageIcon getImage(String path)
{
ImageIcon img = Main.loadImageResource("res/img/tables/" + path + ".png");
img.setDescription(path.replace("_"," "));
return img;
}
} |
3e0e2d58fd7be988861f05633f354d367979f30c | 12,264 | java | Java | services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexScanTest.java | Bennett-Lynch/aws-sdk-java-v2 | 6282ed73eca3a1f15a78e259da2d8d0ded13d94f | [
"Apache-2.0"
] | 1,467 | 2017-06-28T17:47:37.000Z | 2022-03-30T15:41:29.000Z | services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexScanTest.java | Bennett-Lynch/aws-sdk-java-v2 | 6282ed73eca3a1f15a78e259da2d8d0ded13d94f | [
"Apache-2.0"
] | 2,520 | 2017-06-28T21:51:51.000Z | 2022-03-31T23:49:59.000Z | services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexScanTest.java | Bennett-Lynch/aws-sdk-java-v2 | 6282ed73eca3a1f15a78e259da2d8d0ded13d94f | [
"Apache-2.0"
] | 703 | 2017-06-28T17:57:09.000Z | 2022-03-24T21:42:20.000Z | 42.881119 | 120 | 0.581784 | 6,011 | /*
* Copyright 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://aws.amazon.com/apache2.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 software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
public class IndexScanTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
private String gsiId;
private Integer gsiSort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
private Integer getValue() {
return value;
}
private Record setValue(Integer value) {
this.value = value;
return this;
}
private String getGsiId() {
return gsiId;
}
private Record setGsiId(String gsiId) {
this.gsiId = gsiId;
return this;
}
private Integer getGsiSort() {
return gsiSort;
}
private Record setGsiSort(Integer gsiSort) {
this.gsiSort = gsiSort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value) &&
Objects.equals(gsiId, record.gsiId) &&
Objects.equals(gsiSort, record.gsiSort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value, gsiId, gsiSort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.addAttribute(String.class, a -> a.name("gsi_id")
.getter(Record::getGsiId)
.setter(Record::setGsiId)
.tags(secondaryPartitionKey("gsi_keys_only")))
.addAttribute(Integer.class, a -> a.name("gsi_sort")
.getter(Record::getGsiSort)
.setter(Record::setGsiSort)
.tags(secondarySortKey("gsi_keys_only")))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record()
.setId("id-value")
.setSort(i)
.setValue(i)
.setGsiId("gsi-id-value")
.setGsiSort(i))
.collect(Collectors.toList());
private static final List<Record> KEYS_ONLY_RECORDS =
RECORDS.stream()
.map(record -> new Record()
.setId(record.id)
.setSort(record.sort)
.setGsiId(record.gsiId)
.setGsiSort(record.gsiSort))
.collect(Collectors.toList());
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only");
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)));
}
@BeforeEach
public void createTable() {
mappedTable.createTable(
r -> r.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(
EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_keys_only")
.projection(p -> p.projectionType(ProjectionType.KEYS_ONLY))
.provisionedThroughput(getDefaultProvisionedThroughput())
.build()));
}
@AfterEach
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void scanAllRecordsDefaultSettings() {
insertRecords();
Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().build()).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(KEYS_ONLY_RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("sort >= :min_value AND sort <= :max_value")
.expressionValues(expressionValues)
.build();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(),
is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanLimit() {
insertRecords();
Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(r -> r.limit(5)).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page1 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page2 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page3 = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4)));
assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9)));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanEmpty() {
Iterator<Page<Record>> results = keysOnlyMappedIndex.scan().iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanExclusiveStartKey() {
insertRecords();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
private Map<String, AttributeValue> getKeyMap(int sort) {
Map<String, AttributeValue> result = new HashMap<>();
result.put("id", stringValue(KEYS_ONLY_RECORDS.get(sort).getId()));
result.put("sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getSort()));
result.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(sort).getGsiId()));
result.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getGsiSort()));
return Collections.unmodifiableMap(result);
}
}
|
3e0e2e279e3c9f4acab1ad196a3b4818197b575f | 1,897 | java | Java | src/main/java/com/mingzuozhibi/support/SpiderUtils.java | mingzuozhibi/mzzb-spider | b215dad40e8ac6087a022db70a85bf454800fe6b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mingzuozhibi/support/SpiderUtils.java | mingzuozhibi/mzzb-spider | b215dad40e8ac6087a022db70a85bf454800fe6b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mingzuozhibi/support/SpiderUtils.java | mingzuozhibi/mzzb-spider | b215dad40e8ac6087a022db70a85bf454800fe6b | [
"Apache-2.0"
] | null | null | null | 32.152542 | 84 | 0.597786 | 6,012 | package com.mingzuozhibi.support;
import com.mingzuozhibi.commons.domain.Result;
import io.webfolder.cdp.session.SessionFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.Random;
import static com.mingzuozhibi.support.SpiderCdp4j.waitResultCdp4j;
import static com.mingzuozhibi.support.SpiderJsoup.waitResultJsoup;
@Slf4j
public abstract class SpiderUtils {
public static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/99.0.4844.74 Safari/537.36 " +
"Edg/99.0.1150.46";
public static Result<String> waitResult(SessionFactory factory, String asin) {
String url = buildUrl(asin);
log.debug("{}: {}", asin, url);
Result<String> result;
if (factory != null) {
result = waitResultCdp4j(factory, url);
} else {
result = waitResultJsoup(url);
}
if (result.isSuccess() && StringUtils.isEmpty(result.getData())) {
return Result.ofError(String.format("抓取碟片[%s]:结果为空", asin));
}
return result;
}
public static String buildUrl(String asin) {
return "https://www.amazon.co.jp/" + randomWord(25) + "/dp/" + asin + "/?" +
randomWord(5) + "=" + randomWord(3) + "&" +
"language=ja_JP&" +
randomWord(6) + "=" + randomWord(4) + "&" +
"_encoding=UTF8&" +
randomWord(3) + "=" + randomWord(5);
}
private static String randomWord(int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append(randomChar());
}
return builder.toString();
}
private static char randomChar() {
return (char) (new Random().nextInt(26) + 'a');
}
}
|
3e0e2e99c8cfe9d12d917eba347c1dfe6c09e175 | 3,832 | java | Java | aws-java-sdk-chime/src/main/java/com/amazonaws/services/chime/model/DeleteVoiceConnectorOriginationRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-chime/src/main/java/com/amazonaws/services/chime/model/DeleteVoiceConnectorOriginationRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-chime/src/main/java/com/amazonaws/services/chime/model/DeleteVoiceConnectorOriginationRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 30.656 | 134 | 0.652662 | 6,013 | /*
* Copyright 2016-2021 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://aws.amazon.com/apache2.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.amazonaws.services.chime.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/chime-2018-05-01/DeleteVoiceConnectorOrigination"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteVoiceConnectorOriginationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Chime Voice Connector ID.
* </p>
*/
private String voiceConnectorId;
/**
* <p>
* The Amazon Chime Voice Connector ID.
* </p>
*
* @param voiceConnectorId
* The Amazon Chime Voice Connector ID.
*/
public void setVoiceConnectorId(String voiceConnectorId) {
this.voiceConnectorId = voiceConnectorId;
}
/**
* <p>
* The Amazon Chime Voice Connector ID.
* </p>
*
* @return The Amazon Chime Voice Connector ID.
*/
public String getVoiceConnectorId() {
return this.voiceConnectorId;
}
/**
* <p>
* The Amazon Chime Voice Connector ID.
* </p>
*
* @param voiceConnectorId
* The Amazon Chime Voice Connector ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteVoiceConnectorOriginationRequest withVoiceConnectorId(String voiceConnectorId) {
setVoiceConnectorId(voiceConnectorId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVoiceConnectorId() != null)
sb.append("VoiceConnectorId: ").append(getVoiceConnectorId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteVoiceConnectorOriginationRequest == false)
return false;
DeleteVoiceConnectorOriginationRequest other = (DeleteVoiceConnectorOriginationRequest) obj;
if (other.getVoiceConnectorId() == null ^ this.getVoiceConnectorId() == null)
return false;
if (other.getVoiceConnectorId() != null && other.getVoiceConnectorId().equals(this.getVoiceConnectorId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVoiceConnectorId() == null) ? 0 : getVoiceConnectorId().hashCode());
return hashCode;
}
@Override
public DeleteVoiceConnectorOriginationRequest clone() {
return (DeleteVoiceConnectorOriginationRequest) super.clone();
}
}
|
3e0e2eae6bb25e08136545c47333008338aa7627 | 1,742 | java | Java | projects/stage-1/middleware-frameworks/my-cache/src/main/java/org/geektimes/cache/annotation/DefaultCacheKeyGenerator.java | DiligentNezha/geekbang-lessons | 0043114e4236865739aec698240a506bc3e642af | [
"Apache-2.0"
] | 887 | 2019-12-18T11:02:20.000Z | 2022-02-15T16:58:11.000Z | projects/stage-1/middleware-frameworks/my-cache/src/main/java/org/geektimes/cache/annotation/DefaultCacheKeyGenerator.java | DiligentNezha/geekbang-lessons | 0043114e4236865739aec698240a506bc3e642af | [
"Apache-2.0"
] | 19 | 2019-12-09T14:27:35.000Z | 2022-03-07T06:19:03.000Z | projects/stage-1/middleware-frameworks/my-cache/src/main/java/org/geektimes/cache/annotation/DefaultCacheKeyGenerator.java | DiligentNezha/geekbang-lessons | 0043114e4236865739aec698240a506bc3e642af | [
"Apache-2.0"
] | 736 | 2019-12-09T13:15:10.000Z | 2022-03-28T08:06:16.000Z | 40.581395 | 122 | 0.771347 | 6,014 | /*
* 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.geektimes.cache.annotation;
import javax.cache.annotation.CacheKeyGenerator;
import javax.cache.annotation.CacheKeyInvocationContext;
import javax.cache.annotation.GeneratedCacheKey;
import java.lang.annotation.Annotation;
import java.util.Arrays;
/**
* Default {@link CacheKeyGenerator} implementation:
* <p>
* Defaults to a key generator that uses {@link Arrays#deepHashCode(Object[])}
* and {@link Arrays#deepEquals(Object[], Object[])} with the array
* returned by {@link CacheKeyInvocationContext#getKeyParameters()}
*
* @author <a href="mailto:hzdkv@example.com">Mercy</a>
* @see DefaultGeneratedCacheKey
* @since 1.0.0
*/
public class DefaultCacheKeyGenerator implements CacheKeyGenerator {
@Override
public GeneratedCacheKey generateCacheKey(CacheKeyInvocationContext<? extends Annotation> cacheKeyInvocationContext) {
return new DefaultGeneratedCacheKey(cacheKeyInvocationContext);
}
}
|
3e0e30669ec1230f86de6f16fd570909bf4656f1 | 4,631 | java | Java | aliyun-java-sdk-vod-v5/src/main/java/com/aliyuncs/v5/vod/model/v20170321/GetUploadDetailsResponse.java | aliyun/aliyun-openapi-java-sdk-v5 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | [
"Apache-2.0"
] | 4 | 2020-05-14T05:04:30.000Z | 2021-08-20T11:08:46.000Z | aliyun-java-sdk-vod-v5/src/main/java/com/aliyuncs/v5/vod/model/v20170321/GetUploadDetailsResponse.java | aliyun/aliyun-openapi-java-sdk-v5 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | [
"Apache-2.0"
] | 2 | 2020-10-13T07:47:10.000Z | 2021-06-04T02:42:57.000Z | aliyun-java-sdk-vod-v5/src/main/java/com/aliyuncs/v5/vod/model/v20170321/GetUploadDetailsResponse.java | aliyun/aliyun-openapi-java-sdk-v5 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | [
"Apache-2.0"
] | null | null | null | 21.947867 | 84 | 0.713669 | 6,015 | /*
* 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.aliyuncs.v5.vod.model.v20170321;
import java.util.List;
import com.aliyuncs.v5.AcsResponse;
import com.aliyuncs.v5.vod.transform.v20170321.GetUploadDetailsResponseUnmarshaller;
import com.aliyuncs.v5.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class GetUploadDetailsResponse extends AcsResponse {
private String requestId;
private List<UploadDetail> uploadDetails;
private List<String> nonExistMediaIds;
private List<String> forbiddenMediaIds;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public List<UploadDetail> getUploadDetails() {
return this.uploadDetails;
}
public void setUploadDetails(List<UploadDetail> uploadDetails) {
this.uploadDetails = uploadDetails;
}
public List<String> getNonExistMediaIds() {
return this.nonExistMediaIds;
}
public void setNonExistMediaIds(List<String> nonExistMediaIds) {
this.nonExistMediaIds = nonExistMediaIds;
}
public List<String> getForbiddenMediaIds() {
return this.forbiddenMediaIds;
}
public void setForbiddenMediaIds(List<String> forbiddenMediaIds) {
this.forbiddenMediaIds = forbiddenMediaIds;
}
public static class UploadDetail {
private String mediaId;
private String title;
private Long fileSize;
private String status;
private String uploadStatus;
private String creationTime;
private String modificationTime;
private String completionTime;
private Long uploadSize;
private Float uploadRatio;
private String uploadIP;
private String uploadSource;
private String deviceModel;
public String getMediaId() {
return this.mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getFileSize() {
return this.fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUploadStatus() {
return this.uploadStatus;
}
public void setUploadStatus(String uploadStatus) {
this.uploadStatus = uploadStatus;
}
public String getCreationTime() {
return this.creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getModificationTime() {
return this.modificationTime;
}
public void setModificationTime(String modificationTime) {
this.modificationTime = modificationTime;
}
public String getCompletionTime() {
return this.completionTime;
}
public void setCompletionTime(String completionTime) {
this.completionTime = completionTime;
}
public Long getUploadSize() {
return this.uploadSize;
}
public void setUploadSize(Long uploadSize) {
this.uploadSize = uploadSize;
}
public Float getUploadRatio() {
return this.uploadRatio;
}
public void setUploadRatio(Float uploadRatio) {
this.uploadRatio = uploadRatio;
}
public String getUploadIP() {
return this.uploadIP;
}
public void setUploadIP(String uploadIP) {
this.uploadIP = uploadIP;
}
public String getUploadSource() {
return this.uploadSource;
}
public void setUploadSource(String uploadSource) {
this.uploadSource = uploadSource;
}
public String getDeviceModel() {
return this.deviceModel;
}
public void setDeviceModel(String deviceModel) {
this.deviceModel = deviceModel;
}
}
@Override
public GetUploadDetailsResponse getInstance(UnmarshallerContext context) {
return GetUploadDetailsResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
|
3e0e307eb4aa88a529066d4b4823a38f4ac64316 | 4,560 | java | Java | dashbuilder/dashbuilder-client/dashbuilder-displayer-screen/src/main/java/org/dashbuilder/displayer/client/PerspectiveCoordinator.java | LeonidLapshin/appformer | 2cf15393aeb922cab813938aee2c665d51ede57f | [
"Apache-2.0"
] | 200 | 2015-02-26T22:09:19.000Z | 2022-01-11T15:01:57.000Z | dashbuilder/dashbuilder-client/dashbuilder-displayer-screen/src/main/java/org/dashbuilder/displayer/client/PerspectiveCoordinator.java | LeonidLapshin/appformer | 2cf15393aeb922cab813938aee2c665d51ede57f | [
"Apache-2.0"
] | 940 | 2017-03-21T08:15:36.000Z | 2022-03-25T13:18:36.000Z | dashbuilder/dashbuilder-client/dashbuilder-displayer-screen/src/main/java/org/dashbuilder/displayer/client/PerspectiveCoordinator.java | LeonidLapshin/appformer | 2cf15393aeb922cab813938aee2c665d51ede57f | [
"Apache-2.0"
] | 178 | 2017-03-14T10:44:31.000Z | 2022-03-28T23:02:29.000Z | 32.112676 | 106 | 0.643421 | 6,016 | /*
* Copyright 2014 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.dashbuilder.displayer.client;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.dashbuilder.dataset.DataSet;
import org.dashbuilder.dataset.DataSetLookup;
import org.dashbuilder.dataset.events.DataSetModifiedEvent;
import org.dashbuilder.displayer.DisplayerSettings;
import org.uberfire.client.workbench.events.PerspectiveChange;
/**
* It holds the set of Displayer instances being displayed on the current perspective.
* <p>It also makes sure those instances are properly synced to reflect the data set manipulation requests
* issued by any Displayer on the dashboard.</p>
*/
@ApplicationScoped
public class PerspectiveCoordinator {
/**
* The real coordinator.
*/
private DisplayerCoordinator displayerCoordinator;
/**
* Flag indicating if the perspective is on edit mode.
*/
boolean editOn = false;
public PerspectiveCoordinator() {
}
@Inject
public PerspectiveCoordinator(DisplayerCoordinator coordinator) {
this.displayerCoordinator = coordinator;
}
/**
* Adds a Displayer instance to the current perspective context.
*/
public void addDisplayer(Displayer displayer) {
displayerCoordinator.addDisplayer(displayer);
}
/**
* Removes a Displayer instance from the current perspective context.
*/
public boolean removeDisplayer(Displayer displayer) {
return displayerCoordinator.removeDisplayer(displayer);
}
/**
*
* @return the current list of displayers
*/
public List<Displayer> getDisplayerList(){
return displayerCoordinator.getDisplayerList();
}
/**
* Turn on the edition of the perspective
*/
public void editOn() {
editOn = true;
// Turns off the automatic refresh of all the displayers.
for (Displayer displayer : displayerCoordinator.getDisplayerList()) {
displayer.setRefreshOn(false);
}
}
/**
* Turn off the edition of the perspective
*/
public void editOff() {
editOn = false;
// Resumes the automatic refresh on all the displayers.
for (Displayer displayer : displayerCoordinator.getDisplayerList()) {
displayer.setRefreshOn(true);
}
}
/**
* Reset the coordinator every time the perspective is changed.
*/
private void onPerspectiveChanged(@Observes final PerspectiveChange event) {
displayerCoordinator.clear();
}
/**
* Listen to modifications on any of the data set being used in this perspective.
*/
private void onDataSetModifiedEvent(@Observes DataSetModifiedEvent event) {
if (!editOn) {
String targetUUID = event.getDataSetDef().getUUID();
for (Displayer displayer : displayerCoordinator.getDisplayerList()) {
DisplayerSettings settings = displayer.getDisplayerSettings();
// Do nothing if the displayer:
// - Is not drawn
// - Is handling the refresh by itself
// - Is not configured to be updated on stale data
if (!displayer.isDrawn() || displayer.isRefreshOn() || !settings.isRefreshStaleData()) {
continue;
}
String uuid = null;
DataSet dataSet = settings.getDataSet();
if (dataSet != null) {
uuid = dataSet.getUUID();
}
DataSetLookup dataSetLookup = settings.getDataSetLookup();
if (uuid == null && dataSetLookup != null) {
uuid = dataSetLookup.getDataSetUUID();
}
if (uuid != null && targetUUID.equals(uuid)) {
displayer.redraw();
}
}
}
}
}
|
3e0e30a8c44a089e3d4fb84b2fa6d44e66345cb6 | 1,041 | java | Java | src/main/org/codehaus/groovy/runtime/wrappers/FloatWrapper.java | NoraLuna/git-github.com-NoraLuna-tgit | 01309f9d4be34ddf93c4a9943b5a97843bff6181 | [
"Apache-2.0"
] | 860 | 2015-01-01T01:08:04.000Z | 2022-03-29T10:25:57.000Z | src/main/org/codehaus/groovy/runtime/wrappers/FloatWrapper.java | NoraLuna/git-github.com-NoraLuna-tgit | 01309f9d4be34ddf93c4a9943b5a97843bff6181 | [
"Apache-2.0"
] | 103 | 2015-01-01T09:35:05.000Z | 2019-03-06T22:22:32.000Z | src/main/org/codehaus/groovy/runtime/wrappers/FloatWrapper.java | NoraLuna/git-github.com-NoraLuna-tgit | 01309f9d4be34ddf93c4a9943b5a97843bff6181 | [
"Apache-2.0"
] | 285 | 2015-01-03T11:33:14.000Z | 2022-03-03T12:25:28.000Z | 35.896552 | 64 | 0.730067 | 6,017 | /**
* 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.codehaus.groovy.runtime.wrappers;
/**
* @author John Wilson
*/
public class FloatWrapper extends PojoWrapper {
public FloatWrapper(final float wrapped) {
super(wrapped, float.class);
}
}
|
3e0e30f53decd40ddae2f350beb12e196d86e86b | 7,977 | java | Java | tsfile/src/test/java/org/apache/iotdb/tsfile/write/TsFileReadWriteTest.java | LeiRui/iotdb-s1 | aba005265805c88039083f5fa313caa3b225158c | [
"Apache-2.0"
] | 42 | 2018-12-12T02:56:43.000Z | 2021-01-01T10:48:48.000Z | tsfile/src/test/java/org/apache/iotdb/tsfile/write/TsFileReadWriteTest.java | LeiRui/iotdb-s1 | aba005265805c88039083f5fa313caa3b225158c | [
"Apache-2.0"
] | 88 | 2018-12-11T14:35:37.000Z | 2021-06-21T11:57:21.000Z | tsfile/src/test/java/org/apache/iotdb/tsfile/write/TsFileReadWriteTest.java | LeiRui/iotdb-s1 | aba005265805c88039083f5fa313caa3b225158c | [
"Apache-2.0"
] | 15 | 2018-12-12T02:56:47.000Z | 2020-11-02T12:09:22.000Z | 36.108597 | 94 | 0.695113 | 6,018 | /**
* Copyright © 2019 Apache IoTDB(incubating) (hzdkv@example.com)
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.iotdb.tsfile.write;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.iotdb.tsfile.exception.write.WriteProcessException;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
import org.apache.iotdb.tsfile.read.ReadOnlyTsFile;
import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
import org.apache.iotdb.tsfile.read.common.Path;
import org.apache.iotdb.tsfile.read.common.RowRecord;
import org.apache.iotdb.tsfile.read.expression.QueryExpression;
import org.apache.iotdb.tsfile.read.query.dataset.QueryDataSet;
import org.apache.iotdb.tsfile.write.record.TSRecord;
import org.apache.iotdb.tsfile.write.record.datapoint.DataPoint;
import org.apache.iotdb.tsfile.write.record.datapoint.DoubleDataPoint;
import org.apache.iotdb.tsfile.write.record.datapoint.FloatDataPoint;
import org.apache.iotdb.tsfile.write.record.datapoint.IntDataPoint;
import org.apache.iotdb.tsfile.write.record.datapoint.LongDataPoint;
import org.apache.iotdb.tsfile.write.schema.MeasurementSchema;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TsFileReadWriteTest {
private final double delta = 0.0000001;
private String path = "read_write_rle.tsfile";
private File f;
private TsFileWriter tsFileWriter;
@Before
public void setUp() throws Exception {
f = new File(path);
if (f.exists()) {
f.delete();
}
tsFileWriter = new TsFileWriter(f);
}
@After
public void tearDown() throws Exception {
f = new File(path);
if (f.exists()) {
f.delete();
}
}
@Test
public void intTest() throws IOException, WriteProcessException {
int floatCount = 1024 * 1024 * 13 + 1023;
// add measurements into file schema
tsFileWriter
.addMeasurement(new MeasurementSchema("sensor_1", TSDataType.INT32, TSEncoding.RLE));
for (long i = 1; i < floatCount; i++) {
// construct TSRecord
TSRecord tsRecord = new TSRecord(i, "device_1");
DataPoint dPoint1 = new IntDataPoint("sensor_1", (int) i);
tsRecord.addTuple(dPoint1);
// write a TSRecord to TsFile
tsFileWriter.write(tsRecord);
}
// close TsFile
tsFileWriter.close();
TsFileSequenceReader reader = new TsFileSequenceReader(path);
ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader);
ArrayList<Path> paths = new ArrayList<>();
paths.add(new Path("device_1.sensor_1"));
QueryExpression queryExpression = QueryExpression.create(paths, null);
QueryDataSet queryDataSet = readTsFile.query(queryExpression);
for (int j = 0; j < paths.size(); j++) {
assertEquals(paths.get(j), queryDataSet.getPaths().get(j));
}
int i = 1;
while (queryDataSet.hasNext()) {
RowRecord r = queryDataSet.next();
assertEquals(i, r.getTimestamp());
assertEquals(i, r.getFields().get(0).getIntV());
i++;
}
reader.close();
}
@Test
public void longTest() throws IOException, WriteProcessException {
int floatCount = 1024 * 1024 * 13 + 1023;
// add measurements into file schema
tsFileWriter
.addMeasurement(new MeasurementSchema("sensor_1", TSDataType.INT64, TSEncoding.RLE));
for (long i = 1; i < floatCount; i++) {
// construct TSRecord
TSRecord tsRecord = new TSRecord(i, "device_1");
DataPoint dPoint1 = new LongDataPoint("sensor_1", i);
tsRecord.addTuple(dPoint1);
// write a TSRecord to TsFile
tsFileWriter.write(tsRecord);
}
// close TsFile
tsFileWriter.close();
TsFileSequenceReader reader = new TsFileSequenceReader(path);
ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader);
ArrayList<Path> paths = new ArrayList<>();
paths.add(new Path("device_1.sensor_1"));
QueryExpression queryExpression = QueryExpression.create(paths, null);
QueryDataSet queryDataSet = readTsFile.query(queryExpression);
for (int j = 0; j < paths.size(); j++) {
assertEquals(paths.get(j), queryDataSet.getPaths().get(j));
}
int i = 1;
while (queryDataSet.hasNext()) {
RowRecord r = queryDataSet.next();
assertEquals(i, r.getTimestamp());
assertEquals(i, r.getFields().get(0).getLongV());
i++;
}
reader.close();
}
@Test
public void floatTest() throws IOException, WriteProcessException {
int floatCount = 1024 * 1024 * 13 + 1023;
// add measurements into file schema
tsFileWriter
.addMeasurement(new MeasurementSchema("sensor_1", TSDataType.FLOAT, TSEncoding.RLE));
for (long i = 1; i < floatCount; i++) {
// construct TSRecord
TSRecord tsRecord = new TSRecord(i, "device_1");
DataPoint dPoint1 = new FloatDataPoint("sensor_1", (float) i);
tsRecord.addTuple(dPoint1);
// write a TSRecord to TsFile
tsFileWriter.write(tsRecord);
}
// close TsFile
tsFileWriter.close();
TsFileSequenceReader reader = new TsFileSequenceReader(path);
ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader);
ArrayList<Path> paths = new ArrayList<>();
paths.add(new Path("device_1.sensor_1"));
QueryExpression queryExpression = QueryExpression.create(paths, null);
QueryDataSet queryDataSet = readTsFile.query(queryExpression);
for (int j = 0; j < paths.size(); j++) {
assertEquals(paths.get(j), queryDataSet.getPaths().get(j));
}
int i = 1;
while (queryDataSet.hasNext()) {
RowRecord r = queryDataSet.next();
assertEquals(i, r.getTimestamp());
assertEquals((float) i, r.getFields().get(0).getFloatV(), delta);
i++;
}
reader.close();
}
@Test
public void doubleTest() throws IOException, WriteProcessException {
int floatCount = 1024 * 1024 * 13 + 1023;
// add measurements into file schema
tsFileWriter
.addMeasurement(new MeasurementSchema("sensor_1", TSDataType.DOUBLE, TSEncoding.RLE));
for (long i = 1; i < floatCount; i++) {
// construct TSRecord
TSRecord tsRecord = new TSRecord(i, "device_1");
DataPoint dPoint1 = new DoubleDataPoint("sensor_1", (double) i);
tsRecord.addTuple(dPoint1);
// write a TSRecord to TsFile
tsFileWriter.write(tsRecord);
}
// close TsFile
tsFileWriter.close();
TsFileSequenceReader reader = new TsFileSequenceReader(path);
ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader);
ArrayList<Path> paths = new ArrayList<>();
paths.add(new Path("device_1.sensor_1"));
QueryExpression queryExpression = QueryExpression.create(paths, null);
QueryDataSet queryDataSet = readTsFile.query(queryExpression);
for (int j = 0; j < paths.size(); j++) {
assertEquals(paths.get(j), queryDataSet.getPaths().get(j));
}
int i = 1;
while (queryDataSet.hasNext()) {
RowRecord r = queryDataSet.next();
assertEquals(i, r.getTimestamp());
assertEquals((double) i, r.getFields().get(0).getDoubleV(), delta);
i++;
}
reader.close();
}
}
|
3e0e31262618a3a0441e2151978aee180c56ba33 | 2,105 | java | Java | billing-api/src/main/java/com/tony/billing/model/BudgetReportModel.java | TonyJiangWJ/BillingDubbo | 0adc8a027a978f545a40c064fe63a325492a5b10 | [
"Apache-2.0"
] | 2 | 2019-10-31T06:54:52.000Z | 2019-10-31T07:03:40.000Z | billing-api/src/main/java/com/tony/billing/model/BudgetReportModel.java | TonyJiangWJ/BillingDubbo | 0adc8a027a978f545a40c064fe63a325492a5b10 | [
"Apache-2.0"
] | 2 | 2020-10-14T02:22:32.000Z | 2022-03-04T05:15:37.000Z | billing-api/src/main/java/com/tony/billing/model/BudgetReportModel.java | TonyJiangWJ/BillingDubbo | 0adc8a027a978f545a40c064fe63a325492a5b10 | [
"Apache-2.0"
] | 3 | 2019-10-31T07:03:58.000Z | 2019-10-31T07:10:24.000Z | 24.476744 | 82 | 0.672209 | 6,019 | package com.tony.billing.model;
import com.tony.billing.dto.BudgetReportItemDTO;
import org.apache.commons.collections.CollectionUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author jiangwenjie 2019-03-22
*/
public class BudgetReportModel implements Serializable {
private String yearMonthInfo;
private Long totalAmount;
private Long budgetUsed;
private Long remain;
private Long noBudgetUsed;
private List<BudgetReportItemDTO> reportItems;
public BudgetReportModel() {
this.totalAmount = budgetUsed = remain = noBudgetUsed = 0L;
reportItems = new ArrayList<>();
}
public String getYearMonthInfo() {
return yearMonthInfo;
}
public void setYearMonthInfo(String yearMonthInfo) {
this.yearMonthInfo = yearMonthInfo;
}
public Long getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Long totalAmount) {
this.totalAmount = totalAmount;
}
public Long getBudgetUsed() {
return budgetUsed;
}
public void setBudgetUsed(Long budgetUsed) {
this.budgetUsed = budgetUsed;
}
public Long getRemain() {
return remain;
}
public void setRemain(Long remain) {
this.remain = remain;
}
public Long getNoBudgetUsed() {
return noBudgetUsed;
}
public void setNoBudgetUsed(Long noBudgetUsed) {
this.noBudgetUsed = noBudgetUsed;
}
public List<BudgetReportItemDTO> getReportItems() {
return reportItems;
}
public void setReportItems(List<BudgetReportItemDTO> reportItems) {
this.reportItems = reportItems;
}
public void addBudgetInfos(BudgetReportItemDTO item) {
this.reportItems.add(item);
}
public BudgetReportModel build() {
if (CollectionUtils.isNotEmpty(this.reportItems)) {
reportItems.forEach(budget -> this.totalAmount += budget.getAmount());
}
this.remain = this.totalAmount - this.budgetUsed - this.noBudgetUsed;
return this;
}
}
|
3e0e33e40a96baa359446f0c06588f8bcce06cb1 | 3,757 | java | Java | library/src/main/java/it/sephiroth/android/library/viewrevealanimator/ICSRevealAnimatorImpl.java | sephiroth74/ViewRevealAnimator | 40c3956878b686e38d9604b52f83eb5742fa9d99 | [
"Apache-2.0"
] | 378 | 2015-02-04T06:32:33.000Z | 2022-02-15T13:41:47.000Z | library/src/main/java/it/sephiroth/android/library/viewrevealanimator/ICSRevealAnimatorImpl.java | sephiroth74/ViewRevealAnimator | 40c3956878b686e38d9604b52f83eb5742fa9d99 | [
"Apache-2.0"
] | 4 | 2015-02-11T09:43:20.000Z | 2016-02-22T10:13:54.000Z | library/src/main/java/it/sephiroth/android/library/viewrevealanimator/ICSRevealAnimatorImpl.java | sephiroth74/ViewRevealAnimator | 40c3956878b686e38d9604b52f83eb5742fa9d99 | [
"Apache-2.0"
] | 79 | 2015-02-04T14:51:36.000Z | 2022-02-15T13:41:53.000Z | 34.787037 | 103 | 0.599681 | 6,020 | package it.sephiroth.android.library.viewrevealanimator;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import static it.sephiroth.android.library.viewrevealanimator.ViewRevealAnimator.DBG;
/**
* Created by alessandro on 01/02/15.
*/
public class ICSRevealAnimatorImpl extends RevealAnimatorImpl {
ICSRevealAnimatorImpl(final ViewRevealAnimator animator) {
super(animator);
}
@Override
public void showOnly(final int previousChild, final int childIndex, @Nullable final Point origin) {
if (DBG) {
Log.i(TAG, "showOnly: " + previousChild + " >> " + childIndex);
}
parent.mInAnimation.setAnimationListener(new MyAnimationListener(previousChild, childIndex));
final int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
final View child = parent.getChildAt(i);
if (i == childIndex) {
if (parent.mInAnimation != null) {
child.startAnimation(parent.mInAnimation);
}
child.setVisibility(View.VISIBLE);
parent.mFirstTime = false;
} else {
if (parent.mOutAnimation != null && child.getVisibility() == View.VISIBLE) {
child.startAnimation(parent.mOutAnimation);
} else if (child.getAnimation() == parent.mInAnimation) {
parent.mInAnimation.setAnimationListener(null);
child.clearAnimation();
}
child.setVisibility(View.GONE);
}
}
}
@Override
public void showOnlyNoAnimation(final int previousIndex, final int childIndex) {
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
child.setVisibility(i == childIndex ? View.VISIBLE : View.GONE);
if (child.getAnimation() == parent.mInAnimation) {
parent.mInAnimation.setAnimationListener(null);
child.clearAnimation();
} else if (child.getAnimation() == parent.mOutAnimation) {
child.clearAnimation();
}
}
}
@Override
public boolean isAnimating() {
return
(parent.mInAnimation != null &&
(parent.mInAnimation.hasStarted() && !parent.mInAnimation.hasEnded()))
|| (parent.mOutAnimation != null &&
(parent.mOutAnimation.hasStarted() && !parent.mOutAnimation.hasEnded()));
}
@Override
public boolean shouldAnimate() {
return (!parent.mFirstTime || parent.mAnimateFirstTime)
&& !isAnimating()
&& null != parent.mInAnimation
&& null != parent.mOutAnimation;
}
class MyAnimationListener implements Animation.AnimationListener {
final int prevIndex;
final int childIndex;
public MyAnimationListener(final int previousChild, final int childIndex) {
this.prevIndex = previousChild;
this.childIndex = childIndex;
}
@Override
public void onAnimationStart(final Animation animation) {
parent.onAnimationStarted(prevIndex, childIndex);
}
@Override
public void onAnimationEnd(final Animation animation) {
if (DBG) {
Log.d(TAG, "onAnimationEnd");
}
parent.onAnimationCompleted(prevIndex, childIndex);
parent.onViewChanged(prevIndex, childIndex);
}
@Override
public void onAnimationRepeat(final Animation animation) {
}
}
}
|
3e0e347a2457e7eabf0988f6ffb0f2f1a2c74c2c | 2,276 | java | Java | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/directcollection/typeattribute/identifiedbyname/withoutgroupingelement/WithoutGroupingElementIdentifiedByNameIntegerTestCases.java | marschall/eclipselink.runtime | 3d59eaa9e420902d5347b9fb60fbe6c92310894b | [
"BSD-3-Clause"
] | null | null | null | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/directcollection/typeattribute/identifiedbyname/withoutgroupingelement/WithoutGroupingElementIdentifiedByNameIntegerTestCases.java | marschall/eclipselink.runtime | 3d59eaa9e420902d5347b9fb60fbe6c92310894b | [
"BSD-3-Clause"
] | 2 | 2021-03-24T17:58:46.000Z | 2021-12-14T20:59:52.000Z | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/directcollection/typeattribute/identifiedbyname/withoutgroupingelement/WithoutGroupingElementIdentifiedByNameIntegerTestCases.java | marschall/eclipselink.runtime | 3d59eaa9e420902d5347b9fb60fbe6c92310894b | [
"BSD-3-Clause"
] | null | null | null | 48.425532 | 213 | 0.743849 | 6,021 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.mappings.directcollection.typeattribute.identifiedbyname.withoutgroupingelement;
import java.util.Vector;
import org.eclipse.persistence.testing.oxm.mappings.XMLMappingTestCases;
import org.eclipse.persistence.testing.oxm.mappings.directcollection.Employee;
public class WithoutGroupingElementIdentifiedByNameIntegerTestCases extends XMLMappingTestCases {
private final static String XML_RESOURCE = "org/eclipse/persistence/testing/oxm/mappings/directcollection/typeattribute/identifiedbyname/withoutgroupingelement/WithoutGroupingElementIntegerIdentifiedByName.xml";
private final static int CONTROL_ID = 123;
private final static Integer CONTROL_RESPONSIBILITY1 = new Integer(100);
private final static Integer CONTROL_RESPONSIBILITY2 = new Integer(200);
private final static Integer CONTROL_RESPONSIBILITY3 = new Integer(300);
public WithoutGroupingElementIdentifiedByNameIntegerTestCases(String name) throws Exception {
super(name);
setControlDocument(XML_RESOURCE);
setProject(new WithoutGroupingElementIdentifiedByNameProject());
}
protected Object getControlObject() {
Vector responsibilities = new Vector();
responsibilities.addElement(CONTROL_RESPONSIBILITY1);
responsibilities.addElement(CONTROL_RESPONSIBILITY2);
responsibilities.addElement(CONTROL_RESPONSIBILITY3);
Employee employee = new Employee();
employee.setID(CONTROL_ID);
employee.setResponsibilities(responsibilities);
return employee;
}
}
|
3e0e349863f1d90467a9018bee95e106b9f6311b | 232 | java | Java | savings/src/main/java/com/marticus/Company.java | dhanababu123/110-dhanalakshmi | 22bebe9baccec307ad8170181476ead2f0f3fe4a | [
"Unlicense"
] | null | null | null | savings/src/main/java/com/marticus/Company.java | dhanababu123/110-dhanalakshmi | 22bebe9baccec307ad8170181476ead2f0f3fe4a | [
"Unlicense"
] | null | null | null | savings/src/main/java/com/marticus/Company.java | dhanababu123/110-dhanalakshmi | 22bebe9baccec307ad8170181476ead2f0f3fe4a | [
"Unlicense"
] | 1 | 2022-01-04T08:54:23.000Z | 2022-01-04T08:54:23.000Z | 10.086957 | 34 | 0.637931 | 6,022 | package com.marticus;
public class Company {
private account acc;
public account getacc() {
return acc;
}
public void setacc(account acc) {
this.acc = acc;
}
public void showacc()
{
acc.showaccType();
}
}
|
3e0e34b3df12251719ebaf3fbc61eecf38af4c35 | 13,177 | java | Java | arcoflex056/src/WIP/mame056/drivers/suprloco.java | javaemus/arcoflex056 | 6997efbc3d05112b29b0008a988111d71d8babf7 | [
"Apache-2.0"
] | null | null | null | arcoflex056/src/WIP/mame056/drivers/suprloco.java | javaemus/arcoflex056 | 6997efbc3d05112b29b0008a988111d71d8babf7 | [
"Apache-2.0"
] | null | null | null | arcoflex056/src/WIP/mame056/drivers/suprloco.java | javaemus/arcoflex056 | 6997efbc3d05112b29b0008a988111d71d8babf7 | [
"Apache-2.0"
] | null | null | null | 37.434659 | 216 | 0.665554 | 6,023 | /******************************************************************************
Super Locomotive
driver by Zsolt Vasvari
TODO:
- Bit 5 in suprloco_control_w is pulsed when loco turns "super". This is supposed
to make red parts of sprites blink to purple, it's not clear how this is
implemented in hardware, there's a hack to support it.
******************************************************************************/
/*
* ported to v0.56
* using automatic conversion tool v0.01
*/
package WIP.mame056.drivers;
import static arcadeflex056.fucPtr.*;
import static common.ptr.*;
import static mame056.commonH.*;
import static mame056.common.*;
import static mame056.cpuexec.*;
import static mame056.cpuexecH.*;
import static mame056.cpuintrfH.*;
import static mame056.memory.*;
import static mame056.drawgfxH.*;
import static mame056.driverH.*;
import static mame056.inptport.*;
import static mame056.inptportH.*;
import static mame056.memoryH.*;
import static mame056.palette.*;
import static mame056.sndintrf.*;
import static mame056.sndintrfH.*;
import static mame056.timer.*;
import static mame056.timerH.*;
import static WIP.mame056.vidhrdw.suprloco.*;
import static mame056.sound.ay8910.*;
import mame056.sound.ay8910H.AY8910interface;
import static arcadeflex056.osdepend.logerror;
import static mame056.sound._2203intf.*;
import static mame056.sound._2203intfH.*;
import static mame056.sound._3526intf.*;
import static mame056.sound._3812intfH.*;
import static mame056.sound.sn76496.*;
import static mame056.sound.sn76496H.*;
import static mame056.vidhrdw.generic.*;
import static WIP.mame056.machine.segacrpt.*;
import static mame056.inputH.KEYCODE_F2;
public class suprloco
{
public static WriteHandlerPtr suprloco_soundport_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
soundlatch_w.handler(0,data);
cpu_cause_interrupt(1,Z80_NMI_INT);
/* spin for a while to let the Z80 read the command (fixes hanging sound in Regulus) */
cpu_spinuntil_time(TIME_IN_USEC(50));
} };
public static Memory_ReadAddress readmem[]={
new Memory_ReadAddress(MEMPORT_MARKER, MEMPORT_DIRECTION_READ | MEMPORT_TYPE_MEM | MEMPORT_WIDTH_8),
new Memory_ReadAddress( 0x0000, 0xbfff, MRA_ROM ),
new Memory_ReadAddress( 0xc000, 0xc1ff, MRA_RAM ),
new Memory_ReadAddress( 0xc800, 0xc800, input_port_0_r ),
new Memory_ReadAddress( 0xd000, 0xd000, input_port_1_r ),
new Memory_ReadAddress( 0xd800, 0xd800, input_port_2_r ),
new Memory_ReadAddress( 0xe000, 0xe000, input_port_3_r ),
new Memory_ReadAddress( 0xe001, 0xe001, input_port_4_r ),
new Memory_ReadAddress( 0xe801, 0xe801, suprloco_control_r ),
new Memory_ReadAddress( 0xf000, 0xf6ff, MRA_RAM ),
new Memory_ReadAddress( 0xf7e0, 0xf7ff, suprloco_scrollram_r ),
new Memory_ReadAddress( 0xf800, 0xffff, MRA_RAM ),
new Memory_ReadAddress(MEMPORT_MARKER, 0)
};
public static Memory_WriteAddress writemem[]={
new Memory_WriteAddress(MEMPORT_MARKER, MEMPORT_DIRECTION_WRITE | MEMPORT_TYPE_MEM | MEMPORT_WIDTH_8),
new Memory_WriteAddress( 0x0000, 0xbfff, MWA_ROM ),
new Memory_WriteAddress( 0xc000, 0xc1ff, MWA_RAM, spriteram, spriteram_size ),
new Memory_WriteAddress( 0xe800, 0xe800, suprloco_soundport_w ),
new Memory_WriteAddress( 0xe801, 0xe801, suprloco_control_w ),
new Memory_WriteAddress( 0xf000, 0xf6ff, suprloco_videoram_w, suprloco_videoram ),
new Memory_WriteAddress( 0xf7e0, 0xf7ff, suprloco_scrollram_w ),
new Memory_WriteAddress( 0xf800, 0xffff, MWA_RAM ),
new Memory_WriteAddress(MEMPORT_MARKER, 0)
};
public static Memory_ReadAddress sound_readmem[]={
new Memory_ReadAddress(MEMPORT_MARKER, MEMPORT_DIRECTION_READ | MEMPORT_TYPE_MEM | MEMPORT_WIDTH_8),
new Memory_ReadAddress( 0x0000, 0x7fff, MRA_ROM ),
new Memory_ReadAddress( 0x8000, 0x87ff, MRA_RAM ),
new Memory_ReadAddress( 0xe000, 0xe000, soundlatch_r ),
new Memory_ReadAddress(MEMPORT_MARKER, 0)
};
public static Memory_WriteAddress sound_writemem[]={
new Memory_WriteAddress(MEMPORT_MARKER, MEMPORT_DIRECTION_WRITE | MEMPORT_TYPE_MEM | MEMPORT_WIDTH_8),
new Memory_WriteAddress( 0x0000, 0x7fff, MWA_ROM ),
new Memory_WriteAddress( 0x8000, 0x87ff, MWA_RAM ),
new Memory_WriteAddress( 0xa000, 0xa003, SN76496_0_w ),
new Memory_WriteAddress( 0xc000, 0xc003, SN76496_1_w ),
new Memory_WriteAddress(MEMPORT_MARKER, 0)
};
static InputPortPtr input_ports_suprloco = new InputPortPtr(){ public void handler() {
PORT_START(); /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 );
PORT_BITX(0x04, IP_ACTIVE_LOW, IPT_SERVICE, DEF_STR( "Service_Mode" ), KEYCODE_F2, IP_JOY_NONE );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN3 );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START1 );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 );
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED );
PORT_START(); /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 );
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED );
PORT_START(); /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL );
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL );
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL );
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL );
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL );
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL );
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED );
PORT_START(); /* DSW1 */
PORT_DIPNAME( 0x07, 0x00, DEF_STR( "Coin_A") );
PORT_DIPSETTING( 0x07, DEF_STR( "5C_1C") );
PORT_DIPSETTING( 0x06, DEF_STR( "4C_1C") );
PORT_DIPSETTING( 0x05, DEF_STR( "3C_1C") );
PORT_DIPSETTING( 0x04, DEF_STR( "2C_1C") );
PORT_DIPSETTING( 0x00, DEF_STR( "1C_1C") );
PORT_DIPSETTING( 0x01, DEF_STR( "1C_2C") );
PORT_DIPSETTING( 0x02, DEF_STR( "1C_3C") );
PORT_DIPSETTING( 0x03, DEF_STR( "1C_6C") );
PORT_DIPNAME( 0x38, 0x00, DEF_STR( "Coin_B") );
PORT_DIPSETTING( 0x38, DEF_STR( "5C_1C") );
PORT_DIPSETTING( 0x30, DEF_STR( "4C_1C") );
PORT_DIPSETTING( 0x28, DEF_STR( "3C_1C") );
PORT_DIPSETTING( 0x20, DEF_STR( "2C_1C") );
PORT_DIPSETTING( 0x00, DEF_STR( "1C_1C") );
PORT_DIPSETTING( 0x08, DEF_STR( "1C_2C") );
PORT_DIPSETTING( 0x10, DEF_STR( "1C_3C") );
PORT_DIPSETTING( 0x18, DEF_STR( "1C_6C") );
PORT_DIPNAME( 0xc0, 0x40, DEF_STR( "Lives") );
PORT_DIPSETTING( 0x00, "2" );
PORT_DIPSETTING( 0x40, "3" );
PORT_DIPSETTING( 0x80, "4" );
PORT_DIPSETTING( 0xc0, "5" );
PORT_START(); /* DSW2 */
PORT_DIPNAME( 0x03, 0x00, DEF_STR( "Bonus_Life") );
PORT_DIPSETTING( 0x00, "20000" );
PORT_DIPSETTING( 0x01, "30000" );
PORT_DIPSETTING( 0x02, "40000" );
PORT_DIPSETTING( 0x03, "50000" );
PORT_DIPNAME( 0x04, 0x04, DEF_STR( "Unused") );
PORT_DIPSETTING( 0x04, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_DIPNAME( 0x08, 0x08, DEF_STR( "Free_Play") );
PORT_DIPSETTING( 0x08, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_DIPNAME( 0x10, 0x10, DEF_STR( "Difficulty") );
PORT_DIPSETTING( 0x10, "Easy" );
PORT_DIPSETTING( 0x00, "Hard" );
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Infinite Lives", IP_KEY_NONE, IP_JOY_NONE );
PORT_DIPSETTING( 0x20, DEF_STR( "Off") );
PORT_DIPSETTING( 0x00, DEF_STR( "On") );
PORT_DIPNAME( 0x40, 0x40, "Initial Entry" );
PORT_DIPSETTING( 0x00, DEF_STR( "Off") );
PORT_DIPSETTING( 0x40, DEF_STR( "On") );
PORT_DIPNAME( 0x80, 0x00, DEF_STR( "Cabinet") );
PORT_DIPSETTING( 0x00, DEF_STR( "Upright") );
PORT_DIPSETTING( 0x80, DEF_STR( "Cocktail") );
INPUT_PORTS_END(); }};
static GfxLayout charlayout = new GfxLayout
(
8,8, /* 8 by 8 */
1024, /* 1024 characters */
4, /* 4 bits per pixel */
new int[] { 0, 1024*8*8, 2*1024*8*8, 3*1024*8*8, 4*1024*8*8, 5*1024*8*8, 6*1024*8*8, 7*1024*8*8 }, /* plane */
new int[] { 0, 1, 2, 3, 4, 5, 6, 7 },
new int[] { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
8*8
);
static GfxDecodeInfo gfxdecodeinfo[] =
{
/* sprites use colors 256-511 + 512-767 */
new GfxDecodeInfo( REGION_GFX1, 0x6000, charlayout, 0, 16 ),
new GfxDecodeInfo( -1 ) /* end of array */
};
static SN76496interface sn76496_interface = new SN76496interface
(
2, /* 2 chips */
new int[] { 4000000, 2000000 }, /* 8 MHz / 4 ?*/
new int[] { 100, 100 }
);
static MachineDriver machine_driver_suprloco = new MachineDriver
(
/* basic machine hardware */
new MachineCPU[] {
new MachineCPU(
CPU_Z80,
4000000, /* 4 MHz (?) */
readmem,writemem,null,null,
interrupt,1
),
new MachineCPU(
CPU_Z80 | CPU_AUDIO_CPU,
4000000,
sound_readmem,sound_writemem,null,null,
interrupt,4 /* NMIs are caused by the main CPU */
),
},
60, 5000, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
32*8, 32*8, /* screen_width, screen_height */
new rectangle( 1*8, 31*8-1, 0*8, 28*8-1 ), /* struct rectangle visible_area */
gfxdecodeinfo, /* GfxDecodeInfo */
512+256, 0,
suprloco_vh_convert_color_prom, /* convert color prom routine */
VIDEO_TYPE_RASTER,
null, /* vh_init routine */
suprloco_vh_start, /* vh_start routine */
null, /* vh_stop routine */
suprloco_vh_screenrefresh, /* vh_update routine */
/* sound hardware */
0,0,0,0,
new MachineSound[] {
new MachineSound(
SOUND_SN76496,
sn76496_interface
)
}
);
/***************************************************************************
Game driver(s)
***************************************************************************/
static RomLoadPtr rom_suprloco = new RomLoadPtr(){ public void handler(){
ROM_REGION( 2*0x10000, REGION_CPU1, 0 );/* 64k for code + 64k for decrypted opcodes */
ROM_LOAD( "ic37.bin", 0x0000, 0x4000, 0x57f514dd );/* encrypted */
ROM_LOAD( "ic15.bin", 0x4000, 0x4000, 0x5a1d2fb0 );/* encrypted */
ROM_LOAD( "ic28.bin", 0x8000, 0x4000, 0xa597828a );
ROM_REGION( 0x10000, REGION_CPU2, 0 );/* 64k for sound cpu */
ROM_LOAD( "ic64.bin", 0x0000, 0x2000, 0x0aa57207 );
ROM_REGION( 0xe000, REGION_GFX1, ROMREGION_DISPOSE );
ROM_LOAD( "ic63.bin", 0x0000, 0x2000, 0xe571fe81 );
ROM_LOAD( "ic62.bin", 0x2000, 0x2000, 0x6130f93c );
ROM_LOAD( "ic61.bin", 0x4000, 0x2000, 0x3b03004e );
/*0x6000- 0xe000 will be created by init_suprloco */
ROM_REGION( 0x8000, REGION_GFX2, 0 );/* 32k for sprites data used at runtime */
ROM_LOAD( "ic55.bin", 0x0000, 0x4000, 0xee2d3ed3 );
ROM_LOAD( "ic56.bin", 0x4000, 0x2000, 0xf04a4b50 );
/*0x6000 empty */
ROM_REGION( 0x0620, REGION_PROMS, 0 );
ROM_LOAD( "ic100.bin", 0x0100, 0x0080, 0x7b0c8ce5 ); /* color PROM */
ROM_CONTINUE( 0x0000, 0x0080 );
ROM_CONTINUE( 0x0180, 0x0080 );
ROM_CONTINUE( 0x0080, 0x0080 );
ROM_LOAD( "ic89.bin", 0x0200, 0x0400, 0x1d4b02cb ); /* 3bpp to 4bpp table */
ROM_LOAD( "ic7.bin", 0x0600, 0x0020, 0x89ba674f );/* unknown */
ROM_END(); }};
public static InitDriverPtr init_suprloco = new InitDriverPtr() { public void handler()
{
/* convert graphics to 4bpp from 3bpp */
int i, j, k, color_source, color_dest;
UBytePtr source=new UBytePtr(), dest=new UBytePtr(), lookup=new UBytePtr();
source = memory_region(REGION_GFX1);
dest = new UBytePtr(source, 0x6000);
lookup = new UBytePtr(memory_region(REGION_PROMS), 0x0200);
for (i = 0; i < 0x80; i++, lookup.inc(8))
{
for (j = 0; j < 0x40; j++, source.inc(), dest.inc())
{
dest.write(0, 0);
dest.write(0x2000, 0);
dest.write(0x4000, 0);
dest.write(0x6000, 0);
for (k = 0; k < 8; k++)
{
color_source = (((source.read(0x0000) >> k) & 0x01) << 2) |
(((source.read(0x2000) >> k) & 0x01) << 1) |
(((source.read(0x4000) >> k) & 0x01) << 0);
color_dest = lookup.read(color_source);
dest.write(0x0000, dest.read(0x0000) | (((color_dest >> 3) & 0x01) << k));
dest.write(0x2000, dest.read(0x2000) | (((color_dest >> 2) & 0x01) << k));
dest.write(0x4000, dest.read(0x4000) | (((color_dest >> 1) & 0x01) << k));
dest.write(0x6000, dest.read(0x6000) | (((color_dest >> 0) & 0x01) << k));
}
}
}
/* decrypt program ROMs */
suprloco_decode();
} };
public static GameDriver driver_suprloco = new GameDriver("1982" ,"suprloco" ,"suprloco.java" ,rom_suprloco,null ,machine_driver_suprloco ,input_ports_suprloco ,init_suprloco ,ROT0 , "Sega", "Super Locomotive" );
}
|
3e0e368984b0dfdae5b52b159e8693c18da6fab0 | 1,333 | java | Java | messaging-client/src/main/java/com/streamsets/datacollector/event/client/api/EventClient.java | tinawenqiao/datacollector | 06e4a5c6ed920b624195fb8c2c14c3b0515ea054 | [
"Apache-2.0"
] | 7 | 2019-12-01T06:45:02.000Z | 2021-09-12T02:42:01.000Z | messaging-client/src/main/java/com/streamsets/datacollector/event/client/api/EventClient.java | tinawenqiao/datacollector | 06e4a5c6ed920b624195fb8c2c14c3b0515ea054 | [
"Apache-2.0"
] | null | null | null | messaging-client/src/main/java/com/streamsets/datacollector/event/client/api/EventClient.java | tinawenqiao/datacollector | 06e4a5c6ed920b624195fb8c2c14c3b0515ea054 | [
"Apache-2.0"
] | 5 | 2019-12-02T05:59:10.000Z | 2020-10-19T09:57:40.000Z | 31.738095 | 75 | 0.753938 | 6,024 | /*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.event.client.api;
import java.util.List;
import java.util.Map;
import com.streamsets.datacollector.event.json.ClientEventJson;
import com.streamsets.datacollector.event.json.SDCMetricsJson;
import com.streamsets.datacollector.event.json.ServerEventJson;
public interface EventClient {
List<ServerEventJson> submit(
String path,
Map<String, String> queryParams,
Map<String, String> headerParams,
boolean compression,
List<ClientEventJson> clientEventJson) throws EventException;
void submit(
String targetUrl,
Map<String, String> queryParams,
Map<String, String> headerParams,
List<SDCMetricsJson> clientEventJson,
long retryAttempts);
}
|
3e0e37581a572793f5e1672c175a0d6609b3b4a4 | 288 | java | Java | BackUp/20110125 - Before Adding Data To Corpus/Persian Transliteration/src/Main.java | sina-cb/PersianTransliterator | 72e5965622baa91e0aaa78429f4f09ce4a34a070 | [
"Apache-2.0"
] | 5 | 2016-07-07T19:19:36.000Z | 2017-12-17T05:46:52.000Z | Persian Transliteration - Completed - IntelliJ Project/src/Main.java | sina-cb/PersianTransliterator | 72e5965622baa91e0aaa78429f4f09ce4a34a070 | [
"Apache-2.0"
] | null | null | null | Persian Transliteration - Completed - IntelliJ Project/src/Main.java | sina-cb/PersianTransliterator | 72e5965622baa91e0aaa78429f4f09ce4a34a070 | [
"Apache-2.0"
] | null | null | null | 19.2 | 64 | 0.635417 | 6,025 | import GUI.InputForm;
/**
* Created by IntelliJ IDEA.
* User: sina
* Date: 1/22/11
* Time: 3:27 AM
* To change this template use File | Settings | File Templates.
*/
public class Main {
public static void main(String[] args) {
InputForm main = new InputForm();
}
}
|
3e0e378f2f85c71c7b3a4cc8349774be1b893f2a | 2,020 | java | Java | src/main/java/tv/amwa/maj/integer/Int32.java | PortalMedia/embARC-maj | 1022b4e0b2f47eaa53b27158bfb9ef1014d14828 | [
"Apache-2.0"
] | 16 | 2016-09-08T09:19:28.000Z | 2021-05-08T11:52:54.000Z | src/main/java/tv/amwa/maj/integer/Int32.java | PortalMedia/embARC-maj | 1022b4e0b2f47eaa53b27158bfb9ef1014d14828 | [
"Apache-2.0"
] | 18 | 2016-02-04T19:30:35.000Z | 2021-11-12T11:24:52.000Z | src/main/java/tv/amwa/maj/integer/Int32.java | PortalMedia/embARC-maj | 1022b4e0b2f47eaa53b27158bfb9ef1014d14828 | [
"Apache-2.0"
] | 16 | 2017-04-20T15:24:33.000Z | 2022-02-25T20:09:12.000Z | 31.5625 | 177 | 0.725248 | 6,026 | /*
* Copyright 2016 Richard Cartwright
*
* 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.
*/
/*
* $Log: Int32.java,v $
* Revision 1.6 2009/05/14 16:15:30 vizigoth
* Major refactor to remove dependency on JPA and introduce better interface and implementation separation. Removed all setPropertiesFromInterface and castFromInterface methods.
*
* Revision 1.5 2009/03/30 09:05:07 vizigoth
* Refactor to use SMPTE harmonized names and add early KLV file support.
*
* Revision 1.4 2007/12/12 12:51:44 vizigoth
* Added documentation tag to annotations.
*
* Revision 1.3 2007/11/23 15:07:16 vizigoth
* Minor documentation edits.
*
* Revision 1.2 2007/11/22 12:38:01 vizigoth
* Edited javadoc comments to release standard.
*
*
*/
package tv.amwa.maj.integer;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* <p>Labels a 32-bit 2's complement integer value. This annotation is used
* to show that a Java <code>int</code> value is being used to represent an AAF
* <code>Int32</code> type value.</p>
*
* <p>
* Original C type name: <code>aafInt32</code><br>
* C base type: <code>signed int</code><br>
* Java base type: <code>int</code>
* </p>
*
*
*
* @see tv.amwa.maj.industry.TypeDefinitions#Int32
* @see tv.amwa.maj.industry.TypeDefinitions#Int32Array
* @see Int32Array
*/
@Documented
@Target(value={ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface Int32 { }
|
3e0e39b93bdb353e1c009927ecadb763ce4bad19 | 9,138 | java | Java | src/test/java/ru/pravvich/web/rest/TaskResourceIntTest.java | triodjangopiter/jhipster-taskapp-mongo | 14414e2b6cbc1c8b26f8a464e3d507ed6dd3dd84 | [
"Apache-2.0"
] | 1 | 2019-01-14T17:23:29.000Z | 2019-01-14T17:23:29.000Z | src/test/java/ru/pravvich/web/rest/TaskResourceIntTest.java | triodjangopiter/jhipster-taskapp-mongo | 14414e2b6cbc1c8b26f8a464e3d507ed6dd3dd84 | [
"Apache-2.0"
] | null | null | null | src/test/java/ru/pravvich/web/rest/TaskResourceIntTest.java | triodjangopiter/jhipster-taskapp-mongo | 14414e2b6cbc1c8b26f8a464e3d507ed6dd3dd84 | [
"Apache-2.0"
] | null | null | null | 37.297959 | 101 | 0.687021 | 6,027 | package ru.pravvich.web.rest;
import ru.pravvich.TasksmongoApp;
import ru.pravvich.domain.Task;
import ru.pravvich.repository.TaskRepository;
import ru.pravvich.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static ru.pravvich.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the TaskResource REST controller.
*
* @see TaskResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TasksmongoApp.class)
public class TaskResourceIntTest {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final LocalDate DEFAULT_DUE_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DUE_DATE = LocalDate.now(ZoneId.systemDefault());
private static final Boolean DEFAULT_COMPLETED = false;
private static final Boolean UPDATED_COMPLETED = true;
@Autowired
private TaskRepository taskRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
private MockMvc restTaskMockMvc;
private Task task;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final TaskResource taskResource = new TaskResource(taskRepository);
this.restTaskMockMvc = MockMvcBuilders.standaloneSetup(taskResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Task createEntity() {
Task task = new Task()
.name(DEFAULT_NAME)
.dueDate(DEFAULT_DUE_DATE)
.completed(DEFAULT_COMPLETED);
return task;
}
@Before
public void initTest() {
taskRepository.deleteAll();
task = createEntity();
}
@Test
public void createTask() throws Exception {
int databaseSizeBeforeCreate = taskRepository.findAll().size();
// Create the Task
restTaskMockMvc.perform(post("/api/tasks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(task)))
.andExpect(status().isCreated());
// Validate the Task in the database
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeCreate + 1);
Task testTask = taskList.get(taskList.size() - 1);
assertThat(testTask.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testTask.getDueDate()).isEqualTo(DEFAULT_DUE_DATE);
assertThat(testTask.isCompleted()).isEqualTo(DEFAULT_COMPLETED);
}
@Test
public void createTaskWithExistingId() throws Exception {
int databaseSizeBeforeCreate = taskRepository.findAll().size();
// Create the Task with an existing ID
task.setId("existing_id");
// An entity with an existing ID cannot be created, so this API call must fail
restTaskMockMvc.perform(post("/api/tasks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(task)))
.andExpect(status().isBadRequest());
// Validate the Task in the database
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeCreate);
}
@Test
public void getAllTasks() throws Exception {
// Initialize the database
taskRepository.save(task);
// Get all the taskList
restTaskMockMvc.perform(get("/api/tasks?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(task.getId())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
.andExpect(jsonPath("$.[*].dueDate").value(hasItem(DEFAULT_DUE_DATE.toString())))
.andExpect(jsonPath("$.[*].completed").value(hasItem(DEFAULT_COMPLETED.booleanValue())));
}
@Test
public void getTask() throws Exception {
// Initialize the database
taskRepository.save(task);
// Get the task
restTaskMockMvc.perform(get("/api/tasks/{id}", task.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(task.getId()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
.andExpect(jsonPath("$.dueDate").value(DEFAULT_DUE_DATE.toString()))
.andExpect(jsonPath("$.completed").value(DEFAULT_COMPLETED.booleanValue()));
}
@Test
public void getNonExistingTask() throws Exception {
// Get the task
restTaskMockMvc.perform(get("/api/tasks/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
public void updateTask() throws Exception {
// Initialize the database
taskRepository.save(task);
int databaseSizeBeforeUpdate = taskRepository.findAll().size();
// Update the task
Task updatedTask = taskRepository.findOne(task.getId());
updatedTask
.name(UPDATED_NAME)
.dueDate(UPDATED_DUE_DATE)
.completed(UPDATED_COMPLETED);
restTaskMockMvc.perform(put("/api/tasks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedTask)))
.andExpect(status().isOk());
// Validate the Task in the database
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeUpdate);
Task testTask = taskList.get(taskList.size() - 1);
assertThat(testTask.getName()).isEqualTo(UPDATED_NAME);
assertThat(testTask.getDueDate()).isEqualTo(UPDATED_DUE_DATE);
assertThat(testTask.isCompleted()).isEqualTo(UPDATED_COMPLETED);
}
@Test
public void updateNonExistingTask() throws Exception {
int databaseSizeBeforeUpdate = taskRepository.findAll().size();
// Create the Task
// If the entity doesn't have an ID, it will be created instead of just being updated
restTaskMockMvc.perform(put("/api/tasks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(task)))
.andExpect(status().isCreated());
// Validate the Task in the database
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
public void deleteTask() throws Exception {
// Initialize the database
taskRepository.save(task);
int databaseSizeBeforeDelete = taskRepository.findAll().size();
// Get the task
restTaskMockMvc.perform(delete("/api/tasks/{id}", task.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Task.class);
Task task1 = new Task();
task1.setId("id1");
Task task2 = new Task();
task2.setId(task1.getId());
assertThat(task1).isEqualTo(task2);
task2.setId("id2");
assertThat(task1).isNotEqualTo(task2);
task1.setId(null);
assertThat(task1).isNotEqualTo(task2);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.