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
3e045350e9c2d6433bdac9470a54688bd18e7e05
1,848
java
Java
src/main/java/mixac1/dangerrpg/api/entity/EAWithExistIAttr.java
linkinkov/DangerRPG
3b4a419604aecb21827cf7fa203fb3cdae545579
[ "MIT" ]
1
2021-06-15T13:04:57.000Z
2021-06-15T13:04:57.000Z
src/main/java/mixac1/dangerrpg/api/entity/EAWithExistIAttr.java
ipl-adm/DangerRPG
3b4a419604aecb21827cf7fa203fb3cdae545579
[ "MIT" ]
null
null
null
src/main/java/mixac1/dangerrpg/api/entity/EAWithExistIAttr.java
ipl-adm/DangerRPG
3b4a419604aecb21827cf7fa203fb3cdae545579
[ "MIT" ]
2
2019-09-10T18:25:55.000Z
2020-05-23T16:29:18.000Z
29.333333
113
0.669913
1,813
package mixac1.dangerrpg.api.entity; import java.util.UUID; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.entity.ai.attributes.IAttributeInstance; public class EAWithExistIAttr extends EAWithIAttr { protected final UUID IDBase; public EAWithExistIAttr(String name, UUID IDBase, IAttribute attribute) { super(name, attribute); this.IDBase = IDBase; } @Override public void init(EntityLivingBase entity) { LvlEAProvider lvlProvider = getLvlProvider(entity); if (lvlProvider != null) { lvlProvider.init(entity); } } @Override public void serverInit(EntityLivingBase entity) {} @Override @Deprecated public Float getValueRaw(EntityLivingBase entity) { return (float) entity.getEntityAttribute(attribute).getAttributeValue(); } @Override @Deprecated public boolean setValueRaw(Float value, EntityLivingBase entity) { if (!value.equals(getValueRaw(entity)) && !entity.worldObj.isRemote) { IAttributeInstance attr = entity.getEntityAttribute(attribute); AttributeModifier mod = attr.getModifier(IDBase); if (mod != null) { attr.removeModifier(mod); } value -= (float) attr.getBaseValue(); AttributeModifier newMod = new AttributeModifier(IDBase, name, value, 0).setSaved(true); attr.applyModifier(newMod); return true; } return false; } @Override public Float getBaseValue(EntityLivingBase entity) { return (float) entity.getEntityAttribute(attribute).getBaseValue() + getModificatorValue(entity, IDBase); } }
3e045466df3ff0b6e473d79e910bcf9e9b71dd13
6,478
java
Java
mozu-java-core/src/main/java/com/mozu/api/clients/commerce/checkouts/PaymentClient.java
Mozu/mozu-java
1e672165f2dc280843f5263be953f51d9e7e2aea
[ "MIT" ]
4
2015-04-13T17:19:55.000Z
2021-02-09T16:49:45.000Z
mozu-java-core/src/main/java/com/mozu/api/clients/commerce/checkouts/PaymentClient.java
Mozu/mozu-java
1e672165f2dc280843f5263be953f51d9e7e2aea
[ "MIT" ]
4
2016-04-28T06:01:26.000Z
2019-10-22T12:15:02.000Z
mozu-java-core/src/main/java/com/mozu/api/clients/commerce/checkouts/PaymentClient.java
Mozu/mozu-java
1e672165f2dc280843f5263be953f51d9e7e2aea
[ "MIT" ]
14
2015-04-16T15:49:53.000Z
2022-01-09T04:41:54.000Z
51.824
272
0.763507
1,814
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce.checkouts; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use this resource to manage payments while the Checkouts resource is active (the Checkouts resource only applies to sites that enable shipping to multiple destinations within the same order). The Checkouts resource remains active until the shopper submits their order. * </summary> */ public class PaymentClient { /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> mozuClient=PerformPaymentActionClient( action, checkoutId, paymentId); * client.setBaseAddress(url); * client.executeRequest(); * Checkout checkout = client.Result(); * </code></pre></p> * @param checkoutId The unique identifier of the checkout. * @param paymentId Unique identifier of the payment for which to perform the action. * @param action The name of the action to perform. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.checkouts.Checkout> * @see com.mozu.api.contracts.commerceruntime.checkouts.Checkout * @see com.mozu.api.contracts.commerceruntime.payments.PaymentAction */ public static MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> performPaymentActionClient(com.mozu.api.contracts.commerceruntime.payments.PaymentAction action, String checkoutId, String paymentId) throws Exception { return performPaymentActionClient( action, checkoutId, paymentId, null); } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> mozuClient=PerformPaymentActionClient( action, checkoutId, paymentId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Checkout checkout = client.Result(); * </code></pre></p> * @param checkoutId The unique identifier of the checkout. * @param paymentId Unique identifier of the payment for which to perform the action. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param action The name of the action to perform. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.checkouts.Checkout> * @see com.mozu.api.contracts.commerceruntime.checkouts.Checkout * @see com.mozu.api.contracts.commerceruntime.payments.PaymentAction */ public static MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> performPaymentActionClient(com.mozu.api.contracts.commerceruntime.payments.PaymentAction action, String checkoutId, String paymentId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.checkouts.PaymentUrl.performPaymentActionUrl(checkoutId, paymentId, responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.commerceruntime.checkouts.Checkout.class; MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(action); return mozuClient; } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> mozuClient=CreatePaymentActionClient( action, checkoutId); * client.setBaseAddress(url); * client.executeRequest(); * Checkout checkout = client.Result(); * </code></pre></p> * @param checkoutId The unique identifier of the checkout. * @param action The name of the action to create. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.checkouts.Checkout> * @see com.mozu.api.contracts.commerceruntime.checkouts.Checkout * @see com.mozu.api.contracts.commerceruntime.payments.PaymentAction */ public static MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> createPaymentActionClient(com.mozu.api.contracts.commerceruntime.payments.PaymentAction action, String checkoutId) throws Exception { return createPaymentActionClient( action, checkoutId, null); } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> mozuClient=CreatePaymentActionClient( action, checkoutId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Checkout checkout = client.Result(); * </code></pre></p> * @param checkoutId The unique identifier of the checkout. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param action The name of the action to create. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.checkouts.Checkout> * @see com.mozu.api.contracts.commerceruntime.checkouts.Checkout * @see com.mozu.api.contracts.commerceruntime.payments.PaymentAction */ public static MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> createPaymentActionClient(com.mozu.api.contracts.commerceruntime.payments.PaymentAction action, String checkoutId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.checkouts.PaymentUrl.createPaymentActionUrl(checkoutId, responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.commerceruntime.checkouts.Checkout.class; MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.checkouts.Checkout>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(action); return mozuClient; } }
3e0455496ed8c647a488f8841d1c6dc44caed9a2
1,235
java
Java
src/test/java/org/chocosolver/util/CustomListener.java
philippe3263/choco-solver
f0148cc864dac946271f5959a7e2a00ffe1d9f92
[ "BSD-4-Clause" ]
1
2019-08-29T07:48:20.000Z
2019-08-29T07:48:20.000Z
src/test/java/org/chocosolver/util/CustomListener.java
philippe3263/choco-solver
f0148cc864dac946271f5959a7e2a00ffe1d9f92
[ "BSD-4-Clause" ]
null
null
null
src/test/java/org/chocosolver/util/CustomListener.java
philippe3263/choco-solver
f0148cc864dac946271f5959a7e2a00ffe1d9f92
[ "BSD-4-Clause" ]
null
null
null
23.75
107
0.631579
1,815
/** * This file is part of choco-solver, http://choco-solver.org/ * * Copyright (c) 2017, IMT Atlantique. All rights reserved. * * Licensed under the BSD 4-clause license. * See LICENSE file in the project root for full license information. */ package org.chocosolver.util; import org.testng.ITestResult; import org.testng.TestListenerAdapter; /** * <br/> * * @author Charles Prud'homme * @version choco * @since 20/08/2014 */ public class CustomListener extends TestListenerAdapter { private int m_count = 0; @Override public void onTestStart(ITestResult tr) { System.out.print(String.format("\t%s.%s ..", tr.getTestClass().getName(), tr.getName())); } @Override public void onTestFailure(ITestResult tr) { log(tr, "FAILURE"); } @Override public void onTestSkipped(ITestResult tr) { log(tr, "SKIP"); } @Override public void onTestSuccess(ITestResult tr) { log(tr, "SUCCESS"); } private void log(ITestResult tr, String RESULT) { System.out.print(String.format(".. %s (%dms)\n", RESULT, tr.getEndMillis() - tr.getStartMillis())); if (++m_count % 40 == 0) { System.out.println(""); } } }
3e045658ea72df799860d42a73898d994c3ab9c6
1,845
java
Java
spring-context-test/src/test/java/com/spring/test/prototype/clone/Resume.java
xwzl/spring-framework
e586c58f1f940651c168c4c30b37ac7a45e69993
[ "Apache-2.0" ]
null
null
null
spring-context-test/src/test/java/com/spring/test/prototype/clone/Resume.java
xwzl/spring-framework
e586c58f1f940651c168c4c30b37ac7a45e69993
[ "Apache-2.0" ]
null
null
null
spring-context-test/src/test/java/com/spring/test/prototype/clone/Resume.java
xwzl/spring-framework
e586c58f1f940651c168c4c30b37ac7a45e69993
[ "Apache-2.0" ]
null
null
null
21.964286
84
0.580488
1,816
package com.spring.test.prototype.clone; /** * 克隆 * * @author xuweizhi * @since 2020/06/15 14:21 */ public class Resume implements Cloneable { private String name; private String sex; private String age; private WorkExperience work; public Resume(String name) { this.name = name; work = new WorkExperience(); } public Resume(WorkExperience work) { this.work = work; } //设置个人信息 public void SetPersonalInfo(String sex, String age) { this.sex = sex; this.age = age; } //设置工作经历 public void SetWorkExperience(String workDate, String company) { work.setWorkDate(workDate); work.setCompany(company); } //显示 public void Display() { System.out.println(name + "\t" + sex + "\t" + age); System.out.println("工作经历:" + work.getWorkDate() + "\t" + work.getCompany()); } ///** // * Clone()方法是这样的,如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用 // * 但不复制引用的对象;因此,原始对象及其复本引用同一对象。 // */ //@Override //protected Object clone() throws CloneNotSupportedException { // return super.clone(); //} /** * 深复制 */ @Override protected Object clone() throws CloneNotSupportedException { Resume obj = (Resume) super.clone(); obj.work = (WorkExperience) obj.work.clone(); return obj; } public static void main(String[] args) throws CloneNotSupportedException { Resume a = new Resume("小明"); a.SetPersonalInfo("男", "29"); a.SetWorkExperience("1998-2000", "xx公司"); Resume b = (Resume) a.clone(); b.SetWorkExperience("1998-2018", "YY公司"); Resume c = (Resume) a.clone(); a.SetWorkExperience("1998-2000", "ZZ公司"); a.Display(); b.Display(); c.Display(); } }
3e045659eace1cd74b757740c943fce5a8e10f4b
377
java
Java
lang/src/main/java/pers/lee/common/lang/concurrent/ExecuteStatus.java
Leejaywell/common-module
079856c3fd161914a04edd6ca1087cfc8d2d1f11
[ "Apache-2.0" ]
null
null
null
lang/src/main/java/pers/lee/common/lang/concurrent/ExecuteStatus.java
Leejaywell/common-module
079856c3fd161914a04edd6ca1087cfc8d2d1f11
[ "Apache-2.0" ]
null
null
null
lang/src/main/java/pers/lee/common/lang/concurrent/ExecuteStatus.java
Leejaywell/common-module
079856c3fd161914a04edd6ca1087cfc8d2d1f11
[ "Apache-2.0" ]
null
null
null
15.708333
85
0.697613
1,817
package pers.lee.common.lang.concurrent; /** * The status of task * * @author Passyt * */ public enum ExecuteStatus { Wait(true), Executing(true), Finish(false), Cancel(false), Error(false), Lock(true); private boolean isRunning; private ExecuteStatus(boolean isRunning) { this.isRunning = isRunning; } public boolean isRunning() { return isRunning; } }
3e0457258e724cd9759a8ea9223f8727bb7ca334
61,142
java
Java
dockstore-client/src/main/java/io/dockstore/client/cli/nested/ToolClient.java
denis-yuen/dockstore-cli
b999d4042fc75f8e50b587742b33d257ddb6fece
[ "Apache-2.0" ]
1
2020-07-14T18:30:24.000Z
2020-07-14T18:30:24.000Z
dockstore-client/src/main/java/io/dockstore/client/cli/nested/ToolClient.java
denis-yuen/dockstore-cli
b999d4042fc75f8e50b587742b33d257ddb6fece
[ "Apache-2.0" ]
118
2019-09-13T16:08:31.000Z
2022-03-16T20:17:48.000Z
dockstore-client/src/main/java/io/dockstore/client/cli/nested/ToolClient.java
denis-yuen/dockstore-cli
b999d4042fc75f8e50b587742b33d257ddb6fece
[ "Apache-2.0" ]
4
2020-02-11T04:50:22.000Z
2022-01-07T16:31:05.000Z
46.706646
191
0.557566
1,818
/* * Copyright 2017 OICR * * 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.dockstore.client.cli.nested; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ws.rs.core.GenericType; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; import io.dockstore.client.cli.Client; import io.dockstore.client.cli.SwaggerUtility; import io.dockstore.common.DescriptorLanguage; import io.dockstore.common.Registry; import io.swagger.client.ApiException; import io.swagger.client.api.ContainersApi; import io.swagger.client.api.ContainertagsApi; import io.swagger.client.api.UsersApi; import io.swagger.client.model.DockstoreTool; import io.swagger.client.model.Label; import io.swagger.client.model.PublishRequest; import io.swagger.client.model.SourceFile; import io.swagger.client.model.StarRequest; import io.swagger.client.model.Tag; import io.swagger.client.model.ToolDescriptor; import io.swagger.client.model.User; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.validator.routines.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.dockstore.client.cli.ArgumentUtility.DESCRIPTION_HEADER; import static io.dockstore.client.cli.ArgumentUtility.GIT_HEADER; import static io.dockstore.client.cli.ArgumentUtility.MAX_DESCRIPTION; import static io.dockstore.client.cli.ArgumentUtility.NAME_HEADER; import static io.dockstore.client.cli.ArgumentUtility.boolWord; import static io.dockstore.client.cli.ArgumentUtility.columnWidthsTool; import static io.dockstore.client.cli.ArgumentUtility.containsHelpRequest; import static io.dockstore.client.cli.ArgumentUtility.errorMessage; import static io.dockstore.client.cli.ArgumentUtility.exceptionMessage; import static io.dockstore.client.cli.ArgumentUtility.optVal; import static io.dockstore.client.cli.ArgumentUtility.out; import static io.dockstore.client.cli.ArgumentUtility.outFormatted; import static io.dockstore.client.cli.ArgumentUtility.printHelpFooter; import static io.dockstore.client.cli.ArgumentUtility.printHelpHeader; import static io.dockstore.client.cli.ArgumentUtility.printLineBreak; import static io.dockstore.client.cli.ArgumentUtility.reqVal; import static io.swagger.client.model.DockstoreTool.ModeEnum.HOSTED; /** * Implement all operations that have to do with tools. * * @author dyuen */ public class ToolClient extends AbstractEntryClient<DockstoreTool> { public static final String UPDATE_TOOL = "update_tool"; private static final Logger LOG = LoggerFactory.getLogger(ToolClient.class); private final Client client; private ContainersApi containersApi; private ContainertagsApi containerTagsApi; private UsersApi usersApi; public ToolClient(Client client, boolean isAdmin) { /* for testing */ this.client = client; this.isAdmin = isAdmin; } public ToolClient(ContainersApi containersApi, ContainertagsApi containerTagsApi, UsersApi usersApi, Client client, boolean isAdmin) { this.containersApi = containersApi; this.containerTagsApi = containerTagsApi; this.usersApi = usersApi; this.client = client; this.isAdmin = isAdmin; } @Override public String getEntryType() { return "Tool"; } @Override public boolean processEntrySpecificCommands(List<String> args, String activeCommand) { if (null != activeCommand) { switch (activeCommand) { case "version_tag": versionTag(args); break; case ToolClient.UPDATE_TOOL: updateTool(args); break; default: return false; } return true; } return false; } private static void printToolList(List<DockstoreTool> containers) { containers.sort((c1, c2) -> c1.getPath().compareToIgnoreCase(c2.getPath())); int[] maxWidths = columnWidthsTool(containers); int nameWidth = maxWidths[0] + Client.PADDING; int descWidth = maxWidths[1] + Client.PADDING; int gitWidth = maxWidths[2] + Client.PADDING; String format = "%-" + nameWidth + "s%-" + descWidth + "s%-" + gitWidth + "s%-16s%-16s%-10s"; outFormatted(format, NAME_HEADER, DESCRIPTION_HEADER, GIT_HEADER, "PUBLISHED", "DESCRIPTOR", "AUTOMATED"); for (DockstoreTool container : containers) { String descriptor = "No"; String automated = "No"; String description = ""; String gitUrl = ""; if (container.isIsPublished()) { descriptor = "Yes"; } if (container.getGitUrl() != null && !container.getGitUrl().isEmpty()) { automated = "Yes"; gitUrl = container.getGitUrl(); } description = MoreObjects.firstNonNull(container.getDescription(), ""); if (description.length() > MAX_DESCRIPTION) { description = description.substring(0, MAX_DESCRIPTION - Client.PADDING) + "..."; } outFormatted(format, container.getToolPath(), description, gitUrl, boolWord(container.isIsPublished()), descriptor, automated); } } private static void printPublishedList(List<DockstoreTool> containers) { containers.sort((c1, c2) -> c1.getPath().compareToIgnoreCase(c2.getPath())); int[] maxWidths = columnWidthsTool(containers); int nameWidth = maxWidths[0] + Client.PADDING; int descWidth = maxWidths[1] + Client.PADDING; int gitWidth = maxWidths[2] + Client.PADDING; String format = "%-" + nameWidth + "s%-" + descWidth + "s%-" + gitWidth + "s"; outFormatted(format, NAME_HEADER, DESCRIPTION_HEADER, GIT_HEADER); for (DockstoreTool container : containers) { String description = ""; String gitUrl = ""; if (container.getGitUrl() != null && !container.getGitUrl().isEmpty()) { gitUrl = container.getGitUrl(); } description = getCleanedDescription(container.getDescription()); outFormatted(format, container.getToolPath(), description, gitUrl); } } protected void handleList() { try { // check user info after usage so that users can get usage without live webservice User user = usersApi.getUser(); if (user == null) { errorMessage("User not found", Client.CLIENT_ERROR); } List<DockstoreTool> containers = usersApi.userPublishedContainers(user.getId()); printPublishedList(containers); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } protected void handleSearch(String pattern) { try { List<DockstoreTool> containers = containersApi.allPublishedContainers(null, null, pattern, null, null); out("MATCHING TOOLS"); printLineBreak(); printToolList(containers); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } protected void handlePublishUnpublish(String entryPath, String newName, boolean unpublishRequest) { DockstoreTool existingTool = null; boolean isPublished = false; // Cannot be making an unpublish request with a specified new name assert (!(unpublishRequest && newName != null)); try { existingTool = containersApi.getContainerByToolPath(entryPath, null); isPublished = existingTool.isIsPublished(); } catch (ApiException ex) { exceptionMessage(ex, "Unable to " + (unpublishRequest ? "unpublish " : "publish ") + entryPath, Client.API_ERROR); } if (unpublishRequest) { if (isPublished) { publish(false, entryPath); } else { out("The following tool is already unpublished: " + entryPath); } } else { if (newName == null) { if (isPublished) { out("The following tool is already published: " + entryPath); } else { publish(true, entryPath); } } else if (!toolExists(entryPath + "/" + newName)) { try { DockstoreTool newContainer = new DockstoreTool(); // copy only the fields that we want to replicate, not sure why simply blanking // the returned container does not work newContainer.setMode(existingTool.getMode()); newContainer.setName(existingTool.getName()); newContainer.setNamespace(existingTool.getNamespace()); newContainer.setRegistryString(existingTool.getRegistryString()); newContainer.setDefaultDockerfilePath(existingTool.getDefaultDockerfilePath()); newContainer.setDefaultCwlPath(existingTool.getDefaultCwlPath()); newContainer.setDefaultWdlPath(existingTool.getDefaultWdlPath()); newContainer.setDefaultCWLTestParameterFile(existingTool.getDefaultCWLTestParameterFile()); newContainer.setDefaultWDLTestParameterFile(existingTool.getDefaultWDLTestParameterFile()); newContainer.setIsPublished(false); newContainer.setGitUrl(existingTool.getGitUrl()); newContainer.setToolname(newName); newContainer = containersApi.registerManual(newContainer); out("Successfully registered " + entryPath + "/" + newName); containersApi.refresh(newContainer.getId()); publish(true, newContainer.getToolPath()); } catch (ApiException ex) { exceptionMessage(ex, "Unable to publish " + newName, Client.API_ERROR); } } else { out("The following tool is already registered: " + entryPath + "/" + newName); } } } private boolean toolExists(String entryPath) { try { containersApi.getContainerByToolPath(entryPath, null); return true; } catch (ApiException ex) { return false; } } @Override protected void publishHelp() { printHelpHeader(); out("Usage: dockstore " + getEntryType().toLowerCase() + " publish --help"); out(" dockstore " + getEntryType().toLowerCase() + " publish"); out(" dockstore " + getEntryType().toLowerCase() + " publish [parameters]"); out(" dockstore " + getEntryType().toLowerCase() + " publish --unpub [parameters]"); out(""); out("Description:"); out(" Publish/unpublish a registered " + getEntryType() + "."); out(" No arguments will list the current and potential " + getEntryType() + "s to share."); out("Required Parameter(s):"); out(" --entry <entry> Complete " + getEntryType() + " path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out("Optional Parameter(s):"); out(" --new-entry-name <new-tool-name> " + "New name to give the tool specified by --entry. " + "This will register and publish a new copy of the tool with the given name."); printHelpFooter(); } @Override protected void handleTestParameter(String entry, String versionName, List<String> adds, List<String> removes, String descriptorType, String parentEntry) { try { DockstoreTool container = containersApi.getContainerByToolPath(entry, null); long containerId = container.getId(); if (adds.size() > 0) { containersApi.addTestParameterFiles(containerId, adds, descriptorType, "", versionName); } if (removes.size() > 0) { containersApi.deleteTestParameterFiles(containerId, removes, descriptorType, versionName); } if (adds.size() > 0 || removes.size() > 0) { containersApi.refresh(container.getId()); out("The test parameter files for tag " + versionName + " of tool " + parentEntry + " have been updated."); } else { out("Please provide at least one test parameter file to add or remove."); } } catch (ApiException ex) { exceptionMessage(ex, "There was an error updating the test parameter files for " + parentEntry + " version " + versionName, Client.API_ERROR); } } protected void handleListNonpublishedEntries() { try { // check user info after usage so that users can get usage without live webservice User user = usersApi.getUser(); if (user == null) { errorMessage("User not found", Client.CLIENT_ERROR); } List<DockstoreTool> containers = usersApi.userContainers(user.getId()); out("YOUR AVAILABLE CONTAINERS"); printLineBreak(); printToolList(containers); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } @Override protected void handleListUnstarredEntries() { try { List<DockstoreTool> containers = containersApi.allPublishedContainers(null, null, null, null, null); out("ALL PUBLISHED TOOLS"); printLineBreak(); printPublishedList(containers); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } private void publish(boolean publish, String entry) { String action = "publish"; if (!publish) { action = "unpublish"; } try { DockstoreTool container = containersApi.getContainerByToolPath(entry, null); //TODO where did the setter for PublishRequest go? PublishRequest pub = SwaggerUtility.createPublishRequest(publish); container = containersApi.publish(container.getId(), pub); if (container != null) { out("Successfully " + action + "ed " + entry); } else { errorMessage("Unable to " + action + " container " + entry, Client.COMMAND_ERROR); } } catch (ApiException ex) { exceptionMessage(ex, "Unable to " + action + " container " + entry, Client.API_ERROR); } } /** * Interacts with API to star/unstar a workflow * @param entry the workflow or tool * @param star true to star, false to unstar */ @Override protected void handleStarUnstar(String entry, boolean star) { String action = star ? "star" : "unstar"; try { DockstoreTool container = containersApi.getPublishedContainerByToolPath(entry, null); StarRequest request = new StarRequest(); request.setStar(star); containersApi.starEntry(container.getId(), request); out("Successfully " + action + "red " + entry); } catch (ApiException ex) { exceptionMessage(ex, "Unable to " + action + " container " + entry, Client.API_ERROR); } } // Checkstyle suppressed warnings should by fixed @Override @SuppressWarnings("checkstyle:methodlength") public void manualPublish(final List<String> args) { if (containsHelpRequest(args)) { manualPublishHelp(); } else if (args.isEmpty()) { printRegistriesAvailable(); } else { final String name = reqVal(args, "--name"); final String namespace = reqVal(args, "--namespace"); final String gitURL = reqVal(args, "--git-url"); final String dockerfilePath = optVal(args, "--dockerfile-path", "/Dockerfile"); final String cwlPath = optVal(args, "--cwl-path", "/Dockstore.cwl"); final String wdlPath = optVal(args, "--wdl-path", "/Dockstore.wdl"); final String testCwlPath = optVal(args, "--test-cwl-path", "/test.cwl.json"); final String testWdlPath = optVal(args, "--test-wdl-path", "/test.wdl.json"); final String gitReference = reqVal(args, "--git-reference"); final String toolname = optVal(args, "--toolname", null); final String toolMaintainerEmail = optVal(args, "--tool-maintainer-email", null); final String registry = optVal(args, "--registry", Registry.DOCKER_HUB.name()); final String privateAccess = optVal(args, "--private", "false"); final String customDockerPath = optVal(args, "--custom-docker-path", null); if (toolname != null && toolname.startsWith("_")) { errorMessage("Tool names cannot start with an underscore.", Client.CLIENT_ERROR); } // Check that registry is valid boolean validRegistry = Stream.of(Registry.values()).anyMatch(r -> r.name().equals(registry)); if (!validRegistry) { out("The registry \'" + registry + "\' is not available."); printRegistriesAvailable(); errorMessage("", Client.CLIENT_ERROR); } // Determine if chosen registry has special conditions boolean isPrivateRegistry = Stream.of(Registry.values()).anyMatch(r -> r.name().equals(registry) && r.isPrivateOnly()); boolean hasCustomDockerPath = Stream.of(Registry.values()).anyMatch(r -> r.name().equals(registry) && r.hasCustomDockerPath()); // Check if registry needs to override the docker path if (hasCustomDockerPath) { // Ensure that customDockerPath is not null // TODO: add validity checker for given path if (Strings.isNullOrEmpty(customDockerPath)) { errorMessage(registry + " requires a custom Docker path to be set.", Client.CLIENT_ERROR); } else if ("AMAZON_ECR".equals(registry) && !customDockerPath.matches("^[a-zA-Z0-9]+\\.dkr\\.ecr\\.[a-zA-Z0-9]+\\.amazonaws\\.com")) { errorMessage(registry + " must be of the form *.dkr.ecr.*.amazonaws.com, where * can be any alphanumeric character.", Client.CLIENT_ERROR); } else if ("SEVEN_BRIDGES".equals(registry) && !customDockerPath.matches("^([a-zA-Z0-9]+-)?images\\.sbgenomics\\.com")) { errorMessage(registry + " must be of the form *images.sbgenomics.com or images.sbgenomics.com, where * can be any alphanumeric character.", Client.CLIENT_ERROR); } } // Check for correct private access if (!("false".equalsIgnoreCase(privateAccess) || "true".equalsIgnoreCase(privateAccess))) { errorMessage("The possible values for --private are 'true' and 'false'.", Client.CLIENT_ERROR); } // Private access boolean setPrivateAccess = "true".equalsIgnoreCase(privateAccess); // Ensure that tool is set to private if it is a private only registry if (isPrivateRegistry) { if (!setPrivateAccess) { errorMessage(registry + " is private only and requires the tool to be private.", Client.CLIENT_ERROR); } } // Check that tool maintainer email is given if the tool is private with no email setup if (setPrivateAccess) { if (Strings.isNullOrEmpty(toolMaintainerEmail)) { errorMessage("For a private tool, the tool maintainer email is required.", Client.CLIENT_ERROR); } } // Check validity of email if (!Strings.isNullOrEmpty(toolMaintainerEmail)) { EmailValidator emailValidator = EmailValidator.getInstance(); if (!emailValidator.isValid(toolMaintainerEmail)) { errorMessage("The email address that you entered is invalid.", Client.CLIENT_ERROR); } } // Swagger does not fully copy the enum (leaves out properties), so we need to map Registry enum to RegistryEnum in DockstoreTool Optional<Registry> regEnum = getRegistryEnum(registry); if (regEnum.isEmpty()) { errorMessage("The registry that you entered does not exist. Run \'dockstore tool manual_publish\' to see valid registries.", Client.CLIENT_ERROR); } DockstoreTool tool = new DockstoreTool(); tool.setMode(DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH); tool.setName(name); tool.setNamespace(namespace); tool.setRegistryString(regEnum.get().getDockerPath()); // Registry path used (ex. quay.io) Optional<String> registryPath; // If the registry requires a custom docker path we must use it instead of the default if (hasCustomDockerPath) { registryPath = Optional.of(customDockerPath); } else { registryPath = getRegistryPath(registry); } if (registryPath.isEmpty()) { if (hasCustomDockerPath) { errorMessage("The registry path is unavailable.", Client.CLIENT_ERROR); } else { errorMessage( "The registry path is unavailable. Did you remember to enter a valid docker registry path and docker registry?", Client.CLIENT_ERROR); } } if (hasCustomDockerPath) { tool.setRegistryString(registryPath.get()); } tool.setDefaultDockerfilePath(dockerfilePath); tool.setDefaultCwlPath(cwlPath); tool.setDefaultWdlPath(wdlPath); tool.setDefaultCWLTestParameterFile(testCwlPath); tool.setDefaultWDLTestParameterFile(testWdlPath); tool.setIsPublished(false); tool.setGitUrl(gitURL); tool.setToolname(toolname); tool.setPrivateAccess(setPrivateAccess); tool.setToolMaintainerEmail(toolMaintainerEmail); // Check that tool has at least one default path if (Strings.isNullOrEmpty(cwlPath) && Strings.isNullOrEmpty(wdlPath)) { errorMessage("A tool must have at least one descriptor default path.", Client.CLIENT_ERROR); } if (!Registry.QUAY_IO.name().equals(registry)) { final String versionName = optVal(args, "--version-name", "latest"); final Tag tag = new Tag(); tag.setReference(gitReference); tag.setDockerfilePath(dockerfilePath); tag.setCwlPath(cwlPath); tag.setWdlPath(wdlPath); tag.setName(versionName); List<Tag> tagList = new ArrayList<>(); tagList.add(tag); tool.setWorkflowVersions(tagList); } // Register new tool final String fullName = Joiner.on("/").skipNulls().join(registryPath.get(), namespace, name, toolname); try { tool = containersApi.registerManual(tool); if (tool != null) { // Refresh to update validity containersApi.refresh(tool.getId()); // If registration is successful then attempt to publish it PublishRequest pub = SwaggerUtility.createPublishRequest(true); DockstoreTool publishedTool; try { publishedTool = containersApi.publish(tool.getId(), pub); if (publishedTool.isIsPublished()) { out("Successfully published " + fullName); } else { out("Successfully registered " + fullName + ", however it is not valid to publish."); // Should this throw an // error? } } catch (ApiException ex) { exceptionMessage(ex, "Successfully registered " + fullName + ", however it is not valid to publish.", Client.API_ERROR); } } else { errorMessage("Unable to register " + fullName, Client.COMMAND_ERROR); } } catch (final ApiException ex) { exceptionMessage(ex, "Unable to register " + fullName, Client.API_ERROR); } } } /** * Given a registry ENUM string, returns the matching registry enum * * @param registry * @return An optional value of the registry enum */ private Optional<Registry> getRegistryEnum(String registry) { for (Registry reg : Registry.values()) { if (registry.equals(reg.name())) { return Optional.of(reg); } } return Optional.empty(); } /** * Given a registry ENUM string, returns the default docker registry path * * @param registry * @return An optional docker registry path */ private Optional<String> getRegistryPath(String registry) { for (Registry r : Registry.values()) { if (registry.equals(r.name())) { if (r.hasCustomDockerPath()) { return Optional.of(null); } else { return Optional.of(r.toString()); } } } return Optional.empty(); } protected void refreshAllEntries() { try { User user = usersApi.getUser(); if (user == null) { throw new RuntimeException("User not found"); } out("Getting existing tools"); final List<DockstoreTool> dockstoreTools = usersApi.userContainers(user.getId()); final List<DockstoreTool> containers = dockstoreTools.stream() // Skip hosted tools as well as other tools that don't have git url (SEAB-1393) .filter(dockstoreTool -> StringUtils.isNotEmpty(dockstoreTool.getGitUrl())) .map(dockstoreTool -> { out(MessageFormat.format("Refreshing {0}", dockstoreTool.getToolPath())); try { return containersApi.refresh(dockstoreTool.getId()); } catch (ApiException ex) { exceptionMessage(ex, "", 0); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); out("YOUR UPDATED TOOLS"); printLineBreak(); printToolList(containers); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } public void refreshTargetEntry(String toolpath) { try { DockstoreTool container = containersApi.getContainerByToolPath(toolpath, null); final Long containerId = container.getId(); out("Refreshing tool..."); DockstoreTool updatedContainer = containersApi.refresh(containerId); List<DockstoreTool> containerList = new ArrayList<>(); containerList.add(updatedContainer); out("YOUR UPDATED TOOLS"); printLineBreak(); printToolList(containerList); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } public File downloadTargetEntry(String toolpath, ToolDescriptor.TypeEnum type, boolean unzip) { return downloadTargetEntry(toolpath, type, unzip, new File(System.getProperty("user.dir"))); } /** * Disturbingly similar to WorkflowClient#downloadTargetEntry, could use cleanup refactoring * @param toolpath a unique identifier for an entry, called a path for workflows and tools * @param unzip unzip the entry after downloading * @param type descriptor type * @param directory directory to unzip descriptors into * @return path to the primary descriptor */ public File downloadTargetEntry(String toolpath, ToolDescriptor.TypeEnum type, boolean unzip, File directory) { String[] parts = toolpath.split(":"); String path = parts[0]; DockstoreTool container = getDockstoreTool(path); final String fixTag = getVersionID(toolpath); Optional<Tag> first = container.getWorkflowVersions().stream().filter(foo -> foo.getName().equalsIgnoreCase(fixTag)).findFirst(); if (first.isPresent()) { Long versionId = first.get().getId(); // https://github.com/dockstore/dockstore/issues/1712 client seems to use jersey logging which is not controlled from logback containersApi.getApiClient().setDebugging(false); byte[] arbitraryURL = SwaggerUtility .getArbitraryURL("/containers/" + container.getId() + "/zip/" + versionId, new GenericType<byte[]>() { }, containersApi.getApiClient()); containersApi.getApiClient().setDebugging(Client.DEBUG.get()); try { File zipFile = new File(zipFilename(container)); FileUtils.writeByteArrayToFile(zipFile, arbitraryURL, false); if (unzip) { SwaggerUtility.unzipFile(zipFile, directory); } return new File(directory, type == ToolDescriptor.TypeEnum.CWL ? first.get().getCwlPath() : first.get().getWdlPath()); } catch (IOException e) { throw new RuntimeException("could not write zip file to disk, out of space?"); } } else { throw new RuntimeException("version not found"); } } /** * Returns the version ID for the provided entry path * @param entryPath Tool path */ @Override public String getVersionID(String entryPath) { final String[] parts = entryPath.split(":"); final DockstoreTool container = getDockstoreTool(parts[0]); // attempt to locate default version, fallback to 'latest' final String defaultVersion = container.getDefaultVersion() != null ? container.getDefaultVersion() : "latest"; // if a version is specified in the path, use that, otherwise uses the default version final String versionID = parts.length > 1 ? parts[1] : defaultVersion; Optional<Tag> firstTag = container.getWorkflowVersions().stream().filter(tag -> tag.getName().equalsIgnoreCase(versionID)) .findFirst(); if (firstTag.isEmpty()) { firstTag = container.getWorkflowVersions().stream().max(Comparator.comparing(Tag::getLastBuilt)); firstTag.ifPresent(tag -> out( "Could not locate tool with version '" + versionID + "'. Using last built version '" + tag.getName() + "' instead.")); } return firstTag.isEmpty() ? versionID : firstTag.get().getName(); } @Override public String zipFilename(DockstoreTool container) { return container.getToolPath().replaceAll("/", "_") + ".zip"; } public void handleLabels(String entryPath, Set<String> addsSet, Set<String> removesSet) { // Try and update the labels for the given container try { DockstoreTool container = containersApi.getContainerByToolPath(entryPath, null); long containerId = container.getId(); List<Label> existingLabels = container.getLabels(); String combinedLabelString = generateLabelString(addsSet, removesSet, existingLabels); DockstoreTool updatedContainer = containersApi.updateLabels(containerId, combinedLabelString, ""); List<Label> newLabels = updatedContainer.getLabels(); if (!newLabels.isEmpty()) { out("The container now has the following labels:"); for (Label newLabel : newLabels) { out(newLabel.getValue()); } } else { out("The container has no labels."); } } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } @Override public void handleInfo(String entryPath) { try { DockstoreTool container = containersApi.getPublishedContainerByToolPath(entryPath, null); if (container == null || !container.isIsPublished()) { errorMessage("This container is not published.", Client.COMMAND_ERROR); } else { final Long lastBuildLong = container.getLastBuild(); Date dateUploaded = null; if (lastBuildLong != null) { final Date lastBuild = new Date(lastBuildLong); dateUploaded = Date.from(lastBuild.toInstant()); } String description = container.getDescription(); if (description == null) { description = ""; } String author = container.getAuthor(); if (author == null) { author = ""; } String date = ""; if (dateUploaded != null) { date = dateUploaded.toString(); } out("DESCRIPTION:"); out(description); out("AUTHOR:"); out(author); if (dateUploaded != null) { out("DATE UPLOADED:"); out(date); } out("TAGS"); List<Tag> tags = container.getWorkflowVersions(); int tagSize = tags.size(); StringBuilder builder = new StringBuilder(); if (tagSize > 0) { builder.append(tags.get(0).getName()); for (int i = 1; i < tagSize; i++) { builder.append(", ").append(tags.get(i).getName()); } } out(builder.toString()); out("SOURCE CONTROL:"); if (Objects.equals(container.getMode(), HOSTED)) { out("Dockstore.org"); } else { out(container.getGitUrl()); } out("DOCKER IMAGE:"); out(container.getNamespace() + "/" + container.getName() + " on " + container.getRegistryString()); } } catch (ApiException ex) { exceptionMessage(ex, "Could not find container", Client.API_ERROR); } } private void versionTag(List<String> args) { if (args.isEmpty() || (containsHelpRequest(args) && !args.contains("add") && !args.contains("update") && !args .contains("remove"))) { versionTagHelp(); } else { String subcommand = args.remove(0); if (containsHelpRequest(args)) { switch (subcommand) { case "add": versionTagAddHelp(); return; case "remove": versionTagRemoveHelp(); return; case "update": versionTagUpdateHelp(); return; default: errorMessage("Please provide a correct subcommand", Client.CLIENT_ERROR); break; } } final String toolpath = reqVal(args, "--entry"); try { DockstoreTool container = containersApi.getContainerByToolPath(toolpath, null); long containerId = container.getId(); switch (subcommand) { case "add": if (containsHelpRequest(args)) { versionTagAddHelp(); } else { if (container.getMode() != DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH) { errorMessage("Only manually added images can add version tags.", Client.CLIENT_ERROR); } final String tagName = reqVal(args, "--name"); final String gitReference = reqVal(args, "--git-reference"); final Boolean hidden = Boolean.valueOf(optVal(args, "--hidden", "f")); final String cwlPath = optVal(args, "--cwl-path", "/Dockstore.cwl"); final String wdlPath = optVal(args, "--wdl-path", "/Dockstore.wdl"); final String dockerfilePath = optVal(args, "--dockerfile-path", "/Dockerfile"); final String imageId = reqVal(args, "--image-id"); final Tag tag = new Tag(); tag.setName(tagName); tag.setHidden(hidden); tag.setCwlPath(cwlPath); tag.setWdlPath(wdlPath); tag.setDockerfilePath(dockerfilePath); tag.setImageId(imageId); tag.setReference(gitReference); List<Tag> tags = new ArrayList<>(); tags.add(tag); List<Tag> updatedTags = containerTagsApi.addTags(containerId, tags); containersApi.refresh(container.getId()); out("The tool now has the following tags:"); for (Tag newTag : updatedTags) { out(newTag.getName()); } } break; case "update": if (containsHelpRequest(args)) { versionTagUpdateHelp(); } else { final String tagName = reqVal(args, "--name"); List<Tag> tags = Optional.ofNullable(container.getWorkflowVersions()).orElse(new ArrayList<>()); boolean updated = false; for (Tag tag : tags) { if (tag.getName().equals(tagName)) { final Boolean hidden = Boolean.valueOf(optVal(args, "--hidden", tag.isHidden().toString())); final String cwlPath = optVal(args, "--cwl-path", tag.getCwlPath()); final String wdlPath = optVal(args, "--wdl-path", tag.getWdlPath()); final String dockerfilePath = optVal(args, "--dockerfile-path", tag.getDockerfilePath()); final String imageId = optVal(args, "--image-id", tag.getImageId()); tag.setName(tagName); tag.setHidden(hidden); tag.setCwlPath(cwlPath); tag.setWdlPath(wdlPath); tag.setDockerfilePath(dockerfilePath); tag.setImageId(imageId); List<Tag> newTags = new ArrayList<>(); newTags.add(tag); containerTagsApi.updateTags(containerId, newTags); containersApi.refresh(container.getId()); out("Tag " + tagName + " has been updated."); updated = true; break; } } if (!updated) { errorMessage("Tag " + tagName + " does not exist.", Client.CLIENT_ERROR); } } break; case "remove": if (containsHelpRequest(args)) { versionTagRemoveHelp(); } else { if (container.getMode() != DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH) { errorMessage("Only manually added images can add version tags.", Client.CLIENT_ERROR); } final String tagName = reqVal(args, "--name"); List<Tag> tags = containerTagsApi.getTagsByPath(containerId); long tagId; boolean removed = false; for (Tag tag : tags) { if (tag.getName().equals(tagName)) { tagId = tag.getId(); containerTagsApi.deleteTags(containerId, tagId); removed = true; tags = containerTagsApi.getTagsByPath(containerId); out("The container now has the following tags:"); for (Tag newTag : tags) { out(newTag.getName()); } break; } } if (!removed) { errorMessage("Tag " + tagName + " does not exist.", Client.CLIENT_ERROR); } } break; default: errorMessage("Not a valid subcommand", Client.CLIENT_ERROR); break; } } catch (ApiException ex) { exceptionMessage(ex, "Could not find container", Client.API_ERROR); } } } private void updateTool(List<String> args) { if (args.isEmpty() || containsHelpRequest(args)) { updateToolHelp(); } else { final String toolpath = reqVal(args, "--entry"); try { DockstoreTool tool = containersApi.getContainerByToolPath(toolpath, null); long containerId = tool.getId(); final String cwlPath = optVal(args, "--cwl-path", tool.getDefaultCwlPath()); final String wdlPath = optVal(args, "--wdl-path", tool.getDefaultWdlPath()); final String dockerfilePath = optVal(args, "--dockerfile-path", tool.getDefaultDockerfilePath()); final String testCwlPath = optVal(args, "--test-cwl-path", tool.getDefaultCWLTestParameterFile()); final String testWdlPath = optVal(args, "--test-wdl-path", tool.getDefaultWDLTestParameterFile()); final String gitUrl = optVal(args, "--git-url", tool.getGitUrl()); final String defaultTag = optVal(args, "--default-version", tool.getDefaultVersion()); // Check that user did not use manual only attributes for an auto tool if (tool.getMode() != DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH && (args.contains("--private") || args .contains("--tool-maintainer-email"))) { out("--private and --tool-maintainer-email are only available for use with manually registered tools."); } final String toolMaintainerEmail = optVal(args, "--tool-maintainer-email", tool.getToolMaintainerEmail()); final String privateAccess = optVal(args, "--private", tool.isPrivateAccess().toString()); // Check for correct private access if (!("false".equalsIgnoreCase(privateAccess) || "true".equalsIgnoreCase(privateAccess))) { errorMessage("The possible values for --private are 'true' and 'false'.", Client.CLIENT_ERROR); } // Check that the tool maintainer email is valid if (tool.getMode() == DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH && !toolMaintainerEmail.equals(tool.getToolMaintainerEmail()) && !Strings.isNullOrEmpty(toolMaintainerEmail)) { EmailValidator emailValidator = EmailValidator.getInstance(); if (!emailValidator.isValid(toolMaintainerEmail)) { errorMessage("The email address that you entered is invalid.", Client.CLIENT_ERROR); } } tool.setDefaultCwlPath(cwlPath); tool.setDefaultWdlPath(wdlPath); tool.setDefaultDockerfilePath(dockerfilePath); tool.setDefaultCWLTestParameterFile(testCwlPath); tool.setDefaultWDLTestParameterFile(testWdlPath); tool.setGitUrl(gitUrl); // The following is only for manual tools as only they can be private tools if (tool.getMode() == DockstoreTool.ModeEnum.MANUAL_IMAGE_PATH) { // Can't set tool maintainer null for private, published repos unless tool author email exists if (tool.isIsPublished() && tool.isPrivateAccess()) { if (Strings.isNullOrEmpty(toolMaintainerEmail) && Strings.isNullOrEmpty(tool.getEmail())) { errorMessage("A published, private tool must have either an tool author email or tool maintainer email set up.", Client.CLIENT_ERROR); } } tool.setToolMaintainerEmail(toolMaintainerEmail); // privateAccess should be either 'true' or 'false' boolean setPrivateAccess = Boolean.parseBoolean(privateAccess); // When changing public tool to private and the tool is published, either tool author email or tool maintainer email must be set up if (setPrivateAccess && !tool.isPrivateAccess() && tool.isIsPublished()) { if (Strings.isNullOrEmpty(toolMaintainerEmail) && Strings.isNullOrEmpty(tool.getEmail())) { errorMessage("A published, private tool must have either an tool author email or tool maintainer email set up.", Client.CLIENT_ERROR); } } boolean isPrivateRegistry = Stream.of(Registry.values()) .anyMatch(r -> r.name().equals(tool.getRegistry().name()) && r.isPrivateOnly()); // Cannot set private only registry tools to public if (isPrivateRegistry) { if (!setPrivateAccess) { errorMessage(tool.getRegistry() + " is a private only Docker registry, which means that the tool cannot be set to public.", Client.CLIENT_ERROR); } } tool.setPrivateAccess(setPrivateAccess); } // Check that tool has at least one default path if (Strings.isNullOrEmpty(cwlPath) && Strings.isNullOrEmpty(wdlPath)) { errorMessage("A tool must have at least one descriptor default path.", Client.CLIENT_ERROR); } // if valid version boolean updateVersionSuccess = false; for (Tag tag : Optional.ofNullable(tool.getWorkflowVersions()).orElse(new ArrayList<>())) { if (tag.getName().equals(defaultTag)) { tool.setDefaultVersion(defaultTag); updateVersionSuccess = true; break; } } if (!updateVersionSuccess && defaultTag != null) { out("Not a valid version."); out("Valid versions include:"); for (Tag tag : Optional.ofNullable(tool.getWorkflowVersions()).orElse(new ArrayList<>())) { out(tag.getReference()); } errorMessage("Please enter a valid version.", Client.CLIENT_ERROR); } containersApi.updateContainer(containerId, tool); containersApi.refresh(containerId); out("The tool has been updated."); } catch (ApiException ex) { exceptionMessage(ex, "", Client.API_ERROR); } } } public SourceFile getDescriptorFromServer(String entry, DescriptorLanguage descriptorType) throws ApiException { String[] parts = entry.split(":"); String path = parts[0]; String tag = (parts.length > 1) ? parts[1] : null; SourceFile file = new SourceFile(); DockstoreTool container = getDockstoreTool(path); if (tag == null && container.getDefaultVersion() != null) { tag = container.getDefaultVersion(); } if (container != null) { file = containersApi.primaryDescriptor(container.getId(), tag, descriptorType.toString()); } else { errorMessage("No tool found with path " + entry, Client.API_ERROR); } return file; } private DockstoreTool getDockstoreTool(String path) { // simply getting published descriptors does not require permissions DockstoreTool container = null; try { container = containersApi.getPublishedContainerByToolPath(path, null); } catch (ApiException e) { if (e.getResponseBody().contains("Entry not found")) { LOG.info("Unable to locate entry without credentials, trying again as authenticated user"); container = containersApi.getContainerByToolPath(path, null); } } finally { if (container == null) { errorMessage("No tool found with path " + path, Client.ENTRY_NOT_FOUND); } } return container; } /** * This will attempt to launch a tool given the command arguments * */ void wesLaunch(String entry, String paramsPath, List<String> filePaths) { // Only supports workflows for the moment throw new RuntimeException("WES launch does not currently support tools. Please launch a workflow instead."); } @Override public Client getClient() { return client; } @Override public String getConfigFile() { return client.getConfigFile(); } // Help Commands protected void printClientSpecificHelp() { out(""); out(" version_tag : updates version tags for an individual tool"); out(""); out(" " + ToolClient.UPDATE_TOOL + " : updates certain fields of a tool"); out(""); out(" manual_publish : registers a manual tool in the dockstore and then attempt to publish"); out(""); } private static void updateToolHelp() { printHelpHeader(); out("Usage: dockstore tool " + UPDATE_TOOL + " --help"); out(" dockstore tool " + UPDATE_TOOL + " [parameters]"); out(""); out("Description:"); out(" Update certain fields for a given tool."); out(""); out("Required Parameters:"); out(" --entry <entry> Complete tool path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out(""); out("Optional Parameters"); out(" --cwl-path <cwl-path> Path to default cwl location"); out(" --wdl-path <wdl-path> Path to default wdl location"); out(" --test-cwl-path <test-cwl-path> Path to default test cwl location"); out(" --test-wdl-path <test-wdl-path> Path to default test wdl location"); out(" --dockerfile-path <dockerfile-path> Path to default dockerfile location"); out(" --git-url <git-url> Git url"); out(" --default-version <default-version> Default branch name"); out(" --tool-maintainer-email <tool-maintainer-email> Email of tool maintainer (Used for private tools). Manual tools only."); out(" --private <true/false> Private tools have private docker images, public tools do not. Manual tools only."); printHelpFooter(); } private static void versionTagHelp() { printHelpHeader(); out("Usage: dockstore tool version_tag --help"); out(" dockstore tool version_tag [command] --help"); out(" dockstore tool version_tag [command] [parameters]"); out(""); out("Description:"); out(" Add, update or remove version tags. For auto tools you can only update."); out(""); out("Commands:"); out(" add Add a new version tag"); out(""); out(" update Update an existing version tag"); out(""); out(" remove Remove an existing version tag"); printHelpFooter(); } private static void versionTagRemoveHelp() { printHelpHeader(); out("Usage: dockstore tool version_tag remove --help"); out(" dockstore tool version_tag remove [parameters]"); out(""); out("Description:"); out(" Remove an existing version tag of a tool."); out(""); out("Required Parameters:"); out(" --entry <entry> Complete tool path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out(" --name <name> Name of the version tag to remove"); printHelpFooter(); } private static void versionTagUpdateHelp() { printHelpHeader(); out("Usage: dockstore tool version_tag update --help"); out(" dockstore tool version_tag update [parameters]"); out(""); out("Description:"); out(" Update an existing version tag of a tool."); out(""); out("Required Parameters:"); out(" --entry <entry> Complete tool path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out(" --name <name> Name of the version tag to update"); out(""); out("Optional Parameters:"); out(" --hidden <true/false> Hide the tag from public viewing, default false"); out(" --cwl-path <cwl-path> Path to cwl location, defaults to tool default"); out(" --wdl-path <wdl-path> Path to wdl location, defaults to tool default"); out(" --dockerfile-path <dockerfile-path> Path to dockerfile location, defaults to tool default"); out(" --image-id <image-id> Docker image ID"); printHelpFooter(); } private static void versionTagAddHelp() { printHelpHeader(); out("Usage: dockstore tool version_tag add --help"); out(" dockstore tool version_tag add [parameters]"); out(""); out("Description:"); out(" Add a new version tag to a manually added tool."); out(""); out("Required Parameters:"); out(" --entry <entry> Complete tool path in the Dockstore (ex. quay.io/collaboratory/seqware-bwa-workflow)"); out(" --name <name> Name of the version tag to add"); out(""); out("Optional Parameters:"); out(" --git-reference <git-reference> Git reference for the version tag"); out(" --hidden <true/false> Hide the tag from public viewing, default false"); out(" --cwl-path <cwl-path> Path to cwl location, defaults to tool default"); out(" --wdl-path <wdl-path> Path to wdl location, defaults to tool default"); out(" --dockerfile-path <dockerfile-path> Path to dockerfile location, defaults to tool default"); out(" --image-id <image-id> Docker image ID"); printHelpFooter(); } private static void manualPublishHelp() { printHelpHeader(); out("Usage: dockstore tool manual_publish --help"); out(" dockstore tool manual_publish [parameters]"); out(""); out("Description:"); out(" Manually register an tool in the dockstore."); out(" No parameters will show the list of available registries."); out(""); out("Required parameters:"); out(" --name <name> Name for the docker container"); out(" --namespace <namespace> Organization for the docker container"); out(" --git-url <url> Reference to the git repo holding descriptor(s) and Dockerfile ex: \"[email protected]:user/test1.git\""); out(" --git-reference <reference> Reference to git branch or tag where the CWL and Dockerfile is checked-in"); out(""); out("Optional parameters:"); out(" --dockerfile-path <file> Path for the dockerfile, defaults to /Dockerfile"); out(" --cwl-path <file> Path for the CWL document, defaults to /Dockstore.cwl"); out(" --wdl-path <file> Path for the WDL document, defaults to /Dockstore.wdl"); out(" --test-cwl-path <test-cwl-path> Path to default test cwl location, defaults to /test.cwl.json"); out(" --test-wdl-path <test-wdl-path> Path to default test wdl location, defaults to /test.wdl.json"); out(" --toolname <toolname> Name of the tool, can be omitted, defaults to null"); out(" --registry <registry> Docker registry, can be omitted, defaults to DOCKER_HUB. Run command with no parameters to see available registries."); out(" --version-name <version> Version tag name for Dockerhub containers only, defaults to latest."); out(" --private <true/false> Is the tool private or not, defaults to false."); out(" --tool-maintainer-email <tool maintainer email> The contact email for the tool maintainer. Required for private repositories."); out(" --custom-docker-path <custom docker path> Custom Docker registry path (ex. registry.hub.docker.com). Only available for certain registries."); printHelpFooter(); } private static void printRegistriesAvailable() { out("The available Docker Registries are:"); for (Registry r : Registry.values()) { if (!r.hasCustomDockerPath()) { out(" *" + r.name() + " (" + r.toString() + ")"); } else { out(" *" + r.name() + " (Custom)"); } } } }
3e045864b5d1a996a8e96b7e5d6ef74e4be63f14
2,583
java
Java
solr/solrj/src/java/org/apache/solr/common/IteratorWriter.java
murx/solr
a25c53112e158cfb84c59518de66581fe98e1a6c
[ "Apache-2.0" ]
585
2015-01-04T06:12:50.000Z
2022-03-31T14:20:42.000Z
solr/solrj/src/java/org/apache/solr/common/IteratorWriter.java
murx/solr
a25c53112e158cfb84c59518de66581fe98e1a6c
[ "Apache-2.0" ]
394
2021-03-10T13:55:50.000Z
2022-03-31T23:29:56.000Z
solr/solrj/src/java/org/apache/solr/common/IteratorWriter.java
murx/solr
a25c53112e158cfb84c59518de66581fe98e1a6c
[ "Apache-2.0" ]
378
2015-01-13T11:40:27.000Z
2022-03-31T14:20:59.000Z
27.478723
94
0.657762
1,819
/* * 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.solr.common; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; /** * Interface to help do push writing to an array */ public interface IteratorWriter { /** * @param iw after this method returns , the ItemWriter Object is invalid * Do not hold a reference to this object */ void writeIter(ItemWriter iw) throws IOException; interface ItemWriter { /**The item could be any supported type */ ItemWriter add(Object o) throws IOException; default ItemWriter addNoEx(Object o) { try { add(o); } catch (IOException e) { throw new RuntimeException(e); } return this; } default ItemWriter add(int v) throws IOException { add((Integer) v); return this; } default ItemWriter add(long v) throws IOException { add((Long) v); return this; } default ItemWriter add(float v) throws IOException { add((Float) v); return this; } default ItemWriter add(double v) throws IOException { add((Double) v); return this; } default ItemWriter add(boolean v) throws IOException { add((Boolean) v); return this; } } default List<Object> toList(List<Object> l) { try { writeIter(new ItemWriter() { @Override public ItemWriter add(Object o) throws IOException { if (o instanceof MapWriter) o = ((MapWriter) o).toMap(new LinkedHashMap<>()); if (o instanceof IteratorWriter) o = ((IteratorWriter) o).toList(new ArrayList<>()); l.add(o); return this; } }); } catch (IOException e) { throw new RuntimeException(e); } return l; } }
3e04590301764ff9e32e137562d34bd421dfa42c
587
java
Java
src/main/java/com/mkotb/github/gson/GsonProvider.java
mkotb/github-webhook-java
e7b04c9687152497a3be1b0f2ee52b0ede3b28d7
[ "MIT" ]
null
null
null
src/main/java/com/mkotb/github/gson/GsonProvider.java
mkotb/github-webhook-java
e7b04c9687152497a3be1b0f2ee52b0ede3b28d7
[ "MIT" ]
null
null
null
src/main/java/com/mkotb/github/gson/GsonProvider.java
mkotb/github-webhook-java
e7b04c9687152497a3be1b0f2ee52b0ede3b28d7
[ "MIT" ]
null
null
null
27.952381
80
0.71891
1,820
package com.mkotb.github.gson; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Modifier; import java.util.Date; public class GsonProvider { private static final Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.STATIC) .registerTypeAdapter(Date.class, new GitHubDateAdapter()) .create(); public Gson get() { return gson; } }
3e04591cd68a3038338ea1e6ce4d10b2dfeede23
9,158
java
Java
mongodb/subsystem/src/main/java/org/wildfly/extension/nosql/cdi/MongoExtension.java
wildfly/wildfly-nosql
d9d608c21fc583e098eb97a3a6c906a832bd1514
[ "Apache-2.0" ]
8
2017-02-01T16:26:41.000Z
2020-02-29T05:39:10.000Z
mongodb/subsystem/src/main/java/org/wildfly/extension/nosql/cdi/MongoExtension.java
Jakarta-EE-Petclinic/wildfly-nosql
d9d608c21fc583e098eb97a3a6c906a832bd1514
[ "Apache-2.0" ]
4
2016-12-15T19:26:44.000Z
2017-11-20T21:55:54.000Z
mongodb/subsystem/src/main/java/org/wildfly/extension/nosql/cdi/MongoExtension.java
Jakarta-EE-Petclinic/wildfly-nosql
d9d608c21fc583e098eb97a3a6c906a832bd1514
[ "Apache-2.0" ]
10
2016-11-11T19:42:50.000Z
2022-03-01T15:50:48.000Z
34.689394
139
0.636274
1,821
/* * Copyright 2017 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.nosql.cdi; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanAttributes; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.InjectionPoint; import javax.enterprise.inject.spi.InjectionTarget; import javax.enterprise.inject.spi.InjectionTargetFactory; import org.jboss.as.server.CurrentServiceContainer; import org.wildfly.extension.nosql.subsystem.mongodb.MongoSubsystemService; import org.wildfly.nosql.common.ConnectionServiceAccess; import org.wildfly.nosql.common.SubsystemService; import org.wildfly.nosql.common.spi.NoSQLConnection; /** * This CDI Extension registers a <code>Mongoclient</code> * defined by @Inject in application beans * Registration will be aborted if user defines her own <code>MongoClient</code> bean or producer * * @author Antoine Sabot-Durand * @author Scott Marlow */ public class MongoExtension implements Extension { private final Class mongoClientClass; private final Class mongoDatabaseClass; public MongoExtension(Class mongoClientClass, Class mongoDatabaseClass) { this.mongoClientClass = mongoClientClass; this.mongoDatabaseClass = mongoDatabaseClass; } private static final Logger log = Logger.getLogger(MongoExtension.class.getName()); void registerNoSQLSourceBeans(@Observes AfterBeanDiscovery abd, BeanManager bm) { if (bm.getBeans(mongoClientClass, DefaultLiteral.INSTANCE).isEmpty()) { // Iterate profiles and create Cluster/Session bean for each profile, that application code can @Inject for(String profile: getService().profileNames()) { log.log(Level.INFO, "Registering bean for profile {0}", profile); abd.addBean(bm.createBean( new MongoClientBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(mongoClientClass)), profile), mongoClientClass, new MongoClientProducerFactory(profile, mongoClientClass))); abd.addBean(bm.createBean( new MongoDatabaseBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(mongoDatabaseClass)), profile), mongoDatabaseClass, new MongoDatabaseProducerFactory(profile, mongoDatabaseClass))); } } else { log.log(Level.INFO, "Application contains a default MongoClient Bean, automatic registration will be disabled"); } } private SubsystemService getService() { return (SubsystemService) CurrentServiceContainer.getServiceContainer().getService(MongoSubsystemService.serviceName()).getValue(); } private static class MongoClientBeanAttributes<T> implements BeanAttributes<T> { private BeanAttributes<T> delegate; private final String profile; MongoClientBeanAttributes(BeanAttributes<T> beanAttributes, String profile) { delegate = beanAttributes; this.profile = profile; } @Override public String getName() { return delegate.getName(); } @Override public Set<Annotation> getQualifiers() { Set<Annotation> qualifiers = new HashSet<>(delegate.getQualifiers()); NamedLiteral namedLiteral = new NamedLiteral(profile); // name the bean for @Inject @Named lookup qualifiers.add(namedLiteral); return qualifiers; } @Override public Class<? extends Annotation> getScope() { return ApplicationScoped.class; } @Override public Set<Class<? extends Annotation>> getStereotypes() { return delegate.getStereotypes(); } @Override public Set<Type> getTypes() { return delegate.getTypes(); } @Override public boolean isAlternative() { return delegate.isAlternative(); } } private static class MongoClientProducerFactory<T> implements InjectionTargetFactory<T> { final String profile; final Class mongoClientClass; MongoClientProducerFactory(String profile, Class mongoClientClass) { this.profile = profile; this.mongoClientClass = mongoClientClass; } @Override public InjectionTarget<T> createInjectionTarget(Bean<T> bean) { return new InjectionTarget<T>() { @Override public void inject(T instance, CreationalContext<T> ctx) { } @Override public void postConstruct(T instance) { } @Override public void preDestroy(T instance) { } @Override public T produce(CreationalContext<T> ctx) { NoSQLConnection noSQLConnection = ConnectionServiceAccess.connection(profile); return (T)noSQLConnection.unwrap(mongoClientClass); } @Override public void dispose(T connection) { // connection.close(); } @Override public Set<InjectionPoint> getInjectionPoints() { return Collections.EMPTY_SET; } }; } } private static class MongoDatabaseBeanAttributes<T> implements BeanAttributes<T> { private BeanAttributes<T> delegate; private final String profile; MongoDatabaseBeanAttributes(BeanAttributes<T> beanAttributes, String profile) { delegate = beanAttributes; this.profile = profile; } @Override public String getName() { return delegate.getName(); } @Override public Set<Annotation> getQualifiers() { Set<Annotation> qualifiers = new HashSet<>(delegate.getQualifiers()); NamedLiteral namedLiteral = new NamedLiteral(profile); // name the bean for @Inject @Named lookup qualifiers.add(namedLiteral); return qualifiers; } @Override public Class<? extends Annotation> getScope() { return ApplicationScoped.class; } @Override public Set<Class<? extends Annotation>> getStereotypes() { return delegate.getStereotypes(); } @Override public Set<Type> getTypes() { return delegate.getTypes(); } @Override public boolean isAlternative() { return delegate.isAlternative(); } } private static class MongoDatabaseProducerFactory<T> implements InjectionTargetFactory<T> { private final String profile; private final Class mongoDatabaseClass; MongoDatabaseProducerFactory(String profile, Class mongoDatabaseClass) { this.profile = profile; this.mongoDatabaseClass = mongoDatabaseClass; } @Override public InjectionTarget<T> createInjectionTarget(Bean<T> bean) { return new InjectionTarget<T>() { @Override public void inject(T instance, CreationalContext<T> ctx) { } @Override public void postConstruct(T instance) { } @Override public void preDestroy(T instance) { } @Override public T produce(CreationalContext<T> ctx) { NoSQLConnection noSQLConnection = ConnectionServiceAccess.connection(profile); return (T)noSQLConnection.unwrap(mongoDatabaseClass); } @Override public void dispose(T database) { } @Override public Set<InjectionPoint> getInjectionPoints() { return Collections.EMPTY_SET; } }; } } }
3e04593a8a4f218cdea07766fdd85ce2aa52da9b
1,173
java
Java
src/main/java/de/fdamken/minecraft/pe/facade/protocol/pocket/client/AbstractPocketClientPacket.java
fdamken/minecraft-pe-facade
e5d3ed8060301789530e4d4ff6aecefa9fc221cb
[ "Apache-2.0" ]
null
null
null
src/main/java/de/fdamken/minecraft/pe/facade/protocol/pocket/client/AbstractPocketClientPacket.java
fdamken/minecraft-pe-facade
e5d3ed8060301789530e4d4ff6aecefa9fc221cb
[ "Apache-2.0" ]
null
null
null
src/main/java/de/fdamken/minecraft/pe/facade/protocol/pocket/client/AbstractPocketClientPacket.java
fdamken/minecraft-pe-facade
e5d3ed8060301789530e4d4ff6aecefa9fc221cb
[ "Apache-2.0" ]
null
null
null
30.076923
79
0.714408
1,822
/* * #%L * Minecraft Pocket Edition Facade * %% * Copyright (C) 2016 - 2016 Fabian Damken * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.fdamken.minecraft.pe.facade.protocol.pocket.client; import de.fdamken.minecraft.pe.facade.protocol.pocket.AbstractPocketPacket; /** * Represents a pocket, client-bound packet. * */ public abstract class AbstractPocketClientPacket extends AbstractPocketPacket { /** * {@inheritDoc} * * @see de.fdamken.minecraft.pe.facade.protocol.Packet#getDirection() */ @Override public BoundDirection getDirection() { return BoundDirection.CLIENT_BOUND; } }
3e045962d2ebf158676eb18e02319cd7e7ca288c
2,901
java
Java
core-wih/src/main/java/io/elimu/a2d2/corewih/ServiceResponseDelegate.java
MrLarryMan/a2d2
c31ec709b49067aa76bd92a3971033ee48798f94
[ "Apache-2.0" ]
null
null
null
core-wih/src/main/java/io/elimu/a2d2/corewih/ServiceResponseDelegate.java
MrLarryMan/a2d2
c31ec709b49067aa76bd92a3971033ee48798f94
[ "Apache-2.0" ]
21
2021-01-29T16:08:20.000Z
2022-03-17T14:52:23.000Z
core-wih/src/main/java/io/elimu/a2d2/corewih/ServiceResponseDelegate.java
MrLarryMan/a2d2
c31ec709b49067aa76bd92a3971033ee48798f94
[ "Apache-2.0" ]
1
2021-07-20T02:43:08.000Z
2021-07-20T02:43:08.000Z
32.965909
94
0.750776
1,823
// Copyright 2018-2020 Elimu Informatics // // 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.elimu.a2d2.corewih; import java.util.Map; import java.util.Map.Entry; import org.kie.api.runtime.process.WorkItem; import org.kie.api.runtime.process.WorkItemHandler; import org.kie.api.runtime.process.WorkItemManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.elimu.a2d2.genericmodel.ServiceResponse; public class ServiceResponseDelegate implements WorkItemHandler { private static final String SERVICE_RESPONSE = "serviceResponse"; private static final String RESPONSE_CODE = "responseCode"; private static final String HEADER_VALUE_PARAM = "header_value_"; private static final String RESPONSE_BODY = "body"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { Map<String, Object> workItemResult = workItem.getResults(); String body = (String) workItem.getParameter(RESPONSE_BODY); Object objResponseCode = workItem.getParameter(RESPONSE_CODE); Integer responseCode = null; if (objResponseCode != null) { responseCode = Integer.valueOf(workItem.getParameter(RESPONSE_CODE).toString()); } ServiceResponse serviceResponse = (ServiceResponse) workItem.getParameter(SERVICE_RESPONSE); if (serviceResponse == null) { serviceResponse = new ServiceResponse(); } if (body == null) { logger.warn("body is null"); } else { serviceResponse.setBody(body); } if (responseCode == null) { logger.warn("responseCode is null"); } else { serviceResponse.setResponseCode(responseCode); } for (Entry<String, Object> entry : workItem.getParameters().entrySet()) { if (entry.getKey().startsWith(HEADER_VALUE_PARAM)) { String key = entry.getKey().replace(HEADER_VALUE_PARAM, ""); if (key.contains("__")) { key = key.replace("__", "-"); } serviceResponse.addHeaderValue(key, (String) entry.getValue()); } } workItemResult.put(SERVICE_RESPONSE, serviceResponse); manager.completeWorkItem(workItem.getId(), workItemResult); logger.trace("Service Response Delegate execution completed"); } @Override public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { manager.abortWorkItem(workItem.getId()); logger.warn("Service Response delegate Aborted"); } }
3e045976f7cd3959851105a920c9dc8c51aaba89
2,567
java
Java
test/testsuite/ouroboros/rc_test/RC0257-rc-function-ROSAlloc-Alloc_3_10x8B/Alloc_3_10x8B.java
openmaple/MapleCompiler
1648e63144766563f1ec44a25e0b618415648627
[ "MulanPSL-1.0" ]
5
2019-09-02T04:44:52.000Z
2021-11-08T12:23:51.000Z
test/testsuite/ouroboros/rc_test/RC0257-rc-function-ROSAlloc-Alloc_3_10x8B/Alloc_3_10x8B.java
venshine/OpenArkCompiler
264cd4463834356658154f0d254672ef559f245f
[ "MulanPSL-1.0" ]
2
2020-07-21T01:22:01.000Z
2021-12-06T08:07:16.000Z
test/testsuite/ouroboros/rc_test/RC0257-rc-function-ROSAlloc-Alloc_3_10x8B/Alloc_3_10x8B.java
venshine/OpenArkCompiler
264cd4463834356658154f0d254672ef559f245f
[ "MulanPSL-1.0" ]
4
2019-09-02T04:46:52.000Z
2020-09-10T11:30:03.000Z
33.337662
164
0.600701
1,824
/* *- @TestCaseID:Alloc_3_10x8B *- @TestCaseName:MyselfClassName *- @RequirementName:[运行时需求]支持自动内存管理 *- @Title:ROS Allocator is in charge of applying and releasing objects.This testcase is mainly for testing objects from 3*8B to 10*8B(max) *- @Condition: no * -#c1 *- @Brief:functionTest * -#step1 *- @Expect:ExpectResult\n *- @Priority: High *- @Source: Alloc_3_10x8B.java *- @ExecuteClass: Alloc_3_10x8B *- @ExecuteArgs: *- @Remark: */ import java.util.ArrayList; public class Alloc_3_10x8B { private final static int PAGE_SIZE=4*1024; private final static int OBJ_HEADSIZE = 8; private final static int MAX_3_8B=3*8; private final static int MAX_4_8B=4*8; private final static int MAX_5_8B=5*8; private final static int MAX_6_8B=6*8; private final static int MAX_7_8B=7*8; private final static int MAX_8_8B=8*8; private final static int MAX_9_8B=9*8; private final static int MAX_10_8B=10*8; private static ArrayList<byte[]> store; private static int alloc_test(int slot_type){ store=new ArrayList<byte[]>(); byte[] temp; int i; if(slot_type==24){ i=1;} else if(slot_type==1024){ i=64*8+1-OBJ_HEADSIZE; }else{ i=slot_type-2*8+1; } for(;i<=slot_type-OBJ_HEADSIZE;i++) { for(int j=0;j<(PAGE_SIZE/(i+OBJ_HEADSIZE)+10);j++) { temp = new byte[i]; store.add(temp); } } int check_size=store.size(); store=new ArrayList<byte[]>(); return check_size; } public static void main(String[] args){ store=new ArrayList<byte[]>(); int countSize3 = alloc_test(MAX_3_8B); int countSize4 = alloc_test(MAX_4_8B); int countSize5 = alloc_test(MAX_5_8B); int countSize6 = alloc_test(MAX_6_8B); int countSize7 = alloc_test(MAX_7_8B); int countSize8 = alloc_test(MAX_8_8B); int countSize9 = alloc_test(MAX_9_8B); int countSize10 = alloc_test(MAX_10_8B); if(countSize3==4488 && countSize4==1234 && countSize5==978 && countSize6==816 && countSize7==701 && countSize8==620 &&countSize9==556 && countSize10==505 ) System.out.println("ExpectResult"); else System.out.println("Error"); } } // EXEC:%maple %f %build_option -o %n.so // EXEC:%run %n.so %n %run_option | compare %f // ASSERT: scan-full ExpectResult\n
3e045a947ae9ac11d9dff80ad73ae937c53d2aa5
700
java
Java
jframe-web-test/quartz/src/main/java/com/jf/system/quartz/jobs/Job1.java
qurikuduo/JFrameBoot
2ee99209ab156ea08d6c07b35cb279ef7dc2f6bf
[ "BSD-3-Clause" ]
7
2018-01-26T03:26:51.000Z
2019-08-30T10:35:05.000Z
jframe-web-test/quartz/src/main/java/com/jf/system/quartz/jobs/Job1.java
qurikuduo/JFrameBoot
2ee99209ab156ea08d6c07b35cb279ef7dc2f6bf
[ "BSD-3-Clause" ]
2
2019-12-13T03:09:41.000Z
2020-06-17T03:15:40.000Z
jframe-web-test/quartz/src/main/java/com/jf/system/quartz/jobs/Job1.java
qurikuduo/JFrameBoot
2ee99209ab156ea08d6c07b35cb279ef7dc2f6bf
[ "BSD-3-Clause" ]
3
2018-03-27T14:36:21.000Z
2019-08-30T08:03:57.000Z
23.333333
106
0.76
1,825
package com.jf.system.quartz.jobs; import com.jf.service.JobService; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; import javax.annotation.Resource; /** * Created with IntelliJ IDEA. * Description: * User: xujunfei * Date: 2018-03-02 * Time: 16:09 */ @DisallowConcurrentExecution public class Job1 extends QuartzJobBean { @Resource private JobService jobService; @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { jobService.test("###### Job1 ######"); } }
3e045a9ab6f04e7a7ad294f7ead1b365cad2923f
3,505
java
Java
shardingsphere-features/shardingsphere-encrypt/shardingsphere-encrypt-core/src/test/java/org/apache/shardingsphere/encrypt/distsql/update/DropEncryptRuleStatementUpdaterTest.java
zzq1314zll/shardingsphere
bfb784c9a0e47fd147c8a654c2f0b2a1e86c2c27
[ "Apache-2.0" ]
1
2021-08-05T05:59:11.000Z
2021-08-05T05:59:11.000Z
shardingsphere-features/shardingsphere-encrypt/shardingsphere-encrypt-core/src/test/java/org/apache/shardingsphere/encrypt/distsql/update/DropEncryptRuleStatementUpdaterTest.java
zzq1314zll/shardingsphere
bfb784c9a0e47fd147c8a654c2f0b2a1e86c2c27
[ "Apache-2.0" ]
null
null
null
shardingsphere-features/shardingsphere-encrypt/shardingsphere-encrypt-core/src/test/java/org/apache/shardingsphere/encrypt/distsql/update/DropEncryptRuleStatementUpdaterTest.java
zzq1314zll/shardingsphere
bfb784c9a0e47fd147c8a654c2f0b2a1e86c2c27
[ "Apache-2.0" ]
null
null
null
50.797101
178
0.789729
1,826
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.encrypt.distsql.update; import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration; import org.apache.shardingsphere.encrypt.api.config.rule.EncryptColumnRuleConfiguration; import org.apache.shardingsphere.encrypt.api.config.rule.EncryptTableRuleConfiguration; import org.apache.shardingsphere.encrypt.distsql.exception.EncryptRuleNotExistedException; import org.apache.shardingsphere.encrypt.distsql.parser.statement.DropEncryptRuleStatement; import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration; import org.apache.shardingsphere.infra.metadata.resource.ShardingSphereResource; import org.junit.Test; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Properties; import static org.mockito.Mockito.mock; public final class DropEncryptRuleStatementUpdaterTest { private final DropEncryptRuleStatementUpdater updater = new DropEncryptRuleStatementUpdater(); @Test(expected = EncryptRuleNotExistedException.class) public void assertCheckSQLStatementWithoutCurrentRule() { updater.checkSQLStatement("foo", createSQLStatement(), null, mock(ShardingSphereResource.class)); } @Test(expected = EncryptRuleNotExistedException.class) public void assertCheckSQLStatementWithoutToBeDroppedRule() { updater.checkSQLStatement("foo", createSQLStatement(), new EncryptRuleConfiguration(Collections.emptyList(), Collections.emptyMap()), mock(ShardingSphereResource.class)); } @Test public void assertUpdateCurrentRuleConfiguration() { updater.updateCurrentRuleConfiguration("foo", createSQLStatement(), createCurrentRuleConfiguration()); // TODO assert current rule configuration } private DropEncryptRuleStatement createSQLStatement() { return new DropEncryptRuleStatement(Collections.singleton("t_encrypt")); } private EncryptRuleConfiguration createCurrentRuleConfiguration() { EncryptColumnRuleConfiguration columnRuleConfig = new EncryptColumnRuleConfiguration("user_id", "user_cipher", "", "user_plain", "t_encrypt_user_id_MD5"); EncryptTableRuleConfiguration tableRuleConfig = new EncryptTableRuleConfiguration("t_encrypt", Collections.singleton(columnRuleConfig)); Map<String, ShardingSphereAlgorithmConfiguration> encryptors = new HashMap<>(1, 1); encryptors.put("t_encrypt_user_id_MD5", new ShardingSphereAlgorithmConfiguration("TEST", new Properties())); return new EncryptRuleConfiguration(new LinkedList<>(Collections.singleton(tableRuleConfig)), encryptors, true); } }
3e045afd7619ef85341ef4da812dd4b3fdec11c5
664
java
Java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/DslErrorReporter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/DslErrorReporter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/DslErrorReporter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
44.266667
140
0.813253
1,827
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.dsl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; public abstract class DslErrorReporter { public static DslErrorReporter getInstance() { return ApplicationManager.getApplication().getService(DslErrorReporter.class); } public abstract void invokeDslErrorPopup(Throwable e, final Project project, @NotNull VirtualFile vfile); }
3e045b2d2068d6f7fd4041db53b0506c9e5ea71f
1,597
java
Java
XiaoYuanFenApp/commonlibrary/src/main/java/foundation/widget/recyclerView/ResourceItemDivider.java
fugx/XiaoYuanFen
6b936f023601fc6058ba112266d06c72147a2b62
[ "Apache-2.0" ]
null
null
null
XiaoYuanFenApp/commonlibrary/src/main/java/foundation/widget/recyclerView/ResourceItemDivider.java
fugx/XiaoYuanFen
6b936f023601fc6058ba112266d06c72147a2b62
[ "Apache-2.0" ]
null
null
null
XiaoYuanFenApp/commonlibrary/src/main/java/foundation/widget/recyclerView/ResourceItemDivider.java
fugx/XiaoYuanFen
6b936f023601fc6058ba112266d06c72147a2b62
[ "Apache-2.0" ]
null
null
null
33.270833
86
0.673763
1,828
package foundation.widget.recyclerView; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by wujian on 2017/1/2. */ public class ResourceItemDivider extends RecyclerView.ItemDecoration { private Drawable mDrawable; /** * 作为Divider的Drawable对象 * * @param context 当前上下文用于获取资源 * @param resId color drawable等类型资源文件 */ public ResourceItemDivider(Context context, int resId) { mDrawable = ContextCompat.getDrawable(context,resId); } public void onDrawOver(Canvas c, RecyclerView parent) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); //以下计算主要用来确定绘制的位置 final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDrawable.getIntrinsicHeight(); mDrawable.setBounds(left, top, right, bottom); mDrawable.draw(c); } } public void getItemOffsets(Rect outRect, int position, RecyclerView parent) { outRect.set(0, 0, 0, mDrawable.getIntrinsicWidth()); } }
3e045b94d6c6deda7efcc6c0a91170a742fcb7ae
2,553
java
Java
src/main/java/com/microsoft/graph/requests/extensions/DomainCollectionRequestBuilder.java
ashwanikumar04/msgraph-sdk-java
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
[ "MIT" ]
1
2021-05-17T07:56:01.000Z
2021-05-17T07:56:01.000Z
src/main/java/com/microsoft/graph/requests/extensions/DomainCollectionRequestBuilder.java
ashwanikumar04/msgraph-sdk-java
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
[ "MIT" ]
21
2021-02-01T08:37:29.000Z
2022-03-02T11:07:27.000Z
src/main/java/com/microsoft/graph/requests/extensions/DomainCollectionRequestBuilder.java
ashwanikumar04/msgraph-sdk-java
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
[ "MIT" ]
null
null
null
39.890625
177
0.708186
1,829
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.Domain; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.requests.extensions.IDomainCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IDomainRequestBuilder; import com.microsoft.graph.requests.extensions.IDomainCollectionRequest; import com.microsoft.graph.http.BaseRequestBuilder; import com.microsoft.graph.core.IBaseClient; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Domain Collection Request Builder. */ public class DomainCollectionRequestBuilder extends BaseRequestBuilder implements IDomainCollectionRequestBuilder { /** * The request builder for this collection of Domain * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public DomainCollectionRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the IUserRequest instance */ public IDomainCollectionRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request * * @param requestOptions the options for this request * @return the IUserRequest instance */ public IDomainCollectionRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new DomainCollectionRequest(getRequestUrl(), getClient(), requestOptions); } public IDomainRequestBuilder byId(final String id) { return new DomainRequestBuilder(getRequestUrlWithAdditionalSegment(id), getClient(), getOptions()); } }
3e045bec6122f930391b328681ef78db50365b72
1,565
java
Java
bbs/test/com/fancige/main/CommonPostManagerTest.java
fancige/exercise
63c025710581782e982ab53c54c2f26bb414c448
[ "MIT" ]
null
null
null
bbs/test/com/fancige/main/CommonPostManagerTest.java
fancige/exercise
63c025710581782e982ab53c54c2f26bb414c448
[ "MIT" ]
null
null
null
bbs/test/com/fancige/main/CommonPostManagerTest.java
fancige/exercise
63c025710581782e982ab53c54c2f26bb414c448
[ "MIT" ]
null
null
null
30.096154
89
0.799361
1,830
package com.fancige.main; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import com.fancige.util.StringHandler; public class CommonPostManagerTest { private String randomId1; private String randomId2; private String normalPostid = "1234567890"; private String deletePostid = "1234567891"; private String realUserid = "111111"; @Before public void setUp() { randomId1 = StringHandler.getRandomNumber(15); randomId2 = StringHandler.getRandomNumber(15); } @Test public void testTestPostid() { assertEquals(0, CommonPostManager.testPostid(normalPostid)); assertEquals(1, CommonPostManager.testPostid(deletePostid)); assertEquals(-1, CommonPostManager.testPostid(randomId1)); } @Test public void testUpdatePostid1() { assertEquals(-1, CommonPostManager.testPostid(randomId1)); CommonPostManager.updatePostid(randomId1, realUserid, CommonPostManager.NORMAL_POSTID); assertEquals(0, CommonPostManager.testPostid(randomId1)); CommonPostManager.updatePostid(randomId1, realUserid, CommonPostManager.DELETE_POSTID); assertEquals(1, CommonPostManager.testPostid(randomId1)); } @Test public void testUpdatePostid2() { assertEquals(-1, CommonPostManager.testPostid(randomId1)); CommonPostManager.updatePostid(randomId1, randomId2, CommonPostManager.NORMAL_POSTID); assertEquals(0, CommonPostManager.testPostid(randomId1)); CommonPostManager.updatePostid(randomId1, randomId2, CommonPostManager.DELETE_POSTID); assertEquals(1, CommonPostManager.testPostid(randomId1)); } }
3e045c084ef483a62b789643c5dd3dbd4dd9712d
4,310
java
Java
src/main/java/com/amazonaws/services/cloudformation/model/transform/CreateStackRequestMarshaller.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
2
2015-04-09T03:30:56.000Z
2020-07-06T20:23:21.000Z
src/main/java/com/amazonaws/services/cloudformation/model/transform/CreateStackRequestMarshaller.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazonaws/services/cloudformation/model/transform/CreateStackRequestMarshaller.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
4
2015-02-03T19:36:40.000Z
2020-07-06T20:30:56.000Z
42.254902
166
0.695592
1,831
/* * Copyright 2010-2012 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.cloudformation.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.cloudformation.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Create Stack Request Marshaller */ public class CreateStackRequestMarshaller implements Marshaller<Request<CreateStackRequest>, CreateStackRequest> { public Request<CreateStackRequest> marshall(CreateStackRequest createStackRequest) { if (createStackRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<CreateStackRequest> request = new DefaultRequest<CreateStackRequest>(createStackRequest, "AmazonCloudFormation"); request.addParameter("Action", "CreateStack"); request.addParameter("Version", "2010-05-15"); if (createStackRequest.getStackName() != null) { request.addParameter("StackName", StringUtils.fromString(createStackRequest.getStackName())); } if (createStackRequest.getTemplateBody() != null) { request.addParameter("TemplateBody", StringUtils.fromString(createStackRequest.getTemplateBody())); } if (createStackRequest.getTemplateURL() != null) { request.addParameter("TemplateURL", StringUtils.fromString(createStackRequest.getTemplateURL())); } java.util.List<Parameter> parametersList = createStackRequest.getParameters(); int parametersListIndex = 1; for (Parameter parametersListValue : parametersList) { Parameter parameterMember = parametersListValue; if (parameterMember != null) { if (parameterMember.getParameterKey() != null) { request.addParameter("Parameters.member." + parametersListIndex + ".ParameterKey", StringUtils.fromString(parameterMember.getParameterKey())); } if (parameterMember.getParameterValue() != null) { request.addParameter("Parameters.member." + parametersListIndex + ".ParameterValue", StringUtils.fromString(parameterMember.getParameterValue())); } } parametersListIndex++; } if (createStackRequest.isDisableRollback() != null) { request.addParameter("DisableRollback", StringUtils.fromBoolean(createStackRequest.isDisableRollback())); } if (createStackRequest.getTimeoutInMinutes() != null) { request.addParameter("TimeoutInMinutes", StringUtils.fromInteger(createStackRequest.getTimeoutInMinutes())); } java.util.List<String> notificationARNsList = createStackRequest.getNotificationARNs(); int notificationARNsListIndex = 1; for (String notificationARNsListValue : notificationARNsList) { if (notificationARNsListValue != null) { request.addParameter("NotificationARNs.member." + notificationARNsListIndex, StringUtils.fromString(notificationARNsListValue)); } notificationARNsListIndex++; } java.util.List<String> capabilitiesList = createStackRequest.getCapabilities(); int capabilitiesListIndex = 1; for (String capabilitiesListValue : capabilitiesList) { if (capabilitiesListValue != null) { request.addParameter("Capabilities.member." + capabilitiesListIndex, StringUtils.fromString(capabilitiesListValue)); } capabilitiesListIndex++; } return request; } }
3e045d85689dc17ba0b0626ef5a3d5e1aebaa126
2,406
java
Java
src/main/java/constructmod/cards/HastyRepair.java
dbrowncode/StS-ConstructMod
ca0924ce36aa7cfd1020125bfa9567a22753e668
[ "MIT" ]
null
null
null
src/main/java/constructmod/cards/HastyRepair.java
dbrowncode/StS-ConstructMod
ca0924ce36aa7cfd1020125bfa9567a22753e668
[ "MIT" ]
null
null
null
src/main/java/constructmod/cards/HastyRepair.java
dbrowncode/StS-ConstructMod
ca0924ce36aa7cfd1020125bfa9567a22753e668
[ "MIT" ]
null
null
null
37.015385
109
0.798836
1,832
package constructmod.cards; import com.megacrit.cardcrawl.actions.common.HealAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import constructmod.ConstructMod; import constructmod.actions.GainMaxHPAction; import constructmod.patches.AbstractCardEnum; public class HastyRepair extends AbstractConstructCard { public static final String ID = ConstructMod.makeID("HastyRepair"); private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); public static final String NAME = cardStrings.NAME; public static final String DESCRIPTION = cardStrings.DESCRIPTION; public static final String M_UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; private static final int COST = 1; private static final int HEAL_AMT = 12; private static final int MAX_HP_GAIN_AMT = -2; //private static final int M_UPGRADE_PLUS_MAX_HP_GAIN_AMT = 1; private static final int UPGRADE_HEAL_AMT = 4; private static final int POOL = 1; private int maxHpGain; public HastyRepair() { super(ID, NAME, "img/cards/"+ID+".png", COST, DESCRIPTION, AbstractCard.CardType.SKILL, AbstractCardEnum.CONSTRUCTMOD, AbstractCard.CardRarity.RARE, AbstractCard.CardTarget.SELF, POOL); this.magicNumber = this.baseMagicNumber = HEAL_AMT; this.maxHpGain = MAX_HP_GAIN_AMT; this.exhaust = true; this.tags.add(CardTags.HEALING); } @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new HealAction(p,p,this.magicNumber)); AbstractDungeon.actionManager.addToBottom(new GainMaxHPAction(p,p,maxHpGain)); if (megaUpgraded) AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(this.makeCopy())); } @Override public AbstractCard makeCopy() { return new HastyRepair(); } @Override public void upgrade() { if (!this.upgraded) { this.upgradeName(); this.upgradeMagicNumber(UPGRADE_HEAL_AMT); } else if (this.canUpgrade()) { this.megaUpgradeName(); this.rawDescription = M_UPGRADE_DESCRIPTION; this.initializeDescription(); } } }
3e045d9bab0667589676e4cfa05e7b01e0c33289
4,267
java
Java
src/main/java/localhost3000/models/Validate.java
sufyankhanrao/tester-SDK
55b0a445cbcd9befd26580b53dee199b21a339c5
[ "MIT" ]
null
null
null
src/main/java/localhost3000/models/Validate.java
sufyankhanrao/tester-SDK
55b0a445cbcd9befd26580b53dee199b21a339c5
[ "MIT" ]
null
null
null
src/main/java/localhost3000/models/Validate.java
sufyankhanrao/tester-SDK
55b0a445cbcd9befd26580b53dee199b21a339c5
[ "MIT" ]
null
null
null
23.445055
99
0.544176
1,833
/* * TesterLib * * This file was automatically generated for Stamplay by APIMATIC v3.0 ( https://www.apimatic.io ). */ package localhost3000.models; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; /** * This is a model class for Validate type. */ public class Validate extends BaseModel { private String field; private String name; private String address; /** * Default constructor. */ public Validate() { } /** * Initialization constructor. * @param field String value for field. * @param name String value for name. * @param address String value for address. */ public Validate( String field, String name, String address) { this.field = field; this.name = name; this.address = address; } /** * Getter for Field. * @return Returns the String */ @JsonGetter("field") public String getField() { return field; } /** * Setter for Field. * @param field Value for String */ @JsonSetter("field") public void setField(String field) { this.field = field; } /** * Getter for Name. * @return Returns the String */ @JsonGetter("name") public String getName() { return name; } /** * Setter for Name. * @param name Value for String */ @JsonSetter("name") public void setName(String name) { this.name = name; } /** * Getter for Address. * @return Returns the String */ @JsonGetter("address") @JsonInclude(JsonInclude.Include.NON_NULL) public String getAddress() { return address; } /** * Setter for Address. * @param address Value for String */ @JsonSetter("address") public void setAddress(String address) { this.address = address; } /** * Converts this Validate into string format. * @return String representation of this class */ @Override public String toString() { return "Validate [" + "field=" + field + ", name=" + name + ", address=" + address + ", additionalProperties=" + getAdditionalProperties() + "]"; } /** * Builds a new {@link Validate.Builder} object. * Creates the instance with the state of the current model. * @return a new {@link Validate.Builder} object */ public Builder toBuilder() { Builder builder = new Builder(field, name) .address(getAddress()); return builder; } /** * Class to build instances of {@link Validate}. */ public static class Builder { private String field; private String name; private String address; /** * Initialization constructor. */ public Builder() { } /** * Initialization constructor. * @param field String value for field. * @param name String value for name. */ public Builder(String field, String name) { this.field = field; this.name = name; } /** * Setter for field. * @param field String value for field. * @return Builder */ public Builder field(String field) { this.field = field; return this; } /** * Setter for name. * @param name String value for name. * @return Builder */ public Builder name(String name) { this.name = name; return this; } /** * Setter for address. * @param address String value for address. * @return Builder */ public Builder address(String address) { this.address = address; return this; } /** * Builds a new {@link Validate} object using the set fields. * @return {@link Validate} */ public Validate build() { return new Validate(field, name, address); } } }
3e045f715b799ad988b4671d4a1c599a0e629a6e
8,987
java
Java
interactive_engine/sdk/src/main/java/com/alibaba/graphscope/groot/sdk/example/LoadLdbc.java
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
[ "Apache-2.0" ]
1
2021-12-30T02:55:16.000Z
2021-12-30T02:55:16.000Z
interactive_engine/sdk/src/main/java/com/alibaba/graphscope/groot/sdk/example/LoadLdbc.java
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
[ "Apache-2.0" ]
null
null
null
interactive_engine/sdk/src/main/java/com/alibaba/graphscope/groot/sdk/example/LoadLdbc.java
lnfjpt/GraphScope
917146f86d8387302a2e1de6963115e7568bf3ee
[ "Apache-2.0" ]
null
null
null
43
100
0.452988
1,834
/** * Copyright 2020 Alibaba Group Holding Limited. * * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.graphscope.groot.sdk.example; import com.alibaba.graphscope.groot.sdk.MaxGraphClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class LoadLdbc { private static final Logger logger = LoggerFactory.getLogger(LoadLdbc.class); public static void main(String[] args) throws IOException, ParseException { String dataDir = args[0]; String host = args[1]; int port = Integer.valueOf(args[2]); int batchSize = Integer.valueOf(args[3]); logger.info( "dataDir [" + dataDir + "] host [" + host + "] port [" + port + "] batch [" + batchSize + "]"); MaxGraphClient client = MaxGraphClient.newBuilder().addHost(host, port).build(); int processed = 0; int ignored = 0; for (Path path : Files.list(Paths.get(dataDir)).collect(Collectors.toList())) { logger.info("process file [" + path.getFileName() + "]"); String fileName = path.getFileName().toString(); if (!fileName.endsWith("_0_0.csv") || fileName.startsWith(".") || fileName.startsWith("person_speaks_language") || fileName.startsWith("person_email_emailaddress")) { logger.info("ignore [" + fileName + "]"); ignored++; continue; } String name = fileName.substring(0, fileName.length() - 8); String[] items = name.split("_"); if (items.length == 1) { String label = firstUpperCase(items[0]); logger.info("vertex table: [" + label + "]"); processVertex(client, label, path, batchSize); } else { String srcLabel = firstUpperCase(items[0]); String label = items[1]; String dstLabel = firstUpperCase(items[2]); logger.info("edge table: [" + srcLabel + "-" + label + "->" + dstLabel + "]"); processEdge(client, label, srcLabel, dstLabel, path, batchSize); } processed++; } logger.info( "Total [" + (processed + ignored) + "]. processed [" + processed + "], ignored [" + ignored + "]"); } public static String firstUpperCase(String origin) { return origin; } private static void processVertex(MaxGraphClient client, String label, Path path, int batchSize) throws IOException, ParseException { List<String> propertyNames = new ArrayList<>(); int count = 0; long snapshotId = 0; try (BufferedReader br = new BufferedReader(new FileReader(path.toFile()))) { String line; while ((line = br.readLine()) != null) { if (propertyNames.size() == 0) { // First line for (String item : line.split("\\|")) { propertyNames.add(item.split(":")[0]); } } else { Map<String, String> properties = new HashMap<>(); String[] items = line.split("\\|"); for (int i = 0; i < items.length; i++) { String propertyName = propertyNames.get(i); String propertyVal = items[i]; // if (propertyName.endsWith("Date")) { // propertyVal = // String.valueOf(df.parse(propertyVal).getTime()); // } else if (propertyName.equals("birthday")) { // propertyVal = // String.valueOf(df2.parse(propertyVal).getTime()); // } properties.put(propertyName, propertyVal); } try { client.addVertex(label, properties); } catch (Exception e) { logger.error( "add vertex label [" + label + "], properties [" + properties + "] failed", e); } count++; if (count == batchSize) { snapshotId = client.commit(); count = 0; } } } } long maybeSnapshotId = client.commit(); long flushSnapshotId = maybeSnapshotId == 0 ? snapshotId : maybeSnapshotId; logger.info("flush snapshotId [" + flushSnapshotId + "]"); client.remoteFlush(flushSnapshotId); logger.info("done"); } private static void processEdge( MaxGraphClient client, String label, String srcLabel, String dstLabel, Path path, int batchSize) throws IOException, ParseException { List<String> propertyNames = new ArrayList<>(); int count = 0; long snapshotId = 0; try (BufferedReader br = new BufferedReader(new FileReader(path.toFile()))) { String line; while ((line = br.readLine()) != null) { if (propertyNames.size() == 0) { // First line for (String item : line.split("\\|")) { propertyNames.add(item.split(":")[0]); } } else { Map<String, String> properties = new HashMap<>(); String[] items = line.split("\\|"); for (int i = 2; i < items.length; i++) { String propertyName = propertyNames.get(i); String propertyVal = items[i]; // if (propertyName.endsWith("Date") && // propertyVal.indexOf('-') != -1) { // try { // propertyVal = // String.valueOf(df.parse(propertyVal).getTime()); // } catch (Exception e) { // logger.error("parse failed [" + // propertyVal + "]"); // throw e; // } // } properties.put(propertyName, propertyVal); } client.addEdge( label, srcLabel, dstLabel, Collections.singletonMap("id", items[0]), Collections.singletonMap("id", items[1]), properties); count++; if (count == batchSize) { snapshotId = client.commit(); count = 0; } } } } long maybeSnapshotId = client.commit(); long flushSnapshotId = maybeSnapshotId == 0 ? snapshotId : maybeSnapshotId; logger.info("flush snapshotId [" + flushSnapshotId + "]"); client.remoteFlush(flushSnapshotId); logger.info("done"); } }
3e04604653d697618310bdbf418722972d9c2fc3
1,274
java
Java
pcgen/code/src/java/pcgen/rules/context/AssociatedChanges.java
odraccir/pcgen-deprecated
ab07cb4250e5d0419fd805197fb040a2ea425cc8
[ "OML" ]
1
2022-03-15T22:42:34.000Z
2022-03-15T22:42:34.000Z
pcgen/code/src/java/pcgen/rules/context/AssociatedChanges.java
odraccir/pcgen-deprecated
ab07cb4250e5d0419fd805197fb040a2ea425cc8
[ "OML" ]
null
null
null
pcgen/code/src/java/pcgen/rules/context/AssociatedChanges.java
odraccir/pcgen-deprecated
ab07cb4250e5d0419fd805197fb040a2ea425cc8
[ "OML" ]
null
null
null
33.763158
81
0.744349
1,835
/* * Copyright 2008 (C) Tom Parker <[email protected]> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package pcgen.rules.context; import java.util.Collection; import pcgen.base.util.MapToList; import pcgen.cdom.base.AssociatedPrereqObject; public interface AssociatedChanges<T> { public boolean includesGlobalClear(); public Collection<T> getAdded(); public Collection<T> getRemoved(); public MapToList<T, AssociatedPrereqObject> getAddedAssociations(); public MapToList<T, AssociatedPrereqObject> getRemovedAssociations(); }
3e0460f01012fefd9fddca5c09018d939d39f7ab
39,485
java
Java
src/com/lilithsthrone/main/Main.java
Arrrammis/liliths-throne-public
bbbbbb90336179b3a7fd27f84e2d3f62f3e40131
[ "Linux-OpenIB" ]
null
null
null
src/com/lilithsthrone/main/Main.java
Arrrammis/liliths-throne-public
bbbbbb90336179b3a7fd27f84e2d3f62f3e40131
[ "Linux-OpenIB" ]
null
null
null
src/com/lilithsthrone/main/Main.java
Arrrammis/liliths-throne-public
bbbbbb90336179b3a7fd27f84e2d3f62f3e40131
[ "Linux-OpenIB" ]
null
null
null
45.859466
229
0.674357
1,836
package com.lilithsthrone.main; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import com.lilithsthrone.controller.MainController; import com.lilithsthrone.controller.TooltipUpdateThread; import com.lilithsthrone.game.Game; import com.lilithsthrone.game.Properties; import com.lilithsthrone.game.PropertyValue; import com.lilithsthrone.game.character.CharacterImportSetting; import com.lilithsthrone.game.character.CharacterUtils; import com.lilithsthrone.game.character.PlayerCharacter; import com.lilithsthrone.game.character.body.valueEnums.Femininity; import com.lilithsthrone.game.character.gender.Gender; import com.lilithsthrone.game.character.persona.NameTriplet; import com.lilithsthrone.game.character.quests.QuestLine; import com.lilithsthrone.game.character.race.RaceStage; import com.lilithsthrone.game.character.race.Subspecies; import com.lilithsthrone.game.dialogue.DialogueNodeOld; import com.lilithsthrone.game.dialogue.DialogueNodeType; import com.lilithsthrone.game.dialogue.responses.Response; import com.lilithsthrone.game.dialogue.story.CharacterCreation; import com.lilithsthrone.game.dialogue.utils.OptionsDialogue; import com.lilithsthrone.game.inventory.enchanting.TFEssence; import com.lilithsthrone.game.sex.Sex; import com.lilithsthrone.utils.Colour; import com.lilithsthrone.utils.CreditsSlot; import com.lilithsthrone.world.Generation; import com.lilithsthrone.world.WorldType; import com.lilithsthrone.world.places.PlaceType; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; /** * @since 0.1.0 * @version 0.2.11 * @author Innoxia */ public class Main extends Application { public static Game game; public static Sex sexEngine; public static MainController mainController; public static Scene mainScene; public static Stage primaryStage; public static String author = "Innoxia"; public static final String VERSION_NUMBER = "0.2.11.5"; public static final String VERSION_DESCRIPTION = "Alpha"; /** * To turn it on, just add -Ddebug=true to java's VM options. (You should be able to do this in Eclipse through Run::Run Configurations...::Arguments tab::VM Arguments). * Help page: https://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.pde.doc.user%2Fguide%2Ftools%2Flaunchers%2Farguments.htm * Or, from the command line java -Ddebug=true -jar LilithsThrone.jar */ public final static boolean DEBUG = Boolean.valueOf(System.getProperty("debug", "false")); public static final Image WINDOW_IMAGE = new Image("/com/lilithsthrone/res/images/windowIcon32.png"); private static Properties properties; public static String patchNotes = "<p>" + "Hello again!" + "</p>" + "<p>" + "I've got the majority of the fortress framework done, but the imp citadel (the one in the very middle) is going to play a role in the main story a little larger than I originally planned." + " For that reason, it's still under construction, but will be finished for 0.3, along with all of the fortress dialogue and Lyssieth's palace." + "</p>" + "<p>" + "I expect the work on 0.3 to take at least a week, so the full version will be out some time between 9th-13th November." + "</p>" + "<p>" + "I've completely run out of time, and so haven't had the chance to thoroughly test this version (outside of the normal testing that I do alongside adding new stuff)," + " so if there are any major bugs/issues, I'll try to get them fixed for a hotfix by weekend's end." + "</p>" + "<p>" + "Thank you all for playing Lilith's Throne! And a very big thank you to all the people supporting me on Patreon!" + " If you wanted to ask me any specific questions about the game, you can either find me on my blog, or on the Lilith's Throne Discord. You can find a link to the discord on my blog. ^^" + "</p>" + "<br/>" + "<list>" + "<h6>v0.2.11.5</h6>" +"<li>Gameplay:</li>" +"<ul>Added framework for imp fortresses, with (very rough) placeholder dialogue. (Central imp citadel is still closed - it will be ready for the next update!)</ul>" +"<ul>Added next stage of main quest to the guards at Lyssieth's palace gate.</ul>" +"<li>Items:</li>" +"<ul>Added 'gothic dress', 'gothic sleeveless dress', and 'gothic heels' into the base game. (The items that were released as a mod on Halloween.)</ul>" +"<ul>Added several new weapons and items of clothing that I had planned for the imp fortress bosses. These are as follows:</ul>" +"<ul>Added weapon 'knuckle dusters'. (Sold by Vicky.)</ul>" +"<ul>Added weapon 'katana'. (Sold by Vicky. Daisho set.)</ul>" +"<ul>Added weapon 'wakizashi'. (Sold by Vicky. Daisho set.)</ul>" +"<ul>Added clothing 'striped gloves'. (Hand slot. Sold by Nyan.)</ul>" +"<ul>Added clothing 'men's hakama'. (Leg slot. Ronin set. Reindeer gift item, and worn by one of the imp fortress bosses.)</ul>" +"<ul>Added three new clothing items (for eyes, over-torso, and neck), and a new melee weapon, all of which are only found being worn/equipped by the central imp citadel's boss. (Not specified to avoid spoilers.)</ul>" +"<li>Other:</li>" +"<ul>Added new 'quest' rarity, and a new tab in your inventory for quest-related items. (Only Arthur's package and the new imp keys use this at the moment.)</ul>" +"<ul>You can no longer sell or drop quest items.</ul>" +"<ul>Rarity is now displayed in item/clothing/weapon tooltips.</ul>" +"<ul>Improved 'Potion effects' status effect icon.</ul>" +"<ul>Item tooltips now have the same format as weapons and clothing.</ul>" +"<ul>Added options to change number of arm pairs, eye pairs, horn rows, and tails in the slime, demon, and debug transform menus.</ul>" +"<ul>Arcane storm vulnerability is no longer bound to a character's race, but is instead applied when their 'arcane' attribute is less than 20. (The player is always immune.)</ul>" +"<ul>Added colouring options for all body part coverings in the slime/demon self-transform menu, and included ass, underarm, pubic, and facial hair colourings and lengths (if the relevant content option is turned on).</ul>" +"<ul>Added a simplified version of clothing mod's displacementText/replacementText fields. Look at the bottom of the new 'arcane_amulet.xml' file to see how it works.</ul>" +"<ul>Added new 'Major Attribute' primary enchantment modifier for clothing & weapons, with secondary enchantments for energy, aura, physique, arcane, and corruption.</ul>" +"<ul>Increased potency costs for 'major drain/drain/minor drain/minor boost/boost/major boost' from 4/2/1/1/2/4 to 8/4/1/1/4/8.</ul>" +"<ul>Increased enchantment modifier costs for 'rare/epic/legendary' from '3/5/8' to '4/8/12'.</ul>" +"<ul>Added & improved icons for enchantment modifiers.</ul>" +"<ul>Added 'chuuni' perk, which gives a large boost to spell power, but also makes your character say embarrassing things when you cast spells.</ul>" +"<ul>Added 'brass' and 'midnight green' as colours for clothing/weapons, and 'light purple' as a skin/hair covering colour.</ul>" +"<ul>Added support for weapons to count towards sets. (Like the Enforcer set, Maid set, etc.) Look at the katana and wakazashi files to see how they're defined in mods.</ul>" +"<ul>Reduced dagger's base value from 5000 to 1500.</ul>" +"<ul>You can now only teleport to tiles you've previously visited. (The teleport spell is still only available via the debug menu.)</ul>" +"<ul>Tiles you have discovered (by travelling next to them), but haven't visited, are now shaded. (When loading in from a version prior to 0.2.11.5, all discovered tiles will be set as having been visited before.)</ul>" +"<li>Bugs:</li>" +"<ul>Fixed issue with group oral not working correctly.</ul>" +"<ul>Fixed imp attack dialogue not working if you had a companion with you.</ul>" +"<ul>Vicky should now correctly stock modded weapons and items with the 'SOLD_BY_VICKY' tag.</ul>" +"<ul>Added correct covering detection for all sock and leg clothing, so that cumming onto feet or thighs should now correctly dirty the clothing that's covering those related areas.</ul>" +"<ul>Fixed issue where NPCs would start/stop actions in sex. (For what must be the tenth time...)</ul>" +"<ul>Fixed bug with the 'Take all' action being used on an NPC's inventory throwing a background error.</ul>" +"<ul>Fixed issues with being able to pick up items/weapons/clothing from the floor, even if your inventory was full.</ul>" +"<ul>Typo fixes.</ul>" +"<ul>Fixed issue with companion's elementals being treated as slaves when in Lilaya's house.</ul>" +"<ul>Fixed issue where clothing or weapon tooltip images could sometimes be displayed incorrectly.</ul>" +"<ul>Fixed issue with NPC encounter dialogue where the NPC's impregnation fetish check was firing incorrectly.</ul>" +"<ul>Fixed initial footjob start text not being shown in sex, as well as the extra tooltip description not working.</ul>" +"<ul>Fixed bug where Lilaya's panty scenes involving Rose would all softlock.</ul>" +"<ul>Fixed bug in missionary sex where actions to stop penetrations would not be given.</ul>" +"<ul>Fixed issue where enchanted clothing without a unique name would sometimes not display the enchantment postfix.</ul>" +"<ul>Fixed bug with Arcanist's Hat xml file.</ul>" +"<ul>Fixed imp encounters in the central imp tunnels (the dark purple ones) not working correctly.</ul>" +"<ul>Fixed background error when starting a group missionary sex scene (which might have been causing the action to start sex to not work).</ul>" +"<ul>Weapons that should be pluralised by default are now actually pluralised.</ul>" +"<ul>Fixed missionary 'spread legs' action not working.</ul>" +"<ul>Fixed issue with modded clothing marked as 'RARE' being given the rarity 'EPIC' in-game.</ul>" +"<ul>Fixed issue with wrong character's tail being described in a lot of tail-pegging actions.</ul>" +"<ul>Fixed issue with weapons having incorrect determiners.</ul>" +"<ul>Fixed bug at end of imp female encounter, where an extra 'endif' would be displayed.</ul>" + "</list>" ; public static String disclaimer = "<h6 style='text-align: center; color:"+Colour.GENERIC_ARCANE.toWebHexString()+";'>You must read and agree to the following in order to play this game!</h6>" + "<p>This game is a <b>fictional</b> text-based erotic RPG. All content contained within this game forms part of a fictional universe that is not related to real-life places, people or events.<br/><br/>" + " All of the characters that appear in this story are fictional entities who have given their consent to appear and act in this story." + " If you find yourself concerned for the characters in the story then please be reassured that they are all consenting adults who are speaking lines from a script." + " None of the characters portrayed within this game were or are being harmed in any way during the construction or execution of this game." + " Every character in the game is at least 18 years of age (or is magically the legal age needed to appear in erotic literature in whatever country you are playing this).<br/><br/>" + "By agreeing to this disclaimer and playing this game you agree to be exposed to graphic sexual and adult content that is presented as part of the game's fictional universe." + " Such content consists of, but is not limited to; graphic depictions of sex, inter-species sex (with fantasy creatures), sexual transformation," + " rape fantasy/implied lack of consent, mild physical violence, sexual violence, and drug use.<br/>" + "Extreme fetish content such as gore/extreme violence, scat, and under/questionable age, is <i>not</i> a part of this game.<br/><br/>" + "By agreeing to this disclaimer and playing this game you also agree that you are <b>at least 18 years of age</b>," + " or at least the legal age for you to purchase and view pornographic material in your country if that age is over 18.<br/><br/>" + "As a final note, the creators of this game wish to stress that the content presented within is entirely fictional and does not reflect any of their personal views or opinions." + " This game has been made in the spirit of creating a piece of artistic interactive literature, and it is imperative that you maintain a clear distinction between reality and the fictional events depicted in this game.</p>"; public static List<CreditsSlot> credits = new ArrayList<>(); // World generation: public static Generation gen; @Override public void start(Stage primaryStage) throws Exception { CheckForDataDirectory(); CheckForResFolder(); credits.add(new CreditsSlot("Anonymous", "", 99, 99, 99, 99)); credits.add(new CreditsSlot("Adhana Konker", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("Akira", "", 0, 0, 0, 2)); credits.add(new CreditsSlot("Aleskah", "", 0, 0, 0, 1)); credits.add(new CreditsSlot("Lexi <3", "", 0, 0, 0, 1)); credits.add(new CreditsSlot("Alvinsimon", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("48days", "", 0, 0, 2, 12)); credits.add(new CreditsSlot("Mylerra", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Spaghetti Code", "", 0, 0, 2, 3)); credits.add(new CreditsSlot("Anonymous_Platypus", "", 0, 0, 1, 0)); credits.add(new CreditsSlot("Apthydragon", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Archan9el S117", "", 0, 0, 0, 7)); credits.add(new CreditsSlot("SchALLieS", "", 0, 0, 2, 11)); credits.add(new CreditsSlot("Argmoe", "", 0, 0, 13, 0)); credits.add(new CreditsSlot("HoneyNutQueerios", "", 0, 0, 11, 0)); credits.add(new CreditsSlot("Arkhan", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Ash", "", 0, 1, 0, 10)); credits.add(new CreditsSlot("Jack Cloudie", "", 0, 1, 10, 0)); credits.add(new CreditsSlot("b00marrows", "", 0, 1, 5, 0)); credits.add(new CreditsSlot("Deimios", "", 0, 0, 3, 5)); credits.add(new CreditsSlot("Baz GoldenClaw", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("FidelPinochetov", "", 0, 0, 0, 9)); credits.add(new CreditsSlot("Tieria", "", 0, 0, 1, 0)); credits.add(new CreditsSlot("Runehood66", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Krissy2017", "", 0, 0, 2, 6)); credits.add(new CreditsSlot("Blackcanine", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("Blackheart", "", 0, 0, 1, 3)); credits.add(new CreditsSlot("Blacktouch", "", 0, 0, 2, 12)); credits.add(new CreditsSlot("BlakLite", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Blue999", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Captain_Sigmus", "", 0, 0, 2, 0)); credits.add(new CreditsSlot("Brandon Stach", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("BreakerB", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("BRobort", "", 0, 0, 9, 0)); credits.add(new CreditsSlot("BloodsailXXII", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Burt", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Calrak", "", 0, 0, 0, 13)); credits.add(new CreditsSlot("CancerMage", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("Casper &quot;Cdaser&quot; D.", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("CelestialNightmare", "", 0, 0, 0, 13)); credits.add(new CreditsSlot("Sxythe", "", 0, 0, 0, 2)); credits.add(new CreditsSlot("Lexi the slut", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Chattyneko", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Vmpireassassin (Chloe)", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("cinless", "", 0, 0, 0, 8)); credits.add(new CreditsSlot("crashtestdummy", "", 0, 0, 9, 5)); credits.add(new CreditsSlot("Crimson", "", 0, 0, 0, 12)); credits.add(new CreditsSlot("CrowCorvus", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Cryostorm", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("Cursed Rena", "", 0, 0, 1, 12)); credits.add(new CreditsSlot("Cynical-Cy", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Dace617", "", 0, 0, 0, 4)); credits.add(new CreditsSlot("Saladofstones", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("Dan", "", 0, 1, 0, 10)); credits.add(new CreditsSlot("Daniel D Magnan", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Darthsawyer", "", 0, 0, 1, 0)); credits.add(new CreditsSlot("Yllarius", "", 0, 0, 2, 0)); credits.add(new CreditsSlot("DeadEyesSee", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("DeadMasterZero", "", 0, 0, 8, 1)); credits.add(new CreditsSlot("Demonicgamer666", "", 0, 0, 0, 8)); credits.add(new CreditsSlot("John Scarlet", "", 0, 0, 0, 1)); credits.add(new CreditsSlot("Desgax", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("Destont", "", 0, 0, 11, 0)); credits.add(new CreditsSlot("rinoskin", "", 0, 0, 0, 4)); credits.add(new CreditsSlot("suka", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Alatar", "", 0, 0, 0, 2)); credits.add(new CreditsSlot("Elmsdor", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("EnigmaticYoshi", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Endless", "", 0, 0, 5, 2)); credits.add(new CreditsSlot("Gr33n B3ans", "", 0, 0, 0, 2)); credits.add(new CreditsSlot("Erin Kyan", "", 0, 0, 8, 0)); credits.add(new CreditsSlot("Avandemine", "", 0, 0, 1, 6)); credits.add(new CreditsSlot("F. Rowan", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("Farseeker", "", 0, 0, 8, 0)); credits.add(new CreditsSlot("pupslut felix", "", 0, 0, 0, 12)); credits.add(new CreditsSlot("Fenrakk101", "", 0, 0, 11, 0)); credits.add(new CreditsSlot("Fiona", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("ForeverFree2MeTaMax", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("FossorTumulus", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Freekingamer", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("fun_bot", "", 0, 0, 0, 3)); credits.add(new CreditsSlot("Niki Parks", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Garkylal", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Georgio154", "", 0, 0, 1, 6)); credits.add(new CreditsSlot("glocknar", "", 0, 0, 11, 0)); credits.add(new CreditsSlot("Goldmember", "", 0, 0, 0, 3)); credits.add(new CreditsSlot("Grakcnar", "", 0, 0, 9, 0)); credits.add(new CreditsSlot("WodashGSJ", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("Aceofspades", "", 0, 0, 2, 0)); credits.add(new CreditsSlot("Assiyalos", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Hedgehog", "", 0, 0, 0, 6)); credits.add(new CreditsSlot("Helyriel", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("Jatch", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Bocaj91", "", 0, 0, 0, 12)); credits.add(new CreditsSlot("Krejil", "", 0, 0, 9, 0)); credits.add(new CreditsSlot("Eushully", "", 0, 0, 0, 8)); credits.add(new CreditsSlot("Garth614", "", 0, 0, 0, 10)); credits.add(new CreditsSlot("HerrKommissar11", "", 0, 0, 1, 4)); credits.add(new CreditsSlot("Kaerea", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("Tappi", "", 0, 0, 2, 0)); credits.add(new CreditsSlot("Kaleb the Wise", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Karlimero", "", 0, 0, 0, 3)); credits.add(new CreditsSlot("KingofKings", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("KazukiNero", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("Kelly999", "", 0, 1, 10, 0)); credits.add(new CreditsSlot("kenshin5491", "", 0, 0, 13, 0)); credits.add(new CreditsSlot("Kestrel", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Kiroberos", "", 0, 0, 0, 12)); credits.add(new CreditsSlot("Kernog", "", 0, 0, 1, 0)); credits.add(new CreditsSlot("Knight-Lord Xander", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Chris Turpin", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("Lee Thompson", "", 0, 0, 9, 0)); credits.add(new CreditsSlot("Leob", "", 0, 0, 10, 4)); credits.add(new CreditsSlot("Pallid", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("ilderon", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Littlemankitten", "", 0, 0, 0, 7)); credits.add(new CreditsSlot("Mr L", "", 0, 0, 4, 1)); credits.add(new CreditsSlot("loveless", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Vaddex", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Kitsune Lyn", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("matchsticks", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("masterpuppet", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("Nightmare", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("AlphaOneBravo", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Max Nobody", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Neximus", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Mora", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Muhaku", "", 0, 0, 9, 0)); credits.add(new CreditsSlot("Kobu", "", 0, 0, 0, 9)); credits.add(new CreditsSlot("IreCobra", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("NeonRaven94", "", 0, 0, 0, 4)); credits.add(new CreditsSlot("Nick LaBlue", "", 0, 0, 13, 0)); credits.add(new CreditsSlot("Kvernik", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Niko", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Nnxx", "", 0, 1, 3, 2)); credits.add(new CreditsSlot("NorwegianMonster", "", 0, 0, 0, 6)); credits.add(new CreditsSlot("Seo Leifthrasir", "", 0, 0, 0, 1)); credits.add(new CreditsSlot("Odd8Ball", "", 0, 0, 0, 13)); credits.add(new CreditsSlot("Party Commissar", "", 0, 0, 4, 8)); credits.add(new CreditsSlot("Rohsie", "", 0, 0, 0, 10)); credits.add(new CreditsSlot("P.", "", 0, 0, 0, 4)); credits.add(new CreditsSlot("BLKCandy", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("Pierre Mura", "", 0, 0, 0, 11)); credits.add(new CreditsSlot("Pokys", "", 0, 0, 9, 0)); credits.add(new CreditsSlot("QQQ", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Rakesh", "", 0, 0, 8, 0)); credits.add(new CreditsSlot("R.W", "", 0, 3, 6, 0)); credits.add(new CreditsSlot("The Void Prince", "", 0, 0, 8, 0)); credits.add(new CreditsSlot("Master's dumb bitch", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Reila Oda", "", 0, 0, 0, 7)); credits.add(new CreditsSlot("Roarik", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Dark_Lord", "", 0, 0, 0, 6)); credits.add(new CreditsSlot("redwulfen", "", 0, 0, 0, 13)); credits.add(new CreditsSlot("Roger Reyne", "", 0, 0, 0, 3)); credits.add(new CreditsSlot("RogueRandom", "", 0, 0, 11, 0)); credits.add(new CreditsSlot("Horagen81", "", 0, 0, 0, 13)); credits.add(new CreditsSlot("RyubosJ", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Saladine the Legendary", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Sand9k", "", 0, 0, 0, 6)); credits.add(new CreditsSlot("Schande", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Blue Kobold", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("sebasjac", "", 0, 0, 0, 2)); credits.add(new CreditsSlot("S", "", 0, 0, 1, 12)); credits.add(new CreditsSlot("Shas'O Dal'yth Kauyon Kais Taku", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Crow Invictus", "", 0, 0, 13, 0)); credits.add(new CreditsSlot("Sheltem", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("shrikes", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Sig", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Silentark", "", 0, 0, 11, 0)); credits.add(new CreditsSlot("Sir beans", "", 0, 0, 5, 0)); credits.add(new CreditsSlot("Sorter", "", 0, 0, 0, 9)); credits.add(new CreditsSlot("Spectacular", "", 0, 0, 6, 0)); credits.add(new CreditsSlot("Spookermen", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Starchiller", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Steph", "", 0, 0, 4, 0)); credits.add(new CreditsSlot("Strigon888", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Suvarestin", "", 0, 0, 2, 0)); credits.add(new CreditsSlot("Swift Shot", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("TalonMort", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("Tanall", "", 0, 1, 12, 0)); credits.add(new CreditsSlot("Tanner D.", "", 0, 0, 0, 6)); credits.add(new CreditsSlot("Terrance", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("Testostetyrone", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("The Brocenary", "", 0, 0, 0, 1)); credits.add(new CreditsSlot("Jordan Aitken", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("T. Garou", "", 0, 0, 0, 12)); credits.add(new CreditsSlot("xerton", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("Timmybond24", "", 0, 0, 0, 4)); credits.add(new CreditsSlot("TKaempfer", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("FreakyHydra", "", 0, 0, 0, 4)); credits.add(new CreditsSlot("Kahvi_Toope", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("Torinir", "", 0, 0, 13, 0)); credits.add(new CreditsSlot("Torsten015", "", 0, 0, 0, 13)); credits.add(new CreditsSlot("TreenVall", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("triangleman", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("Antriad", "", 0, 0, 1, 8)); credits.add(new CreditsSlot("Isidoros", "", 0, 0, 7, 0)); credits.add(new CreditsSlot("SolarEidolon", "", 0, 0, 3, 0)); credits.add(new CreditsSlot("Vaelin", "", 0, 0, 4, 9)); credits.add(new CreditsSlot("vasadariu", "", 0, 0, 10, 0)); credits.add(new CreditsSlot("Venomy", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("waaaghkus", "", 0, 0, 14, 0)); credits.add(new CreditsSlot("iloveyouMiaoNiNi", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Weegschaal", "", 0, 0, 0, 3)); credits.add(new CreditsSlot("Whatever", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("William Brown", "", 0, 0, 5, 2)); credits.add(new CreditsSlot("Drahin", "", 0, 0, 0, 5)); credits.add(new CreditsSlot("CMPirate9867", "", 0, 0, 8, 0)); credits.add(new CreditsSlot("Wolfrave", "", 0, 0, 2, 0)); credits.add(new CreditsSlot("Wolfregis", "", 0, 0, 0, 14)); credits.add(new CreditsSlot("Nelson Adams", "", 0, 0, 12, 0)); credits.add(new CreditsSlot("Zakarin", "", 0, 0, 0, 9)); credits.sort(Comparator.comparing((CreditsSlot a) -> a.getName().toLowerCase())); Main.primaryStage = primaryStage; Main.primaryStage.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) { if(t) { TooltipUpdateThread.cancelThreads = true; } } }); Main.primaryStage.getIcons().add(WINDOW_IMAGE); Main.primaryStage.setTitle("Lilith's Throne " + VERSION_NUMBER + " " + VERSION_DESCRIPTION+(DEBUG?" (Debug Mode)":"")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/lilithsthrone/res/fxml/main.fxml")); Pane pane = loader.load(); mainScene = new Scene(pane); if (properties.hasValue(PropertyValue.lightTheme)) { mainScene.getStylesheets().add("/com/lilithsthrone/res/css/stylesheet_light.css"); } else { mainScene.getStylesheets().add("/com/lilithsthrone/res/css/stylesheet.css"); } mainController = loader.getController(); Main.primaryStage.setScene(mainScene); Main.primaryStage.show(); Main.game = new Game(); Main.sexEngine = new Sex(); loader = new FXMLLoader(getClass().getResource("/com/lilithsthrone/res/fxml/main.fxml")); try { if (Main.mainScene == null) { pane = loader.load(); Main.mainController = loader.getController(); Main.mainScene = new Scene(pane); if (Main.getProperties().hasValue(PropertyValue.lightTheme)) Main.mainScene.getStylesheets().add("/com/lilithsthrone/res/css/stylesheet_light.css"); else Main.mainScene.getStylesheets().add("/com/lilithsthrone/res/css/stylesheet.css"); } Main.primaryStage.setScene(Main.mainScene); } catch (Exception e) { e.printStackTrace(); } Main.game.setContent(new Response("", "", OptionsDialogue.MENU)); } protected static void CheckForDataDirectory() { File dir = new File("data/"); if(!dir.exists()) { Alert a = new Alert(AlertType.ERROR, "Unable to find the 'data' folder. Saving and error logging is disabled.\nMake sure that you've extracted the game from the zip file, and that the file has write permissions.\nContinue?", ButtonType.YES, ButtonType.NO); a.showAndWait().ifPresent(response -> { if (response == ButtonType.NO) { System.exit(1); } }); } } protected static void CheckForResFolder() { File dir = new File("res/"); if(!dir.exists()) { Alert a = new Alert(AlertType.WARNING, "Could not find the 'res' folder. This might cause errors and present sections of missing text.\nContinue?", ButtonType.YES, ButtonType.NO); a.showAndWait().ifPresent(response -> { if(response == ButtonType.NO) { System.exit(1); } }); } } public static void main(String[] args) { // Create folders: File dir = new File("data/"); dir.mkdir(); dir = new File("data/saves"); dir.mkdir(); dir = new File("data/characters"); dir.mkdir(); // Open error log if(!DEBUG) { try { @SuppressWarnings("resource") PrintStream stream = new PrintStream("data/error.log"); System.setErr(stream); } catch (FileNotFoundException e) { e.printStackTrace(); } } // Load properties: if (new File("data/properties.xml").exists()) { try { properties = new Properties(); properties.loadPropertiesFromXML(); } catch (Exception ex) { ex.printStackTrace(); } } else { properties = new Properties(); properties.savePropertiesAsXML(); } launch(args); } /** * Starts a completely new game. Runs a new World Generation. */ public static void startNewGame(DialogueNodeOld startingDialogueNode) { Main.game = new Game(); // Generate world: if (!(gen == null)) if (gen.isRunning()) { gen.cancel(); } gen = new Generation(); gen.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/lilithsthrone/res/fxml/main.fxml")); Pane pane; try { if (Main.mainScene == null) { pane = loader.load(); Main.mainController = loader.getController(); Main.mainScene = new Scene(pane); if (Main.getProperties().hasValue(PropertyValue.lightTheme)) Main.mainScene.getStylesheets().add("/com/lilithsthrone/res/css/stylesheet_light.css"); else Main.mainScene.getStylesheets().add("/com/lilithsthrone/res/css/stylesheet.css"); } Main.primaryStage.setScene(Main.mainScene); } catch (Exception e) { e.printStackTrace(); } Main.game.setPlayer(new PlayerCharacter(new NameTriplet("Player"), 1, null, Gender.M_P_MALE, Subspecies.HUMAN, RaceStage.HUMAN, null, WorldType.EMPTY, PlaceType.GENERIC_MUSEUM)); Main.game.initNewGame(startingDialogueNode); Main.game.endTurn(0); //Main.mainController.processNewDialogue(); } }); new Thread(gen).start(); } public static boolean isVersionOlderThan(String versionToCheck, String versionToCheckAgainst) { String[] v1 = versionToCheck.split("\\."); String[] v2 = versionToCheckAgainst.split("\\."); try { int maxlength = (v1.length > v2.length) ? v1.length : v2.length; for (int i = 0; i < maxlength; i++) { int v1i; int v2i; if(v1[1].charAt(0)=='1') { // Versions prior to 0.2.x used an old system of the format: 0.1.10.1 being a lower version than 0.1.9.1: v1i = (i < v1.length) ? Integer.valueOf((v1[i]+"00").substring(0, 3)) : 0; v2i = (i < v2.length) ? Integer.valueOf((v2[i]+"00").substring(0, 3)) : 0; } else { // Versions of 0.2.x and higher use a new system of the format: 0.2.10.1 being a higher version than 0.2.9.1: v1i = (i < v1.length) ? Integer.valueOf(v1[i]) : 0; v2i = (i < v2.length) ? Integer.valueOf(v2[i]) : 0; } if (v1i < v2i) { return true; } else if (v1i > v2i) { return false; } } } catch(Exception ex) { return true; } return false; } public static int getFontSize() { return properties.fontSize; } public static void setFontSize(int size) { properties.fontSize = size; properties.savePropertiesAsXML(); } public static void quickSaveGame() { if (Main.game.isInCombat()) { Main.game.flashMessage(Colour.GENERIC_BAD, "Cannot quicksave while in combat!"); } else if (Main.game.isInSex()) { Main.game.flashMessage(Colour.GENERIC_BAD, "Cannot quicksave while in sex!"); } else if (Main.game.getCurrentDialogueNode().getDialogueNodeType()!=DialogueNodeType.NORMAL) { Main.game.flashMessage(Colour.GENERIC_BAD, "Can only quicksave in a normal scene!"); } else if (!Main.game.isStarted() || !Main.game.getCurrentDialogueNode().equals(Main.game.getDefaultDialogueNoEncounter())) { Main.game.flashMessage(Colour.GENERIC_BAD, "Cannot save in this scene!"); } else { Main.getProperties().lastQuickSaveName = "QuickSave_"+Main.game.getPlayer().getName(); saveGame("QuickSave_"+Main.game.getPlayer().getName(), true); } } public static void quickLoadGame() { String name = "QuickSave_"+Main.game.getPlayer().getName(); // if(new File("data/saves/"+name+".lts").exists()) { loadGame(name); // } else { // loadGame(Main.getProperties().lastQuickSaveName); // } } public static boolean isSaveGameAvailable() { return Main.game.isStarted() && Main.game.getSavedDialogueNode() == Main.game.getDefaultDialogueNoEncounter(); } public static void saveGame(String name, boolean allowOverwrite) { if (name.length()==0) { Main.game.flashMessage(Colour.GENERIC_BAD, "Name too short!"); return; } if (name.length() > 32) { Main.game.flashMessage(Colour.GENERIC_BAD, "Name too long!"); return; } if (!name.matches("[a-zA-Z0-9]+[a-zA-Z0-9' _]*")) { Main.game.flashMessage(Colour.GENERIC_BAD, "Incompatible characters!"); return; } Game.exportGame(name, allowOverwrite); try { properties.lastSaveLocation = name;//"data/saves/"+name+".lts"; properties.nameColour = Femininity.valueOf(game.getPlayer().getFemininityValue()).getColour().toWebHexString(); properties.name = game.getPlayer().getName(); properties.level = game.getPlayer().getLevel(); properties.money = game.getPlayer().getMoney(); properties.arcaneEssences = game.getPlayer().getEssenceCount(TFEssence.ARCANE); properties.race = game.getPlayer().getSubspecies().getName(game.getPlayer()); properties.quest = game.getPlayer().getQuest(QuestLine.MAIN).getName(); properties.savePropertiesAsXML(); } catch (Exception ex) { ex.printStackTrace(); } } public static boolean isLoadGameAvailable(String name) { File file = new File("data/saves/"+name+".xml"); return file.exists(); } public static void loadGame(String name) { if (isLoadGameAvailable(name)) { Game.importGame(name); } } public static void deleteGame(String name) { File file = new File("data/saves/"+name+".xml"); if (file.exists()) { try { file.delete(); Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode())); } catch (Exception ex) { ex.printStackTrace(); } } else { Main.game.flashMessage(Colour.GENERIC_BAD, "File not found..."); } } public static void deleteExportedGame(String name) { File file = new File("data/saves/"+name+".xml"); if (file.exists()) { try { file.delete(); Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode())); } catch (Exception ex) { ex.printStackTrace(); } } else { Main.game.flashMessage(Colour.GENERIC_BAD, "File not found..."); } } public static void deleteExportedCharacter(String name) { File file = new File("data/characters/"+name+".xml"); if (file.exists()) { try { file.delete(); Main.game.setContent(new Response("", "", Main.game.getCurrentDialogueNode())); } catch (Exception ex) { ex.printStackTrace(); } } else { Main.game.flashMessage(Colour.GENERIC_BAD, "File not found..."); } } public static List<File> getSavedGames() { List<File> filesList = new ArrayList<>(); File dir = new File("data/saves"); if (dir.isDirectory()) { File[] directoryListing = dir.listFiles((path, name) -> name.endsWith(".xml")); if (directoryListing != null) { filesList.addAll(Arrays.asList(directoryListing)); } } filesList.sort(Comparator.comparingLong(File::lastModified).reversed()); return filesList; } public static List<File> getCharactersForImport() { List<File> filesList = new ArrayList<>(); File dir = new File("data/characters"); if (dir.isDirectory()) { File[] directoryListing = dir.listFiles((path, name) -> name.endsWith(".xml")); if (directoryListing != null) { filesList.addAll(Arrays.asList(directoryListing)); } } filesList.sort(Comparator.comparingLong(File::lastModified).reversed()); return filesList; } public static List<File> getSlavesForImport() { List<File> filesList = new ArrayList<>(); File dir = new File("data/characters"); if (dir.isDirectory()) { File[] directoryListing = dir.listFiles((path, name) -> name.endsWith(".xml")); if (directoryListing != null) { filesList.addAll(Arrays.asList(directoryListing)); } } filesList.sort(Comparator.comparingLong(File::lastModified).reversed()); return filesList; } public static List<File> getGamesForImport() { List<File> filesList = new ArrayList<>(); File dir = new File("data/saves"); if (dir.isDirectory()) { File[] directoryListing = dir.listFiles((path, name) -> name.endsWith(".xml")); if (directoryListing != null) { filesList.addAll(Arrays.asList(directoryListing)); } } filesList.sort(Comparator.comparingLong(File::lastModified).reversed()); return filesList; } public static void importCharacter(File file) { if (file != null) { try { Main.game.setPlayer(CharacterUtils.startLoadingCharacterFromXML()); Main.game.setPlayer(CharacterUtils.loadCharacterFromXML(file, Main.game.getPlayer(), CharacterImportSetting.NO_PREGNANCY, CharacterImportSetting.NO_COMPANIONS, CharacterImportSetting.NO_ELEMENTAL, CharacterImportSetting.CLEAR_SLAVERY)); Main.game.getPlayer().getSlavesOwned().clear(); Main.game.getPlayer().endPregnancy(false); Main.game.setRenderAttributesSection(true); Main.game.clearTextStartStringBuilder(); Main.game.clearTextEndStringBuilder(); Main.getProperties().setValue(PropertyValue.newWeaponDiscovered, false); Main.getProperties().setValue(PropertyValue.newClothingDiscovered, false); Main.getProperties().setValue(PropertyValue.newItemDiscovered, false); Main.game.getPlayer().calculateStatusEffects(0); Main.game.initNewGame(CharacterCreation.START_GAME_WITH_IMPORT); } catch (Exception ex) { ex.printStackTrace(); } } } public static Properties getProperties() { return properties; } public static void saveProperties() { properties.savePropertiesAsXML(); } }
3e0461148d6cff6358dcfcec988c5101ef67d035
2,866
java
Java
src/main/java/openmods/dropdebug/CommandControl.java
boq/DropDebug
eef908a419f3b1b201fea3501342824b344f06c9
[ "MIT" ]
null
null
null
src/main/java/openmods/dropdebug/CommandControl.java
boq/DropDebug
eef908a419f3b1b201fea3501342824b344f06c9
[ "MIT" ]
null
null
null
src/main/java/openmods/dropdebug/CommandControl.java
boq/DropDebug
eef908a419f3b1b201fea3501342824b344f06c9
[ "MIT" ]
null
null
null
33.325581
164
0.700279
1,837
package openmods.dropdebug; import java.util.List; import java.util.Locale; import net.minecraft.command.CommandException; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentTranslation; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class CommandControl implements ICommand { private static final String SUBCOMMAND_UNINSTALL = "uninstall"; private static final String SUBCOMMAND_INSTALL = "install"; private static final String SUBCOMMAND_STATE = "state"; private static final List<String> SUBCOMMANDS = ImmutableList.of(SUBCOMMAND_INSTALL, SUBCOMMAND_UNINSTALL, SUBCOMMAND_STATE); @Override public int compareTo(Object o) { return getCommandName().compareTo(((ICommand)o).getCommandName()); } @Override public String getCommandName() { return "debug_drops"; } @Override public String getCommandUsage(ICommandSender sender) { return Joiner.on(", ").join(SUBCOMMANDS); } @Override public List<?> getCommandAliases() { return null; } @Override public void processCommand(ICommandSender sender, String[] args) { if (args.length != 1) throw new CommandException("dropdebug.command.invalid_subcommand"); if (args[0].equalsIgnoreCase(SUBCOMMAND_STATE)) { sender.addChatMessage(new ChatComponentTranslation(DropDebug.instance.isInstalled() ? "dropdebug.command.installed" : "dropdebug.command.uninstalled")); } else if (args[0].equalsIgnoreCase(SUBCOMMAND_INSTALL)) { DropDebug.instance.install(); sender.addChatMessage(new ChatComponentTranslation("dropdebug.command.installed")); } else if (args[0].equalsIgnoreCase(SUBCOMMAND_UNINSTALL)) { DropDebug.instance.uninstall(); sender.addChatMessage(new ChatComponentTranslation("dropdebug.command.uninstalled")); } } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { return sender.canCommandSenderUseCommand(2, getCommandName()); } @Override public List<?> addTabCompletionOptions(ICommandSender sender, String[] args) { return (args.length == 1) ? filterPrefixes(args[0], SUBCOMMANDS) : null; } public static List<String> filterPrefixes(String prefix, Iterable<String> proposals) { prefix = prefix.toLowerCase(Locale.ENGLISH); List<String> result = Lists.newArrayList(); for (String s : proposals) if (s.toLowerCase(Locale.ENGLISH).startsWith(prefix)) result.add(s); return result; } @Override public boolean isUsernameIndex(String[] args, int index) { return false; } }
3e04626a6273295ae0dbefad3d8f51a26e230714
852
java
Java
examples/jsonb-configuration/src/main/java/org/superbiz/model/User.java
robinsonvs/tomee
4dd082476fbf47c95c59aa557d4f02abe3acd846
[ "Apache-2.0" ]
1
2019-03-17T03:04:48.000Z
2019-03-17T03:04:48.000Z
examples/jsonb-configuration/src/main/java/org/superbiz/model/User.java
robinsonvs/tomee
4dd082476fbf47c95c59aa557d4f02abe3acd846
[ "Apache-2.0" ]
1
2021-02-24T02:53:52.000Z
2021-02-24T02:53:52.000Z
examples/jsonb-configuration/src/main/java/org/superbiz/model/User.java
t4fm/tomee
1af4d7b1177d487268a2421b596159326cf29e94
[ "Apache-2.0" ]
2
2019-11-09T17:00:40.000Z
2021-01-13T11:24:03.000Z
15.214286
54
0.660798
1,838
package org.superbiz.model; import java.time.LocalDate; import java.time.Month; import java.util.Date; public class User { private Integer id; private String name; private LocalDate registration; public User(Integer id, String name) { super(); this.id = id; this.name = name; registration = LocalDate.of(2019, Month.JANUARY, 1); } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } public LocalDate getRegistration() { return registration; } public void setRegistration(LocalDate registration) { this.registration = registration; } }
3e0462893b4770d31bc247f91315ac1fabefeca5
24,048
java
Java
proto-google-cloud-video-intelligence-v1/src/main/java/com/google/cloud/videointelligence/v1/FaceSegment.java
suztomo/java-video-intelligence
6a4dfaf244e190014f7d105f4c3391df424408ec
[ "Apache-2.0" ]
9
2020-09-19T12:36:55.000Z
2021-10-05T08:00:18.000Z
proto-google-cloud-video-intelligence-v1/src/main/java/com/google/cloud/videointelligence/v1/FaceSegment.java
suztomo/java-video-intelligence
6a4dfaf244e190014f7d105f4c3391df424408ec
[ "Apache-2.0" ]
521
2019-10-16T20:34:34.000Z
2022-03-30T00:29:02.000Z
proto-google-cloud-video-intelligence-v1/src/main/java/com/google/cloud/videointelligence/v1/FaceSegment.java
suztomo/java-video-intelligence
6a4dfaf244e190014f7d105f4c3391df424408ec
[ "Apache-2.0" ]
18
2019-10-18T16:09:22.000Z
2021-10-07T04:32:29.000Z
32.673913
100
0.679807
1,839
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/videointelligence/v1/video_intelligence.proto package com.google.cloud.videointelligence.v1; /** * * * <pre> * Video segment level annotation results for face detection. * </pre> * * Protobuf type {@code google.cloud.videointelligence.v1.FaceSegment} */ public final class FaceSegment extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.videointelligence.v1.FaceSegment) FaceSegmentOrBuilder { private static final long serialVersionUID = 0L; // Use FaceSegment.newBuilder() to construct. private FaceSegment(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FaceSegment() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FaceSegment(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private FaceSegment( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.videointelligence.v1.VideoSegment.Builder subBuilder = null; if (segment_ != null) { subBuilder = segment_.toBuilder(); } segment_ = input.readMessage( com.google.cloud.videointelligence.v1.VideoSegment.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(segment_); segment_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.videointelligence.v1.VideoIntelligenceServiceProto .internal_static_google_cloud_videointelligence_v1_FaceSegment_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.videointelligence.v1.VideoIntelligenceServiceProto .internal_static_google_cloud_videointelligence_v1_FaceSegment_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.videointelligence.v1.FaceSegment.class, com.google.cloud.videointelligence.v1.FaceSegment.Builder.class); } public static final int SEGMENT_FIELD_NUMBER = 1; private com.google.cloud.videointelligence.v1.VideoSegment segment_; /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> * * @return Whether the segment field is set. */ @java.lang.Override public boolean hasSegment() { return segment_ != null; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> * * @return The segment. */ @java.lang.Override public com.google.cloud.videointelligence.v1.VideoSegment getSegment() { return segment_ == null ? com.google.cloud.videointelligence.v1.VideoSegment.getDefaultInstance() : segment_; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ @java.lang.Override public com.google.cloud.videointelligence.v1.VideoSegmentOrBuilder getSegmentOrBuilder() { return getSegment(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (segment_ != null) { output.writeMessage(1, getSegment()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (segment_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getSegment()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.videointelligence.v1.FaceSegment)) { return super.equals(obj); } com.google.cloud.videointelligence.v1.FaceSegment other = (com.google.cloud.videointelligence.v1.FaceSegment) obj; if (hasSegment() != other.hasSegment()) return false; if (hasSegment()) { if (!getSegment().equals(other.getSegment())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasSegment()) { hash = (37 * hash) + SEGMENT_FIELD_NUMBER; hash = (53 * hash) + getSegment().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.videointelligence.v1.FaceSegment parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.videointelligence.v1.FaceSegment parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.videointelligence.v1.FaceSegment parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.videointelligence.v1.FaceSegment prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Video segment level annotation results for face detection. * </pre> * * Protobuf type {@code google.cloud.videointelligence.v1.FaceSegment} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.videointelligence.v1.FaceSegment) com.google.cloud.videointelligence.v1.FaceSegmentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.videointelligence.v1.VideoIntelligenceServiceProto .internal_static_google_cloud_videointelligence_v1_FaceSegment_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.videointelligence.v1.VideoIntelligenceServiceProto .internal_static_google_cloud_videointelligence_v1_FaceSegment_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.videointelligence.v1.FaceSegment.class, com.google.cloud.videointelligence.v1.FaceSegment.Builder.class); } // Construct using com.google.cloud.videointelligence.v1.FaceSegment.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); if (segmentBuilder_ == null) { segment_ = null; } else { segment_ = null; segmentBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.videointelligence.v1.VideoIntelligenceServiceProto .internal_static_google_cloud_videointelligence_v1_FaceSegment_descriptor; } @java.lang.Override public com.google.cloud.videointelligence.v1.FaceSegment getDefaultInstanceForType() { return com.google.cloud.videointelligence.v1.FaceSegment.getDefaultInstance(); } @java.lang.Override public com.google.cloud.videointelligence.v1.FaceSegment build() { com.google.cloud.videointelligence.v1.FaceSegment result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.videointelligence.v1.FaceSegment buildPartial() { com.google.cloud.videointelligence.v1.FaceSegment result = new com.google.cloud.videointelligence.v1.FaceSegment(this); if (segmentBuilder_ == null) { result.segment_ = segment_; } else { result.segment_ = segmentBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.videointelligence.v1.FaceSegment) { return mergeFrom((com.google.cloud.videointelligence.v1.FaceSegment) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.videointelligence.v1.FaceSegment other) { if (other == com.google.cloud.videointelligence.v1.FaceSegment.getDefaultInstance()) return this; if (other.hasSegment()) { mergeSegment(other.getSegment()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.videointelligence.v1.FaceSegment parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.videointelligence.v1.FaceSegment) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.cloud.videointelligence.v1.VideoSegment segment_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.videointelligence.v1.VideoSegment, com.google.cloud.videointelligence.v1.VideoSegment.Builder, com.google.cloud.videointelligence.v1.VideoSegmentOrBuilder> segmentBuilder_; /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> * * @return Whether the segment field is set. */ public boolean hasSegment() { return segmentBuilder_ != null || segment_ != null; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> * * @return The segment. */ public com.google.cloud.videointelligence.v1.VideoSegment getSegment() { if (segmentBuilder_ == null) { return segment_ == null ? com.google.cloud.videointelligence.v1.VideoSegment.getDefaultInstance() : segment_; } else { return segmentBuilder_.getMessage(); } } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ public Builder setSegment(com.google.cloud.videointelligence.v1.VideoSegment value) { if (segmentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } segment_ = value; onChanged(); } else { segmentBuilder_.setMessage(value); } return this; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ public Builder setSegment( com.google.cloud.videointelligence.v1.VideoSegment.Builder builderForValue) { if (segmentBuilder_ == null) { segment_ = builderForValue.build(); onChanged(); } else { segmentBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ public Builder mergeSegment(com.google.cloud.videointelligence.v1.VideoSegment value) { if (segmentBuilder_ == null) { if (segment_ != null) { segment_ = com.google.cloud.videointelligence.v1.VideoSegment.newBuilder(segment_) .mergeFrom(value) .buildPartial(); } else { segment_ = value; } onChanged(); } else { segmentBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ public Builder clearSegment() { if (segmentBuilder_ == null) { segment_ = null; onChanged(); } else { segment_ = null; segmentBuilder_ = null; } return this; } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ public com.google.cloud.videointelligence.v1.VideoSegment.Builder getSegmentBuilder() { onChanged(); return getSegmentFieldBuilder().getBuilder(); } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ public com.google.cloud.videointelligence.v1.VideoSegmentOrBuilder getSegmentOrBuilder() { if (segmentBuilder_ != null) { return segmentBuilder_.getMessageOrBuilder(); } else { return segment_ == null ? com.google.cloud.videointelligence.v1.VideoSegment.getDefaultInstance() : segment_; } } /** * * * <pre> * Video segment where a face was detected. * </pre> * * <code>.google.cloud.videointelligence.v1.VideoSegment segment = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.videointelligence.v1.VideoSegment, com.google.cloud.videointelligence.v1.VideoSegment.Builder, com.google.cloud.videointelligence.v1.VideoSegmentOrBuilder> getSegmentFieldBuilder() { if (segmentBuilder_ == null) { segmentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.videointelligence.v1.VideoSegment, com.google.cloud.videointelligence.v1.VideoSegment.Builder, com.google.cloud.videointelligence.v1.VideoSegmentOrBuilder>( getSegment(), getParentForChildren(), isClean()); segment_ = null; } return segmentBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.videointelligence.v1.FaceSegment) } // @@protoc_insertion_point(class_scope:google.cloud.videointelligence.v1.FaceSegment) private static final com.google.cloud.videointelligence.v1.FaceSegment DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.videointelligence.v1.FaceSegment(); } public static com.google.cloud.videointelligence.v1.FaceSegment getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FaceSegment> PARSER = new com.google.protobuf.AbstractParser<FaceSegment>() { @java.lang.Override public FaceSegment parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new FaceSegment(input, extensionRegistry); } }; public static com.google.protobuf.Parser<FaceSegment> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FaceSegment> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.videointelligence.v1.FaceSegment getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
3e04638ff60a216c57af97d088f7a51d314e1f1d
448
java
Java
sandbox/src/main/java/ru/stqa/pft/sandbox/Collections.java
AKChervyakov/java_course
39ad5c563f4dfe2ff5c6f7f05b0114c9a47fcdec
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/ru/stqa/pft/sandbox/Collections.java
AKChervyakov/java_course
39ad5c563f4dfe2ff5c6f7f05b0114c9a47fcdec
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/ru/stqa/pft/sandbox/Collections.java
AKChervyakov/java_course
39ad5c563f4dfe2ff5c6f7f05b0114c9a47fcdec
[ "Apache-2.0" ]
null
null
null
21.333333
74
0.625
1,840
package ru.stqa.pft.sandbox; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Sanchez on 26.02.2017. */ public class Collections { public static void main (String[] args) { String[] langs = {"Java", "C#", "Python", "PHP"}; List<String> languages = Arrays.asList("Java", "C#", "Python", "PHP"); for (String l : languages) { System.out.println("Я хочу выучить " + l); } } }
3e0464375161348216a816903eea83ca6d16247c
2,769
java
Java
sphairas-service/niedersachsen/src/org/thespheres/betula/niedersachsen/NdsNamingResolverProvider.java
sphairas/sphairas-desktop
f47c8d4ea62c1fc2876c0ffa44e5925bfaebc316
[ "Apache-2.0" ]
1
2021-11-09T20:33:07.000Z
2021-11-09T20:33:07.000Z
sphairas-service/niedersachsen/src/org/thespheres/betula/niedersachsen/NdsNamingResolverProvider.java
sphairas/sphairas-desktop
f47c8d4ea62c1fc2876c0ffa44e5925bfaebc316
[ "Apache-2.0" ]
null
null
null
sphairas-service/niedersachsen/src/org/thespheres/betula/niedersachsen/NdsNamingResolverProvider.java
sphairas/sphairas-desktop
f47c8d4ea62c1fc2876c0ffa44e5925bfaebc316
[ "Apache-2.0" ]
1
2021-11-09T20:34:30.000Z
2021-11-09T20:34:30.000Z
32.576471
110
0.673889
1,841
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.thespheres.betula.niedersachsen; import java.util.Collections; import java.util.Map; import org.thespheres.betula.Identity; import org.thespheres.betula.services.IllegalAuthorityException; import org.thespheres.betula.services.ProviderInfo; import org.thespheres.betula.services.ProviderRegistry; import org.thespheres.betula.services.NamingResolver; /** * * @author boris.heithecker */ public abstract class NdsNamingResolverProvider implements NamingResolver.Provider { final NdsNaming naming; final Resolver resolver; @SuppressWarnings({"OverridableMethodCallInConstructor"}) protected NdsNamingResolverProvider(final String prov) { this(prov, null, 5, 11); } @SuppressWarnings({"OverridableMethodCallInConstructor"}) protected NdsNamingResolverProvider(final String prov, final String firstElement, int base, int baseAbi) { this.naming = NdsNaming.create(prov, firstElement, base, baseAbi); this.resolver = new Resolver(prov); } public static NdsNamingResolverProvider create(final Map<String, ?> args) { final String provider = (String) args.get("provider"); final String fe = (String) args.get("first-element"); final String firstElement = (fe == null || fe.trim().isEmpty()) ? null : fe.trim(); final Integer b = (Integer) args.get("base-level"); final int base = (b != null && b > 0) ? b : 5; final Integer ba = (Integer) args.get("base-level-abitur"); final int baseAbi = (ba != null && ba > 0) ? b : 11; class ProviderImpl extends NdsNamingResolverProvider { ProviderImpl() { super(provider, firstElement, base, baseAbi); } } return new ProviderImpl(); } @Override public NamingResolver findNamingResolver(String provider) { return provider.equals(resolver.provider) ? resolver : null; } private class Resolver implements NamingResolver { private final String provider; private Resolver(String provider) { this.provider = provider; } @Override public NamingResolver.Result resolveDisplayNameResult(Identity id) throws IllegalAuthorityException { return naming.resolve(id); } @Override public ProviderInfo getInfo() { return ProviderRegistry.getDefault().get(provider); } @Override public Map<String, String> properties() { return Collections.unmodifiableMap(naming.properties()); } } }
3e0465a88e92383718cb12e4c2ab2a977d7ee2c2
5,313
java
Java
src/ecrm-pull/src/com/hy/pull/common/util/game/hb/HostedLocator.java
Douglas890116/Atom
bd0627d744abcff881f5de9a101215949e0c3f3e
[ "Unlicense" ]
2
2019-01-04T03:00:26.000Z
2019-09-18T10:33:19.000Z
src/ecrm-pull/src/com/hy/pull/common/util/game/hb/HostedLocator.java
Douglas890116/Atom
bd0627d744abcff881f5de9a101215949e0c3f3e
[ "Unlicense" ]
null
null
null
src/ecrm-pull/src/com/hy/pull/common/util/game/hb/HostedLocator.java
Douglas890116/Atom
bd0627d744abcff881f5de9a101215949e0c3f3e
[ "Unlicense" ]
2
2019-01-04T03:02:52.000Z
2020-12-16T04:50:48.000Z
37.153846
189
0.643139
1,842
/** * HostedLocator.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.hy.pull.common.util.game.hb; public class HostedLocator extends org.apache.axis.client.Service implements com.hy.pull.common.util.game.hb.Hosted { public HostedLocator() { } public HostedLocator(org.apache.axis.EngineConfiguration config) { super(config); } public HostedLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException { super(wsdlLoc, sName); } // Use to get a proxy class for HostedSoap private java.lang.String HostedSoap_address = "http://ws-a.insvr.com/hosted.asmx"; public java.lang.String getHostedSoapAddress() { return HostedSoap_address; } // The WSDD service name defaults to the port name. private java.lang.String HostedSoapWSDDServiceName = "HostedSoap"; public java.lang.String getHostedSoapWSDDServiceName() { return HostedSoapWSDDServiceName; } public void setHostedSoapWSDDServiceName(java.lang.String name) { HostedSoapWSDDServiceName = name; } public com.hy.pull.common.util.game.hb.HostedSoap getHostedSoap() throws javax.xml.rpc.ServiceException { java.net.URL endpoint; try { endpoint = new java.net.URL(HostedSoap_address); } catch (java.net.MalformedURLException e) { throw new javax.xml.rpc.ServiceException(e); } return getHostedSoap(endpoint); } public com.hy.pull.common.util.game.hb.HostedSoap getHostedSoap(java.net.URL portAddress) throws javax.xml.rpc.ServiceException { try { com.hy.pull.common.util.game.hb.HostedSoapStub _stub = new com.hy.pull.common.util.game.hb.HostedSoapStub(portAddress, this); _stub.setPortName(getHostedSoapWSDDServiceName()); return _stub; } catch (org.apache.axis.AxisFault e) { return null; } } public void setHostedSoapEndpointAddress(java.lang.String address) { HostedSoap_address = address; } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { try { if (com.hy.pull.common.util.game.hb.HostedSoap.class.isAssignableFrom(serviceEndpointInterface)) { com.hy.pull.common.util.game.hb.HostedSoapStub _stub = new com.hy.pull.common.util.game.hb.HostedSoapStub(new java.net.URL(HostedSoap_address), this); _stub.setPortName(getHostedSoapWSDDServiceName()); return _stub; } } catch (java.lang.Throwable t) { throw new javax.xml.rpc.ServiceException(t); } throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName())); } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { if (portName == null) { return getPort(serviceEndpointInterface); } java.lang.String inputPortName = portName.getLocalPart(); if ("HostedSoap".equals(inputPortName)) { return getHostedSoap(); } else { java.rmi.Remote _stub = getPort(serviceEndpointInterface); ((org.apache.axis.client.Stub) _stub).setPortName(portName); return _stub; } } public javax.xml.namespace.QName getServiceName() { return new javax.xml.namespace.QName("http://ws.oxypite.com/", "Hosted"); } private java.util.HashSet ports = null; public java.util.Iterator getPorts() { if (ports == null) { ports = new java.util.HashSet(); ports.add(new javax.xml.namespace.QName("http://ws.oxypite.com/", "HostedSoap")); } return ports.iterator(); } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException { if ("HostedSoap".equals(portName)) { setHostedSoapEndpointAddress(address); } else { // Unknown Port Name throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName); } } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException { setEndpointAddress(portName.getLocalPart(), address); } }
3e0465d8ecd6ef14afc4f264c990f9e49eee386b
4,514
java
Java
src/main/java/com/mckoi/odb/util/FileInfo.java
Mckoi/mckoiddb
665b9d5f4caec4556f6957a857441fc6a18dfd16
[ "Apache-2.0" ]
3
2015-08-08T10:43:55.000Z
2021-04-25T00:32:40.000Z
src/main/java/com/mckoi/odb/util/FileInfo.java
Mckoi/mckoiddb
665b9d5f4caec4556f6957a857441fc6a18dfd16
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mckoi/odb/util/FileInfo.java
Mckoi/mckoiddb
665b9d5f4caec4556f6957a857441fc6a18dfd16
[ "Apache-2.0" ]
1
2015-11-07T16:11:54.000Z
2015-11-07T16:11:54.000Z
24.532609
79
0.637129
1,843
/* * Mckoi Software ( http://www.mckoi.com/ ) * Copyright (C) 2000 - 2015 Diehl and Associates, 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.mckoi.odb.util; import com.mckoi.data.DataFile; /** * A FileInfo object is used by FileRepository to encapsulate information about * a file object. * * @author Tobias Downer */ public interface FileInfo { /** * Returns the DataFile for accessing this file within the context of the * transaction where the file info came from. This DataFile is only valid * if the backed transaction has not been invalidated (by a dispose or * commit). */ DataFile getDataFile(); /** * Returns the full absolute name of this file with respect to the root * directory. */ String getAbsoluteName(); String getMimeType(); long getLastModified(); /** * Updates the 'LastModified' field of this file object to the given value. */ void setLastModified(long last_modified); /** * Updates the 'MimeType' field of this file object to the given value. */ void setMimeType(String mime_type); /** * Returns true if this file item represents a directory. */ boolean isDirectory(); /** * Returns true if this file item represents a file. */ boolean isFile(); /** * Returns the file name without the path. */ String getItemName(); /** * Returns the path name without the file name. */ String getPathName(); // // // /** // * The name of the file. // */ // private final String name; // // /** // * The mime type of the file. // */ // private final String mime_type; // // /** // * The last modified timestamp of the file. // */ // private final long last_modified; // // /** // * Constructor. // */ // FileInfo(String name, String mime_type, long last_modified) { // this.name = name; // this.mime_type = mime_type; // this.last_modified = last_modified; // } // // /** // * Returns the full absolute name of this file with respect to the root // * directory. // */ // public String getAbsoluteName() { // return name; // } // // public String getMimeType() { // return mime_type; // } // // public long getLastModified() { // return last_modified; // } // // /** // * Returns the DataFile for accessing this file within the context of the // * transaction where the file info came from. This DataFile is only valid // * if the backed transaction has not been invalidated (by a dispose or // * commit). // */ // public abstract DataFile getDataFile(); // // /** // * Updates the 'LastModified' field of this file object to the given value. // */ // public abstract void setLastModified(long last_modified); // // /** // * Updates the 'MimeType' field of this file object to the given value. // */ // public abstract void setMimeType(String mime_type); // // /** // * Returns true if this file item represents a directory. // */ // public boolean isDirectory() { // return mime_type != null && mime_type.equals("$dir"); // } // // /** // * Returns true if this file item represents a file. // */ // public boolean isFile() { // return !isDirectory(); // } // // /** // * Returns the file name without the path. // */ // public String getItemName() { // int p = name.lastIndexOf("/", name.length() - 2); // return name.substring(p + 1); // } // // /** // * Returns the path name without the file name. // */ // public String getPathName() { // int p = name.lastIndexOf("/"); // return name.substring(0, p); // } // //// public static Comparator<FileInfo> getNameComparator() { //// return new NameComparator(); //// } //// //// /** //// * Comparator for a sort order on the name field. //// */ //// private static class NameComparator implements Comparator<FileInfo> { //// public int compare(FileInfo o1, FileInfo o2) { //// return o1.getAbsoluteName().compareTo(o2.getAbsoluteName()); //// } //// } }
3e0466772cfc61ab38c204292aa68d572f81aa8e
2,445
java
Java
protect/src/main/java/mi/protectactivity/Utils.java
HooRang/AndroidUniversalSamples
4f6fcd8278adbb6ab0aa13735224182931d937a2
[ "Apache-2.0" ]
null
null
null
protect/src/main/java/mi/protectactivity/Utils.java
HooRang/AndroidUniversalSamples
4f6fcd8278adbb6ab0aa13735224182931d937a2
[ "Apache-2.0" ]
null
null
null
protect/src/main/java/mi/protectactivity/Utils.java
HooRang/AndroidUniversalSamples
4f6fcd8278adbb6ab0aa13735224182931d937a2
[ "Apache-2.0" ]
null
null
null
29.457831
149
0.617587
1,844
package mi.protectactivity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.util.Log; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by magic on 2017/8/15. */ public class Utils { private static final String TAG = Utils.class.getSimpleName(); //mi.attackactivity //C8D69481E7A2722BADA5AD87D61BACBC77E80EF1896C68D6E0D6948C514C22F0 //此时3rd app只有通过包名和签名验证才能打开受保护的Activity public static boolean permissionCheck(String pName ,String sign){ if (pName!=null&&pName.equals("mi.attackactivity")&&sign.equals("C8D69481E7A2722BADA5AD87D61BACBC77E80EF1896C68D6E0D6948C514C22F0")){ return true; }else if (pName!=null&&pName.equals("mi.protectactivity")&&sign.equals("C8D69481E7A2722BADA5AD87D61BACBC77E80EF1896C68D6E0D6948C514C22F0")){ return true; } else { return false; } } public static byte[] getPackageSignDigest(String pName, Context context) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pName, PackageManager.GET_SIGNATURES); // byte[] certBytes = packageInfo.signatures[0].toByteArray(); for (Signature sig : packageInfo.signatures) { digest.update(sig.toByteArray()); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return digest.digest(); } public static String getPackageSignHex(String pName, Context context){ return byte2hex(getPackageSignDigest(pName, context)); } public static String byte2hex(byte[] b) { if (b == null){ return "input is null"; } // 转成16进制字符串 String hs = ""; String tmp = ""; for (int n = 0; n < b.length; n++) { //整数转成十六进制表示 tmp = (Integer.toHexString(b[n] & 0XFF)); if (tmp.length() == 1) { hs = hs + "0" + tmp; } else { hs = hs + tmp; } } tmp = null; return hs.toUpperCase(); } }
3e0466bffc2bda4deadb46b1b3d1811d60361cba
7,445
java
Java
fhir-model/src/main/java/com/ibm/fhir/model/type/Money.java
IBM/fhir
7190cac9f999c8676dc8932ed9362e61100ddaed
[ "Apache-2.0" ]
2
2019-08-14T14:55:19.000Z
2019-08-14T15:01:55.000Z
fhir-model/src/main/java/com/ibm/fhir/model/type/Money.java
IBM/fhir
7190cac9f999c8676dc8932ed9362e61100ddaed
[ "Apache-2.0" ]
null
null
null
fhir-model/src/main/java/com/ibm/fhir/model/type/Money.java
IBM/fhir
7190cac9f999c8676dc8932ed9362e61100ddaed
[ "Apache-2.0" ]
null
null
null
30.020161
128
0.561316
1,845
/* * (C) Copyright IBM Corp. 2019, 2022 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.model.type; import java.util.Collection; import java.util.Objects; import javax.annotation.Generated; import com.ibm.fhir.model.annotation.Binding; import com.ibm.fhir.model.annotation.Summary; import com.ibm.fhir.model.type.code.BindingStrength; import com.ibm.fhir.model.util.ValidationSupport; import com.ibm.fhir.model.visitor.Visitor; /** * An amount of economic utility in some recognized currency. */ @Generated("com.ibm.fhir.tools.CodeGenerator") public class Money extends Element { @Summary private final Decimal value; @Summary @Binding( bindingName = "CurrencyCode", strength = BindingStrength.Value.REQUIRED, valueSet = "http://hl7.org/fhir/ValueSet/currencies|4.3.0-cibuild" ) private final Code currency; private Money(Builder builder) { super(builder); value = builder.value; currency = builder.currency; } /** * Numerical value (with implicit precision). * * @return * An immutable object of type {@link Decimal} that may be null. */ public Decimal getValue() { return value; } /** * ISO 4217 Currency Code. * * @return * An immutable object of type {@link Code} that may be null. */ public Code getCurrency() { return currency; } @Override public boolean hasChildren() { return super.hasChildren() || (value != null) || (currency != null); } @Override public void accept(java.lang.String elementName, int elementIndex, Visitor visitor) { if (visitor.preVisit(this)) { visitor.visitStart(elementName, elementIndex, this); if (visitor.visit(elementName, elementIndex, this)) { // visit children accept(id, "id", visitor); accept(extension, "extension", visitor, Extension.class); accept(value, "value", visitor); accept(currency, "currency", visitor); } visitor.visitEnd(elementName, elementIndex, this); visitor.postVisit(this); } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Money other = (Money) obj; return Objects.equals(id, other.id) && Objects.equals(extension, other.extension) && Objects.equals(value, other.value) && Objects.equals(currency, other.currency); } @Override public int hashCode() { int result = hashCode; if (result == 0) { result = Objects.hash(id, extension, value, currency); hashCode = result; } return result; } @Override public Builder toBuilder() { return new Builder().from(this); } public static Builder builder() { return new Builder(); } public static class Builder extends Element.Builder { private Decimal value; private Code currency; private Builder() { super(); } /** * Unique id for the element within a resource (for internal references). This may be any string value that does not * contain spaces. * * @param id * Unique id for inter-element referencing * * @return * A reference to this Builder instance */ @Override public Builder id(java.lang.String id) { return (Builder) super.id(id); } /** * May be used to represent additional information that is not part of the basic definition of the element. To make the * use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of * extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part * of the definition of the extension. * * <p>Adds new element(s) to the existing list. * If any of the elements are null, calling {@link #build()} will fail. * * @param extension * Additional content defined by implementations * * @return * A reference to this Builder instance */ @Override public Builder extension(Extension... extension) { return (Builder) super.extension(extension); } /** * May be used to represent additional information that is not part of the basic definition of the element. To make the * use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of * extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part * of the definition of the extension. * * <p>Replaces the existing list with a new one containing elements from the Collection. * If any of the elements are null, calling {@link #build()} will fail. * * @param extension * Additional content defined by implementations * * @return * A reference to this Builder instance * * @throws NullPointerException * If the passed collection is null */ @Override public Builder extension(Collection<Extension> extension) { return (Builder) super.extension(extension); } /** * Numerical value (with implicit precision). * * @param value * Numerical value (with implicit precision) * * @return * A reference to this Builder instance */ public Builder value(Decimal value) { this.value = value; return this; } /** * ISO 4217 Currency Code. * * @param currency * ISO 4217 Currency Code * * @return * A reference to this Builder instance */ public Builder currency(Code currency) { this.currency = currency; return this; } /** * Build the {@link Money} * * @return * An immutable object of type {@link Money} * @throws IllegalStateException * if the current state cannot be built into a valid Money per the base specification */ @Override public Money build() { Money money = new Money(this); if (validating) { validate(money); } return money; } protected void validate(Money money) { super.validate(money); ValidationSupport.requireValueOrChildren(money); } protected Builder from(Money money) { super.from(money); value = money.value; currency = money.currency; return this; } } }
3e0466e056d5837d1943c95ff72b81ecf581db01
11,376
java
Java
fancyclient/src/main/java/ysy/game/client/v1/UIMain.java
NeoGitCrt1/g1
de5089c3ecd2bbf23d57fdb61a5783eebe30e08a
[ "MIT" ]
null
null
null
fancyclient/src/main/java/ysy/game/client/v1/UIMain.java
NeoGitCrt1/g1
de5089c3ecd2bbf23d57fdb61a5783eebe30e08a
[ "MIT" ]
null
null
null
fancyclient/src/main/java/ysy/game/client/v1/UIMain.java
NeoGitCrt1/g1
de5089c3ecd2bbf23d57fdb61a5783eebe30e08a
[ "MIT" ]
null
null
null
32.689655
111
0.545007
1,846
package ysy.game.client.v1; import ysy.game.model.Constant; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.HashMap; import java.util.Map; import static ysy.game.model.BodyMeta.Direction.*; import static ysy.game.model.Constant.CANVAS_HEIGHT; import static ysy.game.model.Constant.CANVAS_WIDTH; public class UIMain extends JPanel { public static final UIMain UI = new UIMain(); public static final Map<Long, Body> players = new HashMap<>(); public static final Map<Long, Body> mouses = new HashMap<>(); public static final Food food = new Food(); public static Man me = null; private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UIMain.class); //Declare menubar static JMenuBar menuBar; private GameCanvas pit; private ControlPanel control; private JLabel lblScore; UIMain() { setLayout(new BorderLayout()); //drawing panel pit = new GameCanvas(); pit.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT)); add(pit, BorderLayout.CENTER); //control panel to the bottom control = new ControlPanel(); add(control, BorderLayout.SOUTH); //add the menu bar setupMenuBar(); } public static void start() { //use the event dispatch thread to build the UI for thread-safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("G"); // main JPanel as content pane frame.setContentPane(UI); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); //center the app window frame.setLocationRelativeTo(null); //show the frame frame.setJMenuBar(menuBar); frame.setVisible(true); } }); UI.gameStart(); } public static void restart() { ClientEventHandle.prepareRestart(); UIMain.prepareRestart(); NettyChatClient.reconnect(); } private static void prepareRestart() { me = null; food.reset(); players.clear(); mouses.clear(); } // Helper function to setup the menubar private void setupMenuBar() { JMenu menu; //a menu in the menu bar JMenuItem menuItem; // a regular menu-item in a menu menuBar = new JMenuBar(); // First Menu - "Game" menu = new JMenu("Game"); menu.setMnemonic(KeyEvent.VK_G); menuBar.add(menu); //Help Menu menu = new JMenu("Help"); menu.setMnemonic(KeyEvent.VK_H); menuBar.add(menu); menuItem = new JMenuItem("Help Contents", KeyEvent.VK_H); menu.add(menuItem); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String message = "Play:\n" + "Arrow keys to change direction\n" + "\n\nStartUp: java -jar fancyclient.jar -h xxx.xxx.xxx.xxx -p yyy\n" + "-h : specify your server host> eg. 192.168.41.10\n" + "-p : specify your server port> eg. 8888"; JOptionPane.showMessageDialog(UI, message, "Instructions", JOptionPane.PLAIN_MESSAGE); } }); menuItem = new JMenuItem("About", KeyEvent.VK_A); menu.add(menuItem); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(UI, "[email protected]\n", "About", JOptionPane.PLAIN_MESSAGE); } }); } public void gameStart() { // Create a new thread Thread gameThread = new Thread() { //Override run() to provide the running behavior of this thread public void run() { while (true) { // Refresh the display repaint(); try { //Provides the necessary delay and also yields control //so that other thread can do work Thread.sleep(100); } catch (InterruptedException ex) { } } } }; //Start the thread.start() calls run, which in turn calls gameLoop() gameThread.start(); } private void gameDraw(Graphics g) { //draw game objects if (players.isEmpty() || food == null) { return; } players.values().forEach(b -> b.draw(g)); mouses.values().forEach(b -> b.draw(g)); food.draw(g, lblScore); log.trace("draw foo:{}", food); } private void gameKeyPressed(int keyCode) { Man myBody = me; if (myBody == null) { return; } if (keyCode == KeyEvent.VK_UP) { if (DOWN.directCode == myBody.direction()) { myBody.changeDirect(HALT.directCode); } else { myBody.changeDirect(UP.directCode); } } else if (keyCode == KeyEvent.VK_DOWN) { if (UP.directCode == myBody.direction()) { myBody.changeDirect(HALT.directCode); } else { myBody.changeDirect(DOWN.directCode); } } else if (keyCode == KeyEvent.VK_LEFT) { if (RIGHT.directCode == myBody.direction()) { myBody.changeDirect(HALT.directCode); } else { myBody.changeDirect(LEFT.directCode); } } else if (keyCode == KeyEvent.VK_RIGHT){ if (LEFT.directCode == myBody.direction()) { myBody.changeDirect(HALT.directCode); } else { myBody.changeDirect(RIGHT.directCode); } } NettyChatClient.cf.channel().writeAndFlush(myBody.gcEvent.toByteBuf()); } public void renderMsg(String txt) { lblScore.setText(txt); } class GameCanvas extends JPanel implements KeyListener { private static final long serialVersionUID = 1L; //constructor public GameCanvas() { setFocusable(true); //so that can receive key-events requestFocus(); addKeyListener(this); } //overwrite paintComponent to do custom drawing //called back by repaint() @Override public void paintComponent(Graphics g) { super.paintComponent(g); //paint background, may use an image for background //set background color setBackground(Color.decode("0x3F919E")); //draw the game objects gameDraw(g); } //KeyEvent handlers @Override public void keyPressed(KeyEvent e) { gameKeyPressed(e.getKeyCode()); } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } // Check if this pit contains the given(x,y) for collision detection @Override public boolean contains(int x, int y) { if ((x < 0) || (x >= Constant.ROWS)) return false; if ((y < 0) || (y >= Constant.COLUMNS)) return false; return true; } } //Game Control Panel with Start, Stop, Pause and Mute buttons, designed as an inner class class ControlPanel extends JPanel { private static final long serialVersionUID = 1L; private JButton btnStartPause; private JButton btnStop; private JButton btnMute; //import icons for buttons // private ImageIcon iconRetart = new ImageIcon(getClass().getResource("/images/restart.png"), "START"); // private ImageIcon iconStart = new ImageIcon(getClass().getResource("/images/start.png"), "START"); // private ImageIcon iconPause = new ImageIcon(getClass().getResource("/images/pause.png"), "PAUSE"); // private ImageIcon iconStop = new ImageIcon(getClass().getResource("/images/stop.png"), "STOP"); // private ImageIcon iconSound = new ImageIcon(getClass().getResource("/images/sound.png"), "SOUND ON"); // private ImageIcon iconMuted = new ImageIcon(getClass().getResource("/images/muted.png"), "MUTED"); public ControlPanel() { this.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); btnStartPause = new JButton(iconRetart); btnStartPause.setToolTipText("Restart"); btnStartPause.setCursor(new Cursor(Cursor.HAND_CURSOR)); btnStartPause.setEnabled(true); add(btnStartPause); // btnStop = new JButton(iconStop); // btnStop.setToolTipText("Stop"); // btnStop.setCursor(new Cursor(Cursor.HAND_CURSOR)); // btnStop.setEnabled(true); // add(btnStop); // btnMute = new JButton(iconMuted); // btnMute.setToolTipText("Mute"); // btnMute.setCursor(new Cursor(Cursor.HAND_CURSOR)); // btnMute.setEnabled(true); // add(btnMute); lblScore = new JLabel("Score: 0"); add(lblScore); //handle click events on buttons btnStartPause.addActionListener(e -> { restart(); pit.requestFocus(); }); // btnStop.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // btnStartPause.setEnabled(true); // btnStop.setEnabled(false); // //To play a specific sound //// SoundEffect.CLICK.play(); // // } // }); // btnMute.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { //// if (SoundEffect.volume == SoundEffect.Volume.MUTE) { //// SoundEffect.volume = SoundEffect.Volume.LOW; //// btnMute.setIcon(iconSound); //// //To play a specific sound //// SoundEffect.CLICK.play(); //// pit.requestFocus(); //// } else { //// SoundEffect.volume = SoundEffect.Volume.MUTE; //// btnMute.setIcon(iconMuted); //// //To play a specific sound //// SoundEffect.CLICK.play(); //// pit.requestFocus(); //// } // // } // }); // } // // // Reset control for a new game // public void reset() { // btnStartPause.setIcon(iconStart); // btnStartPause.setEnabled(true); // btnStop.setEnabled(false); // } } }
3e0467e8adcec98df5e67469ca131524357e0f2b
1,753
java
Java
catalogue/src/main/java/org/openbaton/catalogue/nfvo/networks/Network.java
albadmin/nfvo
39f251ed7df9794c12c79ae6377e7ede505861f5
[ "Apache-2.0" ]
65
2015-10-01T04:11:04.000Z
2021-11-11T12:08:22.000Z
catalogue/src/main/java/org/openbaton/catalogue/nfvo/networks/Network.java
albadmin/nfvo
39f251ed7df9794c12c79ae6377e7ede505861f5
[ "Apache-2.0" ]
192
2015-10-06T15:27:48.000Z
2019-12-12T11:27:48.000Z
catalogue/src/main/java/org/openbaton/catalogue/nfvo/networks/Network.java
albadmin/nfvo
39f251ed7df9794c12c79ae6377e7ede505861f5
[ "Apache-2.0" ]
74
2015-10-01T06:34:23.000Z
2022-03-11T08:03:04.000Z
24.347222
75
0.689675
1,847
/* * Copyright (c) 2015-2018 Open Baton (http://openbaton.org) * * 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.openbaton.catalogue.nfvo.networks; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; @Entity public class Network extends BaseNetwork { private Boolean external = false; private Boolean extShared = false; @Override public String toString() { return "Network{" + "external=" + external + ", extShared=" + extShared + ", subnets=" + subnets + "} " + super.toString(); } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<Subnet> subnets; public Network() {} public Boolean getExternal() { return external; } public void setExternal(Boolean external) { this.external = external; } public Boolean getExtShared() { return extShared; } public void setExtShared(Boolean extShared) { this.extShared = extShared; } public Set<Subnet> getSubnets() { return subnets; } public void setSubnets(Set<Subnet> subnets) { this.subnets = subnets; } }
3e04682fd69fdeee51230e5047e3922db544ad58
2,351
java
Java
src/goryachev/swing/theme/ALinearPanel.java
andy-goryachev/PasswordSafe
eeaac1cf97bcd531f5cd558a1483cef4c29c16ca
[ "Apache-2.0" ]
16
2015-02-23T06:50:12.000Z
2020-07-20T13:00:46.000Z
src/goryachev/swing/theme/ALinearPanel.java
andy-goryachev/PasswordSafe
eeaac1cf97bcd531f5cd558a1483cef4c29c16ca
[ "Apache-2.0" ]
5
2016-12-22T00:20:36.000Z
2021-07-24T17:49:35.000Z
src/goryachev/swing/theme/ALinearPanel.java
andy-goryachev/PasswordSafe
eeaac1cf97bcd531f5cd558a1483cef4c29c16ca
[ "Apache-2.0" ]
null
null
null
15.372549
68
0.631378
1,848
// Copyright © 2015-2022 Andy Goryachev <[email protected]> package goryachev.swing.theme; import goryachev.swing.CBorder; import goryachev.swing.Theme; import java.awt.Component; import java.awt.LayoutManager; public class ALinearPanel extends ScrollablePanel { public ALinearPanel(boolean horizontal, int gap) { super(new LinearLayout(horizontal)); setGap(gap); } public ALinearPanel(boolean horizontal) { this(horizontal, 0); } public void space(float spec) { insertCell(spec); } public void space() { space(10); } public Component add(float spec, Component c) { int ix = getCellCount(); add(c, spec); return c; } public Component add(Component c) { add(LinearLayout.PREFERRED, c); return c; } public Component fill(Component c) { add(LinearLayout.FILL, c); return c; } public void fill() { insertCell(LinearLayout.FILL); } protected void insertCell(float spec) { int ix = getCellCount(); linearLayout().setCellSpec(ix, spec); } public int getCellCount() { return linearLayout().getCellCount(); } public void setGap(int gap) { linearLayout().setGap(gap); } public void setLayout(LayoutManager m) { if(m instanceof LinearLayout) { super.setLayout(m); } else { throw new Error(); } } public LinearLayout linearLayout() { return (LinearLayout)getLayout(); } public void setCellMinimumSize(int ix, int size) { linearLayout().setCellMaximumSize(ix, size); } public void setCellMaximumSize(int ix, int size) { linearLayout().setCellMaximumSize(ix, size); } /** creates standard 10-pixel border */ public void border() { setBorder(); } /** creates standard 10-pixel border */ public void setBorder() { setBorder(Theme.border10()); } public CBorder setBorder(int gap) { CBorder b = new CBorder(gap); setBorder(b); return b; } public CBorder setBorder(int vertGap, int horGap) { CBorder b = new CBorder(vertGap, horGap); setBorder(b); return b; } public CBorder setBorder(int top, int left, int bottom, int right) { CBorder b = new CBorder(top, left, bottom, right); setBorder(b); return b; } }
3e046839ea0fec1330086466eff74458183bc7a4
8,022
java
Java
app/src/main/java/com/guashu/book/api/QianQianApi.java
earlma/-
2c11ab2d8ba3e4c20bcebe231ba6b42dc380ba53
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/guashu/book/api/QianQianApi.java
earlma/-
2c11ab2d8ba3e4c20bcebe231ba6b42dc380ba53
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/guashu/book/api/QianQianApi.java
earlma/-
2c11ab2d8ba3e4c20bcebe231ba6b42dc380ba53
[ "Apache-2.0" ]
null
null
null
37.311628
122
0.5455
1,849
package com.guashu.book.api; import com.guashu.book.base.IBookApi; import com.guashu.book.bean.BookDetail; import com.guashu.book.bean.BookMixAToc; import com.guashu.book.bean.BookSource; import com.guashu.book.bean.ChapterRead; import com.guashu.book.bean.Recommend; import com.guashu.book.bean.SearchDetail; import com.sinovoice.hcicloudsdk.common.utils.Md5Util; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import rx.Observable; import rx.Subscriber; /** * 千千小说 * * @author user */ public class QianQianApi implements IBookApi { private static final BookSource BOOK_SOURCE = BookSource.QIANQIAN; @Override public List<Recommend.RecommendBook> getRecommend(String bookType) { return null; } @Override public List<SearchDetail.SearchBooks> searchBooKFuzzy(String name) { List<SearchDetail.SearchBooks> list = new ArrayList<SearchDetail.SearchBooks>(); String url = "http://zhannei.baidu.com/cse/search?q=" + name + "&s=2131500230171486847&entry=1"; try { Document document = Jsoup.connect(url).get(); // 封面 Elements select = document .select(".result-game-item-pic a img[src]"); // 书名和链接 Elements select2 = document .select(".result-item-title.result-game-item-title a"); // 作者 类型 更新时间 Elements select3 = document .select(".result-game-item-info-tag span"); for (int i = 1; i < select.size(); i++) { SearchDetail.SearchBooks books = new SearchDetail.SearchBooks(); books.url = select2.get(i - 1).attr("href"); books.title = select2.get(i - 1).attr("title"); books.author = select3.get(7 * (i - 1) + 1).text(); books.bookType = select3.get(7 * (i - 1) + 3).text(); books.updateTime = select3.get(7 * (i - 1) + 5).text(); books.cover = select.get(i - 1).attr("src"); books.bookSource = BOOK_SOURCE; books._id = Md5Util.MD5(books.url); list.add(books); } return list; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public SearchDetail.SearchBooks searchBooKExact(String name) { String url = "http://zhannei.baidu.com/cse/search?q=" + name + "&s=2131500230171486847&entry=1"; try { Document document = Jsoup.connect(url).get(); // 封面 Elements select = document .select(".result-game-item-pic a img[src]"); // 书名和链接 Elements select2 = document .select(".result-item-title.result-game-item-title a"); // 作者 类型 更新时间 Elements select3 = document .select(".result-game-item-info-tag span"); for (int i = 1; i < select.size(); i++) { SearchDetail.SearchBooks books = new SearchDetail.SearchBooks(); books.url = select2.get(i - 1).attr("href"); books.title = select2.get(i - 1).attr("title"); books.author = select3.get(7 * (i - 1) + 1).text(); books.bookType = select3.get(7 * (i - 1) + 3).text(); books.updateTime = select3.get(7 * (i - 1) + 5).text(); books.cover = select.get(i - 1).attr("src"); books.bookSource = BOOK_SOURCE; books._id = Md5Util.MD5(books.url); if (name.equals(books.title)) { System.err.println(books.toString()); return books; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public List<BookMixAToc.mixToc.Chapters> getChapterList(String bookUrl) { List<BookMixAToc.mixToc.Chapters> list = new ArrayList<BookMixAToc.mixToc.Chapters>(); try { Document document = Jsoup.connect(bookUrl).get(); Elements select = document.select("dd a"); for (int i = 0; i < select.size(); i++) { BookMixAToc.mixToc.Chapters chapter = new BookMixAToc.mixToc.Chapters(); chapter.link = bookUrl + select.get(i).attr("href"); chapter.title = select.get(i).text(); chapter.id = Md5Util.MD5(chapter.link); list.add(chapter); } return list; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public Observable<ChapterRead.Chapter> getChapter(final String chapterUrl) { Observable<ChapterRead.Chapter> observable = Observable.create(new Observable.OnSubscribe<ChapterRead.Chapter>() { @Override public void call(Subscriber<? super ChapterRead.Chapter> subscriber) { subscriber.onNext(getChapterRead(chapterUrl)); subscriber.onCompleted(); } }); return observable; } @Override public BookDetail getBookDetail(String bookUrl) { try { Document document = Jsoup.connect(bookUrl).get(); Elements select = document.select("meta"); if (select.size() < 20) { return null; } BookDetail book = new BookDetail(); // 书名 Element element = select.get(15); book.title = (element.attr("content").toString()); // 简介 Element element2 = select.get(11); book.longIntro = (element2.attr("content").toString()); // 封面链接 Element element3 = select.get(12); book.cover = (element3.attr("content").toString()); // 分类 Element element4 = select.get(13); book.type = (element4.attr("content").toString()); // 作者 Element element5 = select.get(14); book.author = (element5.attr("content").toString()); // 书籍链接 Element element6 = select.get(16); book.url = (element6.attr("content").toString()); // 状态 Element element7 = select.get(18); book.status = (element7.attr("content").toString()); // 更新时间 Element element8 = select.get(20); book.updated = (element8.attr("content").toString()); // 最后一章 Element element9 = select.get(21); book.lastChapter = (element9.attr("content").toString()); book.bookSource = BOOK_SOURCE; book._id = Md5Util.MD5(book.url); return book; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public List<Recommend.RecommendBook> getRecommendBooks() { return null; } @Override public ChapterRead.Chapter getChapterRead(String chapterUrl) { try { Document document = Jsoup.connect(chapterUrl).get(); String body = document.select("#TXT").text(); String title = document.select("h1").text(); String[] split = body.split("     "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < split.length; i++) { String string = "     " + split[i] + "\n"; sb.append(string); } return new ChapterRead.Chapter(title, sb.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } }
3e0468a4bdfe0f7dc691148dddd96db7e3966598
2,148
java
Java
src/game/db/dao/ClasseDao.java
jjanuario/databaseeditor
459c0fc459f6127b0c45e38cfcb30ed80a422f51
[ "BSD-3-Clause" ]
null
null
null
src/game/db/dao/ClasseDao.java
jjanuario/databaseeditor
459c0fc459f6127b0c45e38cfcb30ed80a422f51
[ "BSD-3-Clause" ]
null
null
null
src/game/db/dao/ClasseDao.java
jjanuario/databaseeditor
459c0fc459f6127b0c45e38cfcb30ed80a422f51
[ "BSD-3-Clause" ]
null
null
null
29.972222
134
0.644115
1,850
package game.db.dao; import game.db.entity.Classe; import game.db.util.HibernateUtil; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; /** * =========================================== <br> * PROJETO PARALLAX - Data Base Editor <br> * Data de alteração do arquivo: 30/10/2012 <br> * =========================================== * <P> * * A classe <b>ClasseDao</b> (ClasseDao) * Acessa os dados dos objetos no banco. * <p> * * @see <a * href="http://www.einformacao.com.br/parallax/component/content/article/35-conteudo-site/86-documentos-para-leitura">Documentos * para Leitura</a> * @author <a href="mailto:[email protected]">Jeferson Januario</a> * @version 1.0.1 * @since Existe desde a versão 1.0.1 do projeto */ public class ClasseDao { private final Session session = HibernateUtil.getSessionFactory().openSession(); @SuppressWarnings("unchecked") public List<Classe> lista() { return session.createCriteria(Classe.class).list(); } @SuppressWarnings("unchecked") public List<Integer> getAnimationObjectMovimentId() { return session.createSQLQuery("select ANIMATIONOBJECT.ID from ANIMATIONOBJECT WHERE TYPEIMAGE='moviment'").list(); } @SuppressWarnings("unchecked") public List<Integer> getImagemBattlerId() { return session.createSQLQuery("select IMAGEM.ID from IMAGEM WHERE TYPEIMAGE='battle'").list(); } @SuppressWarnings("unchecked") public List<Integer> getImagemFaceId() { return session.createSQLQuery("select IMAGEM.ID from IMAGEM WHERE TYPEIMAGE='face'").list(); } public void saveOrUpDate(Classe classe) { Transaction tx = session.beginTransaction(); session.saveOrUpdate(classe); tx.commit(); } public void remove(List<Classe> list) { Transaction tx = session.beginTransaction(); try{ for(int i=0; list.size() > i; i++){ session.delete(list.get(i)); }}catch(HibernateException he){ new Throwable(he); } tx.commit(); } }
3e0468bafc1c83cfb7ac8dcfc747025bbaf655b8
3,247
java
Java
app/src/main/java/com/app/wi_fi_direct/helpers/PathUtil.java
GhodelApps/WiFi-Direct-File-Transfer-App
8fbbdc84be16dc87b7ac8fce2146fb7acad36296
[ "Apache-2.0" ]
85
2018-04-09T21:05:24.000Z
2022-03-11T03:06:32.000Z
app/src/main/java/com/app/wi_fi_direct/helpers/PathUtil.java
naveensenapathi/File-Transfer-WiFi-Direct
cf9c109caf90c43c24bd349bd664c48e8f10a134
[ "Apache-2.0" ]
6
2018-04-06T07:46:30.000Z
2022-01-09T13:06:30.000Z
app/src/main/java/com/app/wi_fi_direct/helpers/PathUtil.java
naveensenapathi/File-Transfer-WiFi-Direct
cf9c109caf90c43c24bd349bd664c48e8f10a134
[ "Apache-2.0" ]
34
2018-04-11T12:19:02.000Z
2022-02-16T02:45:45.000Z
35.681319
101
0.674161
1,851
package com.app.wi_fi_direct.helpers; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; public class PathUtil { /* * Gets the file path of the given Uri. */ @SuppressLint("NewApi") public static String getPath(Context context, Uri uri) { final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19; String selection = null; String[] selectionArgs = null; // Uri is different in versions after KITKAT (Android 4.4), we need to // deal with different Uris. if (needToCheckUri && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) { if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); return Environment.getExternalStorageDirectory() + "/" + split[1]; } else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); uri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); } else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("image".equals(type)) { uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } selection = "_id=?"; selectionArgs = new String[]{split[1]}; } } if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } }
3e0469aa7f8872219e4d6ec35c24b590d66216ab
1,266
java
Java
metrics-aggregator/src/main/java/org/oisp/services/conf/CmdlineOptions.java
Open-IoT-Service-Platform/oisp-services
1491d9ebd734ef64e2e00a22551ed3d51d816c9f
[ "Apache-2.0" ]
1
2021-08-31T11:14:53.000Z
2021-08-31T11:14:53.000Z
metrics-aggregator/src/main/java/org/oisp/services/conf/CmdlineOptions.java
Open-IoT-Service-Platform/oisp-services
1491d9ebd734ef64e2e00a22551ed3d51d816c9f
[ "Apache-2.0" ]
15
2020-09-11T11:20:52.000Z
2022-01-21T14:39:00.000Z
metrics-aggregator/src/main/java/org/oisp/services/conf/CmdlineOptions.java
Open-IoT-Service-Platform/oisp-services
1491d9ebd734ef64e2e00a22551ed3d51d816c9f
[ "Apache-2.0" ]
2
2019-12-17T10:49:56.000Z
2020-08-23T16:57:57.000Z
32.461538
75
0.739336
1,852
/* * Copyright (c) 2020 Intel Corporation * * 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.oisp.services.conf; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; public interface CmdlineOptions extends PipelineOptions { @Description("Kafka topic for metrics") @Default.String("") String getMetricsTopic(); void setMetricsTopic(String value); @Description("Kafka Bootstrap Servers") @Default.String("") String getBootstrapServers(); void setBootstrapServers(String value); @Description("Service Name") @Default.String("aggregator") String getServiceName(); void setServiceName(String value); }
3e046a969e06d7202c39693c481aedffda6ef9a8
4,767
java
Java
app/src/main/java/apackage/com/yournight/view/MainActivity.java
AuroraSyN/YourNight
b5aff40ceb0a2df91573a6ac971cafe04fcd7f0d
[ "MIT" ]
null
null
null
app/src/main/java/apackage/com/yournight/view/MainActivity.java
AuroraSyN/YourNight
b5aff40ceb0a2df91573a6ac971cafe04fcd7f0d
[ "MIT" ]
null
null
null
app/src/main/java/apackage/com/yournight/view/MainActivity.java
AuroraSyN/YourNight
b5aff40ceb0a2df91573a6ac971cafe04fcd7f0d
[ "MIT" ]
null
null
null
40.07563
105
0.621514
1,853
package apackage.com.yournight.view; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import apackage.com.yournight.R; import apackage.com.yournight.model.access.AccessLogin; import apackage.com.yournight.view.fragment.FragmentHome; import apackage.com.yournight.view.fragment.FragmentMap; import apackage.com.yournight.view.fragment.FragmentProfile; import apackage.com.yournight.view.EventSearch.FragmentSearch; import apackage.com.yournight.view.helper.BottomNavigationViewHelper; public class MainActivity extends AppCompatActivity { final static String ID_KEY = "ID"; final static String NAME_KEY = "NAME"; final static String EMAIL_KEY = "EMAIL"; private AccessLogin asses; //Save private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; @Override protected void onPause() { super.onPause(); editor = sharedPreferences.edit(); editor.putString(ID_KEY, asses.getUserID()); editor.putString(NAME_KEY, asses.getUserName()); editor.putString(EMAIL_KEY, asses.getUserEmail()); editor.commit(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AccessLogin.initialize(); asses = AccessLogin.getInstance(); // init_layout(); init(); BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigation); bottomNavigationView.setOnNavigationItemSelectedListener (new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment selectedFragment = null; switch (item.getItemId()) { case R.id.action_item1: selectedFragment = FragmentHome.newInstance(); break; case R.id.action_item2: selectedFragment = FragmentMap.newInstance(); break; case R.id.action_item3: selectedFragment = FragmentSearch.newInstance(); break; case R.id.action_item4: selectedFragment = FragmentProfile.newInstance(); break; } FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_layout, selectedFragment); transaction.commit(); return true; } }); BottomNavigationViewHelper.disableShiftMode(bottomNavigationView); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_layout, FragmentHome.newInstance()); transaction.commit(); //.Remove //showUserDataInLog(); } private void loadDataBase(){ asses.setUserID(sharedPreferences.getString(ID_KEY, "Network error, try reconnect")); asses.setUserEmail(sharedPreferences.getString(NAME_KEY, "Network error, try reconnect")); asses.setUserEmail(sharedPreferences.getString(EMAIL_KEY, "Network error, try reconnect")); } private void init(){ sharedPreferences = getPreferences(MODE_PRIVATE); if (asses.getToken() != null) { asses.setUserEmail(asses.getToken().getEmail()); asses.setUserName(asses.getToken().getUserName()); asses.setUserID(asses.getToken().getUserId()); // userPictureView.setProfileId(userID); } else { asses.setUserEmail("[email protected]"); asses.setUserName("Offline Login"); asses.setUserID("0ffline"); } if (asses.getUserEmail() == null || asses.getUserName() == null) { loadDataBase(); } } private void showUserDataInLog() { Log.e("Main:", asses.getUserEmail()); Log.e("Main:", asses.getUserName()); Log.e("Main:", asses.getUserID()); // Log.e("MainToken:", "" + asses.getToken().getToken()); } }
3e046b8842b3b2778752ceda7b5b9e1c21e35b08
5,547
java
Java
src/main/java/com/acmeair/jpa/service/FlightServiceImpl.java
dmckinstry/acme-air
44b90a79b4808209cfebb8c47bcb55eaf4def11c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/acmeair/jpa/service/FlightServiceImpl.java
dmckinstry/acme-air
44b90a79b4808209cfebb8c47bcb55eaf4def11c
[ "Apache-2.0" ]
16
2020-08-13T20:29:01.000Z
2021-06-10T20:40:44.000Z
src/main/java/com/acmeair/jpa/service/FlightServiceImpl.java
dmckinstry/acme-air
44b90a79b4808209cfebb8c47bcb55eaf4def11c
[ "Apache-2.0" ]
1
2022-02-25T22:10:23.000Z
2022-02-25T22:10:23.000Z
41.395522
170
0.633496
1,854
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * 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.acmeair.jpa.service; import com.acmeair.entities.AirportCodeMapping; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightPK; import com.acmeair.entities.FlightSegment; import com.acmeair.service.FlightService; import com.acmeair.service.KeyGenerator; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class FlightServiceImpl implements FlightService { private final EntityManager em; private final KeyGenerator keyGenerator; public FlightServiceImpl(EntityManager em, KeyGenerator keyGenerator) { this.em = em; this.keyGenerator = keyGenerator; } @Override public Flight getFlightByFlightKey(FlightPK key) { return em.find(Flight.class, key); } @Override public List<Flight> getFlightByAirportsAndDepartureDate(String fromAirport, String toAirport, Date deptDate) { final List<Flight> flights = new ArrayList<Flight>(); final TypedQuery<FlightSegment> q = em.createQuery("SELECT obj FROM FlightSegment obj where obj.destPort=?1 and obj.originPort=?2", FlightSegment.class) .setParameter(1, toAirport) .setParameter(2, fromAirport); final List<FlightSegment> results = q.getResultList(); for (FlightSegment seg : results) { final TypedQuery<Flight> qq = em.createQuery("SELECT obj FROM Flight obj where obj.scheduledDepartureTime=?1 and obj.pkey.flightSegmentId=?2", Flight.class) .setParameter(1, deptDate) .setParameter(2, seg.getFlightName()); final List<Flight> foundFlights = qq.getResultList(); for (Flight flight : foundFlights) { flight.setFlightSegment(seg); flights.add(flight); } } return flights; } @Override public List<Flight> getFlightByAirports(String fromAirport, String toAirport) { final TypedQuery<FlightSegment> q = em.createQuery("SELECT obj FROM FlightSegment obj where obj.destPort=?1 and obj.originPort=?2", FlightSegment.class) .setParameter(1, toAirport) .setParameter(2, fromAirport); final List<Flight> flights = new ArrayList<>(); final List<FlightSegment> results = q.getResultList(); for (FlightSegment seg : results) { final TypedQuery<Flight> qq = em.createQuery("SELECT obj FROM Flight obj where obj.pkey.flightSegmentId=?1", Flight.class) .setParameter(1, seg.getFlightName()); final List<Flight> foundFlights = qq.getResultList(); for (Flight flight : foundFlights) { flight.setFlightSegment(seg); flights.add(flight); } } return flights; } @Transactional @Override public void storeAirportMapping(AirportCodeMapping mapping) { final TypedQuery<AirportCodeMapping> q = em.createQuery("SELECT obj FROM AirportCodeMapping obj where obj.id=?1 and obj.airportName=?2", AirportCodeMapping.class) .setParameter(1, mapping.getAirportCode()) .setParameter(2, mapping.getAirportName()); if (q.getResultList().isEmpty()) { try { em.persist(mapping); } catch (Exception e) { throw new RuntimeException(e); } } } @Transactional @Override public Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId) { try { final String id = keyGenerator.generate().toString(); final Flight flight = new Flight(id, flightSegmentId, scheduledDepartureTime, scheduledArrivalTime, firstClassBaseCost, economyClassBaseCost, numFirstClassSeats, numEconomyClassSeats, airplaneTypeId); em.persist(flight); return flight; } catch (Exception e) { throw new RuntimeException(e); } } @Transactional @Override public void storeFlightSegment(FlightSegment flightSeg) { try { em.persist(flightSeg); } catch (Exception e) { throw new RuntimeException(e); } } }
3e046c69da10c6c47fe99c15278b1e9f8ce370d4
23,946
java
Java
basex-core/src/main/java/org/basex/query/expr/ParseExpr.java
Acidburn0zzz/basex
755b116e96aa0fb48f4de5f2f34de0e5213df391
[ "BSD-3-Clause" ]
1
2017-03-23T17:41:51.000Z
2017-03-23T17:41:51.000Z
basex-core/src/main/java/org/basex/query/expr/ParseExpr.java
Acidburn0zzz/basex
755b116e96aa0fb48f4de5f2f34de0e5213df391
[ "BSD-3-Clause" ]
null
null
null
basex-core/src/main/java/org/basex/query/expr/ParseExpr.java
Acidburn0zzz/basex
755b116e96aa0fb48f4de5f2f34de0e5213df391
[ "BSD-3-Clause" ]
null
null
null
32.938102
99
0.675311
1,855
package org.basex.query.expr; import static org.basex.query.QueryError.*; import static org.basex.query.QueryText.*; import static org.basex.util.Token.*; import org.basex.query.*; import org.basex.query.func.*; import org.basex.query.iter.*; import org.basex.query.value.*; import org.basex.query.value.array.Array; import org.basex.query.value.item.*; import org.basex.query.value.map.*; import org.basex.query.value.node.*; import org.basex.query.value.seq.*; import org.basex.query.value.type.*; import org.basex.util.*; /** * Abstract parse expression. All non-value expressions are derived from this class. * * @author BaseX Team 2005-17, BSD License * @author Christian Gruen */ public abstract class ParseExpr extends Expr { /** Input information. */ public InputInfo info; /** Static type. */ public SeqType seqType; /** Cardinality of result; {@code -1} if unknown * ({@link #seqType} will then be requested to estimate result size). */ protected long size = -1; /** * Constructor. * @param info input info (can be {@code null} */ protected ParseExpr(final InputInfo info) { this.info = info; } @Override public Iter iter(final QueryContext qc) throws QueryException { final Item it = item(qc, info); return it != null ? it.iter() : Empty.ITER; } @Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final Iter ir = iter(qc); final Item it = ir.next(); if(it == null || ir.size() == 1) return it; final Item n = ir.next(); if(n != null) { final ValueBuilder vb = new ValueBuilder().add(it).add(n); if(ir.next() != null) vb.add(Str.get(DOTS)); throw SEQFOUND_X.get(info, vb.value()); } return it; } @Override public Value value(final QueryContext qc) throws QueryException { if(seqType().zeroOrOne()) { final Value v = item(qc, info); return v == null ? Empty.SEQ : v; } return qc.iter(this).value(); } @Override public Value atomValue(final QueryContext qc, final InputInfo ii) throws QueryException { return value(qc).atomValue(info); } @Override public final Item atomItem(final QueryContext qc, final InputInfo ii) throws QueryException { final Item it = item(qc, info); return it == null ? null : it.atomItem(info); } /** * Copies this expression's return type and size to the given expression. * @param <T> expression type * @param ex expression * @return the expression for convenience */ protected final <T extends ParseExpr> T copyType(final T ex) { ex.seqType = seqType; ex.size = size; return ex; } @Override public final Item ebv(final QueryContext qc, final InputInfo ii) throws QueryException { final Item it; if(seqType().zeroOrOne()) { it = item(qc, info); } else { final Iter ir = iter(qc); it = ir.next(); if(it != null && !(it instanceof ANode)) { final Item n = ir.next(); if(n != null) { final ValueBuilder vb = new ValueBuilder().add(it).add(n); if(ir.next() != null) vb.add(Str.get(DOTS)); throw EBV_X.get(info, vb.value()); } } } return it == null ? Bln.FALSE : it; } @Override public final Item test(final QueryContext qc, final InputInfo ii) throws QueryException { final Item it = ebv(qc, info); return (it instanceof ANum ? it.dbl(info) == qc.focus.pos : it.bool(info)) ? it : null; } @Override public final SeqType seqType() { return seqType != null ? seqType : SeqType.ITEM_ZM; } @Override public final long size() { final long s = size; return s == -1 ? seqType().occ() : s; } // OPTIMIZATIONS ================================================================================ /** * Pre-evaluates the specified expression. * @param cc compilation context * @return optimized expression * @throws QueryException query exception */ protected final Expr preEval(final CompileContext cc) throws QueryException { return optPre(item(cc.qc, info), cc); } /** * Adds an optimization info for pre-evaluating the specified expression. * @param cc compilation context * @return optimized expression */ protected final Expr optPre(final CompileContext cc) { return optPre(null, cc); } /** * Adds an optimization info for pre-evaluating the specified expression. * @param ex original or optimized expression (can be {@code null}) * @param cc compilation context * @return optimized expression */ protected final Expr optPre(final Expr ex, final CompileContext cc) { if(ex != this) cc.info(OPTPRE_X, this); return ex == null ? Empty.SEQ : ex; } /** * Returns a boolean equivalent for the specified expression. * If the specified expression yields a boolean value anyway, it will be * returned as is. Otherwise, it will be wrapped into a boolean function. * @param ex expression to be rewritten * @param info input info * @param sc static context * @return expression */ protected static Expr compBln(final Expr ex, final InputInfo info, final StaticContext sc) { return ex.seqType().eq(SeqType.BLN) ? ex : Function.BOOLEAN.get(sc, info, ex); } // VALIDITY CHECKS ============================================================================== /** * Ensures that the specified expression performs no updates. * Otherwise, throws an exception. * @param expr expression (may be {@code null}) * @throws QueryException query exception */ protected void checkNoUp(final Expr expr) throws QueryException { if(expr == null) return; expr.checkUp(); if(expr.has(Flag.UPD)) throw UPNOT_X.get(info, description()); } /** * Ensures that none of the specified expressions performs an update. * Otherwise, throws an exception. * @param exprs expressions (may be {@code null}, and may contain {@code null} references) * @throws QueryException query exception */ protected final void checkNoneUp(final Expr... exprs) throws QueryException { if(exprs == null) return; checkAllUp(exprs); for(final Expr expr : exprs) { if(expr != null && expr.has(Flag.UPD)) throw UPNOT_X.get(info, description()); } } /** * Ensures that all specified expressions are vacuous or either updating or non-updating. * Otherwise, throws an exception. * @param exprs expressions to be checked * @throws QueryException query exception */ void checkAllUp(final Expr... exprs) throws QueryException { // updating state: 0 = initial state, 1 = updating, -1 = non-updating int s = 0; for(final Expr expr : exprs) { expr.checkUp(); if(expr.isVacuous()) continue; final boolean u = expr.has(Flag.UPD); if(u ? s == -1 : s == 1) throw UPALL.get(info, description()); s = u ? 1 : -1; } } /** * Returns the current context value or throws an exception if the context value is not set. * @param qc query context * @return context * @throws QueryException query exception */ protected final Value ctxValue(final QueryContext qc) throws QueryException { final Value v = qc.focus.value; if(v != null) return v; throw NOCTX_X.get(info, this); } // CONVERSIONS ================================================================================== /** * Checks if the specified expression yields a string. * Returns a value as token or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return token * @throws QueryException query exception */ protected final byte[] toToken(final Expr ex, final QueryContext qc) throws QueryException { final Item it = ex.atomItem(qc, info); if(it == null) throw EMPTYFOUND_X.get(info, AtomType.STR); return toToken(it); } /** * Checks if the specified expression yields a string or an empty sequence. * Returns a value as token or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return token (empty string if result is an empty sequence) * @throws QueryException query exception */ protected final byte[] toEmptyToken(final Expr ex, final QueryContext qc) throws QueryException { final Item it = ex.atomItem(qc, info); return it == null ? EMPTY : toToken(it); } /** * Checks if the specified non-empty item is a string. * Returns its value as token or throws an exception. * @param it item to be checked * @return token * @throws QueryException query exception */ protected final byte[] toToken(final Item it) throws QueryException { final Type ip = it.type; if(ip.isStringOrUntyped()) return it.string(info); throw it instanceof FItem ? FIATOM_X.get(info, it.type) : castError(it, AtomType.STR, info); } /** * Checks if the specified expression yields a boolean. * Returns the boolean or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return boolean * @throws QueryException query exception */ protected final boolean toBoolean(final Expr ex, final QueryContext qc) throws QueryException { return toBoolean(ex.atomItem(qc, info)); } /** * Checks if the specified item is a boolean. * Returns the boolean or throws an exception. * @param it item be checked * @return boolean * @throws QueryException query exception */ protected final boolean toBoolean(final Item it) throws QueryException { final Type ip = checkNoEmpty(it, AtomType.BLN).type; if(ip == AtomType.BLN) return it.bool(info); if(ip.isUntyped()) return Bln.parse(it.string(info), info); throw castError(it, AtomType.BLN, info); } /** * Checks if the specified expression yields a double. * Returns the double or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return double * @throws QueryException query exception */ protected final double toDouble(final Expr ex, final QueryContext qc) throws QueryException { return toDouble(ex.atomItem(qc, info)); } /** * Checks if the specified item is a double. * Returns the double or throws an exception. * @param it item * @return double * @throws QueryException query exception */ protected final double toDouble(final Item it) throws QueryException { if(checkNoEmpty(it, AtomType.DBL).type.isNumberOrUntyped()) return it.dbl(info); throw numberError(this, it); } /** * Checks if the specified expression yields a number or {@code null}. * Returns the number, {@code null}, or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return double * @throws QueryException query exception */ protected final ANum toNumber(final Expr ex, final QueryContext qc) throws QueryException { final Item it = ex.atomItem(qc, info); return it == null ? null : toNumber(it); } /** * Checks if the specified, non-empty item is a double. * Returns the double or throws an exception. * @param it item to be checked * @return number * @throws QueryException query exception */ private ANum toNumber(final Item it) throws QueryException { if(it.type.isUntyped()) return Dbl.get(it.dbl(info)); if(it instanceof ANum) return (ANum) it; throw numberError(this, it); } /** * Checks if the specified expression yields a float. * Returns the float or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return float * @throws QueryException query exception */ protected final float toFloat(final Expr ex, final QueryContext qc) throws QueryException { final Item it = ex.atomItem(qc, info); if(checkNoEmpty(it, AtomType.FLT).type.isNumberOrUntyped()) return it.flt(info); throw numberError(this, it); } /** * Checks if the specified expression yields an integer. * Returns a token representation or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return integer value * @throws QueryException query exception */ protected final long toLong(final Expr ex, final QueryContext qc) throws QueryException { return toLong(ex.atomItem(qc, info)); } /** * Checks if the specified item is a number. * Returns a token representation or throws an exception. * @param it item to be checked * @return number * @throws QueryException query exception */ protected final long toLong(final Item it) throws QueryException { final Type ip = checkNoEmpty(it, AtomType.ITR).type; if(ip.instanceOf(AtomType.ITR) || ip.isUntyped()) return it.itr(info); throw castError(it, AtomType.ITR, info); } /** * Checks if the specified expression yields a node. * Returns the boolean or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return node * @throws QueryException query exception */ protected final ANode toNode(final Expr ex, final QueryContext qc) throws QueryException { return toNode(checkNoEmpty(ex.item(qc, info), NodeType.NOD)); } /** * Checks if the specified expression yields a node or {@code null}. * Returns the node, {@code null}, or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return node or {@code null} * @throws QueryException query exception */ protected final ANode toEmptyNode(final Expr ex, final QueryContext qc) throws QueryException { final Item it = ex.item(qc, info); return it == null ? null : toNode(it); } /** * Checks if the specified non-empty item is a node. * Returns the node or throws an exception. * @param it item to be checked * @return node * @throws QueryException query exception */ protected final ANode toNode(final Item it) throws QueryException { if(it instanceof ANode) return (ANode) it; throw castError(it, NodeType.NOD, info); } /** * Checks if the specified item is a node or {@code null}. * Returns the node, {@code null}, or throws an exception. * @param it item to be checked * @return node or {@code null} * @throws QueryException query exception */ final ANode toEmptyNode(final Item it) throws QueryException { return it == null ? null : toNode(it); } /** * Checks if the evaluated expression yields a node or item. * Returns the item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return node or atomized item * @throws QueryException query exception */ protected final Item toNodeOrAtomItem(final Expr ex, final QueryContext qc) throws QueryException { return toNodeOrAtomItem(toItem(ex, qc)); } /** * Checks if the specified item yields a node or item. * Returns the item or throws an exception. * @param it item to be checked (can be {@code null}) * @return node or atomized item * @throws QueryException query exception */ protected final Item toNodeOrAtomItem(final Item it) throws QueryException { return it == null || it instanceof ANode ? it : it.atomItem(info); } /** * Checks if the evaluated expression yields a non-empty item. * Returns the item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return item * @throws QueryException query exception */ protected final Item toItem(final Expr ex, final QueryContext qc) throws QueryException { return checkNoEmpty(ex.item(qc, info)); } /** * Checks if the specified expression yields a non-empty item. * Returns the item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @param type expected type * @return item * @throws QueryException query exception */ private Item toItem(final Expr ex, final QueryContext qc, final Type type) throws QueryException { return checkNoEmpty(ex.item(qc, info), type); } /** * Checks if the evaluated expression yields a non-empty item. * Returns the atomized item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return atomized item * @throws QueryException query exception */ protected final Item toAtomItem(final Expr ex, final QueryContext qc) throws QueryException { return checkNoEmpty(ex.atomItem(qc, info)); } /** * Checks if the specified expression yields an element. * Returns the element or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return binary item * @throws QueryException query exception */ protected final ANode toElem(final Expr ex, final QueryContext qc) throws QueryException { return (ANode) checkType(ex.item(qc, info), NodeType.ELM); } /** * Checks if the specified expression yields a binary item. * Returns the binary item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return binary item * @throws QueryException query exception */ protected final Bin toBin(final Expr ex, final QueryContext qc) throws QueryException { return toBin(ex.atomItem(qc, info)); } /** * Checks if the specified item is a binary item. * Returns the binary item or throws an exception. * @param it item to be checked * @return binary item * @throws QueryException query exception */ protected Bin toBin(final Item it) throws QueryException { if(checkNoEmpty(it) instanceof Bin) return (Bin) it; throw BINARY_X.get(info, it.type); } /** * Checks if the specified expression yields a string or binary item. * @param ex expression to be evaluated * @param qc query context * @return byte array * @throws QueryException query exception */ protected final byte[] toBytes(final Expr ex, final QueryContext qc) throws QueryException { return toBytes(ex.atomItem(qc, info)); } /** * Checks if the specified expression yields a Base64 item. * Returns the item or throws an exception. * @param empty allow empty result * @param ex expression to be evaluated * @param qc query context * @return Bas64 item * @throws QueryException query exception */ protected final B64 toB64(final Expr ex, final QueryContext qc, final boolean empty) throws QueryException { return toB64(ex.atomItem(qc, info), empty); } /** * Checks if the specified item is a Base64 item. * Returns the item or throws an exception. * @param empty allow empty result * @param it item * @return Bas64 item * @throws QueryException query exception */ protected final B64 toB64(final Item it, final boolean empty) throws QueryException { if(empty && it == null) return null; return (B64) checkType(it, AtomType.B64); } /** * Checks if the specified item is a string or binary item. * @param it item to be checked * @return byte array * @throws QueryException query exception */ protected final byte[] toBytes(final Item it) throws QueryException { if(checkNoEmpty(it).type.isStringOrUntyped()) return it.string(info); if(it instanceof Bin) return ((Bin) it).binary(info); throw STRBIN_X_X.get(info, it.type, it); } /** * Checks if the specified expression yields a QName. * Returns the item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @param empty allow empty result * @return QNm item * @throws QueryException query exception */ protected final QNm toQNm(final Expr ex, final QueryContext qc, final boolean empty) throws QueryException { return toQNm(ex.atomItem(qc, info), empty); } /** * Checks if the specified item is a QName. * Returns the item or throws an exception. * @param it item * @param empty allow empty result * @return QNm item * @throws QueryException query exception */ protected final QNm toQNm(final Item it, final boolean empty) throws QueryException { if(empty && it == null) return null; final Type ip = checkNoEmpty(it, AtomType.QNM).type; if(ip == AtomType.QNM) return (QNm) it; if(ip.isUntyped()) throw NSSENS_X_X.get(info, ip, AtomType.QNM); throw castError(it, AtomType.QNM, info); } /** * Checks if the specified expression yields a function. * Returns the function or throws an exception. * @param ex expression to be evaluated * @param qc query context * @return function item * @throws QueryException query exception */ protected FItem toFunc(final Expr ex, final QueryContext qc) throws QueryException { return (FItem) checkType(toItem(ex, qc, SeqType.ANY_FUN), SeqType.ANY_FUN); } /** * Checks if the specified expression yields a map. * Returns the map or throws an exception. * @param ex expression * @param qc query context * @return map * @throws QueryException query exception */ protected Map toMap(final Expr ex, final QueryContext qc) throws QueryException { return toMap(toItem(ex, qc, SeqType.ANY_MAP)); } /** * Checks if the specified item is a map. * Returns the map or throws an exception. * @param it item to check * @return the map * @throws QueryException if the item is not a map */ protected Map toMap(final Item it) throws QueryException { if(it instanceof Map) return (Map) it; throw castError(it, SeqType.ANY_MAP, info); } /** * Checks if the specified expression yields an array. * @param e expression * @param qc query context * @return array * @throws QueryException query exception */ protected Array toArray(final Expr e, final QueryContext qc) throws QueryException { return toArray(toItem(e, qc, SeqType.ANY_ARRAY)); } /** * Assures that the specified item item is an array. * @param it item to check * @return the array * @throws QueryException if the item is not an array */ protected Array toArray(final Item it) throws QueryException { if(it instanceof Array) return (Array) it; throw castError(it, SeqType.ANY_ARRAY, info); } /** * Checks if the specified expression yields an item of the specified atomic type. * Returns the item or throws an exception. * @param ex expression to be evaluated * @param qc query context * @param type type to be checked * @return item * @throws QueryException query exception */ protected Item checkAtomic(final Expr ex, final QueryContext qc, final Type type) throws QueryException { return checkType(ex.atomItem(qc, info), type); } /** * Checks if the specified expression is an empty sequence; if yes, throws * an exception. * @param it item to be checked * @param type type to be checked * @return specified item * @throws QueryException query exception */ protected Item checkType(final Item it, final Type type) throws QueryException { if(checkNoEmpty(it, type).type.instanceOf(type)) return it; throw castError(it, type, info); } /** * Checks if the specified item is no empty sequence. * @param it item to be checked * @return specified item * @throws QueryException query exception */ protected final Item checkNoEmpty(final Item it) throws QueryException { if(it != null) return it; throw EMPTYFOUND.get(info); } /** * Checks if the specified item is no empty sequence. * @param it item to be checked * @param type expected type * @return specified item * @throws QueryException query exception */ protected Item checkNoEmpty(final Item it, final Type type) throws QueryException { if(it != null) return it; throw EMPTYFOUND_X.get(info, type); } }
3e046c7789d7d983fabd5864145d513122eefd17
1,741
java
Java
presto-proxy/src/test/java/io/prestosql/proxy/TestProxyConfig.java
rzeyde-varada/prestodb
3a3d33271e98d315940d06dc7fbe38d6a4912f51
[ "Apache-2.0" ]
476
2020-06-30T14:24:39.000Z
2022-03-29T13:13:33.000Z
presto-proxy/src/test/java/io/prestosql/proxy/TestProxyConfig.java
rzeyde-varada/prestodb
3a3d33271e98d315940d06dc7fbe38d6a4912f51
[ "Apache-2.0" ]
316
2020-06-30T11:44:52.000Z
2022-03-30T11:08:04.000Z
presto-proxy/src/test/java/io/prestosql/proxy/TestProxyConfig.java
rzeyde-varada/prestodb
3a3d33271e98d315940d06dc7fbe38d6a4912f51
[ "Apache-2.0" ]
326
2020-06-30T11:40:14.000Z
2022-03-31T07:55:03.000Z
33.480769
87
0.699024
1,856
/* * 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.prestosql.proxy; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import java.io.File; import java.net.URI; import java.util.Map; import static io.airlift.configuration.testing.ConfigAssertions.assertFullMapping; import static io.airlift.configuration.testing.ConfigAssertions.assertRecordedDefaults; import static io.airlift.configuration.testing.ConfigAssertions.recordDefaults; public class TestProxyConfig { @Test public void testDefaults() { assertRecordedDefaults(recordDefaults(ProxyConfig.class) .setUri(null) .setSharedSecretFile(null)); } @Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("proxy.uri", "http://example.net/") .put("proxy.shared-secret-file", "test.secret") .build(); ProxyConfig expected = new ProxyConfig() .setUri(URI.create("http://example.net/")) .setSharedSecretFile(new File("test.secret")); assertFullMapping(properties, expected); } }
3e046c9daeef45510abdb09346847148fb0fc4ee
407
java
Java
album/src/main/java/com/yanzhenjie/album/impl/OnCheckedClickListener.java
Hsicen/Album
987c2d0339346caf651f98dec906516074527bf9
[ "Apache-2.0" ]
1
2021-03-06T11:31:54.000Z
2021-03-06T11:31:54.000Z
album/src/main/java/com/yanzhenjie/album/impl/OnCheckedClickListener.java
Hsicen/Album
987c2d0339346caf651f98dec906516074527bf9
[ "Apache-2.0" ]
null
null
null
album/src/main/java/com/yanzhenjie/album/impl/OnCheckedClickListener.java
Hsicen/Album
987c2d0339346caf651f98dec906516074527bf9
[ "Apache-2.0" ]
2
2020-07-08T07:15:18.000Z
2020-08-24T07:05:45.000Z
20.7
61
0.657005
1,857
package com.yanzhenjie.album.impl; import android.widget.CompoundButton; /** * <p>作者:hsicen 2019/11/7 15:08 * <[email protected] * <p>功能: * <p>描述:选择框点击监听 */ public interface OnCheckedClickListener { /** * Compound button is clicked. * * @param button view. * @param position the position in the list. */ void onCheckedClick(CompoundButton button, int position); }
3e046d88315eb0b53b5f89513b2f3207bd21e232
724
java
Java
storage/src/main/java/io/atomix/storage/statistics/package-info.java
sullis/atomix
842276c02541267a61bca47f82c2e9d740245fcb
[ "Apache-2.0" ]
2,027
2015-09-29T05:30:54.000Z
2022-03-31T07:49:24.000Z
storage/src/main/java/io/atomix/storage/statistics/package-info.java
sullis/atomix
842276c02541267a61bca47f82c2e9d740245fcb
[ "Apache-2.0" ]
641
2015-10-20T08:57:16.000Z
2022-02-10T16:42:03.000Z
storage/src/main/java/io/atomix/storage/statistics/package-info.java
sullis/atomix
842276c02541267a61bca47f82c2e9d740245fcb
[ "Apache-2.0" ]
394
2015-10-12T23:02:30.000Z
2022-03-23T16:39:58.000Z
34.47619
75
0.751381
1,858
/* * Copyright 2018-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Provides utilities for querying system storage information. */ package io.atomix.storage.statistics;
3e046da11ed5f806ab196e6eac2de416cdc11660
117
java
Java
app/src/main/java/com/example/administrator/coolweather/BaseView.java
YangRT/coolweather
799bed20835c898a5e66e7745f498dd90920454c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/administrator/coolweather/BaseView.java
YangRT/coolweather
799bed20835c898a5e66e7745f498dd90920454c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/administrator/coolweather/BaseView.java
YangRT/coolweather
799bed20835c898a5e66e7745f498dd90920454c
[ "Apache-2.0" ]
null
null
null
19.5
46
0.777778
1,859
package com.example.administrator.coolweather; public interface BaseView<T> { void setPresenter(T presenter); }
3e046dcf990d19c0af557fb9c3a6fd55e5cc08f4
769
java
Java
jaxws-ri/tests/unit-rearch/src/client/dispatch/xmlhttp/client/AllTests.java
eheeren/metro-jax-ws
16810e6f6a3dad5c4c4ef08fd76130a68dc08fea
[ "BSD-3-Clause" ]
40
2018-10-05T10:39:25.000Z
2022-03-31T07:27:39.000Z
jaxws-ri/tests/unit-rearch/src/client/dispatch/xmlhttp/client/AllTests.java
eheeren/metro-jax-ws
16810e6f6a3dad5c4c4ef08fd76130a68dc08fea
[ "BSD-3-Clause" ]
98
2018-10-18T12:20:48.000Z
2022-03-26T13:43:10.000Z
jaxws-ri/tests/unit-rearch/src/client/dispatch/xmlhttp/client/AllTests.java
eheeren/metro-jax-ws
16810e6f6a3dad5c4c4ef08fd76130a68dc08fea
[ "BSD-3-Clause" ]
40
2018-10-17T20:43:51.000Z
2022-03-10T18:01:31.000Z
24.03125
78
0.697009
1,860
/* * Copyright (c) 2004, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package client.dispatch.xmlhttp.client; import junit.framework.*; import client.dispatch.xmlhttp.client.XMLHttpClient; /** * * @author JAX-RPC RI Development Team */ public class AllTests extends TestCase { public AllTests(String name) { super(name); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(XMLHttpClient.class); return suite; } }
3e046e5aa58d0e4d95fa41867ff3c15df0f7328e
3,350
java
Java
core/index/src/main/java/mil/nga/giat/geowave/core/index/PartitionIndexStrategyWrapper.java
cjw5db/geowave
3cf39ecb94263f60021641bc91f95f9a9d9c3c16
[ "Apache-2.0" ]
null
null
null
core/index/src/main/java/mil/nga/giat/geowave/core/index/PartitionIndexStrategyWrapper.java
cjw5db/geowave
3cf39ecb94263f60021641bc91f95f9a9d9c3c16
[ "Apache-2.0" ]
null
null
null
core/index/src/main/java/mil/nga/giat/geowave/core/index/PartitionIndexStrategyWrapper.java
cjw5db/geowave
3cf39ecb94263f60021641bc91f95f9a9d9c3c16
[ "Apache-2.0" ]
1
2021-09-01T08:48:07.000Z
2021-09-01T08:48:07.000Z
26.171875
126
0.795821
1,861
package mil.nga.giat.geowave.core.index; import java.util.List; import java.util.Set; import mil.nga.giat.geowave.core.index.dimension.NumericDimensionDefinition; import mil.nga.giat.geowave.core.index.persist.PersistenceUtils; import mil.nga.giat.geowave.core.index.sfc.data.MultiDimensionalNumericData; public class PartitionIndexStrategyWrapper implements NumericIndexStrategy { private PartitionIndexStrategy<MultiDimensionalNumericData, MultiDimensionalNumericData> partitionIndexStrategy; public PartitionIndexStrategyWrapper() {} public PartitionIndexStrategyWrapper( final PartitionIndexStrategy<MultiDimensionalNumericData, MultiDimensionalNumericData> partitionIndexStrategy ) { this.partitionIndexStrategy = partitionIndexStrategy; } @Override public QueryRanges getQueryRanges( final MultiDimensionalNumericData indexedRange, final IndexMetaData... hints ) { // TODO Auto-generated method stub return null; } @Override public QueryRanges getQueryRanges( final MultiDimensionalNumericData indexedRange, final int maxEstimatedRangeDecomposition, final IndexMetaData... hints ) { // TODO Auto-generated method stub return null; } @Override public InsertionIds getInsertionIds( final MultiDimensionalNumericData indexedData ) { // TODO Auto-generated method stub return null; } @Override public InsertionIds getInsertionIds( final MultiDimensionalNumericData indexedData, final int maxEstimatedDuplicateIds ) { // TODO Auto-generated method stub return null; } @Override public MultiDimensionalNumericData getRangeForId( final ByteArrayId partitionKey, final ByteArrayId sortKey ) { // TODO Auto-generated method stub return null; } @Override public String getId() { return partitionIndexStrategy.getId(); } @Override public List<IndexMetaData> createMetaData() { return partitionIndexStrategy.createMetaData(); } @Override public byte[] toBinary() { return PersistenceUtils.toBinary(partitionIndexStrategy); } @Override public void fromBinary( final byte[] bytes ) { partitionIndexStrategy = (PartitionIndexStrategy<MultiDimensionalNumericData, MultiDimensionalNumericData>) PersistenceUtils .fromBinary(bytes); } @Override public MultiDimensionalCoordinates getCoordinatesPerDimension( final ByteArrayId partitionKey, final ByteArrayId sortKey ) { return new MultiDimensionalCoordinates(); } @Override public MultiDimensionalCoordinateRanges[] getCoordinateRangesPerDimension( final MultiDimensionalNumericData dataRange, final IndexMetaData... hints ) { return null; } @Override public NumericDimensionDefinition[] getOrderedDimensionDefinitions() { return null; } @Override public double[] getHighestPrecisionIdRangePerDimension() { return null; } @Override public int getPartitionKeyLength() { return partitionIndexStrategy.getPartitionKeyLength(); } @Override public Set<ByteArrayId> getInsertionPartitionKeys( final MultiDimensionalNumericData insertionData ) { return partitionIndexStrategy.getInsertionPartitionKeys(insertionData); } @Override public Set<ByteArrayId> getQueryPartitionKeys( final MultiDimensionalNumericData queryData, final IndexMetaData... hints ) { return partitionIndexStrategy.getQueryPartitionKeys( queryData, hints); } }
3e046e6d8120c6b1abf11d2dcdbcb127b1a0e9d6
2,110
java
Java
src/main/java/uk/ac/uea/cmp/srnaworkbench/io/externalops/StringSizeEstimator.java
sRNAworkbenchuea/UEA_sRNA_Workbench
b6e0c54f6e9ebc27fd700aa1c5aaa4e184339e65
[ "MIT" ]
7
2018-05-06T00:25:54.000Z
2022-03-16T16:14:39.000Z
src/main/java/uk/ac/uea/cmp/srnaworkbench/io/externalops/StringSizeEstimator.java
yinyunqian/UEA_sRNA_Workbench
b6e0c54f6e9ebc27fd700aa1c5aaa4e184339e65
[ "MIT" ]
11
2018-09-18T14:18:05.000Z
2022-01-28T05:39:51.000Z
src/main/java/uk/ac/uea/cmp/srnaworkbench/io/externalops/StringSizeEstimator.java
yinyunqian/UEA_sRNA_Workbench
b6e0c54f6e9ebc27fd700aa1c5aaa4e184339e65
[ "MIT" ]
3
2019-01-09T08:49:24.000Z
2022-02-23T08:21:09.000Z
29.305556
88
0.704265
1,862
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package uk.ac.uea.cmp.srnaworkbench.io.externalops; /** * @author Eleftherios Chetzakis * */ public final class StringSizeEstimator { private static int OBJ_HEADER; private static int ARR_HEADER; private static int INT_FIELDS = 12; private static int OBJ_REF; private static int OBJ_OVERHEAD; private static boolean IS_64_BIT_JVM; /** * Private constructor to prevent instantiation. */ private StringSizeEstimator() { } /** * Class initializations. */ static { // By default we assume 64 bit JVM // (defensive approach since we will get // larger estimations in case we are not sure) IS_64_BIT_JVM = true; // check the system property "sun.arch.data.model" // not very safe, as it might not work for all JVM implementations // nevertheless the worst thing that might happen is that the JVM is 32bit // but we assume its 64bit, so we will be counting a few extra bytes per string object // no harm done here since this is just an approximation. String arch = System.getProperty("sun.arch.data.model"); if (arch != null) { if (arch.indexOf("32") != -1) { // If exists and is 32 bit then we assume a 32bit JVM IS_64_BIT_JVM = false; } } // The sizes below are a bit rough as we don't take into account // advanced JVM options such as compressed oops // however if our calculation is not accurate it'll be a bit over // so there is no danger of an out of memory error because of this. OBJ_HEADER = IS_64_BIT_JVM ? 16 : 8; ARR_HEADER = IS_64_BIT_JVM ? 24 : 12; OBJ_REF = IS_64_BIT_JVM ? 8 : 4; OBJ_OVERHEAD = OBJ_HEADER + INT_FIELDS + OBJ_REF + ARR_HEADER; } /** * Estimates the size of a {@link String} object in bytes. * * @param s The string to estimate memory footprint. * @return The <strong>estimated</strong> size in bytes. */ public static long estimatedSizeOf(String s) { return (s.length() * 2) + OBJ_OVERHEAD; } }
3e046fff5440fbdf8c6ef99ebcc0503461cbcc78
9,992
java
Java
src/java/voldemort/client/MockStoreClientFactory.java
tellapart/voldemort
d92829d8cac3af437d049908a84632fb076c1891
[ "Apache-2.0" ]
1,379
2015-01-02T23:56:28.000Z
2022-03-29T08:02:39.000Z
src/java/voldemort/client/MockStoreClientFactory.java
harshsaver/voldemort
3524d2b02ce217838d4ae3809a42ef95cb470a05
[ "Apache-2.0" ]
235
2015-01-03T09:55:27.000Z
2022-01-21T03:21:02.000Z
src/java/voldemort/client/MockStoreClientFactory.java
harshsaver/voldemort
3524d2b02ce217838d4ae3809a42ef95cb470a05
[ "Apache-2.0" ]
316
2015-01-02T12:47:41.000Z
2022-03-25T08:11:16.000Z
47.808612
162
0.591873
1,863
/* * Copyright 2008-2009 LinkedIn, 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 voldemort.client; import java.io.StringReader; import java.util.List; import voldemort.cluster.failuredetector.FailureDetector; import voldemort.cluster.failuredetector.NoopFailureDetector; import voldemort.serialization.DefaultSerializerFactory; import voldemort.serialization.Serializer; import voldemort.store.StorageEngine; import voldemort.store.Store; import voldemort.store.StoreDefinition; import voldemort.store.StoreUtils; import voldemort.store.memory.InMemoryStorageEngine; import voldemort.store.serialized.SerializingStore; import voldemort.store.versioned.InconsistencyResolvingStore; import voldemort.store.versioned.VersionIncrementingStore; import voldemort.store.views.ViewStorageConfiguration; import voldemort.store.views.ViewStorageEngine; import voldemort.utils.SystemTime; import voldemort.utils.Time; import voldemort.versioning.ChainedResolver; import voldemort.versioning.InconsistencyResolver; import voldemort.versioning.TimeBasedInconsistencyResolver; import voldemort.versioning.VectorClockInconsistencyResolver; import voldemort.versioning.Versioned; import voldemort.xml.StoreDefinitionsMapper; /** * A store client that produces non-persistent, in-memory stores. This is useful * for unit testing. * * */ @SuppressWarnings("unchecked") public class MockStoreClientFactory implements StoreClientFactory { private final int nodeId; private final Serializer<?> keySerializer; private final Serializer<?> valueSerializer; private final Serializer<?> viewValueSerializer; private final Serializer<?> transformsSerializer; private final Time time; private final FailureDetector failureDetector; private static final StoreDefinitionsMapper storeMapper = new StoreDefinitionsMapper(); private String storesXml; public MockStoreClientFactory(Serializer<?> keySerializer, Serializer<?> valueSerializer, Serializer<?> transformsSerializer) { this(keySerializer, valueSerializer, null, transformsSerializer, 0, SystemTime.INSTANCE); } public MockStoreClientFactory(Serializer<?> keySerializer, Serializer<?> valueSerializer, Serializer<?> viewValueSerializer, Serializer<?> transformsSerializer, String storesXml) { this(keySerializer, valueSerializer, viewValueSerializer, transformsSerializer, 0, SystemTime.INSTANCE); this.storesXml = storesXml; } public MockStoreClientFactory(Serializer<?> keySerializer, Serializer<?> valueSerializer, Serializer<?> viewValueSerializer, Serializer<?> transformsSerializer, int nodeId, Time time) { this.nodeId = nodeId; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; this.viewValueSerializer = viewValueSerializer; this.transformsSerializer = transformsSerializer; this.time = time; failureDetector = new NoopFailureDetector(); } public <K, V> StoreClient<K, V> getStoreClient(String storeName) { return getStoreClient(storeName, new TimeBasedInconsistencyResolver<V>()); } public <K, V> StoreClient<K, V> getStoreClient(String storeName, InconsistencyResolver<Versioned<V>> resolver) { return new DefaultStoreClient(storeName, resolver, this, 3); } public <K1, V1, T1> Store<K1, V1, T1> getRawStore(String storeName, InconsistencyResolver<Versioned<V1>> resolver) { if(this.storesXml != null) return getRawStore(storeName); // Add inconsistency resolving decorator, using their inconsistency // resolver (if they gave us one) InconsistencyResolver<Versioned<V1>> secondaryResolver = new TimeBasedInconsistencyResolver(); if(resolver != null) secondaryResolver = resolver; Store store = new VersionIncrementingStore(new InMemoryStorageEngine(storeName), nodeId, time); if(isSerialized()) store = new SerializingStore(store, keySerializer, valueSerializer, transformsSerializer); Store<K1, V1, T1> consistentStore = new InconsistencyResolvingStore<K1, V1, T1>(store, new ChainedResolver<Versioned<V1>>(new VectorClockInconsistencyResolver(), secondaryResolver)); return consistentStore; } private <K1, V1, T1> Store<K1, V1, T1> getRawStore(String storeName) { List<StoreDefinition> storeDefs = storeMapper.readStoreList(new StringReader(storesXml)); StoreDefinition storeDef = null; for(StoreDefinition d: storeDefs) if(d.getName().equals(storeName)) storeDef = d; if(storeDef == null) throw new BootstrapFailureException("Unknown store '" + storeName + "'."); DefaultSerializerFactory serializerFactory = new DefaultSerializerFactory(); Serializer<K1> keySerializer = (Serializer<K1>) serializerFactory.getSerializer(storeDef.getKeySerializer()); Serializer<V1> valueSerializer = (Serializer<V1>) serializerFactory.getSerializer(storeDef.getValueSerializer()); Serializer<T1> transformsSerializer = null; if(storeDef.isView()) transformsSerializer = (Serializer<T1>) serializerFactory.getSerializer(storeDef.getTransformsSerializer()); // Add inconsistency resolving decorator, using their inconsistency // resolver (if they gave us one) InconsistencyResolver<Versioned<V1>> secondaryResolver = new TimeBasedInconsistencyResolver(); StorageEngine engine; if(storeDef.isView()) engine = new InMemoryStorageEngine(storeDef.getViewTargetStoreName()); else engine = new InMemoryStorageEngine(storeDef.getName()); if(storeDef.isView()) { // instantiate view String targetName = storeDef.getViewTargetStoreName(); StoreDefinition targetDef = StoreUtils.getStoreDef(storeDefs, targetName); engine = new ViewStorageEngine(storeName, engine, this.viewValueSerializer != null ? this.viewValueSerializer : serializerFactory.getSerializer(storeDef.getValueSerializer()), this.transformsSerializer != null ? this.transformsSerializer : serializerFactory.getSerializer(storeDef.getTransformsSerializer()), this.keySerializer != null ? this.keySerializer : serializerFactory.getSerializer(targetDef.getKeySerializer()), this.valueSerializer != null ? this.valueSerializer : serializerFactory.getSerializer(targetDef.getValueSerializer()), null, ViewStorageConfiguration.loadTransformation(storeDef.getValueTransformation())); } Store store = new VersionIncrementingStore(engine, nodeId, time); store = new SerializingStore(store, this.keySerializer != null ? this.keySerializer : keySerializer, this.valueSerializer != null ? this.valueSerializer : valueSerializer, this.transformsSerializer != null ? this.transformsSerializer : transformsSerializer); Store<K1, V1, T1> consistentStore = new InconsistencyResolvingStore<K1, V1, T1>(store, new ChainedResolver<Versioned<V1>>(new VectorClockInconsistencyResolver(), secondaryResolver)); return consistentStore; } private boolean isSerialized() { return keySerializer != null && valueSerializer != null; } public void close() { } public FailureDetector getFailureDetector() { return failureDetector; } }
3e0470171325855ead94632498eaef3bae163d53
879
java
Java
alink_core/src/main/java/com/alibaba/alink/streamoperator/recommendation/AlsPredictStreamOp.java
yangsishu/Alink
ee9bcca382d244b1473fc6d1772646928034be84
[ "Apache-2.0" ]
1
2019-04-29T12:39:28.000Z
2019-04-29T12:39:28.000Z
alink_core/src/main/java/com/alibaba/alink/streamoperator/recommendation/AlsPredictStreamOp.java
tomzhang/Alink
ee9bcca382d244b1473fc6d1772646928034be84
[ "Apache-2.0" ]
null
null
null
alink_core/src/main/java/com/alibaba/alink/streamoperator/recommendation/AlsPredictStreamOp.java
tomzhang/Alink
ee9bcca382d244b1473fc6d1772646928034be84
[ "Apache-2.0" ]
1
2019-01-22T09:21:03.000Z
2019-01-22T09:21:03.000Z
38.217391
91
0.780432
1,864
package com.alibaba.alink.streamoperator.recommendation; import com.alibaba.alink.common.AlinkParameter; import com.alibaba.alink.batchoperator.BatchOperator; import com.alibaba.alink.common.recommendation.ALSRatingModelPredictor; import com.alibaba.alink.common.recommendation.ALSTopKModelPredictor; import com.alibaba.alink.streamoperator.utils.AlinkPredictStreamOp; /** * input parameters: * -# task: optional, "rating" or "topk", default "topk", should agree with trainBatch * -# predResultColName: required * -# keepColNames: optional * */ public class AlsPredictStreamOp extends AlinkPredictStreamOp { public AlsPredictStreamOp(BatchOperator model, AlinkParameter params) { super(model, params.getStringOrDefault("task", "topk").equalsIgnoreCase("rating") ? ALSRatingModelPredictor.class : ALSTopKModelPredictor.class, params); } }
3e04710cbc4734ed02dc4501bc9c6e4300d800c6
1,485
java
Java
src/main/java/com/lihui/study/thread/Demo05.java
lihui02/design_pattern_study
ae4b9f1565523c9840112b4d403fcb165b5db31e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lihui/study/thread/Demo05.java
lihui02/design_pattern_study
ae4b9f1565523c9840112b4d403fcb165b5db31e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lihui/study/thread/Demo05.java
lihui02/design_pattern_study
ae4b9f1565523c9840112b4d403fcb165b5db31e
[ "Apache-2.0" ]
null
null
null
23.951613
52
0.437037
1,865
package com.lihui.study.thread; /** * 一个线程的生产者与一个线程的消费者(多线程有问题,你notify的时候,生产者和消费者都唤醒了 * 消费者1消费完了唤醒了消费者2(实际上需要唤醒生产者),由于没有生产者生产,消费者2也wait了, * 这样所有的生产者和消费者2都wait了,没有其他线程去唤醒他们了 * */ public class Demo05 { private volatile int i; private volatile boolean isProduce = false; public static void main(String[] args) { Demo05 demo05=new Demo05(); Thread t1=new Thread(()->{ while (true){ demo05.produce(); } }); Thread t2=new Thread(()->{ while (true){ demo05.consumer(); } }); t1.start(); t2.start(); } private void produce(){ synchronized (this){ if (!isProduce){ System.out.println("P-->>"+(++i)); isProduce=true; this.notify(); }else { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } private void consumer(){ synchronized (this){ if (isProduce){ System.out.println("C-->>"+i); isProduce=false; this.notify(); }else { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
3e047135dfc597aa887109627855232d525dd6d6
4,459
java
Java
icu4j/samples/src/com/ibm/icu/samples/text/pluralformat/PluralFormatSample.java
ionsphere/icu-cmake
ba3750c592a4f221da9bb80b9145d09f21279adc
[ "Apache-2.0" ]
null
null
null
icu4j/samples/src/com/ibm/icu/samples/text/pluralformat/PluralFormatSample.java
ionsphere/icu-cmake
ba3750c592a4f221da9bb80b9145d09f21279adc
[ "Apache-2.0" ]
null
null
null
icu4j/samples/src/com/ibm/icu/samples/text/pluralformat/PluralFormatSample.java
ionsphere/icu-cmake
ba3750c592a4f221da9bb80b9145d09f21279adc
[ "Apache-2.0" ]
null
null
null
45.969072
116
0.531509
1,866
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* ******************************************************************************* * Copyright (C) 2013-2014, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.samples.text.pluralformat; // ---PluralFormatExample import java.text.FieldPosition; import com.ibm.icu.text.MessageFormat; import com.ibm.icu.text.PluralFormat; import com.ibm.icu.util.ULocale; // ---PluralFormatExample public class PluralFormatSample { public static void main(String[] args) { PluralFormatExample(); } private static void PluralFormatExample(){ System.out.println("======================================================================================="); System.out.println(" PluralFormatExample()"); System.out.println(); System.out.println(" Use PluralFormat and Messageformat to get appropriate Plural Form for languages below:"); System.out.println(" English, Slovenian"); System.out.println("======================================================================================="); // ---PluralFormatExample ULocale locEn = new ULocale("en"); ULocale locSl = new ULocale("sl"); String patEn = "one{dog} other{dogs}"; // English 'dog' String patSl = "one{pes} two{psa} few{psi} other{psov}"; // Slovenian translation of dog in Plural Form // Create a new PluralFormat for a given locale locale and pattern string PluralFormat plfmtEn = new PluralFormat(locEn, patEn); PluralFormat plfmtSl = new PluralFormat(locSl, patSl); // Constructs a MessageFormat for the specified locale and pattern. MessageFormat msgfmtEn = new MessageFormat("{0,number} {1}", locEn); MessageFormat msgfmtSl = new MessageFormat("{0,number} {1}", locSl); final int[] numbers = {0, 1, 2, 3, 4, 5, 10, 100, 101, 102}; System.out.println("Output by using PluralFormat and MessageFormat API\n"); System.out.printf("%-16s%-16s%-16s\n", "Number", "English", "Slovenian"); // Use MessageFormat.format () to format the objects and appends to the given StringBuffer for (int num : numbers) { StringBuffer msgEn = new StringBuffer(); StringBuffer msgSl = new StringBuffer(); msgfmtEn.format(new Object[] {num, plfmtEn.format(num)}, msgEn, new FieldPosition(0)); msgfmtSl.format(new Object[] {num, plfmtSl.format(num)}, msgSl, new FieldPosition(0)); System.out.printf("%-16s%-16s%-16s\n", num, msgEn, msgSl); } System.out.println(); // Equivalent code with message format pattern String msgPatEn = "{0,plural, one{# dog} other{# dogs}}"; String msgPatSl = "{0,plural, one{# pes} two{# psa} few{# psi} other{# psov}}"; MessageFormat altMsgfmtEn = new MessageFormat(msgPatEn, locEn); MessageFormat altMsgfmtSl = new MessageFormat(msgPatSl, locSl); System.out.println("Same Output by using MessageFormat API only\n"); System.out.printf("%-16s%-16s%-16s\n", "Number", "English", "Slovenian"); for (int num : numbers) { StringBuffer msgEn = new StringBuffer(); StringBuffer msgSl = new StringBuffer(); altMsgfmtEn.format(new Object[] {num}, msgEn, new FieldPosition(0)); altMsgfmtSl.format(new Object[] {num}, msgSl, new FieldPosition(0)); System.out.printf("%-16s%-16s%-16s\n", num, msgEn, msgSl); } /** output of the sample code: ******************************************************************** Number English Slovenian 0 0 dogs 0 psov 1 1 dog 1 pes 2 2 dogs 2 psa 3 3 dogs 3 psi 4 4 dogs 4 psi 5 5 dogs 5 psov 10 10 dogs 10 psov 100 100 dogs 100 psov 101 101 dogs 101 pes 102 102 dogs 102 psa *******************************************************************/ // ---PluralFormatExample } }
3e0471f85e9347d0e49ad730fbfdf966cffdea80
432
java
Java
spring-boot-react-cors-cross-origin-csrf/backend-spring-boot-react-cors-cross-origin-csrf/src/main/java/com/in28minutes/fullstack/springboot/rest/api/springbootcorscrossorigincsrf/SpringBootFullStackCorsCrossOriginCsrfApplication.java
hpulicherla/Harish
98d1ac1c96fe5f6d239b10e629c08013f087951b
[ "MIT" ]
245
2019-03-27T14:36:04.000Z
2022-03-18T09:07:57.000Z
spring-boot-react-cors-cross-origin-csrf/backend-spring-boot-react-cors-cross-origin-csrf/src/main/java/com/in28minutes/fullstack/springboot/rest/api/springbootcorscrossorigincsrf/SpringBootFullStackCorsCrossOriginCsrfApplication.java
sbetsabe/spring-boot-react-fullstack-examples
99836f3c5c709bbc901a3c762399cded6371db47
[ "MIT" ]
10
2019-08-13T07:01:22.000Z
2022-02-27T21:08:48.000Z
spring-boot-react-cors-cross-origin-csrf/backend-spring-boot-react-cors-cross-origin-csrf/src/main/java/com/in28minutes/fullstack/springboot/rest/api/springbootcorscrossorigincsrf/SpringBootFullStackCorsCrossOriginCsrfApplication.java
sbetsabe/spring-boot-react-fullstack-examples
99836f3c5c709bbc901a3c762399cded6371db47
[ "MIT" ]
514
2019-03-29T07:04:17.000Z
2022-03-12T14:45:59.000Z
30.857143
87
0.861111
1,867
package com.in28minutes.fullstack.springboot.rest.api.springbootcorscrossorigincsrf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootFullStackCorsCrossOriginCsrfApplication { public static void main(String[] args) { SpringApplication.run(SpringBootFullStackCorsCrossOriginCsrfApplication.class, args); } }
3e0471fea97cb597981ad5d5b66b15e2c2d02e29
6,419
java
Java
EulerProject/src/andy/EulerProjectAns/Problem013.java
KenShumKL/Andy-ITClass
a006dd056c20a720ef2e261574eba4e23c3f3291
[ "MIT" ]
null
null
null
EulerProject/src/andy/EulerProjectAns/Problem013.java
KenShumKL/Andy-ITClass
a006dd056c20a720ef2e261574eba4e23c3f3291
[ "MIT" ]
null
null
null
EulerProject/src/andy/EulerProjectAns/Problem013.java
KenShumKL/Andy-ITClass
a006dd056c20a720ef2e261574eba4e23c3f3291
[ "MIT" ]
null
null
null
45.524823
57
0.838604
1,868
package andy.EulerProjectAns; import java.math.BigInteger; /** * * @author Andy *Very difficult. */ //Large sum public class Problem013 { public static void main(String[] args) { final String[] nums = { "37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538", "74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250", "23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757", "28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318", "47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951", "62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178", "92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828", "80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586", "86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938", "54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145", "36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045", "17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692", "51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691", "15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126", "18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954", "78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984", "48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332", "59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085", "41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375", "35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275", "88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526", "36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141", "91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470", "23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470", "63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822", "95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236", "37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522", "29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715", "38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539", "40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903", "41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457", "23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672", "11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581", "97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327", "55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886", "75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731", "32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622", "73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818", "97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090", "10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039", "62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411", "60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096", "66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252", "16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791", "78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078", "40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535", "41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280", "82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197", "77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516", "20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690" }; String answer = ""; BigInteger sum; sum = BigInteger.ZERO; // Initialize the value for (String num: nums) { sum = sum.add(new BigInteger(num)); } /*OR*/ sum = BigInteger.ZERO; // Initialize the value for (int i=0; i<nums.length; i++) { sum = sum.add(new BigInteger(nums[i])); } answer = sum.toString().substring(0, 10); System.out.println(answer); } }
3e0472f27e306aa49a6bbb57df7b518a23f18f33
1,523
java
Java
jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java
samakovuluk/olingo-jpa-processor-v4
f8535bb8767d6b6dc13ca4974541ae080c72a796
[ "Apache-2.0" ]
1
2019-06-20T11:01:26.000Z
2019-06-20T11:01:26.000Z
jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java
samakovuluk/olingo-jpa-processor-v4
f8535bb8767d6b6dc13ca4974541ae080c72a796
[ "Apache-2.0" ]
null
null
null
jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java
samakovuluk/olingo-jpa-processor-v4
f8535bb8767d6b6dc13ca4974541ae080c72a796
[ "Apache-2.0" ]
null
null
null
37.146341
97
0.760341
1,869
package com.sap.olingo.jpa.processor.core.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.junit.jupiter.api.BeforeAll; import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; public class TestBase { protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; public static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" }; protected static EntityManagerFactory emf; protected TestHelper helper; protected Map<String, List<String>> headers; protected static JPAEdmNameBuilder nameBuilder; protected static DataSource ds; @BeforeAll public static void setupClass() throws ODataJPAModelException { ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_DERBY); emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); } protected void createHeaders() { headers = new HashMap<>(); List<String> languageHeaders = new ArrayList<>(); languageHeaders.add("de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); headers.put("accept-language", languageHeaders); } }
3e04730c7fafd02b4136d0ba06e80e00a353c8d2
1,084
java
Java
bundle/jsky.app.ot/src/main/java/jsky/app/ot/tpe/TpeImageDisplayControl.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
13
2015-02-04T21:33:56.000Z
2020-04-10T01:37:41.000Z
bundle/jsky.app.ot/src/main/java/jsky/app/ot/tpe/TpeImageDisplayControl.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
1,169
2015-01-02T13:20:50.000Z
2022-03-21T12:01:59.000Z
bundle/jsky.app.ot/src/main/java/jsky/app/ot/tpe/TpeImageDisplayControl.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
13
2015-04-07T18:01:55.000Z
2021-02-03T12:57:58.000Z
27.1
92
0.706642
1,870
package jsky.app.ot.tpe; import java.awt.*; import jsky.image.gui.ImageDisplayControl; import jsky.image.gui.ImageDisplayStatusPanel; import jsky.image.gui.DivaMainImageDisplay; /** * Extends the NavigatorImageDisplayControl class by adding Gemini specific features. * * @version $Revision: 39998 $ * @author Allan Brighton */ public class TpeImageDisplayControl extends ImageDisplayControl { /** * Construct a TpeImageDisplayControl widget. * * @param parent the top level parent frame (or internal frame) used to close the window * @param size the size (width, height) to use for the pan and zoom windows. */ TpeImageDisplayControl(Component parent, int size) { super(parent, size); } /** Make and return the image display window */ @Override protected TpeImageWidget makeImageDisplay() { return new TpeImageWidget(parent); } /** Make and return the status panel */ @Override protected ImageDisplayStatusPanel makeStatusPanel() { return new TpeImageDisplayStatusPanel(); } }
3e04731c7fd74b89e95aafb70f8fcf7330b7daf7
1,385
java
Java
excelium-model/src/main/java/excelium/model/test/TestCase.java
PhungDucKien/excelium
c7febe06209c212f8ad5c40bb53c9d0eeba3a8f1
[ "MIT" ]
5
2018-03-24T23:44:00.000Z
2018-04-27T15:12:35.000Z
excelium-model/src/main/java/excelium/model/test/TestCase.java
PhungDucKien/excelium
c7febe06209c212f8ad5c40bb53c9d0eeba3a8f1
[ "MIT" ]
22
2019-12-19T06:56:24.000Z
2022-02-27T00:24:56.000Z
excelium-model/src/main/java/excelium/model/test/TestCase.java
PhungDucKien/excelium
c7febe06209c212f8ad5c40bb53c9d0eeba3a8f1
[ "MIT" ]
null
null
null
36.447368
81
0.74657
1,871
/* * MIT License * * Copyright (c) 2018 Excelium * * 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 excelium.model.test; /** * Represents test case model. * A test case contains one or more test steps. * * @author PhungDucKien * @since 2018.03.30 */ public class TestCase extends TestFlow { public static final String ALL = "ALL"; }
3e047321050ff9b536a3cb9130dbabbcb4c39da1
730
java
Java
Hibernate & Spring Data/11. Exam/Exam03April2020/Airline_Skeleton/src/main/java/softuni/exam/models/dto/seed/xml/TownToTownDto.java
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
1
2019-07-21T13:00:31.000Z
2019-07-21T13:00:31.000Z
Hibernate & Spring Data/11. Exam/Exam03April2020/Airline_Skeleton/src/main/java/softuni/exam/models/dto/seed/xml/TownToTownDto.java
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
Hibernate & Spring Data/11. Exam/Exam03April2020/Airline_Skeleton/src/main/java/softuni/exam/models/dto/seed/xml/TownToTownDto.java
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
23.548387
52
0.738356
1,872
package softuni.exam.models.dto.seed.xml; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @XmlRootElement(name = "to-town") @XmlAccessorType(XmlAccessType.FIELD) public class TownToTownDto implements Serializable { @XmlElement private String name; public TownToTownDto() { } @NotNull @Length(min = 2) public String getName() { return name; } public void setName(String name) { this.name = name; } }
3e047350a10bd8767493936b1d60e416c2e4b4da
5,104
java
Java
cloudsim/src/main/java/org/cloudbus/cloudsim/VmAllocationPolicySimple.java
cypherskar/cloudsim
da3451f54b3669689e673015ec459337673f7601
[ "Apache-2.0" ]
null
null
null
cloudsim/src/main/java/org/cloudbus/cloudsim/VmAllocationPolicySimple.java
cypherskar/cloudsim
da3451f54b3669689e673015ec459337673f7601
[ "Apache-2.0" ]
null
null
null
cloudsim/src/main/java/org/cloudbus/cloudsim/VmAllocationPolicySimple.java
cypherskar/cloudsim
da3451f54b3669689e673015ec459337673f7601
[ "Apache-2.0" ]
null
null
null
24.189573
97
0.653017
1,873
/* * Title: CloudSim Toolkit * Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds * Licence: GPL - http://www.gnu.org/copyleft/gpl.html * * Copyright (c) 2009-2012, The University of Melbourne, Australia */ package org.cloudbus.cloudsim; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.cloudbus.cloudsim.core.CloudSim; /** * VmAllocationPolicySimple is an VmAllocationPolicy that chooses, as the host for a VM, the host * with less PEs in use. It is therefore a Worst Fit policy, allocating VMs into the * host with most available PE. * * @author Rodrigo N. Calheiros * @author Anton Beloglazov * @since CloudSim Toolkit 1.0 */ public class VmAllocationPolicySimple extends VmAllocationPolicy { /** The map between each VM and its allocated host. * The map key is a VM UID and the value is the allocated host for that VM. */ private Map<String, Host> vmTable; /** The map between each VM and the number of Pes used. * The map key is a VM UID and the value is the number of used Pes for that VM. */ private Map<String, Integer> usedPes; /** The number of free Pes for each host from {@link #getHostList() }. */ private List<Integer> freePes; /** * Creates a new VmAllocationPolicySimple object. * * @param list the list of hosts * @pre $none * @post $none */ public VmAllocationPolicySimple(List<? extends Host> list) { super(list); setFreePes(new ArrayList<Integer>()); for (Host host : getHostList()) { getFreePes().add(host.getNumberOfPes()); } setVmTable(new HashMap<String, Host>()); setUsedPes(new HashMap<String, Integer>()); } /** * Allocates the host with less PEs in use for a given VM. * * @param vm {@inheritDoc} * @return {@inheritDoc} * @pre $none * @post $none */ @Override public boolean allocateHostForVm(Vm vm) { int requiredPes = vm.getNumberOfPes(); boolean result = false; int tries = 0; List<Integer> freePesTmp = new ArrayList<Integer>(); for (Integer freePes : getFreePes()) { freePesTmp.add(freePes); } if (!getVmTable().containsKey(vm.getUid())) { // if this vm was not created do {// we still trying until we find a host or until we try all of them int moreFree = Integer.MIN_VALUE; int idx = -1; // we want the host with less pes in use for (int i = 0; i < freePesTmp.size(); i++) { if (freePesTmp.get(i) > moreFree) { moreFree = freePesTmp.get(i); idx = i; } } Host host = getHostList().get(idx); result = host.vmCreate(vm); if (result) { // if vm were succesfully created in the host getVmTable().put(vm.getUid(), host); getUsedPes().put(vm.getUid(), requiredPes); getFreePes().set(idx, getFreePes().get(idx) - requiredPes); result = true; break; } else { freePesTmp.set(idx, Integer.MIN_VALUE); } tries++; } while (!result && tries < getFreePes().size()); } return result; } @Override public void deallocateHostForVm(Vm vm) { Host host = getVmTable().remove(vm.getUid()); int idx = getHostList().indexOf(host); int pes = getUsedPes().remove(vm.getUid()); if (host != null) { host.vmDestroy(vm); getFreePes().set(idx, getFreePes().get(idx) + pes); } } @Override public Host getHost(Vm vm) { return getVmTable().get(vm.getUid()); } @Override public Host getHost(int vmId, int userId) { return getVmTable().get(Vm.getUid(userId, vmId)); } /** * Gets the vm table. * * @return the vm table */ public Map<String, Host> getVmTable() { return vmTable; } /** * Sets the vm table. * * @param vmTable the vm table */ protected void setVmTable(Map<String, Host> vmTable) { this.vmTable = vmTable; } /** * Gets the used pes. * * @return the used pes */ protected Map<String, Integer> getUsedPes() { return usedPes; } /** * Sets the used pes. * * @param usedPes the used pes */ protected void setUsedPes(Map<String, Integer> usedPes) { this.usedPes = usedPes; } /** * Gets the free pes. * * @return the free pes */ protected List<Integer> getFreePes() { return freePes; } /** * Sets the free pes. * * @param freePes the new free pes */ protected void setFreePes(List<Integer> freePes) { this.freePes = freePes; } @Override public List<Map<String, Object>> optimizeAllocation(List<? extends Vm> vmList) { // TODO: the method isn't in fact implemented return null; } @Override public boolean allocateHostForVm(Vm vm, Host host) { if (host.vmCreate(vm)) { // if vm has been succesfully created in the host getVmTable().put(vm.getUid(), host); int requiredPes = vm.getNumberOfPes(); int idx = getHostList().indexOf(host); getUsedPes().put(vm.getUid(), requiredPes); getFreePes().set(idx, getFreePes().get(idx) - requiredPes); Log.formatLine( "%.2f: VM #" + vm.getId() + " has been allocated to the host #" + host.getId(), CloudSim.clock()); return true; } return false; } }
3e04747c39dd436322f6f09b8edf027b327d9e97
2,835
java
Java
src/main/java/com/google/devtools/build/lib/skyframe/StarlarkBuiltinsValue.java
gorakhargosh/bazel
243c94502dd2f5527ec05481535300f206d74828
[ "Apache-2.0" ]
4
2019-06-25T08:16:52.000Z
2022-01-12T11:35:49.000Z
src/main/java/com/google/devtools/build/lib/skyframe/StarlarkBuiltinsValue.java
gorakhargosh/bazel
243c94502dd2f5527ec05481535300f206d74828
[ "Apache-2.0" ]
25
2019-05-27T17:56:38.000Z
2020-08-21T01:45:40.000Z
src/main/java/com/google/devtools/build/lib/skyframe/StarlarkBuiltinsValue.java
gorakhargosh/bazel
243c94502dd2f5527ec05481535300f206d74828
[ "Apache-2.0" ]
4
2019-11-22T23:23:41.000Z
2022-03-01T01:51:48.000Z
31.853933
95
0.721693
1,874
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.skyframe.SkyFunctionName; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; /** * A Skyframe value representing the Starlark symbols defined by the {@code @builtins} * pseudo-repository. * * <p>These are parsed from {@code @builtins//:exports.bzl}. */ public final class StarlarkBuiltinsValue implements SkyValue { // These are all deeply immutable (the Starlark values are already frozen), so let's skip the // accessors and mutators. /** Top-level predeclared symbols for a .bzl file (loaded on behalf of a BUILD file). */ // TODO(#11437): Corresponding predeclaredForBuild for BUILD files public final ImmutableMap<String, Object> predeclaredForBuildBzl; /** Contents of the {@code exported_to_java} dict. */ public final ImmutableMap<String, Object> exportedToJava; /** Transitive digest of all .bzl files in {@code @builtins}. */ public final byte[] transitiveDigest; public StarlarkBuiltinsValue( ImmutableMap<String, Object> predeclaredForBuildBzl, ImmutableMap<String, Object> exportedToJava, byte[] transitiveDigest) { this.predeclaredForBuildBzl = predeclaredForBuildBzl; this.exportedToJava = exportedToJava; this.transitiveDigest = transitiveDigest; } /** Returns the singleton SkyKey for this type of value. */ public static Key key() { return Key.INSTANCE; } /** * Skyframe key for retrieving the {@code @builtins} definitions. * * <p>This has no fields since there is only one {@code StarlarkBuiltinsValue} at a time. */ static final class Key implements SkyKey { private static final Key INSTANCE = new Key(); private Key() {} @Override public SkyFunctionName functionName() { return SkyFunctions.STARLARK_BUILTINS; } @Override public String toString() { return "Starlark @builtins"; } @Override public boolean equals(Object other) { return other instanceof Key; } @Override public int hashCode() { return 7727; // more or less xkcd/221 } } }
3e0474a105bff505f985811f0fb4494b6b0316c5
733
java
Java
device/device-entity/src/main/java/com/lion/device/entity/device/vo/DetailsDeviceVo.java
MrLiuFang/hospital
1fa1316d89633744569a3fe3ff2721f281476222
[ "MIT" ]
null
null
null
device/device-entity/src/main/java/com/lion/device/entity/device/vo/DetailsDeviceVo.java
MrLiuFang/hospital
1fa1316d89633744569a3fe3ff2721f281476222
[ "MIT" ]
null
null
null
device/device-entity/src/main/java/com/lion/device/entity/device/vo/DetailsDeviceVo.java
MrLiuFang/hospital
1fa1316d89633744569a3fe3ff2721f281476222
[ "MIT" ]
null
null
null
19.289474
50
0.702592
1,875
package com.lion.device.entity.device.vo; import com.lion.device.entity.device.Device; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import javax.persistence.Column; /** * @author Mr.Liu * @Description: * @date 2021/4/1上午11:35 */ @Data @Schema public class DetailsDeviceVo extends Device { @Schema(description = "归属科室名称") private String departmentName; @Schema(description = "归属科室id") private Long departmentId; @Schema(description = "建筑名称(安装位置)") private String buildName; @Schema(description = "楼层名称(安装位置)") private String buildFloorName; @Schema(description = "地图") private String mapUrl; @Schema(description = "图片") private String imgUrl; }
3e047526d8ec4711b8230d364030e7d86ea171ad
1,689
java
Java
src/main/java/club/minnced/discord/webhook/exception/HttpException.java
esamarathon/oengus-discord-webhooks
b9bd4778d31b23ad5e9fa749f4ae77af42721b24
[ "Apache-2.0" ]
108
2018-10-31T10:20:36.000Z
2022-01-26T08:24:46.000Z
src/main/java/club/minnced/discord/webhook/exception/HttpException.java
esamarathon/oengus-discord-webhooks
b9bd4778d31b23ad5e9fa749f4ae77af42721b24
[ "Apache-2.0" ]
34
2018-11-09T10:40:38.000Z
2022-03-14T19:48:21.000Z
src/main/java/club/minnced/discord/webhook/exception/HttpException.java
esamarathon/oengus-discord-webhooks
b9bd4778d31b23ad5e9fa749f4ae77af42721b24
[ "Apache-2.0" ]
34
2019-01-03T18:00:35.000Z
2022-03-30T17:37:22.000Z
24.838235
84
0.653049
1,876
/* * Copyright 2018-2020 Florian Spieß * * 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 club.minnced.discord.webhook.exception; import okhttp3.Headers; import org.jetbrains.annotations.NotNull; /** * Exception thrown in case of unexpected non-2xx HTTP response. */ public class HttpException extends RuntimeException { private final int code; private final String body; private final Headers headers; public HttpException(int code, @NotNull String body, @NotNull Headers headers) { super("Request returned failure " + code + ": " + body); this.body = body; this.code = code; this.headers = headers; } /** * The HTTP status code * * @return The status code */ public int getCode() { return code; } /** * The body of HTTP response * * @return The body */ @NotNull public String getBody() { return body; } /** * The HTTP headers. Useful to check content-type or rate limit buckets. * * @return {@link okhttp3.Headers} */ @NotNull public Headers getHeaders() { return headers; } }
3e04767e3e8d8152fbc056cae5abc4f002e8e265
6,745
java
Java
wit-tools/src/main/java/org/febit/wit/tools/testunit/AssertGlobalRegister.java
Andyfoo/wit
794138cdbe9c5d4289ded8f7f4eb1cd1a96917ee
[ "BSD-3-Clause" ]
20
2016-12-06T03:51:08.000Z
2021-12-31T08:45:47.000Z
wit-tools/src/main/java/org/febit/wit/tools/testunit/AssertGlobalRegister.java
Amy2303/wit
89ee29efbc5633b79c30c3c7b953c9f4130575af
[ "BSD-3-Clause" ]
17
2017-10-05T09:45:52.000Z
2021-03-28T05:08:16.000Z
wit-tools/src/main/java/org/febit/wit/tools/testunit/AssertGlobalRegister.java
Amy2303/wit
89ee29efbc5633b79c30c3c7b953c9f4130575af
[ "BSD-3-Clause" ]
8
2017-07-22T06:51:23.000Z
2022-03-30T01:59:34.000Z
33.226601
95
0.626686
1,877
// Copyright (c) 2013-present, febit.org. All Rights Reserved. package org.febit.wit.tools.testunit; import org.febit.wit.InternalContext; import org.febit.wit.global.GlobalManager; import org.febit.wit.global.GlobalRegister; import java.lang.reflect.Array; import java.util.concurrent.atomic.LongAdder; import static org.febit.wit.Context.VOID; import static org.febit.wit.util.ArrayUtil.get; /** * @author zqq90 */ public class AssertGlobalRegister implements GlobalRegister { public static final String ASSERT_COUNT_KEY = "$$LIB_ASSERT_COUNT"; @Override public void regist(final GlobalManager manager) { manager.setConstMethod("assertTrue", AssertGlobalRegister::assertTrue); manager.setConstMethod("assertFalse", AssertGlobalRegister::assertFalse); manager.setConstMethod("assertNull", AssertGlobalRegister::assertNull); manager.setConstMethod("assertNotNull", AssertGlobalRegister::assertNotNull); manager.setConstMethod("assertSame", AssertGlobalRegister::assertSame); manager.setConstMethod("assertNotSame", AssertGlobalRegister::assertNotSame); manager.setConstMethod("assertEquals", AssertGlobalRegister::assertEquals); manager.setConstMethod("assertArrayEquals", AssertGlobalRegister::assertArrayEquals); } private static void plusAssertCount(InternalContext context) { LongAdder count = (LongAdder) context.getLocal(ASSERT_COUNT_KEY); if (count == null) { count = new LongAdder(); context.setLocal(ASSERT_COUNT_KEY, count); } count.increment(); } private static void assertObjectTrue(Object condition) { if (condition instanceof Boolean) { assertTrue((Boolean) condition); } else { fail("not a Boolean"); } } private static void assertTrue(boolean condition) { if (!condition) { fail(null); } } private static void assertObjectFalse(Object condition) { if (condition instanceof Boolean) { assertTrue(!(Boolean) condition); } else { fail("not a Boolean"); } } private static void assertNotNull(Object object) { assertTrue(object != null); } private static void assertNull(Object object) { assertTrue(object == null); } private static void assertEquals(Object expected, Object actual) { if ((expected == null && actual != null) || (expected != null && !expected.equals(actual))) { failNotEquals(expected, actual); } } private static void assertSame(Object expected, Object actual) { if (expected == actual) { return; } failNotSame(expected, actual); } private static void assertNotSame(Object unexpected, Object actual) { if (unexpected == actual) { failSame(); } } private static void assertArrayEquals(Object expected, Object actual) { if (expected == actual) { return; } final int expectedLength = assertArraysAreSameLength(expected, actual); for (int i = 0; i < expectedLength; i++) { try { assertEquals(Array.get(expected, i), Array.get(actual, i)); } catch (AssertionError e) { fail("arrays first differed at element " + i); } } } private static int assertArraysAreSameLength(Object expected, Object actual) { if (expected == null) { fail("expected array was null"); } if (actual == null) { fail("actual array was null"); } int actualLength = Array.getLength(actual); int expectedLength = Array.getLength(expected); if (actualLength != expectedLength) { fail("array lengths differed, expected.length=" + expectedLength + " actual.length=" + actualLength); } return expectedLength; } private static void fail(String message) { throw new AssertionError(message == null ? "" : message); } private static void failSame() { fail("expected not same"); } private static void failNotSame(Object expected, Object actual) { fail("expected same:<" + expected + "> was not:<" + actual + ">"); } private static void failNotEquals(Object expected, Object actual) { fail(format(expected, actual)); } private static String format(Object expected, Object actual) { String expectedString = String.valueOf(expected); String actualString = String.valueOf(actual); if (expectedString.equals(actualString)) { return "expected: " + formatClassAndValue(expected, expectedString) + " but was: " + formatClassAndValue(actual, actualString); } else { return "expected:<" + expectedString + "> but was:<" + actualString + ">"; } } private static String formatClassAndValue(Object value, String valueString) { return (value == null ? "null" : value.getClass().getName()) + "<" + valueString + ">"; } private static Object assertTrue(InternalContext context, Object[] args) { plusAssertCount(context); assertObjectTrue(get(args, 0)); return VOID; } private static Object assertFalse(InternalContext context, Object[] args) { plusAssertCount(context); assertObjectFalse(get(args, 0)); return VOID; } private static Object assertNotNull(InternalContext context, Object[] args) { plusAssertCount(context); assertNotNull(get(args, 0)); return VOID; } private static Object assertNull(InternalContext context, Object[] args) { plusAssertCount(context); assertNull(get(args, 0)); return VOID; } private static Object assertEquals(InternalContext context, Object[] args) { plusAssertCount(context); assertEquals(get(args, 0), get(args, 1)); return VOID; } private static Object assertSame(InternalContext context, Object[] args) { plusAssertCount(context); assertSame(get(args, 0), get(args, 1)); return VOID; } private static Object assertNotSame(InternalContext context, Object[] args) { plusAssertCount(context); assertNotSame(get(args, 0), get(args, 1)); return VOID; } private static Object assertArrayEquals(InternalContext context, Object[] args) { plusAssertCount(context); assertArrayEquals(get(args, 0), get(args, 1)); return VOID; } }
3e047792a0f531fd63ce3b43212b228d83578535
1,787
java
Java
app/src/main/java/com/ejoy/tool/ui/activity/datetime/timeline/ITimeLineActivity.java
maiduoduo/EJoy
81953ba5627399acf6cafdbc19e60a983721722d
[ "Apache-2.0", "MIT" ]
4
2019-11-28T06:57:01.000Z
2020-06-29T02:03:12.000Z
app/src/main/java/com/ejoy/tool/ui/activity/datetime/timeline/ITimeLineActivity.java
maiduoduo/EJoy
81953ba5627399acf6cafdbc19e60a983721722d
[ "Apache-2.0", "MIT" ]
2
2020-01-19T08:38:09.000Z
2020-07-18T06:35:36.000Z
app/src/main/java/com/ejoy/tool/ui/activity/datetime/timeline/ITimeLineActivity.java
maiduoduo/EJoy
81953ba5627399acf6cafdbc19e60a983721722d
[ "Apache-2.0", "MIT" ]
3
2020-06-29T02:40:14.000Z
2020-09-02T21:37:18.000Z
20.134831
74
0.577009
1,878
package com.ejoy.tool.ui.activity.datetime.timeline; // ┏┓   ┏┓ //┏┛┻━━━┛┻┓ //┃       ┃ //┃   ━   ┃ //┃ ┳┛ ┗┳ ┃ //┃       ┃ //┃   ┻   ┃ //┃       ┃ //┗━┓   ┏━┛ // ┃   ┃ 神兽保佑 // ┃   ┃ 永无BUG! // ┃   ┗━━━┓ // ┃       ┣┓ // ┃       ┏┛ // ┗┓┓┏━┳┓┏┛ // ┃┫┫ ┃┫┫ // ┗┻┛ ┗┻┛ import android.graphics.Color; import android.view.View; import com.ejoy.tool.R; import com.ejoy.tool.scaffold.utils.StatusBarTool; import com.ejoy.tool.ui.base.base_activity.IBaseActivity; import com.kongzue.baseframework.interfaces.DarkStatusBarTheme; import com.kongzue.baseframework.interfaces.Layout; /** * @ClassName: ITimeLineActivity * @Author: bsj-dingcl * @Email: [email protected] * @Date: 2020/07/20 * @des: 时间线 */ @Layout(R.layout.activity_timeline) @DarkStatusBarTheme(true) public class ITimeLineActivity extends IBaseActivity { @Override protected boolean isRegistSatusbarFullScreenTransluent() { return true; } @Override public void initViews() { StatusBarTool.setRootViewFitsSystemWindows(me,true); StatusBarTool.setStatusBarColor(me,Color.parseColor("#ff529aff")); } @Override public void initDatas() { } @Override public void setEvents() { } public void ivBack(View view) { finishActivity(); } /** * 日历+时间线 * @param view */ public void calendarTimeLine(View view) { jump(ITimeLineCalendarActivity.class); } /** * 自定义时间线(RecyclerView) * @param view */ public void timeLIneRecyclerView(View view) { jump(ITimeLineRecyclerviewActivity.class); } /** * 仿「美柚」官网大事记时间线 * @param view */ public void myouTimeLIneRecyclerView(View view) { } }
3e047794aa3914144fda47c95f2077d8975c8e0d
649
java
Java
enos-sdk-core/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/message/upstream/network/NetworkStatusReportResponse.java
EnvisionIot/enos-iot-java-sdk
ba7b48c07c9dd0608fd492045f7d13db2c6dfdb7
[ "Apache-2.0" ]
1
2021-03-10T02:12:25.000Z
2021-03-10T02:12:25.000Z
enos-sdk-core/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/message/upstream/network/NetworkStatusReportResponse.java
EnvisionIot/enos-iot-java-sdk
ba7b48c07c9dd0608fd492045f7d13db2c6dfdb7
[ "Apache-2.0" ]
4
2020-01-20T07:28:09.000Z
2022-01-04T16:42:14.000Z
enos-sdk-core/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/message/upstream/network/NetworkStatusReportResponse.java
EnvisionIot/enos-iot-java-sdk
ba7b48c07c9dd0608fd492045f7d13db2c6dfdb7
[ "Apache-2.0" ]
8
2020-01-20T07:36:14.000Z
2021-06-24T09:34:48.000Z
30.904762
95
0.793529
1,879
package com.envisioniot.enos.iot_mqtt_sdk.message.upstream.network; import com.envisioniot.enos.iot_mqtt_sdk.core.internals.constants.ArrivedTopicPattern; import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.BaseMqttResponse; import java.util.regex.Pattern; /** * @author mengyuantan * @date 2020/10/16 13:58 */ public class NetworkStatusReportResponse extends BaseMqttResponse { private static final long serialVersionUID = 6049281715026111313L; private static Pattern pattern = Pattern.compile(ArrivedTopicPattern.NETWORK_STATUS_REPLY); @Override public Pattern getMatchTopicPattern() { return pattern; } }
3e0478c3adeae55890a1273f387d10c49393acb7
2,487
java
Java
Technology Fundamentals 4.0/10. Maps, Lambda and Stream API/Maps, Lambda and Stream API - More Exercise/src/P4_Snowwhite.java
GabrielGardev/skill-receiving
7227323d065f3472a6aedc1cbf3efd41562269f2
[ "MIT" ]
3
2019-01-24T20:22:38.000Z
2019-08-19T13:45:31.000Z
Technology Fundamentals 4.0/10. Maps, Lambda and Stream API/Maps, Lambda and Stream API - More Exercise/src/P4_Snowwhite.java
GabrielGardev/soft-uni
7227323d065f3472a6aedc1cbf3efd41562269f2
[ "MIT" ]
null
null
null
Technology Fundamentals 4.0/10. Maps, Lambda and Stream API/Maps, Lambda and Stream API - More Exercise/src/P4_Snowwhite.java
GabrielGardev/soft-uni
7227323d065f3472a6aedc1cbf3efd41562269f2
[ "MIT" ]
null
null
null
30.329268
91
0.470446
1,880
import java.util.*; public class P4_Snowwhite { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List<Dwarf> dwarves = new ArrayList<>(); LinkedHashMap<String, Integer> colorAndCount = new LinkedHashMap<>(); while (true) { String[] line = scanner.nextLine().split(" <:> "); if (line[0].equals("Once upon a time")) { break; } String name = line[0]; String color = line[1]; int physics = Integer.parseInt(line[2]); Dwarf dwarf = new Dwarf(name, physics, color, 1); boolean hasAdded = false; boolean hasSameNameAndColor = false; for (Dwarf unit : dwarves) { if (unit.Name.equals(dwarf.Name)) { if (unit.Color.equals(dwarf.Color)) { hasSameNameAndColor = true; if (dwarf.Physics > unit.Physics) { unit.Physics = dwarf.Physics; hasAdded = true; break; } } } } if (!hasAdded && !hasSameNameAndColor) { dwarves.add(dwarf); if (!colorAndCount.containsKey(color)) { colorAndCount.put(color, 0); } colorAndCount.put(color, colorAndCount.get(color) + 1); } } for (Dwarf unit : dwarves) { for (var color : colorAndCount.entrySet()) { if (unit.Color.equals(color.getKey())) { unit.ColorCount = color.getValue(); } } } dwarves.stream().sorted((e1, e2) -> { int result = Integer.compare(e2.Physics, e1.Physics); if (result == 0) { result = Integer.compare(e2.ColorCount, e1.ColorCount); } return result; }).forEach(x -> System.out.printf("(%s) %s <-> %d%n", x.Color, x.Name, x.Physics)); } static class Dwarf { public String Name; public int Physics; public String Color; public int ColorCount; public Dwarf(String name, int physics, String color, int colorCount) { Name = name; Physics = physics; Color = color; ColorCount = colorCount; } } }
3e0479d48d3cc6e7384b3d8e938eb6174e67f711
3,364
java
Java
src/main/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java
AspireWorld-Project/AspireCore
61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042
[ "WTFPL" ]
null
null
null
src/main/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java
AspireWorld-Project/AspireCore
61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042
[ "WTFPL" ]
null
null
null
src/main/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java
AspireWorld-Project/AspireCore
61dfc4f6cc7bca4ed7fd4de1413b7c8030a72042
[ "WTFPL" ]
null
null
null
25.293233
115
0.607015
1,881
package net.minecraft.client.renderer.entity; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import java.util.Random; @SideOnly(Side.CLIENT) public class RenderLightningBolt extends Render { private static final String __OBFID = "CL_00001011"; public void doRender(EntityLightningBolt p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_) { Tessellator tessellator = Tessellator.instance; GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); double[] adouble = new double[8]; double[] adouble1 = new double[8]; double d3 = 0.0D; double d4 = 0.0D; Random random = new Random(p_76986_1_.boltVertex); for (int i = 7; i >= 0; --i) { adouble[i] = d3; adouble1[i] = d4; d3 += random.nextInt(11) - 5; d4 += random.nextInt(11) - 5; } for (int k1 = 0; k1 < 4; ++k1) { Random random1 = new Random(p_76986_1_.boltVertex); for (int j = 0; j < 3; ++j) { int k = 7; int l = 0; if (j > 0) { k = 7 - j; } if (j > 0) { l = k - 2; } double d5 = adouble[k] - d3; double d6 = adouble1[k] - d4; for (int i1 = k; i1 >= l; --i1) { double d7 = d5; double d8 = d6; if (j == 0) { d5 += random1.nextInt(11) - 5; d6 += random1.nextInt(11) - 5; } else { d5 += random1.nextInt(31) - 15; d6 += random1.nextInt(31) - 15; } tessellator.startDrawing(5); float f2 = 0.5F; tessellator.setColorRGBA_F(0.9F * f2, 0.9F * f2, 1.0F * f2, 0.3F); double d9 = 0.1D + k1 * 0.2D; if (j == 0) { d9 *= i1 * 0.1D + 1.0D; } double d10 = 0.1D + k1 * 0.2D; if (j == 0) { d10 *= (i1 - 1) * 0.1D + 1.0D; } for (int j1 = 0; j1 < 5; ++j1) { double d11 = p_76986_2_ + 0.5D - d9; double d12 = p_76986_6_ + 0.5D - d9; if (j1 == 1 || j1 == 2) { d11 += d9 * 2.0D; } if (j1 == 2 || j1 == 3) { d12 += d9 * 2.0D; } double d13 = p_76986_2_ + 0.5D - d10; double d14 = p_76986_6_ + 0.5D - d10; if (j1 == 1 || j1 == 2) { d13 += d10 * 2.0D; } if (j1 == 2 || j1 == 3) { d14 += d10 * 2.0D; } tessellator.addVertex(d13 + d5, p_76986_4_ + i1 * 16, d14 + d6); tessellator.addVertex(d11 + d7, p_76986_4_ + (i1 + 1) * 16, d12 + d8); } tessellator.draw(); } } } GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_TEXTURE_2D); } protected ResourceLocation getEntityTexture(EntityLightningBolt p_110775_1_) { return null; } @Override protected ResourceLocation getEntityTexture(Entity p_110775_1_) { return this.getEntityTexture((EntityLightningBolt) p_110775_1_); } @Override public void doRender(Entity p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_) { this.doRender((EntityLightningBolt) p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_); } }
3e047a2c2723db2bee525d13cd2d0d9f712ab6e8
472
java
Java
apps/src/main/java/org/sikuli/slides/examples/ParameterizedInputExample.java
sikuli/sikuli-slides
1a4a82cd97f577e0d7abe4218bf702e053acf003
[ "MIT" ]
47
2015-01-07T21:48:36.000Z
2021-05-02T09:25:06.000Z
apps/src/main/java/org/sikuli/slides/examples/ParameterizedInputExample.java
sikuli/sikuli-slides
1a4a82cd97f577e0d7abe4218bf702e053acf003
[ "MIT" ]
12
2015-02-18T06:50:22.000Z
2018-07-26T13:41:59.000Z
apps/src/main/java/org/sikuli/slides/examples/ParameterizedInputExample.java
sikuli/sikuli-slides
1a4a82cd97f577e0d7abe4218bf702e053acf003
[ "MIT" ]
24
2015-02-18T05:27:39.000Z
2021-11-15T11:29:15.000Z
26.222222
71
0.773305
1,882
package org.sikuli.slides.examples; import org.sikuli.slides.api.Context; import org.sikuli.slides.api.SlideExecutionException; import org.sikuli.slides.api.Slides; public class ParameterizedInputExample { public static void main(String[] arg) throws SlideExecutionException { Context context = new Context(); context.addParameter("username", "user2142"); context.addParameter("password", "cdads2ev"); Slides.execute(Resources.login_pptx, context); } }
3e047b0cdcd8d153d33cc9e1539d7a64420e2339
1,739
java
Java
core/src/test/java/noop/graph/VertexCreatingVisitorTest.java
hmahal/noop
188117d334791ff391f239f2852efe1f7f365020
[ "Apache-2.0" ]
2
2017-10-04T23:52:23.000Z
2021-06-20T19:11:58.000Z
core/src/test/java/noop/graph/VertexCreatingVisitorTest.java
hmahal/noop
188117d334791ff391f239f2852efe1f7f365020
[ "Apache-2.0" ]
null
null
null
core/src/test/java/noop/graph/VertexCreatingVisitorTest.java
hmahal/noop
188117d334791ff391f239f2852efe1f7f365020
[ "Apache-2.0" ]
1
2021-06-20T19:12:06.000Z
2021-06-20T19:12:06.000Z
29.525424
75
0.702641
1,883
/* * Copyright 2010 Google 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 noop.graph; import noop.model.Clazz; import noop.model.Library; import noop.model.Method; import noop.model.Project; import org.junit.Test; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * @author [email protected] (Alex Eagle) */ public class VertexCreatingVisitorTest { @Test public void shouldCreateVerticesForEveryElementUnderAProject() { Project p = new Project("example", "p", "MIT license"); UUID uid = UUID.randomUUID(); Library l = new Library(uid, "l"); Clazz c = new Clazz("c"); Method m = new Method("m"); Library l2 = new Library(UUID.randomUUID(), "l2"); p.addLibrary(l); p.addLibrary(l2); l.addClazz(c); c.addBlock(m); p.accept(new VertexCreatingVisitor()); assertEquals(l, l.getElements().get(0)); assertEquals(c, l.getElements().get(1)); assertEquals(m, l.getElements().get(2)); assertEquals(new Vertex(uid, 0), l.vertex); assertEquals(new Vertex(uid, 1), c.vertex); assertEquals(new Vertex(uid, 2), m.vertex); assertFalse(l2.vertex.libraryUid.equals(uid)); } }
3e047b0ecd0d86d697118bbb97d6af602093aba0
2,809
java
Java
SPF.Client/src/dk/aau/cs/spf/callable/SpfHttpRequestThread.java
Chraebe/StarPatternFragments
524129ab1358d317cffe32e2eb3e214904bc0f51
[ "MIT" ]
null
null
null
SPF.Client/src/dk/aau/cs/spf/callable/SpfHttpRequestThread.java
Chraebe/StarPatternFragments
524129ab1358d317cffe32e2eb3e214904bc0f51
[ "MIT" ]
6
2020-02-20T07:35:55.000Z
2020-12-02T18:41:54.000Z
SPF.Client/src/dk/aau/cs/spf/callable/SpfHttpRequestThread.java
Chraebe/StarPatternFragments
524129ab1358d317cffe32e2eb3e214904bc0f51
[ "MIT" ]
null
null
null
43.215385
126
0.725881
1,884
package dk.aau.cs.spf.callable; import dk.aau.cs.spf.main.SparqlQueryProcessor; import dk.aau.cs.spf.task.BrtpfHttpRequestTask; import dk.aau.cs.spf.task.BrtpfParseResponseTask; import dk.aau.cs.spf.task.SpfHttpRequestTask; import dk.aau.cs.spf.task.SpfParseResponseTask; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.fluent.Content; import org.apache.http.client.fluent.Request; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.atomic.AtomicInteger; public class SpfHttpRequestThread implements Callable<Boolean> { private SpfHttpRequestTask httpRequestTask; private ConcurrentHashMap<String, Content> httpResponseCache; private ExecutorCompletionService<Boolean> executorCompletionService; private AtomicInteger numberOfTasks; public SpfHttpRequestThread(SpfHttpRequestTask httpRequestTask, ConcurrentHashMap<String, Content> httpResponseCache, ExecutorCompletionService<Boolean> executorCompletionService, AtomicInteger numberOfTasks) { this.httpRequestTask = httpRequestTask; this.httpResponseCache = httpResponseCache; this.executorCompletionService = executorCompletionService; this.numberOfTasks = numberOfTasks; } /* * (non-Javadoc) * * @see java.util.concurrent.Callable#call() */ @Override public Boolean call() throws ClientProtocolException, IOException { String httpUrl = httpRequestTask.getFragmentURL(); Content content = null; if (httpResponseCache.containsKey(httpUrl)) { content = httpResponseCache.get(httpUrl); } else { SparqlQueryProcessor.NUMBER_OF_HTTP_REQUESTS.incrementAndGet(); SparqlQueryProcessor.NUMBER_OF_BINDINGS_SENT.addAndGet(httpRequestTask.getBindings().size()); SparqlQueryProcessor.SERVER_REQUESTS.incrementAndGet(); content = Request.Get(httpUrl).addHeader("accept", "text/turtle").execute().returnContent(); SparqlQueryProcessor.TRANSFERRED_BYTES.addAndGet(content.asBytes().length + httpUrl.getBytes().length); httpResponseCache.put(httpUrl, content); } if (content != null) { SpfParseResponseTask prTask = new SpfParseResponseTask(httpRequestTask, content.asStream()); numberOfTasks.incrementAndGet(); SpfResponseParserThread rpThread = new SpfResponseParserThread(prTask, executorCompletionService, httpResponseCache, numberOfTasks); executorCompletionService.submit(rpThread); } return true; } }
3e047be4da73f5f27c4fa15f12b1b7fa0bd6a075
1,307
java
Java
mvn-golang-wrapper/src/main/java/com/igormaznitsa/mvngolang/utils/StringComparatorABC.java
Theoderich/mvn-golang
a1dd6d80a54bb3cf8a92a2f20bbd0e769b4498f6
[ "Apache-2.0" ]
null
null
null
mvn-golang-wrapper/src/main/java/com/igormaznitsa/mvngolang/utils/StringComparatorABC.java
Theoderich/mvn-golang
a1dd6d80a54bb3cf8a92a2f20bbd0e769b4498f6
[ "Apache-2.0" ]
null
null
null
mvn-golang-wrapper/src/main/java/com/igormaznitsa/mvngolang/utils/StringComparatorABC.java
Theoderich/mvn-golang
a1dd6d80a54bb3cf8a92a2f20bbd0e769b4498f6
[ "Apache-2.0" ]
null
null
null
29.704545
84
0.742158
1,885
/* * Copyright 2016 Igor Maznitsa. * * 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.igormaznitsa.mvngolang.utils; import javax.annotation.Nonnull; import javax.annotation.concurrent.ThreadSafe; import java.io.Serializable; import java.util.Comparator; @ThreadSafe public final class StringComparatorABC implements Comparator<String>, Serializable { private static final long serialVersionUID = -8700761616096593374L; private static final StringComparatorABC INSTANCE = new StringComparatorABC(); private StringComparatorABC() { } @Nonnull public static StringComparatorABC getInstance() { return INSTANCE; } @Override public int compare(@Nonnull final String a, @Nonnull final String b) { return a.compareTo(b); } }
3e047ca6f885f20f792347cf4d2118f38fb21b23
490
java
Java
app/models/MediaDescriptor.java
welkin91/google-storage-java
3cfe694d12573eab72f963d91b3ad411b7d5748d
[ "CC0-1.0" ]
null
null
null
app/models/MediaDescriptor.java
welkin91/google-storage-java
3cfe694d12573eab72f963d91b3ad411b7d5748d
[ "CC0-1.0" ]
null
null
null
app/models/MediaDescriptor.java
welkin91/google-storage-java
3cfe694d12573eab72f963d91b3ad411b7d5748d
[ "CC0-1.0" ]
null
null
null
18.148148
63
0.616327
1,886
package models; public class MediaDescriptor { private String mediaUrl; private String itemName; private String mediaId; public MediaDescriptor(String name, String id, String url){ this.itemName = name; this.mediaId = id; this.mediaUrl = url; } public String getMediaUrl() { return mediaUrl; } public String getItemName() { return itemName; } public String getMediaId() { return mediaId; } }
3e047e61f3c5e88b5fd0de2e7b48aac792dc0fab
8,359
java
Java
toolkit/src/main/java/com/google/api/codegen/CodeGeneratorApi.java
SurferJeffAtGoogle/discovery-artifact-manager
913a25b34f8b97b39fefa8111d2b2b21b0fc463d
[ "Apache-2.0" ]
38
2017-07-20T17:54:08.000Z
2022-02-20T02:16:31.000Z
toolkit/src/main/java/com/google/api/codegen/CodeGeneratorApi.java
SurferJeffAtGoogle/discovery-artifact-manager
913a25b34f8b97b39fefa8111d2b2b21b0fc463d
[ "Apache-2.0" ]
183
2017-03-23T17:17:24.000Z
2022-02-09T00:07:17.000Z
toolkit/src/main/java/com/google/api/codegen/CodeGeneratorApi.java
SurferJeffAtGoogle/discovery-artifact-manager
913a25b34f8b97b39fefa8111d2b2b21b0fc463d
[ "Apache-2.0" ]
42
2017-03-23T19:20:20.000Z
2022-02-20T02:17:09.000Z
36.662281
99
0.699964
1,887
/* Copyright 2016 Google 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.google.api.codegen; import com.google.api.codegen.advising.Adviser; import com.google.api.codegen.config.GapicProductConfig; import com.google.api.codegen.config.PackageMetadataConfig; import com.google.api.codegen.gapic.GapicGeneratorConfig; import com.google.api.codegen.gapic.GapicProvider; import com.google.api.codegen.gapic.GapicProviderFactory; import com.google.api.codegen.util.ClassInstantiator; import com.google.api.tools.framework.model.ConfigSource; import com.google.api.tools.framework.model.Diag; import com.google.api.tools.framework.model.Model; import com.google.api.tools.framework.model.SimpleLocation; import com.google.api.tools.framework.model.stages.Merged; import com.google.api.tools.framework.snippet.Doc; import com.google.api.tools.framework.tools.ToolDriverBase; import com.google.api.tools.framework.tools.ToolOptions; import com.google.api.tools.framework.tools.ToolOptions.Option; import com.google.api.tools.framework.tools.ToolUtil; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.TypeLiteral; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.Message; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; /** Main class for the code generator. */ public class CodeGeneratorApi extends ToolDriverBase { public static final Option<String> OUTPUT_FILE = ToolOptions.createOption( String.class, "output_file", "The name of the output file or folder to put generated code.", ""); public static final Option<List<String>> GENERATOR_CONFIG_FILES = ToolOptions.createOption( new TypeLiteral<List<String>>() {}, "config_files", "The list of YAML configuration files for the code generator.", ImmutableList.<String>of()); public static final Option<String> PACKAGE_CONFIG_FILE = ToolOptions.createOption( String.class, "package_config", "The package metadata configuration.", ""); public static final Option<List<String>> ENABLED_ARTIFACTS = ToolOptions.createOption( new TypeLiteral<List<String>>() {}, "enabled_artifacts", "The artifacts to be generated by the code generator.", ImmutableList.<String>of()); public static final Option<List<String>> ADVICE_SUPPRESSORS = ToolOptions.createOption( new TypeLiteral<List<String>>() {}, "supress_warning", "Names of adviser rules to suppress warnings for.", ImmutableList.<String>of()); /** Constructs a code generator api based on given options. */ public CodeGeneratorApi(ToolOptions options) { super(options); } @Override public ExtensionRegistry getPlatformExtensions() { ExtensionRegistry extensionRegistry = super.getPlatformExtensions(); return extensionRegistry; } @Override protected void process() throws Exception { // Read the YAML config and convert it to proto. List<String> configFileNames = options.get(GENERATOR_CONFIG_FILES); if (configFileNames.size() == 0) { error(String.format("--%s must be provided", GENERATOR_CONFIG_FILES.name())); return; } ConfigSource configSource = loadConfigFromFiles(configFileNames); if (configSource == null) { return; } ConfigProto configProto = (ConfigProto) configSource.getConfig(); if (configProto == null) { return; } model.establishStage(Merged.KEY); List<String> adviceSuppressors = options.get(ADVICE_SUPPRESSORS); Adviser adviser = new Adviser(adviceSuppressors); adviser.advise(model, configProto); if (model.getDiagCollector().getErrorCount() > 0) { for (Diag diag : model.getDiagCollector().getDiags()) { System.err.println(diag.toString()); } return; } PackageMetadataConfig packageConfig = null; if (!Strings.isNullOrEmpty(options.get(PACKAGE_CONFIG_FILE))) { String contents = new String( Files.readAllBytes(Paths.get(options.get(PACKAGE_CONFIG_FILE))), StandardCharsets.UTF_8); packageConfig = PackageMetadataConfig.createFromString(contents); } GeneratorProto generator = configProto.getGenerator(); GapicProductConfig productConfig = GapicProductConfig.create(model, configProto); if (productConfig == null) { return; } if (generator != null) { String factory = generator.getFactory(); String id = generator.getId(); GapicProviderFactory<GapicProvider<? extends Object>> providerFactory = createProviderFactory(model, factory); GapicGeneratorConfig generatorConfig = GapicGeneratorConfig.newBuilder() .id(id) .enabledArtifacts(options.get(ENABLED_ARTIFACTS)) .build(); String outputPath = options.get(OUTPUT_FILE); List<GapicProvider<? extends Object>> providers = providerFactory.create(model, productConfig, generatorConfig, packageConfig, outputPath); Map<String, Doc> outputFiles = Maps.newHashMap(); for (GapicProvider<? extends Object> provider : providers) { outputFiles.putAll(provider.generate()); } writeCodeGenOutput(outputFiles, outputPath); } } @VisibleForTesting public static void writeCodeGenOutput(Map<String, Doc> outputFiles, String outputFile) throws IOException { // TODO: Support zip output. if (outputFile.endsWith(".jar")) { ToolUtil.writeJar(outputFiles, outputFile); } else { ToolUtil.writeFiles(outputFiles, outputFile); } } private static GapicProviderFactory<GapicProvider<? extends Object>> createProviderFactory( final Model model, String factory) { @SuppressWarnings("unchecked") GapicProviderFactory<GapicProvider<? extends Object>> provider = ClassInstantiator.createClass( factory, GapicProviderFactory.class, new Class<?>[] {}, new Object[] {}, "generator", new ClassInstantiator.ErrorReporter() { @Override public void error(String message, Object... args) { model .getDiagCollector() .addDiag(Diag.error(SimpleLocation.TOPLEVEL, message, args)); } }); return provider; } private ConfigSource loadConfigFromFiles(List<String> configFileNames) { List<File> configFiles = pathsToFiles(configFileNames); if (model.getDiagCollector().getErrorCount() > 0) { return null; } ImmutableMap<String, Message> supportedConfigTypes = ImmutableMap.<String, Message>of( ConfigProto.getDescriptor().getFullName(), ConfigProto.getDefaultInstance()); return MultiYamlReader.read(model.getDiagCollector(), configFiles, supportedConfigTypes); } private List<File> pathsToFiles(List<String> configFileNames) { List<File> files = new ArrayList<>(); for (String configFileName : configFileNames) { File file = model.findDataFile(configFileName); if (file == null) { error("Cannot find configuration file '%s'.", configFileName); continue; } files.add(file); } return files; } private void error(String message, Object... args) { model.getDiagCollector().addDiag(Diag.error(SimpleLocation.TOPLEVEL, message, args)); } }
3e047ed216bd404e85751130fdfcbf927a88ca27
6,102
java
Java
JPS_DISCOVERY/src/uk/ac/cam/cares/jps/discovery/knowledgebase/AgentKnowledgeBase.java
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
011aee78c016b76762eaf511c78fabe3f98189f4
[ "MIT" ]
21
2021-03-08T01:58:25.000Z
2022-03-09T15:46:16.000Z
JPS_DISCOVERY/src/uk/ac/cam/cares/jps/discovery/knowledgebase/AgentKnowledgeBase.java
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
011aee78c016b76762eaf511c78fabe3f98189f4
[ "MIT" ]
63
2021-05-04T15:05:30.000Z
2022-03-23T14:32:29.000Z
JPS_DISCOVERY/src/uk/ac/cam/cares/jps/discovery/knowledgebase/AgentKnowledgeBase.java
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
011aee78c016b76762eaf511c78fabe3f98189f4
[ "MIT" ]
15
2021-03-08T07:52:03.000Z
2022-03-29T04:46:20.000Z
31.78125
143
0.704851
1,888
package uk.ac.cam.cares.jps.discovery.knowledgebase; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Resource; import uk.ac.cam.cares.jps.base.discovery.Agent; import uk.ac.cam.cares.jps.base.discovery.AgentServiceDescription; import uk.ac.cam.cares.jps.base.discovery.Parameter; import uk.ac.cam.cares.jps.base.exception.JPSRuntimeException; public class AgentKnowledgeBase { public static final String ONTOAGENT_BASE_IRI = "http://www.theworldavatar.com/OntoAgent"; public static final String ONTOAGENT_ONTOLOGY_IRI = ONTOAGENT_BASE_IRI + "/OntoAgent.owl"; private static AgentKnowledgeBase instance = null; private Logger logger = LoggerFactory.getLogger(AgentKnowledgeBase.class); private OntModel knowledgebase = null; private AgentKnowledgeBase () { } public static synchronized AgentKnowledgeBase getInstance() { if (instance == null) { instance = new AgentKnowledgeBase(); String dir = getDirForAgentKnowledgesBase(); instance.knowledgebase = JenaHelper.createModel(dir); instance.logger.info("AgentKnowledgeBase was created"); } return instance; } public static synchronized AgentKnowledgeBase createNewInstanceWithoutReading() { instance = new AgentKnowledgeBase(); instance.knowledgebase = JenaHelper.createModel(); return instance; } public static String getFileForAgentOntology() { return null; //AgentLocator.getPathToJpsDataOntologyDir() + "/OntoAgent/OntoAgent.owl"; } public static String getDirForAgentKnowledgesBase() { return null; //AgentLocator.getPathToJpsDataKnowledgeDir() + "/OntoAgent"; } public synchronized void read(String path) { JenaHelper.read(path, knowledgebase); } public synchronized void add(Agent agent) { String sparql = "PREFIX jpsago:<http://www.theworldavatar.com/OntoAgent/OntoAgent.owl#> " + "SELECT ?agent " + "WHERE { " + "?agent a jpsago:Agent ." + "?agent jpsago:hasName \"" + agent.getName() + "\" ." + "}"; ResultSet rs = query(sparql); if (rs.hasNext()) { throw new JPSRuntimeException("can't add agent to knowledge base because an agent with the same already exists, name = " + agent.getName()); } String serializedAgent = OWLSerializer.getInstance().convertToString(agent); JenaHelper.readFromString(serializedAgent, knowledgebase); } public synchronized ResultSet query(String sparql) { return JenaHelper.query(sparql, knowledgebase); } public Collection<Agent> getAllAgents() { List<Agent> result = new ArrayList<Agent>(); //TODO-AE URGENT since we can use the uri in sparql we might not need the iri property for agent anymore String sparql = "PREFIX jpsago:<http://www.theworldavatar.com/OntoAgent/OntoAgent.owl#> " + "SELECT ?agent ?name " + "WHERE { " + "?agent a jpsago:Agent ." //+ "?agent jpsago:hasId ?id ." + "?agent jpsago:hasName ?name ." + "}"; ResultSet rs = query(sparql); QuerySolution sol = null; while (rs.hasNext()) { Agent agent = new Agent(); sol = rs.nextSolution(); String name = sol.getLiteral("name").getString(); agent.setName(name); String agentURI = sol.getResource("agent").getURI(); List<AgentServiceDescription> descriptions = createListOfAgentServiceDescriptions(agentURI); agent.getDescriptions().addAll(descriptions); result.add(agent); } return result; } private List<AgentServiceDescription> createListOfAgentServiceDescriptions(String agentIRI) { List<AgentServiceDescription> result = new ArrayList<AgentServiceDescription>(); String sparql = "PREFIX jpsago:<http://www.theworldavatar.com/OntoAgent/OntoAgent.owl#> " + "SELECT ?descr " + "WHERE { " + "<" + agentIRI + "> jpsago:hasAgentServiceDescription ?descr" + "}"; ResultSet rs = query(sparql); QuerySolution sol = null; while (rs.hasNext()) { sol = rs.nextSolution(); Resource descr = sol.getResource("descr"); AgentServiceDescription description = createAgentServiceDescription(descr.getURI()); result.add(description); } return result; } private AgentServiceDescription createAgentServiceDescription(String descriptionIRI) { AgentServiceDescription result = new AgentServiceDescription(); String sparql = "PREFIX jpsago:<http://www.theworldavatar.com/OntoAgent/OntoAgent.owl#> " + "SELECT ?index ?type ?key ?value " + "WHERE { " + "<" + descriptionIRI + "> jpsago:hasKeyValuePair ?pair ." + "?pair a ?type ." + "?pair jpsago:hasIndex ?index ." + "?pair jpsago:hasKey ?key . " + "OPTIONAL { ?pair jpsago:hasValue ?value . }" + "} " + "ORDER BY ASC(?index)"; ResultSet rs = query(sparql); QuerySolution sol = null; while(rs.hasNext()) { sol = rs.nextSolution(); int index = sol.getLiteral("index").getInt(); String typeLocalName = sol.getResource("type").getLocalName(); String key = sol.getLiteral("key").getString(); Literal literal = sol.getLiteral("value"); String value = (literal == null)? null : literal.getString(); System.out.println(index + " " + typeLocalName + " " + key + " " + value); Parameter param = new Parameter(key, value); String type = getConceptName(typeLocalName); if ("Property".equals(type)) { result.getProperties().add(param); } else if ("InputParameter".equals(type)) { result.getInputParameters().add(param); } else if ("OutputParameter".equals(type)) { result.getOutputParameters().add(param); } else { throw new JPSRuntimeException("Parameter type is unknown, type = " + typeLocalName); } } return result; } private String getConceptName(String name) { int index = name.lastIndexOf(':'); if (index == -1) { index = name.lastIndexOf('#'); } if (index == -1) { return name; } return name.substring(index+1, name.length()-1); } }
3e047fe09563a6101f397cc399a63f6d6aea1fa0
1,278
java
Java
src/main/java/com/jsoft/framework/ssm/model/sys/user/UserDO.java
easonjim/ssm-framework
144d47005dc28f2992199a9f7ae98faa1989ca11
[ "MIT" ]
11
2018-05-22T03:44:08.000Z
2021-09-21T16:10:38.000Z
src/main/java/com/jsoft/framework/ssm/model/sys/user/UserDO.java
easonjim/ssm-framework
144d47005dc28f2992199a9f7ae98faa1989ca11
[ "MIT" ]
1
2020-02-01T09:00:43.000Z
2020-02-01T09:00:43.000Z
src/main/java/com/jsoft/framework/ssm/model/sys/user/UserDO.java
easonjim/ssm-framework
144d47005dc28f2992199a9f7ae98faa1989ca11
[ "MIT" ]
6
2018-06-16T01:50:18.000Z
2020-08-11T00:20:05.000Z
16.597403
101
0.586072
1,889
package com.jsoft.framework.ssm.model.sys.user; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * User 数据对象 * * @author jim * @date 2018/04/26 */ @Getter @Setter @ToString public class UserDO { /** * 主键ID */ private Long id; /** * 用户名 */ @JsonProperty("name") private String userName; /** * 手机 */ @JsonProperty("phone") private String userPhone; /** * 邮箱 */ @JsonProperty("email") private String userEmail; /** * 密码 */ @JsonProperty("pwd") private String userPwd; /** * 性别 */ @JsonProperty("sex") private Short userSex; /** * 创建时间 */ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonProperty("ctime") protected Date createTime; /** * 修改时间 */ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonProperty("mtime") private Date modifyTime; /** * 是否删除 */ @JsonProperty("delete") private Short isDelete; }
3e047ff9ed5ceff0da0cef8be6dde765cbbc441c
67,791
java
Java
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerSinkTaskTest.java
tklebanoff/kafka
3aa909575d3f978a5045200986eb692eebd47ab8
[ "Apache-2.0" ]
22
2020-05-03T12:56:17.000Z
2022-03-07T02:16:53.000Z
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerSinkTaskTest.java
tklebanoff/kafka
3aa909575d3f978a5045200986eb692eebd47ab8
[ "Apache-2.0" ]
5
2020-05-13T06:31:00.000Z
2021-02-24T04:01:51.000Z
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerSinkTaskTest.java
tklebanoff/kafka
3aa909575d3f978a5045200986eb692eebd47ab8
[ "Apache-2.0" ]
3
2020-12-27T16:17:58.000Z
2022-03-05T10:07:46.000Z
46.242156
175
0.683085
1,890
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime; import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.clients.consumer.OffsetCommitCallback; import org.apache.kafka.common.MetricName; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.WakeupException; import org.apache.kafka.common.record.RecordBatch; import org.apache.kafka.common.record.TimestampType; import org.apache.kafka.common.utils.MockTime; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaAndValue; import org.apache.kafka.connect.errors.RetriableException; import org.apache.kafka.connect.runtime.ConnectMetrics.MetricGroup; import org.apache.kafka.connect.runtime.distributed.ClusterConfigState; import org.apache.kafka.connect.runtime.WorkerSinkTask.SinkTaskMetricsGroup; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperatorTest; import org.apache.kafka.connect.runtime.isolation.PluginClassLoader; import org.apache.kafka.connect.runtime.standalone.StandaloneConfig; import org.apache.kafka.connect.sink.SinkConnector; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.apache.kafka.connect.storage.Converter; import org.apache.kafka.connect.storage.HeaderConverter; import org.apache.kafka.connect.util.ConnectorTaskId; import org.easymock.Capture; import org.easymock.CaptureType; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(PowerMockRunner.class) @PrepareForTest(WorkerSinkTask.class) @PowerMockIgnore("javax.management.*") public class WorkerSinkTaskTest { // These are fixed to keep this code simpler. In this example we assume byte[] raw values // with mix of integer/string in Connect private static final String TOPIC = "test"; private static final int PARTITION = 12; private static final int PARTITION2 = 13; private static final int PARTITION3 = 14; private static final long FIRST_OFFSET = 45; private static final Schema KEY_SCHEMA = Schema.INT32_SCHEMA; private static final int KEY = 12; private static final Schema VALUE_SCHEMA = Schema.STRING_SCHEMA; private static final String VALUE = "VALUE"; private static final byte[] RAW_KEY = "key".getBytes(); private static final byte[] RAW_VALUE = "value".getBytes(); private static final TopicPartition TOPIC_PARTITION = new TopicPartition(TOPIC, PARTITION); private static final TopicPartition TOPIC_PARTITION2 = new TopicPartition(TOPIC, PARTITION2); private static final TopicPartition TOPIC_PARTITION3 = new TopicPartition(TOPIC, PARTITION3); private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(SinkConnector.TOPICS_CONFIG, TOPIC); TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private ConnectorTaskId taskId = new ConnectorTaskId("job", 0); private ConnectorTaskId taskId1 = new ConnectorTaskId("job", 1); private TargetState initialState = TargetState.STARTED; private MockTime time; private WorkerSinkTask workerTask; @Mock private SinkTask sinkTask; private Capture<WorkerSinkTaskContext> sinkTaskContext = EasyMock.newCapture(); private WorkerConfig workerConfig; private MockConnectMetrics metrics; @Mock private PluginClassLoader pluginLoader; @Mock private Converter keyConverter; @Mock private Converter valueConverter; @Mock private HeaderConverter headerConverter; @Mock private TransformationChain<SinkRecord> transformationChain; @Mock private TaskStatus.Listener statusListener; @Mock private KafkaConsumer<byte[], byte[]> consumer; private Capture<ConsumerRebalanceListener> rebalanceListener = EasyMock.newCapture(); private Capture<Pattern> topicsRegex = EasyMock.newCapture(); private long recordsReturnedTp1; private long recordsReturnedTp3; @Before public void setUp() { time = new MockTime(); Map<String, String> workerProps = new HashMap<>(); workerProps.put("key.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("value.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("internal.key.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("internal.value.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("internal.key.converter.schemas.enable", "false"); workerProps.put("internal.value.converter.schemas.enable", "false"); workerProps.put("offset.storage.file.filename", "/tmp/connect.offsets"); workerConfig = new StandaloneConfig(workerProps); pluginLoader = PowerMock.createMock(PluginClassLoader.class); metrics = new MockConnectMetrics(time); recordsReturnedTp1 = 0; recordsReturnedTp3 = 0; } private void createTask(TargetState initialState) { workerTask = new WorkerSinkTask( taskId, sinkTask, statusListener, initialState, workerConfig, ClusterConfigState.EMPTY, metrics, keyConverter, valueConverter, headerConverter, transformationChain, consumer, pluginLoader, time, RetryWithToleranceOperatorTest.NOOP_OPERATOR); } @After public void tearDown() { if (metrics != null) metrics.stop(); } @Test public void testStartPaused() throws Exception { createTask(TargetState.PAUSED); expectInitializeTask(); expectPollInitialAssignment(); Set<TopicPartition> partitions = new HashSet<>(asList(TOPIC_PARTITION, TOPIC_PARTITION2)); EasyMock.expect(consumer.assignment()).andReturn(partitions); consumer.pause(partitions); PowerMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); time.sleep(10000L); assertSinkMetricValue("partition-count", 2); assertTaskMetricValue("status", "paused"); assertTaskMetricValue("running-ratio", 0.0); assertTaskMetricValue("pause-ratio", 1.0); assertTaskMetricValue("offset-commit-max-time-ms", Double.NaN); PowerMock.verifyAll(); } @Test public void testPause() throws Exception { createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); Set<TopicPartition> partitions = new HashSet<>(asList(TOPIC_PARTITION, TOPIC_PARTITION2)); // Pause statusListener.onPause(taskId); EasyMock.expectLastCall(); expectConsumerWakeup(); EasyMock.expect(consumer.assignment()).andReturn(partitions); consumer.pause(partitions); PowerMock.expectLastCall(); // Offset commit as requested when pausing; No records returned by consumer.poll() sinkTask.preCommit(EasyMock.<Map<TopicPartition, OffsetAndMetadata>>anyObject()); EasyMock.expectLastCall().andStubReturn(Collections.emptyMap()); expectConsumerPoll(0); sinkTask.put(Collections.<SinkRecord>emptyList()); EasyMock.expectLastCall(); // And unpause statusListener.onResume(taskId); EasyMock.expectLastCall(); expectConsumerWakeup(); EasyMock.expect(consumer.assignment()).andReturn(new HashSet<>(asList(TOPIC_PARTITION, TOPIC_PARTITION2))); consumer.resume(singleton(TOPIC_PARTITION)); PowerMock.expectLastCall(); consumer.resume(singleton(TOPIC_PARTITION2)); PowerMock.expectLastCall(); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // initial assignment workerTask.iteration(); // fetch some data workerTask.transitionTo(TargetState.PAUSED); time.sleep(10000L); assertSinkMetricValue("partition-count", 2); assertSinkMetricValue("sink-record-read-total", 1.0); assertSinkMetricValue("sink-record-send-total", 1.0); assertSinkMetricValue("sink-record-active-count", 1.0); assertSinkMetricValue("sink-record-active-count-max", 1.0); assertSinkMetricValue("sink-record-active-count-avg", 0.333333); assertSinkMetricValue("offset-commit-seq-no", 0.0); assertSinkMetricValue("offset-commit-completion-rate", 0.0); assertSinkMetricValue("offset-commit-completion-total", 0.0); assertSinkMetricValue("offset-commit-skip-rate", 0.0); assertSinkMetricValue("offset-commit-skip-total", 0.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 1.0); assertTaskMetricValue("batch-size-avg", 0.5); assertTaskMetricValue("offset-commit-max-time-ms", Double.NaN); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 0.0); workerTask.iteration(); // wakeup workerTask.iteration(); // now paused time.sleep(30000L); assertSinkMetricValue("offset-commit-seq-no", 1.0); assertSinkMetricValue("offset-commit-completion-rate", 0.0333); assertSinkMetricValue("offset-commit-completion-total", 1.0); assertSinkMetricValue("offset-commit-skip-rate", 0.0); assertSinkMetricValue("offset-commit-skip-total", 0.0); assertTaskMetricValue("status", "paused"); assertTaskMetricValue("running-ratio", 0.25); assertTaskMetricValue("pause-ratio", 0.75); workerTask.transitionTo(TargetState.STARTED); workerTask.iteration(); // wakeup workerTask.iteration(); // now unpaused //printMetrics(); PowerMock.verifyAll(); } @Test public void testPollRedelivery() throws Exception { createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); // If a retriable exception is thrown, we should redeliver the same batch, pausing the consumer in the meantime expectConsumerPoll(1); expectConversionAndTransformation(1); Capture<Collection<SinkRecord>> records = EasyMock.newCapture(CaptureType.ALL); sinkTask.put(EasyMock.capture(records)); EasyMock.expectLastCall().andThrow(new RetriableException("retry")); // Pause HashSet<TopicPartition> partitions = new HashSet<>(asList(TOPIC_PARTITION, TOPIC_PARTITION2)); EasyMock.expect(consumer.assignment()).andReturn(partitions); consumer.pause(partitions); PowerMock.expectLastCall(); // Retry delivery should succeed expectConsumerPoll(0); sinkTask.put(EasyMock.capture(records)); EasyMock.expectLastCall(); // And unpause EasyMock.expect(consumer.assignment()).andReturn(partitions); consumer.resume(singleton(TOPIC_PARTITION)); PowerMock.expectLastCall(); consumer.resume(singleton(TOPIC_PARTITION2)); PowerMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); time.sleep(10000L); assertSinkMetricValue("partition-count", 2); assertSinkMetricValue("sink-record-read-total", 0.0); assertSinkMetricValue("sink-record-send-total", 0.0); assertSinkMetricValue("sink-record-active-count", 0.0); assertSinkMetricValue("sink-record-active-count-max", 0.0); assertSinkMetricValue("sink-record-active-count-avg", 0.0); assertSinkMetricValue("offset-commit-seq-no", 0.0); assertSinkMetricValue("offset-commit-completion-rate", 0.0); assertSinkMetricValue("offset-commit-completion-total", 0.0); assertSinkMetricValue("offset-commit-skip-rate", 0.0); assertSinkMetricValue("offset-commit-skip-total", 0.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 0.0); assertTaskMetricValue("batch-size-avg", 0.0); assertTaskMetricValue("offset-commit-max-time-ms", Double.NaN); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 0.0); workerTask.iteration(); workerTask.iteration(); time.sleep(30000L); assertSinkMetricValue("sink-record-read-total", 1.0); assertSinkMetricValue("sink-record-send-total", 1.0); assertSinkMetricValue("sink-record-active-count", 1.0); assertSinkMetricValue("sink-record-active-count-max", 1.0); assertSinkMetricValue("sink-record-active-count-avg", 0.5); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("batch-size-max", 1.0); assertTaskMetricValue("batch-size-avg", 0.5); PowerMock.verifyAll(); } @Test public void testErrorInRebalancePartitionRevocation() throws Exception { RuntimeException exception = new RuntimeException("Revocation error"); createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectRebalanceRevocationError(exception); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); try { workerTask.iteration(); fail("Poll should have raised the rebalance exception"); } catch (RuntimeException e) { assertEquals(exception, e); } PowerMock.verifyAll(); } @Test public void testErrorInRebalancePartitionAssignment() throws Exception { RuntimeException exception = new RuntimeException("Assignment error"); createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectRebalanceAssignmentError(exception); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); try { workerTask.iteration(); fail("Poll should have raised the rebalance exception"); } catch (RuntimeException e) { assertEquals(exception, e); } PowerMock.verifyAll(); } @Test public void testWakeupInCommitSyncCausesRetry() throws Exception { createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final List<TopicPartition> partitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2); final Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(); offsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); offsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); sinkTask.preCommit(offsets); EasyMock.expectLastCall().andReturn(offsets); // first one raises wakeup consumer.commitSync(EasyMock.<Map<TopicPartition, OffsetAndMetadata>>anyObject()); EasyMock.expectLastCall().andThrow(new WakeupException()); // we should retry and complete the commit consumer.commitSync(EasyMock.<Map<TopicPartition, OffsetAndMetadata>>anyObject()); EasyMock.expectLastCall(); sinkTask.close(new HashSet<>(partitions)); EasyMock.expectLastCall(); EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET); EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET); sinkTask.open(partitions); EasyMock.expectLastCall(); EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andAnswer( new IAnswer<ConsumerRecords<byte[], byte[]>>() { @Override public ConsumerRecords<byte[], byte[]> answer() throws Throwable { rebalanceListener.getValue().onPartitionsRevoked(partitions); rebalanceListener.getValue().onPartitionsAssigned(partitions); return ConsumerRecords.empty(); } }); EasyMock.expect(consumer.assignment()).andReturn(new HashSet<>(partitions)); consumer.resume(Collections.singleton(TOPIC_PARTITION)); EasyMock.expectLastCall(); consumer.resume(Collections.singleton(TOPIC_PARTITION2)); EasyMock.expectLastCall(); statusListener.onResume(taskId); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); time.sleep(30000L); workerTask.initializeAndStart(); time.sleep(30000L); workerTask.iteration(); // poll for initial assignment time.sleep(30000L); workerTask.iteration(); // first record delivered workerTask.iteration(); // now rebalance with the wakeup triggered time.sleep(30000L); assertSinkMetricValue("partition-count", 2); assertSinkMetricValue("sink-record-read-total", 1.0); assertSinkMetricValue("sink-record-send-total", 1.0); assertSinkMetricValue("sink-record-active-count", 0.0); assertSinkMetricValue("sink-record-active-count-max", 1.0); assertSinkMetricValue("sink-record-active-count-avg", 0.33333); assertSinkMetricValue("offset-commit-seq-no", 1.0); assertSinkMetricValue("offset-commit-completion-total", 1.0); assertSinkMetricValue("offset-commit-skip-total", 0.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 1.0); assertTaskMetricValue("batch-size-avg", 1.0); assertTaskMetricValue("offset-commit-max-time-ms", 0.0); assertTaskMetricValue("offset-commit-avg-time-ms", 0.0); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 1.0); PowerMock.verifyAll(); } @Test public void testRequestCommit() throws Exception { createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(); offsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); offsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); sinkTask.preCommit(offsets); EasyMock.expectLastCall().andReturn(offsets); final Capture<OffsetCommitCallback> callback = EasyMock.newCapture(); consumer.commitAsync(EasyMock.eq(offsets), EasyMock.capture(callback)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { callback.getValue().onComplete(offsets, null); return null; } }); expectConsumerPoll(0); sinkTask.put(Collections.<SinkRecord>emptyList()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); // Initial assignment time.sleep(30000L); workerTask.iteration(); assertSinkMetricValue("partition-count", 2); // First record delivered workerTask.iteration(); assertSinkMetricValue("partition-count", 2); assertSinkMetricValue("sink-record-read-total", 1.0); assertSinkMetricValue("sink-record-send-total", 1.0); assertSinkMetricValue("sink-record-active-count", 1.0); assertSinkMetricValue("sink-record-active-count-max", 1.0); assertSinkMetricValue("sink-record-active-count-avg", 0.333333); assertSinkMetricValue("offset-commit-seq-no", 0.0); assertSinkMetricValue("offset-commit-completion-total", 0.0); assertSinkMetricValue("offset-commit-skip-total", 0.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 1.0); assertTaskMetricValue("batch-size-avg", 0.5); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 0.0); sinkTaskContext.getValue().requestCommit(); assertTrue(sinkTaskContext.getValue().isCommitRequested()); assertNotEquals(offsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); time.sleep(10000L); workerTask.iteration(); // triggers the commit time.sleep(10000L); assertFalse(sinkTaskContext.getValue().isCommitRequested()); // should have been cleared assertEquals(offsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); assertEquals(0, workerTask.commitFailures()); assertSinkMetricValue("partition-count", 2); assertSinkMetricValue("sink-record-read-total", 1.0); assertSinkMetricValue("sink-record-send-total", 1.0); assertSinkMetricValue("sink-record-active-count", 0.0); assertSinkMetricValue("sink-record-active-count-max", 1.0); assertSinkMetricValue("sink-record-active-count-avg", 0.2); assertSinkMetricValue("offset-commit-seq-no", 1.0); assertSinkMetricValue("offset-commit-completion-total", 1.0); assertSinkMetricValue("offset-commit-skip-total", 0.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 1.0); assertTaskMetricValue("batch-size-avg", 0.33333); assertTaskMetricValue("offset-commit-max-time-ms", 0.0); assertTaskMetricValue("offset-commit-avg-time-ms", 0.0); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 1.0); PowerMock.verifyAll(); } @Test public void testPreCommit() throws Exception { createTask(initialState); expectInitializeTask(); // iter 1 expectPollInitialAssignment(); // iter 2 expectConsumerPoll(2); expectConversionAndTransformation(2); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final Map<TopicPartition, OffsetAndMetadata> workerStartingOffsets = new HashMap<>(); workerStartingOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET)); workerStartingOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); final Map<TopicPartition, OffsetAndMetadata> workerCurrentOffsets = new HashMap<>(); workerCurrentOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 2)); workerCurrentOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); final Map<TopicPartition, OffsetAndMetadata> taskOffsets = new HashMap<>(); taskOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); // act like FIRST_OFFSET+2 has not yet been flushed by the task taskOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET + 1)); // should be ignored because > current offset taskOffsets.put(new TopicPartition(TOPIC, 3), new OffsetAndMetadata(FIRST_OFFSET)); // should be ignored because this partition is not assigned final Map<TopicPartition, OffsetAndMetadata> committableOffsets = new HashMap<>(); committableOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); committableOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); sinkTask.preCommit(workerCurrentOffsets); EasyMock.expectLastCall().andReturn(taskOffsets); // Expect extra invalid topic partition to be filtered, which causes the consumer assignment to be logged EasyMock.expect(consumer.assignment()).andReturn(workerCurrentOffsets.keySet()); final Capture<OffsetCommitCallback> callback = EasyMock.newCapture(); consumer.commitAsync(EasyMock.eq(committableOffsets), EasyMock.capture(callback)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { callback.getValue().onComplete(committableOffsets, null); return null; } }); expectConsumerPoll(0); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // iter 1 -- initial assignment assertEquals(workerStartingOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "currentOffsets")); workerTask.iteration(); // iter 2 -- deliver 2 records assertEquals(workerCurrentOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "currentOffsets")); assertEquals(workerStartingOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); sinkTaskContext.getValue().requestCommit(); workerTask.iteration(); // iter 3 -- commit assertEquals(committableOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); PowerMock.verifyAll(); } @Test public void testIgnoredCommit() throws Exception { createTask(initialState); expectInitializeTask(); // iter 1 expectPollInitialAssignment(); // iter 2 expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final Map<TopicPartition, OffsetAndMetadata> workerStartingOffsets = new HashMap<>(); workerStartingOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET)); workerStartingOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); final Map<TopicPartition, OffsetAndMetadata> workerCurrentOffsets = new HashMap<>(); workerCurrentOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); workerCurrentOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); // iter 3 sinkTask.preCommit(workerCurrentOffsets); EasyMock.expectLastCall().andReturn(workerStartingOffsets); // no actual consumer.commit() triggered expectConsumerPoll(0); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // iter 1 -- initial assignment assertEquals(workerStartingOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "currentOffsets")); assertEquals(workerStartingOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); workerTask.iteration(); // iter 2 -- deliver 2 records sinkTaskContext.getValue().requestCommit(); workerTask.iteration(); // iter 3 -- commit PowerMock.verifyAll(); } // Test that the commitTimeoutMs timestamp is correctly computed and checked in WorkerSinkTask.iteration() // when there is a long running commit in process. See KAFKA-4942 for more information. @Test public void testLongRunningCommitWithoutTimeout() throws Exception { createTask(initialState); expectInitializeTask(); // iter 1 expectPollInitialAssignment(); // iter 2 expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final Map<TopicPartition, OffsetAndMetadata> workerStartingOffsets = new HashMap<>(); workerStartingOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET)); workerStartingOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); final Map<TopicPartition, OffsetAndMetadata> workerCurrentOffsets = new HashMap<>(); workerCurrentOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); workerCurrentOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); // iter 3 - note that we return the current offset to indicate they should be committed sinkTask.preCommit(workerCurrentOffsets); EasyMock.expectLastCall().andReturn(workerCurrentOffsets); // We need to delay the result of trying to commit offsets to Kafka via the consumer.commitAsync // method. We do this so that we can test that we do not erroneously mark a commit as timed out // while it is still running and under time. To fake this for tests we have the commit run in a // separate thread and wait for a latch which we control back in the main thread. final ExecutorService executor = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(1); consumer.commitAsync(EasyMock.eq(workerCurrentOffsets), EasyMock.<OffsetCommitCallback>anyObject()); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @SuppressWarnings("unchecked") @Override public Void answer() throws Throwable { // Grab the arguments passed to the consumer.commitAsync method final Object[] args = EasyMock.getCurrentArguments(); final Map<TopicPartition, OffsetAndMetadata> offsets = (Map<TopicPartition, OffsetAndMetadata>) args[0]; final OffsetCommitCallback callback = (OffsetCommitCallback) args[1]; executor.execute(new Runnable() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } callback.onComplete(offsets, null); } }); return null; } }); // no actual consumer.commit() triggered expectConsumerPoll(0); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // iter 1 -- initial assignment assertEquals(workerStartingOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "currentOffsets")); assertEquals(workerStartingOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); time.sleep(WorkerConfig.OFFSET_COMMIT_TIMEOUT_MS_DEFAULT); workerTask.iteration(); // iter 2 -- deliver 2 records sinkTaskContext.getValue().requestCommit(); workerTask.iteration(); // iter 3 -- commit in progress // Make sure the "committing" flag didn't immediately get flipped back to false due to an incorrect timeout assertTrue("Expected worker to be in the process of committing offsets", workerTask.isCommitting()); // Let the async commit finish and wait for it to end latch.countDown(); executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); assertEquals(workerCurrentOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "currentOffsets")); assertEquals(workerCurrentOffsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); PowerMock.verifyAll(); } // Verify that when commitAsync is called but the supplied callback is not called by the consumer before a // rebalance occurs, the async callback does not reset the last committed offset from the rebalance. // See KAFKA-5731 for more information. @Test public void testCommitWithOutOfOrderCallback() throws Exception { createTask(initialState); expectInitializeTask(); // iter 1 expectPollInitialAssignment(); // iter 2 expectConsumerPoll(1); expectConversionAndTransformation(4); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final Map<TopicPartition, OffsetAndMetadata> workerStartingOffsets = new HashMap<>(); workerStartingOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET)); workerStartingOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); final Map<TopicPartition, OffsetAndMetadata> workerCurrentOffsets = new HashMap<>(); workerCurrentOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); workerCurrentOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); final List<TopicPartition> originalPartitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2); final List<TopicPartition> rebalancedPartitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2, TOPIC_PARTITION3); final Map<TopicPartition, OffsetAndMetadata> rebalanceOffsets = new HashMap<>(); rebalanceOffsets.put(TOPIC_PARTITION, workerCurrentOffsets.get(TOPIC_PARTITION)); rebalanceOffsets.put(TOPIC_PARTITION2, workerCurrentOffsets.get(TOPIC_PARTITION2)); rebalanceOffsets.put(TOPIC_PARTITION3, new OffsetAndMetadata(FIRST_OFFSET)); final Map<TopicPartition, OffsetAndMetadata> postRebalanceCurrentOffsets = new HashMap<>(); postRebalanceCurrentOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 3)); postRebalanceCurrentOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); postRebalanceCurrentOffsets.put(TOPIC_PARTITION3, new OffsetAndMetadata(FIRST_OFFSET + 2)); // iter 3 - note that we return the current offset to indicate they should be committed sinkTask.preCommit(workerCurrentOffsets); EasyMock.expectLastCall().andReturn(workerCurrentOffsets); // We need to delay the result of trying to commit offsets to Kafka via the consumer.commitAsync // method. We do this so that we can test that the callback is not called until after the rebalance // changes the lastCommittedOffsets. To fake this for tests we have the commitAsync build a function // that will call the callback with the appropriate parameters, and we'll run that function later. final AtomicReference<Runnable> asyncCallbackRunner = new AtomicReference<>(); final AtomicBoolean asyncCallbackRan = new AtomicBoolean(); consumer.commitAsync(EasyMock.eq(workerCurrentOffsets), EasyMock.<OffsetCommitCallback>anyObject()); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @SuppressWarnings("unchecked") @Override public Void answer() throws Throwable { // Grab the arguments passed to the consumer.commitAsync method final Object[] args = EasyMock.getCurrentArguments(); final Map<TopicPartition, OffsetAndMetadata> offsets = (Map<TopicPartition, OffsetAndMetadata>) args[0]; final OffsetCommitCallback callback = (OffsetCommitCallback) args[1]; asyncCallbackRunner.set(new Runnable() { @Override public void run() { callback.onComplete(offsets, null); asyncCallbackRan.set(true); } }); return null; } }); // Expect the next poll to discover and perform the rebalance, THEN complete the previous callback handler, // and then return one record for TP1 and one for TP3. final AtomicBoolean rebalanced = new AtomicBoolean(); EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andAnswer( new IAnswer<ConsumerRecords<byte[], byte[]>>() { @Override public ConsumerRecords<byte[], byte[]> answer() throws Throwable { // Rebalance always begins with revoking current partitions ... rebalanceListener.getValue().onPartitionsRevoked(originalPartitions); // Respond to the rebalance Map<TopicPartition, Long> offsets = new HashMap<>(); offsets.put(TOPIC_PARTITION, rebalanceOffsets.get(TOPIC_PARTITION).offset()); offsets.put(TOPIC_PARTITION2, rebalanceOffsets.get(TOPIC_PARTITION2).offset()); offsets.put(TOPIC_PARTITION3, rebalanceOffsets.get(TOPIC_PARTITION3).offset()); sinkTaskContext.getValue().offset(offsets); rebalanceListener.getValue().onPartitionsAssigned(rebalancedPartitions); rebalanced.set(true); // Run the previous async commit handler asyncCallbackRunner.get().run(); // And prep the two records to return long timestamp = RecordBatch.NO_TIMESTAMP; TimestampType timestampType = TimestampType.NO_TIMESTAMP_TYPE; List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>(); records.add(new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + recordsReturnedTp1 + 1, timestamp, timestampType, 0L, 0, 0, RAW_KEY, RAW_VALUE)); records.add(new ConsumerRecord<>(TOPIC, PARTITION3, FIRST_OFFSET + recordsReturnedTp3 + 1, timestamp, timestampType, 0L, 0, 0, RAW_KEY, RAW_VALUE)); recordsReturnedTp1 += 1; recordsReturnedTp3 += 1; return new ConsumerRecords<>(Collections.singletonMap(new TopicPartition(TOPIC, PARTITION), records)); } }); // onPartitionsRevoked sinkTask.preCommit(workerCurrentOffsets); EasyMock.expectLastCall().andReturn(workerCurrentOffsets); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); sinkTask.close(workerCurrentOffsets.keySet()); EasyMock.expectLastCall(); consumer.commitSync(workerCurrentOffsets); EasyMock.expectLastCall(); // onPartitionsAssigned - step 1 final long offsetTp1 = rebalanceOffsets.get(TOPIC_PARTITION).offset(); final long offsetTp2 = rebalanceOffsets.get(TOPIC_PARTITION2).offset(); final long offsetTp3 = rebalanceOffsets.get(TOPIC_PARTITION3).offset(); EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(offsetTp1); EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(offsetTp2); EasyMock.expect(consumer.position(TOPIC_PARTITION3)).andReturn(offsetTp3); // onPartitionsAssigned - step 2 sinkTask.open(rebalancedPartitions); EasyMock.expectLastCall(); // onPartitionsAssigned - step 3 rewind consumer.seek(TOPIC_PARTITION, offsetTp1); EasyMock.expectLastCall(); consumer.seek(TOPIC_PARTITION2, offsetTp2); EasyMock.expectLastCall(); consumer.seek(TOPIC_PARTITION3, offsetTp3); EasyMock.expectLastCall(); // iter 4 - note that we return the current offset to indicate they should be committed sinkTask.preCommit(postRebalanceCurrentOffsets); EasyMock.expectLastCall().andReturn(postRebalanceCurrentOffsets); final Capture<OffsetCommitCallback> callback = EasyMock.newCapture(); consumer.commitAsync(EasyMock.eq(postRebalanceCurrentOffsets), EasyMock.capture(callback)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { callback.getValue().onComplete(postRebalanceCurrentOffsets, null); return null; } }); // no actual consumer.commit() triggered expectConsumerPoll(1); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // iter 1 -- initial assignment assertEquals(workerStartingOffsets, Whitebox.getInternalState(workerTask, "currentOffsets")); assertEquals(workerStartingOffsets, Whitebox.getInternalState(workerTask, "lastCommittedOffsets")); time.sleep(WorkerConfig.OFFSET_COMMIT_TIMEOUT_MS_DEFAULT); workerTask.iteration(); // iter 2 -- deliver 2 records sinkTaskContext.getValue().requestCommit(); workerTask.iteration(); // iter 3 -- commit in progress assertSinkMetricValue("partition-count", 3); assertSinkMetricValue("sink-record-read-total", 3.0); assertSinkMetricValue("sink-record-send-total", 3.0); assertSinkMetricValue("sink-record-active-count", 4.0); assertSinkMetricValue("sink-record-active-count-max", 4.0); assertSinkMetricValue("sink-record-active-count-avg", 0.71429); assertSinkMetricValue("offset-commit-seq-no", 2.0); assertSinkMetricValue("offset-commit-completion-total", 1.0); assertSinkMetricValue("offset-commit-skip-total", 1.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 2.0); assertTaskMetricValue("batch-size-avg", 1.0); assertTaskMetricValue("offset-commit-max-time-ms", 0.0); assertTaskMetricValue("offset-commit-avg-time-ms", 0.0); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 1.0); assertTrue(asyncCallbackRan.get()); assertTrue(rebalanced.get()); // Check that the offsets were not reset by the out-of-order async commit callback assertEquals(postRebalanceCurrentOffsets, Whitebox.getInternalState(workerTask, "currentOffsets")); assertEquals(rebalanceOffsets, Whitebox.getInternalState(workerTask, "lastCommittedOffsets")); time.sleep(WorkerConfig.OFFSET_COMMIT_TIMEOUT_MS_DEFAULT); sinkTaskContext.getValue().requestCommit(); workerTask.iteration(); // iter 4 -- commit in progress // Check that the offsets were not reset by the out-of-order async commit callback assertEquals(postRebalanceCurrentOffsets, Whitebox.getInternalState(workerTask, "currentOffsets")); assertEquals(postRebalanceCurrentOffsets, Whitebox.getInternalState(workerTask, "lastCommittedOffsets")); assertSinkMetricValue("partition-count", 3); assertSinkMetricValue("sink-record-read-total", 4.0); assertSinkMetricValue("sink-record-send-total", 4.0); assertSinkMetricValue("sink-record-active-count", 0.0); assertSinkMetricValue("sink-record-active-count-max", 4.0); assertSinkMetricValue("sink-record-active-count-avg", 0.5555555); assertSinkMetricValue("offset-commit-seq-no", 3.0); assertSinkMetricValue("offset-commit-completion-total", 2.0); assertSinkMetricValue("offset-commit-skip-total", 1.0); assertTaskMetricValue("status", "running"); assertTaskMetricValue("running-ratio", 1.0); assertTaskMetricValue("pause-ratio", 0.0); assertTaskMetricValue("batch-size-max", 2.0); assertTaskMetricValue("batch-size-avg", 1.0); assertTaskMetricValue("offset-commit-max-time-ms", 0.0); assertTaskMetricValue("offset-commit-avg-time-ms", 0.0); assertTaskMetricValue("offset-commit-failure-percentage", 0.0); assertTaskMetricValue("offset-commit-success-percentage", 1.0); PowerMock.verifyAll(); } @Test public void testDeliveryWithMutatingTransform() throws Exception { createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectConsumerPoll(1); expectConversionAndTransformation(1, "newtopic_"); sinkTask.put(EasyMock.<Collection<SinkRecord>>anyObject()); EasyMock.expectLastCall(); final Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(); offsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); offsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET)); sinkTask.preCommit(offsets); EasyMock.expectLastCall().andReturn(offsets); final Capture<OffsetCommitCallback> callback = EasyMock.newCapture(); consumer.commitAsync(EasyMock.eq(offsets), EasyMock.capture(callback)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { callback.getValue().onComplete(offsets, null); return null; } }); expectConsumerPoll(0); sinkTask.put(Collections.<SinkRecord>emptyList()); EasyMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // initial assignment workerTask.iteration(); // first record delivered sinkTaskContext.getValue().requestCommit(); assertTrue(sinkTaskContext.getValue().isCommitRequested()); assertNotEquals(offsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); workerTask.iteration(); // triggers the commit assertFalse(sinkTaskContext.getValue().isCommitRequested()); // should have been cleared assertEquals(offsets, Whitebox.<Map<TopicPartition, OffsetAndMetadata>>getInternalState(workerTask, "lastCommittedOffsets")); assertEquals(0, workerTask.commitFailures()); assertEquals(1.0, metrics.currentMetricValueAsDouble(workerTask.taskMetricsGroup().metricGroup(), "batch-size-max"), 0.0001); PowerMock.verifyAll(); } @Test public void testMissingTimestampPropagation() throws Exception { createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectConsumerPoll(1, RecordBatch.NO_TIMESTAMP, TimestampType.CREATE_TIME); expectConversionAndTransformation(1); Capture<Collection<SinkRecord>> records = EasyMock.newCapture(CaptureType.ALL); sinkTask.put(EasyMock.capture(records)); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // iter 1 -- initial assignment workerTask.iteration(); // iter 2 -- deliver 1 record SinkRecord record = records.getValue().iterator().next(); // we expect null for missing timestamp, the sentinel value of Record.NO_TIMESTAMP is Kafka's API assertEquals(null, record.timestamp()); assertEquals(TimestampType.CREATE_TIME, record.timestampType()); PowerMock.verifyAll(); } @Test public void testTimestampPropagation() throws Exception { final Long timestamp = System.currentTimeMillis(); final TimestampType timestampType = TimestampType.CREATE_TIME; createTask(initialState); expectInitializeTask(); expectPollInitialAssignment(); expectConsumerPoll(1, timestamp, timestampType); expectConversionAndTransformation(1); Capture<Collection<SinkRecord>> records = EasyMock.newCapture(CaptureType.ALL); sinkTask.put(EasyMock.capture(records)); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); workerTask.initializeAndStart(); workerTask.iteration(); // iter 1 -- initial assignment workerTask.iteration(); // iter 2 -- deliver 1 record SinkRecord record = records.getValue().iterator().next(); assertEquals(timestamp, record.timestamp()); assertEquals(timestampType, record.timestampType()); PowerMock.verifyAll(); } @Test public void testTopicsRegex() throws Exception { Map<String, String> props = new HashMap<>(TASK_PROPS); props.remove("topics"); props.put("topics.regex", "te.*"); TaskConfig taskConfig = new TaskConfig(props); createTask(TargetState.PAUSED); consumer.subscribe(EasyMock.capture(topicsRegex), EasyMock.capture(rebalanceListener)); PowerMock.expectLastCall(); sinkTask.initialize(EasyMock.capture(sinkTaskContext)); PowerMock.expectLastCall(); sinkTask.start(props); PowerMock.expectLastCall(); expectPollInitialAssignment(); Set<TopicPartition> partitions = new HashSet<>(asList(TOPIC_PARTITION, TOPIC_PARTITION2)); EasyMock.expect(consumer.assignment()).andReturn(partitions); consumer.pause(partitions); PowerMock.expectLastCall(); PowerMock.replayAll(); workerTask.initialize(taskConfig); workerTask.initializeAndStart(); workerTask.iteration(); time.sleep(10000L); PowerMock.verifyAll(); } @Test public void testMetricsGroup() { SinkTaskMetricsGroup group = new SinkTaskMetricsGroup(taskId, metrics); SinkTaskMetricsGroup group1 = new SinkTaskMetricsGroup(taskId1, metrics); for (int i = 0; i != 10; ++i) { group.recordRead(1); group.recordSend(2); group.recordPut(3); group.recordPartitionCount(4); group.recordOffsetSequenceNumber(5); } Map<TopicPartition, OffsetAndMetadata> committedOffsets = new HashMap<>(); committedOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 1)); group.recordCommittedOffsets(committedOffsets); Map<TopicPartition, OffsetAndMetadata> consumedOffsets = new HashMap<>(); consumedOffsets.put(TOPIC_PARTITION, new OffsetAndMetadata(FIRST_OFFSET + 10)); group.recordConsumedOffsets(consumedOffsets); for (int i = 0; i != 20; ++i) { group1.recordRead(1); group1.recordSend(2); group1.recordPut(30); group1.recordPartitionCount(40); group1.recordOffsetSequenceNumber(50); } committedOffsets = new HashMap<>(); committedOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET + 2)); committedOffsets.put(TOPIC_PARTITION3, new OffsetAndMetadata(FIRST_OFFSET + 3)); group1.recordCommittedOffsets(committedOffsets); consumedOffsets = new HashMap<>(); consumedOffsets.put(TOPIC_PARTITION2, new OffsetAndMetadata(FIRST_OFFSET + 20)); consumedOffsets.put(TOPIC_PARTITION3, new OffsetAndMetadata(FIRST_OFFSET + 30)); group1.recordConsumedOffsets(consumedOffsets); assertEquals(0.333, metrics.currentMetricValueAsDouble(group.metricGroup(), "sink-record-read-rate"), 0.001d); assertEquals(0.667, metrics.currentMetricValueAsDouble(group.metricGroup(), "sink-record-send-rate"), 0.001d); assertEquals(9, metrics.currentMetricValueAsDouble(group.metricGroup(), "sink-record-active-count"), 0.001d); assertEquals(4, metrics.currentMetricValueAsDouble(group.metricGroup(), "partition-count"), 0.001d); assertEquals(5, metrics.currentMetricValueAsDouble(group.metricGroup(), "offset-commit-seq-no"), 0.001d); assertEquals(3, metrics.currentMetricValueAsDouble(group.metricGroup(), "put-batch-max-time-ms"), 0.001d); // Close the group group.close(); for (MetricName metricName : group.metricGroup().metrics().metrics().keySet()) { // Metrics for this group should no longer exist assertFalse(group.metricGroup().groupId().includes(metricName)); } // Sensors for this group should no longer exist assertNull(group.metricGroup().metrics().getSensor("source-record-poll")); assertNull(group.metricGroup().metrics().getSensor("source-record-write")); assertNull(group.metricGroup().metrics().getSensor("poll-batch-time")); assertEquals(0.667, metrics.currentMetricValueAsDouble(group1.metricGroup(), "sink-record-read-rate"), 0.001d); assertEquals(1.333, metrics.currentMetricValueAsDouble(group1.metricGroup(), "sink-record-send-rate"), 0.001d); assertEquals(45, metrics.currentMetricValueAsDouble(group1.metricGroup(), "sink-record-active-count"), 0.001d); assertEquals(40, metrics.currentMetricValueAsDouble(group1.metricGroup(), "partition-count"), 0.001d); assertEquals(50, metrics.currentMetricValueAsDouble(group1.metricGroup(), "offset-commit-seq-no"), 0.001d); assertEquals(30, metrics.currentMetricValueAsDouble(group1.metricGroup(), "put-batch-max-time-ms"), 0.001d); } private void expectInitializeTask() throws Exception { consumer.subscribe(EasyMock.eq(asList(TOPIC)), EasyMock.capture(rebalanceListener)); PowerMock.expectLastCall(); sinkTask.initialize(EasyMock.capture(sinkTaskContext)); PowerMock.expectLastCall(); sinkTask.start(TASK_PROPS); PowerMock.expectLastCall(); } private void expectRebalanceRevocationError(RuntimeException e) { final List<TopicPartition> partitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2); sinkTask.close(new HashSet<>(partitions)); EasyMock.expectLastCall().andThrow(e); sinkTask.preCommit(EasyMock.<Map<TopicPartition, OffsetAndMetadata>>anyObject()); EasyMock.expectLastCall().andReturn(Collections.emptyMap()); EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andAnswer( new IAnswer<ConsumerRecords<byte[], byte[]>>() { @Override public ConsumerRecords<byte[], byte[]> answer() throws Throwable { rebalanceListener.getValue().onPartitionsRevoked(partitions); return ConsumerRecords.empty(); } }); } private void expectRebalanceAssignmentError(RuntimeException e) { final List<TopicPartition> partitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2); sinkTask.close(new HashSet<>(partitions)); EasyMock.expectLastCall(); sinkTask.preCommit(EasyMock.<Map<TopicPartition, OffsetAndMetadata>>anyObject()); EasyMock.expectLastCall().andReturn(Collections.emptyMap()); EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET); EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET); sinkTask.open(partitions); EasyMock.expectLastCall().andThrow(e); EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andAnswer( new IAnswer<ConsumerRecords<byte[], byte[]>>() { @Override public ConsumerRecords<byte[], byte[]> answer() throws Throwable { rebalanceListener.getValue().onPartitionsRevoked(partitions); rebalanceListener.getValue().onPartitionsAssigned(partitions); return ConsumerRecords.empty(); } }); } private void expectPollInitialAssignment() { final List<TopicPartition> partitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2); sinkTask.open(partitions); EasyMock.expectLastCall(); EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andAnswer(new IAnswer<ConsumerRecords<byte[], byte[]>>() { @Override public ConsumerRecords<byte[], byte[]> answer() throws Throwable { rebalanceListener.getValue().onPartitionsAssigned(partitions); return ConsumerRecords.empty(); } }); EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET); EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET); sinkTask.put(Collections.<SinkRecord>emptyList()); EasyMock.expectLastCall(); } private void expectConsumerWakeup() { consumer.wakeup(); EasyMock.expectLastCall(); EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andThrow(new WakeupException()); } private void expectConsumerPoll(final int numMessages) { expectConsumerPoll(numMessages, RecordBatch.NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE); } private void expectConsumerPoll(final int numMessages, final long timestamp, final TimestampType timestampType) { EasyMock.expect(consumer.poll(Duration.ofMillis(EasyMock.anyLong()))).andAnswer( new IAnswer<ConsumerRecords<byte[], byte[]>>() { @Override public ConsumerRecords<byte[], byte[]> answer() throws Throwable { List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>(); for (int i = 0; i < numMessages; i++) records.add(new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + recordsReturnedTp1 + i, timestamp, timestampType, 0L, 0, 0, RAW_KEY, RAW_VALUE)); recordsReturnedTp1 += numMessages; return new ConsumerRecords<>( numMessages > 0 ? Collections.singletonMap(new TopicPartition(TOPIC, PARTITION), records) : Collections.<TopicPartition, List<ConsumerRecord<byte[], byte[]>>>emptyMap() ); } }); } private void expectConversionAndTransformation(final int numMessages) { expectConversionAndTransformation(numMessages, null); } private void expectConversionAndTransformation(final int numMessages, final String topicPrefix) { EasyMock.expect(keyConverter.toConnectData(TOPIC, RAW_KEY)).andReturn(new SchemaAndValue(KEY_SCHEMA, KEY)).times(numMessages); EasyMock.expect(valueConverter.toConnectData(TOPIC, RAW_VALUE)).andReturn(new SchemaAndValue(VALUE_SCHEMA, VALUE)).times(numMessages); final Capture<SinkRecord> recordCapture = EasyMock.newCapture(); EasyMock.expect(transformationChain.apply(EasyMock.capture(recordCapture))) .andAnswer(new IAnswer<SinkRecord>() { @Override public SinkRecord answer() { SinkRecord origRecord = recordCapture.getValue(); return topicPrefix != null && !topicPrefix.isEmpty() ? origRecord.newRecord( topicPrefix + origRecord.topic(), origRecord.kafkaPartition(), origRecord.keySchema(), origRecord.key(), origRecord.valueSchema(), origRecord.value(), origRecord.timestamp() ) : origRecord; } }).times(numMessages); } private void assertSinkMetricValue(String name, double expected) { MetricGroup sinkTaskGroup = workerTask.sinkTaskMetricsGroup().metricGroup(); double measured = metrics.currentMetricValueAsDouble(sinkTaskGroup, name); assertEquals(expected, measured, 0.001d); } private void assertTaskMetricValue(String name, double expected) { MetricGroup taskGroup = workerTask.taskMetricsGroup().metricGroup(); double measured = metrics.currentMetricValueAsDouble(taskGroup, name); assertEquals(expected, measured, 0.001d); } private void assertTaskMetricValue(String name, String expected) { MetricGroup taskGroup = workerTask.taskMetricsGroup().metricGroup(); String measured = metrics.currentMetricValueAsString(taskGroup, name); assertEquals(expected, measured); } private void printMetrics() { System.out.println(); sinkMetricValue("sink-record-read-rate"); sinkMetricValue("sink-record-read-total"); sinkMetricValue("sink-record-send-rate"); sinkMetricValue("sink-record-send-total"); sinkMetricValue("sink-record-active-count"); sinkMetricValue("sink-record-active-count-max"); sinkMetricValue("sink-record-active-count-avg"); sinkMetricValue("partition-count"); sinkMetricValue("offset-commit-seq-no"); sinkMetricValue("offset-commit-completion-rate"); sinkMetricValue("offset-commit-completion-total"); sinkMetricValue("offset-commit-skip-rate"); sinkMetricValue("offset-commit-skip-total"); sinkMetricValue("put-batch-max-time-ms"); sinkMetricValue("put-batch-avg-time-ms"); taskMetricValue("status-unassigned"); taskMetricValue("status-running"); taskMetricValue("status-paused"); taskMetricValue("status-failed"); taskMetricValue("status-destroyed"); taskMetricValue("running-ratio"); taskMetricValue("pause-ratio"); taskMetricValue("offset-commit-max-time-ms"); taskMetricValue("offset-commit-avg-time-ms"); taskMetricValue("batch-size-max"); taskMetricValue("batch-size-avg"); taskMetricValue("offset-commit-failure-percentage"); taskMetricValue("offset-commit-success-percentage"); } private double sinkMetricValue(String metricName) { MetricGroup sinkTaskGroup = workerTask.sinkTaskMetricsGroup().metricGroup(); double value = metrics.currentMetricValueAsDouble(sinkTaskGroup, metricName); System.out.println("** " + metricName + "=" + value); return value; } private double taskMetricValue(String metricName) { MetricGroup taskGroup = workerTask.taskMetricsGroup().metricGroup(); double value = metrics.currentMetricValueAsDouble(taskGroup, metricName); System.out.println("** " + metricName + "=" + value); return value; } private void assertMetrics(int minimumPollCountExpected) { MetricGroup sinkTaskGroup = workerTask.sinkTaskMetricsGroup().metricGroup(); MetricGroup taskGroup = workerTask.taskMetricsGroup().metricGroup(); double readRate = metrics.currentMetricValueAsDouble(sinkTaskGroup, "sink-record-read-rate"); double readTotal = metrics.currentMetricValueAsDouble(sinkTaskGroup, "sink-record-read-total"); double sendRate = metrics.currentMetricValueAsDouble(sinkTaskGroup, "sink-record-send-rate"); double sendTotal = metrics.currentMetricValueAsDouble(sinkTaskGroup, "sink-record-send-total"); } private abstract static class TestSinkTask extends SinkTask { } }
3e0480d3f312106347d5d5eff3bc531b4421b754
2,081
java
Java
proxy/src/main/java/com/td/admin/dao/TaskConfigManageDao.java
tyang513/enterprise.adapter
1b4790b75168415edd6cadcf29cb08c1b3a76ee7
[ "Apache-2.0" ]
null
null
null
proxy/src/main/java/com/td/admin/dao/TaskConfigManageDao.java
tyang513/enterprise.adapter
1b4790b75168415edd6cadcf29cb08c1b3a76ee7
[ "Apache-2.0" ]
null
null
null
proxy/src/main/java/com/td/admin/dao/TaskConfigManageDao.java
tyang513/enterprise.adapter
1b4790b75168415edd6cadcf29cb08c1b3a76ee7
[ "Apache-2.0" ]
1
2022-01-04T14:27:03.000Z
2022-01-04T14:27:03.000Z
30.15942
90
0.751081
1,891
package com.td.admin.dao; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.td.admin.entity.SysProcessConfig; import com.td.admin.entity.SysProcessTaskConfig; import com.td.admin.mapper.SysProcessTaskConfigMapper; import com.td.common.bean.Body; import com.td.common.bean.PageBean; @Service public class TaskConfigManageDao { private static final Logger logger = LoggerFactory.getLogger(TaskConfigManageDao.class); @Autowired private SysProcessTaskConfigMapper finTaskConfigMapper; public PageBean queryTaskConfig(SysProcessTaskConfig record){ logger.debug("查询任务设置====="); Long total = finTaskConfigMapper.queryTotalCount(record); PageBean pageBean = new PageBean(record.getPageNum(), record.getNumPerPage(), total); record.setBeginIndex(pageBean.getFirstResult()); logger.debug("起始查询位置===="+record.getBeginIndex()+"要查询的记录数"+record.getNumPerPage()); List<SysProcessConfig> list = finTaskConfigMapper.queryTaskConfig(record); pageBean.getExtend().put("list", list); return pageBean; } public Body saveTaskConfig(SysProcessTaskConfig record) { Body body = new Body(); logger.info("添加任务设置操作"); record.setCtime(new Date()); finTaskConfigMapper.insertSelective(record); body.setMessage("添加成功"); body.success(); return body; } public Body deleteTaskConfig(SysProcessTaskConfig record) { Body body = new Body(); logger.info("删除任务设置操作"); finTaskConfigMapper.deleteByPrimaryKey(record.getId()); body.setMessage("删除成功"); body.success(); return body; } public Body updateTaskConfig(SysProcessTaskConfig record) { Body body = new Body(); logger.info("更新任务设置操作"); record.setMtime(new Date()); // System.out.println(record.getProcessconfigid() + record.getSystemcode()); finTaskConfigMapper.updateByPrimaryKeySelective(record); body.setMessage("更新成功"); body.success(); return body; } }
3e0480ddd4e767fa7ef3dbcc0ca0740a486d5b90
7,057
java
Java
rs-join-triangle-counter/src/main/java/edu/neu/ccs/TriangleAmplifier.java
siddhesh21ace/mr-jobs
e5e2e0c85ff0efcd808a7ebdf9c00e79140608f2
[ "Apache-2.0" ]
null
null
null
rs-join-triangle-counter/src/main/java/edu/neu/ccs/TriangleAmplifier.java
siddhesh21ace/mr-jobs
e5e2e0c85ff0efcd808a7ebdf9c00e79140608f2
[ "Apache-2.0" ]
null
null
null
rs-join-triangle-counter/src/main/java/edu/neu/ccs/TriangleAmplifier.java
siddhesh21ace/mr-jobs
e5e2e0c85ff0efcd808a7ebdf9c00e79140608f2
[ "Apache-2.0" ]
null
null
null
33.445498
119
0.600964
1,892
package edu.neu.ccs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.MultipleInputs; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TriangleAmplifier extends Configured implements Tool { private static final Logger logger = LogManager.getLogger(TriangleAmplifier.class); private static final String COMMA_SEPARATOR = ","; private static final Long MAX_NODE_ID = 20000L; public static class Step1Mapper extends Mapper<Object, Text, Text, Text> { private Text outkey = new Text(); private Text outvalue = new Text(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String[] splitVals = value.toString().split(COMMA_SEPARATOR); if (splitVals.length != 2) { return; } String node1Val = splitVals[0]; String node2Val = splitVals[1]; if (Long.valueOf(node1Val) >= MAX_NODE_ID || Long.valueOf(node2Val) >= MAX_NODE_ID) return; outkey.set(node2Val); outvalue.set("F" + node1Val); context.write(outkey, outvalue); outkey.set(node1Val); outvalue.set("T" + node2Val); context.write(outkey, outvalue); } } public static class Step1Reducer extends Reducer<Text, Text, Text, Text> { private List<Text> fromList = new ArrayList<>(); private List<Text> toList = new ArrayList<>(); private Text outkey = new Text(); private Text outvalue = new Text(); @Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { fromList.clear(); toList.clear(); Step2Reducer.populateNodes(values, fromList, toList); if (!fromList.isEmpty() && !toList.isEmpty()) { for (Text A : fromList) { outkey.set(A); for (Text B : toList) { outvalue.set("S" + B); context.write(outkey, outvalue); } } } } } public static class Step2Mapper extends Mapper<Object, Text, Text, Text> { private Text outkey = new Text(); private Text outvalue = new Text(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String[] splitVals = value.toString().split(COMMA_SEPARATOR); if (splitVals.length != 2) { return; } String node1Val = splitVals[0]; String node2Val = splitVals[1]; if (node2Val.charAt(0) == 'S') { outkey.set(node1Val); outvalue.set("T" + node2Val.substring(1)); } else { outkey.set(node2Val); outvalue.set("F" + node1Val); } context.write(outkey, outvalue); } } public static class Step2Reducer extends Reducer<Text, Text, Text, Text> { private List<Text> fromList = new ArrayList<>(); private List<Text> toList = new ArrayList<>(); @Override public void reduce(Text key, Iterable<Text> values, Context context) { fromList.clear(); toList.clear(); populateNodes(values, fromList, toList); if (!fromList.isEmpty() && !toList.isEmpty()) { fromList.sort(Comparator.comparing(Text::toString)); for (Text B : toList) { if (Collections.binarySearch(fromList, B) > -1) { context.getCounter(CounterEnum.TRIANGLE_COUNTER).increment(1); } } } } private static void populateNodes(Iterable<Text> values, List<Text> fromList, List<Text> toList) { for (Text text : values) { if (text.charAt(0) == 'F') { fromList.add(new Text(text.toString().substring(1))); } else if (text.charAt(0) == 'T') { toList.add(new Text(text.toString().substring(1))); } } } } /** * @param args - input values */ public static void main(final String[] args) { if (args.length != 3) { throw new IllegalArgumentException("Two arguments required:\n<input-dir> <output-dir>"); } try { ToolRunner.run(new TriangleAmplifier(), args); } catch (final Exception e) { logger.error("", e); } } /** * @param args runner arguments * @return job waiting statis * @throws Exception error during execution */ @Override public int run(final String[] args) throws Exception { final Configuration conf = getConf(); final Job job = Job.getInstance(conf, "RS Join"); job.setJarByClass(TriangleAmplifier.class); final Configuration jobConf = job.getConfiguration(); jobConf.set("mapreduce.output.textoutputformat.separator", COMMA_SEPARATOR); job.setMapperClass(Step1Mapper.class); job.setReducerClass(Step1Reducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.waitForCompletion(true); final Job job2 = Job.getInstance(conf, "RS Join Triangle Amplifier"); job2.setJarByClass(TriangleAmplifier.class); MultipleInputs.addInputPath(job2, new Path(args[1]), TextInputFormat.class); MultipleInputs.addInputPath(job2, new Path(args[0]), TextInputFormat.class); job2.setMapperClass(Step2Mapper.class); job2.setReducerClass(Step2Reducer.class); job2.setOutputKeyClass(Text.class); job2.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job2, new Path(args[2])); boolean isComplete = job2.waitForCompletion(true); Counters cn = job2.getCounters(); Counter c1 = cn.findCounter(CounterEnum.TRIANGLE_COUNTER); logger.info("Triangle count:" + c1.getDisplayName() + ":" + c1.getValue() / 3); return isComplete ? 0 : 1; } }
3e0481920806fe07abb4777a82ae56206ddc4eaa
1,138
java
Java
clouddriver-ecs/src/main/java/com/netflix/spinnaker/clouddriver/ecs/security/NetflixECSCredentials.java
gopaljayanthi/clouddriver
351a4331560e67d255983c1b3b6122f68a741d27
[ "Apache-2.0" ]
382
2015-11-16T17:54:23.000Z
2022-03-24T05:35:37.000Z
clouddriver-ecs/src/main/java/com/netflix/spinnaker/clouddriver/ecs/security/NetflixECSCredentials.java
gopaljayanthi/clouddriver
351a4331560e67d255983c1b3b6122f68a741d27
[ "Apache-2.0" ]
2,541
2015-11-17T11:22:10.000Z
2022-03-28T22:30:12.000Z
clouddriver-ecs/src/main/java/com/netflix/spinnaker/clouddriver/ecs/security/NetflixECSCredentials.java
gopaljayanthi/clouddriver
351a4331560e67d255983c1b3b6122f68a741d27
[ "Apache-2.0" ]
1,229
2015-11-16T19:22:35.000Z
2022-03-28T18:32:40.000Z
29.947368
79
0.757469
1,893
/* * Copyright 2018 Lookout, 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.netflix.spinnaker.clouddriver.ecs.security; import com.netflix.spinnaker.clouddriver.aws.security.NetflixAmazonCredentials; public class NetflixECSCredentials extends NetflixAmazonCredentials { private static final String CLOUD_PROVIDER = "ecs"; public NetflixECSCredentials(NetflixAmazonCredentials copy) { super(copy, copy.getCredentialsProvider()); } @Override public String getCloudProvider() { return CLOUD_PROVIDER; } @Override public String getAccountType() { return CLOUD_PROVIDER; } }
3e0481d5cb8d766e6c27839b26261e1f18fddc1b
16,246
java
Java
src/com/google/api/ads/dfp/v201302/CustomField.java
hockeyprincess/google-api-dfp-java
f9ec49d46292ba510d6be67c68f59959d0495f06
[ "Apache-2.0" ]
null
null
null
src/com/google/api/ads/dfp/v201302/CustomField.java
hockeyprincess/google-api-dfp-java
f9ec49d46292ba510d6be67c68f59959d0495f06
[ "Apache-2.0" ]
null
null
null
src/com/google/api/ads/dfp/v201302/CustomField.java
hockeyprincess/google-api-dfp-java
f9ec49d46292ba510d6be67c68f59959d0495f06
[ "Apache-2.0" ]
null
null
null
36.922727
138
0.618306
1,894
/** * CustomField.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201302; /** * An additional, user-created field on an entity. */ public class CustomField implements java.io.Serializable { /* Unique ID of the {@code CustomField}. This value is readonly * and is assigned by * Google. */ private java.lang.Long id; /* Name of the {@code CustomField}. This is value is required * to create a custom field. The * max length is 127 characters. */ private java.lang.String name; /* A description of the custom field. This value is optional. * The maximum length is 511 * characters */ private java.lang.String description; /* Specifies whether or not the custom fields is active. This * attribute is read-only. */ private java.lang.Boolean isActive; /* The type of entity that this custom field is associated with. * This attribute is read-only * if there exists a {@link CustomFieldValue} for this * field. */ private com.google.api.ads.dfp.v201302.CustomFieldEntityType entityType; /* The type of data this custom field contains. This attribute * is read-only * if there exists a {@link CustomFieldValue} for this * field. */ private com.google.api.ads.dfp.v201302.CustomFieldDataType dataType; /* How visible/accessible this field is in the UI. */ private com.google.api.ads.dfp.v201302.CustomFieldVisibility visibility; /* Indicates that this instance is a subtype of CustomField. * Although this field is returned in the response, it * is ignored on input * and cannot be selected. Specify xsi:type instead. */ private java.lang.String customFieldType; public CustomField() { } public CustomField( java.lang.Long id, java.lang.String name, java.lang.String description, java.lang.Boolean isActive, com.google.api.ads.dfp.v201302.CustomFieldEntityType entityType, com.google.api.ads.dfp.v201302.CustomFieldDataType dataType, com.google.api.ads.dfp.v201302.CustomFieldVisibility visibility, java.lang.String customFieldType) { this.id = id; this.name = name; this.description = description; this.isActive = isActive; this.entityType = entityType; this.dataType = dataType; this.visibility = visibility; this.customFieldType = customFieldType; } /** * Gets the id value for this CustomField. * * @return id * Unique ID of the {@code CustomField}. This value is readonly * and is assigned by * Google. */ public java.lang.Long getId() { return id; } /** * Sets the id value for this CustomField. * * @param id * Unique ID of the {@code CustomField}. This value is readonly * and is assigned by * Google. */ public void setId(java.lang.Long id) { this.id = id; } /** * Gets the name value for this CustomField. * * @return name * Name of the {@code CustomField}. This is value is required * to create a custom field. The * max length is 127 characters. */ public java.lang.String getName() { return name; } /** * Sets the name value for this CustomField. * * @param name * Name of the {@code CustomField}. This is value is required * to create a custom field. The * max length is 127 characters. */ public void setName(java.lang.String name) { this.name = name; } /** * Gets the description value for this CustomField. * * @return description * A description of the custom field. This value is optional. * The maximum length is 511 * characters */ public java.lang.String getDescription() { return description; } /** * Sets the description value for this CustomField. * * @param description * A description of the custom field. This value is optional. * The maximum length is 511 * characters */ public void setDescription(java.lang.String description) { this.description = description; } /** * Gets the isActive value for this CustomField. * * @return isActive * Specifies whether or not the custom fields is active. This * attribute is read-only. */ public java.lang.Boolean getIsActive() { return isActive; } /** * Sets the isActive value for this CustomField. * * @param isActive * Specifies whether or not the custom fields is active. This * attribute is read-only. */ public void setIsActive(java.lang.Boolean isActive) { this.isActive = isActive; } /** * Gets the entityType value for this CustomField. * * @return entityType * The type of entity that this custom field is associated with. * This attribute is read-only * if there exists a {@link CustomFieldValue} for this * field. */ public com.google.api.ads.dfp.v201302.CustomFieldEntityType getEntityType() { return entityType; } /** * Sets the entityType value for this CustomField. * * @param entityType * The type of entity that this custom field is associated with. * This attribute is read-only * if there exists a {@link CustomFieldValue} for this * field. */ public void setEntityType(com.google.api.ads.dfp.v201302.CustomFieldEntityType entityType) { this.entityType = entityType; } /** * Gets the dataType value for this CustomField. * * @return dataType * The type of data this custom field contains. This attribute * is read-only * if there exists a {@link CustomFieldValue} for this * field. */ public com.google.api.ads.dfp.v201302.CustomFieldDataType getDataType() { return dataType; } /** * Sets the dataType value for this CustomField. * * @param dataType * The type of data this custom field contains. This attribute * is read-only * if there exists a {@link CustomFieldValue} for this * field. */ public void setDataType(com.google.api.ads.dfp.v201302.CustomFieldDataType dataType) { this.dataType = dataType; } /** * Gets the visibility value for this CustomField. * * @return visibility * How visible/accessible this field is in the UI. */ public com.google.api.ads.dfp.v201302.CustomFieldVisibility getVisibility() { return visibility; } /** * Sets the visibility value for this CustomField. * * @param visibility * How visible/accessible this field is in the UI. */ public void setVisibility(com.google.api.ads.dfp.v201302.CustomFieldVisibility visibility) { this.visibility = visibility; } /** * Gets the customFieldType value for this CustomField. * * @return customFieldType * Indicates that this instance is a subtype of CustomField. * Although this field is returned in the response, it * is ignored on input * and cannot be selected. Specify xsi:type instead. */ public java.lang.String getCustomFieldType() { return customFieldType; } /** * Sets the customFieldType value for this CustomField. * * @param customFieldType * Indicates that this instance is a subtype of CustomField. * Although this field is returned in the response, it * is ignored on input * and cannot be selected. Specify xsi:type instead. */ public void setCustomFieldType(java.lang.String customFieldType) { this.customFieldType = customFieldType; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof CustomField)) return false; CustomField other = (CustomField) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.id==null && other.getId()==null) || (this.id!=null && this.id.equals(other.getId()))) && ((this.name==null && other.getName()==null) || (this.name!=null && this.name.equals(other.getName()))) && ((this.description==null && other.getDescription()==null) || (this.description!=null && this.description.equals(other.getDescription()))) && ((this.isActive==null && other.getIsActive()==null) || (this.isActive!=null && this.isActive.equals(other.getIsActive()))) && ((this.entityType==null && other.getEntityType()==null) || (this.entityType!=null && this.entityType.equals(other.getEntityType()))) && ((this.dataType==null && other.getDataType()==null) || (this.dataType!=null && this.dataType.equals(other.getDataType()))) && ((this.visibility==null && other.getVisibility()==null) || (this.visibility!=null && this.visibility.equals(other.getVisibility()))) && ((this.customFieldType==null && other.getCustomFieldType()==null) || (this.customFieldType!=null && this.customFieldType.equals(other.getCustomFieldType()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getId() != null) { _hashCode += getId().hashCode(); } if (getName() != null) { _hashCode += getName().hashCode(); } if (getDescription() != null) { _hashCode += getDescription().hashCode(); } if (getIsActive() != null) { _hashCode += getIsActive().hashCode(); } if (getEntityType() != null) { _hashCode += getEntityType().hashCode(); } if (getDataType() != null) { _hashCode += getDataType().hashCode(); } if (getVisibility() != null) { _hashCode += getVisibility().hashCode(); } if (getCustomFieldType() != null) { _hashCode += getCustomFieldType().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(CustomField.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "CustomField")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("id"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "id")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("name"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "name")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("description"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "description")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("isActive"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "isActive")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("entityType"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "entityType")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "CustomFieldEntityType")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("dataType"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "dataType")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "CustomFieldDataType")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("visibility"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "visibility")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "CustomFieldVisibility")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("customFieldType"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "CustomField.Type")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
3e04821d910b45b76592a02059d68c2890d87e66
997
java
Java
src/main/java/com/home/base/rest/BaseController.java
weedmmg/spring-boot-excel-import-export
1666a2517fc9dafca25778aeabdce0d1789f5e5c
[ "Apache-2.0" ]
1
2020-04-27T14:54:32.000Z
2020-04-27T14:54:32.000Z
src/main/java/com/home/base/rest/BaseController.java
weedmmg/spring-boot-excel-import-export
1666a2517fc9dafca25778aeabdce0d1789f5e5c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/home/base/rest/BaseController.java
weedmmg/spring-boot-excel-import-export
1666a2517fc9dafca25778aeabdce0d1789f5e5c
[ "Apache-2.0" ]
null
null
null
26.945946
71
0.729188
1,895
package com.home.base.rest; import com.home.base.exceptions.DataAccessException; import com.home.base.secruity.JwtTokenUtil; import com.home.base.secruity.JwtUser; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; /** * @author chenxf * @date 4/11/2018 * @description */ public class BaseController { @Autowired private JwtTokenUtil jwtTokenUtil; public String getCurrentName(){ String name= jwtTokenUtil.getNameFromToken(getToken()); if(StringUtils.isBlank(name)){ throw new DataAccessException("token无效"); } return name; } private String getToken(){ SecurityContext sc = SecurityContextHolder.getContext(); Object principal = sc.getAuthentication().getDetails(); return principal.toString(); } }
3e048263f8e9eb532f63a8fd3456b468124eb393
1,519
java
Java
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/api/internal/file/copy/DestinationRootCopySpec.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
158
2015-04-18T23:39:02.000Z
2021-07-01T18:28:29.000Z
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/api/internal/file/copy/DestinationRootCopySpec.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
31
2015-04-29T18:52:40.000Z
2020-06-29T19:25:24.000Z
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/api/internal/file/copy/DestinationRootCopySpec.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
32
2016-01-05T21:58:24.000Z
2021-06-21T21:56:34.000Z
28.660377
90
0.731402
1,896
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.file.copy; import org.gradle.api.file.CopySpec; import org.gradle.api.internal.file.FileResolver; import java.io.File; public class DestinationRootCopySpec extends DelegatingCopySpecInternal { private final FileResolver fileResolver; private final CopySpecInternal delegate; private Object destinationDir; public DestinationRootCopySpec(FileResolver fileResolver, CopySpecInternal delegate) { this.fileResolver = fileResolver; this.delegate = delegate; } @Override protected CopySpecInternal getDelegateCopySpec() { return delegate; } @Override public CopySpec into(Object destinationDir) { this.destinationDir = destinationDir; return this; } public File getDestinationDir() { return destinationDir == null ? null : fileResolver.resolve(destinationDir); } }
3e048382168deb4db4874b42ae61688e23f5bafa
25,645
java
Java
src/main/java/com/aarrelaakso/drawl/Shape.java
aarre/drawl
ee9018d2dca6da3c885c9c6dd6f7a5cb8188b283
[ "MIT" ]
1
2020-04-19T15:08:38.000Z
2020-04-19T15:08:38.000Z
src/main/java/com/aarrelaakso/drawl/Shape.java
aarre/drawl
ee9018d2dca6da3c885c9c6dd6f7a5cb8188b283
[ "MIT" ]
16
2020-04-25T21:38:31.000Z
2020-04-30T19:01:19.000Z
src/main/java/com/aarrelaakso/drawl/Shape.java
aarre/drawl
ee9018d2dca6da3c885c9c6dd6f7a5cb8188b283
[ "MIT" ]
null
null
null
33.348505
119
0.650653
1,897
/* * Drawl, the world's best drawing language. * * Copyright (c) 2020 Aarre Laakso * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.aarrelaakso.drawl; import com.google.common.flogger.FluentLogger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Objects; /** * Abstract class represents shapes such as circles, rectangles, and lines. */ public class Shape { private static final Number ABOVE = DrawlNumber.ZERO; private static final Number BELOW = DrawlNumber.valueOf(180); private static final Number LEFT = DrawlNumber.valueOf(270); private static final Number RIGHT = DrawlNumber.valueOf(90); private static final String CANNOT_BE_ADJACENT_TO_ITSELF = "A circle cannot be adjacent to itself"; private static final @NotNull FluentLogger logger; static { logger = FluentLogger.forEnclosingClass(); } /** * The angle, in degrees, to a neighbor. 0 represents up, and 90 degrees represents to the right. */ private Number angleToNeighbor; /** * The explicit height of a Shape defaults to <code>null</code> to indicate it that has not yet been set. */ private @Nullable Number explicitHeight; /** * The explicit width of a Shape defaults to <code>null</code> to indicate that it has not yet been set. */ private @Nullable Number explicitWidth; /** * A default Shape is centered at (0,0) in explicit coordinates */ private Point explicitPositionCenter = new Point(0, 0); /** * The fill of this Shape. Defaults to null, meaning the SVG default. */ private String fill; /** * The implicit height of a default Shape is 1. */ private Number implicitHeight = DrawlNumber.ONE; /** * The implicit width of a default Shape is 1. */ private Number implicitWidth = DrawlNumber.ONE; /** * A default Shape is centered at (0,0) in implicit coordinates. */ private Point implicitPositionCenter = new Point(0, 0); /** * A shape adjacent to this one, if any */ private Shape neighbor; /** * The stroke of this Shape. Defaults to null, meaning the SVG default. */ private String stroke; /** * Text inside this Shape. Defaults to null, meaning no Text in this Shape. */ private @Nullable Text text; /** * Adds Text inside this Shape. * * @param text a Text object representing the text to be drawn inside this Shape. */ public void addText(@Nullable final Text text) { this.text = text; } /** * Gets this Shape's neighbor above (this Shape is below that one), if any. * * @return the Shape to the right of this one, if any; * <code>null</code> otherwise. */ public @Nullable Shape getAbove() { @Nullable Shape returnValue = null; if (this.angleToNeighbor.equals(Shape.BELOW)) { returnValue = this.neighbor; } return returnValue; } /** * Sets this Shape above another Shape. * * @param shape The Shape that will be below this one. */ public void setAbove(@NotNull final Shape shape) { this.setAbove(shape, new Measure(0)); } /** * Gets this Shape's neighbor below (this Shape is above that one), if any. * * @return the Shape to below this one, if any; * <code>null</code> otherwise. */ public @Nullable Shape getBelow() { @Nullable Shape returnValue = null; if (this.angleToNeighbor.equals(Shape.ABOVE)) { returnValue = this.neighbor; } return returnValue; } /** * Sets this Shape below another Shape. * * @param shape The Shape that will be above this one. */ public void setBelow(@NotNull final Shape shape) { this.setBelow(shape, new Measure(0)); } /** * Returns a Point object representing this Shape's bottom port. * * @return */ public @NotNull Point getBottomPort() { final Number xCoordinate = this.getImplicitXPositionCenter(); final Number yCoordinate = this.getImplicitYPositionBottom(); return new Point(xCoordinate, yCoordinate); } /** * Gets half the explicit height of this Shape. * * @return half the explicit height of this Shape. */ private Number getExplicitHalfHeight() { if (this.getExplicitHeight() == null) { throw new UnsupportedOperationException("Cannot calculate explicit height without dimensions"); } return this.getExplicitHeight().divide(DrawlNumber.valueOf(2), DrawlNumber.mcOperations); } /** * Gets half the explicit width of this Shape. * * @return half the explicit width of this Shape. */ protected Number getExplicitHalfWidth() { if (this.getExplicitWidth() == null) { throw new UnsupportedOperationException("Cannot calculate explicit width without dimensions"); } return this.getExplicitWidth().divide(DrawlNumber.valueOf(2), DrawlNumber.mcOperations); } /** * Get the explicit height of this Shape. * * @return the explicit height of this Shape, or <code>null</code> if this Shape has not yet been assigned an * explicit height. */ protected @Nullable Number getExplicitHeight() { return this.explicitHeight; } /** * Set the height of this Shape to an explicit value. * <p> * * @param height The new height of this Shape. Can be <code>null</code> to indicate that this Shape has not yet * been assigned an explicit height. */ protected void setExplicitHeight(@Nullable final Number height) { this.explicitHeight = height; if (Boolean.TRUE.equals(this.hasText())) { Objects.requireNonNull(this.getText()).setExplicitHeight(height); } } /** * Get the explicit width of this Shape. * * @return the explicit width of this Shape, or <code>null</code> if this Shape has not yet been assigned an * explicit width. */ protected @Nullable Number getExplicitWidth() { return this.explicitWidth; } /** * Set the width of this Shape to an explicit value. * <p> * * @param width the new width of this Shape, or <code>null</code> to indicate that this Shape has not yet * been assigned an explicit width. */ protected void setExplicitWidth(@Nullable final Number width) { this.explicitWidth = width; if (Boolean.TRUE.equals(this.hasText())) { Objects.requireNonNull(this.getText()).setExplicitWidth(width); } } /** * Gets the explicit x-position of the center of this Shape. * * @return the explicit x-position of the center of this Shape. */ @NotNull protected Number getExplicitXPositionCenter() { return this.explicitPositionCenter.getX(); } /** * Sets the explicit center position of this Shape. * * @param x the explicit x position of the center of this Shape. */ protected void setExplicitXPositionCenter(final Number x) { this.explicitPositionCenter.setX(x); if (Boolean.TRUE.equals(this.hasText())) { Objects.requireNonNull(this.getText()).setExplicitXPositionCenter(x); } } /** * Sets the explicit x position of the center of this Shape. * * @param x the explicit x position of the center of this Shape. */ protected void setExplicitXPositionCenter(final Integer x) { this.setExplicitXPositionCenter(DrawlNumber.valueOf(x)); } /** * Gets the explicit x position of the left edge of this Shape. * * @return the explicit x position of the left edge of this Shape. */ protected Number getExplicitXPositionLeft() { return this.explicitPositionCenter.getX().subtract(this.getExplicitHalfWidth()); } /** * Gets the explicit x position of the right edge of this Shape. * * @return the explicit x position of the right edge of this Shape. */ protected Number getExplicitXPositionRight() { return this.explicitPositionCenter.getX().add(this.getExplicitHalfWidth()); } /** * Gets the explicit y position of the bottom of this Shape. * * @return the explicit y position of the bottom of this Shape. */ @NotNull protected Number getExplicitYPositionBottom() { return this.getExplicitYPositionCenter().add(this.getExplicitHalfHeight()); } /** * Gets the explicit y-position of the center of this Shape. * * @return the explicit y-position of the center of this Shape. */ @NotNull protected Number getExplicitYPositionCenter() { return this.explicitPositionCenter.getY(); } /** * Sets the explicit y-position of the center of this Shape. This convenience allows passing the argument as an * Integer rather than a DrawlNumber. * * @param y The explicit y position of this shape. */ protected void setExplicitYPositionCenter(final Integer y) { this.setExplicitYPositionCenter(DrawlNumber.valueOf(y)); } /** * Sets the explicit y position of this Shape. * <p> * The y position marks the vertical position of the Shape's center. The explicit coordinate system is the * common Cartesian coordinate system, with higher values of y upward and lower values of y downward. * * @param y The explicit y position of this Shape. */ protected void setExplicitYPositionCenter(final Number y) { this.explicitPositionCenter.setY(y); if (Boolean.TRUE.equals(this.hasText())) { Objects.requireNonNull(this.getText()).setExplicitYPositionCenter(y); } } /** * Gets the explicit y-position of the top of this Shape. * * @return the explicit y-position of the top of this Shape. */ @NotNull protected Number getExplicitYPositionTop() { return this.getExplicitYPositionCenter().subtract(this.getExplicitHalfHeight()); } /** * Returns the fill associated with this Shape, if any. * * @return the fill associated with this Shape, or null if no fill has been associated with this Shape. */ @Nullable public String getFill() { return this.fill; } /** * Set the fill of this Shape. * * @param s A string representing a fill color, e.g., "white". */ public void setFill(final String s) { this.fill = s; } /** * Returns a Measure object that represents the height of this Shape. * * @return a Measure object that represents the height of this Shape. */ public @NotNull Measure getHeight() { @Nullable final Number height = this.getImplicitHeight(); return new Measure(height); } /** * Gets half of the implicit height of this Shape. * * @return half of the implicit height of this Shape. */ protected Number getImplicitHalfHeight() { return Objects.requireNonNull(this.getImplicitHeight()).divide(DrawlNumber.TWO, DrawlNumber.mcOperations); } /** * Gets half of the implicit width of this Shape. * * @return half of the implicit width of this Shape. */ protected Number getImplicitHalfWidth() { return this.getImplicitWidth().divide(DrawlNumber.TWO, DrawlNumber.mcOperations); } /** * Gets the implicit height of this Shape. * * @return the implicit height of this Shape. */ protected @Nullable Number getImplicitHeight() { return this.implicitHeight; } /** * Sets the implicit height of this Shape. * * @param implicitHeight */ protected final void setImplicitHeight(@NotNull final Number implicitHeight) { logger.atFine().log("Setting implicit height to %s", implicitHeight.toPlainString()); this.implicitHeight = implicitHeight; } /** * Gets the implicit width of this Shape. * * @return the implicit width of this Shape. */ protected Number getImplicitWidth() { return this.implicitWidth; } /** * Sets the implicit width of this Shape. * * @param implicitWidth the implicit width of this Shape. */ protected final void setImplicitWidth(@NotNull final Number implicitWidth) { logger.atFine().log("Setting implicit width to %s", implicitWidth.toPlainString()); this.implicitWidth = implicitWidth; } /** * Get the implicit maximum (rightmost) x-position of this Shape. * * @return The implicit maximum (rightmost) x-position of this Shape. */ protected Number getImplicitXMaximum() { return this.getImplicitXPositionCenter().add(this.getImplicitHalfWidth()); } /** * Get the implicit minimum (leftmost) x-position of this Shape. * * @return The implicit minimum (leftmost) x-position of this Shape. */ protected Number getImplicitXMinimum() { return this.getImplicitXPositionCenter().subtract(this.getImplicitHalfWidth()); } /** * Get the implicit x position of the center of this Shape. * * @return The implicit x position of the center of this Shape. */ protected Number getImplicitXPositionCenter() { return this.implicitPositionCenter.getX(); } /** * Sets the implicit x position of the center of this Shape. * * @param x implicit x position of the center of this Shape. */ protected void setImplicitXPositionCenter(final Number x) { this.implicitPositionCenter.setX(x); if (Boolean.TRUE.equals(this.hasText())) { Objects.requireNonNull(this.getText()).setImplicitXPositionCenter(x); } } /** * Gets the implicit x position of the left edge of this Shape. * * @return The implicit x position of the left edge of this Shape. */ protected Number getImplicitXPositionLeft() { return this.getImplicitXPositionCenter().subtract(this.getImplicitHalfWidth()); } /** * Gets the implicit x position of the right edge of this Shape. * * @return The implicit x position of the right edge of this Shape. */ protected Number getImplicitXPositionRight() { return this.getImplicitXPositionCenter().add(this.getImplicitHalfWidth()); } /** * Gets the implicit bottommost y-position of this Shape. In implicit coordinates, this is the minimum y-position. * * @return The implicit minimum (bottommost) y-position of this Shape. */ protected Number getImplicitYPositionBottom() { return this.getImplicitYPositionCenter().subtract(this.getImplicitHalfHeight()); } /** * Gets the implicit y position of the center of this Shape. * * @return The implicit y position of the center of this Shape. */ protected Number getImplicitYPositionCenter() { return this.implicitPositionCenter.getY(); } /** * Sets the implicit y position of this Shape. * <p> * The y position marks the vertical position of the Shape's center. In the implicit coordinate system, higher * values of y are upward whereas lower values of y are downward. * * @param y The implicit y position of this Shape. */ protected void setImplicitYPositionCenter(final Number y) { this.implicitPositionCenter.setY(y); if (Boolean.TRUE.equals(this.hasText())) { Objects.requireNonNull(this.getText()).setImplicitYPositionCenter(y); } } /** * Gets the implicit topmost y position of this Shape. In implicit coordinates, this is the maximum y position. * * @return The implicit maximum (topmost) y-position of this Shape. */ protected Number getImplicitYPositionTop() { return this.getImplicitYPositionCenter().add(this.getImplicitHalfHeight()); } /** * Gets this Shape's neighbor to the right (this Shape is to the left of that one), if any. * * @return the Shape to the right of this one, if any; * <code>null</code> otherwise. */ public @Nullable Shape getLeftOf() { @Nullable Shape returnValue = null; if (RIGHT.equals(this.angleToNeighbor)) { returnValue = this.neighbor; } return returnValue; } /** * Sets this Shape to the left of another one. * * @param shape the Shape that will be to the right of this one. */ public void setLeftOf(@NotNull final Shape shape) { this.setLeftOf(shape, new Measure(0)); } /** * Returns a Point object representing this Shape's left port. * * @return */ public @NotNull Point getLeftPort() { final Number xCoordinate = this.getImplicitXPositionLeft(); final Number yCoordinate = this.getImplicitYPositionCenter(); return new Point(xCoordinate, yCoordinate); } /** * Gets this Shape's neighbor to the left (this Shape is to the right of that one), if any. * * @return the Shape to the left of this one, if any; * <code>null</code> otherwise. */ public @Nullable Shape getRightOf() { @Nullable Shape returnValue = null; if ((this.angleToNeighbor != null) && (this.angleToNeighbor.isEqualTo(LEFT))) { returnValue = this.neighbor; } return returnValue; } /** * Sets this Shape's neighbor to the left (this Shape is to the right of that one). * * @param shape the Shape to the left of this one */ public void setRightOf(@NotNull final Shape shape) { this.setRightOf(shape, new Measure(0)); } /** * Returns a Point object representing this Shape's left port. * * @return */ public @NotNull Point getRightPort() { final Number xCoordinate = this.getImplicitXPositionRight(); final Number yCoordinate = this.getImplicitYPositionCenter(); return new Point(xCoordinate, yCoordinate); } public String getSVG() { return "oops"; } /** * Gets the stroke of this Shape. * * @return The stroke of this shape, or null if the stroke of this Shape has not been set. */ @Nullable public String getStroke() { return this.stroke; } /** * Sets the stroke of this shape. * * @param s A stroke name. */ public void setStroke(final String s) { this.stroke = s; } /** * Returns a Text object that belongs to this Shape, if there is one. * * @return A Text object that belongs to this Shape, or <code>null</code> if this Shape does not have a Text object * associated with it. */ @Nullable public Text getText() { return this.text; } /** * Returns a Point object representing this Shape's top port. * * @return */ public @NotNull Point getTopPort() { final Number xCoordinate = this.getImplicitXPositionCenter(); final Number yCoordinate = this.getImplicitYPositionTop(); return new Point(xCoordinate, yCoordinate); } /** * Sets the width of this object. */ public void setWidth(Measure width) { this.setImplicitWidth(width.toDrawlNumber()); } /** * Returns a Measure object that represents the width of this Shape. * * @return */ public @NotNull Measure getWidth() { final Number width = this.getImplicitWidth(); return new Measure(width); } /** * Indicates whether this shape has a Text object associated with it. * * @return TRUE if this shape has a Text object associated with it, FALSE otherwise. */ @NotNull public Boolean hasText() { if (this.getText() == null) { return Boolean.FALSE; } else { return Boolean.TRUE; } } /** * Sets this Shape above another Shape. * * @param shape The circle that will be below this one. */ public void setAbove(@NotNull final Shape shape, @NotNull final Measure offset) { if (shape == this) { throw new UnsupportedOperationException(CANNOT_BE_ADJACENT_TO_ITSELF); } this.neighbor = shape; this.angleToNeighbor = BELOW; // Set the y position of this Shape final Number topBoundaryOfShape = shape.getImplicitYPositionTop(); Number thisImplicitYPosition = topBoundaryOfShape.add(this.getImplicitHalfHeight(), DrawlNumber.mcOperations); thisImplicitYPosition = thisImplicitYPosition.add(offset.toDrawlNumber()); this.setImplicitYPositionCenter(thisImplicitYPosition); // Set the x position of this Shape to match the one it is above this.setImplicitXPositionCenter(shape.getImplicitXPositionCenter()); this.setExplicitXPositionCenter(shape.getExplicitXPositionCenter()); } /** * Sets this circle below another circle. * * @param shape The circle that will be above this one. */ public void setBelow(@NotNull final Shape shape, @NotNull final Measure offset) { if (shape == this) { throw new UnsupportedOperationException(CANNOT_BE_ADJACENT_TO_ITSELF); } this.neighbor = shape; this.angleToNeighbor = Shape.ABOVE; final Number bottomBoundaryOfShape = shape.getImplicitYPositionBottom(); Number thisImplicitYPosition = bottomBoundaryOfShape.subtract(this.getImplicitHalfHeight(), DrawlNumber.mcOperations); thisImplicitYPosition = thisImplicitYPosition.subtract(offset.toDrawlNumber()); this.setImplicitYPositionCenter(thisImplicitYPosition); // Set the x position of this Shape to match the one it is above this.setImplicitXPositionCenter(shape.getImplicitXPositionCenter()); this.setExplicitXPositionCenter(shape.getExplicitXPositionCenter()); } /** * Sets this Shape's neighbor to the right (this Shape is to the left of that one). * * @param shape the Shape to the right of this one */ public void setLeftOf(@NotNull final Shape shape, @NotNull final Measure offset) { if (shape == this) { throw new UnsupportedOperationException(CANNOT_BE_ADJACENT_TO_ITSELF); } this.neighbor = shape; this.angleToNeighbor = RIGHT; // Set the x position of this shape final Number leftBoundaryOfShape = shape.getImplicitXMinimum(); Number thisImplicitXPosition = leftBoundaryOfShape.subtract(this.getImplicitHalfWidth(), DrawlNumber.mcOperations); thisImplicitXPosition = thisImplicitXPosition.subtract(offset.toDrawlNumber()); this.setImplicitXPositionCenter(thisImplicitXPosition); // Set the y position of this shape to match the one it is to the left of this.setImplicitYPositionCenter(shape.getImplicitYPositionCenter()); this.setExplicitYPositionCenter(shape.getExplicitYPositionCenter()); } /** * Sets this Shape's neighbor to the left with an offset. (This Shape is to the right of that one by an offset.) * * @param shape The Shape to set to the right of which this one will be set. * @param offset The distance to offset the other Shape from this one. */ public void setRightOf(@NotNull final Shape shape, @NotNull final Measure offset) { if (shape == this) { throw new UnsupportedOperationException(CANNOT_BE_ADJACENT_TO_ITSELF); } this.neighbor = shape; this.angleToNeighbor = LEFT; // Set the x position of this Shape final Number rightBoundaryOfShape = shape.getImplicitXMaximum(); Number thisImplicitXPosition = rightBoundaryOfShape.add(this.getImplicitHalfWidth(), DrawlNumber.mcOperations); thisImplicitXPosition = thisImplicitXPosition.add(offset.toDrawlNumber()); this.setImplicitXPositionCenter(thisImplicitXPosition); // Set the y position of this shape to match the one it is to the left of this.setImplicitYPositionCenter(shape.getImplicitYPositionCenter()); this.setExplicitYPositionCenter(shape.getExplicitYPositionCenter()); } }
3e04841514d199a76873d5a629a44aa3c7f38142
222
java
Java
modules/app-community-wanli/app-community-wanli-mapper/src/main/java/com/mit/community/mapper/mapper/XmsfPeopleMapper.java
1056215801/-MITC-YING_TAN
7badf6038927fd53a2bc04912264e951946de36e
[ "Apache-2.0" ]
1
2020-09-08T06:23:32.000Z
2020-09-08T06:23:32.000Z
modules/app-community-wanli/app-community-wanli-mapper/src/main/java/com/mit/community/mapper/mapper/XmsfPeopleMapper.java
1056215801/-
7badf6038927fd53a2bc04912264e951946de36e
[ "Apache-2.0" ]
2
2021-06-04T02:20:12.000Z
2022-03-31T21:52:31.000Z
modules/app-community-wanli/app-community-wanli-mapper/src/main/java/com/mit/community/mapper/mapper/XmsfPeopleMapper.java
1056215801/-
7badf6038927fd53a2bc04912264e951946de36e
[ "Apache-2.0" ]
1
2021-07-02T10:02:34.000Z
2021-07-02T10:02:34.000Z
27.75
70
0.842342
1,898
package com.mit.community.mapper.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.mit.community.entity.entity.XmsfPeopleInfo; public interface XmsfPeopleMapper extends BaseMapper<XmsfPeopleInfo> { }
3e0484166c834a3bbbf9ad7826dc5e638107f275
223
java
Java
src/main/java/org/springframework/samples/petclinic/proxy/Stroe.java
KwonSeungwon/spring-petclinic
bd943264b96f02eb07fa9cf39619120f7b2fab65
[ "Apache-2.0" ]
null
null
null
src/main/java/org/springframework/samples/petclinic/proxy/Stroe.java
KwonSeungwon/spring-petclinic
bd943264b96f02eb07fa9cf39619120f7b2fab65
[ "Apache-2.0" ]
null
null
null
src/main/java/org/springframework/samples/petclinic/proxy/Stroe.java
KwonSeungwon/spring-petclinic
bd943264b96f02eb07fa9cf39619120f7b2fab65
[ "Apache-2.0" ]
null
null
null
13.9375
52
0.713004
1,899
package org.springframework.samples.petclinic.proxy; public class Stroe { Payment payment; public Stroe(Payment payment) { // 의존성주입 this.payment = payment; } public void buySomeThing() { payment.pay(100); } }
3e04841cd53f6c18c03f30c1f4ae78aa0913ef04
1,696
java
Java
ZhiHu/app/src/main/java/com/teemo/zhihu/http/HttpUtils.java
teemo927/hello-world
fda89ebb5b33724f2a9ffc77cb05e9ebff14d0ff
[ "Apache-2.0" ]
2
2016-05-11T13:36:17.000Z
2016-05-11T13:36:20.000Z
ZhiHu/app/src/main/java/com/teemo/zhihu/http/HttpUtils.java
demo920/hello-world
fda89ebb5b33724f2a9ffc77cb05e9ebff14d0ff
[ "Apache-2.0" ]
null
null
null
ZhiHu/app/src/main/java/com/teemo/zhihu/http/HttpUtils.java
demo920/hello-world
fda89ebb5b33724f2a9ffc77cb05e9ebff14d0ff
[ "Apache-2.0" ]
null
null
null
21.468354
106
0.591392
1,900
package com.teemo.zhihu.http; import com.teemo.zhihu.utils.LogUtils; import retrofit2.Call; import retrofit2.Callback; /** * Created by Administrator on 2016/9/5. */ public class HttpUtils { private static HttpInterface create; private static Call call; static { create = RetrofitHelper.getInstance().getRetrofit().create(HttpInterface.class); if (call != null) { call.cancel(); call = null; } } /** * 获取启动图片 */ public static void getImage(String url, Callback callback) { String base = url.substring(0, url.lastIndexOf("/") + 1); String path = url.substring(url.lastIndexOf("/") + 1, url.length()); LogUtils.e("Activity", "base:" + base + "\n" + "path:" + path); HttpInterface create = RetrofitHelper.getInstance().getRetrofit(base).create(HttpInterface.class); call = create.getImage(path); call.enqueue(callback); } /** * 1.查询启动图片 */ public static void startImage(Callback callback) { call = create.startImage(); call.enqueue(callback); } /** * 3.最新消息 */ public static void latestNews(Callback callback) { call = create.latestNews(); call.enqueue(callback); } /** * 消息内容获取与离线下载 URL: http://news-at.zhihu.com/api/4/news/3892357 */ public static void news(int newsId,Callback callback) { call = create.news(newsId); call.enqueue(callback); } /** * 5.过往消息 */ public static void beforeNews(String date ,Callback callback) { call = create.beforeNews(date); call.enqueue(callback); } }
3e0484bf13863378eec8863d8c342366ea06417c
1,273
java
Java
spring-android-showcase/client/src/org/springframework/android/showcase/rest/GoogleSearchResult.java
quang-nh/Spring-for-android
f2bb0b8f8a57660ec2d50288b059efcb3e7afc59
[ "Apache-2.0" ]
392
2015-01-05T05:13:01.000Z
2022-02-05T16:45:57.000Z
spring-android-showcase/client/src/org/springframework/android/showcase/rest/GoogleSearchResult.java
quang-nh/Spring-for-android
f2bb0b8f8a57660ec2d50288b059efcb3e7afc59
[ "Apache-2.0" ]
8
2015-01-09T18:33:53.000Z
2021-12-09T20:37:32.000Z
spring-android-showcase/client/src/org/springframework/android/showcase/rest/GoogleSearchResult.java
quang-nh/Spring-for-android
f2bb0b8f8a57660ec2d50288b059efcb3e7afc59
[ "Apache-2.0" ]
300
2015-01-02T12:26:25.000Z
2022-01-29T09:37:48.000Z
21.948276
75
0.729772
1,901
/* * Copyright 2010-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.android.showcase.rest; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * @author Roy Clarkson */ @JsonIgnoreProperties(ignoreUnknown = true) public class GoogleSearchResult { private String title; private String url; private String content; public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setUrl(String url) { this.url = url; } public String getUrl() { return this.url; } public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } }
3e0485af374e84110f3318e9fe20b44e3277f3e0
709
java
Java
Lesson-09/Activities/ChallengeActivity3-ATM/src/fudgebanking/ATM.java
rohitnig/playing-with-java
6fb18fd92233e84eff13d0842ba37f73ab3f92d3
[ "MIT" ]
422
2015-01-02T20:03:18.000Z
2022-03-12T01:01:51.000Z
Lesson-09/Activities/ChallengeActivity3-ATM/src/fudgebanking/ATM.java
rohitnig/playing-with-java
6fb18fd92233e84eff13d0842ba37f73ab3f92d3
[ "MIT" ]
3
2015-02-27T23:13:50.000Z
2020-05-29T14:36:03.000Z
Lesson-09/Activities/ChallengeActivity3-ATM/src/fudgebanking/ATM.java
rohitnig/playing-with-java
6fb18fd92233e84eff13d0842ba37f73ab3f92d3
[ "MIT" ]
346
2015-01-02T20:03:23.000Z
2022-03-28T20:47:20.000Z
22.15625
86
0.5811
1,902
/* Challenge Activity 3 - ATM Let's use the ATMMenu enum and switch statement to a main menu for an ATM. 1) Print the ATM menu 2) Prompt for a menu choice: d = deposit, w = withdrawl, b = balance and q = quit. 3) use the switch statement to determine the choice 4) print the output back to the user SAMPLE EXECUTION: ********************************* *** Welcome to FudgeBank ATM! *** *** Main Menu *** ********************************* [d=Deposit,w=Withdrawl,b=Balance,q=Quit] ? w You selected: Withdrawl */ package fudgebanking; import java.util.Scanner; public class ATM { public static void main(String[] args) { // TODO : code here } }
3e0486a77b1e1bbcdffdb1eb26969b010b39d45d
8,126
java
Java
core/src/main/java/com/sas/framework/expojo/PersistenceProvider.java
expojo/expojo-maven-parent
c0c33ac75df8e2f36463b8c38a166c3be07a3405
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/sas/framework/expojo/PersistenceProvider.java
expojo/expojo-maven-parent
c0c33ac75df8e2f36463b8c38a166c3be07a3405
[ "Apache-2.0" ]
2
2021-09-11T08:16:24.000Z
2022-01-04T16:33:09.000Z
core/src/main/java/com/sas/framework/expojo/PersistenceProvider.java
expojo/expojo-maven-parent
c0c33ac75df8e2f36463b8c38a166c3be07a3405
[ "Apache-2.0" ]
null
null
null
21.272251
97
0.73271
1,903
// -[KeepHeading]- // -[Copyright]- /** * (c) 2007, 2015. Step Ahead Software Pty Ltd. * This software is released under the Apache 2 License, a copy of which can be found * at: * http://www.apache.org/licenses/LICENSE-2.0.html * * Source file created and managed by Javelin (TM) Step Ahead Software. * To maintain code and model synchronization you may directly edit code in method bodies * and any sections starting with the 'Keep_*' marker. Make all other changes via Javelin. * See http://stepaheadsoftware.com for more details. */ package com.sas.framework.expojo; import java.lang.*; import com.sas.framework.expojo.ExpojoContext; import com.sas.framework.expojo.ExpojoContextFactory; // -[KeepBeforeClass]- import java.util.Collection; // -[Class]- /** * Class Name : PersistenceProvider * Diagram : Expojo Context and Components * Project : ExPOJO Core * Type : abstract * Superclass for all persistence providers. This class is extended to provide persistence * engine specific implementations. eg., HibernatePersistenceProvider and JdoPersistenceProvider. * These objects are typically kept 'open' throughout multiple HTTP requests, for each * request a transaction is begun at the start and commited (or rolled back) at the end. * This implements the 'OpenSessionInView' (hibernate) or 'OpenPersistenceManagerInView' * pattern. * A future possible enhancement is to add an optional "free persistence provider' mechanism * at the end of each HTTP request. * * @author Chris Colman */ public abstract class PersistenceProvider { // -[KeepWithinClass]- // -[Fields]- /** * Depth of the deepest transaction. 0 = no active transaction. * beginTx increments and commitTx and rollbackTx decrement depth. * See rollbackTx for more information. */ protected int depth = 0; public ExpojoContext expojoContext; // -[Methods]- /** * Returns true if the given object is of a class that has been configured to be 'able * to be persisted' by whatever the current ORM implementation requires. */ public abstract boolean isPersistenceCapable(Object object); /** * Detects if the given object related directly or indirectly to any attached objects. * Typically used when re-detaching an supposedly already detached object graph to ensure * that there are no references to attached objects. */ public abstract void detectAttachedRelationships(Object o); /** * Returns the object of the given class and oid. */ public abstract Object getObject(Class cls, long oid); /** * Returns the numeric portion of the OID for the given object. */ public abstract long getObjectId(Object o); /** * Forces a real rollback, regardless of the current transaction depth. Afterwards the * transaction is reopened and the txDepth is restored to its previous value less 1. */ public void forceRollbackTx() { int txDepth = getTxDepth(); // Commit enough times to get a real commit through to the database while (getTxDepth() != 0) rollbackTx(); // Restore transaction depth back to where it was while (getTxDepth() != txDepth) beginTx(); } /** * Deletes the persistent objects contained in the collection. * Maybe be overridden by some derived classes to perform a native ORM Collection delete. */ public void deleteAll(Collection toDelete) { // Need to make a copy because the provided collection might be the collection implementing a // relationship. As items are deleted they will/might be deleted (depending on how JDO works!) // and so we can miss every second item! Object[] deathRow = toDelete.toArray(); for (Object o: deathRow) { delete(o); } } /** * Returns a summary of the statistics regarding the PersistenceProvider. Typically this * will be a count of the number of objects it is currently managing in it's L1 cache. */ public String getStatistics() { return "PersistenceProvider: No statistics available"; } /** * Returns a detached copy of the given persistent object. */ public abstract Object detachCopy(Object po); /** * Forces a real commit, regardless of the current transaction depth. Afterwards the * transaction is reopened and the txDepth is restored to its previous value less 1. */ public void forceCommitTx() { int txDepth = getTxDepth(); // Commit enough times to get a real commit through to the database while (getTxDepth() != 0) commitTx(); // Restore transaction depth back to where it was while (getTxDepth() != txDepth) beginTx(); } /** * Reattaches the given unattached object to the PersistenceProvider */ public abstract Object attach(Object object); /** * Static method that returns the PersistenceManager of the ModelExposer attached to * the current thread. */ public static PersistenceProvider get() { return ModelExposer.get().getPersistenceProvider(); } /** * Flushes all object modifications to SQL (as yet uncommitted) that makes newly created * objects and changes available to DB queries within the current transaction. */ public abstract void flush(); /** * Rollsback any active transaction and sets the tx depth back to 0. */ public void clearTx() { if ( depth != 0 ) { depth = 1; rollbackTx(); } } /** * Not normally required. Causes all of the uncommitted changes to be committed to the * database. Occassionally it is desirable or sometimes even necessary to get all changes * to your model up to a certain point commited to the database prior to proceeding further * - regardless of the current transaction depth. This method will do a forced commit * and return with the transaction depth at the same level it was at when called. */ public void flushChanges() { flush(); } /** * Refresh all transactional instances - only has effect if within the context of an * open transaction. */ public abstract void refreshAll(); /** * Refreshes a single object instance. */ public abstract void refresh(Object o); /** * Returns the transaction depth. This does not infer support for nested transactions * (they would have to be supported by the underlying ORM) but it does allow for more * than one call to beginTx without a corresponding commitTx or rollbackTx so long as * the beginTx calls eventually matches the sum of the commitTx and rollbackTx calls. */ public int getTxDepth() { return depth; } /** * Evicts all objects from the PersistenceManager's cache. */ public abstract void evictAll(); /** * Evicts a persistent object from the PersistenceProvider's cache. */ public abstract void evict(Object po); /** * Returns true if the PersistenceProvider has an active transaction. */ public abstract boolean hasActiveTx(); /** * Sets the owning ExpojoContext. */ public void setExpojoContext(ExpojoContext iExpojoContext) { expojoContext = iExpojoContext; } /** * Opens a persistence provider. */ public abstract void open(); /** * Processes an exception thrown while in a transaction. The exception * could be relevent to the persistence technology or a generic RuntimeException. * If it's an optimistic verification exception (optimistic locking check * failed) then no exception is thrown and the persistence technology * may or may not need clean. In the case of JDO a rollback as already * been performed. */ public abstract RuntimeException processException(RuntimeException e); /** * Closes the persistence provider. It can no longer be used after being * closed. */ public abstract void close(); /** * Deletes the persistent object from the datastore. */ public abstract void delete(Object object); { } /** * Makes the given object persistent. */ public abstract Object persist(Object object); { } /** * Rolls back a transaction. */ public abstract void rollbackTx(); /** * Commits a transaction if the transaction depth is 1, otherwise merely decreases the * transaction depth. To force a real commit regardless of the current transaction depth * use forceCommitTx. */ public abstract void commitTx(); /** * Begins a transaction. */ public abstract void beginTx(); }
3e0486cbc8fca082dfb2a9827bce1bfe204ba902
1,714
java
Java
src/main/java/com/mmall/concurrency/example/syncContainer/CollectionExample1.java
ChanaLii/Concurrency
b280fcb8ebef356429c087e1940db133f9d01387
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mmall/concurrency/example/syncContainer/CollectionExample1.java
ChanaLii/Concurrency
b280fcb8ebef356429c087e1940db133f9d01387
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mmall/concurrency/example/syncContainer/CollectionExample1.java
ChanaLii/Concurrency
b280fcb8ebef356429c087e1940db133f9d01387
[ "Apache-2.0" ]
null
null
null
29.551724
91
0.610852
1,904
package com.mmall.concurrency.example.syncContainer; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /** * @author ligy * @date 2018/4/9 0009 22:37 */ @Slf4j public class CollectionExample1 { private static final int CLIENT_TOTAL = 5000; private static final int THREAD_TOTAL = 200; private static List<Integer> list = Collections.synchronizedList(Lists.newArrayList()); public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(THREAD_TOTAL); final CountDownLatch countDownLatch = new CountDownLatch(CLIENT_TOTAL); for (int i = 0; i < CLIENT_TOTAL; i++) { final int count = i; executorService.execute(()->{ try { //获取信号量许可证 semaphore.acquire(); update(count); //释放信号量许可证 semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } //释放线程 countDownLatch.countDown(); }); } //休眠 countDownLatch.await(); //关闭线程 executorService.shutdown(); log.info("{}",list.size()); } private static void update(int i){ list.add(1); } }
3e0486d3819fc7f56a8f6f798a24b72222c2b105
597
java
Java
OfflineTasks/src/offlineWork/Task3.java
LewisRedfern/QAC-Exercises-
0b833186edcb0fe46b97ed664c0a4188b8d7fc03
[ "MIT" ]
null
null
null
OfflineTasks/src/offlineWork/Task3.java
LewisRedfern/QAC-Exercises-
0b833186edcb0fe46b97ed664c0a4188b8d7fc03
[ "MIT" ]
null
null
null
OfflineTasks/src/offlineWork/Task3.java
LewisRedfern/QAC-Exercises-
0b833186edcb0fe46b97ed664c0a4188b8d7fc03
[ "MIT" ]
null
null
null
12.978261
47
0.539363
1,905
package offlineWork; public class Task3 { // //evenlySpaced(2, 4, 6) → true //evenlySpaced(4, 6, 2) → true //evenlySpaced(4, 6, 3) → false public void run() { Spacing(2, 4, 6); Spacing(4, 6, 2); Spacing(4, 6, 3); } public boolean Spacing (int a, int b, int c) { int first = a - b; int second = b - c; int third = b - a; int fourth = c -b; boolean pos = first == second; boolean neg = boolean ans = first == second; if (yes) { System.out.println(yes); } else if (!yes) { System.out.println(yes); } return yes; } }
3e048704b4c783f52e445ce8636ca22a73d6f9f6
3,263
java
Java
src/main/java/edu/gdei/gdeiassistant/Controller/Secret/Controller/SecretController.java
GdeiAssistant/GdeiAssistant
98078e6d22bf9275ab856fc41edb5543ef47a1df
[ "MIT" ]
100
2019-06-11T13:39:24.000Z
2022-03-29T09:14:51.000Z
src/main/java/edu/gdei/gdeiassistant/Controller/Secret/Controller/SecretController.java
GdeiAssistant/GdeiAssistant
98078e6d22bf9275ab856fc41edb5543ef47a1df
[ "MIT" ]
2
2021-11-13T08:11:12.000Z
2022-03-29T10:15:35.000Z
src/main/java/edu/gdei/gdeiassistant/Controller/Secret/Controller/SecretController.java
GdeiAssistant/GdeiAssistant
98078e6d22bf9275ab856fc41edb5543ef47a1df
[ "MIT" ]
41
2019-05-29T03:12:32.000Z
2022-03-29T12:51:22.000Z
36.255556
122
0.721422
1,906
package edu.gdei.gdeiassistant.Controller.Secret.Controller; import edu.gdei.gdeiassistant.Annotation.CheckAuthentication; import edu.gdei.gdeiassistant.Pojo.Entity.Secret; import edu.gdei.gdeiassistant.Pojo.JSSDK.JSSDKSignature; import edu.gdei.gdeiassistant.Service.Secret.SecretService; import edu.gdei.gdeiassistant.Service.Wechat.WechatService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class SecretController { @Autowired private SecretService secretService; @Autowired private WechatService wechatService; /** * 进入校园树洞应用首页 * * @return */ @RequestMapping(value = {"/secret"}, method = RequestMethod.GET) @CheckAuthentication(name = "secret") public ModelAndView ResolveSecretIndexPage(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("Secret/secretIndex"); return modelAndView; } /** * 进入树洞信息发布界面 * * @param request * @return */ @RequestMapping(value = {"/secret/publish"}, method = RequestMethod.GET) @CheckAuthentication(name = "secret") public ModelAndView ResolveSecretPublishPage(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("Secret/secretPublish"); JSSDKSignature jssdkSignature = wechatService.SetUpJSSDKConfig(request.getRequestURL().toString()); modelAndView.addObject("JSSDKSignature", jssdkSignature); return modelAndView; } /** * 进入树洞个人页面 * * @param request * @return */ @RequestMapping(value = {"/secret/profile"}, method = RequestMethod.GET) @CheckAuthentication(name = "secret") public ModelAndView ResolveSecretProfilePage(HttpServletRequest request) throws Exception { ModelAndView modelAndView = new ModelAndView(); String username = (String) request.getSession().getAttribute("username"); List<Secret> secretList = secretService.GetSecretInfo(username); modelAndView.addObject("SecretList", secretList); modelAndView.setViewName("Secret/secretProfile"); return modelAndView; } /** * 进入树洞信息详细信息页面 * * @param request * @return */ @RequestMapping(value = {"/secret/detail/id/{id}"}, method = RequestMethod.GET) @CheckAuthentication(name = "secret") public ModelAndView ResolveSecretDetailPage(HttpServletRequest request, @PathVariable("id") int id) throws Exception { ModelAndView modelAndView = new ModelAndView(); String username = (String) request.getSession().getAttribute("username"); Secret secret = secretService.GetSecretDetailInfo(id, username); modelAndView.setViewName("Secret/secretDetail"); modelAndView.addObject("Secret", secret); return modelAndView; } }
3e0487093bc839ab42ba7685ad29ea584de26ba3
470
java
Java
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/CommentReplayService.java
clown14/gulimall
29dfc52d136a0a756faa2c3d944235880e734a8d
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/CommentReplayService.java
clown14/gulimall
29dfc52d136a0a756faa2c3d944235880e734a8d
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/CommentReplayService.java
clown14/gulimall
29dfc52d136a0a756faa2c3d944235880e734a8d
[ "Apache-2.0" ]
null
null
null
22.333333
77
0.776119
1,907
package com.atguigu.gulimall.product.service; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.common.utils.PageUtils; import com.atguigu.gulimall.product.entity.CommentReplayEntity; import java.util.Map; /** * 商品评价回复关系 * * @author clown * @email [email protected] * @date 2020-11-06 15:25:09 */ public interface CommentReplayService extends IService<CommentReplayEntity> { PageUtils queryPage(Map<String, Object> params); }
3e048781aa289e18c9a1459d6b4af54400cf0763
1,092
java
Java
src/main/java/synchronizedAndVolatile/synchronized_/innerClassTest/test_2/Run.java
xiapeng612430/multi-thread
b2cbe27511fa3e7ae17b3d5839939e31812c473d
[ "Apache-2.0" ]
null
null
null
src/main/java/synchronizedAndVolatile/synchronized_/innerClassTest/test_2/Run.java
xiapeng612430/multi-thread
b2cbe27511fa3e7ae17b3d5839939e31812c473d
[ "Apache-2.0" ]
null
null
null
src/main/java/synchronizedAndVolatile/synchronized_/innerClassTest/test_2/Run.java
xiapeng612430/multi-thread
b2cbe27511fa3e7ae17b3d5839939e31812c473d
[ "Apache-2.0" ]
null
null
null
26
88
0.571429
1,908
package synchronizedAndVolatile.synchronized_.innerClassTest.test_2; import synchronizedAndVolatile.synchronized_.innerClassTest.test_2.OutClass.InnerClass1; import synchronizedAndVolatile.synchronized_.innerClassTest.test_2.OutClass.InnerClass2; /** * Created by xianpeng.xia * on 2019-06-08 20:21 */ public class Run { public static void main(String[] args) { final InnerClass1 innerClass1 = new InnerClass1(); final InnerClass2 innerClass2 = new InnerClass2(); Thread t1 = new Thread(new Runnable() { @Override public void run() { innerClass1.method1(innerClass2); } }, "T1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { innerClass1.method2(); } }, "T2"); Thread t3 = new Thread(new Runnable() { @Override public void run() { innerClass2.method1(); } }, "T3"); t1.start(); t2.start(); t3.start(); } }
3e04882980e38931f4c365c589cd5ea31ad82d8e
246
java
Java
src/main/java/org/epodia/dao/PathologicalGenealogyRepository.java
louay47/Epodia
bd6d389cda496f68c2a9c2cc25afa61aa82f8a93
[ "MIT" ]
null
null
null
src/main/java/org/epodia/dao/PathologicalGenealogyRepository.java
louay47/Epodia
bd6d389cda496f68c2a9c2cc25afa61aa82f8a93
[ "MIT" ]
null
null
null
src/main/java/org/epodia/dao/PathologicalGenealogyRepository.java
louay47/Epodia
bd6d389cda496f68c2a9c2cc25afa61aa82f8a93
[ "MIT" ]
null
null
null
27.333333
103
0.853659
1,909
package org.epodia.dao; import org.epodia.entities.Pathological_genealogy; import org.springframework.data.jpa.repository.JpaRepository; public interface PathologicalGenealogyRepository extends JpaRepository<Pathological_genealogy, Long> { }
3e04883cf4561f2b58024247a3256d23f010ae34
2,791
java
Java
app/src/main/java/com/wass08/futureseduction/sender/NotificationSender.java
wass08/Seduce-Me-With-Your-Watch
4bd1c7debbd3bf14ad44e0a3e4bea825d5bed004
[ "MIT" ]
1
2015-02-16T20:27:21.000Z
2015-02-16T20:27:21.000Z
app/src/main/java/com/wass08/futureseduction/sender/NotificationSender.java
wass08/Seduce-Me-With-Your-Watch
4bd1c7debbd3bf14ad44e0a3e4bea825d5bed004
[ "MIT" ]
null
null
null
app/src/main/java/com/wass08/futureseduction/sender/NotificationSender.java
wass08/Seduce-Me-With-Your-Watch
4bd1c7debbd3bf14ad44e0a3e4bea825d5bed004
[ "MIT" ]
null
null
null
40.449275
94
0.698316
1,910
package com.wass08.futureseduction.sender; import android.app.Notification; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import com.wass08.futureseduction.R; /** * Created by wassimsamad on 07/12/14. */ public class NotificationSender { private static int notificationId = 1; private static void sendNotification(Context context, String title, String content) { Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(), R.drawable.default_background); NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender() .setHintHideIcon(true) .setBackground(bitmap) .setContentIcon(R.drawable.heart_picto); long pattern[] = {500, 500}; // Create a NotificationCompat.Builder to build a standard notification // then extend it with the WearableExtender Notification notif = new NotificationCompat.Builder(context) .setContentTitle(title) .setContentText(content) .setSmallIcon(R.drawable.heart_picto) .extend(wearableExtender) .setVibrate(pattern) .build(); // Get an instance of the NotificationManager service NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); // Issue the notification with notification manager. notificationManager.notify(notificationId++, notif); } public static void sendDefaultManNotification(Context context) { String title = context.getResources().getString(R.string.sample_man_title); String content = context.getResources().getString(R.string.sample_man_content); sendNotification(context, title, content); } public static void sendDefaultWomanNotification(Context context) { String title = context.getResources().getString(R.string.sample_woman_title); String content = context.getResources().getString(R.string.sample_woman_content); sendNotification(context, title, content); } public static void sendDefaultLoveNotification(Context context) { String title = context.getResources().getString(R.string.sample_love_title); String content = context.getResources().getString(R.string.sample_love_content); sendNotification(context, title, content); } public static void sendCustomNotification(Context context, String title, String content) { sendNotification(context, title, content); } }
3e04884b4c31d93c90cdb8758be7e397262e0048
1,508
java
Java
src/tests/Test2.java
semcjaku/Enterprise-performance-testing-library
162a438a79b288a990cfc1ecabd37fb5bc4c73be
[ "Unlicense" ]
null
null
null
src/tests/Test2.java
semcjaku/Enterprise-performance-testing-library
162a438a79b288a990cfc1ecabd37fb5bc4c73be
[ "Unlicense" ]
null
null
null
src/tests/Test2.java
semcjaku/Enterprise-performance-testing-library
162a438a79b288a990cfc1ecabd37fb5bc4c73be
[ "Unlicense" ]
1
2021-03-21T19:37:57.000Z
2021-03-21T19:37:57.000Z
30.77551
153
0.691645
1,911
package tests; import testing_library.TestMethod; import testing_library.Tester; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Test2 { public Test2(){ } @TestMethod(testedValue = {Tester.TestStrategy.CLOCK,Tester.TestStrategy.PROCESSOR}, indicesOfParameters = {0}) public void DelaySec(int time) throws InterruptedException { TimeUnit.SECONDS.sleep(time); } public static void main(String[] args) throws InterruptedException, InvocationTargetException, SQLException, ParseException, IllegalAccessException { Test2 instance = new Test2(); int time=5; Object[] params = {time}; Tester tester = new Tester(instance,params); System.out.println("Calculating a "+time+" second delay..."); System.out.println("Testing with nanoTime..."); long startTime = System.nanoTime(); instance.DelaySec(time); long searchTime = System.nanoTime()-startTime; System.out.println("Done"); System.out.println("Testing with TestingLibrary.Tester..."); tester.performTest(); System.out.println("Done"); System.out.println("Execution time according to TestingLibrary.Tester:"); tester.showResults(); System.out.println("Clock execution time according to System.nanoTime: "); System.out.println(searchTime +" nanosecdonds"); } }
3e0488d6cb49d70a03d57cc1a50590305023f550
144
java
Java
src/main/java/com/jamieswhiteshirt/clotheslinefabric/api/util/package-info.java
Yoghurt4C/clothesline-fabric
55dbebe6d97ae9082f355941cbb1bfcbd92646c9
[ "MIT" ]
null
null
null
src/main/java/com/jamieswhiteshirt/clotheslinefabric/api/util/package-info.java
Yoghurt4C/clothesline-fabric
55dbebe6d97ae9082f355941cbb1bfcbd92646c9
[ "MIT" ]
null
null
null
src/main/java/com/jamieswhiteshirt/clotheslinefabric/api/util/package-info.java
Yoghurt4C/clothesline-fabric
55dbebe6d97ae9082f355941cbb1bfcbd92646c9
[ "MIT" ]
null
null
null
28.8
56
0.895833
1,912
@ParametersAreNonnullByDefault package com.jamieswhiteshirt.clotheslinefabric.api.util; import javax.annotation.ParametersAreNonnullByDefault;