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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923c88a23ac11c817893bc32d2f6415da3f4d3ff | 156 | java | Java | JasminBuilder/src/main/java/me/Munchii/JasminBuilder/DataTypes/VoidType.java | Dmunch04/JasminBuilder | 6c28a35fc8497c0688b6340c7d24184122fa6bb0 | [
"MIT"
] | 2 | 2021-04-18T11:48:05.000Z | 2021-11-22T14:30:00.000Z | JasminBuilder/src/main/java/me/Munchii/JasminBuilder/DataTypes/VoidType.java | Dmunch04/JasminBuilder | 6c28a35fc8497c0688b6340c7d24184122fa6bb0 | [
"MIT"
] | null | null | null | JasminBuilder/src/main/java/me/Munchii/JasminBuilder/DataTypes/VoidType.java | Dmunch04/JasminBuilder | 6c28a35fc8497c0688b6340c7d24184122fa6bb0 | [
"MIT"
] | null | null | null | 15.6 | 43 | 0.673077 | 999,966 | package me.Munchii.JasminBuilder.DataTypes;
public class VoidType extends DataType {
public VoidType() {
super("V", ValueType.VOID);
}
}
|
923c899e081deb2e47f5f8af9a2c18b799e4a736 | 2,691 | java | Java | tasks-jsf/src/test/java/org/jboss/as/quickstarts/tasksJsf/TaskListBeanTest.java | mmusgrov/quickstart | b0799bfb8e88d73b93842b919a7ff7c5b281f2e2 | [
"Apache-2.0"
] | null | null | null | tasks-jsf/src/test/java/org/jboss/as/quickstarts/tasksJsf/TaskListBeanTest.java | mmusgrov/quickstart | b0799bfb8e88d73b93842b919a7ff7c5b281f2e2 | [
"Apache-2.0"
] | null | null | null | tasks-jsf/src/test/java/org/jboss/as/quickstarts/tasksJsf/TaskListBeanTest.java | mmusgrov/quickstart | b0799bfb8e88d73b93842b919a7ff7c5b281f2e2 | [
"Apache-2.0"
] | null | null | null | 27.742268 | 103 | 0.681531 | 999,967 | package org.jboss.as.quickstarts.tasksJsf;
import static org.junit.Assert.assertEquals;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.quickstarts.tasksJsf.Task;
import org.jboss.as.quickstarts.tasksJsf.TaskDao;
import org.jboss.as.quickstarts.tasksJsf.TaskList;
import org.jboss.as.quickstarts.tasksJsf.TaskListBean;
import org.jboss.as.quickstarts.tasksJsf.User;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Lukas Fryc
*/
@RunWith(Arquillian.class)
public class TaskListBeanTest {
public static final String WEBAPP_SRC = "src/main/webapp";
@Deployment
public static WebArchive deployment() throws IllegalArgumentException, FileNotFoundException {
return new DefaultDeployment().withPersistence().withImportedData().getArchive()
.addClasses(User.class, Task.class, TaskList.class, TaskListBean.class, TaskDao.class);
}
@Inject
private TaskDaoStub taskDaoStub;
@Inject
private TaskList taskList;
@Test
public void dao_method_getAll_should_be_called_only_once_on() {
taskList.getAll();
taskList.getAll();
taskList.getAll();
assertEquals(1, taskDaoStub.getGetAllCallsCount());
}
@Test
public void dao_method_getAll_should_be_called_after_invalidation() {
taskList.getAll();
taskList.getAll();
assertEquals(1, taskDaoStub.getGetAllCallsCount());
taskList.invalidate();
assertEquals(1, taskDaoStub.getGetAllCallsCount());
taskList.getAll();
taskList.getAll();
assertEquals(2, taskDaoStub.getGetAllCallsCount());
}
@RequestScoped
public static class TaskDaoStub implements TaskDao {
private int getAllCallsCount = 0;
@Override
public void createTask(User user, Task task) {
}
@Override
public List<Task> getAll(User user) {
getAllCallsCount += 1;
return Arrays.asList(new Task[] {});
}
@Override
public List<Task> getRange(User user, int offset, int count) {
return null;
}
@Override
public List<Task> getForTitle(User user, String title) {
return null;
}
@Override
public void deleteTask(Task task) {
}
public int getGetAllCallsCount() {
return getAllCallsCount;
}
}
}
|
923c8a9e7eeb3c131fa751854c9aca11f7f57107 | 2,840 | java | Java | arangodb-java-reactive-driver/src/main/java/com/arangodb/reactive/api/collection/entity/CollectionSchema.java | arangodb/arangodb-java-reactive-drive | 4c0571b639a1376c1825d719d7833b2b6a2afdab | [
"Apache-2.0"
] | 2 | 2021-01-25T03:19:13.000Z | 2021-02-23T17:01:51.000Z | arangodb-java-reactive-driver/src/main/java/com/arangodb/reactive/api/collection/entity/CollectionSchema.java | arangodb/arangodb-java-reactive-driver | 4c0571b639a1376c1825d719d7833b2b6a2afdab | [
"Apache-2.0"
] | null | null | null | arangodb-java-reactive-driver/src/main/java/com/arangodb/reactive/api/collection/entity/CollectionSchema.java | arangodb/arangodb-java-reactive-driver | 4c0571b639a1376c1825d719d7833b2b6a2afdab | [
"Apache-2.0"
] | null | null | null | 30.537634 | 120 | 0.69331 | 999,968 | /*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* 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.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
package com.arangodb.reactive.api.collection.entity;
import com.arangodb.reactive.entity.GenerateBuilder;
import com.arangodb.reactive.entity.serde.VPackDeserializers;
import com.arangodb.reactive.entity.serde.VPackSerializers;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* @author Michele Rastelli
* @see <a href="https://www.arangodb.com/docs/stable/data-modeling-documents-schema-validation.html">API
* Documentation</a>
*/
@GenerateBuilder
@JsonDeserialize(builder = CollectionSchemaBuilder.class)
public interface CollectionSchema {
static CollectionSchemaBuilder builder() {
return new CollectionSchemaBuilder();
}
/**
* @return JSON Schema description
*/
@JsonSerialize(using = VPackSerializers.RawJsonSerializer.class)
@JsonDeserialize(using = VPackDeserializers.RawJsonDeserializer.class)
String getRule();
/**
* @return level at which the validation will be applied
*/
Level getLevel();
/**
* @return the message that will be used when validation fails
*/
String getMessage();
enum Level {
/**
* The rule is inactive and validation thus turned off.
*/
@JsonProperty("none")
NONE,
/**
* Only newly inserted documents are validated.
*/
@JsonProperty("new")
NEW,
/**
* New and modified documents must pass validation, except for modified documents where the OLD value did not
* pass validation already. This level is useful if you have documents which do not match your target structure,
* but you want to stop the insertion of more invalid documents and prohibit that valid documents are changed to
* invalid documents.
*/
@JsonProperty("moderate")
MODERATE,
/**
* All new and modified document must strictly pass validation. No exceptions are made (default).
*/
@JsonProperty("strict")
STRICT
}
}
|
923c8af745e43b8f78d9d3559c22b23fb14cec51 | 891 | java | Java | conveyor-persistence/conveyor-persistence-jdbc/src/main/java/com/aegisql/conveyor/persistence/jdbc/engine/statement_executor/NonCachingStatementExecutor.java | aegisql/conveyor | 0cad6c0ab9f69735e1af5405b356ab636afc980c | [
"Apache-2.0"
] | 11 | 2017-02-17T07:02:45.000Z | 2021-08-24T13:17:48.000Z | conveyor-persistence/conveyor-persistence-jdbc/src/main/java/com/aegisql/conveyor/persistence/jdbc/engine/statement_executor/NonCachingStatementExecutor.java | aegisql/conveyor | 0cad6c0ab9f69735e1af5405b356ab636afc980c | [
"Apache-2.0"
] | 29 | 2020-03-04T21:58:11.000Z | 2022-03-29T11:06:34.000Z | conveyor-persistence/conveyor-persistence-jdbc/src/main/java/com/aegisql/conveyor/persistence/jdbc/engine/statement_executor/NonCachingStatementExecutor.java | aegisql/conveyor | 0cad6c0ab9f69735e1af5405b356ab636afc980c | [
"Apache-2.0"
] | null | null | null | 26.205882 | 81 | 0.712682 | 999,969 | package com.aegisql.conveyor.persistence.jdbc.engine.statement_executor;
import com.aegisql.conveyor.persistence.core.PersistenceException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Supplier;
/**
* The type Non caching statement executor.
*/
public class NonCachingStatementExecutor extends AbstractStatementExecutor {
/**
* Instantiates a new Non caching statement executor.
*
* @param connectionSupplier the connection supplier
*/
public NonCachingStatementExecutor(Supplier<Connection> connectionSupplier) {
super(connectionSupplier);
}
@Override
public void close() throws IOException {
try {
connection.close();
} catch (SQLException e) {
throw new PersistenceException("Failed closing connection",e);
}
}
}
|
923c8c093a4ae03b8b8cd992333811e0d924993f | 693 | java | Java | src/main/java/spaceinvaders/client/mvc/Controller.java | gabrielAduku/networked-spaceinvaders | a79c6830f2419c8a0da8636a1e269b1727a1a844 | [
"MIT"
] | 11 | 2017-08-07T22:49:49.000Z | 2021-10-13T08:07:24.000Z | src/main/java/spaceinvaders/client/mvc/Controller.java | gabrielAduku/networked-spaceinvaders | a79c6830f2419c8a0da8636a1e269b1727a1a844 | [
"MIT"
] | null | null | null | src/main/java/spaceinvaders/client/mvc/Controller.java | gabrielAduku/networked-spaceinvaders | a79c6830f2419c8a0da8636a1e269b1727a1a844 | [
"MIT"
] | 4 | 2020-02-11T21:13:05.000Z | 2022-03-31T16:24:52.000Z | 22.354839 | 87 | 0.694084 | 999,970 | package spaceinvaders.client.mvc;
import java.util.List;
import java.util.Observer;
/**
* Separates application data and user interface.
*
* @see spaceinvaders.client.mvc.Model
* @see spaceinvaders.client.mvc.View
*/
public interface Controller extends Observer {
/**
* Register a view with this controller.
*
* @param view the view to be registered.
*/
public void registerView(View view);
/**
* Get the {@link spaceinvaders.client.mvc.Model} registered with this controller.
*/
public Model getModel();
/**
* Get a list of all {@link spaceinvaders.client.mvc.View views} registered with this
* controller.
*/
public List<View> getViews();
}
|
923c8cd2a12cb686ed09833da8bf8e9a4437f03f | 561 | java | Java | src/main/java/io/renren/modules/inspection/dao/ZoneDeviceDao.java | zhu5369598zhu/sva | 9133fc35a96d76c7539847d9054ad6fde0d1a08f | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/inspection/dao/ZoneDeviceDao.java | zhu5369598zhu/sva | 9133fc35a96d76c7539847d9054ad6fde0d1a08f | [
"Apache-2.0"
] | 1 | 2021-04-22T17:10:06.000Z | 2021-04-22T17:10:06.000Z | src/main/java/io/renren/modules/inspection/dao/ZoneDeviceDao.java | zhu5369598zhu/sva | 9133fc35a96d76c7539847d9054ad6fde0d1a08f | [
"Apache-2.0"
] | null | null | null | 23.5 | 75 | 0.776596 | 999,971 | package io.renren.modules.inspection.dao;
import io.renren.modules.inspection.entity.ZoneDeviceEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
*
*
* @author chenshun
* @email upchh@example.com
* @date 2019-01-21 03:10:48
*/
@Mapper
public interface ZoneDeviceDao extends BaseMapper<ZoneDeviceEntity> {
List<Map<String, Object>> findDeviceByZoneId(Long zoneId);
Integer insertDeviceBatch(List<ZoneDeviceEntity> zoneDeviceEntityList);
}
|
923c8e0a3114ccb7eb4b22e1340b3c8349244bfc | 1,242 | java | Java | src/main/java/cn/mrerror/one/utils/TencentSMS.java | meixianghan/one | e4f74c94b4c2b6a4146894281f7ab2dfcf32e3ed | [
"Unlicense"
] | 1 | 2019-04-13T06:59:21.000Z | 2019-04-13T06:59:21.000Z | src/main/java/cn/mrerror/one/utils/TencentSMS.java | ErrorLove/one | e4f74c94b4c2b6a4146894281f7ab2dfcf32e3ed | [
"Unlicense"
] | 2 | 2020-03-04T22:07:12.000Z | 2021-05-12T00:18:31.000Z | src/main/java/cn/mrerror/one/utils/TencentSMS.java | ErrorLove/one | e4f74c94b4c2b6a4146894281f7ab2dfcf32e3ed | [
"Unlicense"
] | null | null | null | 36.529412 | 123 | 0.636876 | 999,972 | package cn.mrerror.one.utils;
import cn.mrerror.one.configuration.Applications;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import java.io.IOException;
public class TencentSMS {
public void sendMessage(String phonenumbers[], int templateId, String[] params) {
try {
params = new String[]{"5678"};//数组具体的元素个数和模板中变量个数必须一致,例如事例中templateId:5678对应一个变量,参数数组中元素个数也必须是一个
SmsSingleSender ssender = new SmsSingleSender(Applications.TENCENT_SMS_APPID, Applications.TENCENT_SMS_APPKEY);
for (int i = 0; i < phonenumbers.length; i++) {
SmsSingleSenderResult result = ssender.sendWithParam("86", phonenumbers[i],
templateId, params, "", "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
System.out.println(result);
}
} catch (HTTPException e) {
// HTTP响应码错误
e.printStackTrace();
} catch (JSONException e) {
// json解析错误
e.printStackTrace();
} catch (IOException e) {
// 网络IO错误
e.printStackTrace();
}
}
}
|
923c8f4634108ea49ccbda1f54802fde825d0e54 | 3,368 | java | Java | coopr-server/src/main/java/co/cask/coopr/spec/plugin/ProviderType.java | cybervisiontech/coopr | 0096cd2fff1fa6d788ada4ff1cc975a5f5b76363 | [
"Apache-2.0"
] | 3 | 2019-12-20T05:15:15.000Z | 2020-09-30T07:00:49.000Z | coopr-server/src/main/java/co/cask/coopr/spec/plugin/ProviderType.java | cybervisiontech/coopr | 0096cd2fff1fa6d788ada4ff1cc975a5f5b76363 | [
"Apache-2.0"
] | null | null | null | coopr-server/src/main/java/co/cask/coopr/spec/plugin/ProviderType.java | cybervisiontech/coopr | 0096cd2fff1fa6d788ada4ff1cc975a5f5b76363 | [
"Apache-2.0"
] | 2 | 2022-02-21T20:15:36.000Z | 2022-03-21T18:49:21.000Z | 36.215054 | 116 | 0.699525 | 999,973 | /*
* Copyright © 2012-2014 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.cask.coopr.spec.plugin;
import co.cask.coopr.spec.BaseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* A Provider type defines what parameters admins and users need to provide to a
* {@link co.cask.coopr.spec.Provider} in order for it to provide machines properly.
*/
public class ProviderType extends AbstractPluginSpecification {
private static final Logger LOG = LoggerFactory.getLogger(ProviderType.class);
private ProviderType(BaseEntity.Builder baseBuilder,
Map<ParameterType, ParametersSpecification> parameters,
Map<String, ResourceTypeSpecification> resourceTypes) {
super(baseBuilder, parameters, resourceTypes);
}
/**
* Given a map of field name to value, filter out all fields that are not admin overridable fields or user fields,
* and group fields by type. For example, sensitive fields will be grouped together, as will non sensitive fields.
*
* @param input Mapping of field name to value.
* @return {@link PluginFields} containing fields grouped by type.
*/
public PluginFields groupFields(Map<String, Object> input) {
PluginFields.Builder builder = PluginFields.builder();
Map<String, FieldSchema> adminFields = getParametersSpecification(ParameterType.ADMIN).getFields();
Map<String, FieldSchema> userFields = getParametersSpecification(ParameterType.USER).getFields();
for (Map.Entry<String, Object> entry : input.entrySet()) {
String field = entry.getKey();
Object fieldVal = entry.getValue();
// see if this is an overridable admin field
FieldSchema fieldSchema = adminFields.get(field);
if (fieldSchema == null || !fieldSchema.isOverride()) {
// not an overridable admin field. check if its a user field
fieldSchema = userFields.get(field);
}
// if its not a user field or an overridable admin field, ignore it
if (fieldSchema != null) {
if (fieldSchema.isSensitive()) {
builder.putSensitive(field, fieldVal);
} else {
builder.putNonsensitive(field, fieldVal);
}
} else {
LOG.info("Ignoring field {} as its not an overridable admin field or user field.", field);
}
}
return builder.build();
}
/**
* Get a builder for creating provider types.
*
* @return builder for creating provider types
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for creating provider types.
*/
public static class Builder extends AbstractPluginSpecification.Builder<ProviderType> {
@Override
public ProviderType build() {
return new ProviderType(this, parameters, resourceTypes);
}
}
}
|
923c8f816984f71541b8137e7cbb8b9d092cdad6 | 1,334 | java | Java | SortingBooks/src/Book.java | Nevzatcs/kodluyoruz-java102 | 92a9ac3e873b7c27a0184b4c0c0ecc3cae2f7119 | [
"MIT"
] | null | null | null | SortingBooks/src/Book.java | Nevzatcs/kodluyoruz-java102 | 92a9ac3e873b7c27a0184b4c0c0ecc3cae2f7119 | [
"MIT"
] | null | null | null | SortingBooks/src/Book.java | Nevzatcs/kodluyoruz-java102 | 92a9ac3e873b7c27a0184b4c0c0ecc3cae2f7119 | [
"MIT"
] | null | null | null | 23.821429 | 90 | 0.564468 | 999,974 |
public class Book implements Comparable<Book>{
private String bookName;
private int pageNumber;
private String authorName;
private int publishYear;
public Book(String bookName, int pageNumber, String authorName, int publishYear) {
this.bookName = bookName;
this.pageNumber = pageNumber;
this.authorName = authorName;
this.publishYear = publishYear;
}
@Override
public int compareTo(Book o) {
return this.bookName.compareTo(o.getBookName());
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public int getPublishYear() {
return publishYear;
}
public void setPublishYear(int publishYear) {
this.publishYear = publishYear;
}
}
|
923c900a5ba972c7bf5f248f94bb00ae755a7944 | 7,988 | java | Java | src/test/java/org/overrun/glutest/Tesselator3Test.java | Over-Run/GLUtils | 5383bedd643a6dcb7d69918fae49f515958c416f | [
"MIT"
] | 1 | 2021-06-05T02:23:23.000Z | 2021-06-05T02:23:23.000Z | src/test/java/org/overrun/glutest/Tesselator3Test.java | Over-Run/GLUtils | 5383bedd643a6dcb7d69918fae49f515958c416f | [
"MIT"
] | 3 | 2021-11-02T14:34:34.000Z | 2021-12-26T13:50:31.000Z | src/test/java/org/overrun/glutest/Tesselator3Test.java | Over-Run/GLUtils | 5383bedd643a6dcb7d69918fae49f515958c416f | [
"MIT"
] | null | null | null | 31.203125 | 81 | 0.518528 | 999,975 | /*
* MIT License
*
* Copyright (c) 2021 Overrun Organization
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.overrun.glutest;
import org.joml.Matrix4f;
import org.joml.Matrix4fStack;
import org.overrun.glutils.IndexedTesselator3;
import org.overrun.glutils.MipmapMode;
import org.overrun.glutils.Tesselator3;
import org.overrun.glutils.game.*;
import static java.lang.Math.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.overrun.glutils.game.GLStateManager.enableBlend;
import static org.overrun.glutils.game.GLStateManager.enableDepthTest;
import static org.overrun.glutils.game.GameEngine.*;
import static org.overrun.glutils.math.Transform.*;
/**
* @author squid233
*/
public class Tesselator3Test extends Game {
private float x = 0, y = 0, z = 0,
xRot = 0, yRot = 0,
xo = 0, yo = 0, zo = 0,
xd = 0, yd = 0, zd = 0;
private final Matrix4fStack mat3d = new Matrix4fStack(32);
private final Matrix4f mat2d = new Matrix4f();
private IndexedTesselator3 it;
private Tesselator3 t;
private Texture2D sth;
private class Scr extends Screen {
public Scr(final Screen parent) {
super(parent);
}
@Override
public void render() {
it.setMatrix(mat2d);
it.init()
.color(0, 0, 0, 0.5f).vertex(0, 0, 0)
.color(0, 0, 0, 0.5f).vertex(0, height, 0)
.color(0, 0, 0, 0.5f).vertex(width, height, 0)
.color(0, 0, 0, 0.5f).vertex(width, 0, 0)
.indices(0, 1, 2, 2, 3, 0)
.draw();
super.render();
}
}
@Override
public void create() {
glClearColor(0.4f, 0.6f, 0.9f, 1.0f);
enableDepthTest();
enableBlend();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
window.setGrabbed(true);
it = new IndexedTesselator3(false);
t = new Tesselator3(true)
.vertexUV(0, 0, 0, 0, 0)
.vertexUV(0, 17, 0, 0, 1)
.vertexUV(17, 17, 0, 1, 1)
.vertexUV(17, 17, 0, 1, 1)
.vertexUV(17, 0, 0, 1, 0)
.vertexUV(0, 0, 0, 0, 0);
sth = new Texture2D(ClassLoader.getSystemClassLoader(),
"tstest.png",
new MipmapMode()
.minFilter(GL_NEAREST)
.magFilter(GL_NEAREST));
}
@Override
public void render() {
float delta = timer.getDelta();
float tx = xo + (x - xo) * delta;
float ty = yo + (y - yo) * delta;
float tz = zo + (z - zo) * delta;
rotateY(
rotateX(
setPerspective(mat3d, 90, framebuffer, 0.05f, 1000.0f)
.translate(0, 0, -0.3f),
-xRot),
yRot).translate(-tx, -ty, -tz);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mat3d.pushMatrix();
float sin = (float) sin(timer.getCurrTime());
float c0 = abs(sin);
float c1 = 1 - c0;
it.setMatrix(mat3d.scaleLocal((c0 * 0.95f + 1f) / 2f));
it.init()
.color(c0, c1, c0).vertex(0, 1, 0)
.color(c0, c0, c0).vertex(0, 0, 0)
.color(c1, c0, c0).vertex(1, 0, 0)
.color(c1, c1, c0).vertex(1, 1, 0)
.color(c0, c1, c1).vertex(0, 1, -1)
.color(c0, c0, c1).vertex(0, 0, -1)
.color(c1, c0, c1).vertex(1, 0, -1)
.color(c1, c1, c1).vertex(1, 1, -1)
.indices(
// south
0, 1, 2, 2, 3, 0,
// north
7, 6, 5, 5, 4, 7,
// west
4, 5, 1, 1, 0, 4,
// east
3, 2, 6, 6, 7, 3,
// up
4, 0, 3, 3, 7, 4,
// down
1, 5, 6, 6, 2, 1
)
.draw();
mat3d.popMatrix();
mat3d.pushMatrix();
mat3d.popMatrix();
glClear(GL_DEPTH_BUFFER_BIT);
sth.bind();
t.setMatrix(mat2d);
t.draw();
sth.unbind();
super.render();
}
@Override
public void tick() {
super.tick();
xo = x;
yo = y;
zo = z;
float xa = 0, ya = 0, za = 0;
if (input.keyPressed(GLFW_KEY_W)) {
--za;
}
if (input.keyPressed(GLFW_KEY_S)) {
++za;
}
if (input.keyPressed(GLFW_KEY_A)) {
--xa;
}
if (input.keyPressed(GLFW_KEY_D)) {
++xa;
}
if (input.keyPressed(GLFW_KEY_LEFT_SHIFT)) {
--ya;
}
if (input.keyPressed(GLFW_KEY_SPACE)) {
++ya;
}
float dist = xa * xa + ya * ya + za * za;
if (dist >= 0.01) {
dist = (float) (0.1 / sqrt(dist));
xa *= dist;
ya *= dist;
za *= dist;
float sin = (float) sin(toRadians(yRot));
float cos = (float) cos(toRadians(yRot));
xd += xa * cos - za * sin;
yd += ya;
zd += za * cos + xa * sin;
}
x += xd;
y += yd;
z += zd;
xd *= 0.91 * 0.7;
yd *= 0.98 * 0.65;
zd *= 0.91 * 0.7;
}
@Override
public void resize(final int width,
final int height) {
glViewport(0, 0, width, height);
mat2d.setOrtho2D(0, width, height, 0);
super.resize(width, height);
}
@Override
public void onUpdated() {
super.onUpdated();
window.setTitle("Tesselator3 Test FPS:" + graphics.getFps());
}
@Override
public void cursorPosCb(int x, int y) {
if (window.isGrabbed()) {
xRot -= input.getDeltaMY() * 0.15;
yRot += input.getDeltaMX() * 0.15;
if (xRot < -90) {
xRot = -90;
} else if (xRot > 90) {
xRot = 90;
}
}
super.cursorPosCb(x, y);
}
@Override
public void keyReleased(final int key,
final int scancode,
final int mods) {
if (key == GLFW_KEY_ESCAPE) {
window.setGrabbed(!window.isGrabbed());
if (screen == null) {
openScreen(new Scr(null));
} else {
openScreen(screen.getParent());
}
}
super.keyReleased(key, scancode, mods);
}
@Override
public void free() {
sth.free();
it.free();
t.free();
}
public static void main(final String[] args) {
GameConfig config = new GameConfig();
config.width = 854;
config.height = 480;
config.title = "Tesselator3 Test";
//config.glVersion = 3.3;
//config.coreProfile = true;
new GameApp(new Tesselator3Test(), config);
}
}
|
923c901eabd72a38add61ce54f2f82f406c6ac8e | 1,370 | java | Java | web/src/main/java/com/bazaarvoice/emodb/web/resources/databus/PeekOrPollResponseHelper.java | sibasish-palo/emodb | b17149af391bcf0f00ce012e57fd9f28647e39c0 | [
"Apache-2.0"
] | 57 | 2016-08-26T15:26:44.000Z | 2022-02-16T07:35:27.000Z | web/src/main/java/com/bazaarvoice/emodb/web/resources/databus/PeekOrPollResponseHelper.java | sibasish-palo/emodb | b17149af391bcf0f00ce012e57fd9f28647e39c0 | [
"Apache-2.0"
] | 238 | 2016-08-25T18:13:49.000Z | 2022-03-31T13:29:35.000Z | web/src/main/java/com/bazaarvoice/emodb/web/resources/databus/PeekOrPollResponseHelper.java | sibasish-palo/emodb | b17149af391bcf0f00ce012e57fd9f28647e39c0 | [
"Apache-2.0"
] | 60 | 2016-08-25T19:25:13.000Z | 2022-03-25T14:55:38.000Z | 33.414634 | 116 | 0.743796 | 999,976 | package com.bazaarvoice.emodb.web.resources.databus;
import com.bazaarvoice.emodb.common.json.JsonHelper;
import com.bazaarvoice.emodb.databus.api.EventViews;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helper class used by peek and poll operations. This class ensures that the events returned are serialized
* including only those attributes expected by the caller. In particular, it only includes event tags if the
* caller explicitly requested to include tags.
*/
public class PeekOrPollResponseHelper {
private final JsonHelper.JsonWriterWithViewHelper _json;
public PeekOrPollResponseHelper(final Class<? extends EventViews.ContentOnly> view) {
checkNotNull(view, "view");
_json = JsonHelper.withView(view);
}
/**
* Returns a JSON helper that can be used to serialize events using the proper view.
*/
public JsonHelper.JsonWriterWithViewHelper getJson() {
return _json;
}
/**
* Returns an object that can be serialized as a response entity to output the event list using the proper view.
*/
public StreamingOutput asEntity(final Object events) {
return out -> _json.writeJson(out, events);
}
}
|
923c9217e847ed8245ad3818056d4d6a05dd9bcb | 2,996 | java | Java | asyncflows-core/src/main/java/org/asyncflows/core/vats/SingleThreadVatWithIdle.java | const/asyncflows | b398001212f7737e61b1cecc96fac1a4965e3032 | [
"MIT"
] | 5 | 2018-09-19T14:33:36.000Z | 2021-03-26T09:58:48.000Z | asyncflows-core/src/main/java/org/asyncflows/core/vats/SingleThreadVatWithIdle.java | const/asyncflows | b398001212f7737e61b1cecc96fac1a4965e3032 | [
"MIT"
] | 1 | 2020-12-29T16:06:25.000Z | 2020-12-29T16:06:25.000Z | asyncflows-core/src/main/java/org/asyncflows/core/vats/SingleThreadVatWithIdle.java | const/asyncflows | b398001212f7737e61b1cecc96fac1a4965e3032 | [
"MIT"
] | null | null | null | 27.236364 | 82 | 0.612817 | 999,977 | /*
* Copyright (c) 2018-2020 Konstantin Plotnikov
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.asyncflows.core.vats;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The single thread vat with an idle action.
*/
public abstract class SingleThreadVatWithIdle extends BatchedVat {
/**
* The stop object.
*/
private final Object myStopKey;
/**
* If true, the vat is stopped.
*/
private final AtomicBoolean stopped = new AtomicBoolean();
/**
* The constructor.
*
* @param maxBatchSize max batch size
* @param stopKey the stop key
*/
public SingleThreadVatWithIdle(final int maxBatchSize, final Object stopKey) {
super(maxBatchSize);
myStopKey = stopKey;
}
/**
* Start the vat in the current thread.
*/
public void runInCurrentThread() {
boolean hasMore = true;
while (true) {
if (hasMore) {
pollIdle();
} else {
if (stopped.get()) {
break;
} else {
idle();
}
}
hasMore = runBatch();
}
}
/**
* The idle action.
*/
protected abstract void idle();
/**
* The wake up action.
*/
protected abstract void wakeUp();
/**
* Close the vat, wake up if needed.
*/
protected abstract void closeVat();
/**
* Poll idle.
*/
protected abstract void pollIdle();
/**
* Stop the vat.
*
* @param stopKey the key used to stop the vat
*/
public void stop(final Object stopKey) {
if (myStopKey != stopKey) {
throw new IllegalArgumentException("The stop key is invalid");
}
if (stopped.compareAndSet(false, true)) {
closeVat();
}
}
@Override
protected void schedule() {
wakeUp();
}
}
|
923c92795e094845f6117e0704c782b4cecb3959 | 104 | java | Java | Dashboard/src/main/java/org/semanticcloud/web/websocket/dto/package-info.java | SemanticCloud/SemanticCloud | 39c3fc9e0ca372381051ec8812462adeab0440a6 | [
"Apache-2.0"
] | null | null | null | Dashboard/src/main/java/org/semanticcloud/web/websocket/dto/package-info.java | SemanticCloud/SemanticCloud | 39c3fc9e0ca372381051ec8812462adeab0440a6 | [
"Apache-2.0"
] | 9 | 2016-03-08T14:53:44.000Z | 2020-07-06T00:41:39.000Z | Dashboard/src/main/java/org/semanticcloud/web/websocket/dto/package-info.java | SemanticCloud/SemanticCloud | 39c3fc9e0ca372381051ec8812462adeab0440a6 | [
"Apache-2.0"
] | 1 | 2020-07-07T01:42:48.000Z | 2020-07-07T01:42:48.000Z | 20.8 | 50 | 0.75 | 999,978 | /**
* Data Access Objects used by WebSocket services.
*/
package org.semanticcloud.web.websocket.dto;
|
923c92b637f2a715b07a11efa0819bbd75a5e6ab | 916 | java | Java | Mage.Sets/src/mage/cards/v/VernadiShieldmate.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/v/VernadiShieldmate.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/v/VernadiShieldmate.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 24.105263 | 79 | 0.689956 | 999,979 | package mage.cards.v;
import java.util.UUID;
import mage.MageInt;
import mage.constants.SubType;
import mage.abilities.keyword.VigilanceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
/**
*
* @author TheElk801
*/
public final class VernadiShieldmate extends CardImpl {
public VernadiShieldmate(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{G/W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.SOLDIER);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Vigilance
this.addAbility(VigilanceAbility.getInstance());
}
private VernadiShieldmate(final VernadiShieldmate card) {
super(card);
}
@Override
public VernadiShieldmate copy() {
return new VernadiShieldmate(this);
}
}
|
923c92fa0edc855af89cbf743d1a3bf4a0706348 | 3,805 | java | Java | openapi-generator-for-spring-web/src/main/java/de/qaware/openapigeneratorforspring/common/paths/method/merger/MergedSpringWebHandlerMethodMapper.java | MueChr/openapi-generator-for-spring | a3e9399fbb3c9ad80eee9a530c99524aea7fc15e | [
"Apache-2.0"
] | 56 | 2020-12-01T10:50:22.000Z | 2022-03-23T10:46:31.000Z | openapi-generator-for-spring-web/src/main/java/de/qaware/openapigeneratorforspring/common/paths/method/merger/MergedSpringWebHandlerMethodMapper.java | MueChr/openapi-generator-for-spring | a3e9399fbb3c9ad80eee9a530c99524aea7fc15e | [
"Apache-2.0"
] | 74 | 2020-11-30T08:55:14.000Z | 2022-03-24T04:14:30.000Z | openapi-generator-for-spring-web/src/main/java/de/qaware/openapigeneratorforspring/common/paths/method/merger/MergedSpringWebHandlerMethodMapper.java | MueChr/openapi-generator-for-spring | a3e9399fbb3c9ad80eee9a530c99524aea7fc15e | [
"Apache-2.0"
] | 4 | 2020-12-04T09:55:09.000Z | 2021-12-21T13:07:41.000Z | 43.735632 | 138 | 0.727201 | 999,980 | /*-
* #%L
* OpenAPI Generator for Spring Boot :: Web
* %%
* Copyright (C) 2020 QAware GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package de.qaware.openapigeneratorforspring.common.paths.method.merger;
import de.qaware.openapigeneratorforspring.common.mapper.MapperContext;
import de.qaware.openapigeneratorforspring.common.mapper.MediaTypesProvider;
import de.qaware.openapigeneratorforspring.common.paths.HandlerMethod;
import de.qaware.openapigeneratorforspring.model.requestbody.RequestBody;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import javax.annotation.Nullable;
import java.util.List;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MergedSpringWebHandlerMethodMapper {
public static class ContextModifierMapper implements HandlerMethod.ContextModifierMapper<MapperContext> {
@Nullable
@Override
public HandlerMethod.ContextModifier<MapperContext> map(@Nullable HandlerMethod.Context context) {
if (context instanceof MergedSpringWebHandlerMethodContext) {
MergedSpringWebHandlerMethodContext mergedHandlerMethodContext = (MergedSpringWebHandlerMethodContext) context;
MediaTypesProvider mediaTypesProvider = owningType -> {
if (RequestBody.class.equals(owningType)) {
return mergedHandlerMethodContext.getConsumesContentTypes();
}
throw new IllegalStateException("Cannot provide media types for " + owningType.getSimpleName() + " in merged method");
};
return mapperContext -> mapperContext.withMediaTypesProvider(mediaTypesProvider);
}
return null; // indicates we can't map this handler method context
}
}
@RequiredArgsConstructor
public static class RequestBodyMapper implements HandlerMethod.RequestBodyMapper {
private final SpringWebHandlerMethodRequestBodyMerger requestBodyMerger;
@Nullable
@Override
public List<HandlerMethod.RequestBody> map(HandlerMethod handlerMethod) {
if (handlerMethod instanceof MergedSpringWebHandlerMethod) {
MergedSpringWebHandlerMethod mergedSpringWebHandlerMethod = (MergedSpringWebHandlerMethod) handlerMethod;
return requestBodyMerger.mergeRequestBodies(mergedSpringWebHandlerMethod.getHandlerMethods());
}
return null; // indicates we can't map this handler method instance
}
}
@RequiredArgsConstructor
public static class ResponseMapper implements HandlerMethod.ResponseMapper {
private final SpringWebHandlerMethodResponseMerger responseMerger;
@Nullable
@Override
public List<HandlerMethod.Response> map(HandlerMethod handlerMethod) {
if (handlerMethod instanceof MergedSpringWebHandlerMethod) {
MergedSpringWebHandlerMethod mergedSpringWebHandlerMethod = (MergedSpringWebHandlerMethod) handlerMethod;
return responseMerger.mergeResponses(mergedSpringWebHandlerMethod.getHandlerMethods());
}
return null; // indicates we can't map this handler method instance
}
}
}
|
923c930ebebfffe17d26f578324d6551b6e935cb | 790 | java | Java | DECODEIT.java | Milon34/CodeShef_Problem_Solution_Java | 610cf726d56e51bf3c97d905de41703e755d7cc5 | [
"MIT"
] | null | null | null | DECODEIT.java | Milon34/CodeShef_Problem_Solution_Java | 610cf726d56e51bf3c97d905de41703e755d7cc5 | [
"MIT"
] | null | null | null | DECODEIT.java | Milon34/CodeShef_Problem_Solution_Java | 610cf726d56e51bf3c97d905de41703e755d7cc5 | [
"MIT"
] | null | null | null | 26.333333 | 51 | 0.379747 | 999,981 | package CodeShef;
import java.util.Scanner;
public class DECODEIT {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
String s = "abcdefghijklmnop";
char ch[] = sc.next().toCharArray();
int l = 0, h = 15;
StringBuilder sb = new StringBuilder();
for(char c : ch){
if(c == '0'){
h = (h+l)/2;
}else {
l = (h+l)/2 + 1;
}
if(l == h){
sb.append(s.charAt(l));
l = 0; h = 15;
}
}
System.out.println(sb);
}
}
}
|
923c93a66caf9fc0515720d3dd540c14ffac64aa | 1,628 | java | Java | commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/product_discount/ProductDiscountSetValidUntilActionBuilder.java | pintomau/commercetools-sdk-java-v2 | 503a767d35b1495b2740f96082a235cd2d82409f | [
"Apache-2.0"
] | 17 | 2020-09-23T10:01:29.000Z | 2022-03-21T05:58:32.000Z | commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/product_discount/ProductDiscountSetValidUntilActionBuilder.java | pintomau/commercetools-sdk-java-v2 | 503a767d35b1495b2740f96082a235cd2d82409f | [
"Apache-2.0"
] | 130 | 2020-08-25T08:16:38.000Z | 2022-03-31T10:19:58.000Z | commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/product_discount/ProductDiscountSetValidUntilActionBuilder.java | pintomau/commercetools-sdk-java-v2 | 503a767d35b1495b2740f96082a235cd2d82409f | [
"Apache-2.0"
] | 6 | 2021-06-17T08:42:53.000Z | 2022-03-09T13:16:20.000Z | 33.22449 | 120 | 0.767199 | 999,982 |
package com.commercetools.api.models.product_discount;
import java.util.*;
import javax.annotation.Nullable;
import io.vrap.rmf.base.client.Builder;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
public class ProductDiscountSetValidUntilActionBuilder implements Builder<ProductDiscountSetValidUntilAction> {
@Nullable
private java.time.ZonedDateTime validUntil;
public ProductDiscountSetValidUntilActionBuilder validUntil(@Nullable final java.time.ZonedDateTime validUntil) {
this.validUntil = validUntil;
return this;
}
@Nullable
public java.time.ZonedDateTime getValidUntil() {
return this.validUntil;
}
public ProductDiscountSetValidUntilAction build() {
return new ProductDiscountSetValidUntilActionImpl(validUntil);
}
/**
* builds ProductDiscountSetValidUntilAction without checking for non null required values
*/
public ProductDiscountSetValidUntilAction buildUnchecked() {
return new ProductDiscountSetValidUntilActionImpl(validUntil);
}
public static ProductDiscountSetValidUntilActionBuilder of() {
return new ProductDiscountSetValidUntilActionBuilder();
}
public static ProductDiscountSetValidUntilActionBuilder of(final ProductDiscountSetValidUntilAction template) {
ProductDiscountSetValidUntilActionBuilder builder = new ProductDiscountSetValidUntilActionBuilder();
builder.validUntil = template.getValidUntil();
return builder;
}
}
|
923c941d1c2fb2268aa137c182f9cf536bde1662 | 825 | java | Java | MPP Labs/Tema-Laborator11-MPP/Proiect-Java-MPP/Networking/src/main/java/touristagency/network/dto/EmployeeDTO.java | georgeindries/mpp-projects | 5687658ed7372fc5e6d22489a5c1cfa8fecaed6c | [
"MIT"
] | null | null | null | MPP Labs/Tema-Laborator11-MPP/Proiect-Java-MPP/Networking/src/main/java/touristagency/network/dto/EmployeeDTO.java | georgeindries/mpp-projects | 5687658ed7372fc5e6d22489a5c1cfa8fecaed6c | [
"MIT"
] | null | null | null | MPP Labs/Tema-Laborator11-MPP/Proiect-Java-MPP/Networking/src/main/java/touristagency/network/dto/EmployeeDTO.java | georgeindries/mpp-projects | 5687658ed7372fc5e6d22489a5c1cfa8fecaed6c | [
"MIT"
] | null | null | null | 21.153846 | 58 | 0.589091 | 999,983 | package touristagency.network.dto;
import java.io.Serializable;
public class EmployeeDTO implements Serializable {
private String username;
private String password;
public EmployeeDTO(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "EmployeeDTO[" +
"username='" + username + '\'' +
", password='" + password + '\'' +
']';
}
}
|
923c947aac12e45cd6a132e15fde054344e9e148 | 1,405 | java | Java | src/test/java/com/youzan/bigdata/query/NestedQueryTest.java | maoxiajun/query-builder4es-lite | 5c266450bfd13127c6a5de761087cea279c89bf9 | [
"Apache-2.0"
] | 3 | 2019-04-01T03:30:27.000Z | 2019-07-15T03:43:01.000Z | src/test/java/com/youzan/bigdata/query/NestedQueryTest.java | maoxiajun/query-builder4es-lite | 5c266450bfd13127c6a5de761087cea279c89bf9 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/youzan/bigdata/query/NestedQueryTest.java | maoxiajun/query-builder4es-lite | 5c266450bfd13127c6a5de761087cea279c89bf9 | [
"Apache-2.0"
] | null | null | null | 33.452381 | 230 | 0.600712 | 999,984 | package com.youzan.bigdata.query;
import com.fordeal.search.QueryBuilders;
import com.fordeal.search.query.Bool;
import com.fordeal.search.query.Nested;
import com.fordeal.search.query.Term;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Created by maoxiajun on 17/12/12.
*/
public class NestedQueryTest {
private Nested nested;
private Bool bool;
@Before
public void setUp() {
nested = new Nested("admin", new Term("admin.admin_id", 5161096));
bool = new Bool().must(new Term("admin.admin_id", 5161096));
}
@Test
public void testX5() {
Assert.assertEquals("{\"nested\":{\"path\":\"admin\",\"query\":{\"term\":{\"admin.admin_id\":5161096}}}}", nested.toJsonString());
nested.query(bool);
Assert.assertEquals("{\"nested\":{\"path\":\"admin\",\"query\":{\"bool\":{\"must\":[{\"term\":{\"admin.admin_id\":5161096}}]}}}}",
nested.toJsonString());
}
@Test
public void testBuilder() {
nested.query(bool);
Assert.assertEquals("{\"size\":10,\"query\":{\"bool\":{\"must\":[{\"nested\":{\"path\":\"admin\",\"query\":{\"bool\":{\"must\":[{\"term\":{\"admin.admin_id\":5161096}}]}}}},{\"term\":{\"kdt_id\":26203600}}]}},\"from\":0}",
QueryBuilders.x5().addQuery(new Bool().must(nested).must(new Term("kdt_id", 26203600))).toJsonString());
}
}
|
923c95951969c7327efabd9c534bb2da5a7a95c9 | 26,327 | java | Java | engine/src/main/java/org/camunda/bpm/engine/ExternalTaskService.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 2,577 | 2015-01-02T07:43:55.000Z | 2022-03-31T22:31:45.000Z | engine/src/main/java/org/camunda/bpm/engine/ExternalTaskService.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 839 | 2015-01-12T22:06:28.000Z | 2022-03-24T13:26:29.000Z | engine/src/main/java/org/camunda/bpm/engine/ExternalTaskService.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 1,270 | 2015-01-02T03:39:25.000Z | 2022-03-31T06:04:37.000Z | 52.654 | 210 | 0.726365 | 999,985 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine;
import java.util.List;
import java.util.Map;
import org.camunda.bpm.engine.authorization.BatchPermissions;
import org.camunda.bpm.engine.authorization.Permissions;
import org.camunda.bpm.engine.authorization.Resources;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.exception.NotFoundException;
import org.camunda.bpm.engine.externaltask.ExternalTask;
import org.camunda.bpm.engine.externaltask.ExternalTaskQuery;
import org.camunda.bpm.engine.externaltask.ExternalTaskQueryBuilder;
import org.camunda.bpm.engine.externaltask.UpdateExternalTaskRetriesBuilder;
import org.camunda.bpm.engine.externaltask.UpdateExternalTaskRetriesSelectBuilder;
/**
* Service that provides access to {@link ExternalTask} instances. External tasks
* represent work items that are processed externally and independently of the process
* engine.
*
* @author Thorben Lindhauer
* @author Christopher Zell
*/
public interface ExternalTaskService {
/**
* Calls method fetchAndLock(maxTasks, workerId, usePriority), where usePriority is false.
*
* @param maxTasks the maximum number of tasks to return
* @param workerId the id of the worker to lock the tasks for
* @return a builder to define and execute an external task fetching operation
* @see {@link ExternalTaskService#fetchAndLock(int, java.lang.String, boolean)}.
*/
public ExternalTaskQueryBuilder fetchAndLock(int maxTasks, String workerId);
/**
* <p>Defines fetching of external tasks by using a fluent builder.
* The following parameters must be specified:
* A worker id, a maximum number of tasks to fetch and a flag that indicates
* whether priority should be regarded or not.
* The builder allows to specify multiple topics to fetch tasks for and
* individual lock durations. For every topic, variables can be fetched
* in addition. If priority is enabled, the tasks with the highest priority are fetched.</p>
*
* <p>Returned tasks are locked for the given worker until
* <code>now + lockDuration</code> expires.
* Locked tasks cannot be fetched or completed by other workers. When the lock time has expired,
* a task may be fetched and locked by other workers.</p>
*
* <p>Returns at most <code>maxTasks</code> tasks. The tasks are arbitrarily
* distributed among the specified topics. Example: Fetching 10 tasks of topics
* "a"/"b"/"c" may return 3/3/4 tasks, or 10/0/0 tasks, etc.</p>
*
* <p>May return less than <code>maxTasks</code> tasks, if there exist not enough
* unlocked tasks matching the provided topics or if parallel fetching by other workers
* results in locking failures.</p>
*
* <p>
* Returns only tasks that the currently authenticated user has at least one
* permission out of all of the following groups for:
*
* <ul>
* <li>{@link Permissions#READ} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#READ_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
* </p>
*
* @param maxTasks the maximum number of tasks to return
* @param workerId the id of the worker to lock the tasks for
* @param usePriority the flag to enable the priority fetching mechanism
* @return a builder to define and execute an external task fetching operation
*/
public ExternalTaskQueryBuilder fetchAndLock(int maxTasks, String workerId, boolean usePriority);
/**
* <p>Lock an external task on behalf of a worker.
* Note: Attempting to lock an already locked external task with the same <code>workerId</code>
* will succeed and a new lock duration will be set, starting from the current moment.
* </p>
*
* @param externalTaskId the id of the external task to lock
* @param workerId the id of the worker to lock the task for
* @param lockDuration the duration in milliseconds for which task should be locked
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task was already locked by a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void lock(String externalTaskId, String workerId, long lockDuration);
/**
* <p>Completes an external task on behalf of a worker. The given task must be
* assigned to the worker.</p>
*
* @param externalTaskId the id of the external task to complete
* @param workerId the id of the worker that completes the task
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void complete(String externalTaskId, String workerId);
/**
* <p>Completes an external task on behalf of a worker and submits variables
* to the process instance before continuing execution. The given task must be
* assigned to the worker.</p>
*
* @param externalTaskId the id of the external task to complete
* @param workerId the id of the worker that completes the task
* @param variables a map of variables to set on the execution (non-local)
* the external task is assigned to
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void complete(String externalTaskId, String workerId, Map<String, Object> variables);
/**
* <p>Completes an external task on behalf of a worker and submits variables
* to the process instance before continuing execution. The given task must be
* assigned to the worker.</p>
*
* @param externalTaskId the id of the external task to complete
* @param workerId the id of the worker that completes the task
* @param variables a map of variables to set on the execution
* the external task is assigned to
* @param localVariables a map of variables to set on the execution locally
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void complete(String externalTaskId, String workerId, Map<String, Object> variables, Map<String, Object> localVariables);
/**
* <p>Extends a lock of an external task on behalf of a worker.
* The given task must be assigned to the worker.</p>
*
* @param externalTaskId the id of the external task
* @param workerId the id of the worker that extends the lock of the task
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void extendLock(String externalTaskId, String workerId, long newLockDuration);
/**
* <p>Signals that an external task could not be successfully executed.
* The task must be assigned to the given worker. The number of retries left can be specified. In addition, a timeout can be
* provided, such that the task cannot be fetched before <code>now + retryTimeout</code> again.</p>
*
* <p>If <code>retries</code> is 0, an incident with the given error message is created. The incident gets resolved,
* once the number of retries is increased again.</p>
*
* <p>Exceptions raised in evaluating expressions of error event definitions attached to the task will be ignored by this method
* and the event definitions considered as not-matching.</p>
*
* @param externalTaskId the id of the external task to report a failure for
* @param workerId the id of the worker that reports the failure
* @param errorMessage short error message related to this failure. This message can be retrieved via
* {@link ExternalTask#getErrorMessage()} and is used as the incident message in case <code>retries</code> is <code>null</code>.
* May be <code>null</code>.
* @param retries the number of retries left. External tasks with 0 retries cannot be fetched anymore unless
* the number of retries is increased via API. Must be >= 0.
* @param retryTimeout the timeout before the task can be fetched again. Must be >= 0.
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void handleFailure(String externalTaskId, String workerId, String errorMessage, int retries, long retryTimeout);
/**
* <p>Signals that an external task could not be successfully executed.
* The task must be assigned to the given worker. The number of retries left can be specified. In addition, a timeout can be
* provided, such that the task cannot be fetched before <code>now + retryTimeout</code> again.</p>
*
* <p>If <code>retries</code> is 0, an incident with the given error message is created. The incident gets resolved,
* once the number of retries is increased again.</p>
*
* <p>Exceptions raised in evaluating expressions of error event definitions attached to the task will be ignored by this method
* and the event definitions considered as not-matching.</p>
*
* @param externalTaskId the id of the external task to report a failure for
* @param workerId the id of the worker that reports the failure
* @param errorMessage short error message related to this failure. This message can be retrieved via
* {@link ExternalTask#getErrorMessage()} and is used as the incident message in case <code>retries</code> is <code>null</code>.
* May be <code>null</code>.
* @param errorDetails full error message related to this failure. This message can be retrieved via
* {@link ExternalTaskService#getExternalTaskErrorDetails(String)} ()}
* @param retries the number of retries left. External tasks with 0 retries cannot be fetched anymore unless
* the number of retries is increased via API. Must be >= 0.
* @param retryTimeout the timeout before the task can be fetched again. Must be >= 0.
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void handleFailure(String externalTaskId, String workerId, String errorMessage, String errorDetails, int retries, long retryTimeout);
/**
* <p>Signals that an external task could not be successfully executed.
* The task must be assigned to the given worker. The number of retries left can be specified. In addition, a timeout can be
* provided, such that the task cannot be fetched before <code>now + retryTimeout</code> again.</p>
*
* <p>If <code>retries</code> is 0, an incident with the given error message is created. The incident gets resolved,
* once the number of retries is increased again.</p>
*
* <p>Exceptions raised in evaluating expressions of error event definitions attached to the task will be ignored by this method
* and the event definitions considered as not-matching.</p>
*
* Variables passed with the <code>variables</code> or <code>localVariables</code> parameter will be set before any
* output mapping is performed.
*
* @param externalTaskId the id of the external task to report a failure for
* @param workerId the id of the worker that reports the failure
* @param errorMessage short error message related to this failure. This message can be retrieved via
* {@link ExternalTask#getErrorMessage()} and is used as the incident message in case <code>retries</code> is <code>null</code>.
* May be <code>null</code>.
* @param errorDetails full error message related to this failure. This message can be retrieved via
* {@link ExternalTaskService#getExternalTaskErrorDetails(String)} ()}
* @param retries the number of retries left. External tasks with 0 retries cannot be fetched anymore unless
* the number of retries is increased via API. Must be >= 0.
* @param retryTimeout the timeout before the task can be fetched again. Must be >= 0.
* @param variables a map of variables to set on the execution
* the external task is assigned to
* @param localVariables a map of variables to set on the execution locally
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void handleFailure(String externalTaskId, String workerId, String errorMessage, String errorDetails, int retries, long retryDuration, Map<String, Object> variables, Map<String, Object> localVariables);
/**
* <p>Signals that an business error appears, which should be handled by the process engine.
* The task must be assigned to the given worker. The error will be propagated to the next error handler.
* Is no existing error handler for the given bpmn error the activity instance of the external task
* ends.</p>
*
* @param externalTaskId the id of the external task to report a bpmn error
* @param workerId the id of the worker that reports the bpmn error
* @param errorCode the error code of the corresponding bmpn error
* @since 7.5
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void handleBpmnError(String externalTaskId, String workerId, String errorCode);
/**
* <p>Signals that an business error appears, which should be handled by the process engine.
* The task must be assigned to the given worker. The error will be propagated to the next error handler.
* Is no existing error handler for the given bpmn error the activity instance of the external task
* ends.</p>
*
* @param externalTaskId the id of the external task to report a bpmn error
* @param workerId the id of the worker that reports the bpmn error
* @param errorCode the error code of the corresponding bmpn error
* @param errorMessage the error message of the corresponding bmpn error
* @since 7.10
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void handleBpmnError(String externalTaskId, String workerId, String errorCode, String errorMessage);
/**
* <p>Signals that an business error appears, which should be handled by the process engine.
* The task must be assigned to the given worker. The error will be propagated to the next error handler.
* Is no existing error handler for the given bpmn error the activity instance of the external task
* ends.</p>
*
* @param externalTaskId the id of the external task to report a bpmn error
* @param workerId the id of the worker that reports the bpmn error
* @param errorCode the error code of the corresponding bmpn error
* @param errorMessage the error message of the corresponding bmpn error
* @param variables the variables to pass to the execution
* @since 7.10
*
* @throws NotFoundException if no external task with the given id exists
* @throws BadUserRequestException if the task is assigned to a different worker
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void handleBpmnError(String externalTaskId, String workerId, String errorCode, String errorMessage, Map<String, Object> variables);
/**
* Unlocks an external task instance.
*
* @param externalTaskId the id of the task to unlock
* @throws NotFoundException if no external task with the given id exists
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void unlock(String externalTaskId);
/**
* Sets the retries for an external task. If the new value is 0, a new incident with a <code>null</code>
* message is created. If the old value is 0 and the new value is greater than 0, an existing incident
* is resolved.
*
* @param externalTaskId the id of the task to set the
* @param retries
* @throws NotFoundException if no external task with the given id exists
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void setRetries(String externalTaskId, int retries);
/**
* Sets the retries for external tasks. If the new value is 0, a new incident with a <code>null</code>
* message is created. If the old value is 0 and the new value is greater than 0, an existing incident
* is resolved.
*
* @param externalTaskIds the ids of the tasks to set the
* @param retries
* @throws NotFoundException if no external task with one of the given id exists
* @throws BadUserRequestException if the ids are null or the number of retries is negative
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void setRetries(List<String> externalTaskIds, int retries);
/**
* Sets the retries for external tasks asynchronously as batch. The returned batch
* can be used to track the progress. If the new value is 0, a new incident with a <code>null</code>
* message is created. If the old value is 0 and the new value is greater than 0, an existing incident
* is resolved.
*
*
* @return the batch
*
* @param externalTaskIds the ids of the tasks to set the
* @param retries
* @param externalTaskQuery a query which selects the external tasks to set the retries for.
* @throws NotFoundException if no external task with one of the given id exists
* @throws BadUserRequestException if the ids are null or the number of retries is negative
* @throws AuthorizationException
* If the user has no {@link Permissions#CREATE} or
* {@link BatchPermissions#CREATE_BATCH_SET_EXTERNAL_TASK_RETRIES} permission on {@link Resources#BATCH}.
*/
public Batch setRetriesAsync(List<String> externalTaskIds, ExternalTaskQuery externalTaskQuery, int retries);
/**
* Sets the retries for external tasks using a fluent builder.
*
* Specify the instances by calling one of the following methods, like
* <i>externalTaskIds</i>. To set the retries call
* {@link UpdateExternalTaskRetriesBuilder#set(int)} or
* {@link UpdateExternalTaskRetriesBuilder#setAsync(int)}.
*
* @since 7.8
*/
public UpdateExternalTaskRetriesSelectBuilder updateRetries();
/**
* Sets the priority for an external task.
*
* @param externalTaskId the id of the task to set the
* @param priority the new priority of the task
* @throws NotFoundException if no external task with the given id exists
* @throws AuthorizationException thrown if the current user does not possess any of the following permissions:
* <ul>
* <li>{@link Permissions#UPDATE} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#UPDATE_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
*/
public void setPriority(String externalTaskId, long priority);
/**
* <p>
* Queries for tasks that the currently authenticated user has at least one
* of the following permissions for:
*
* <ul>
* <li>{@link Permissions#READ} on {@link Resources#PROCESS_INSTANCE}</li>
* <li>{@link Permissions#READ_INSTANCE} on {@link Resources#PROCESS_DEFINITION}</li>
* </ul>
* </p>
*
* @return a new {@link ExternalTaskQuery} that can be used to dynamically
* query for external tasks.
*/
public ExternalTaskQuery createExternalTaskQuery();
/**
* Returns a list of distinct topic names of all currently existing external tasks.
* Returns an empty list if no topics are found.
*/
List<String> getTopicNames();
/**
* Returns a list of distinct topic names of all currently existing external tasks
* restricted by the parameters.
* Returns an empty list if no matching tasks are found.
* Parameters are conjunctive, i.e. only tasks are returned that match all parameters
* with value <code>true</code>. Parameters with value <code>false</code> are effectively ignored.
* For example, this means that an empty list is returned if both <code>withLockedTasks</code>
* and <code>withUnlockedTasks</code> are true.
*
* @param withLockedTasks return only topic names of unlocked tasks
* @param withUnlockedTasks return only topic names of locked tasks
* @param withRetriesLeft return only topic names of tasks with retries remaining
*/
List<String> getTopicNames(boolean withLockedTasks, boolean withUnlockedTasks, boolean withRetriesLeft);
/**
* Returns the full error details that occurred while running external task
* with the given id. Returns null when the external task has no error details.
*
* @param externalTaskId id of the external task, cannot be null.
*
* @throws ProcessEngineException
* When no external task exists with the given id.
* @throws AuthorizationException
* If the user has no {@link Permissions#READ} permission on {@link Resources#PROCESS_INSTANCE}
* or no {@link Permissions#READ_INSTANCE} permission on {@link Resources#PROCESS_DEFINITION}.
* @since 7.6
*/
String getExternalTaskErrorDetails(String externalTaskId);
} |
923c99bdc46d0e32e954713e58f1702c6adff59d | 13,620 | java | Java | src/main/java/usa/cactuspuppy/uhc_automation/utils/BiHashMap.java | CactusPuppy/uhcautomation | 537293fd279a3a90983cc20327b3aab990ebb0e0 | [
"MIT"
] | 3 | 2018-05-06T05:11:14.000Z | 2018-08-09T18:45:03.000Z | src/main/java/usa/cactuspuppy/uhc_automation/utils/BiHashMap.java | CactusPuppy/uhcautomation | 537293fd279a3a90983cc20327b3aab990ebb0e0 | [
"MIT"
] | 13 | 2018-05-15T17:44:10.000Z | 2018-11-30T21:05:08.000Z | src/main/java/usa/cactuspuppy/uhc_automation/utils/BiHashMap.java | CactusPuppy/uhcautomation | 537293fd279a3a90983cc20327b3aab990ebb0e0 | [
"MIT"
] | null | null | null | 45.704698 | 138 | 0.604552 | 999,986 | package usa.cactuspuppy.uhc_automation.utils;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class BiHashMap<K, V> implements Map<K, V> {
private HashMap<K, V> keyToValue = new HashMap<>();
private HashMap<V, K> valueToKey = new HashMap<>();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than {@code Integer.MAX_VALUE} elements, returns
* {@code Integer.MAX_VALUE}.
*
* @return the number of key-value mappings in this map
*/
@Override
public int size() {
return keyToValue.size();
}
/**
* Returns {@code true} if this map contains no key-value mappings.
*
* @return {@code true} if this map contains no key-value mappings
*/
@Override
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns {@code true} if this map contains a mapping for the specified
* key. More formally, returns {@code true} if and only if
* this map contains a mapping for a key {@code k} such that
* {@code Objects.equals(key, k)}. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return {@code true} if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
*/
@Override
public boolean containsKey(Object key) {
return keyToValue.containsKey(key);
}
/**
* Returns {@code true} if this map maps one or more keys to the
* specified value. More formally, returns {@code true} if and only if
* this map contains at least one mapping to a value {@code v} such that
* {@code Objects.equals(value, v)}. This operation
* will probably require time linear in the map size for most
* implementations of the {@code Map} interface.
*
* @param value value whose presence in this map is to be tested
* @return {@code true} if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
*/
@Override
public boolean containsValue(Object value) {
return valueToKey.containsKey(value);
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that
* {@code Objects.equals(key, k)},
* then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
*/
@Override
public V get(Object key) {
return keyToValue.get(key);
}
public K getKey(V value) {
return valueToKey.get(value);
}
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* {@code m} is said to contain a mapping for a key {@code k} if and only
* if {@link #containsKey(Object) m.containsKey(k)} would return
* {@code true}.)
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key},
* if the implementation supports {@code null} values.)
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
*/
@Override
public V put(K key, V value) {
if (containsValue(value)) {
K oldKey = valueToKey.get(value);
keyToValue.remove(oldKey);
}
if (containsKey(key)) {
V oldValue = keyToValue.get(key);
valueToKey.remove(oldValue);
}
keyToValue.put(key, value);
valueToKey.put(value, key);
return value;
}
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key {@code k} to value {@code v} such that
* {@code Objects.equals(key, k)}, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or {@code null} if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to {@code null}.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* @throws UnsupportedOperationException if the {@code remove} operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
*/
@Override
public V remove(Object key) {
V value = keyToValue.get(key);
keyToValue.remove(key);
valueToKey.remove(value);
return value;
}
public K removeValue(V value) {
K key = valueToKey.get(value);
keyToValue.remove(key);
valueToKey.remove(value);
return key;
}
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(Object, Object) put(k, v)} on this map once
* for each mapping from key {@code k} to value {@code v} in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the {@code putAll} operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (K key : m.keySet()) {
put(key, m.get(key));
}
}
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the {@code clear} operation
* is not supported by this map
*/
@Override
public void clear() {
keyToValue = new HashMap<>();
valueToKey = new HashMap<>();
}
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own {@code remove} operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations. It does not support the {@code add} or {@code addAll}
* operations.
*
* @return a set view of the keys contained in this map
*/
@Override
public Set<K> keySet() {
return keyToValue.keySet();
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own {@code remove} operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll} and {@code clear} operations. It does not
* support the {@code add} or {@code addAll} operations.
*
* @return a collection view of the values contained in this map
*/
@Override
public Collection<V> values() {
return valueToKey.keySet();
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own {@code remove} operation, or through the
* {@code setValue} operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Set.remove}, {@code removeAll}, {@code retainAll} and
* {@code clear} operations. It does not support the
* {@code add} or {@code addAll} operations.
*
* @return a set view of the mappings contained in this map
*/
@Override
public Set<Entry<K, V>> entrySet() {
return keyToValue.entrySet();
}
}
|
923c9a25b98de9821692a245b038ec764f55b7af | 1,160 | java | Java | Q6.java | Ashishvrm487/BCE-C501-AUT-SEM | 398636b655a7dd66fc6458d51a03fd44523af19e | [
"MIT"
] | null | null | null | Q6.java | Ashishvrm487/BCE-C501-AUT-SEM | 398636b655a7dd66fc6458d51a03fd44523af19e | [
"MIT"
] | null | null | null | Q6.java | Ashishvrm487/BCE-C501-AUT-SEM | 398636b655a7dd66fc6458d51a03fd44523af19e | [
"MIT"
] | null | null | null | 31.351351 | 84 | 0.527586 | 999,987 | import java.util.*;
class Q6
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
double x1=0,x2=0,discriminant,a,b,c;
System.out.println("Enter the cofficient of x^2 in the quadratic equation");
a = sc.nextDouble();
System.out.println("Enter the cofficient of x in the quadratic equation");
b = sc.nextDouble();
System.out.println("Enter the value of constant in the quadratic equation");
c = sc.nextDouble();
discriminant = b*b - 4*a*c;
if(discriminant>=0)
{
x1 = (-b + Math.sqrt(discriminant))/(2*a);
x2 = (-b - Math.sqrt(discriminant))/(2*a);
}
if(discriminant<0)
{
System.out.println("Imaginary Roots");
}
else if(discriminant>0)
{
System.out.println("Unequal Roots");
System.out.println("Roots");
System.out.println(x1+"\t"+x2);
}
else
{
System.out.println("Equal Roots");
System.out.println("Roots");
System.out.println(x1+"\t"+x2);
}
}
} |
923c9ba36229ee6ba42175c30da0c8477911ca58 | 4,657 | java | Java | src/matlabcontrol/MatlabBroadcaster.java | shisheng-1/matconsolectl | 37e44fc825a9e53c268d29f6b9aa5b9f2afe3682 | [
"BSD-3-Clause"
] | 47 | 2015-10-19T12:19:27.000Z | 2022-03-30T10:13:08.000Z | src/matlabcontrol/MatlabBroadcaster.java | shisheng-1/matconsolectl | 37e44fc825a9e53c268d29f6b9aa5b9f2afe3682 | [
"BSD-3-Clause"
] | 18 | 2016-04-09T19:59:46.000Z | 2020-11-13T06:58:19.000Z | src/matlabcontrol/MatlabBroadcaster.java | shisheng-1/matconsolectl | 37e44fc825a9e53c268d29f6b9aa5b9f2afe3682 | [
"BSD-3-Clause"
] | 18 | 2015-12-10T07:12:59.000Z | 2021-11-05T23:08:34.000Z | 31.053333 | 114 | 0.723057 | 999,988 | /*
* Code licensed under new-style BSD (see LICENSE).
* All code up to tags/original: Copyright (c) 2013, Joshua Kaplan
* All code after tags/original: Copyright (c) 2016, DiffPlug
*/
package matlabcontrol;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Timer;
import java.util.TimerTask;
/**
* Enables a session of MATLAB to be connected to by matlabcontrol running outside MATLAB.
*
* @since 4.0.0
*
* @author <a href="mailto:dycjh@example.com">Joshua Kaplan</a>
*/
class MatlabBroadcaster {
/**
* A reference to the RMI registry which holds {@code MatlabSession}s.
*/
private static Registry _registry = null;
/**
* Represents this session of MATLAB.
*/
private static final MatlabSessionImpl _session = new MatlabSessionImpl();
/**
* The frequency (in milliseconds) with which to check if the connection to the registry still exists.
*/
private static final int BROADCAST_CHECK_PERIOD = 1000;
/**
* The timer used to check if still connected to the registry.
*/
private static final Timer _broadcastTimer = new Timer("MLC Broadcast Maintainer");
/**
* Private constructor so this class cannot be constructed.
*/
private MatlabBroadcaster() {}
/**
* Returns the session object bound to the RMI registry by this broadcaster.
*
* @return
*/
static MatlabSessionImpl getSession() {
return _session;
}
/**
* Makes this session of MATLAB visible to matlabcontrol. Once broadcasting, matlabcontrol running outside MATLAB
* will be able to connect to this session of MATLAB.
*
* @throws MatlabConnectionException thrown if not running inside MATLAB or unable to broadcast
*/
synchronized static void broadcast(int broadcastPort) throws MatlabConnectionException {
//If the registry hasn't been created
if (_registry == null) {
//Create or retrieve an RMI registry
setupRegistry(broadcastPort);
//Register this session so that it can be reconnected to
bindSession();
//If the registry becomes disconnected, either create a new one or locate a new one
maintainRegistryConnection(broadcastPort);
}
}
/**
* Attempts to create a registry, and if that cannot be done, then attempts to get an existing registry.
*
* @throws MatlabConnectionException if a registry can neither be created nor retrieved
*/
private static void setupRegistry(int broadcastPort) throws MatlabConnectionException {
try {
_registry = LocalHostRMIHelper.createRegistry(broadcastPort);
}
//If we can't create one, try to retrieve an existing one
catch (Exception e) {
try {
_registry = LocalHostRMIHelper.getRegistry(broadcastPort);
} catch (Exception ex) {
throw new MatlabConnectionException("Could not create or connect to the RMI registry", ex);
}
}
}
/**
* Binds the session object, an instance of {@link MatlabSession} to the registry with {@link #SESSION_ID}.
*
* @throws MatlabConnectionException
*/
private static void bindSession() throws MatlabConnectionException {
//Unexport the object, it will throw an exception if it is not bound - so ignore that
try {
UnicastRemoteObject.unexportObject(_session, true);
} catch (NoSuchObjectException e) {}
try {
_registry.bind(_session.getSessionID(), LocalHostRMIHelper.exportObject(_session));
} catch (Exception e) {
throw new MatlabConnectionException("Could not register this session of MATLAB", e);
}
}
/**
* Checks with a timer that the registry still exists and that the session object is exported to it. If either
* stop being the case then an attempt is made to re-establish.
*/
private static void maintainRegistryConnection(final int broadcastPort) {
//Configure the a timer to monitor the broadcast
_broadcastTimer.schedule(new TimerTask() {
@Override
public void run() {
//Check if the registry is connected
try {
//Will succeed if connected and the session object is still exported
_registry.lookup(_session.getSessionID());
}
//Session object is no longer exported
catch (NotBoundException e) {
try {
bindSession();
}
//Nothing more can be done if this fails
catch (MatlabConnectionException ex) {}
}
//Registry is no longer connected
catch (RemoteException e) {
try {
setupRegistry(broadcastPort);
bindSession();
}
//Nothing more can be done if this fails
catch (MatlabConnectionException ex) {}
}
}
}, BROADCAST_CHECK_PERIOD, BROADCAST_CHECK_PERIOD);
}
}
|
923c9c7660356414f8a9b6600176217ec0f44601 | 5,957 | java | Java | SafetyNetAndroidExample/safetynetsample/src/main/java/com/example/tarento/executer/VolleyErrorHelper.java | TarentoTechnologies/AndroidSafetyNetTrial | 6bdd9e74bad77e7fce44f31c706d90a158b01ec5 | [
"MIT"
] | 2 | 2018-01-20T01:38:52.000Z | 2018-01-22T05:37:00.000Z | SafetyNetAndroidExample/safetynetsample/src/main/java/com/example/tarento/executer/VolleyErrorHelper.java | TarentoTechnologies/AndroidSafetyNetTrial | 6bdd9e74bad77e7fce44f31c706d90a158b01ec5 | [
"MIT"
] | 1 | 2018-03-15T20:41:56.000Z | 2018-03-15T20:41:56.000Z | SafetyNetAndroidExample/safetynetsample/src/main/java/com/example/tarento/executer/VolleyErrorHelper.java | TarentoTechnologies/AndroidSafetyNetTrial | 6bdd9e74bad77e7fce44f31c706d90a158b01ec5 | [
"MIT"
] | null | null | null | 35.041176 | 140 | 0.54608 | 999,989 | package com.example.tarento.executer;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.example.tarento.ui.R;
import com.example.tarento.util.Constant;
import com.google.gson.JsonSyntaxException;
public class VolleyErrorHelper {
private static final String TAG = VolleyErrorHelper.class.getSimpleName();
private static VolleyErrorHelper volleyErrorHelper = null;
private Context mContext;
private VolleyErrorHelper(Context mContext) {
this.mContext = mContext;
}
/**
* @param mContext
* @return
*/
public static synchronized VolleyErrorHelper getInstance(Context mContext) {
if (volleyErrorHelper == null) {
volleyErrorHelper = new VolleyErrorHelper(mContext);
}
return volleyErrorHelper;
}
/**
* Returns appropriate message which is to be displayed to the user
* against the specified error object.
*
* @param error
* @return
*/
public String getMessage(Object error) {
getErrorCode(error);
String errorMessage = null;
if (error instanceof TimeoutError) {
errorMessage = mContext.getResources().getString(R.string.alert_lbl_the_server_down);
} else if (isServerProblem(error)) {
errorMessage = handleServerError(error, mContext);
} else if (isNetworkProblem(error)) {
errorMessage = mContext.getResources()
.getString(R.string.alert_lbl_no_internet_connectivity);
} else {
errorMessage = mContext.getResources().getString(R.string.alert_lbl_the_server_down);
}
showAlertDialog(errorMessage);
return errorMessage;
}
/**
* get connection error code
*
* @param error
*/
private int getErrorCode(Object error) {
VolleyError volleyError = (VolleyError) error;
NetworkResponse response = volleyError.networkResponse;
int errorCode = 0;
if (response != null) {
errorCode = response.statusCode;
if (Constant.DEBUG) {
Log.d(TAG, "Error Code: " + errorCode);
}
}
return errorCode;
}
/**
* Determines whether the error is related to network
*
* @param error
* @return
*/
private boolean isNetworkProblem(Object error) {
return (error instanceof NetworkError) || (error instanceof NoConnectionError);
}
/**
* Determines whether the error is related to server
*
* @param error
* @return
*/
private boolean isServerProblem(Object error) {
return (error instanceof ServerError) || (error instanceof AuthFailureError);
}
/**
* Handles the server error, tries to determine whether to show a stock message or to
* show a message retrieved from the server.
*
* @param error
* @param context
* @return
*/
private String handleServerError(Object error, Context context) {
int errorCode = getErrorCode(error);
VolleyError volleyError = (VolleyError) error;
NetworkResponse response = volleyError.networkResponse;
if (response != null && errorCode > 0) {
switch (errorCode) {
case 404:
case 400:
case 422:
case 401:
String errorMessage = new String(response.data);
// find a error message from json
try {
// TODO enable if required
// if (Constants.DEBUG) {
// if (!TextUtils.isEmpty(errorMessage)) {
// Log.d(TAG, "Error response: " + errorMessage);
// }
// }
// ErrorResponse errorResponse = GsonUtil.getGson().fromJson(errorMessage,
// ErrorResponse.class);
// if (errorResponse != null) {
// errorMessage = errorResponse.getErrorMessage();
// }
//
// if (errorCode == 401 && errorMessage == null) {
// errorMessage = mContext
// .getString(R.string.alert__lbl__your_session_has_expired_please_login_again_);
// }
return errorMessage;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
// invalid request
return volleyError.getMessage();
default:
return context.getResources().getString(R.string.alert_lbl_the_server_down);
}
}
return context.getResources().getString(R.string.alert_lbl_the_server_down);
}
/**
* show error message dialog
*
* @param errorMessage
*/
private void showAlertDialog(final String errorMessage) {
if (TextUtils.isEmpty(errorMessage)) {
return;
}
//show toast
Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
}
} |
923c9c911b22657d003f53f9f3f67de09ff137a0 | 1,817 | java | Java | warehouse/query-core/src/test/java/datawave/query/predicate/TLDEventDataFilterTest.java | smonaem/datawave-1 | 03898efed35a3868f0187f9eb864201612d573e9 | [
"Apache-2.0"
] | null | null | null | warehouse/query-core/src/test/java/datawave/query/predicate/TLDEventDataFilterTest.java | smonaem/datawave-1 | 03898efed35a3868f0187f9eb864201612d573e9 | [
"Apache-2.0"
] | null | null | null | warehouse/query-core/src/test/java/datawave/query/predicate/TLDEventDataFilterTest.java | smonaem/datawave-1 | 03898efed35a3868f0187f9eb864201612d573e9 | [
"Apache-2.0"
] | null | null | null | 33.036364 | 112 | 0.675839 | 999,990 | package datawave.query.predicate;
import datawave.query.Constants;
import datawave.query.util.TypeMetadata;
import org.apache.accumulo.core.data.Key;
import org.apache.commons.jexl2.parser.ASTJexlScript;
import org.easymock.EasyMock;
import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class TLDEventDataFilterTest extends EasyMockSupport {
private TLDEventDataFilter filter;
private ASTJexlScript mockScript;
private TypeMetadata mockAttributeFactory;
@Before
public void setup() {
mockScript = createMock(ASTJexlScript.class);
mockAttributeFactory = createMock(TypeMetadata.class);
}
@Test
public void getCurrentField_standardTest() {
EasyMock.expect(mockScript.jjtGetNumChildren()).andReturn(0).anyTimes();
replayAll();
// expected key structure
Key key = new Key("row", "column", "field" + Constants.NULL_BYTE_STRING + "value");
filter = new TLDEventDataFilter(mockScript, mockAttributeFactory, false, null, null, -1, -1);
String field = filter.getCurrentField(key);
assertTrue(field.equals("field"));
verifyAll();
}
@Test
public void getCurrentField_groupingTest() {
EasyMock.expect(mockScript.jjtGetNumChildren()).andReturn(0).anyTimes();
replayAll();
// expected key structure
Key key = new Key("row", "column", "field.part_1.part_2.part_3" + Constants.NULL_BYTE_STRING + "value");
filter = new TLDEventDataFilter(mockScript, mockAttributeFactory, false, null, null, -1, -1);
String field = filter.getCurrentField(key);
assertTrue(field.equals("field"));
verifyAll();
}
}
|
923c9d2e7a0417491dc2444c0dd682eb9dc0a605 | 3,404 | java | Java | src/main/java/com/github/vladimirantin/core/repo/sql/SQLQueryBuilder.java | VladimirAntin/spring-core | 90b2454c1ec3e8df3c17b76898f4dcf404c3e1af | [
"MIT"
] | null | null | null | src/main/java/com/github/vladimirantin/core/repo/sql/SQLQueryBuilder.java | VladimirAntin/spring-core | 90b2454c1ec3e8df3c17b76898f4dcf404c3e1af | [
"MIT"
] | 2 | 2020-10-19T23:02:04.000Z | 2022-02-15T21:22:13.000Z | src/main/java/com/github/vladimirantin/core/repo/sql/SQLQueryBuilder.java | VladimirAntin/spring-core | 90b2454c1ec3e8df3c17b76898f4dcf404c3e1af | [
"MIT"
] | null | null | null | 31.229358 | 93 | 0.63631 | 999,991 | package com.github.vladimirantin.core.repo.sql;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
/**
* Created by IntelliJ IDEA
* User: vladimir_antin
* Date: 23.11.2019
* Time: 22:08
*/
public final class SQLQueryBuilder extends LinkedHashMap<String, Object> {
private StringBuilder whereClause;
public SQLQueryBuilder() {
super();
whereClause = new StringBuilder();
}
private SQLQueryBuilder standardQuery(String dbValue, Object value, String query) {
String key = String.format("__%s",this.values().size() + 1);
this.whereClause.append(String.format(query, dbValue, key));
this.put(key, value);
return this;
}
public SQLQueryBuilder startingWith(String dbValue, String value){
return this.standardQuery(dbValue, value+"%", "%s like :%s");
}
public SQLQueryBuilder endingWith(String dbValue, String value){
return this.standardQuery(dbValue, "%"+value, "%s like :%s");
}
public SQLQueryBuilder contains(String dbValue, String value){
return this.standardQuery(dbValue, "%"+value+"%", "%s like :%s");
}
public SQLQueryBuilder equal(String dbValue, Object value){
return this.standardQuery(dbValue, value, "%s=:%s");
}
public SQLQueryBuilder moreThan(String dbValue, Object value){
return this.standardQuery(dbValue, value, "%s>:%s");
}
public SQLQueryBuilder lessThan(String dbValue, Object value){
return this.standardQuery(dbValue, value, "%s<:%s");
}
public SQLQueryBuilder moreOrEquals(String dbValue, Object value){
return this.standardQuery(dbValue, value, "%s>=:%s");
}
public SQLQueryBuilder lessOrEquals(String dbValue, Object value){
return this.standardQuery(dbValue, value, "%s<=:%s");
}
public SQLQueryBuilder in(String dbValue, Collection<Object> values){
return this.standardQuery(dbValue, values, "%s in :%s");
}
public SQLQueryBuilder notIn(String dbValue, Collection<Object> values){
return this.standardQuery(dbValue, values, "%s not in :%s");
}
public SQLQueryBuilder in(String dbValue, Object... values){
return this.in(dbValue, Arrays.asList(values));
}
public SQLQueryBuilder notIn(String dbValue, Object... values){
return this.notIn(dbValue, Arrays.asList(values));
}
public SQLQueryBuilder between(String dbValue, Object start, Object end){
String key = String.format("__%s",this.values().size() + 1);
String key2 = String.format("__%s",this.values().size() + 2);
this.whereClause.append(String.format("%s between :%s and :%s", dbValue, key, key2));
this.put(key, start);
this.put(key2, end);
return this;
}
public SQLQueryBuilder and() {
this.whereClause.append(" and ");
return this;
}
public SQLQueryBuilder or() {
this.whereClause.append(" or ");
return this;
}
public String getWhereQuery() {
String retVal = this.whereClause.toString().trim();
if (retVal.endsWith("or") || retVal.endsWith("and")) {
retVal = retVal.substring(0, retVal.length() - 3).trim();
}
if (retVal.isEmpty()) {
return "";
} else {
return String.format("where %s", retVal);
}
}
}
|
923c9d63e5de029e3d0c88a752667639d4ab13c9 | 200 | java | Java | Parser Algebraic Notation/src/parser/BoardPiece.java | pchaigno/chess-service | a273492fbbb076728e294a1c700f668c3e3cd93a | [
"MIT"
] | 5 | 2015-11-06T11:06:30.000Z | 2021-12-27T17:57:07.000Z | Parser Algebraic Notation/src/parser/BoardPiece.java | pchaigno/chess-service | a273492fbbb076728e294a1c700f668c3e3cd93a | [
"MIT"
] | null | null | null | Parser Algebraic Notation/src/parser/BoardPiece.java | pchaigno/chess-service | a273492fbbb076728e294a1c700f668c3e3cd93a | [
"MIT"
] | 6 | 2015-11-06T10:05:19.000Z | 2021-04-02T16:41:46.000Z | 16.666667 | 48 | 0.675 | 999,992 | package parser;
public class BoardPiece {
String name;
String color;
BoardSquare square;
public BoardPiece(String name, String color) {
this.name = name;
this.color = color;
}
} |
923c9dd7f201447784e253f06bd1ac67cfd1c62d | 362 | java | Java | Avant/src/cl/zpricing/avant/model/Publico.java | zpricing/AvantPricing | a274f511dd62d06e6abcf60192caf89a4b942f34 | [
"MIT"
] | null | null | null | Avant/src/cl/zpricing/avant/model/Publico.java | zpricing/AvantPricing | a274f511dd62d06e6abcf60192caf89a4b942f34 | [
"MIT"
] | null | null | null | Avant/src/cl/zpricing/avant/model/Publico.java | zpricing/AvantPricing | a274f511dd62d06e6abcf60192caf89a4b942f34 | [
"MIT"
] | null | null | null | 22.625 | 74 | 0.643646 | 999,993 | package cl.zpricing.avant.model;
/**
* Clase utilizada para decir el tipo de audiencia que posee una pelicula
*
* Registro de versiones:
* <ul>
* <li>1.0 09-02-2009 Oliver Cordero: version inicial.</li>
* </ul>
* <P>
* <B>Todos los derechos reservados por ZhetaPricing.</B>
* <P>
*/
public class Publico extends DescripcionId {
}
|
923c9f69223bf8f28ff4559cf4edd5765c60dd00 | 599 | java | Java | Statistical_Analysis/GUISource/portfolioFramework/PortfolioManagerFrame_Mother.java | swj0418/Java_Course_Project | 4e31436af57c406b9cf3e649f4c9ce0b0e96af00 | [
"MIT"
] | 2 | 2017-11-24T06:12:29.000Z | 2017-11-26T07:08:28.000Z | Statistical_Analysis/GUISource/portfolioFramework/PortfolioManagerFrame_Mother.java | swj0418/Java_Course_Project | 4e31436af57c406b9cf3e649f4c9ce0b0e96af00 | [
"MIT"
] | 1 | 2017-11-28T12:54:15.000Z | 2017-11-28T14:35:22.000Z | Statistical_Analysis/GUISource/portfolioFramework/PortfolioManagerFrame_Mother.java | swj0418/Java_Course_Project | 4e31436af57c406b9cf3e649f4c9ce0b0e96af00 | [
"MIT"
] | null | null | null | 18.71875 | 65 | 0.749583 | 999,994 | package portfolioFramework;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JInternalFrame;
import gray.Global;
public class PortfolioManagerFrame_Mother extends JInternalFrame{
PortfolioManagerPanel_Mother motherpanel;
public PortfolioManagerFrame_Mother() {
super("Portfolio Manager", true, true, true, true);
renderFrame();
}
public void renderFrame() {
motherpanel = new PortfolioManagerPanel_Mother();
setSize(500, 500);
setLocation(300, 300);
add(motherpanel);
validate();
repaint();
setVisible(true);
}
}
|
923c9fba806099d9588653c4d3c96a66e1df8ff5 | 174 | java | Java | src/main/java/to/ares/gamecenter/games/snowwar/room/pathfinding/SpawnPoint.java | Domexx/GameCenter | b12d94dc62d0f59ff7988180bacee6796dcd1b73 | [
"MIT"
] | 5 | 2020-09-17T11:51:18.000Z | 2022-02-21T16:56:33.000Z | src/main/java/to/ares/gamecenter/games/snowwar/room/pathfinding/SpawnPoint.java | Domexx/GameCenter | b12d94dc62d0f59ff7988180bacee6796dcd1b73 | [
"MIT"
] | null | null | null | src/main/java/to/ares/gamecenter/games/snowwar/room/pathfinding/SpawnPoint.java | Domexx/GameCenter | b12d94dc62d0f59ff7988180bacee6796dcd1b73 | [
"MIT"
] | 2 | 2021-05-11T03:22:29.000Z | 2022-02-21T16:56:34.000Z | 15.818182 | 58 | 0.683908 | 999,995 | package to.ares.gamecenter.games.snowwar.room.pathfinding;
public class SpawnPoint {
public int x;
public int y;
public SpawnPoint(int i, int j) {
x = i;
y = j;
}
}
|
923ca002e72e2b19a98b1916d96a6f453e763756 | 3,134 | java | Java | test/com/facebook/buck/util/autosparse/AbstractAutosparseFactoryTest.java | zhangshuai930822/BUCK | 296a5355e3209b409b729035f7724680d2be6f84 | [
"Apache-2.0"
] | null | null | null | test/com/facebook/buck/util/autosparse/AbstractAutosparseFactoryTest.java | zhangshuai930822/BUCK | 296a5355e3209b409b729035f7724680d2be6f84 | [
"Apache-2.0"
] | null | null | null | test/com/facebook/buck/util/autosparse/AbstractAutosparseFactoryTest.java | zhangshuai930822/BUCK | 296a5355e3209b409b729035f7724680d2be6f84 | [
"Apache-2.0"
] | null | null | null | 39.175 | 91 | 0.743778 | 999,996 | /*
* Copyright 2016-present Facebook, 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.facebook.buck.util.autosparse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
public class AbstractAutosparseFactoryTest {
@Test
public void sameSparseStateForSameHgRoot() throws InterruptedException {
Path projectPathBar = Paths.get("/project/path/foo/bar");
Path projectPathBaz = Paths.get("/project/path/foo/baz");
Path hgRoot = Paths.get("/project/path/foo");
AutoSparseConfig config = AutoSparseConfig.of(true, ImmutableList.<Path>of());
FakeHgCommandlineInterface hgFake = new FakeHgCommandlineInterface(hgRoot, "hamspam");
AutoSparseState state1 =
AbstractAutoSparseFactory.getAutoSparseState(
projectPathBar, projectPathBar.resolve("buck-out"), hgFake, config);
AutoSparseState state2 =
AbstractAutoSparseFactory.getAutoSparseState(
projectPathBaz, projectPathBaz.resolve("buck-out"), hgFake, config);
assertSame(state1, state2);
}
@Test
public void newStateForDifferentRevisionId() throws InterruptedException {
Path projectPathBar = Paths.get("/project/path/foo/bar");
Path hgRoot = Paths.get("/project/path/foo");
AutoSparseConfig config = AutoSparseConfig.of(true, ImmutableList.<Path>of());
FakeHgCommandlineInterface hgFake1 = new FakeHgCommandlineInterface(hgRoot, "hamspam");
AutoSparseState state1 =
AbstractAutoSparseFactory.getAutoSparseState(
projectPathBar, projectPathBar.resolve("buck-out"), hgFake1, config);
FakeHgCommandlineInterface hgFake2 =
new FakeHgCommandlineInterface(hgRoot, "differentrevisionid");
AutoSparseState state2 =
AbstractAutoSparseFactory.getAutoSparseState(
projectPathBar, projectPathBar.resolve("buck-out"), hgFake2, config);
assertNotSame(state1, state2);
}
@Test
public void noHgRootNoState() throws InterruptedException {
Path projectPathBar = Paths.get("/project/path/foo/bar");
Path hgRoot = null;
AutoSparseConfig config = AutoSparseConfig.of(true, ImmutableList.<Path>of());
FakeHgCommandlineInterface hgFake = new FakeHgCommandlineInterface(hgRoot, "hamspam");
AutoSparseState state =
AbstractAutoSparseFactory.getAutoSparseState(
projectPathBar, projectPathBar.resolve("buck-out"), hgFake, config);
assertNull(state);
}
}
|
923ca021af396307f94b7a08192d5f7e38671085 | 3,567 | java | Java | Mars-Game/src/main/java/com/live106/mars/game/db/model/Player.java | live106/Mars | 5ee652e2b5a1d0bf87828bf940dc0767619658e5 | [
"Apache-2.0"
] | null | null | null | Mars-Game/src/main/java/com/live106/mars/game/db/model/Player.java | live106/Mars | 5ee652e2b5a1d0bf87828bf940dc0767619658e5 | [
"Apache-2.0"
] | null | null | null | Mars-Game/src/main/java/com/live106/mars/game/db/model/Player.java | live106/Mars | 5ee652e2b5a1d0bf87828bf940dc0767619658e5 | [
"Apache-2.0"
] | null | null | null | 26.819549 | 76 | 0.623213 | 999,997 | package com.live106.mars.game.db.model;
import java.util.Date;
public class Player {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column player.id
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column player.name
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
private String name;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column player.accountId
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
private Integer accountid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column player.createday
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
private Date createday;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column player.id
*
* @return the value of player.id
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column player.id
*
* @param id the value for player.id
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column player.name
*
* @return the value of player.name
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column player.name
*
* @param name the value for player.name
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public void setName(String name) {
this.name = name;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column player.accountId
*
* @return the value of player.accountId
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public Integer getAccountid() {
return accountid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column player.accountId
*
* @param accountid the value for player.accountId
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public void setAccountid(Integer accountid) {
this.accountid = accountid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column player.createday
*
* @return the value of player.createday
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public Date getCreateday() {
return createday;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column player.createday
*
* @param createday the value for player.createday
*
* @mbggenerated Fri Oct 23 10:39:49 CST 2015
*/
public void setCreateday(Date createday) {
this.createday = createday;
}
} |
923ca03762a88f9135c27b084d33ea90c6722511 | 703 | java | Java | JdbcProject/src/main/java/com/bridgeit/model/Employee.java | GulabThakur/SpringProgram | f161869d891596c9e54cf3798a0a4ef95b9832af | [
"MIT"
] | null | null | null | JdbcProject/src/main/java/com/bridgeit/model/Employee.java | GulabThakur/SpringProgram | f161869d891596c9e54cf3798a0a4ef95b9832af | [
"MIT"
] | null | null | null | JdbcProject/src/main/java/com/bridgeit/model/Employee.java | GulabThakur/SpringProgram | f161869d891596c9e54cf3798a0a4ef95b9832af | [
"MIT"
] | null | null | null | 19 | 52 | 0.584637 | 999,998 | package com.bridgeit.model;
public class Employee {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
|
923ca0434147643d89f792503d70a4c53de17399 | 11,690 | java | Java | streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamImplJoin.java | lukaszmac/kafka | d8756e81c57040130ec163e63798663d62298589 | [
"Apache-2.0"
] | 6 | 2021-06-11T15:06:15.000Z | 2022-03-26T13:03:26.000Z | streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamImplJoin.java | lukaszmac/kafka | d8756e81c57040130ec163e63798663d62298589 | [
"Apache-2.0"
] | 15 | 2020-03-05T00:32:48.000Z | 2022-02-16T00:55:24.000Z | streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamImplJoin.java | lukaszmac/kafka | d8756e81c57040130ec163e63798663d62298589 | [
"Apache-2.0"
] | 5 | 2021-06-11T15:16:25.000Z | 2022-02-24T08:37:31.000Z | 54.882629 | 178 | 0.691189 | 999,999 | /*
* 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.streams.kstream.internals;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.kstream.JoinWindows;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.StreamJoined;
import org.apache.kafka.streams.kstream.ValueJoiner;
import org.apache.kafka.streams.kstream.internals.graph.ProcessorGraphNode;
import org.apache.kafka.streams.kstream.internals.graph.ProcessorParameters;
import org.apache.kafka.streams.kstream.internals.graph.StreamStreamJoinNode;
import org.apache.kafka.streams.kstream.internals.graph.StreamsGraphNode;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.WindowBytesStoreSupplier;
import org.apache.kafka.streams.state.WindowStore;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class KStreamImplJoin {
private final InternalStreamsBuilder builder;
private final boolean leftOuter;
private final boolean rightOuter;
KStreamImplJoin(final InternalStreamsBuilder builder,
final boolean leftOuter,
final boolean rightOuter) {
this.builder = builder;
this.leftOuter = leftOuter;
this.rightOuter = rightOuter;
}
public <K1, R, V1, V2> KStream<K1, R> join(final KStream<K1, V1> lhs,
final KStream<K1, V2> other,
final ValueJoiner<? super V1, ? super V2, ? extends R> joiner,
final JoinWindows windows,
final StreamJoined<K1, V1, V2> streamJoined) {
final StreamJoinedInternal<K1, V1, V2> streamJoinedInternal = new StreamJoinedInternal<>(streamJoined);
final NamedInternal renamed = new NamedInternal(streamJoinedInternal.name());
final String joinThisSuffix = rightOuter ? "-outer-this-join" : "-this-join";
final String joinOtherSuffix = leftOuter ? "-outer-other-join" : "-other-join";
final String thisWindowStreamProcessorName = renamed.suffixWithOrElseGet(
"-this-windowed", builder, KStreamImpl.WINDOWED_NAME);
final String otherWindowStreamProcessorName = renamed.suffixWithOrElseGet(
"-other-windowed", builder, KStreamImpl.WINDOWED_NAME);
final String joinThisGeneratedName = rightOuter ? builder.newProcessorName(KStreamImpl.OUTERTHIS_NAME) : builder.newProcessorName(KStreamImpl.JOINTHIS_NAME);
final String joinOtherGeneratedName = leftOuter ? builder.newProcessorName(KStreamImpl.OUTEROTHER_NAME) : builder.newProcessorName(KStreamImpl.JOINOTHER_NAME);
final String joinThisName = renamed.suffixWithOrElseGet(joinThisSuffix, joinThisGeneratedName);
final String joinOtherName = renamed.suffixWithOrElseGet(joinOtherSuffix, joinOtherGeneratedName);
final String joinMergeName = renamed.suffixWithOrElseGet(
"-merge", builder, KStreamImpl.MERGE_NAME);
final StreamsGraphNode thisStreamsGraphNode = ((AbstractStream<?, ?>) lhs).streamsGraphNode;
final StreamsGraphNode otherStreamsGraphNode = ((AbstractStream<?, ?>) other).streamsGraphNode;
final StoreBuilder<WindowStore<K1, V1>> thisWindowStore;
final StoreBuilder<WindowStore<K1, V2>> otherWindowStore;
final String userProvidedBaseStoreName = streamJoinedInternal.storeName();
final WindowBytesStoreSupplier thisStoreSupplier = streamJoinedInternal.thisStoreSupplier();
final WindowBytesStoreSupplier otherStoreSupplier = streamJoinedInternal.otherStoreSupplier();
assertUniqueStoreNames(thisStoreSupplier, otherStoreSupplier);
if (thisStoreSupplier == null) {
final String thisJoinStoreName = userProvidedBaseStoreName == null ? joinThisGeneratedName : userProvidedBaseStoreName + joinThisSuffix;
thisWindowStore = joinWindowStoreBuilder(thisJoinStoreName, windows, streamJoinedInternal.keySerde(), streamJoinedInternal.valueSerde());
} else {
assertWindowSettings(thisStoreSupplier, windows);
thisWindowStore = joinWindowStoreBuilderFromSupplier(thisStoreSupplier, streamJoinedInternal.keySerde(), streamJoinedInternal.valueSerde());
}
if (otherStoreSupplier == null) {
final String otherJoinStoreName = userProvidedBaseStoreName == null ? joinOtherGeneratedName : userProvidedBaseStoreName + joinOtherSuffix;
otherWindowStore = joinWindowStoreBuilder(otherJoinStoreName, windows, streamJoinedInternal.keySerde(), streamJoinedInternal.otherValueSerde());
} else {
assertWindowSettings(otherStoreSupplier, windows);
otherWindowStore = joinWindowStoreBuilderFromSupplier(otherStoreSupplier, streamJoinedInternal.keySerde(), streamJoinedInternal.otherValueSerde());
}
final KStreamJoinWindow<K1, V1> thisWindowedStream = new KStreamJoinWindow<>(thisWindowStore.name());
final ProcessorParameters<K1, V1> thisWindowStreamProcessorParams = new ProcessorParameters<>(thisWindowedStream, thisWindowStreamProcessorName);
final ProcessorGraphNode<K1, V1> thisWindowedStreamsNode = new ProcessorGraphNode<>(thisWindowStreamProcessorName, thisWindowStreamProcessorParams);
builder.addGraphNode(thisStreamsGraphNode, thisWindowedStreamsNode);
final KStreamJoinWindow<K1, V2> otherWindowedStream = new KStreamJoinWindow<>(otherWindowStore.name());
final ProcessorParameters<K1, V2> otherWindowStreamProcessorParams = new ProcessorParameters<>(otherWindowedStream, otherWindowStreamProcessorName);
final ProcessorGraphNode<K1, V2> otherWindowedStreamsNode = new ProcessorGraphNode<>(otherWindowStreamProcessorName, otherWindowStreamProcessorParams);
builder.addGraphNode(otherStreamsGraphNode, otherWindowedStreamsNode);
final KStreamKStreamJoin<K1, R, V1, V2> joinThis = new KStreamKStreamJoin<>(
otherWindowStore.name(),
windows.beforeMs,
windows.afterMs,
joiner,
leftOuter
);
final KStreamKStreamJoin<K1, R, V2, V1> joinOther = new KStreamKStreamJoin<>(
thisWindowStore.name(),
windows.afterMs,
windows.beforeMs,
AbstractStream.reverseJoiner(joiner),
rightOuter
);
final PassThrough<K1, R> joinMerge = new PassThrough<>();
final StreamStreamJoinNode.StreamStreamJoinNodeBuilder<K1, V1, V2, R> joinBuilder = StreamStreamJoinNode.streamStreamJoinNodeBuilder();
final ProcessorParameters<K1, V1> joinThisProcessorParams = new ProcessorParameters<>(joinThis, joinThisName);
final ProcessorParameters<K1, V2> joinOtherProcessorParams = new ProcessorParameters<>(joinOther, joinOtherName);
final ProcessorParameters<K1, R> joinMergeProcessorParams = new ProcessorParameters<>(joinMerge, joinMergeName);
joinBuilder.withJoinMergeProcessorParameters(joinMergeProcessorParams)
.withJoinThisProcessorParameters(joinThisProcessorParams)
.withJoinOtherProcessorParameters(joinOtherProcessorParams)
.withThisWindowStoreBuilder(thisWindowStore)
.withOtherWindowStoreBuilder(otherWindowStore)
.withThisWindowedStreamProcessorParameters(thisWindowStreamProcessorParams)
.withOtherWindowedStreamProcessorParameters(otherWindowStreamProcessorParams)
.withValueJoiner(joiner)
.withNodeName(joinMergeName);
final StreamsGraphNode joinGraphNode = joinBuilder.build();
builder.addGraphNode(Arrays.asList(thisStreamsGraphNode, otherStreamsGraphNode), joinGraphNode);
final Set<String> allSourceNodes = new HashSet<>(((KStreamImpl<K1, V1>) lhs).subTopologySourceNodes);
allSourceNodes.addAll(((KStreamImpl<K1, V2>) other).subTopologySourceNodes);
// do not have serde for joined result;
// also for key serde we do not inherit from either since we cannot tell if these two serdes are different
return new KStreamImpl<>(joinMergeName, streamJoinedInternal.keySerde(), null, allSourceNodes, false, joinGraphNode, builder);
}
private void assertWindowSettings(final WindowBytesStoreSupplier supplier, final JoinWindows joinWindows) {
if (!supplier.retainDuplicates()) {
throw new StreamsException("The StoreSupplier must set retainDuplicates=true, found retainDuplicates=false");
}
final boolean allMatch = supplier.retentionPeriod() == (joinWindows.size() + joinWindows.gracePeriodMs()) &&
supplier.windowSize() == joinWindows.size();
if (!allMatch) {
throw new StreamsException(String.format("Window settings mismatch. WindowBytesStoreSupplier settings %s must match JoinWindows settings %s", supplier, joinWindows));
}
}
private void assertUniqueStoreNames(final WindowBytesStoreSupplier supplier,
final WindowBytesStoreSupplier otherSupplier) {
if (supplier != null
&& otherSupplier != null
&& supplier.name().equals(otherSupplier.name())) {
throw new StreamsException("Both StoreSuppliers have the same name. StoreSuppliers must provide unique names");
}
}
private static <K, V> StoreBuilder<WindowStore<K, V>> joinWindowStoreBuilder(final String storeName,
final JoinWindows windows,
final Serde<K> keySerde,
final Serde<V> valueSerde) {
return Stores.windowStoreBuilder(
Stores.persistentWindowStore(
storeName + "-store",
Duration.ofMillis(windows.size() + windows.gracePeriodMs()),
Duration.ofMillis(windows.size()),
true
),
keySerde,
valueSerde
);
}
private static <K, V> StoreBuilder<WindowStore<K, V>> joinWindowStoreBuilderFromSupplier(final WindowBytesStoreSupplier storeSupplier,
final Serde<K> keySerde,
final Serde<V> valueSerde) {
return Stores.windowStoreBuilder(
storeSupplier,
keySerde,
valueSerde
);
}
}
|
923ca0b69da7a432e19ced20f31e6b99e5aeda3d | 6,488 | java | Java | openjdk11/test/jdk/java/lang/reflect/AccessibleObject/TrySetAccessibleTest.java | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | test/jdk/java/lang/reflect/AccessibleObject/TrySetAccessibleTest.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/jdk/java/lang/reflect/AccessibleObject/TrySetAccessibleTest.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 32.118812 | 81 | 0.653052 | 1,000,000 | /*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @build TrySetAccessibleTest
* @modules java.base/java.lang:open
* java.base/jdk.internal.perf
* java.base/jdk.internal.misc:+open
* @run testng/othervm --illegal-access=deny TrySetAccessibleTest
* @summary Test AccessibleObject::trySetAccessible method
*/
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jdk.internal.misc.Unsafe;
import jdk.internal.perf.Perf;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
@Test
public class TrySetAccessibleTest {
/**
* Invoke a private constructor on a public class in an exported package
*/
public void testPrivateConstructorInExportedPackage() throws Exception {
Constructor<?> ctor = Perf.class.getDeclaredConstructor();
try {
ctor.newInstance();
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertFalse(ctor.trySetAccessible());
assertFalse(ctor.canAccess(null));
}
/**
* Invoke a private constructor on a public class in an open package
*/
public void testPrivateConstructorInOpenedPackage() throws Exception {
Constructor<?> ctor = Unsafe.class.getDeclaredConstructor();
try {
ctor.newInstance();
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertTrue(ctor.trySetAccessible());
assertTrue(ctor.canAccess(null));
Unsafe unsafe = (Unsafe) ctor.newInstance();
}
/**
* Invoke a private method on a public class in an exported package
*/
public void testPrivateMethodInExportedPackage() throws Exception {
Method m = Perf.class.getDeclaredMethod("getBytes", String.class);
try {
m.invoke(null);
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertFalse(m.trySetAccessible());
assertFalse(m.canAccess(null));
}
/**
* Invoke a private method on a public class in an open package
*/
public void testPrivateMethodInOpenedPackage() throws Exception {
Method m = Unsafe.class.getDeclaredMethod("throwIllegalAccessError");
assertFalse(m.canAccess(null));
try {
m.invoke(null);
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertTrue(m.trySetAccessible());
assertTrue(m.canAccess(null));
try {
m.invoke(null);
assertTrue(false);
} catch (InvocationTargetException e) {
// thrown by throwIllegalAccessError
assertTrue(e.getCause() instanceof IllegalAccessError);
}
}
/**
* Invoke a private method on a public class in an exported package
*/
public void testPrivateFieldInExportedPackage() throws Exception {
Field f = Perf.class.getDeclaredField("instance");
try {
f.get(null);
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertFalse(f.trySetAccessible());
assertFalse(f.canAccess(null));
try {
f.get(null);
assertTrue(false);
} catch (IllegalAccessException expected) {}
}
/**
* Access a private field in a public class that is an exported package
*/
public void testPrivateFieldInOpenedPackage() throws Exception {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
try {
f.get(null);
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertTrue(f.trySetAccessible());
assertTrue(f.canAccess(null));
Unsafe unsafe = (Unsafe) f.get(null);
}
/**
* Invoke a public constructor on a public class in a non-exported package
*/
public void testPublicConstructorInNonExportedPackage() throws Exception {
Class<?> clazz = Class.forName("sun.security.x509.X500Name");
Constructor<?> ctor = clazz.getConstructor(String.class);
try {
ctor.newInstance("cn=duke");
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertFalse(ctor.trySetAccessible());
assertFalse(ctor.canAccess(null));
assertTrue(ctor.trySetAccessible() == ctor.isAccessible());
}
/**
* Access a public field in a public class that in a non-exported package
*/
public void testPublicFieldInNonExportedPackage() throws Exception {
Class<?> clazz = Class.forName("sun.security.x509.X500Name");
Field f = clazz.getField("SERIALNUMBER_OID");
try {
f.get(null);
assertTrue(false);
} catch (IllegalAccessException expected) { }
assertFalse(f.trySetAccessible());
assertFalse(f.canAccess(null));
}
/**
* Test that the Class constructor cannot be make accessible.
*/
public void testJavaLangClass() throws Exception {
// non-public constructor
Constructor<?> ctor
= Class.class.getDeclaredConstructor(ClassLoader.class, Class.class);
AccessibleObject[] ctors = { ctor };
assertFalse(ctor.trySetAccessible());
assertFalse(ctor.canAccess(null));
}
}
|
923ca0c3943d235cee73eeeec56cc20c2c423095 | 639 | java | Java | ums/src/main/java/gov/samhsa/c2s/ums/domain/IdentifierSystem.java | bhits-dev/ums | 95128fcc88ccc5783a26419512157eda0e01c67d | [
"Apache-2.0"
] | 1 | 2021-11-25T15:19:48.000Z | 2021-11-25T15:19:48.000Z | ums/src/main/java/gov/samhsa/c2s/ums/domain/IdentifierSystem.java | bhits-dev/ums | 95128fcc88ccc5783a26419512157eda0e01c67d | [
"Apache-2.0"
] | 1 | 2018-07-25T13:58:12.000Z | 2018-08-08T13:44:21.000Z | ums/src/main/java/gov/samhsa/c2s/ums/domain/IdentifierSystem.java | bhits-dev/ums | 95128fcc88ccc5783a26419512157eda0e01c67d | [
"Apache-2.0"
] | 2 | 2017-09-05T02:00:16.000Z | 2020-03-23T03:37:49.000Z | 23.666667 | 83 | 0.760563 | 1,000,001 | package gov.samhsa.c2s.ums.domain;
import lombok.Data;
import org.hibernate.envers.Audited;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Audited
@Table(indexes = @Index(columnList = "system", name = "system_idx", unique = true))
@Data
public class IdentifierSystem {
@Id
@GeneratedValue
private Long id;
private String system;
private String display;
private String oid;
@NotNull
private Boolean reassignable = Boolean.FALSE;
}
|
923ca1461681b396af5407bd63c3031574de0300 | 1,064 | java | Java | takin-webapp/tro-web/tro-web-app/src/main/java/io/shulie/tro/web/app/input/scriptmanage/ShellScriptManagePageQueryInput.java | hydgladiator/Takin | d20ca0266e2010f9bcee82c1334332ca2750869c | [
"Apache-2.0"
] | 1 | 2021-07-07T06:41:53.000Z | 2021-07-07T06:41:53.000Z | takin-webapp/tro-web/tro-web-app/src/main/java/io/shulie/tro/web/app/input/scriptmanage/ShellScriptManagePageQueryInput.java | pirateskipper/Takin | 6dc5c7c531f17d204f2744aa405d5f0d4b9fe280 | [
"Apache-2.0"
] | null | null | null | takin-webapp/tro-web/tro-web-app/src/main/java/io/shulie/tro/web/app/input/scriptmanage/ShellScriptManagePageQueryInput.java | pirateskipper/Takin | 6dc5c7c531f17d204f2744aa405d5f0d4b9fe280 | [
"Apache-2.0"
] | null | null | null | 22.617021 | 70 | 0.698024 | 1,000,002 | /*
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: hzdkv@example.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shulie.tro.web.app.input.scriptmanage;
import java.util.List;
import io.shulie.tro.common.beans.page.PagingDevice;
import lombok.Data;
/**
* @author zhaoyong
*/
@Data
public class ShellScriptManagePageQueryInput extends PagingDevice {
private static final long serialVersionUID = 4907165876058485892L;
/**
* 脚本名称
*/
private String name;
/**
* tagId列表
*/
private List<Long> tagIds;
/**
* 脚本类型
*/
private Integer scriptType;
}
|
923ca1540ffdd02e04fe9ffbbb72e5889adad115 | 1,973 | java | Java | ucloud-sdk-java-usms/src/main/java/cn/ucloud/usms/util/FileUtil.java | liuchangfitcloud/ucloud-sdk-java | ca370c2141527f713feb0c1548d8cc42a8687c2a | [
"Apache-2.0"
] | null | null | null | ucloud-sdk-java-usms/src/main/java/cn/ucloud/usms/util/FileUtil.java | liuchangfitcloud/ucloud-sdk-java | ca370c2141527f713feb0c1548d8cc42a8687c2a | [
"Apache-2.0"
] | null | null | null | ucloud-sdk-java-usms/src/main/java/cn/ucloud/usms/util/FileUtil.java | liuchangfitcloud/ucloud-sdk-java | ca370c2141527f713feb0c1548d8cc42a8687c2a | [
"Apache-2.0"
] | null | null | null | 29.447761 | 79 | 0.568677 | 1,000,003 | package cn.ucloud.usms.util;
import cn.ucloud.common.exception.ValidatorException;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author: codezhang
* @date: 2019/12/13 7:46 下午
* @describe:
**/
public class FileUtil {
private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* 文件需先进行base64编码格式转换,
* 此处填写转换后的字符串。
* 文件大小不超过4 MB
*
* @param path 文件路径
* @return
* @throws ValidatorException
*/
public static String getFileContent2StringAfterBase64Encode(String path)
throws ValidatorException {
String value = "";
FileInputStream fileInputStream = null;
try {
URL fileUrl = new URL("file://" + path);
URLConnection urlConnection = fileUrl.openConnection();
String type = urlConnection.getContentType();
fileInputStream = new FileInputStream(path);
int available = fileInputStream.available();
byte[] buffer = new byte[available];
int readLen = fileInputStream.read(buffer);
log.info("file({}) mime-type:{} , size:{} , read size:{}",
path,
type,
available,
readLen);
value = String.format("data:%s;base64,%s",
type, new String(Base64.encodeBase64(buffer)));
} catch (IOException e) {
throw new ValidatorException(e.getMessage());
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
log.error("close file({}) error:{}", path, e.getMessage());
}
}
}
return value;
}
}
|
923ca2e481a927c8f9b1607fc624131ee1d1ed7f | 6,839 | java | Java | api/src/main/java/io/druid/data/input/impl/DimensionsSpec.java | tanbamboo/druid | 8d816a6312abc23a07658565467fa930145a680b | [
"Apache-2.0"
] | 19 | 2015-02-13T02:45:47.000Z | 2019-07-31T21:37:09.000Z | api/src/main/java/io/druid/data/input/impl/DimensionsSpec.java | tanbamboo/druid | 8d816a6312abc23a07658565467fa930145a680b | [
"Apache-2.0"
] | 38 | 2015-02-24T17:12:19.000Z | 2018-09-02T01:14:20.000Z | api/src/main/java/io/druid/data/input/impl/DimensionsSpec.java | tanbamboo/druid | 8d816a6312abc23a07658565467fa930145a680b | [
"Apache-2.0"
] | 30 | 2015-01-08T16:31:19.000Z | 2020-11-27T11:02:49.000Z | 29.102128 | 99 | 0.687674 | 1,000,004 | /*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.druid.data.input.impl;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.metamx.common.parsers.ParserUtils;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DimensionsSpec
{
private final List<DimensionSchema> dimensions;
private final Set<String> dimensionExclusions;
private final Map<String, DimensionSchema> dimensionSchemaMap;
public static List<DimensionSchema> getDefaultSchemas(List<String> dimNames)
{
return Lists.transform(
dimNames,
new Function<String, DimensionSchema>()
{
@Override
public DimensionSchema apply(String input)
{
return new StringDimensionSchema(input);
}
}
);
}
public static DimensionSchema convertSpatialSchema(SpatialDimensionSchema spatialSchema)
{
return new NewSpatialDimensionSchema(spatialSchema.getDimName(), spatialSchema.getDims());
}
@JsonCreator
public DimensionsSpec(
@JsonProperty("dimensions") List<DimensionSchema> dimensions,
@JsonProperty("dimensionExclusions") List<String> dimensionExclusions,
@Deprecated @JsonProperty("spatialDimensions") List<SpatialDimensionSchema> spatialDimensions
)
{
this.dimensions = dimensions == null
? Lists.<DimensionSchema>newArrayList()
: Lists.newArrayList(dimensions);
this.dimensionExclusions = (dimensionExclusions == null)
? Sets.<String>newHashSet()
: Sets.newHashSet(dimensionExclusions);
List<SpatialDimensionSchema> spatialDims = (spatialDimensions == null)
? Lists.<SpatialDimensionSchema>newArrayList()
: spatialDimensions;
verify(spatialDims);
// Map for easy dimension name-based schema lookup
this.dimensionSchemaMap = new HashMap<>();
for (DimensionSchema schema : this.dimensions) {
dimensionSchemaMap.put(schema.getName(), schema);
}
for(SpatialDimensionSchema spatialSchema : spatialDims) {
DimensionSchema newSchema = DimensionsSpec.convertSpatialSchema(spatialSchema);
this.dimensions.add(newSchema);
dimensionSchemaMap.put(newSchema.getName(), newSchema);
}
}
@JsonProperty
public List<DimensionSchema> getDimensions()
{
return dimensions;
}
@JsonProperty
public Set<String> getDimensionExclusions()
{
return dimensionExclusions;
}
@Deprecated @JsonIgnore
public List<SpatialDimensionSchema> getSpatialDimensions()
{
Iterable<NewSpatialDimensionSchema> filteredList = Iterables.filter(
dimensions, NewSpatialDimensionSchema.class
);
Iterable<SpatialDimensionSchema> transformedList = Iterables.transform(
filteredList,
new Function<NewSpatialDimensionSchema, SpatialDimensionSchema>()
{
@Nullable
@Override
public SpatialDimensionSchema apply(NewSpatialDimensionSchema input)
{
return new SpatialDimensionSchema(input.getName(), input.getDims());
}
}
);
return Lists.newArrayList(transformedList);
}
@JsonIgnore
public List<String> getDimensionNames()
{
return Lists.transform(
dimensions,
new Function<DimensionSchema, String>()
{
@Override
public String apply(DimensionSchema input)
{
return input.getName();
}
}
);
}
public DimensionSchema getSchema(String dimension)
{
return dimensionSchemaMap.get(dimension);
}
public boolean hasCustomDimensions()
{
return !(dimensions == null || dimensions.isEmpty());
}
public DimensionsSpec withDimensions(List<DimensionSchema> dims)
{
return new DimensionsSpec(dims, ImmutableList.copyOf(dimensionExclusions), null);
}
public DimensionsSpec withDimensionExclusions(Set<String> dimExs)
{
return new DimensionsSpec(
dimensions,
ImmutableList.copyOf(Sets.union(dimensionExclusions, dimExs)),
null
);
}
@Deprecated
public DimensionsSpec withSpatialDimensions(List<SpatialDimensionSchema> spatials)
{
return new DimensionsSpec(dimensions, ImmutableList.copyOf(dimensionExclusions), spatials);
}
private void verify(List<SpatialDimensionSchema> spatialDimensions)
{
List<String> dimNames = getDimensionNames();
Preconditions.checkArgument(
Sets.intersection(this.dimensionExclusions, Sets.newHashSet(dimNames)).isEmpty(),
"dimensions and dimensions exclusions cannot overlap"
);
ParserUtils.validateFields(dimNames);
ParserUtils.validateFields(dimensionExclusions);
List<String> spatialDimNames = Lists.transform(
spatialDimensions,
new Function<SpatialDimensionSchema, String>()
{
@Override
public String apply(SpatialDimensionSchema input)
{
return input.getDimName();
}
}
);
// Don't allow duplicates between main list and deprecated spatial list
ParserUtils.validateFields(Iterables.concat(dimNames, spatialDimNames));
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DimensionsSpec that = (DimensionsSpec) o;
if (!dimensions.equals(that.dimensions)) {
return false;
}
return dimensionExclusions.equals(that.dimensionExclusions);
}
@Override
public int hashCode()
{
int result = dimensions.hashCode();
result = 31 * result + dimensionExclusions.hashCode();
return result;
}
}
|
923ca3a41a8b9ade5a5be91d14e4d308a58948ca | 6,048 | java | Java | src/main/java/de/bentzin/bot/Listener.java | TDRMinecraft/UntisBot | 5d9a2d8cd78c322947260d762c79073871f2494c | [
"MIT"
] | null | null | null | src/main/java/de/bentzin/bot/Listener.java | TDRMinecraft/UntisBot | 5d9a2d8cd78c322947260d762c79073871f2494c | [
"MIT"
] | null | null | null | src/main/java/de/bentzin/bot/Listener.java | TDRMinecraft/UntisBot | 5d9a2d8cd78c322947260d762c79073871f2494c | [
"MIT"
] | null | null | null | 36.878049 | 170 | 0.612765 | 1,000,005 | package de.bentzin.bot;
import com.google.i18n.phonenumbers.Phonenumber;
import de.bentzin.bot.permission.Role;
import it.auties.whatsapp4j.listener.WhatsappListener;
import it.auties.whatsapp4j.protobuf.chat.Chat;
import it.auties.whatsapp4j.protobuf.info.MessageInfo;
import it.auties.whatsapp4j.protobuf.message.standard.DocumentMessage;
import it.auties.whatsapp4j.response.impl.json.UserInformationResponse;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
/**
* The type Listener.
*/
public class Listener implements WhatsappListener {
/**
* The constant filePath.
*/
public static final Path filePath = Paths.get("").toAbsolutePath();
@Nullable
private UserInformationResponse informationResponse = null;
private UntisBot Bot;
/**
* Read out string.
*
* @param message the message
* @return the string
*/
public static String readOut(@NotNull MessageInfo message) {
String text;
if (message.container().textMessage() != null) {
text = message.container().textMessage().text();
} else if (message.container().documentMessage() != null) {
DocumentMessage documentMessage = message.container().documentMessage();
text = documentMessage.fileName();
try {
System.out.println("doc: " + documentMessage);
Files.write(new File(filePath + "\\" + UntisBot.getTime().replace(":", ".") + "_" + documentMessage.fileName()).toPath(), documentMessage.decodedMedia());
System.out.println("saved: " + documentMessage.fileName() + " in " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
} else if (message.container().contactMessage() != null) {
text = "contact: " + message.container().contactMessage().displayName();
} else if (message.container().call() != null) {
text = "started call";
} else if (message.container().audioMessage() != null) {
text = "send audio [" + message.container().audioMessage().seconds() + "s]";
} else if (message.container().deviceSyncMessage() != null) {
text = "DeviceSync: " + message.container().deviceSyncMessage().serializedXmlBytes();
} else text = null;
return text;
}
/**
* Gets information response.
*
* @return the information response
*/
public UserInformationResponse getInformationResponse() {
return informationResponse;
}
@SneakyThrows
@Override
public void onLoggedIn(@NotNull UserInformationResponse info) {
this.informationResponse = info;
System.out.println("Login: " + info.pushname() + "@" + info.platform());
Map<Phonenumber.PhoneNumber, Role> map = new HashMap<>();
UntisBot.getPermissionManager().setRoleMap(map);
Thread.sleep(2);
}
@SneakyThrows
@Override
public void onChats() {
System.out.println("The Bot is now ready!");
UntisBot.setChat(UntisBot.getManager().findChatByName("Nils Semrau").get());
System.out.println("The Chat \"" + UntisBot.getChat().displayName() + "\" is now ready!");
// Bot.getApi().sendMessage(Bot.getChat(), "connected - " + getInformationResponse().platform() + ": " + Bot.getTime());
//PDFTest.sendPDF(Bot.getChat(), new File("C:/Users/tureb/OneDrive/Dokumente/Keys.pdf"));
}
@Override
public void onDisconnected() {
System.out.println("The connection was closed!");
if(UntisBot.AUTORESTART)
UntisBot.getApi().connect();
System.exit(5);
}
@Override
public void onMessageDeleted(@NotNull Chat chat, @NotNull MessageInfo message, boolean everyone) {
System.out.println("Message: " + message + " was deleted in " + chat.displayName() + " for everyone? : " + everyone);
}
@SneakyThrows
@Override
public void onNewMessage(@NotNull Chat chat, @NotNull MessageInfo message) {
//while (!message.sender().isPresent()){
// Thread.sleep(20);
// }
String text = "Unknown Type!";
if (message.globalStatus().name().equals("SERVER_ACK")) {
return;
}
/*
if (message.container().textMessage() != null) {
text = message.container().textMessage().text();
} else if (message.container().documentMessage() != null) {
text = message.container().documentMessage().fileName();
}else if(message.container().call() != null) {
text = "started call";
}else if(message.container().audioMessage() != null) {
text = "send audio [" + message.container().audioMessage().seconds() +"s]";
} else {
*/
text = Listener.readOut(message);
if (text == null)
if (message.key().fromMe()) {
System.out.println("System send an unknown message to: " + chat.displayName());
} else {
System.out.println("\"" + message.sender().get().name() + "\" " + "send an unknown message to: " + chat.displayName() + " | " + message.globalStatus());
return;
}
text = text + " | " + message.globalStatus() + " @ " + message.timestamp();
UntisBot.getCommandsystem().handleInput(message);
if (message.key().fromMe()) {
System.out.println("System" + "@" + chat.displayName() + ": " + text);
} else {
System.out.println(message.sender().get().bestName().get() + "@" + chat.displayName() + ": " + text);
}
}
@Override
public void onGroupDescriptionChange(@NotNull Chat group, @NotNull String description, @NotNull String descriptionId) {
System.out.println();
}
}
|
923ca4343b10748947f5e51d305103da4e7c2aa3 | 3,788 | java | Java | src/ij/plugin/filter/ExtendedPlugInFilter.java | KalenBerry/ObjectJ | a5f3ea0d544f06ca62983383cb9a9c47abc30097 | [
"MIT"
] | 7 | 2015-10-23T14:16:49.000Z | 2021-05-02T05:15:51.000Z | src/ij/plugin/filter/ExtendedPlugInFilter.java | KalenBerry/ObjectJ | a5f3ea0d544f06ca62983383cb9a9c47abc30097 | [
"MIT"
] | 2 | 2019-09-06T08:26:01.000Z | 2020-09-10T18:26:46.000Z | src/ij/plugin/filter/ExtendedPlugInFilter.java | KalenBerry/ObjectJ | a5f3ea0d544f06ca62983383cb9a9c47abc30097 | [
"MIT"
] | 7 | 2016-07-19T15:28:20.000Z | 2022-01-05T15:41:20.000Z | 51.189189 | 81 | 0.681098 | 1,000,006 | package ij.plugin.filter;
import ij.*;
import ij.process.*;
/** ImageJ plugins that process an image may implement this interface.
* In addition to the features of PlugInFilter, it is better suited
* for filters that have a dialog asking for the options or filter
* parameters. It also offers support for preview, for a smooth
* progress bar when processing stacks and for calling back
* the PlugInFilterRunner (needed, e.g., to get the slice number
* when processing a stack in parallel threads).
*<p>
* The sequence of calls to an ExtendedPlugInFilter is the following:
*<p>
* - <code>setup(arg, imp)</code>: The filter should return its flags. <p>
* - <code>showDialog(imp, command, pfr)</code>: The filter should display
* the dialog asking for parameters (if any) and do all operations
* needed to prepare for processing the individual image(s) (E.g.,
* slices of a stack). For preview, a separate thread may call
* <code>setNPasses(nPasses)</code> and <code>run(ip)</code> while
* the dialog is displayed. The filter should return its flags. <p>
* - <code>setNPasses(nPasses)</code>: Informs the filter of the number
* of calls of <code>run(ip)</code> that will follow. <p>
* - <code>run(ip)</code>: Processing of the image(s). With the
* <code>CONVERT_TO_FLOAT</code> flag, this method will be called for
* each color channel of an RGB image. With <code>DOES_STACKS</code>,
* it will be called for each slice of a stack. <p>
* - <code>setup("final", imp)</code>: called only if flag
* <code>FINAL_PROCESSING</code> has been specified.
*<p>
* Flag <code>DONE</code> stops this sequence of calls.
*/
public interface ExtendedPlugInFilter extends PlugInFilter {
/**
* This method is called after <code>setup(arg, imp)</code> unless the
* <code>DONE</code> flag has been set.
* @param imp The active image already passed in the
* <code>setup(arg, imp)</code> call. It will be null, however, if
* the <code>NO_IMAGE_REQUIRED</code> flag has been set.
* @param command The command that has led to the invocation of
* the plugin-filter. Useful as a title for the dialog.
* @param pfr The PlugInFilterRunner calling this plugin-filter.
* It can be passed to a GenericDialog by <code>addPreviewCheckbox</code>
* to enable preview by calling the <code>run(ip)</code> method of this
* plugin-filter. <code>pfr</code> can be also used later for calling back
* the PlugInFilterRunner, e.g., to obtain the slice number
* currently processed by <code>run(ip)</code>.
* @return The method should return a combination (bitwise OR)
* of the flags specified in interfaces <code>PlugInFilter</code> and
* <code>ExtendedPlugInFilter</code>.
*/
public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr);
/**
* This method is called by ImageJ to inform the plugin-filter
* about the passes to its run method. During preview, the number of
* passes is one (or 3 for RGB images, if <code>CONVERT_TO_FLOAT</code>
* has been specified). When processing a stack, it is the number
* of slices to be processed (minus one, if one slice has been
* processed for preview before), and again, 3 times that number
* for RGB images processed with <code>CONVERT_TO_FLOAT</code>.
*/
public void setNPasses(int nPasses);
/** Set this flag if the last preview image may be kept as a result.
For stacks, this flag can lead to out-of-sequence processing of the
slices, irrespective of the <code>PARALLELIZE_STACKS<code> flag.
*/
public final int KEEP_PREVIEW = 0x1000000;
}
|
923ca5d89994ef62bb656ed16e6f5089c8ba3c3f | 2,325 | java | Java | src/main/java/tools/xor/util/excel/ExcelExporter.java | ddalton/xor | 32aaed6de435791b8f35a33f597256348390c132 | [
"Apache-2.0"
] | null | null | null | src/main/java/tools/xor/util/excel/ExcelExporter.java | ddalton/xor | 32aaed6de435791b8f35a33f597256348390c132 | [
"Apache-2.0"
] | 10 | 2020-03-04T22:01:36.000Z | 2022-02-16T01:17:50.000Z | src/main/java/tools/xor/util/excel/ExcelExporter.java | ddalton/xor | 32aaed6de435791b8f35a33f597256348390c132 | [
"Apache-2.0"
] | null | null | null | 27.352941 | 84 | 0.68043 | 1,000,008 | /**
* XOR, empowering Model Driven Architecture in J2EE applications
*
* Copyright (c) 2012, Dilip Dalton
*
* 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 tools.xor.util.excel;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import tools.xor.Settings;
import tools.xor.util.ClassUtil;
public class ExcelExporter {
private final OutputStream outputStream;
private final Settings settings;
private final SXSSFWorkbook wb = new SXSSFWorkbook();
private SXSSFSheet sheet;
private int currentRow;
private Font defaultFont;
private Font headerFont;
public ExcelExporter(OutputStream os, Settings settings) {
this.outputStream = os;
this.settings = settings;
wb.setCompressTempFiles(true);
sheet = (SXSSFSheet) wb.createSheet("XOR");
// keep 100 rows in memory, exceeding rows will be flushed to disk
sheet.setRandomAccessWindowSize(100);
}
/**
*
* @param obj should be an object[]
*/
public void writeRow(Object obj) {
Row row = sheet.createRow(currentRow++);
int cellnum = 0;
for(Object cellContent: (Object[]) obj) {
Cell cell = row.createCell(cellnum++);
if(cellContent != null) {
cell.setCellValue(cellContent.toString());
}
}
}
public void writeValidations() {
// TODO: Implement once validation support is added
}
public void finish() {
try {
wb.write(outputStream);
} catch (IOException e) {
ClassUtil.wrapRun(e);
}
}
} |
923ca625ae6fff1ed7cfb198c2911186875d9d5c | 270 | java | Java | analysis/viewshed-location/src/main/java/com/esri/samples/viewshed_location/ViewshedLocationLauncher.java | sclaridge/arcgis-runtime-samples-java | edaa61bd64bab2d268bc9b8239d866beecb41c8f | [
"Apache-2.0"
] | 90 | 2015-03-18T23:50:59.000Z | 2022-03-27T13:12:44.000Z | analysis/viewshed-location/src/main/java/com/esri/samples/viewshed_location/ViewshedLocationLauncher.java | sclaridge/arcgis-runtime-samples-java | edaa61bd64bab2d268bc9b8239d866beecb41c8f | [
"Apache-2.0"
] | 343 | 2015-08-26T16:45:02.000Z | 2022-03-28T10:59:12.000Z | analysis/viewshed-location/src/main/java/com/esri/samples/viewshed_location/ViewshedLocationLauncher.java | sclaridge/arcgis-runtime-samples-java | edaa61bd64bab2d268bc9b8239d866beecb41c8f | [
"Apache-2.0"
] | 138 | 2015-03-19T02:21:11.000Z | 2022-02-16T20:32:10.000Z | 22.5 | 79 | 0.722222 | 1,000,009 | package com.esri.samples.viewshed_location;
/**
* Wrapper required for launching a JavaFX 11 app through Gradle or from a jar.
*/
public class ViewshedLocationLauncher {
public static void main(String[] args) {
ViewshedLocationSample.main(args);
}
}
|
923ca66de6c37273aeb21340bdf23f29148b92cc | 1,111 | java | Java | frameworks/cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/utils/PSJNIHelper.java | ghw-wingsdk/demo-cocos2dx-iOS | 705a98d3f599c0e7e989bab664dd82bc84959340 | [
"MIT"
] | 34 | 2017-08-16T13:58:24.000Z | 2022-03-31T11:50:25.000Z | frameworks/cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/utils/PSJNIHelper.java | ghw-wingsdk/demo-cocos2dx-iOS | 705a98d3f599c0e7e989bab664dd82bc84959340 | [
"MIT"
] | null | null | null | frameworks/cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/utils/PSJNIHelper.java | ghw-wingsdk/demo-cocos2dx-iOS | 705a98d3f599c0e7e989bab664dd82bc84959340 | [
"MIT"
] | 17 | 2017-08-18T07:42:44.000Z | 2022-01-02T02:43:06.000Z | 19.491228 | 65 | 0.712871 | 1,000,010 | package org.cocos2dx.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
public class PSJNIHelper {
static HashMap<String, String> mHashMap = null;
static Vector<String> mVector = null;
static ArrayList<String> mArrayList = null;
public static void createHashMap(){
mHashMap = new HashMap<String, String>();
}
public static HashMap<String, String> getHashMap(){
return mHashMap;
}
public static void pushHashMapElement(String key, String value){
if(mHashMap == null)
return;
mHashMap.put(key, value);
}
public static void createVector(){
mVector = new Vector<String>();
}
public static Vector<String> getVector(){
return mVector;
}
public static void pushVectorElement(String value){
if(mVector == null)
return;
mVector.add(value);
}
public static void createArrayList(){
mArrayList = new ArrayList<String>();
}
public static ArrayList<String> getArrayList(){
return mArrayList;
}
public static void pushArrayListElement(String value){
if(mArrayList == null)
return;
mArrayList.add(value);
}
}
|
923ca6a3488b211e6a8eecb60a4f02c65f454c06 | 2,245 | java | Java | src/arshad/util/microserver/misc/SizeCalcualtor.java | ibrahim-13/java-file-server | 0be20e5580cd7048ff89d0ef0a1e32e186735395 | [
"BSD-3-Clause"
] | null | null | null | src/arshad/util/microserver/misc/SizeCalcualtor.java | ibrahim-13/java-file-server | 0be20e5580cd7048ff89d0ef0a1e32e186735395 | [
"BSD-3-Clause"
] | null | null | null | src/arshad/util/microserver/misc/SizeCalcualtor.java | ibrahim-13/java-file-server | 0be20e5580cd7048ff89d0ef0a1e32e186735395 | [
"BSD-3-Clause"
] | null | null | null | 43.269231 | 88 | 0.691111 | 1,000,011 | // Copyright (C) 2017 MD. Ibrahim Khan
//
// Project Name:
// Author: MD. Ibrahim Khan
// Author's Email: hzdkv@example.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of the contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTIONS) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
package arshad.util.microserver.misc;
/**
*
* @author Arshad
*/
public class SizeCalcualtor {
public static String getFormatedSize(long size) {
Long in = size;
long com1 = 1000;
long com2 = 1000000;
if(in.compareTo(com2) == 1) {
return String.valueOf(Long.divideUnsigned(in, com2) + " MB");
} else if(in.compareTo(com1) == 1) {
return (String.valueOf(Long.divideUnsigned(in, com1)) + " KB");
} else {
return size + " bytes";
}
}
}
|
923ca71095947ddf4b57f1a3d069414916280db9 | 1,641 | java | Java | ardulink-core-digispark/src/main/java/org/ardulink/core/digispark/DigisparkLinkConfig.java | Ardulink/Ardulink-2 | 05474f35a6585df3efdedafe242194b3e00e8601 | [
"Apache-2.0"
] | 56 | 2016-03-15T03:53:58.000Z | 2021-09-21T17:59:17.000Z | ardulink-core-digispark/src/main/java/org/ardulink/core/digispark/DigisparkLinkConfig.java | PizzaProgram/Ardulink-2 | 1bf38155278e2e6914192875db45d622e2c666dc | [
"Apache-2.0"
] | 49 | 2016-04-27T13:46:38.000Z | 2020-12-12T09:15:26.000Z | ardulink-core-digispark/src/main/java/org/ardulink/core/digispark/DigisparkLinkConfig.java | PizzaProgram/Ardulink-2 | 1bf38155278e2e6914192875db45d622e2c666dc | [
"Apache-2.0"
] | 22 | 2016-03-26T02:04:23.000Z | 2021-01-17T13:34:22.000Z | 24.132353 | 73 | 0.753809 | 1,000,012 | /**
Copyright 2013 project Ardulink http://www.ardulink.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.ardulink.core.digispark;
import static org.ardulink.util.Throwables.propagate;
import java.util.Set;
import org.ardulink.core.linkmanager.LinkConfig;
import org.ardulink.core.proto.api.Protocol;
import ch.ntb.usb.USBException;
public class DigisparkLinkConfig implements LinkConfig {
@Named("deviceName")
private String deviceName;
@Named("proto")
private Protocol proto = SimpleDigisparkProtocol.instance();
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
@ChoiceFor("deviceName")
public Set<String> listdeviceNames() {
try {
return DigisparkDiscoveryUtil.getDevices().keySet();
} catch (USBException e) {
throw propagate(e);
}
}
public Protocol getProto() {
return proto;
}
public void setProto(Protocol proto) {
this.proto = proto;
}
@ChoiceFor("proto")
public Protocol[] protos() {
// at the moment the only supported protocol is SimpleDigisparkProtocol
return new Protocol[] { proto };
}
}
|
923ca81e9c66744f9b3e18d7749c08fdab18a95f | 13,283 | java | Java | src/main/java/frc/robot/OI.java | FRC2495/FRC2495-2022 | a2c83525f34a0859f171ed57715077a0f6f4be32 | [
"BSD-3-Clause",
"MIT"
] | 1 | 2022-01-11T23:10:01.000Z | 2022-01-11T23:10:01.000Z | src/main/java/frc/robot/OI.java | FRC2495/FRC2495-2022 | a2c83525f34a0859f171ed57715077a0f6f4be32 | [
"BSD-3-Clause",
"MIT"
] | 2 | 2022-03-22T23:04:58.000Z | 2022-03-23T00:31:56.000Z | src/main/java/frc/robot/OI.java | FRC2495/FRC2495-2022 | a2c83525f34a0859f171ed57715077a0f6f4be32 | [
"BSD-3-Clause",
"MIT"
] | 1 | 2022-01-12T22:53:37.000Z | 2022-01-12T22:53:37.000Z | 40.745399 | 133 | 0.80253 | 1,000,013 | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package frc.robot;
//import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.*;
import frc.robot.commands.*;
import frc.robot.commands.drivetrain.*;
import frc.robot.commands.hinge.*;
import frc.robot.commands.grasper.*;
import frc.robot.commands.feeder.*;
import frc.robot.commands.shooter.*;
import frc.robot.commands.arms.*;
import frc.robot.commands.elbows.*;
import frc.robot.commands.conditional.*;
import frc.robot.commands.groups.*;
import frc.robot.commands.camera.*;
import frc.robot.Ports;
import frc.robot.util.DPadButton;
//import frc.robot.ControllerBase;
import frc.robot.util.GamepadAxis;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public JoystickButton joyLeftBtn1;
public JoystickButton joyLeftBtn2;
public JoystickButton joyLeftBtn3;
public JoystickButton joyLeftBtn4;
public JoystickButton joyLeftBtn5;
public JoystickButton joyLeftBtn6;
public JoystickButton joyLeftBtn7;
public JoystickButton joyLeftBtn8;
public JoystickButton joyLeftBtn9;
public JoystickButton joyLeftBtn10;
public JoystickButton joyLeftBtn11;
public Joystick joyLeft;
public JoystickButton joyRightBtn1;
public JoystickButton joyRightBtn2;
public JoystickButton joyRightBtn3;
public JoystickButton joyRightBtn4;
public JoystickButton joyRightBtn5;
public JoystickButton joyRightBtn6;
public JoystickButton joyRightBtn7;
public JoystickButton joyRightBtn8;
public JoystickButton joyRightBtn9;
public JoystickButton joyRightBtn10;
public JoystickButton joyRightBtn11;
public Joystick joyRight;
public JoystickButton gamepadA;
public JoystickButton gamepadB;
public JoystickButton gamepadX;
public JoystickButton gamepadY;
public JoystickButton gamepadLB;
public JoystickButton gamepadRB;
public JoystickButton gamepadBack;
public JoystickButton gamePadStart;
public JoystickButton gamepadLS;
public JoystickButton gamepadRS;
public GamepadAxis gamepadLXp;
public GamepadAxis gamepadLXn;
public GamepadAxis gamepadLYp;
public GamepadAxis gamepadLYn;
public GamepadAxis gamepadLT;
public GamepadAxis gamepadRT;
public GamepadAxis gamepadRXp;
public GamepadAxis gamepadRXn;
public GamepadAxis gamepadRYp;
public GamepadAxis gamepadRYn;
public Joystick gamepad;
public DPadButton dpadUp;
public DPadButton dpadDown;
public DPadButton dpadLeft;
public DPadButton dpadRight;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public OI() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
gamepad = new Joystick(Ports.USB.GAMEPAD);
gamepadRYp = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.RY);
//gamepadRYp.whenPressed(new RearArmsExtend());
gamepadRYp.whenPressed(new RearArmsRetractWithStallDetection());
gamepadRYn = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.RY,false);
//gamepadRYn.whenPressed(new RearArmsRetract());
gamepadRYn.whenPressed(new RearArmsExtendWithStallDetection());
gamepadRXp = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.RX);
//gamepadRXp.whenPressed(new RearElbowsOpen());
gamepadRXp.whenPressed(new RearElbowsMidwayWithStallDetection());
gamepadRXn = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.RX,false);
gamepadRXn.whenPressed(new RearElbowsCloseWithStallDetection());
gamepadRT = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.RT);
//gamepadRT.whenPressed(new CameraSetLedMode(ICamera.LedMode.FORCE_ON));
gamepadRT.whenPressed(new HingeMoveDown());
gamepadLT = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.LT);
//gamepadLT.whenPressed(new CameraSetLedMode(ICamera.LedMode.FORCE_OFF));
//gamepadLT.whenPressed(new FrontArmsRetract());
gamepadLT.whileHeld(new FeederFeed());
gamepadLYp = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.LY);
//gamepadLYp.whenPressed(new FrontArmsExtend());
gamepadLYp.whenPressed(new FrontArmsRetractWithStallDetection());
//gamepadLYp.whenPressed(new SpinnerColorMatch()); // pulling back towards operator
gamepadLYn = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.LY,false);
//gamepadLYn.whenPressed(new FrontArmsRetract());
gamepadLYn.whenPressed(new FrontArmsExtendWithStallDetection());
//gamepadLYn.whenPressed(new SpinnerSpinThrice()); // pushing forward
gamepadLXp = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.LX);
gamepadLXp.whenPressed(new FrontElbowsCloseWithStallDetection());
gamepadLXn = new GamepadAxis(gamepad, ControllerBase.GamepadAxes.LX,false);
//gamepadLXn.whenPressed(new FrontElbowsOpen());
gamepadLXn.whenPressed(new FrontElbowsMidwayWithStallDetection());
gamepadRS = new JoystickButton(gamepad, ControllerBase.GamepadButtons.RS);
gamepadLS = new JoystickButton(gamepad, ControllerBase.GamepadButtons.LS);
gamePadStart = new JoystickButton(gamepad, ControllerBase.GamepadButtons.START);
//gamePadStart.whenPressed(new HingeAndGrasperAndSpinnerStop());
//gamePadStart.whenPressed(new HingeAndGrasperStop());
//gamePadStart.whenPressed(new HingeAndGrasperAndFeederAndShooterStop());
gamePadStart.whenPressed(new AlmostEverythingStop());
gamepadBack = new JoystickButton(gamepad, ControllerBase.GamepadButtons.BACK);
gamepadBack.whileHeld(new FullCalibrateAndReset());
gamepadRB = new JoystickButton(gamepad, ControllerBase.GamepadButtons.RB);
//gamepadRB.whenPressed(new HingeMoveMidway());
gamepadRB.whenPressed(new HingeMoveUp());
gamepadLB = new JoystickButton(gamepad, ControllerBase.GamepadButtons.LB);
//gamepadLB.whileHeld(new SpinnerSpin());
//gamepadLB.whenPressed(new SpinnerRaiserUp());
gamepadLB.whenPressed(new IfNuclearOptionEnabled(new Climb(), new DoNothing()));
gamepadY = new JoystickButton(gamepad, ControllerBase.GamepadButtons.Y);
//gamepadY.whenPressed(new CameraSetLedMode(ICamera.LedMode.FORCE_ON));
//gamepadY.whileHeld(new WinchWinchStopperMagicWinchUp());
gamepadY.whileHeld(new ShooterShootHigh());
gamepadX = new JoystickButton(gamepad, ControllerBase.GamepadButtons.X);
//gamepadX.whileHeld(new WinchWinchStopperMagicWinchDown());
//gamepadX.whileHeld(new FeederFeed());
gamepadX.whileHeld(new ShooterShootLow());
gamepadB = new JoystickButton(gamepad, ControllerBase.GamepadButtons.B);
gamepadB.whileHeld(new GrasperRelease());
gamepadA = new JoystickButton(gamepad, ControllerBase.GamepadButtons.A);
gamepadA.whileHeld(new GrasperGrasp());
joyRight = new Joystick(Ports.USB.RIGHT);
joyRightBtn11 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN11);
joyRightBtn11.whileHeld(new RearArmsJoystickControl());
joyRightBtn10 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN10);
joyRightBtn10.whileHeld(new FrontArmsJoystickControl());
joyRightBtn9 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN9);
//joyRightBtn9.whenPressed(new WinchStopperSetStop());
//joyRightBtn9.whenPressed(new WinchLockWinchStopperSetLockedAndStop());
joyRightBtn9.whileHeld(new RearElbowsJoystickControl());
joyRightBtn8 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN8);
//joyRightBtn8.whenPressed(new WinchStopperSetFree());
//joyRightBtn8.whenPressed(new WinchLockWinchStopperSetUnlockedAndFree());
joyRightBtn8.whileHeld(new FrontElbowsJoystickControl());
joyRightBtn7 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN7);
joyRightBtn7.whenPressed(new DrivetrainStop());
joyRightBtn6 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN6);
joyRightBtn6.whenPressed(new DrivetrainResetEncoders());
joyRightBtn5 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN5);
//joyRightBtn5.whenPressed(new DrivetrainMoveUsingCameraPidController(LimelightCamera.OFFSET_CAMERA_TARGET_INCHES));
//final int MAGIC_DISTANCE_INCHES = 40;
//joyRightBtn5.whenPressed(new DrivetrainDriveUsingCamera(Robot.camera.getOffsetBetweenCameraAndTarget() + MAGIC_DISTANCE_INCHES));
//joyRightBtn5.whileHeld(new ShooterShootCustom(3200.0*1.2));
//joyRightBtn5.whileHeld(new ShooterShootUsingCamera());
joyRightBtn4 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN4);
joyRightBtn4.whenPressed(new DrivetrainTurnUsingCameraPidController());
//joyRightBtn4.whenPressed(new DrivetrainTurnAngleFromCameraUsingPidController());
joyRightBtn3 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN3);
joyRightBtn2 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN2);
joyRightBtn2.whenPressed(new SwitchedCameraSetUsbCamera(Ports.UsbCamera.SHOOTER_CAMERA));
joyRightBtn1 = new JoystickButton(joyRight, ControllerBase.JoystickButtons.BTN1);
//joyRightBtn1.whenPressed(new GearboxSetGearHigh());
joyLeft = new Joystick(Ports.USB.LEFT);
joyLeftBtn11 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN11);
//joyLeftBtn11.whileHeld(new WinchJoystickControl());
//joyLeftBtn11.whileHeld(new WinchWinchStopperJoystickControl());
joyLeftBtn11.whileHeld(new ShooterJoystickControl());
joyLeftBtn10 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN10);
//joyLeftBtn10.whileHeld(new GrasperJoystickControl());
joyLeftBtn10.whileHeld(new FeederJoystickControl());
joyLeftBtn9 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN9);
joyLeftBtn9.whileHeld(new HingeJoystickControl());
joyLeftBtn8 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN8);
joyLeftBtn8.whileHeld(new GrasperJoystickControl());
joyLeftBtn7 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN7);
joyLeftBtn7.whenPressed(new DrivetrainStop());
joyLeftBtn6 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN6);
joyLeftBtn6.whenPressed(new DrivetrainAndGyroReset());
joyLeftBtn5 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN5);
joyLeftBtn5.whenPressed(new DrivetrainTurnAngleUsingPidController(90));
joyLeftBtn4 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN4);
joyLeftBtn4.whenPressed(new DrivetrainTurnAngleUsingPidController(-90));
joyLeftBtn3 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN3);
joyLeftBtn3.whenPressed(new DrivetrainMoveDistance(50));
joyLeftBtn2 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN2);
joyLeftBtn2.whenPressed(new SwitchedCameraSetUsbCamera(Ports.UsbCamera.GRASPER_CAMERA));
joyLeftBtn1 = new JoystickButton(joyLeft, ControllerBase.JoystickButtons.BTN1);
//joyLeftBtn1.whenPressed(new GearboxSetGearLow());
dpadUp = new DPadButton(gamepad,DPadButton.Direction.UP);
dpadUp.whileHeld(new ShooterShootUsingCamera());
dpadDown = new DPadButton(gamepad,DPadButton.Direction.DOWN);
dpadDown.whileHeld(new ShooterShootPreset());
dpadLeft = new DPadButton(gamepad,DPadButton.Direction.LEFT);
dpadLeft.whenPressed(new ShooterDecreasePresetRpm());
dpadRight = new DPadButton(gamepad,DPadButton.Direction.RIGHT);
dpadRight.whenPressed(new ShooterIncreasePresetRpm());
// SmartDashboard Buttons
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
public Joystick getLeftJoystick() {
return joyLeft;
}
public Joystick getRightJoystick() {
return joyRight;
}
public Joystick getGamepad() {
return gamepad;
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
}
|
923ca81f6f8e481bae123052c9d619909700ebdd | 3,715 | java | Java | aws-java-sdk-dax/src/main/java/com/amazonaws/services/dax/model/CreateClusterResult.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 1 | 2019-02-08T21:30:20.000Z | 2019-02-08T21:30:20.000Z | aws-java-sdk-dax/src/main/java/com/amazonaws/services/dax/model/CreateClusterResult.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 16 | 2018-05-15T05:35:42.000Z | 2018-05-15T07:54:48.000Z | aws-java-sdk-dax/src/main/java/com/amazonaws/services/dax/model/CreateClusterResult.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 3 | 2018-07-13T14:46:29.000Z | 2021-02-15T13:12:55.000Z | 29.484127 | 146 | 0.618573 | 1,000,014 | /*
* Copyright 2013-2018 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.dax.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dax-2017-04-19/CreateCluster" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A description of the DAX cluster that you have created.
* </p>
*/
private Cluster cluster;
/**
* <p>
* A description of the DAX cluster that you have created.
* </p>
*
* @param cluster
* A description of the DAX cluster that you have created.
*/
public void setCluster(Cluster cluster) {
this.cluster = cluster;
}
/**
* <p>
* A description of the DAX cluster that you have created.
* </p>
*
* @return A description of the DAX cluster that you have created.
*/
public Cluster getCluster() {
return this.cluster;
}
/**
* <p>
* A description of the DAX cluster that you have created.
* </p>
*
* @param cluster
* A description of the DAX cluster that you have created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateClusterResult withCluster(Cluster cluster) {
setCluster(cluster);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCluster() != null)
sb.append("Cluster: ").append(getCluster());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateClusterResult == false)
return false;
CreateClusterResult other = (CreateClusterResult) obj;
if (other.getCluster() == null ^ this.getCluster() == null)
return false;
if (other.getCluster() != null && other.getCluster().equals(this.getCluster()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCluster() == null) ? 0 : getCluster().hashCode());
return hashCode;
}
@Override
public CreateClusterResult clone() {
try {
return (CreateClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
923ca891b890897af6157f2d71cf60407b0e51e7 | 2,860 | java | Java | modules/sbe-validation/src/main/java/org/springmodules/validation/bean/conf/loader/xml/handler/SizeRuleElementHandler.java | hiya492/spring | 95b49d64b5f6cab4ee911a92772e5ae446a380af | [
"Apache-2.0"
] | 213 | 2015-01-11T16:07:13.000Z | 2022-03-29T13:19:50.000Z | modules/sbe-validation/src/main/java/org/springmodules/validation/bean/conf/loader/xml/handler/SizeRuleElementHandler.java | hiya492/spring | 95b49d64b5f6cab4ee911a92772e5ae446a380af | [
"Apache-2.0"
] | 8 | 2017-04-24T23:36:43.000Z | 2022-02-10T15:41:23.000Z | modules/sbe-validation/src/main/java/org/springmodules/validation/bean/conf/loader/xml/handler/SizeRuleElementHandler.java | hiya492/spring | 95b49d64b5f6cab4ee911a92772e5ae446a380af | [
"Apache-2.0"
] | 250 | 2015-01-05T12:54:49.000Z | 2021-09-24T11:00:33.000Z | 37.142857 | 114 | 0.730769 | 1,000,015 | /*
* Copyright 2004-2009 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.springmodules.validation.bean.conf.loader.xml.handler;
import org.springframework.util.StringUtils;
import org.springmodules.validation.bean.conf.ValidationConfigurationException;
import org.springmodules.validation.bean.rule.AbstractValidationRule;
import org.springmodules.validation.bean.rule.MaxSizeValidationRule;
import org.springmodules.validation.bean.rule.MinSizeValidationRule;
import org.springmodules.validation.bean.rule.SizeValidationRule;
import org.w3c.dom.Element;
/**
* An {@link AbstractPropertyValidationElementHandler} that parses a size validation rules. This handler creates a
* {@link org.springmodules.validation.util.condition.collection.SizeRangeCollectionCondition},
* {@link org.springmodules.validation.util.condition.collection.MinSizeCollectionCondition}, or
* {@link org.springmodules.validation.util.condition.collection.MaxSizeCollectionCondition} from the <size>
* element.
*
* @author Uri Boness
*/
public class SizeRuleElementHandler extends AbstractPropertyValidationElementHandler {
private static final String ELEMENT_NAME = "size";
private static final String MIN_ATTR = "min";
private static final String MAX_ATTR = "max";
/**
* Constructs a new SizeRuleElementHandler.
*/
public SizeRuleElementHandler(String namespaceUri) {
super(ELEMENT_NAME, namespaceUri);
}
protected AbstractValidationRule createValidationRule(Element element) {
String minText = element.getAttribute(MIN_ATTR);
String maxText = element.getAttribute(MAX_ATTR);
Integer min = (StringUtils.hasText(minText)) ? new Integer(minText) : null;
Integer max = (StringUtils.hasText(maxText)) ? new Integer(maxText) : null;
if (min != null && max != null) {
return new SizeValidationRule(min.intValue(), max.intValue());
}
if (min != null) {
return new MinSizeValidationRule(min.intValue());
}
if (max != null) {
return new MaxSizeValidationRule(max.intValue());
}
throw new ValidationConfigurationException("Element '" + ELEMENT_NAME +
"' must have either 'min' attribute, 'max' attribute, or both");
}
}
|
923ca98bae6773d2011c7ebe850c32d8885846d5 | 416 | java | Java | src/main/java/net/minestom/server/event/entity/EntityDeathEvent.java | Hallzmine/minestom-server | dc722fb0e64b336ec308fd53c93ae2a5a1aa87ec | [
"Apache-2.0"
] | 1 | 2022-03-04T13:59:57.000Z | 2022-03-04T13:59:57.000Z | src/main/java/net/minestom/server/event/entity/EntityDeathEvent.java | Hallzmine/minestom-server | dc722fb0e64b336ec308fd53c93ae2a5a1aa87ec | [
"Apache-2.0"
] | null | null | null | src/main/java/net/minestom/server/event/entity/EntityDeathEvent.java | Hallzmine/minestom-server | dc722fb0e64b336ec308fd53c93ae2a5a1aa87ec | [
"Apache-2.0"
] | null | null | null | 18.909091 | 45 | 0.663462 | 1,000,016 | package net.minestom.server.event.entity;
import net.minestom.server.entity.Entity;
import net.minestom.server.event.Event;
public class EntityDeathEvent extends Event {
private Entity entity;
// TODO cause
public EntityDeathEvent(Entity entity) {
this.entity = entity;
}
/**
* @return the entity that died
*/
public Entity getEntity() {
return entity;
}
}
|
923caa396a23f9899fc6bbfd76a7f02896223a1e | 759 | java | Java | sql/core/target/java/org/apache/spark/sql/execution/datasources/noop/NoopWriteBuilder$.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sql/core/target/java/org/apache/spark/sql/execution/datasources/noop/NoopWriteBuilder$.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sql/core/target/java/org/apache/spark/sql/execution/datasources/noop/NoopWriteBuilder$.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | 63.25 | 149 | 0.769433 | 1,000,017 | package org.apache.spark.sql.execution.datasources.noop;
public class NoopWriteBuilder$ implements org.apache.spark.sql.connector.write.WriteBuilder, org.apache.spark.sql.connector.write.SupportsTruncate {
/**
* Static reference to the singleton instance of this Scala object.
*/
public static final NoopWriteBuilder$ MODULE$ = null;
public NoopWriteBuilder$ () { throw new RuntimeException(); }
public org.apache.spark.sql.connector.write.WriteBuilder truncate () { throw new RuntimeException(); }
public org.apache.spark.sql.connector.write.BatchWrite buildForBatch () { throw new RuntimeException(); }
public org.apache.spark.sql.connector.write.streaming.StreamingWrite buildForStreaming () { throw new RuntimeException(); }
}
|
923caac778c248ae9f27c6ddf3f1a1ed5b640a86 | 17,417 | java | Java | net/ccat/tazs/battle/handlers/archer/BaseArcherHandler.java | carbonacat/tazs-javitto | c8c92424cbcb03c3e7c2fb590384bd79b2acdaff | [
"Apache-2.0"
] | 3 | 2019-11-05T13:09:23.000Z | 2019-12-26T01:38:07.000Z | net/ccat/tazs/battle/handlers/archer/BaseArcherHandler.java | carbonacat/tazs-javitto | c8c92424cbcb03c3e7c2fb590384bd79b2acdaff | [
"Apache-2.0"
] | null | null | null | net/ccat/tazs/battle/handlers/archer/BaseArcherHandler.java | carbonacat/tazs-javitto | c8c92424cbcb03c3e7c2fb590384bd79b2acdaff | [
"Apache-2.0"
] | null | null | null | 41.469048 | 159 | 0.626227 | 1,000,018 | //
// Copyright (C) 2019 Carbonacat
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package net.ccat.tazs.battle.handlers.archer;
import femto.Sprite;
import net.ccat.tazs.battle.handlers.slapper.BaseSlapperHandler;
import net.ccat.tazs.resources.Colors;
import net.ccat.tazs.resources.sprites.NonAnimatedSprite;
import net.ccat.tazs.resources.texts.UNIT_ARCHER;
import net.ccat.tazs.resources.VideoConstants;
import net.ccat.tazs.tools.MathTools;
import net.ccat.tazs.ui.AdvancedHiRes16Color;
import net.ccat.tazs.ui.UITools;
/**
* Base Handler for all Handlers related to the Archer.
*/
public class BaseArcherHandler
implements UnitHandler
{
public static final short HEALTH_INITIAL = 50;
public static final float WALK_SPEED = 0.200f;
public static final float ANGLE_ROTATION_BY_TICK = 24.f / 256.f;
public static final float HAND_DISTANCE = 2.f;
public static final float ATTACK_RANGE_MIN = 0.f;
public static final float ATTACK_RANGE_MAX = 100.f;
public static final int ATTACK_TIMER_START = 1;
public static final int ATTACK_TIMER_PREPARED = ATTACK_TIMER_START + 8;
public static final int ATTACK_TIMER_CHARGING_MIN = ATTACK_TIMER_PREPARED; // If released here, the arrow will travel ATTACK_RANGE_MIN pixels.
public static final int ATTACK_TIMER_CHARGING_MAX = ATTACK_TIMER_CHARGING_MIN + 64; // If released here, the arrow will travel ATTACK_RANGE_MAX pixels.
public static final int ATTACK_TIMER_DECHARGING_MAX = ATTACK_TIMER_CHARGING_MAX; // If released here, the arrow will travel ATTACK_RANGE_MAX pixels.
public static final int ATTACK_TIMER_DECHARGING_MIN = ATTACK_TIMER_DECHARGING_MAX + 64; // If released here, the arrow will travel ATTACK_RANGE_MIN pixels.
public static final int ATTACK_TIMER_FIRING_START = ATTACK_TIMER_DECHARGING_MIN + 1;
public static final int ATTACK_TIMER_FIRING_END = ATTACK_TIMER_FIRING_START + 32;
public static final int ATTACK_TIMER_RECOVERED_HALF = ATTACK_TIMER_FIRING_END + 32;
public static final int ATTACK_TIMER_RECOVERED = ATTACK_TIMER_RECOVERED_HALF + 32;
public static final float ATTACK_ANGLE_MAX = Math.PI * 0.125f;
public static final float ATTACK_RADIUS = 3.f;
public static final float ATTACK_POWER = 20.f;
public static final float CLOSE_DISTANCE = HAND_DISTANCE + ATTACK_RANGE_MAX + HandlersTools.UNIT_RADIUS - 2;
public static final float CLOSE_DISTANCE_SQUARED = CLOSE_DISTANCE * CLOSE_DISTANCE;
public static final int COST = 20;
public static final float INVERSE_WEIGHT = 2.5;
public static final int RECONSIDER_TICKS = 128;
public static final int UI_TIMER_WRAPPER = ATTACK_TIMER_RECOVERED;
/***** INFORMATION *****/
public int unitType()
{
return UnitTypes.ARCHER;
}
public pointer name()
{
return UNIT_ARCHER.bin();
}
public int startingHealth()
{
return HEALTH_INITIAL;
}
public int cost()
{
return COST;
}
public boolean isControlled()
{
return false;
}
public float inverseWeight()
{
return INVERSE_WEIGHT;
}
public boolean isReadyToAttack(UnitsSystem system, int unitIdentifier)
{
return false;
}
/***** EVENTS *****/
public boolean onPlayerControl(UnitsSystem system, int unitIdentifier, boolean control)
{
if (control)
{
system.unitsHandlers[unitIdentifier] = ArcherControlledHandler.instance;
return true;
}
return false;
}
public void onHit(UnitsSystem system, int unitIdentifier,
float powerX, float powerY, float power)
{
if (HandlersTools.hitAndCheckIfBecameDead(system, unitIdentifier, powerX, powerY, power))
system.unitsHandlers[unitIdentifier] = ArcherDeathHandler.instance;
}
/***** RENDERING *****/
public void drawAsUI(UnitsSystem system,
float unitX, float unitY, float unitAngle, int unitTeam,
int unitTimer,
AdvancedHiRes16Color screen)
{
unitTimer = unitTimer % UI_TIMER_WRAPPER;
// Skips the decharging phase.
if (unitTimer >= ATTACK_TIMER_DECHARGING_MAX)
unitTimer += ATTACK_TIMER_FIRING_START - ATTACK_TIMER_DECHARGING_MAX;
drawStandingArcher(unitX, unitY, unitAngle,
system.everythingSprite, BaseSlapperHandler.baseFrameForTeam(unitTeam),
VideoConstants.EVERYTHING_BOW_FRAME + bowFrameForAttackTimer(unitTimer),
bowYOriginForAttackTimer(unitTimer),
screen);
}
public void drawControlUI(UnitsSystem system, int unitIdentifier, AdvancedHiRes16Color screen)
{
HandlersTools.drawControlCircle(system, unitIdentifier, screen);
}
/***** RENDERING TOOLS *****/
/**
* Renders an Idle Archer.
*
* @param system
* @param unitIdentifier
* @param screen
*/
public static void drawIdleArcherUnit(UnitsSystem system, int unitIdentifier, AdvancedHiRes16Color screen)
{
float unitX = system.unitsXs[unitIdentifier];
float unitY = system.unitsYs[unitIdentifier];
float unitAngle = system.unitsAngles[unitIdentifier];
byte unitTeam = system.unitsTeams[unitIdentifier];
drawStandingArcher(unitX, unitY, unitAngle,
system.everythingSprite, BaseSlapperHandler.baseFrameForTeam(unitTeam),
VideoConstants.EVERYTHING_BOW_FRAME + VideoConstants.BOW_IDLE_FRAME,
VideoConstants.SLAPPERBODY_WEAPON_OFFSET_Y,
screen);
}
/**
* Renders a Dying Archer.
*
* @param system
* @param unitIdentifier
* @param screen
*/
public static void drawDyingArcherUnit(UnitsSystem system, int unitIdentifier, AdvancedHiRes16Color screen)
{
float unitX = system.unitsXs[unitIdentifier];
float unitY = system.unitsYs[unitIdentifier];
float unitAngle = system.unitsAngles[unitIdentifier];
byte unitTeam = system.unitsTeams[unitIdentifier];
int unitTimer = system.unitsTimers[unitIdentifier];
// Is the hand above?
if (unitAngle < 0)
drawBow(unitX, unitY - bowYOriginForDeathTimer(unitTimer), unitAngle,
system.everythingSprite, VideoConstants.EVERYTHING_BOW_FRAME + bowFrameForDeathTimer(unitTimer),
screen);
BaseSlapperHandler.drawDyingSlapperBody(unitX, unitY, unitAngle,
unitTimer,
system.everythingSprite, BaseSlapperHandler.baseFrameForTeam(unitTeam),
screen);
// Is the hand below?
if (unitAngle >= 0)
drawBow(unitX, unitY - bowYOriginForDeathTimer(unitTimer), unitAngle,
system.everythingSprite, VideoConstants.EVERYTHING_BOW_FRAME + bowFrameForDeathTimer(unitTimer),
screen);
}
public static void drawAttackingArcherUnit(UnitsSystem system, int unitIdentifier, AdvancedHiRes16Color screen)
{
float unitX = system.unitsXs[unitIdentifier];
float unitY = system.unitsYs[unitIdentifier];
float unitAngle = system.unitsAngles[unitIdentifier];
byte unitTeam = system.unitsTeams[unitIdentifier];
int unitTimer = system.unitsTimers[unitIdentifier];
drawStandingArcher(unitX, unitY, unitAngle,
system.everythingSprite, BaseSlapperHandler.baseFrameForTeam(unitTeam),
VideoConstants.EVERYTHING_BOW_FRAME + bowFrameForAttackTimer(unitTimer),
bowYOriginForAttackTimer(unitTimer),
screen);
}
/**
* Renders a Archer with its weapon at a given distance.
*
* @param unitX
* @param unitY
* @param unitAngle
* @param everythingSprite
* @param baseFrame
* @param bowFrame
* @param bowYOrigin
* @param screen
*/
public static void drawStandingArcher(float unitX, float unitY, float unitAngle,
NonAnimatedSprite everythingSprite, int baseFrame,
int bowFrame, float bowYOrigin,
AdvancedHiRes16Color screen)
{
// Is the hand above?
if (unitAngle < 0)
drawBow(unitX, unitY - bowYOrigin, unitAngle,
everythingSprite, bowFrame,
screen);
BaseSlapperHandler.drawStandingSlapperBody(unitX, unitY, unitAngle,
everythingSprite, baseFrame,
screen);
// Is the hand below?
if (unitAngle >= 0)
drawBow(unitX, unitY - bowYOrigin, unitAngle,
everythingSprite, bowFrame,
screen);
}
/**
* Renders the Archer's Weapon.
* @param unitX
* @param unitY
* @param unitAngle
* @param everythingSprite
* @param bowFrame
* @param screen
*/
public static void drawBow(float unitX, float unitY, float unitAngle,
NonAnimatedSprite everythingSprite, int bowFrame,
AdvancedHiRes16Color screen)
{
boolean mirrored = unitAngle < -MathTools.PI_1_2 || unitAngle > MathTools.PI_1_2;
everythingSprite.setPosition(handX(unitX, unitAngle, HAND_DISTANCE) - VideoConstants.EVERYTHING_ORIGIN_X,
handY(unitY, unitAngle, HAND_DISTANCE) - VideoConstants.EVERYTHING_ORIGIN_Y);
everythingSprite.selectFrame(bowFrame);
everythingSprite.setMirrored(mirrored);
everythingSprite.draw(screen);
}
/***** ATTACKING *****/
/**
* Starts the Attack.
*
* @param system
* @param unitIdentifier
*/
public static void startAttack(UnitsSystem system, int unitIdentifier)
{
system.unitsTimers[unitIdentifier] = ATTACK_TIMER_START;
}
/**
* Handles a started attack.
*
* @param system
* @param unitIdentifier
* @param keepCharging When charging only - If false, immediately release.
* @return False if the attack ended.
*/
public static boolean handleAttack(UnitsSystem system, int unitIdentifier, boolean keepCharging)
{
int unitTimer = system.unitsTimers[unitIdentifier];
if ((unitTimer >= ATTACK_TIMER_CHARGING_MIN) && (unitTimer <= ATTACK_TIMER_DECHARGING_MIN))
{
if (keepCharging)
{
unitTimer++;
if (unitTimer >= ATTACK_TIMER_DECHARGING_MIN)
unitTimer = ATTACK_TIMER_CHARGING_MIN;
}
else
{
float targetDistance = targetDistanceWhenCharging(unitTimer);
float unitX = system.unitsXs[unitIdentifier];
float unitY = system.unitsYs[unitIdentifier];
float unitAngle = system.unitsAngles[unitIdentifier];
byte unitTeam = system.unitsTeams[unitIdentifier];
float targetX = unitX + Math.cos(unitAngle) * targetDistance;
float targetY = unitY + Math.sin(unitAngle) * targetDistance;
int hitUnitIdentifier = system.findClosestLivingUnit(targetX, targetY, Teams.oppositeTeam(unitTeam),
ATTACK_RADIUS + HandlersTools.UNIT_RADIUS);
// TODO: Throw an actual arrow instead of instant hit.
if (hitUnitIdentifier != UnitsSystem.IDENTIFIER_NONE)
system.unitsHandlers[hitUnitIdentifier].onHit(system, hitUnitIdentifier,
ATTACK_POWER * Math.cos(unitAngle), ATTACK_POWER * Math.sin(unitAngle),
ATTACK_POWER);
unitTimer = ATTACK_TIMER_FIRING_START;
}
}
else
unitTimer++;
if (unitTimer == ATTACK_TIMER_RECOVERED)
unitTimer = 0;
system.unitsTimers[unitIdentifier] = unitTimer;
return unitTimer != 0;
}
/**
* @param unitTimer
* @return The distance from the Unit of the target, when the Archer is charging.
*/
public static float targetDistanceWhenCharging(int unitTimer)
{
if ((unitTimer >= ATTACK_TIMER_CHARGING_MIN) && (unitTimer <= ATTACK_TIMER_CHARGING_MAX))
return MathTools.lerp(unitTimer, ATTACK_TIMER_CHARGING_MIN, ATTACK_RANGE_MIN, ATTACK_TIMER_CHARGING_MAX, ATTACK_RANGE_MAX);
if ((unitTimer >= ATTACK_TIMER_DECHARGING_MAX) && (unitTimer <= ATTACK_TIMER_DECHARGING_MIN))
return MathTools.lerp(unitTimer, ATTACK_TIMER_DECHARGING_MIN, ATTACK_RANGE_MIN, ATTACK_TIMER_DECHARGING_MAX, ATTACK_RANGE_MAX);
return ATTACK_RANGE_MIN;
}
/***** TOOLS *****/
public static float handX(float unitX, float unitAngle, float handDistance)
{
return unitX + handDistance * Math.cos(unitAngle);
}
public static float handY(float unitY, float unitAngle, float handDistance)
{
return unitY + handDistance * Math.sin(unitAngle);
}
public static int bowFrameForAttackTimer(int unitTimer)
{
if (unitTimer <= ATTACK_TIMER_PREPARED)
return MathTools.lerpi(unitTimer,
ATTACK_TIMER_START, VideoConstants.BOW_IDLE_FRAME,
ATTACK_TIMER_PREPARED, VideoConstants.BOW_LOAD_FRAMES_START);
if (unitTimer <= ATTACK_TIMER_CHARGING_MAX)
return MathTools.lerpi(unitTimer,
ATTACK_TIMER_CHARGING_MIN, VideoConstants.BOW_LOAD_FRAMES_START,
ATTACK_TIMER_CHARGING_MAX, VideoConstants.BOW_LOAD_FRAMES_LAST);
if (unitTimer <= ATTACK_TIMER_DECHARGING_MIN)
return MathTools.lerpi(unitTimer,
ATTACK_TIMER_DECHARGING_MIN, VideoConstants.BOW_LOAD_FRAMES_START,
ATTACK_TIMER_DECHARGING_MAX, VideoConstants.BOW_LOAD_FRAMES_LAST);
if (unitTimer <= ATTACK_TIMER_FIRING_END)
return MathTools.lerpi(unitTimer,
ATTACK_TIMER_FIRING_START, VideoConstants.BOW_FIRE_FRAMES_START,
ATTACK_TIMER_FIRING_END, VideoConstants.BOW_FIRE_FRAMES_LAST);
if (unitTimer <= ATTACK_TIMER_RECOVERED_HALF)
return MathTools.lerpi(unitTimer,
ATTACK_TIMER_FIRING_END, VideoConstants.BOW_FIRE_FRAMES_LAST,
ATTACK_TIMER_RECOVERED_HALF, VideoConstants.BOW_IDLE_FRAME);
return VideoConstants.BOW_IDLE_FRAME;
}
public static float bowYOriginForAttackTimer(int unitTimer)
{
if (unitTimer <= ATTACK_TIMER_PREPARED)
return MathTools.lerp(unitTimer,
ATTACK_TIMER_START, VideoConstants.SLAPPERBODY_WEAPON_OFFSET_Y,
ATTACK_TIMER_PREPARED, VideoConstants.SLAPPERBODY_AIM_OFFSET_Y);
if (unitTimer <= ATTACK_TIMER_FIRING_END)
return VideoConstants.SLAPPERBODY_AIM_OFFSET_Y;
if (unitTimer <= ATTACK_TIMER_RECOVERED_HALF)
return MathTools.lerp(unitTimer,
ATTACK_TIMER_FIRING_END, VideoConstants.SLAPPERBODY_AIM_OFFSET_Y,
ATTACK_TIMER_RECOVERED_HALF, VideoConstants.SLAPPERBODY_WEAPON_OFFSET_Y);
return VideoConstants.SLAPPERBODY_WEAPON_OFFSET_Y;
}
public static int bowFrameForDeathTimer(int unitTimer)
{
if (unitTimer >= BaseSlapperHandler.DEATH_TICKS / 2)
return VideoConstants.BOW_IDLE_FRAME;
if (unitTimer > 0)
return VideoConstants.BOW_FIRE_FRAMES_LAST;
return VideoConstants.BOW_FADED_FRAME;
}
public static float bowYOriginForDeathTimer(int unitTimer)
{
if ((unitTimer >= 0) && (unitTimer <= BaseSlapperHandler.DEATH_TICKS))
return MathTools.lerp(unitTimer,
0, 0,
BaseSlapperHandler.DEATH_TICKS, VideoConstants.SLAPPERBODY_WEAPON_OFFSET_Y);
return 0;
}
} |
923cac56aca5f84a3ee04714d7f2f3f9c11ca22d | 6,955 | java | Java | core/kernel/kernelSolution/source_gen/jetbrains/mps/smodel/ConceptDeclarationScanner.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | core/kernel/kernelSolution/source_gen/jetbrains/mps/smodel/ConceptDeclarationScanner.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | core/kernel/kernelSolution/source_gen/jetbrains/mps/smodel/ConceptDeclarationScanner.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | 53.5 | 229 | 0.763911 | 1,000,019 | package jetbrains.mps.smodel;
/*Generated by MPS */
import jetbrains.mps.annotations.GeneratedClass;
import java.util.Set;
import org.jetbrains.mps.openapi.model.SNode;
import java.util.HashSet;
import org.jetbrains.mps.openapi.model.SModel;
import org.jetbrains.mps.openapi.module.SModule;
import java.util.List;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SModelOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor;
import org.jetbrains.mps.openapi.model.SModelReference;
import java.util.function.Predicate;
import java.util.Collections;
import org.jetbrains.mps.openapi.language.SReferenceLink;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import org.jetbrains.mps.openapi.language.SConcept;
/**
* Scanner of a model with {@code ConceptDeclarations}to find cross-model dependencies.
* Much like {@link jetbrains.mps.smodel.ModelDependencyScanner } albeit narrow tailored for structure models and extends relation between Language modules.
*/
@GeneratedClass(node = "r:5ff047e0-2953-4750-806a-bdc16824aa89(jetbrains.mps.smodel)/7408719695775110713", model = "r:5ff047e0-2953-4750-806a-bdc16824aa89(jetbrains.mps.smodel)")
public class ConceptDeclarationScanner {
private final Set<SNode> myExternalConcepts = new HashSet<SNode>();
private final Set<SNode> myExternalIfaces = new HashSet<SNode>();
private final Set<SModel> myExtendedModels = new HashSet<SModel>();
private final Set<SModule> myExtendedModules = new HashSet<SModule>();
private boolean myExcludeLangCore = false;
public ConceptDeclarationScanner() {
}
/**
* As long as languages implicitly extend j.m.lang.core, any ConceptDeclaration implies import of
* j.m.lang.core.structure.BaseConcept.
* By default, this scanner gives all cross-model dependencies, including one of {@code BaseConcept}.
* However, generally, there's little use for explicit lang.core import and we can safely omit it.
*
* @return {@code this} for convenience
*/
public ConceptDeclarationScanner omitLangCore() {
myExcludeLangCore = true;
return this;
}
public ConceptDeclarationScanner scan(SModel m) {
List<SNode> roots = SModelOperations.roots(m, null);
for (SNode cd : SNodeOperations.ofConcept(roots, CONCEPTS.ConceptDeclaration$gH)) {
SNode ex = SLinkOperations.getTarget(cd, LINKS.extends$_Isg);
// ex could be null if no explicit BaseConcept in super
if (ex != null && SNodeOperations.getModel(ex) != m) {
myExternalConcepts.add(ex);
}
for (SNode icd : SLinkOperations.collect(SLinkOperations.getChildren(cd, LINKS.implements$u_P2), LINKS.intfc$zM4e)) {
if (SNodeOperations.getModel(icd) != m && (new IAttributeDescriptor.NodeAttribute(CONCEPTS.MarkerInterfaceAttribute$8S).get(icd) == null)) {
// we respect 'marker iface' attribute for the directly implemented interfaces, and don't care if its
// superinterface may be denoted as marker.
myExternalIfaces.add(icd);
}
}
}
for (SNode icd : SNodeOperations.ofConcept(roots, CONCEPTS.InterfaceConceptDeclaration$CG)) {
for (SNode iface : SLinkOperations.collect(SLinkOperations.getChildren(icd, LINKS.extends$nawU), LINKS.intfc$zM4e)) {
if (SNodeOperations.getModel(iface) != m && (new IAttributeDescriptor.NodeAttribute(CONCEPTS.MarkerInterfaceAttribute$8S).get(iface) == null)) {
// XXX again, marker interface directly extended does not constitute 'extends' for languages
myExternalIfaces.add(iface);
}
}
}
for (SNode cd : myExternalConcepts) {
myExtendedModels.add(SNodeOperations.getModel(cd));
}
// XXX for the time being, consider implements of a CD as 'extends' relation between the languages, although this needs extra consideration
// perhaps, shall not treat CD.implements (but still ICD.extends) as mandatory for 'extends' between languages, as it's common to see marker interfaces
// (like IMainClass) that bring (sometimes huge) dependency hierarchy for no added value.
for (SNode cd : myExternalIfaces) {
myExtendedModels.add(SNodeOperations.getModel(cd));
}
if (myExcludeLangCore) {
// here comes an odd way to deal with missing model-reference expression
final SModelReference langCoreStructureModelRef = new SNodePointer("r:00000000-0000-4000-0000-011c89590288(jetbrains.mps.lang.core.structure)", "1133920641626").getModelReference();
myExtendedModels.removeIf(new Predicate<SModel>() {
public boolean test(SModel m) {
return langCoreStructureModelRef.equals(SModelOperations.getPointer(m));
}
});
}
for (SModel em : myExtendedModels) {
myExtendedModules.add(em.getModule());
}
return this;
}
public Set<SModel> getDependencyModels() {
return Collections.unmodifiableSet(myExtendedModels);
}
public Set<SModule> getDependencyModules() {
return Collections.unmodifiableSet(myExtendedModules);
}
public Set<SNode> getExternalConcepts() {
return Collections.unmodifiableSet(myExternalConcepts);
}
public Set<SNode> getExternalInterfaces() {
return Collections.unmodifiableSet(myExternalIfaces);
}
private static final class LINKS {
/*package*/ static final SReferenceLink extends$_Isg = MetaAdapterFactory.getReferenceLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979ba0450L, 0xf979be93cfL, "extends");
/*package*/ static final SContainmentLink implements$u_P2 = MetaAdapterFactory.getContainmentLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979ba0450L, 0x110358d693eL, "implements");
/*package*/ static final SReferenceLink intfc$zM4e = MetaAdapterFactory.getReferenceLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x110356fc618L, 0x110356fe029L, "intfc");
/*package*/ static final SContainmentLink extends$nawU = MetaAdapterFactory.getContainmentLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103556dcafL, 0x110356e9df4L, "extends");
}
private static final class CONCEPTS {
/*package*/ static final SConcept MarkerInterfaceAttribute$8S = MetaAdapterFactory.getConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x4d7dcbe8bf135fd0L, "jetbrains.mps.lang.structure.structure.MarkerInterfaceAttribute");
/*package*/ static final SConcept ConceptDeclaration$gH = MetaAdapterFactory.getConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979ba0450L, "jetbrains.mps.lang.structure.structure.ConceptDeclaration");
/*package*/ static final SConcept InterfaceConceptDeclaration$CG = MetaAdapterFactory.getConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103556dcafL, "jetbrains.mps.lang.structure.structure.InterfaceConceptDeclaration");
}
}
|
923cad3aaf4263be0d0733f9b1f6ff0b8ae44171 | 5,022 | java | Java | src/main/java/net/tlalka/java/hackerrank/datastructures/LinkList.java | jtlalka/hackerrank | 054ec993767a0cc6c2f432efbabb529030558a20 | [
"MIT"
] | 1 | 2016-11-15T16:19:43.000Z | 2016-11-15T16:19:43.000Z | src/main/java/net/tlalka/java/hackerrank/datastructures/LinkList.java | jtlalka/hackerrank | 054ec993767a0cc6c2f432efbabb529030558a20 | [
"MIT"
] | null | null | null | src/main/java/net/tlalka/java/hackerrank/datastructures/LinkList.java | jtlalka/hackerrank | 054ec993767a0cc6c2f432efbabb529030558a20 | [
"MIT"
] | null | null | null | 23.142857 | 70 | 0.487256 | 1,000,020 | package net.tlalka.java.hackerrank.datastructures;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkList<V> implements Iterable<V> {
private Node head;
private Node tail;
private int size;
private class Node {
private V value;
private Node previous;
private Node next;
public Node(V value) {
this(value, null, null);
}
public Node(V value, Node previous, Node next) {
this.value = value;
this.previous = previous;
this.next = next;
}
public Node addPrevious(V value) {
return previous = new Node(value, previous, this);
}
public Node addNext(V value) {
return next = new Node(value, this, next);
}
public Node remove() {
if (previous != null) {
previous.next = next;
}
if (next != null) {
next.previous = previous;
}
return this;
}
public Node revers() {
Node node = previous;
previous = next;
next = node;
return (next == null) ? this : next.revers();
}
}
private class ListIterator implements Iterator<V> {
private Node node;
private V value;
public ListIterator(Node node) {
this.node = node;
}
@Override
public boolean hasNext() {
return node != null;
}
@Override
public V next() {
value = node.value;
node = node.next;
return value;
}
}
public LinkList() {
this.size = 0;
}
public LinkList(V value) {
this.addLast(value);
}
public LinkList(Collection<V> values) {
values.forEach(this::addLast);
}
public V getFirst() {
return getValueFromNode(head);
}
public V getLast() {
return getValueFromNode(tail);
}
private V getValueFromNode(Node node) {
return node != null ? node.value : null;
}
public void addFirst(V value) {
if (head == null) {
head = tail = new Node(value);
} else {
head = head.addPrevious(value);
}
incrementSize();
}
public void addFirst(LinkList<V> list) {
list.forEach(this::addFirst);
}
public void addLast(V value) {
if (tail == null) {
tail = head = new Node(value);
} else {
tail = tail.addNext(value);
}
incrementSize();
}
public void addLast(LinkList<V> list) {
list.forEach(this::addLast);
}
public V removeFirst() {
if (head == null) {
throw new NoSuchElementException("List is empty.");
} else {
Node node = head.remove();
decrementSize();
head = node.next;
return node.value;
}
}
public V removeLast() {
if (tail == null) {
throw new NoSuchElementException("List is empty.");
} else {
Node node = tail.remove();
decrementSize();
tail = node.previous;
return node.value;
}
}
public V remove(int index) {
Node node = head;
for (int i = 0; node != null; i++, node = node.next) {
if (i == index) {
Node removed = node.remove();
head = removed.equals(head) ? removed.next : head;
tail = removed.equals(tail) ? removed.previous : tail;
decrementSize();
return removed.value;
}
}
throw new NoSuchElementException("There is no such value.");
}
public boolean contains(V value) {
for (V item : this) {
if (item == null) {
return value == null;
} else if (item.equals(value)) {
return true;
}
}
return false;
}
public int indexOf(V value) {
Node node = head;
for (int i = 0; node != null; i++, node = node.next) {
if (node.value == null) {
if (value == null) {
return i;
}
} else if (node.value.equals(value)) {
return i;
}
}
throw new NoSuchElementException("There is no such value.");
}
public void revers() {
if (head == null) {
return;
}
head = tail;
tail = head.revers();
}
private int incrementSize() {
return size++;
}
private int decrementSize() {
return size--;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
@Override
public Iterator<V> iterator() {
return new ListIterator(head);
}
}
|
923cadef4cdf65be7b327ee209ffc7c1ec9c553e | 67 | java | Java | glmall-common/src/main/java/com/xj/glmall/common/valid/AddGroup.java | 139yu/glmall | cf12bf17b2f0f1b23407c5239b2250d9d57ef53c | [
"Apache-2.0"
] | null | null | null | glmall-common/src/main/java/com/xj/glmall/common/valid/AddGroup.java | 139yu/glmall | cf12bf17b2f0f1b23407c5239b2250d9d57ef53c | [
"Apache-2.0"
] | 4 | 2021-03-01T13:37:43.000Z | 2021-09-20T21:01:39.000Z | glmall-common/src/main/java/com/xj/glmall/common/valid/AddGroup.java | 139yu/glmall | cf12bf17b2f0f1b23407c5239b2250d9d57ef53c | [
"Apache-2.0"
] | null | null | null | 13.4 | 35 | 0.776119 | 1,000,021 | package com.xj.glmall.common.valid;
public interface AddGroup {
}
|
923cae2d48b696591ca35e245e423a62bfc25722 | 1,248 | java | Java | src源代码/Collection/Generic/Demo06Generic.java | hs-vae/Learn-java-load | d457755fa57ca725f0e2a69bf8bc2b8edfa81d06 | [
"Apache-2.0"
] | 118 | 2020-11-06T14:18:45.000Z | 2022-03-24T03:26:32.000Z | src源代码/Collection/Generic/Demo06Generic.java | hs-vae/Learn-java-load | d457755fa57ca725f0e2a69bf8bc2b8edfa81d06 | [
"Apache-2.0"
] | null | null | null | src源代码/Collection/Generic/Demo06Generic.java | hs-vae/Learn-java-load | d457755fa57ca725f0e2a69bf8bc2b8edfa81d06 | [
"Apache-2.0"
] | 7 | 2020-12-29T03:31:13.000Z | 2021-12-07T04:48:47.000Z | 29.023256 | 70 | 0.661058 | 1,000,022 | package com.hs_vae.Collection.Generic;
import java.util.ArrayList;
import java.util.Collection;
/*
泛型的上限限定: ? extends E 代表使用的泛型只能是E类型的子类或本身
泛型的下限限定: ? super E 代表使用的泛型只能是E类型的父类或本身
*/
public class Demo06Generic {
public static void main(String[] args) {
Collection<Integer> list1=new ArrayList<>();
Collection<String> list2=new ArrayList<>();
Collection<Number> list3=new ArrayList<>();
Collection<Object> list4=new ArrayList<>();
//泛型的上限举例
getElement1(list1);
// getElement1(list2); //报错,因为String类型不是Number类型的子类
getElement1(list3);
// getElement1(list4); //报错,因为Object类型是Number类型的父类而不是子类
//泛型的下限举例
// getElement2(list1); //报错,因为Integer是Number的子类而不是父类
// getElement2(list2); //报错,因为String类型不是Number的父类
getElement2(list3);
getElement2(list4);
}
/*
类与类之间的继承关系
Integer extends Number extends Object
com.hs_vae.String extends Object
*/
//泛型的上限: 此时的泛型?,必须是Number类型或者是Number类型的子类
public static void getElement1(Collection<? extends Number> list){
}
//泛型的下限: 此时的泛型?,必须是Number类型或者是Number类型的父类
public static void getElement2(Collection<? super Number> list){
}
}
|
923cae5511a9d1d8a9861a0b447f0dbe8623bb39 | 30,006 | java | Java | src/StockIT-v1-release_source_from_JADX/sources/com/google/android/exoplayer2/text/webvtt/WebvttCueParser.java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | [
"Apache-2.0"
] | 1 | 2021-11-23T10:12:35.000Z | 2021-11-23T10:12:35.000Z | src/StockIT-v2-release_source_from_JADX/sources/com/google/android/exoplayer2/text/webvtt/WebvttCueParser.java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | [
"Apache-2.0"
] | null | null | null | src/StockIT-v2-release_source_from_JADX/sources/com/google/android/exoplayer2/text/webvtt/WebvttCueParser.java | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | [
"Apache-2.0"
] | 1 | 2021-10-01T13:14:19.000Z | 2021-10-01T13:14:19.000Z | 39.019506 | 343 | 0.540025 | 1,000,023 | package com.google.android.exoplayer2.text.webvtt;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.AlignmentSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import com.facebook.react.uimanager.ViewProps;
import com.google.android.exoplayer2.text.webvtt.WebvttCue;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.message.ParameterizedMessage;
public final class WebvttCueParser {
private static final char CHAR_AMPERSAND = '&';
private static final char CHAR_GREATER_THAN = '>';
private static final char CHAR_LESS_THAN = '<';
private static final char CHAR_SEMI_COLON = ';';
private static final char CHAR_SLASH = '/';
private static final char CHAR_SPACE = ' ';
public static final Pattern CUE_HEADER_PATTERN = Pattern.compile("^(\\S+)\\s+-->\\s+(\\S+)(.*)?$");
private static final Pattern CUE_SETTING_PATTERN = Pattern.compile("(\\S+?):(\\S+)");
private static final String ENTITY_AMPERSAND = "amp";
private static final String ENTITY_GREATER_THAN = "gt";
private static final String ENTITY_LESS_THAN = "lt";
private static final String ENTITY_NON_BREAK_SPACE = "nbsp";
private static final int STYLE_BOLD = 1;
private static final int STYLE_ITALIC = 2;
private static final String TAG = "WebvttCueParser";
private static final String TAG_BOLD = "b";
private static final String TAG_CLASS = "c";
private static final String TAG_ITALIC = "i";
private static final String TAG_LANG = "lang";
private static final String TAG_UNDERLINE = "u";
private static final String TAG_VOICE = "v";
private final StringBuilder textBuilder = new StringBuilder();
public boolean parseCue(ParsableByteArray parsableByteArray, WebvttCue.Builder builder, List<WebvttCssStyle> list) {
String readLine = parsableByteArray.readLine();
if (readLine == null) {
return false;
}
Matcher matcher = CUE_HEADER_PATTERN.matcher(readLine);
if (matcher.matches()) {
return parseCue((String) null, matcher, parsableByteArray, builder, this.textBuilder, list);
}
String readLine2 = parsableByteArray.readLine();
if (readLine2 == null) {
return false;
}
Matcher matcher2 = CUE_HEADER_PATTERN.matcher(readLine2);
if (!matcher2.matches()) {
return false;
}
return parseCue(readLine.trim(), matcher2, parsableByteArray, builder, this.textBuilder, list);
}
static void parseCueSettingsList(String str, WebvttCue.Builder builder) {
Matcher matcher = CUE_SETTING_PATTERN.matcher(str);
while (matcher.find()) {
String group = matcher.group(1);
String group2 = matcher.group(2);
try {
if ("line".equals(group)) {
parseLineAttribute(group2, builder);
} else if ("align".equals(group)) {
builder.setTextAlignment(parseTextAlignment(group2));
} else if (ViewProps.POSITION.equals(group)) {
parsePositionAttribute(group2, builder);
} else if ("size".equals(group)) {
builder.setWidth(WebvttParserUtil.parsePercentage(group2));
} else {
Log.m173w(TAG, "Unknown cue setting " + group + ParameterizedMessage.ERROR_MSG_SEPARATOR + group2);
}
} catch (NumberFormatException unused) {
Log.m173w(TAG, "Skipping bad cue setting: " + matcher.group());
}
}
}
static void parseCueText(String str, String str2, WebvttCue.Builder builder, List<WebvttCssStyle> list) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
ArrayDeque arrayDeque = new ArrayDeque();
ArrayList arrayList = new ArrayList();
int i = 0;
while (i < str2.length()) {
char charAt = str2.charAt(i);
if (charAt == '&') {
i++;
int indexOf = str2.indexOf(59, i);
int indexOf2 = str2.indexOf(32, i);
if (indexOf == -1) {
indexOf = indexOf2;
} else if (indexOf2 != -1) {
indexOf = Math.min(indexOf, indexOf2);
}
if (indexOf != -1) {
applyEntity(str2.substring(i, indexOf), spannableStringBuilder);
if (indexOf == indexOf2) {
spannableStringBuilder.append(StringUtils.SPACE);
}
i = indexOf + 1;
} else {
spannableStringBuilder.append(charAt);
}
} else if (charAt != '<') {
spannableStringBuilder.append(charAt);
i++;
} else {
int i2 = i + 1;
if (i2 < str2.length()) {
int i3 = 1;
boolean z = str2.charAt(i2) == '/';
i2 = findEndOfTag(str2, i2);
int i4 = i2 - 2;
boolean z2 = str2.charAt(i4) == '/';
if (z) {
i3 = 2;
}
int i5 = i + i3;
if (!z2) {
i4 = i2 - 1;
}
String substring = str2.substring(i5, i4);
String tagName = getTagName(substring);
if (tagName != null && isSupportedTag(tagName)) {
if (z) {
while (!arrayDeque.isEmpty()) {
StartTag startTag = (StartTag) arrayDeque.pop();
applySpansForTag(str, startTag, spannableStringBuilder, list, arrayList);
if (startTag.name.equals(tagName)) {
break;
}
}
} else if (!z2) {
arrayDeque.push(StartTag.buildStartTag(substring, spannableStringBuilder.length()));
}
}
}
i = i2;
}
}
while (!arrayDeque.isEmpty()) {
applySpansForTag(str, (StartTag) arrayDeque.pop(), spannableStringBuilder, list, arrayList);
}
applySpansForTag(str, StartTag.buildWholeCueVirtualTag(), spannableStringBuilder, list, arrayList);
builder.setText(spannableStringBuilder);
}
private static boolean parseCue(String str, Matcher matcher, ParsableByteArray parsableByteArray, WebvttCue.Builder builder, StringBuilder sb, List<WebvttCssStyle> list) {
try {
builder.setStartTime(WebvttParserUtil.parseTimestampUs(matcher.group(1))).setEndTime(WebvttParserUtil.parseTimestampUs(matcher.group(2)));
parseCueSettingsList(matcher.group(3), builder);
sb.setLength(0);
while (true) {
String readLine = parsableByteArray.readLine();
if (!TextUtils.isEmpty(readLine)) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(readLine.trim());
} else {
parseCueText(str, sb.toString(), builder, list);
return true;
}
}
} catch (NumberFormatException unused) {
Log.m173w(TAG, "Skipping cue with bad header: " + matcher.group());
return false;
}
}
private static void parseLineAttribute(String str, WebvttCue.Builder builder) throws NumberFormatException {
int indexOf = str.indexOf(44);
if (indexOf != -1) {
builder.setLineAnchor(parsePositionAnchor(str.substring(indexOf + 1)));
str = str.substring(0, indexOf);
} else {
builder.setLineAnchor(Integer.MIN_VALUE);
}
if (str.endsWith("%")) {
builder.setLine(WebvttParserUtil.parsePercentage(str)).setLineType(0);
return;
}
int parseInt = Integer.parseInt(str);
if (parseInt < 0) {
parseInt--;
}
builder.setLine((float) parseInt).setLineType(1);
}
private static void parsePositionAttribute(String str, WebvttCue.Builder builder) throws NumberFormatException {
int indexOf = str.indexOf(44);
if (indexOf != -1) {
builder.setPositionAnchor(parsePositionAnchor(str.substring(indexOf + 1)));
str = str.substring(0, indexOf);
} else {
builder.setPositionAnchor(Integer.MIN_VALUE);
}
builder.setPosition(WebvttParserUtil.parsePercentage(str));
}
/* JADX WARNING: Can't fix incorrect switch cases order */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static int parsePositionAnchor(java.lang.String r5) {
/*
int r0 = r5.hashCode()
r1 = 0
r2 = 3
r3 = 2
r4 = 1
switch(r0) {
case -1364013995: goto L_0x002a;
case -1074341483: goto L_0x0020;
case 100571: goto L_0x0016;
case 109757538: goto L_0x000c;
default: goto L_0x000b;
}
L_0x000b:
goto L_0x0034
L_0x000c:
java.lang.String r0 = "start"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0034
r0 = 0
goto L_0x0035
L_0x0016:
java.lang.String r0 = "end"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0034
r0 = 3
goto L_0x0035
L_0x0020:
java.lang.String r0 = "middle"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0034
r0 = 2
goto L_0x0035
L_0x002a:
java.lang.String r0 = "center"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0034
r0 = 1
goto L_0x0035
L_0x0034:
r0 = -1
L_0x0035:
if (r0 == 0) goto L_0x0058
if (r0 == r4) goto L_0x0057
if (r0 == r3) goto L_0x0057
if (r0 == r2) goto L_0x0056
java.lang.StringBuilder r0 = new java.lang.StringBuilder
r0.<init>()
java.lang.String r1 = "Invalid anchor value: "
r0.append(r1)
r0.append(r5)
java.lang.String r5 = r0.toString()
java.lang.String r0 = "WebvttCueParser"
com.google.android.exoplayer2.util.Log.m173w(r0, r5)
r5 = -2147483648(0xffffffff80000000, float:-0.0)
return r5
L_0x0056:
return r3
L_0x0057:
return r4
L_0x0058:
return r1
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.text.webvtt.WebvttCueParser.parsePositionAnchor(java.lang.String):int");
}
/* JADX WARNING: Can't fix incorrect switch cases order */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static android.text.Layout.Alignment parseTextAlignment(java.lang.String r6) {
/*
int r0 = r6.hashCode()
r1 = 5
r2 = 4
r3 = 3
r4 = 2
r5 = 1
switch(r0) {
case -1364013995: goto L_0x003f;
case -1074341483: goto L_0x0035;
case 100571: goto L_0x002b;
case 3317767: goto L_0x0021;
case 108511772: goto L_0x0017;
case 109757538: goto L_0x000d;
default: goto L_0x000c;
}
L_0x000c:
goto L_0x0049
L_0x000d:
java.lang.String r0 = "start"
boolean r0 = r6.equals(r0)
if (r0 == 0) goto L_0x0049
r0 = 0
goto L_0x004a
L_0x0017:
java.lang.String r0 = "right"
boolean r0 = r6.equals(r0)
if (r0 == 0) goto L_0x0049
r0 = 5
goto L_0x004a
L_0x0021:
java.lang.String r0 = "left"
boolean r0 = r6.equals(r0)
if (r0 == 0) goto L_0x0049
r0 = 1
goto L_0x004a
L_0x002b:
java.lang.String r0 = "end"
boolean r0 = r6.equals(r0)
if (r0 == 0) goto L_0x0049
r0 = 4
goto L_0x004a
L_0x0035:
java.lang.String r0 = "middle"
boolean r0 = r6.equals(r0)
if (r0 == 0) goto L_0x0049
r0 = 3
goto L_0x004a
L_0x003f:
java.lang.String r0 = "center"
boolean r0 = r6.equals(r0)
if (r0 == 0) goto L_0x0049
r0 = 2
goto L_0x004a
L_0x0049:
r0 = -1
L_0x004a:
if (r0 == 0) goto L_0x0074
if (r0 == r5) goto L_0x0074
if (r0 == r4) goto L_0x0071
if (r0 == r3) goto L_0x0071
if (r0 == r2) goto L_0x006e
if (r0 == r1) goto L_0x006e
java.lang.StringBuilder r0 = new java.lang.StringBuilder
r0.<init>()
java.lang.String r1 = "Invalid alignment value: "
r0.append(r1)
r0.append(r6)
java.lang.String r6 = r0.toString()
java.lang.String r0 = "WebvttCueParser"
com.google.android.exoplayer2.util.Log.m173w(r0, r6)
r6 = 0
return r6
L_0x006e:
android.text.Layout$Alignment r6 = android.text.Layout.Alignment.ALIGN_OPPOSITE
return r6
L_0x0071:
android.text.Layout$Alignment r6 = android.text.Layout.Alignment.ALIGN_CENTER
return r6
L_0x0074:
android.text.Layout$Alignment r6 = android.text.Layout.Alignment.ALIGN_NORMAL
return r6
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.text.webvtt.WebvttCueParser.parseTextAlignment(java.lang.String):android.text.Layout$Alignment");
}
private static int findEndOfTag(String str, int i) {
int indexOf = str.indexOf(62, i);
return indexOf == -1 ? str.length() : indexOf + 1;
}
/* JADX WARNING: Removed duplicated region for block: B:22:0x0045 */
/* JADX WARNING: Removed duplicated region for block: B:29:0x0079 */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static void applyEntity(java.lang.String r5, android.text.SpannableStringBuilder r6) {
/*
int r0 = r5.hashCode()
r1 = 3309(0xced, float:4.637E-42)
r2 = 3
r3 = 2
r4 = 1
if (r0 == r1) goto L_0x0038
r1 = 3464(0xd88, float:4.854E-42)
if (r0 == r1) goto L_0x002e
r1 = 96708(0x179c4, float:1.35517E-40)
if (r0 == r1) goto L_0x0024
r1 = 3374865(0x337f11, float:4.729193E-39)
if (r0 == r1) goto L_0x001a
goto L_0x0042
L_0x001a:
java.lang.String r0 = "nbsp"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0042
r0 = 2
goto L_0x0043
L_0x0024:
java.lang.String r0 = "amp"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0042
r0 = 3
goto L_0x0043
L_0x002e:
java.lang.String r0 = "lt"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0042
r0 = 0
goto L_0x0043
L_0x0038:
java.lang.String r0 = "gt"
boolean r0 = r5.equals(r0)
if (r0 == 0) goto L_0x0042
r0 = 1
goto L_0x0043
L_0x0042:
r0 = -1
L_0x0043:
if (r0 == 0) goto L_0x0079
if (r0 == r4) goto L_0x0073
if (r0 == r3) goto L_0x006d
if (r0 == r2) goto L_0x0067
java.lang.StringBuilder r6 = new java.lang.StringBuilder
r6.<init>()
java.lang.String r0 = "ignoring unsupported entity: '&"
r6.append(r0)
r6.append(r5)
java.lang.String r5 = ";'"
r6.append(r5)
java.lang.String r5 = r6.toString()
java.lang.String r6 = "WebvttCueParser"
com.google.android.exoplayer2.util.Log.m173w(r6, r5)
goto L_0x007e
L_0x0067:
r5 = 38
r6.append(r5)
goto L_0x007e
L_0x006d:
r5 = 32
r6.append(r5)
goto L_0x007e
L_0x0073:
r5 = 62
r6.append(r5)
goto L_0x007e
L_0x0079:
r5 = 60
r6.append(r5)
L_0x007e:
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.text.webvtt.WebvttCueParser.applyEntity(java.lang.String, android.text.SpannableStringBuilder):void");
}
/* JADX WARNING: Removed duplicated region for block: B:32:0x0065 A[ADDED_TO_REGION] */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static boolean isSupportedTag(java.lang.String r8) {
/*
int r0 = r8.hashCode()
r1 = 98
r2 = 0
r3 = 5
r4 = 4
r5 = 3
r6 = 2
r7 = 1
if (r0 == r1) goto L_0x0058
r1 = 99
if (r0 == r1) goto L_0x004e
r1 = 105(0x69, float:1.47E-43)
if (r0 == r1) goto L_0x0044
r1 = 3314158(0x3291ee, float:4.644125E-39)
if (r0 == r1) goto L_0x003a
r1 = 117(0x75, float:1.64E-43)
if (r0 == r1) goto L_0x002f
r1 = 118(0x76, float:1.65E-43)
if (r0 == r1) goto L_0x0024
goto L_0x0062
L_0x0024:
java.lang.String r0 = "v"
boolean r8 = r8.equals(r0)
if (r8 == 0) goto L_0x0062
r8 = 5
goto L_0x0063
L_0x002f:
java.lang.String r0 = "u"
boolean r8 = r8.equals(r0)
if (r8 == 0) goto L_0x0062
r8 = 4
goto L_0x0063
L_0x003a:
java.lang.String r0 = "lang"
boolean r8 = r8.equals(r0)
if (r8 == 0) goto L_0x0062
r8 = 3
goto L_0x0063
L_0x0044:
java.lang.String r0 = "i"
boolean r8 = r8.equals(r0)
if (r8 == 0) goto L_0x0062
r8 = 2
goto L_0x0063
L_0x004e:
java.lang.String r0 = "c"
boolean r8 = r8.equals(r0)
if (r8 == 0) goto L_0x0062
r8 = 1
goto L_0x0063
L_0x0058:
java.lang.String r0 = "b"
boolean r8 = r8.equals(r0)
if (r8 == 0) goto L_0x0062
r8 = 0
goto L_0x0063
L_0x0062:
r8 = -1
L_0x0063:
if (r8 == 0) goto L_0x0070
if (r8 == r7) goto L_0x0070
if (r8 == r6) goto L_0x0070
if (r8 == r5) goto L_0x0070
if (r8 == r4) goto L_0x0070
if (r8 == r3) goto L_0x0070
return r2
L_0x0070:
return r7
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.text.webvtt.WebvttCueParser.isSupportedTag(java.lang.String):boolean");
}
/* JADX WARNING: Removed duplicated region for block: B:38:0x0079 A[RETURN] */
/* JADX WARNING: Removed duplicated region for block: B:39:0x007a */
/* JADX WARNING: Removed duplicated region for block: B:40:0x0083 */
/* JADX WARNING: Removed duplicated region for block: B:41:0x008c */
/* JADX WARNING: Removed duplicated region for block: B:44:0x00a0 A[LOOP:0: B:43:0x009e->B:44:0x00a0, LOOP_END] */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static void applySpansForTag(java.lang.String r8, com.google.android.exoplayer2.text.webvtt.WebvttCueParser.StartTag r9, android.text.SpannableStringBuilder r10, java.util.List<com.google.android.exoplayer2.text.webvtt.WebvttCssStyle> r11, java.util.List<com.google.android.exoplayer2.text.webvtt.WebvttCueParser.StyleMatch> r12) {
/*
int r0 = r9.position
int r1 = r10.length()
java.lang.String r2 = r9.name
int r3 = r2.hashCode()
r4 = 0
r5 = 2
r6 = 1
if (r3 == 0) goto L_0x0069
r7 = 105(0x69, float:1.47E-43)
if (r3 == r7) goto L_0x005f
r7 = 3314158(0x3291ee, float:4.644125E-39)
if (r3 == r7) goto L_0x0055
r7 = 98
if (r3 == r7) goto L_0x004b
r7 = 99
if (r3 == r7) goto L_0x0041
r7 = 117(0x75, float:1.64E-43)
if (r3 == r7) goto L_0x0036
r7 = 118(0x76, float:1.65E-43)
if (r3 == r7) goto L_0x002b
goto L_0x0073
L_0x002b:
java.lang.String r3 = "v"
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 5
goto L_0x0074
L_0x0036:
java.lang.String r3 = "u"
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 2
goto L_0x0074
L_0x0041:
java.lang.String r3 = "c"
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 3
goto L_0x0074
L_0x004b:
java.lang.String r3 = "b"
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 0
goto L_0x0074
L_0x0055:
java.lang.String r3 = "lang"
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 4
goto L_0x0074
L_0x005f:
java.lang.String r3 = "i"
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 1
goto L_0x0074
L_0x0069:
java.lang.String r3 = ""
boolean r2 = r2.equals(r3)
if (r2 == 0) goto L_0x0073
r2 = 6
goto L_0x0074
L_0x0073:
r2 = -1
L_0x0074:
r3 = 33
switch(r2) {
case 0: goto L_0x008c;
case 1: goto L_0x0083;
case 2: goto L_0x007a;
case 3: goto L_0x0094;
case 4: goto L_0x0094;
case 5: goto L_0x0094;
case 6: goto L_0x0094;
default: goto L_0x0079;
}
L_0x0079:
return
L_0x007a:
android.text.style.UnderlineSpan r2 = new android.text.style.UnderlineSpan
r2.<init>()
r10.setSpan(r2, r0, r1, r3)
goto L_0x0094
L_0x0083:
android.text.style.StyleSpan r2 = new android.text.style.StyleSpan
r2.<init>(r5)
r10.setSpan(r2, r0, r1, r3)
goto L_0x0094
L_0x008c:
android.text.style.StyleSpan r2 = new android.text.style.StyleSpan
r2.<init>(r6)
r10.setSpan(r2, r0, r1, r3)
L_0x0094:
r12.clear()
getApplicableStyles(r11, r8, r9, r12)
int r8 = r12.size()
L_0x009e:
if (r4 >= r8) goto L_0x00ae
java.lang.Object r9 = r12.get(r4)
com.google.android.exoplayer2.text.webvtt.WebvttCueParser$StyleMatch r9 = (com.google.android.exoplayer2.text.webvtt.WebvttCueParser.StyleMatch) r9
com.google.android.exoplayer2.text.webvtt.WebvttCssStyle r9 = r9.style
applyStyleToText(r10, r9, r0, r1)
int r4 = r4 + 1
goto L_0x009e
L_0x00ae:
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.text.webvtt.WebvttCueParser.applySpansForTag(java.lang.String, com.google.android.exoplayer2.text.webvtt.WebvttCueParser$StartTag, android.text.SpannableStringBuilder, java.util.List, java.util.List):void");
}
private static void applyStyleToText(SpannableStringBuilder spannableStringBuilder, WebvttCssStyle webvttCssStyle, int i, int i2) {
if (webvttCssStyle != null) {
if (webvttCssStyle.getStyle() != -1) {
spannableStringBuilder.setSpan(new StyleSpan(webvttCssStyle.getStyle()), i, i2, 33);
}
if (webvttCssStyle.isLinethrough()) {
spannableStringBuilder.setSpan(new StrikethroughSpan(), i, i2, 33);
}
if (webvttCssStyle.isUnderline()) {
spannableStringBuilder.setSpan(new UnderlineSpan(), i, i2, 33);
}
if (webvttCssStyle.hasFontColor()) {
spannableStringBuilder.setSpan(new ForegroundColorSpan(webvttCssStyle.getFontColor()), i, i2, 33);
}
if (webvttCssStyle.hasBackgroundColor()) {
spannableStringBuilder.setSpan(new BackgroundColorSpan(webvttCssStyle.getBackgroundColor()), i, i2, 33);
}
if (webvttCssStyle.getFontFamily() != null) {
spannableStringBuilder.setSpan(new TypefaceSpan(webvttCssStyle.getFontFamily()), i, i2, 33);
}
if (webvttCssStyle.getTextAlign() != null) {
spannableStringBuilder.setSpan(new AlignmentSpan.Standard(webvttCssStyle.getTextAlign()), i, i2, 33);
}
int fontSizeUnit = webvttCssStyle.getFontSizeUnit();
if (fontSizeUnit == 1) {
spannableStringBuilder.setSpan(new AbsoluteSizeSpan((int) webvttCssStyle.getFontSize(), true), i, i2, 33);
} else if (fontSizeUnit == 2) {
spannableStringBuilder.setSpan(new RelativeSizeSpan(webvttCssStyle.getFontSize()), i, i2, 33);
} else if (fontSizeUnit == 3) {
spannableStringBuilder.setSpan(new RelativeSizeSpan(webvttCssStyle.getFontSize() / 100.0f), i, i2, 33);
}
}
}
private static String getTagName(String str) {
String trim = str.trim();
if (trim.isEmpty()) {
return null;
}
return Util.splitAtFirst(trim, "[ \\.]")[0];
}
private static void getApplicableStyles(List<WebvttCssStyle> list, String str, StartTag startTag, List<StyleMatch> list2) {
int size = list.size();
for (int i = 0; i < size; i++) {
WebvttCssStyle webvttCssStyle = list.get(i);
int specificityScore = webvttCssStyle.getSpecificityScore(str, startTag.name, startTag.classes, startTag.voice);
if (specificityScore > 0) {
list2.add(new StyleMatch(specificityScore, webvttCssStyle));
}
}
Collections.sort(list2);
}
private static final class StyleMatch implements Comparable<StyleMatch> {
public final int score;
public final WebvttCssStyle style;
public StyleMatch(int i, WebvttCssStyle webvttCssStyle) {
this.score = i;
this.style = webvttCssStyle;
}
public int compareTo(StyleMatch styleMatch) {
return this.score - styleMatch.score;
}
}
private static final class StartTag {
private static final String[] NO_CLASSES = new String[0];
public final String[] classes;
public final String name;
public final int position;
public final String voice;
private StartTag(String str, int i, String str2, String[] strArr) {
this.position = i;
this.name = str;
this.voice = str2;
this.classes = strArr;
}
public static StartTag buildStartTag(String str, int i) {
String str2;
String[] strArr;
String trim = str.trim();
if (trim.isEmpty()) {
return null;
}
int indexOf = trim.indexOf(StringUtils.SPACE);
if (indexOf == -1) {
str2 = "";
} else {
String trim2 = trim.substring(indexOf).trim();
trim = trim.substring(0, indexOf);
str2 = trim2;
}
String[] split = Util.split(trim, "\\.");
String str3 = split[0];
if (split.length > 1) {
strArr = (String[]) Arrays.copyOfRange(split, 1, split.length);
} else {
strArr = NO_CLASSES;
}
return new StartTag(str3, i, str2, strArr);
}
public static StartTag buildWholeCueVirtualTag() {
return new StartTag("", 0, "", new String[0]);
}
}
}
|
923cb0eb4c6ce983fdf47f3e16db7c3648a0d53d | 1,821 | java | Java | src/minecraft/biotech/entity/monster/bioCaveSpider.java | liquidgithub/Biotech | 26add7f56eb83c1067f2f71a1f91c41bc081504e | [
"BSD-3-Clause"
] | 1 | 2015-10-02T14:18:59.000Z | 2015-10-02T14:18:59.000Z | src/minecraft/biotech/entity/monster/bioCaveSpider.java | liquidgithub/Biotech | 26add7f56eb83c1067f2f71a1f91c41bc081504e | [
"BSD-3-Clause"
] | null | null | null | src/minecraft/biotech/entity/monster/bioCaveSpider.java | liquidgithub/Biotech | 26add7f56eb83c1067f2f71a1f91c41bc081504e | [
"BSD-3-Clause"
] | null | null | null | 26.014286 | 124 | 0.537617 | 1,000,024 | package biotech.entity.monster;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class bioCaveSpider extends bioSpider
{
public bioCaveSpider(World par1World, int Health, float Width, float Height, int Drops, int EV, int AS, boolean Hostile)
{
super(par1World, Health, Width, Height, Drops, EV, AS, Hostile);
this.texture = "/mob/cavespider.png";
this.setSize(0.7F, 0.5F);
}
@SideOnly(Side.CLIENT)
/**
* How large the spider should be scaled.
*/
public float spiderScaleAmount()
{
return 0.7F;
}
public boolean attackEntityAsMob(Entity par1Entity)
{
if (super.attackEntityAsMob(par1Entity))
{
if (par1Entity instanceof EntityLiving)
{
byte b0 = 0;
if (this.worldObj.difficultySetting > 1)
{
if (this.worldObj.difficultySetting == 2)
{
b0 = 7;
}
else if (this.worldObj.difficultySetting == 3)
{
b0 = 15;
}
}
if (b0 > 0)
{
((EntityLiving)par1Entity).addPotionEffect(new PotionEffect(Potion.poison.id, b0 * 20, 0));
}
}
return true;
}
else
{
return false;
}
}
/**
* Initialize this creature.
*/
public void initCreature() {}
}
|
923cb166b1d10da8e36b6189ecec50672a754373 | 311 | java | Java | SpringWEB/SpringSecurity/LiveSessions/MethodSecurity/src/main/java/com/example/methodsecurity/repositories/AuthorityRepository.java | anupamdev/Spring | 3236bce601779f65809ead080621cff9c743ea7f | [
"Apache-2.0"
] | 25 | 2020-08-24T20:07:37.000Z | 2022-03-04T20:13:20.000Z | SpringWEB/SpringSecurity/LiveSessions/MethodSecurity/src/main/java/com/example/methodsecurity/repositories/AuthorityRepository.java | anupamdev/Spring | 3236bce601779f65809ead080621cff9c743ea7f | [
"Apache-2.0"
] | 20 | 2021-05-18T19:45:12.000Z | 2022-03-24T06:25:40.000Z | SpringWEB/SpringSecurity/LiveSessions/MethodSecurity/src/main/java/com/example/methodsecurity/repositories/AuthorityRepository.java | anupamdev/Spring | 3236bce601779f65809ead080621cff9c743ea7f | [
"Apache-2.0"
] | 19 | 2020-09-07T10:01:20.000Z | 2022-03-05T11:34:45.000Z | 25.916667 | 77 | 0.85209 | 1,000,025 | package com.example.methodsecurity.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.methodsecurity.entities.Authority;
@Repository
public interface AuthorityRepository extends JpaRepository<Authority, Long> {
}
|
923cb1783b2079258a20f48dc8bb31f8af1f2c59 | 212 | java | Java | examples/src/main/java/cn/gmssl/crypto/SM3Jce.java | merchoco/gm-jsse | e158a0568bd78259e08b25fda70e8882e4f78a5e | [
"Apache-2.0"
] | 2 | 2021-12-02T08:01:07.000Z | 2021-12-02T08:01:09.000Z | examples/src/main/java/cn/gmssl/crypto/SM3Jce.java | merchoco/gm-jsse | e158a0568bd78259e08b25fda70e8882e4f78a5e | [
"Apache-2.0"
] | null | null | null | examples/src/main/java/cn/gmssl/crypto/SM3Jce.java | merchoco/gm-jsse | e158a0568bd78259e08b25fda70e8882e4f78a5e | [
"Apache-2.0"
] | 1 | 2021-12-02T08:01:10.000Z | 2021-12-02T08:01:10.000Z | 19.272727 | 53 | 0.726415 | 1,000,026 | package cn.gmssl.crypto;
import cn.gmssl.crypto.impl.SM3;
import org.bc.jcajce.provider.digest.BCMessageDigest;
public class SM3Jce extends BCMessageDigest {
public SM3Jce() {
super(new SM3());
}
}
|
923cb1b4368531639f90dcb55798baea8091be4c | 331 | java | Java | persona/src/main/java/com/crud/persona/interfaceService/IpersonaService.java | hackunix/Frontend-Estudiante-SpringBoot | f117448e18ac772e6fe0cfb62c8c5b08d98f872f | [
"Apache-2.0"
] | null | null | null | persona/src/main/java/com/crud/persona/interfaceService/IpersonaService.java | hackunix/Frontend-Estudiante-SpringBoot | f117448e18ac772e6fe0cfb62c8c5b08d98f872f | [
"Apache-2.0"
] | null | null | null | persona/src/main/java/com/crud/persona/interfaceService/IpersonaService.java | hackunix/Frontend-Estudiante-SpringBoot | f117448e18ac772e6fe0cfb62c8c5b08d98f872f | [
"Apache-2.0"
] | null | null | null | 23.642857 | 54 | 0.758308 | 1,000,027 | package com.crud.persona.interfaceService;
import com.crud.persona.modelo.Persona;
import java.util.List;
import java.util.Optional;
public interface IpersonaService {
public List<Persona> listar();
public Optional<Persona> listarCodsis(int codsis);
public int save(Persona p);
public void delete(int codsis);
}
|
923cb245f7c3702fb9901c9fc02774f9f8a4eb0e | 1,277 | java | Java | src/Test.java | anthrwpos1/JUtils | ab497bf55b86182b20427a0eca488191c853813f | [
"Unlicense"
] | null | null | null | src/Test.java | anthrwpos1/JUtils | ab497bf55b86182b20427a0eca488191c853813f | [
"Unlicense"
] | null | null | null | src/Test.java | anthrwpos1/JUtils | ab497bf55b86182b20427a0eca488191c853813f | [
"Unlicense"
] | null | null | null | 31.146341 | 90 | 0.531715 | 1,000,028 | import MonteCarlo.Method;
import MonteCarlo.VecOp;
import java.util.Random;
import static Diagramm.Plot2D.plot;
public class Test {
static VecOp x;
static VecOp y;
public static void main(String[] args) {
System.out.println("Test");
x = new VecOp(new double[]{1, 2, 3});
y = new VecOp(new double[]{31, 35, 59});
Random r = new Random();
Method m = new Method(r, new VecOp(new double[]{1, 1, 1}), x -> error(x));
VecOp fact = m.runMethod(100000, 0.1, new VecOp(new double[]{0, 0, 0}));
System.out.printf("args: %f, %f, %f\n", fact.vect[0], fact.vect[1], fact.vect[2]);
double[] vdy = new double[100];
for (int i = 0; i < 100; i++) {
vdy[i] = ((double) i) / 100 * 4;
}
VecOp vd = (new VecOp(vdy));
vd.op(a -> formula(a, fact));
plot(vd.vect);
}
static private double error(VecOp args) {
VecOp x1 = x.clone();
x1.op((a, b) -> formula(a, args) - b, y);
return x1.fold(0, (acc, v) -> acc + v * v);
}
private static double formula(double x, VecOp args) {
double a0 = args.vect[0];
double a1 = args.vect[1];
double a2 = args.vect[2];
return (a1 * Math.exp(a0 * x) + a2);
}
} |
923cb34ef7ff1c519c9364a3176b1b07d14a0be7 | 709 | java | Java | projects/g3h1-java/Homework1-OOBasicCSS/src/SumOfArgs.java | keybrl/xdu-coursework | 9d0e905bef28c18d87d3b97643de0d32f9f08ee0 | [
"MIT"
] | null | null | null | projects/g3h1-java/Homework1-OOBasicCSS/src/SumOfArgs.java | keybrl/xdu-coursework | 9d0e905bef28c18d87d3b97643de0d32f9f08ee0 | [
"MIT"
] | null | null | null | projects/g3h1-java/Homework1-OOBasicCSS/src/SumOfArgs.java | keybrl/xdu-coursework | 9d0e905bef28c18d87d3b97643de0d32f9f08ee0 | [
"MIT"
] | null | null | null | 23.633333 | 52 | 0.416079 | 1,000,029 | /**
* 读取命令行参数中所有的整数,打印其和
*/
public class SumOfArgs {
public static void main(String[] args) {
int sum = 0;
String digits = "1234567890";
for (String arg: args) {
// 判断是否为整数
boolean is_num = true;
char[] arg_char_arr = arg.toCharArray();
for (char arg_ch: arg_char_arr) {
if (digits.indexOf(arg_ch) != -1) {
continue;
}
is_num = false;
break;
}
if (!is_num) {
continue;
}
// 加
sum += Integer.valueOf(arg);
}
// 输出
System.out.println(sum);
}
}
|
923cb61ca3ea735306c7260ff73c2fbe12dee35d | 1,328 | java | Java | pinot-core/src/main/java/com/linkedin/pinot/core/operator/docidsets/BitmapBasedBlockDocIdSet.java | newsummit/incubator-pinot | 3fee99dcf2bcce9a5d292519cdfced30e726056b | [
"Apache-2.0"
] | null | null | null | pinot-core/src/main/java/com/linkedin/pinot/core/operator/docidsets/BitmapBasedBlockDocIdSet.java | newsummit/incubator-pinot | 3fee99dcf2bcce9a5d292519cdfced30e726056b | [
"Apache-2.0"
] | null | null | null | pinot-core/src/main/java/com/linkedin/pinot/core/operator/docidsets/BitmapBasedBlockDocIdSet.java | newsummit/incubator-pinot | 3fee99dcf2bcce9a5d292519cdfced30e726056b | [
"Apache-2.0"
] | null | null | null | 31.761905 | 75 | 0.763868 | 1,000,030 | /**
* Copyright (C) 2014-2018 LinkedIn Corp. (anpch@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.core.operator.docidsets;
import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
import com.linkedin.pinot.core.common.BlockDocIdIterator;
import com.linkedin.pinot.core.common.BlockDocIdSet;
import com.linkedin.pinot.core.operator.dociditerators.BitmapDocIdIterator;
public final class BitmapBasedBlockDocIdSet implements BlockDocIdSet {
private final ImmutableRoaringBitmap bitmap;
public BitmapBasedBlockDocIdSet(ImmutableRoaringBitmap bitmap) {
this.bitmap = bitmap;
}
@Override
public BlockDocIdIterator iterator() {
return new BitmapDocIdIterator(bitmap.getIntIterator());
}
@Override
public <T> T getRaw() {
return null;
}
}
|
923cb6ce982dd433b0d0d5fb370462dd2a9dda56 | 4,700 | java | Java | src/test/java/it/reply/orchestrator/service/deployment/providers/factory/MarathonClientFactoryTest.java | maricaantonacci/orchestrator | 8c64f7a86d748cd0bd40c36605aead75931b8ca5 | [
"Apache-2.0"
] | 14 | 2016-10-06T16:02:29.000Z | 2022-02-07T19:35:20.000Z | src/test/java/it/reply/orchestrator/service/deployment/providers/factory/MarathonClientFactoryTest.java | maricaantonacci/orchestrator | 8c64f7a86d748cd0bd40c36605aead75931b8ca5 | [
"Apache-2.0"
] | 270 | 2016-01-27T19:57:41.000Z | 2022-01-03T10:33:29.000Z | src/test/java/it/reply/orchestrator/service/deployment/providers/factory/MarathonClientFactoryTest.java | maricaantonacci/orchestrator | 8c64f7a86d748cd0bd40c36605aead75931b8ca5 | [
"Apache-2.0"
] | 19 | 2017-05-25T18:16:28.000Z | 2022-02-07T19:35:22.000Z | 33.81295 | 98 | 0.742979 | 1,000,031 | /*
* Copyright © 2015-2021 I.N.F.N.
* Copyright © 2015-2020 Santer Reply S.p.A.
*
* 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 it.reply.orchestrator.service.deployment.providers.factory;
import it.reply.orchestrator.dto.CloudProviderEndpoint;
import it.reply.orchestrator.dto.CloudProviderEndpoint.IaaSType;
import it.reply.orchestrator.dto.security.GenericServiceCredential;
import it.reply.orchestrator.service.deployment.providers.CredentialProviderService;
import java.net.URISyntaxException;
import java.util.UUID;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import junitparams.JUnitParamsRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(JUnitParamsRunner.class)
public class MarathonClientFactoryTest {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@MockBean
private CredentialProviderService credProvServ;
private MarathonClientFactory clientFactory;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
clientFactory = new MarathonClientFactory(credProvServ);
}
@Test
public void testgetClientSuccessfulNoIam() throws URISyntaxException {
CloudProviderEndpoint cloudProviderEndpoint = CloudProviderEndpoint
.builder()
.cpEndpoint("http://example.com")
.cpComputeServiceId(UUID.randomUUID().toString())
.iaasType(IaaSType.MARATHON)
.build();
String serviceId = cloudProviderEndpoint.getCpComputeServiceId();
Mockito
.when(credProvServ.credentialProvider(serviceId, "token", GenericServiceCredential.class))
.thenReturn(new GenericServiceCredential("username", "password"));
assertThat(clientFactory.build(cloudProviderEndpoint, "token"))
.extracting("h.target.url")
.containsOnly("http://example.com");
}
@Test
public void testgetClientSuccessful() throws URISyntaxException {
CloudProviderEndpoint cloudProviderEndpoint = CloudProviderEndpoint
.builder()
.cpEndpoint("http://example.com")
.cpComputeServiceId(UUID.randomUUID().toString())
.iaasType(IaaSType.MARATHON)
.iamEnabled(true)
.idpProtocol("oidc")
.build();
String serviceId = cloudProviderEndpoint.getCpComputeServiceId();
Mockito
.when(credProvServ.credentialProvider(serviceId, "token", GenericServiceCredential.class))
.thenReturn(new GenericServiceCredential("username", "password"));
assertThat(clientFactory.build(cloudProviderEndpoint, "token"))
.extracting("h.target.url")
.containsOnly("http://example.com");
}
@Test
public void testgetClientErrorNoIam() {
CloudProviderEndpoint cloudProviderEndpoint = CloudProviderEndpoint
.builder()
.cpEndpoint("http://example.com")
.cpComputeServiceId(UUID.randomUUID().toString())
.iaasType(IaaSType.MARATHON)
.build();
assertThatThrownBy(() -> clientFactory.build(cloudProviderEndpoint, null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void testgetClientError() {
CloudProviderEndpoint cloudProviderEndpoint = CloudProviderEndpoint
.builder()
.cpEndpoint("http://example.com")
.cpComputeServiceId(UUID.randomUUID().toString())
.iaasType(IaaSType.MARATHON)
.iamEnabled(true)
.idpProtocol("oidc")
.build();
assertThatThrownBy(() -> clientFactory.build(cloudProviderEndpoint, null))
.isInstanceOf(NullPointerException.class);
}
}
|
923cb77120fb566112547e46ab7060f2c9560d1e | 2,490 | java | Java | src/proxy/src/main/java/edu/stanford/biosearch/data/elasticsearch/HttpExecutor.java | susom/biocatalyst | 946d638e50c85843f26f9b6a94c0c509650fbff9 | [
"Apache-2.0"
] | 2 | 2019-10-07T14:30:06.000Z | 2019-11-15T16:11:44.000Z | src/proxy/src/main/java/edu/stanford/biosearch/data/elasticsearch/HttpExecutor.java | susom/biocatalyst | 946d638e50c85843f26f9b6a94c0c509650fbff9 | [
"Apache-2.0"
] | 1 | 2020-01-02T21:57:05.000Z | 2020-01-02T21:57:05.000Z | src/proxy/src/main/java/edu/stanford/biosearch/data/elasticsearch/HttpExecutor.java | susom/biocatalyst | 946d638e50c85843f26f9b6a94c0c509650fbff9 | [
"Apache-2.0"
] | 1 | 2019-10-16T20:23:04.000Z | 2019-10-16T20:23:04.000Z | 33.648649 | 101 | 0.735743 | 1,000,032 | package edu.stanford.biosearch.data.elasticsearch;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
@Service
public class HttpExecutor {
private static final Logger logger = Logger.getLogger(HttpExecutor.class);
/**
* Executes an HTTP request. The aspect in ElasticsearchAspect.java adds the user's credentials.
*
* @param request
* @return
* @throws IOException
*/
public Map<String, Object> executeHTTPRequest(HttpRequestBase request) throws IOException {
request.setHeader("Content-Type", "application/json");
Map<String, Object> result = new HashMap<String, Object>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
logger.info(responseCode);
result.put(NetworkClient.RESPONSE_CODE, String.valueOf(responseCode));
HttpEntity responseEntity = response.getEntity();
result.put(NetworkClient.RESPONSE_BODY, ""); // Default Empty
if (responseEntity != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> resp = (Map<String, Object>) mapper.readValue(sb.toString(), Object.class);
result.put(NetworkClient.RESPONSE_BODY, resp);
}
logger.info(result);
logger.info("FINISH HttpExecutor.executeHTTPRequest");
return result;
}
/**
* Executes an HTTP request. The aspect in ElasticsearchAspect.java adds superuser credentials.
* Since executeHTTPRequest is called from a method in the same class, its aspect is not called.
*
* @param request
* @return
* @throws IOException
*/
public Map<String, Object> executeHTTPRequestAsAdmin(HttpRequestBase request) throws IOException {
return executeHTTPRequest(request);
}
}
|
923cbaceaef14f76205a98b4c58c1068ba023594 | 27,340 | java | Java | src/com/dncrm/controller/system/workflow/LeaveController/LeaveController.java | GZ-ZengXiangJun/SouthEastElevatorCRM | 8127b1e3c18feab41b99c9344fdd216d6e331809 | [
"MIT"
] | 1 | 2019-12-08T18:24:30.000Z | 2019-12-08T18:24:30.000Z | src/com/dncrm/controller/system/workflow/LeaveController/LeaveController.java | GZ-ZengXiangJun/SouthEastElevatorCRM | 8127b1e3c18feab41b99c9344fdd216d6e331809 | [
"MIT"
] | null | null | null | src/com/dncrm/controller/system/workflow/LeaveController/LeaveController.java | GZ-ZengXiangJun/SouthEastElevatorCRM | 8127b1e3c18feab41b99c9344fdd216d6e331809 | [
"MIT"
] | null | null | null | 39.113019 | 219 | 0.562838 | 1,000,033 | package com.dncrm.controller.system.workflow.LeaveController;
import com.dncrm.common.WorkFlow;
import com.dncrm.controller.base.BaseController;
import com.dncrm.entity.Page;
import com.dncrm.service.system.workflow.WorkFlowService;
import com.dncrm.service.system.workflow.leave.LeaveService;
import com.dncrm.util.AppUtil;
import com.dncrm.util.Const;
import com.dncrm.util.PageData;
import com.dncrm.util.StringUtil;
import net.sf.json.JSONObject;
import org.activiti.engine.IdentityService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.*;
@RequestMapping("/workflow/leave")
@Controller
public class LeaveController extends BaseController {
@Resource(name = "leaveService")
private LeaveService leaveService;
@Resource(name = "workFlowService")
private WorkFlowService workFlowService;
/**
* 显示我申请的请假
*
* @return
*/
@RequestMapping("/listLeaves")
public ModelAndView listLeaves(Page page) {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
try {
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
String USER_ID = pds.getString("USER_ID");
page.setPd(pds);
mv.setViewName("system/workflow/leave/leave_list");
mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
List<PageData> leaves = leaveService.listLeaves(page);
for (PageData leave:leaves) {
String process_instance_id= leave.getString("process_instance_id");
if (process_instance_id!=null){
WorkFlow workflow = new WorkFlow();
Task task = workflow.getTaskService().createTaskQuery().processInstanceId(process_instance_id).active().singleResult();
if(task!=null){
leave.put("task_id",task.getId());
leave.put("task_name",task.getName());
}
}
}
//待处理任务的count
WorkFlow workflow = new WorkFlow();
List<Task> toHandleListCount = workflow.getTaskService().createTaskQuery().taskCandidateOrAssigned(USER_ID).orderByTaskCreateTime().desc().active().list();
pd.put("count",toHandleListCount.size());
pd.put("isActive1","1");
mv.addObject("pd",pd);
mv.addObject("leaves", leaves);
mv.addObject("userpds", pds);
} catch (Exception e) {
logger.error(e.toString(), e);
}
return mv;
}
/**
* 显示待我处理的请假
*
* @return
*/
@RequestMapping("/listPendingLeaves")
public ModelAndView listPendingLeaves(Page page) {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
try {
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
String USER_ID = pds.getString("USER_ID");
page.setPd(pds);
mv.setViewName("system/workflow/leave/leave_list");
mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
List<PageData> pleaves = new ArrayList<>();
WorkFlow workFlow = new WorkFlow();
// 等待处理的任务
//设置分页数据
int firstResult;//开始游标
int maxResults;//结束游标
int showCount = page.getShowCount();//默认为10
int currentPage = page.getCurrentPage();//默认为0
if (currentPage==0) {//currentPage为0时,页面第一次加载或者刷新
firstResult = currentPage;//从0开始
currentPage+=1;//当前为第一页
maxResults = showCount;
}else{
firstResult = showCount*(currentPage-1);
maxResults = firstResult+showCount;
}
List<Task> toHandleListCount = workFlow.getTaskService().createTaskQuery().taskCandidateOrAssigned(USER_ID).processDefinitionKey("leave").orderByTaskCreateTime().desc().active().list();
List<Task> toHandleList = workFlow.getTaskService().createTaskQuery().taskCandidateOrAssigned(USER_ID).processDefinitionKey("leave").orderByTaskCreateTime().desc().active().listPage(firstResult, maxResults);
for (Task task : toHandleList) {
PageData leave = new PageData();
String processInstanceId = task.getProcessInstanceId();
ProcessInstance processInstance = workFlow.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
String businessKey = processInstance.getBusinessKey();
if (!StringUtils.isEmpty(businessKey)){
//leave.leaveId.
String[] info = businessKey.split("\\.");
leave.put(info[1],info[2]);
leave = leaveService.findById(leave);
leave.put("task_name",task.getName());
leave.put("task_id",task.getId());
if(task.getAssignee()!=null){
leave.put("type","1");//待处理
}else{
leave.put("type","0");//待签收
}
}
pleaves.add(leave);
}
//设置分页数据
int totalResult = toHandleListCount.size();
if (totalResult<=showCount) {
page.setTotalPage(1);
}else{
int count = Integer.valueOf(totalResult/showCount);
int mod= totalResult%showCount;
if (mod>0) {
count =count+1;
}
page.setTotalPage(count);
}
page.setTotalResult(totalResult);
page.setCurrentResult(pleaves.size());
page.setCurrentPage(currentPage);
page.setShowCount(showCount);
page.setEntityOrField(true);
//如果有多个form,设置第几个,从0开始
page.setFormNo(1);
page.setPageStrForActiviti(page.getPageStrForActiviti());
//待处理任务的count
pd.put("count",toHandleListCount.size());
pd.put("isActive2","1");
mv.addObject("pd",pd);
mv.addObject("pleaves", pleaves);
mv.addObject("userpds", pds);
} catch (Exception e) {
logger.error(e.toString(), e);
}
return mv;
}
/**
* 显示我已经处理的请假
*
* @return
*/
@RequestMapping("/listDoneLeaves")
public ModelAndView listDoneLeaves(Page page) {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
try {
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
String USER_ID = pds.getString("USER_ID");
page.setPd(pds);
mv.setViewName("system/workflow/leave/leave_list");
mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
WorkFlow workFlow = new WorkFlow();
// 已处理的任务
List<PageData> dleaves = new ArrayList<>();
List<HistoricTaskInstance> historicTaskInstances = workFlow.getHistoryService().createHistoricTaskInstanceQuery().taskAssignee(USER_ID).processDefinitionKey("leave").orderByTaskCreateTime().desc().list();
//移除重复的
List<HistoricTaskInstance> list = new ArrayList<HistoricTaskInstance>();
HashMap<String,HistoricTaskInstance> map = new HashMap<String,HistoricTaskInstance>();
for (HistoricTaskInstance instance:historicTaskInstances
) {
String processInstanceId = instance.getProcessInstanceId();
HistoricProcessInstance historicProcessInstance = workFlow.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
String businessKey = historicProcessInstance.getBusinessKey();
map.put(businessKey,instance);
}
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()){
Map.Entry entry = (Map.Entry) iter.next();
list.add((HistoricTaskInstance)entry.getValue());
}
//设置分页数据
int firstResult;//开始游标
int maxResults;//结束游标
int showCount = page.getShowCount();//默认为10
int currentPage = page.getCurrentPage();//默认为0
if (currentPage==0) {//currentPage为0时,页面第一次加载或者刷新
firstResult = currentPage;//从0开始
currentPage+=1;//当前为第一页
maxResults = showCount;
}else{
firstResult = showCount*(currentPage-1);
maxResults = firstResult+showCount;
}
int listCount =(list.size()<=maxResults?list.size():maxResults);
//从分页参数开始
for (int i = firstResult; i <listCount ; i++) {
HistoricTaskInstance historicTaskInstance = list.get(i);
PageData leave = new PageData();
String processInstanceId = historicTaskInstance.getProcessInstanceId();
HistoricProcessInstance historicProcessInstance = workFlow.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
String businessKey = historicProcessInstance.getBusinessKey();
if (!StringUtils.isEmpty(businessKey)){
//leave.leaveId.
String[] info = businessKey.split("\\.");
leave.put(info[1],info[2]);
leave = leaveService.findById(leave);
//检查申请者是否是本人,如果是,跳过
if (leave.getString("requester_id").equals(USER_ID))
continue;
//查询当前流程是否还存在
List<ProcessInstance> runing = workFlow.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).list();
if (runing==null||runing.size()<=0){
leave.put("isRuning",0);
}else{
leave.put("isRuning",1);
//正在运行,查询当前的任务信息
Task task = workFlow.getTaskService().createTaskQuery().processInstanceId(processInstanceId).singleResult();
leave.put("task_name",task.getName());
leave.put("task_id",task.getId());
}
dleaves.add(leave);
}
}
//设置分页数据
int totalResult = list.size();
if (totalResult<=showCount) {
page.setTotalPage(1);
}else{
int count = Integer.valueOf(totalResult/showCount);
int mod= totalResult%showCount;
if (mod>0) {
count =count+1;
}
page.setTotalPage(count);
}
page.setTotalResult(totalResult);
page.setCurrentResult(dleaves.size());
page.setCurrentPage(currentPage);
page.setShowCount(showCount);
page.setEntityOrField(true);
//如果有多个form,设置第几个,从0开始
page.setFormNo(2);
page.setPageStrForActiviti(page.getPageStrForActiviti());
//待处理任务的count
WorkFlow workflow = new WorkFlow();
List<Task> toHandleListCount = workflow.getTaskService().createTaskQuery().taskCandidateOrAssigned(USER_ID).orderByTaskCreateTime().desc().active().list();
pd.put("count",toHandleListCount.size());
pd.put("isActive3","1");
mv.addObject("pd",pd);
mv.addObject("dleaves", dleaves);
mv.addObject("userpds", pds);
} catch (Exception e) {
logger.error(e.toString(), e);
}
return mv;
}
/**
* 签收任务
*
* @return
*/
@RequestMapping("/claim")
@ResponseBody
public Object claim() {
Map map = new HashMap();
PageData pd = new PageData();
pd = this.getPageData();
try {
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
// 签收任务
List<PageData> leaves = new ArrayList<>();
WorkFlow workFlow = new WorkFlow();
String task_id = pd.getString("task_id");
String user_id = pds.getString("USER_ID");
workFlow.getTaskService().claim(task_id,user_id);
map.put("msg","success");
} catch (Exception e) {
map.put("msg","failed");
map.put("err","签收失败");
logger.error(e.toString(), e);
}
return JSONObject.fromObject(map);
}
/**
* 重新申请
*
* @return
*/
@RequestMapping("/restartLeave")
@ResponseBody
public Object restartLeave() {
Map map = new HashMap();
PageData pd = new PageData();
pd = this.getPageData();
try {
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
// 签收任务
List<PageData> leaves = new ArrayList<>();
WorkFlow workFlow = new WorkFlow();
String task_id = pd.getString("task_id");
String user_id = pds.getString("USER_ID");
workFlow.getTaskService().claim(task_id,user_id);
Map <String,Object> variables = new HashMap<String,Object>();
variables.put("action","重新提交");
//使得task_id与流程变量关联,查询历史记录时可以通过task_id查询到操作变量,必须使用setVariableLocal方法
workFlow.getTaskService().setVariablesLocal(task_id,variables);
Authentication.setAuthenticatedUserId(user_id);
//处理任务
workFlow.getTaskService().complete(task_id);
//更新业务数据的状态
pd.put("status",1);
leaveService.updateLeaveStatus(pd);
map.put("msg","success");
} catch (Exception e) {
map.put("msg","failed");
map.put("err","重新提交失败");
logger.error(e.toString(), e);
}
return JSONObject.fromObject(map);
}
/**
* 跳到办理任务页面
*
* @return
* @throws Exception
*/
@RequestMapping("/goHandleLeave")
public ModelAndView goHandleLeave() throws Exception {
ModelAndView mv = new ModelAndView();
PageData pd = this.getPageData();
mv.setViewName("system/workflow/leave/leave_handle");
mv.addObject("pd", pd);
return mv;
}
/**
* 处理任务
*
* @return
*/
@RequestMapping("/handle")
public ModelAndView handle() {
ModelAndView mv = new ModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
try {
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
// 办理任务
List<PageData> leaves = new ArrayList<>();
WorkFlow workFlow = new WorkFlow();
String task_id = pd.getString("task_id");
String user_id = pds.getString("USER_ID");
Map<String,Object> variables = new HashMap<String ,Object>();
boolean isApproved = false;
String action = pd.getString("action");
int status;
if (action.equals("approve")){
isApproved = true;
//如果是hr审批
Task task = workFlow.getTaskService().createTaskQuery().taskId(task_id).singleResult();
if (task.getTaskDefinitionKey().equals("HRApproval")){
status = 2;//已完成
pd.put("status",2);
leaveService.updateLeaveStatus(pd);
}
}else if(action.equals("reject")) {
status = 4;//被驳回
pd.put("status",4);
leaveService.updateLeaveStatus(pd);
}
String comment = (String) pd.get("comment");
if (isApproved){
variables.put("action","批准");
}else{
variables.put("action","驳回");
}
variables.put("approved",isApproved);
//使得task_id与流程变量关联,查询历史记录时可以通过task_id查询到操作变量,必须使用setVariableLocal方法
workFlow.getTaskService().setVariablesLocal(task_id,variables);
Authentication.setAuthenticatedUserId(user_id);
workFlow.getTaskService().addComment(task_id,null,comment);
workFlow.getTaskService().complete(task_id,variables);
mv.addObject("msg", "success");
} catch (Exception e) {
mv.addObject("msg", "failed");
mv.addObject("err", "办理失败!");
logger.error(e.toString(), e);
}
mv.addObject("id", "handleLeave");
mv.addObject("form", "handleLeaveForm");
mv.setViewName("save_result");
return mv;
}
/**
* 启动流程
*
*/
@RequestMapping(value = "/apply")
@ResponseBody
public Object apply() {
PageData pd = new PageData();
pd = this.getPageData();
Map<String, Object> map = new HashMap<String, Object>();
try {
String processDefinitionKey = "leave";
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
String USER_ID = pds.getString("USER_ID");
WorkFlow workFlow = new WorkFlow();
// 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
workFlow.getIdentityService().setAuthenticatedUserId(USER_ID);
Task task = workFlow.getTaskService().createTaskQuery().processInstanceId(pd.getString("process_instance_id")).singleResult();
Map<String,Object> variables = new HashMap<String,Object>();
//设置任务角色
workFlow.getTaskService().setAssignee(task.getId(),USER_ID);
//签收任务
workFlow.getTaskService().claim(task.getId(),USER_ID);
//设置流程变量
variables.put("action","提交申请");
workFlow.getTaskService().setVariablesLocal(task.getId(),variables);
//办理任务
workFlow.getTaskService().complete(task.getId());
pd.put("status",1);
//更新状态
leaveService.updateLeaveStatus(pd);
//获取下一个任务的信息
Task task2 = workFlow.getTaskService().createTaskQuery().processInstanceId(pd.getString("process_instance_id")).singleResult();
map.put("task_name",task2.getName());
map.put("msg", "success");
} catch (Exception e) {
logger.error(e.toString(), e);
map.put("msg", "failed");
map.put("err", "系统错误");
}
System.out.println("json-->"+JSONObject.fromObject(map));
return JSONObject.fromObject(map);
}
/**
* 跳到添加页面
*
* @return
*/
@RequestMapping("/goAddLeave")
public ModelAndView goAddLeave() {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
mv.setViewName("system/workflow/leave/leave_edit");
mv.addObject("msg", "addLeave");
mv.addObject("pd", pd);
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
mv.addObject("userpds", pds);
return mv;
}
/**
* 跳到编辑页面
*
* @return
* @throws Exception
*/
@RequestMapping("/goEditLeave")
public ModelAndView goEditLeave() throws Exception {
ModelAndView mv = new ModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
pd = leaveService.findById(pd);
mv.setViewName("system/workflow/leave/leave_edit");
mv.addObject("pd", pd);
mv.addObject("msg", "editLeave");
return mv;
}
/**
* 保存
*
* @return
*/
@RequestMapping("/addLeave")
public ModelAndView addLeave() {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
try {
pd.put("id", UUID.randomUUID().toString());
leaveService.insertLeave(pd);
//启动流程
String processDefinitionKey = "leave";
//shiro管理的session
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
PageData pds = new PageData();
pds = (PageData) session.getAttribute("userpds");
String USER_ID = pds.getString("USER_ID");
// 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
WorkFlow workFlow = new WorkFlow();
IdentityService identityService = workFlow.getIdentityService();
identityService.setAuthenticatedUserId(USER_ID);
//设置businesskey,格式为,表.字段名称.字段值
Object leaveId = pd.get("id");
String businessKey = "leave.leaveId."+leaveId;
//设置变量
Map<String ,Object> variables = new HashMap<String, Object>() ;
variables.put("user_id",USER_ID);
ProcessInstance processInstance = workFlow.getRuntimeService().startProcessInstanceByKey(processDefinitionKey,businessKey,variables);
if (processInstance != null) {
pd.put("process_instance_id",processInstance.getId());
leaveService.updateLeaveProcessInstanceId(pd);
mv.addObject("msg", "success");
} else {
leaveService.deleteLeave(pd);
mv.addObject("msg", "failed");
mv.addObject("err", "保存失败!");
}
} catch (Exception e) {
mv.addObject("msg", "failed");
mv.addObject("err", "保存失败!");
}
mv.addObject("id", "AddLeaves");
mv.addObject("form", "leaveForm");
mv.setViewName("save_result");
return mv;
}
/**
* 保存编辑
*
* @return
* @throws Exception
*/
@RequestMapping("/editLeave")
public ModelAndView editLeave() throws Exception {
ModelAndView mv = new ModelAndView();
PageData pd = this.getPageData();
try {
leaveService.updateLeave(pd);
mv.addObject("msg", "success");
} catch (Exception e) {
mv.addObject("msg", "failed");
mv.addObject("err", "修改失败!");
}
mv.addObject("id", "EditLeaves");
mv.addObject("form", "leaveForm");
mv.setViewName("save_result");
return mv;
}
/**
* 删除一条数据
*
*/
@RequestMapping("/delLeave")
@ResponseBody
public Object delLeave() {
Map<String, Object> map = new HashMap<String, Object>();
PageData pd = this.getPageData();
try {
String leaveId = (String)pd.get("id");
if (!StringUtils.isEmpty(leaveId)) {
pd.put("leaveId",pd.getString("id"));
pd = leaveService.findById(pd);
//删除启动的流程
WorkFlow workflow = new WorkFlow();
String processInstanceId = pd.getString("process_instance_id");
workflow.getRuntimeService().deleteProcessInstance(processInstanceId,"删除业务数据,删除流程");
leaveService.deleteLeave(pd);
map.put("msg", "success");
}else{
map.put("msg", "failed");
map.put("err", "无法获取ID");
}
} catch (Exception e) {
map.put("msg", "failed");
map.put("err", "删除失败");
}
return JSONObject.fromObject(map);
}
/**
* 批量删除
*/
@RequestMapping(value = "/delAllLeaves")
@ResponseBody
public Object delAllLeaves() {
logBefore(logger, "批量删除请假流程");
PageData pd = new PageData();
Map<String, Object> map = new HashMap<String, Object>();
try {
pd = this.getPageData();
List<PageData> pdList = new ArrayList<PageData>();
String DATA_IDS = pd.getString("DATA_IDS");
if (null != DATA_IDS && !"".equals(DATA_IDS)) {
String ArrayDATA_IDS[] = DATA_IDS.split(",");
leaveService.deleteAll(ArrayDATA_IDS);
pd.put("msg", "ok");
} else {
pd.put("msg", "no");
}
pdList.add(pd);
map.put("list", pdList);
} catch (Exception e) {
logger.error(e.toString(), e);
} finally {
logAfter(logger);
}
return AppUtil.returnObject(pd, map);
}
/* ===============================权限================================== */
public Map<String, String> getHC() {
Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
Session session = currentUser.getSession();
return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
}
/* ===============================权限================================== */
}
|
923cbbe168660221c94d6ed08a0ddad03f08e5a2 | 1,350 | java | Java | src/main/java/com/testvagrant/ekam/mobile/remote/RemoteMobileDriverFactory.java | dunzoit/ekam | f783dd92ec101596b6410f7840c355672a26f838 | [
"MIT"
] | 2 | 2021-08-03T05:13:30.000Z | 2021-08-12T16:07:38.000Z | src/main/java/com/testvagrant/ekam/mobile/remote/RemoteMobileDriverFactory.java | dunzoit/ekam | f783dd92ec101596b6410f7840c355672a26f838 | [
"MIT"
] | null | null | null | src/main/java/com/testvagrant/ekam/mobile/remote/RemoteMobileDriverFactory.java | dunzoit/ekam | f783dd92ec101596b6410f7840c355672a26f838 | [
"MIT"
] | 1 | 2021-09-14T08:06:20.000Z | 2021-09-14T08:06:20.000Z | 38.571429 | 90 | 0.767407 | 1,000,034 | package com.testvagrant.ekam.mobile.remote;
import com.testvagrant.ekam.devicemanager.models.TargetDetails;
import com.testvagrant.ekam.mobile.configparser.MobileConfigParser;
import org.apache.commons.lang3.tuple.Triple;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.URL;
import static com.testvagrant.ekam.commons.remote.constants.Hub.*;
import static com.testvagrant.ekam.logger.EkamLogger.ekamLogger;
public class RemoteMobileDriverFactory {
public static Triple<URL, DesiredCapabilities, TargetDetails> remoteMobileDriverFactory(
MobileConfigParser mobileConfigParser) {
String hub = mobileConfigParser.getMobileConfig().getHub();
ekamLogger().info("Creating remote mobile driver for {}", hub);
switch (hub) {
case BROWSERSTACK:
return new BrowserStackDriver(mobileConfigParser).buildRemoteMobileConfig();
case P_CLOUDY:
return new PCloudyDriver(mobileConfigParser).buildRemoteMobileConfig();
case QUALITY_KIOSK:
return new QualityKioskDriver(mobileConfigParser).buildRemoteMobileConfig();
case PERFECTO:
return new PerfectoDriver(mobileConfigParser).buildRemoteMobileConfig();
case KOBITON:
case SAUCE_LABS:
default:
throw new UnsupportedOperationException(String.format("'%s' not supported", hub));
}
}
}
|
923cbc50399869bd332979fc126f464e64b83dbe | 10,035 | java | Java | guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LinkedListMultimapTest.java | yf0994/guava-libraries | 1c5554dedb0924689285a34489ec1d6b57d076e9 | [
"Apache-2.0"
] | 3 | 2017-09-12T08:41:13.000Z | 2021-12-07T03:00:15.000Z | guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LinkedListMultimapTest.java | yf0994/guava-libraries | 1c5554dedb0924689285a34489ec1d6b57d076e9 | [
"Apache-2.0"
] | null | null | null | guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LinkedListMultimapTest.java | yf0994/guava-libraries | 1c5554dedb0924689285a34489ec1d6b57d076e9 | [
"Apache-2.0"
] | 1 | 2019-11-26T09:18:15.000Z | 2019-11-26T09:18:15.000Z | 32.794118 | 87 | 0.640159 | 1,000,035 | /*
* Copyright (C) 2007 The Guava 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 com.google.common.collect;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.testing.EqualsTester;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
/**
* Tests for {@code LinkedListMultimap}.
*
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
public class LinkedListMultimapTest extends TestCase {
protected LinkedListMultimap<String, Integer> create() {
return LinkedListMultimap.create();
}
/**
* Confirm that get() returns a List that doesn't implement RandomAccess.
*/
public void testGetRandomAccess() {
Multimap<String, Integer> multimap = create();
multimap.put("foo", 1);
multimap.put("foo", 3);
assertFalse(multimap.get("foo") instanceof RandomAccess);
assertFalse(multimap.get("bar") instanceof RandomAccess);
}
/**
* Confirm that removeAll() returns a List that implements RandomAccess, even
* though get() doesn't.
*/
public void testRemoveAllRandomAccess() {
Multimap<String, Integer> multimap = create();
multimap.put("foo", 1);
multimap.put("foo", 3);
assertTrue(multimap.removeAll("foo") instanceof RandomAccess);
assertTrue(multimap.removeAll("bar") instanceof RandomAccess);
}
/**
* Confirm that replaceValues() returns a List that implements RandomAccess,
* even though get() doesn't.
*/
public void testReplaceValuesRandomAccess() {
Multimap<String, Integer> multimap = create();
multimap.put("foo", 1);
multimap.put("foo", 3);
assertTrue(multimap.replaceValues("foo", Arrays.asList(2, 4))
instanceof RandomAccess);
assertTrue(multimap.replaceValues("bar", Arrays.asList(2, 4))
instanceof RandomAccess);
}
public void testCreateFromMultimap() {
Multimap<String, Integer> multimap = LinkedListMultimap.create();
multimap.put("foo", 1);
multimap.put("bar", 3);
multimap.put("foo", 2);
LinkedListMultimap<String, Integer> copy =
LinkedListMultimap.create(multimap);
assertEquals(multimap, copy);
assertThat(copy.entries()).containsExactlyElementsIn(multimap.entries()).inOrder();
}
public void testCreateFromSize() {
LinkedListMultimap<String, Integer> multimap
= LinkedListMultimap.create(20);
multimap.put("foo", 1);
multimap.put("bar", 2);
multimap.put("foo", 3);
assertEquals(ImmutableList.of(1, 3), multimap.get("foo"));
}
public void testCreateFromIllegalSize() {
try {
LinkedListMultimap.create(-20);
fail();
} catch (IllegalArgumentException expected) {}
}
public void testLinkedGetAdd() {
LinkedListMultimap<String, Integer> map = create();
map.put("bar", 1);
Collection<Integer> foos = map.get("foo");
foos.add(2);
foos.add(3);
map.put("bar", 4);
map.put("foo", 5);
assertEquals("{bar=[1, 4], foo=[2, 3, 5]}", map.toString());
assertEquals("[bar=1, foo=2, foo=3, bar=4, foo=5]",
map.entries().toString());
}
public void testLinkedGetInsert() {
ListMultimap<String, Integer> map = create();
map.put("bar", 1);
List<Integer> foos = map.get("foo");
foos.add(2);
foos.add(0, 3);
map.put("bar", 4);
map.put("foo", 5);
assertEquals("{bar=[1, 4], foo=[3, 2, 5]}", map.toString());
assertEquals("[bar=1, foo=3, foo=2, bar=4, foo=5]",
map.entries().toString());
}
public void testLinkedPutInOrder() {
Multimap<String, Integer> map = create();
map.put("foo", 1);
map.put("bar", 2);
map.put("bar", 3);
assertEquals("{foo=[1], bar=[2, 3]}", map.toString());
assertEquals("[foo=1, bar=2, bar=3]", map.entries().toString());
}
public void testLinkedPutOutOfOrder() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
assertEquals("{bar=[1, 3], foo=[2]}", map.toString());
assertEquals("[bar=1, foo=2, bar=3]", map.entries().toString());
}
public void testLinkedPutAllMultimap() {
Multimap<String, Integer> src = create();
src.put("bar", 1);
src.put("foo", 2);
src.put("bar", 3);
Multimap<String, Integer> dst = create();
dst.putAll(src);
assertEquals("{bar=[1, 3], foo=[2]}", dst.toString());
assertEquals("[bar=1, foo=2, bar=3]", src.entries().toString());
}
public void testLinkedReplaceValues() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
map.put("bar", 4);
assertEquals("{bar=[1, 3, 4], foo=[2]}", map.toString());
map.replaceValues("bar", asList(1, 2));
assertEquals("[bar=1, foo=2, bar=2]", map.entries().toString());
assertEquals("{bar=[1, 2], foo=[2]}", map.toString());
}
public void testLinkedClear() {
ListMultimap<String, Integer> map = create();
map.put("foo", 1);
map.put("foo", 2);
map.put("bar", 3);
List<Integer> foos = map.get("foo");
Collection<Integer> values = map.values();
assertEquals(asList(1, 2), foos);
assertThat(values).containsExactly(1, 2, 3).inOrder();
map.clear();
assertEquals(Collections.emptyList(), foos);
assertThat(values).isEmpty();
assertEquals("[]", map.entries().toString());
assertEquals("{}", map.toString());
}
public void testLinkedKeySet() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
map.put("bar", 4);
assertEquals("[bar, foo]", map.keySet().toString());
map.keySet().remove("bar");
assertEquals("{foo=[2]}", map.toString());
}
public void testLinkedKeys() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
map.put("bar", 4);
assertEquals("[bar=1, foo=2, bar=3, bar=4]",
map.entries().toString());
assertThat(map.keys()).containsExactly("bar", "foo", "bar", "bar").inOrder();
map.keys().remove("bar"); // bar is no longer the first key!
assertEquals("{foo=[2], bar=[3, 4]}", map.toString());
}
public void testLinkedValues() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
map.put("bar", 4);
assertEquals("[1, 2, 3, 4]", map.values().toString());
map.values().remove(2);
assertEquals("{bar=[1, 3, 4]}", map.toString());
}
public void testLinkedEntries() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
Iterator<Map.Entry<String, Integer>> entries = map.entries().iterator();
Map.Entry<String, Integer> entry = entries.next();
assertEquals("bar", entry.getKey());
assertEquals(1, (int) entry.getValue());
entry = entries.next();
assertEquals("foo", entry.getKey());
assertEquals(2, (int) entry.getValue());
entry.setValue(4);
entry = entries.next();
assertEquals("bar", entry.getKey());
assertEquals(3, (int) entry.getValue());
assertFalse(entries.hasNext());
entries.remove();
assertEquals("{bar=[1], foo=[4]}", map.toString());
}
public void testLinkedAsMapEntries() {
Multimap<String, Integer> map = create();
map.put("bar", 1);
map.put("foo", 2);
map.put("bar", 3);
Iterator<Map.Entry<String, Collection<Integer>>> entries
= map.asMap().entrySet().iterator();
Map.Entry<String, Collection<Integer>> entry = entries.next();
assertEquals("bar", entry.getKey());
assertThat(entry.getValue()).containsExactly(1, 3).inOrder();
try {
entry.setValue(Arrays.<Integer>asList());
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {}
entries.remove(); // clear
entry = entries.next();
assertEquals("foo", entry.getKey());
assertThat(entry.getValue()).contains(2);
assertFalse(entries.hasNext());
assertEquals("{foo=[2]}", map.toString());
}
public void testEntriesAfterMultimapUpdate() {
ListMultimap<String, Integer> multimap = create();
multimap.put("foo", 2);
multimap.put("bar", 3);
Collection<Map.Entry<String, Integer>> entries = multimap.entries();
Iterator<Map.Entry<String, Integer>> iterator = entries.iterator();
Map.Entry<String, Integer> entrya = iterator.next();
Map.Entry<String, Integer> entryb = iterator.next();
assertEquals(2, (int) multimap.get("foo").set(0, 4));
assertFalse(multimap.containsEntry("foo", 2));
assertTrue(multimap.containsEntry("foo", 4));
assertTrue(multimap.containsEntry("bar", 3));
assertEquals(4, (int) entrya.getValue());
assertEquals(3, (int) entryb.getValue());
assertTrue(multimap.put("foo", 5));
assertTrue(multimap.containsEntry("foo", 5));
assertTrue(multimap.containsEntry("foo", 4));
assertTrue(multimap.containsEntry("bar", 3));
assertEquals(4, (int) entrya.getValue());
assertEquals(3, (int) entryb.getValue());
}
public void testEquals() {
new EqualsTester()
.addEqualityGroup(
LinkedListMultimap.create(),
LinkedListMultimap.create(),
LinkedListMultimap.create(1))
.testEquals();
}
}
|
923cbc82f72e790d8d2f71e947a7e48494d6829d | 1,251 | java | Java | src/test/java/ug/sparkpl/network/remittance/LiveRemittanceClientTest.java | sparkplug/momoapi-java | 2b117abe1f139d682c5277c81a470b26ea9dd2bc | [
"MIT"
] | 9 | 2019-05-11T17:06:55.000Z | 2021-12-12T21:23:30.000Z | src/test/java/ug/sparkpl/network/remittance/LiveRemittanceClientTest.java | Bulaimu/momoapi-java-1 | 0621e138049098c12e5e9fdded30c5605d846d7c | [
"MIT"
] | 2 | 2019-10-25T09:35:41.000Z | 2019-12-23T19:10:19.000Z | src/test/java/ug/sparkpl/network/remittance/LiveRemittanceClientTest.java | Bulaimu/momoapi-java-1 | 0621e138049098c12e5e9fdded30c5605d846d7c | [
"MIT"
] | 12 | 2019-03-29T10:11:31.000Z | 2021-01-07T06:16:38.000Z | 22.339286 | 68 | 0.708233 | 1,000,036 | package ug.sparkpl.network.remittance;
import java.io.IOException;
import java.util.HashMap;
import ug.sparkpl.momoapi.models.Balance;
import ug.sparkpl.momoapi.network.MomoApiException;
import ug.sparkpl.momoapi.network.RequestOptions;
import ug.sparkpl.momoapi.network.remittances.RemittancesClient;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertNotNull;
public class LiveRemittanceClientTest {
/**
* Test remittance transfer.
*
* @throws IOException when network error
*/
@Test
public void testTransfer() throws IOException {
RequestOptions opts = RequestOptions.builder()
.build();
HashMap<String, String> collMap = new HashMap<String, String>();
collMap.put("amount", "100");
collMap.put("mobile", "0782181656");
collMap.put("externalId", "ext123");
collMap.put("payeeNote", "testNote");
collMap.put("payerMessage", "testMessage");
RemittancesClient client = new RemittancesClient(opts);
try {
String transactionRef = client.transfer(collMap);
assertNotNull(transactionRef);
Balance bl = client.getBalance();
assertNotNull(bl.getBalance());
} catch (MomoApiException e) {
e.printStackTrace();
}
}
}
|
923cbe2f922c86c78b861e994936b9eb57a50b6f | 1,306 | java | Java | src/main/java/in/zapr/druid/druidry/filter/IntervalFilter.java | qiangmao/druidry | ff4958af3b36a2ff14c30afdec4334ef9ce48e74 | [
"Apache-2.0"
] | null | null | null | src/main/java/in/zapr/druid/druidry/filter/IntervalFilter.java | qiangmao/druidry | ff4958af3b36a2ff14c30afdec4334ef9ce48e74 | [
"Apache-2.0"
] | null | null | null | src/main/java/in/zapr/druid/druidry/filter/IntervalFilter.java | qiangmao/druidry | ff4958af3b36a2ff14c30afdec4334ef9ce48e74 | [
"Apache-2.0"
] | null | null | null | 29.681818 | 89 | 0.740429 | 1,000,037 | /*
* Copyright 2018-present Red Brick Lane Marketing Solutions Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package in.zapr.druid.druidry.filter;
import java.util.List;
import in.zapr.druid.druidry.Interval;
import lombok.*;
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class IntervalFilter extends DruidFilter {
private static String INTERVAL_DRUID_FILTER_TYPE = "interval";
private String type;
private String dimension;
private List<Interval> intervals;
public IntervalFilter(@NonNull String dimension, @NonNull List<Interval> intervals) {
this.type = INTERVAL_DRUID_FILTER_TYPE;
this.dimension = dimension;
this.intervals = intervals;
}
// TODO: support for Extraction Function
}
|
923cbe8cdd24d9e77c425eb085b1f56ab3279ed5 | 317 | java | Java | src/main/java/com/hafiz/erp/requisition/core/crud/ICrudRepository.java | shaikhhafiz/requisition-service | b95861b670979ecf997c36f2aa8630a053f54ffe | [
"MIT"
] | null | null | null | src/main/java/com/hafiz/erp/requisition/core/crud/ICrudRepository.java | shaikhhafiz/requisition-service | b95861b670979ecf997c36f2aa8630a053f54ffe | [
"MIT"
] | null | null | null | src/main/java/com/hafiz/erp/requisition/core/crud/ICrudRepository.java | shaikhhafiz/requisition-service | b95861b670979ecf997c36f2aa8630a053f54ffe | [
"MIT"
] | 1 | 2020-09-06T02:07:02.000Z | 2020-09-06T02:07:02.000Z | 28.818182 | 102 | 0.829653 | 1,000,038 | package com.hafiz.erp.requisition.core.crud;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import java.util.UUID;
@NoRepositoryBean
public interface ICrudRepository<T extends BaseEntity, ID extends UUID> extends JpaRepository<T, ID> {
}
|
923cc0cac8c4c90413a985a590bd065f6cfebc74 | 1,709 | java | Java | src/Fox/core/lib/services/AcoustID/LookupByFP/sources/Artist.java | Ssstlis/AudioAnalyze | 7c4c86ec14e5e44c2fc8f54d45931f4b24a375cb | [
"MIT"
] | 1 | 2018-01-19T19:41:30.000Z | 2018-01-19T19:41:30.000Z | src/Fox/core/lib/services/AcoustID/LookupByFP/sources/Artist.java | Ssstlis/AudioAnalyze | 7c4c86ec14e5e44c2fc8f54d45931f4b24a375cb | [
"MIT"
] | null | null | null | src/Fox/core/lib/services/AcoustID/LookupByFP/sources/Artist.java | Ssstlis/AudioAnalyze | 7c4c86ec14e5e44c2fc8f54d45931f4b24a375cb | [
"MIT"
] | 1 | 2018-02-21T15:52:47.000Z | 2018-02-21T15:52:47.000Z | 17.802083 | 64 | 0.513166 | 1,000,039 | package Fox.core.lib.services.AcoustID.LookupByFP.sources;
import java.util.ArrayList;
import java.util.List;
public class Artist
{
private String id;
private String name;
private String joinphrase;
public Artist()
{
}
public Artist(
String id,
String name,
String joinphrase)
{
this.id = id;
this.name = name;
this.joinphrase = joinphrase;
}
public Artist(Artist copy)
{
if (copy != null)
{
this.name = copy.name;
this.id = copy.id;
this.joinphrase = copy.joinphrase;
}
}
public static List<Artist> ArtistListCopy(List<Artist> copy)
{
List<Artist> temp = null;
if (copy != null)
{
temp = new ArrayList<>();
for (Artist elem : copy)
{
temp.add(new Artist(elem));
}
}
return temp;
}
public String getId()
{
return this.id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public boolean hasId()
{
return id != null && id.length() > 0;
}
public boolean hasName()
{
return name != null && name.length() > 0;
}
public String getJoinphrase()
{
return joinphrase;
}
public void setJoinphrase(String joinphrase)
{
this.joinphrase = joinphrase;
}
public boolean hasJoinPhrase()
{
return (joinphrase!=null && !joinphrase.isEmpty());
}
}
|
923cc0cc011f522e7d7d87aa9305736dd259ca2f | 5,462 | java | Java | shuziwuliu/java/src/main/java/com/antgroup/antchain/openapi/shuziwuliu/models/CreateStandardVoucherRequest.java | alipay/antchain-openapi-prod-sdk | f78549e5135d91756093bd88d191ca260b28e083 | [
"MIT"
] | 6 | 2020-06-28T06:40:50.000Z | 2022-02-25T11:02:18.000Z | shuziwuliu/java/src/main/java/com/antgroup/antchain/openapi/shuziwuliu/models/CreateStandardVoucherRequest.java | alipay/antchain-openapi-prod-sdk | f78549e5135d91756093bd88d191ca260b28e083 | [
"MIT"
] | null | null | null | shuziwuliu/java/src/main/java/com/antgroup/antchain/openapi/shuziwuliu/models/CreateStandardVoucherRequest.java | alipay/antchain-openapi-prod-sdk | f78549e5135d91756093bd88d191ca260b28e083 | [
"MIT"
] | 6 | 2020-06-30T09:29:03.000Z | 2022-01-07T10:42:22.000Z | 28.447917 | 142 | 0.674844 | 1,000,040 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.shuziwuliu.models;
import com.aliyun.tea.*;
public class CreateStandardVoucherRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
// 账户是否存在
@NameInMap("exist")
@Validation(required = true)
public Boolean exist;
// 签署方
@NameInMap("voucher_test_one")
@Validation(required = true)
public VoucherTestTwo voucherTestOne;
// 数据标识
@NameInMap("business_code")
@Validation(required = true, maxLength = 10)
public String businessCode;
// 凭证列表_apiTestList
@NameInMap("voucher_test_three")
@Validation(required = true)
public java.util.List<VoucherTestTwo> voucherTestThree;
// 发行时间
@NameInMap("issue_time")
@Validation(required = true, pattern = "\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})")
public String issueTime;
// 凭证列表_voucherList
@NameInMap("voucher_list")
@Validation(required = true)
public java.util.List<String> voucherList;
// 发行金额_Long
@NameInMap("amount_long")
@Validation(required = true, maximum = 10)
public Long amountLong;
// 发行金额_Integer
@NameInMap("amount_int")
@Validation(required = true, maximum = 10)
public Long amountInt;
// 签署方
@NameInMap("voucher_test_two")
@Validation(required = true)
public VoucherTestTwo voucherTestTwo;
// 凭证列表_booleanList
@NameInMap("boolean_list")
@Validation(required = true)
public java.util.List<Boolean> booleanList;
// 凭证列表_dateList
@NameInMap("date_list")
@Validation(required = true)
public java.util.List<String> dateList;
// 资产类型
@NameInMap("asset_type")
@Validation(required = true, maxLength = 10)
public String assetType;
public static CreateStandardVoucherRequest build(java.util.Map<String, ?> map) throws Exception {
CreateStandardVoucherRequest self = new CreateStandardVoucherRequest();
return TeaModel.build(map, self);
}
public CreateStandardVoucherRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public CreateStandardVoucherRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
public CreateStandardVoucherRequest setExist(Boolean exist) {
this.exist = exist;
return this;
}
public Boolean getExist() {
return this.exist;
}
public CreateStandardVoucherRequest setVoucherTestOne(VoucherTestTwo voucherTestOne) {
this.voucherTestOne = voucherTestOne;
return this;
}
public VoucherTestTwo getVoucherTestOne() {
return this.voucherTestOne;
}
public CreateStandardVoucherRequest setBusinessCode(String businessCode) {
this.businessCode = businessCode;
return this;
}
public String getBusinessCode() {
return this.businessCode;
}
public CreateStandardVoucherRequest setVoucherTestThree(java.util.List<VoucherTestTwo> voucherTestThree) {
this.voucherTestThree = voucherTestThree;
return this;
}
public java.util.List<VoucherTestTwo> getVoucherTestThree() {
return this.voucherTestThree;
}
public CreateStandardVoucherRequest setIssueTime(String issueTime) {
this.issueTime = issueTime;
return this;
}
public String getIssueTime() {
return this.issueTime;
}
public CreateStandardVoucherRequest setVoucherList(java.util.List<String> voucherList) {
this.voucherList = voucherList;
return this;
}
public java.util.List<String> getVoucherList() {
return this.voucherList;
}
public CreateStandardVoucherRequest setAmountLong(Long amountLong) {
this.amountLong = amountLong;
return this;
}
public Long getAmountLong() {
return this.amountLong;
}
public CreateStandardVoucherRequest setAmountInt(Long amountInt) {
this.amountInt = amountInt;
return this;
}
public Long getAmountInt() {
return this.amountInt;
}
public CreateStandardVoucherRequest setVoucherTestTwo(VoucherTestTwo voucherTestTwo) {
this.voucherTestTwo = voucherTestTwo;
return this;
}
public VoucherTestTwo getVoucherTestTwo() {
return this.voucherTestTwo;
}
public CreateStandardVoucherRequest setBooleanList(java.util.List<Boolean> booleanList) {
this.booleanList = booleanList;
return this;
}
public java.util.List<Boolean> getBooleanList() {
return this.booleanList;
}
public CreateStandardVoucherRequest setDateList(java.util.List<String> dateList) {
this.dateList = dateList;
return this;
}
public java.util.List<String> getDateList() {
return this.dateList;
}
public CreateStandardVoucherRequest setAssetType(String assetType) {
this.assetType = assetType;
return this;
}
public String getAssetType() {
return this.assetType;
}
}
|
923cc19fe9a617b89760af9c0333231a747743bd | 8,417 | java | Java | src/main/java/net/oneandone/sushi/fs/http/HttpRoot.java | mlhartme/sushi | b2415cac41d65fa81982f9949f26f29b0eb5836f | [
"Apache-2.0"
] | 4 | 2015-09-21T14:50:42.000Z | 2016-07-01T18:11:26.000Z | src/main/java/net/oneandone/sushi/fs/http/HttpRoot.java | mlhartme/sushi | b2415cac41d65fa81982f9949f26f29b0eb5836f | [
"Apache-2.0"
] | 2 | 2015-09-17T07:41:51.000Z | 2015-09-17T10:24:56.000Z | src/main/java/net/oneandone/sushi/fs/http/HttpRoot.java | mlhartme/sushi | b2415cac41d65fa81982f9949f26f29b0eb5836f | [
"Apache-2.0"
] | 4 | 2015-09-16T16:10:27.000Z | 2019-01-23T13:22:30.000Z | 29.953737 | 146 | 0.623025 | 1,000,041 | /*
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.oneandone.sushi.fs.http;
import net.oneandone.sushi.fs.Root;
import net.oneandone.sushi.fs.http.io.AsciiInputStream;
import net.oneandone.sushi.fs.http.io.AsciiOutputStream;
import net.oneandone.sushi.fs.http.model.Header;
import net.oneandone.sushi.fs.http.model.HeaderList;
import net.oneandone.sushi.fs.http.model.ProtocolException;
import net.oneandone.sushi.fs.http.model.Response;
import net.oneandone.sushi.fs.http.model.StatusCode;
import net.oneandone.sushi.io.LineLogger;
import net.oneandone.sushi.io.LoggingAsciiInputStream;
import net.oneandone.sushi.io.LoggingAsciiOutputStream;
import javax.net.SocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URI;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class HttpRoot implements Root<HttpNode> {
private final HttpFilesystem filesystem;
private final String hostname;
private final int port;
private final String protocol;
// configuration
private int soTimeout = 0;
private int connectionTimeout = 0;
private String username = null;
private String password = null;
private String authorization;
private final URI proxy;
private final Boolean dav;
private final Map<String, String> extraHeaders;
private Oauth oauth;
public HttpRoot(HttpFilesystem filesystem, String protocol, String hostname, int port, URI proxy, Boolean dav) {
this.filesystem = filesystem;
this.protocol = protocol;
this.hostname = hostname;
this.port = port;
this.authorization = null;
this.proxy = proxy;
this.dav = dav;
this.extraHeaders = new HashMap<>();
this.oauth = null;
}
public void setOauth(Oauth oauth) {
this.oauth = oauth;
}
public Oauth getOauth() {
return oauth;
}
public void addExtraHeader(String name, String value) {
extraHeaders.put(name, value);
}
public String getProtocol() {
return protocol;
}
public String getHostname() {
return hostname;
}
public int getPort() {
return port;
}
public void setUserInfo(String userinfo) {
int idx;
idx = userinfo.indexOf(':');
if (idx == -1) {
setCredentials(userinfo, "");
} else {
setCredentials(userinfo.substring(0, idx), userinfo.substring(idx + 1));
}
}
public String getUserInfo() {
if (username == null) {
return null;
}
if (password == null) {
return username;
}
return username + ":" + password;
}
public URI getProxy() {
return proxy;
}
//-- configuration
public void setCredentials(String setUsername, String setPassword) {
this.username = setUsername;
this.password = setPassword;
authorization = "Basic " + Base64.getEncoder().encodeToString(filesystem.getWorld().getSettings().bytes(setUsername + ":" + setPassword));
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int timeout) {
connectionTimeout = timeout;
}
public int getSoTimeout() {
return soTimeout;
}
public void setSoTimeout(final int timeout) {
soTimeout = timeout;
}
public HttpFilesystem getFilesystem() {
return filesystem;
}
public String getId() {
// TODO: credentials?
return "//" + hostname + (port == 80 ? "" : ":" + port) + "/";
}
public HttpNode node(String path, String encodedQuery) {
return new HttpNode(this, path, encodedQuery, false, dav);
}
private final List<HttpConnection> pool = new ArrayList<>();
private int allocated = 0;
public synchronized HttpConnection allocate() throws IOException {
int size;
allocated++;
size = pool.size();
if (size > 0) {
return pool.remove(size - 1);
} else {
return connect();
}
}
public synchronized void free(HttpConnection connection) {
if (allocated == 0) {
throw new IllegalStateException();
}
allocated--;
if (connection.isOpen() && pool.size() < 10) {
pool.add(connection);
}
}
public synchronized int getAllocated() {
return allocated;
}
public HttpConnection connect() throws IOException {
String connectProtocol;
String connectHostname;
int connectPort;
Socket socket;
int buffersize;
InputStream input;
OutputStream output;
AsciiOutputStream aOut;
AsciiInputStream aIn;
Response response;
SocketFactory factory;
if (proxy != null) {
connectProtocol = proxy.getScheme();
connectHostname = proxy.getHost();
connectPort = proxy.getPort();
} else {
connectProtocol = protocol;
connectHostname = hostname;
connectPort = port;
}
factory = filesystem.getSocketFactorySelector().apply(connectProtocol, connectHostname);
if (factory != null) {
socket = factory.createSocket(connectHostname, connectPort);
} else {
socket = new Socket(connectHostname, connectPort);
}
socket.setTcpNoDelay(true);
socket.setSoTimeout(soTimeout);
buffersize = Math.max(socket.getReceiveBufferSize(), 1024);
input = socket.getInputStream();
output = socket.getOutputStream();
if (HttpFilesystem.WIRE.isLoggable(Level.FINE)) {
input = new LoggingAsciiInputStream(input, new LineLogger(HttpFilesystem.WIRE, "<<< "));
output = new LoggingAsciiOutputStream(output, new LineLogger(HttpFilesystem.WIRE, ">>> "));
}
aIn = new AsciiInputStream(input, buffersize);
aOut = new AsciiOutputStream(output, buffersize);
if (proxy != null) {
// TODO: real method
// https://www.ietf.org/rfc/rfc2817.txt
aOut.writeRequestLine("CONNECT", hostname + ":" + port);
aOut.writeAsciiLn();
aOut.flush();
response = Response.parse(null, aIn);
if (response.getStatusLine().code != StatusCode.OK) {
throw new ProtocolException("connect failed: " + response.getStatusLine());
}
}
return new HttpConnection(socket, aIn, aOut);
}
public void addDefaultHeader(HeaderList headerList) {
headerList.add(Header.HOST, hostname);
if (authorization != null) {
headerList.add("Authorization", authorization);
}
headerList.add("Expires", "0");
headerList.add("Pragma", "no-cache");
headerList.add("Cache-control", "no-cache");
headerList.add("Cache-store", "no-store");
headerList.add("User-Agent", "Sushi Http");
for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
headerList.add(entry.getKey(), entry.getValue());
}
}
//--
@Override
public String toString() {
return getProtocol() + "://" + getHostname() + ":" + getPort();
}
@Override
public boolean equals(Object obj) {
HttpRoot root;
if (obj instanceof HttpRoot) {
root = (HttpRoot) obj;
return filesystem == root.filesystem /* TODO params etc */;
}
return false;
}
@Override
public int hashCode() {
return hostname.hashCode();
}
}
|
923cc20ea7efa3a6b1ae59f8acc3ee866c70aa58 | 1,675 | java | Java | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201605/ReportServiceInterfacegetReportJobStatus.java | fernhtls/googleads-java-lib | a330df0799de8d8de0dcdddf4c317d6b0cd2fe10 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201605/ReportServiceInterfacegetReportJobStatus.java | fernhtls/googleads-java-lib | a330df0799de8d8de0dcdddf4c317d6b0cd2fe10 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201605/ReportServiceInterfacegetReportJobStatus.java | fernhtls/googleads-java-lib | a330df0799de8d8de0dcdddf4c317d6b0cd2fe10 | [
"Apache-2.0"
] | null | null | null | 24.275362 | 105 | 0.622687 | 1,000,042 |
package com.google.api.ads.dfp.jaxws.v201605;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Returns the {@link ReportJobStatus} of the report job with the specified ID.
*
*
* <p>Java class for getReportJobStatus element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getReportJobStatus">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="reportJobId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"reportJobId"
})
@XmlRootElement(name = "getReportJobStatus")
public class ReportServiceInterfacegetReportJobStatus {
protected Long reportJobId;
/**
* Gets the value of the reportJobId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getReportJobId() {
return reportJobId;
}
/**
* Sets the value of the reportJobId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setReportJobId(Long value) {
this.reportJobId = value;
}
}
|
923cc4c5a4bc024e8dcb103890cde438b450d503 | 351 | java | Java | src/test/java/com/example/anguisfragilis/AnguisfragilisApplicationTests.java | adamberntsson/AnguisFragilis | ad957ad81421e2cdec9dc39fdb0626d8a16984f5 | [
"MIT"
] | null | null | null | src/test/java/com/example/anguisfragilis/AnguisfragilisApplicationTests.java | adamberntsson/AnguisFragilis | ad957ad81421e2cdec9dc39fdb0626d8a16984f5 | [
"MIT"
] | null | null | null | src/test/java/com/example/anguisfragilis/AnguisfragilisApplicationTests.java | adamberntsson/AnguisFragilis | ad957ad81421e2cdec9dc39fdb0626d8a16984f5 | [
"MIT"
] | null | null | null | 20.647059 | 60 | 0.817664 | 1,000,043 | package com.example.anguisfragilis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnguisfragilisApplicationTests {
@Test
public void contextLoads() {
}
}
|
923cc71a15df7c438acff1a5e0e95a8ba6bb411f | 651 | java | Java | src/main/java/net/defekt/mc/chatclient/protocol/data/ItemInfo.java | qiuzilu/Another-Minecraft-Chat-Client | 903f2d3e30e84dced84497f5ed54444524f46a0b | [
"Apache-2.0"
] | 61 | 2021-04-08T12:02:00.000Z | 2022-03-29T18:05:07.000Z | src/main/java/net/defekt/mc/chatclient/protocol/data/ItemInfo.java | codingwatching/Another-Minecraft-Chat-Client | 5671412dcebf7ef0f73212e6a315405e7e32f3c5 | [
"Apache-2.0"
] | 9 | 2021-07-25T23:56:07.000Z | 2022-03-28T21:28:16.000Z | src/main/java/net/defekt/mc/chatclient/protocol/data/ItemInfo.java | codingwatching/Another-Minecraft-Chat-Client | 5671412dcebf7ef0f73212e6a315405e7e32f3c5 | [
"Apache-2.0"
] | 8 | 2021-04-25T05:06:15.000Z | 2022-02-24T16:21:55.000Z | 15.5 | 51 | 0.642089 | 1,000,044 | package net.defekt.mc.chatclient.protocol.data;
/**
* Class encapsulating a item name info
*
* @author Defective4
*
*/
public class ItemInfo {
private final String name, fileName;
/**
* Constructs new item info object
*
* @param name item name
* @param fileName item's internal name
*/
protected ItemInfo(String name, String fileName) {
this.name = name;
this.fileName = fileName;
}
/**
* Get item's name
*
* @return item name
*/
public String getName() {
return name;
}
/**
* Get item's internal name
*
* @return item's internal name
*/
public String getFileName() {
return fileName;
}
}
|
923cc73a245e0fc3904d20b033e1d6c3a4f67aa2 | 736 | java | Java | com.github.jmodel.adapter.api/src/main/java/com/github/jmodel/adapter/api/persistence/PersisterAdapter.java | jmodel/adapter | b6c77dc5c5103b103b5410d144ea78e2ec642e76 | [
"Apache-2.0"
] | null | null | null | com.github.jmodel.adapter.api/src/main/java/com/github/jmodel/adapter/api/persistence/PersisterAdapter.java | jmodel/adapter | b6c77dc5c5103b103b5410d144ea78e2ec642e76 | [
"Apache-2.0"
] | null | null | null | com.github.jmodel.adapter.api/src/main/java/com/github/jmodel/adapter/api/persistence/PersisterAdapter.java | jmodel/adapter | b6c77dc5c5103b103b5410d144ea78e2ec642e76 | [
"Apache-2.0"
] | null | null | null | 25.413793 | 112 | 0.717775 | 1,000,045 | package com.github.jmodel.adapter.api.persistence;
import com.github.jmodel.adapter.AdapterException;
import com.github.jmodel.adapter.AdapterTerms;
import com.github.jmodel.adapter.api.Adapter;
import com.github.jmodel.adapter.spi.Term;
/**
* Persister adapter
*
* @author lyhxr@example.com
*
*/
public abstract class PersisterAdapter extends Adapter {
@Override
public Term getItemTerm() {
return tfs.getTerm(AdapterTerms.PERSISTER_ADAPTER);
}
//
public abstract <S, T> Long insert(S session, Action<?, ?, ?> action, String json, Class<T> clz)
throws AdapterException;
public abstract <S, T> Long insertObject(S session, Action<?, ?, ?> action, T object) throws AdapterException;
}
|
923cc974f4c04774c5443df434d01b6d117e1f6b | 3,056 | java | Java | src/mysql-connector-java-3.1.14/mysql-connector-java-3.1.14/src/testsuite/simple/NumbersTest.java | NaisilaPuka/GWAG_V13.0 | 3de207b950fb51c7ac7a882dafffd15276dc2ad0 | [
"MIT"
] | 4 | 2018-10-12T20:32:04.000Z | 2019-04-19T17:34:34.000Z | src/mysql-connector-java-3.1.14/mysql-connector-java-3.1.14/src/testsuite/simple/NumbersTest.java | NaisilaPuka/GWAG_V13.0 | 3de207b950fb51c7ac7a882dafffd15276dc2ad0 | [
"MIT"
] | null | null | null | src/mysql-connector-java-3.1.14/mysql-connector-java-3.1.14/src/testsuite/simple/NumbersTest.java | NaisilaPuka/GWAG_V13.0 | 3de207b950fb51c7ac7a882dafffd15276dc2ad0 | [
"MIT"
] | 1 | 2019-11-16T00:06:37.000Z | 2019-11-16T00:06:37.000Z | 25.898305 | 103 | 0.650196 | 1,000,046 | /*
Copyright (C) 2002-2004 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
software distribution.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package testsuite.simple;
import java.sql.SQLException;
import testsuite.BaseTestCase;
/**
*
* @author Mark Matthews
* @version $Id: NumbersTest.java 5313 2006-05-30 17:59:29Z mmatthews $
*/
public class NumbersTest extends BaseTestCase {
// ~ Static fields/initializers
// ---------------------------------------------
private static final long TEST_BIGINT_VALUE = 6147483647L;
// ~ Constructors
// -----------------------------------------------------------
/**
* Creates a new NumbersTest object.
*
* @param name
* DOCUMENT ME!
*/
public NumbersTest(String name) {
super(name);
}
// ~ Methods
// ----------------------------------------------------------------
/**
* Runs all test cases in this test suite
*
* @param args
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(NumbersTest.class);
}
/**
* DOCUMENT ME!
*
* @throws Exception
* DOCUMENT ME!
*/
public void setUp() throws Exception {
super.setUp();
createTestTable();
}
/**
* DOCUMENT ME!
*
* @throws SQLException
* DOCUMENT ME!
*/
public void testNumbers() throws SQLException {
this.rs = this.stmt.executeQuery("SELECT * from number_test");
while (this.rs.next()) {
long minBigInt = this.rs.getLong(1);
long maxBigInt = this.rs.getLong(2);
long testBigInt = this.rs.getLong(3);
assertTrue("Minimum bigint not stored correctly",
(minBigInt == Long.MIN_VALUE));
assertTrue("Maximum bigint not stored correctly",
(maxBigInt == Long.MAX_VALUE));
assertTrue("Test bigint not stored correctly",
(TEST_BIGINT_VALUE == testBigInt));
}
}
private void createTestTable() throws SQLException {
try {
this.stmt.executeUpdate("DROP TABLE number_test");
} catch (SQLException sqlEx) {
;
}
this.stmt
.executeUpdate("CREATE TABLE number_test (minBigInt bigint, maxBigInt bigint, testBigInt bigint)");
this.stmt
.executeUpdate("INSERT INTO number_test (minBigInt,maxBigInt,testBigInt) values ("
+ Long.MIN_VALUE
+ ","
+ Long.MAX_VALUE
+ ","
+ TEST_BIGINT_VALUE + ")");
}
}
|
923cc9bad54c955edc8004efc0976ae4b7b0a32f | 525 | java | Java | Chapter24/java/PhysicsEngine.java | vmistler/Learning-Java-by-Building-Android-Games-Second-Edition | 92bdeefba7e423a06eeeda31e5b1e324e590b6c8 | [
"MIT"
] | 41 | 2018-11-26T21:10:21.000Z | 2022-03-30T17:01:55.000Z | Chapter24/java/PhysicsEngine.java | clerdson/Learning-Java-by-Building-Android-Games-Second-Edition | 92bdeefba7e423a06eeeda31e5b1e324e590b6c8 | [
"MIT"
] | null | null | null | Chapter24/java/PhysicsEngine.java | clerdson/Learning-Java-by-Building-Android-Games-Second-Edition | 92bdeefba7e423a06eeeda31e5b1e324e590b6c8 | [
"MIT"
] | 56 | 2018-09-16T05:47:25.000Z | 2022-02-16T00:30:23.000Z | 25 | 80 | 0.617143 | 1,000,047 | package com.gamecodeschool.c24platformer;
import java.util.ArrayList;
class PhysicsEngine {
void update(long fps, ArrayList<GameObject> objects, GameState gs) {
for (GameObject object : objects) {
object.update(fps,
objects.get(LevelManager.PLAYER_INDEX)
.getTransform());
}
detectCollisions(gs, objects);
}
private void detectCollisions(GameState gs, ArrayList<GameObject> objects) {
// More code here soon
}
}
|
923ccaa9185bbd4d39c38612f9dc3a27a52a6b46 | 1,676 | java | Java | src/main/java/com/logo/data/repository/ReResourceRep.java | logobs/resource-editor | 83e2ca3125303b9334a3b0409a8a14dff0f3899f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/logo/data/repository/ReResourceRep.java | logobs/resource-editor | 83e2ca3125303b9334a3b0409a8a14dff0f3899f | [
"Apache-2.0"
] | 10 | 2018-11-27T12:14:03.000Z | 2018-12-21T12:06:03.000Z | src/main/java/com/logo/data/repository/ReResourceRep.java | logobs/resource-editor | 83e2ca3125303b9334a3b0409a8a14dff0f3899f | [
"Apache-2.0"
] | null | null | null | 44.105263 | 204 | 0.7679 | 1,000,048 | package com.logo.data.repository;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.logo.data.entity.ReResource;
import com.logo.util.QueryConstants;
@Component
@Scope("prototype")
@Transactional(readOnly = true)
public interface ReResourceRep extends JpaRepository<ReResource, Long> {
@Query(value = "select * from RE_RESOURCES with(nolock) where ID = :ref", nativeQuery = true)
ReResource findByid(@Param("ref") Integer ref);
@Query(value = "select TOP 1 * from RE_RESOURCES with(nolock) where RESOURCENR = :resourceNr AND RESOURCEGROUP = :resourcegroup", nativeQuery = true)
ReResource findByresourceNr(@Param("resourceNr") Integer resourceNr, @Param("resourcegroup") String resourcegroup);
@Query(value = "select TOP 10 LTRIM(CONCAT(RESOURCEGROUP,'->',RESOURCENR)) from RE_RESOURCES with(nolock) where STR(RESOURCENR) LIKE CONCAT('%',:resourceNr,'%') ORDER BY RESOURCENR", nativeQuery = true)
List<String> findByresourceNrLike(@Param("resourceNr") Integer resourceNr);
@Query(value = "select max(RESOURCENR) from RE_RESOURCES with(nolock)", nativeQuery = true)
Integer getMaxResourceNr();
@Query(value = QueryConstants.RESGROUPCOUNTQUERY, nativeQuery = true)
<T> List<T> getResGroupCount();
@Query(value = QueryConstants.LANGCOUNTQUERY, nativeQuery = true)
<T> List<T> getResLangCount();
} |
923ccadb05beff064d9a44305556e63000ea551d | 174 | java | Java | AliLiveSDK4.0.2_Demo_Android/app/src/main/java/com/alilive/alilivesdk_demo/listener/OnItemFuncClickListener.java | aliyunvideo/Queen_SDK_Android | e46e32e16f8a6ecf3746a5c397a6a1f36189e93c | [
"Apache-2.0"
] | 2 | 2021-07-06T03:32:25.000Z | 2021-12-17T02:24:16.000Z | AliLiveSDK4.0.2_Demo_Android/app/src/main/java/com/alilive/alilivesdk_demo/listener/OnItemFuncClickListener.java | aliyunvideo/Queen_SDK_Android | e46e32e16f8a6ecf3746a5c397a6a1f36189e93c | [
"Apache-2.0"
] | null | null | null | AliLiveSDK4.0.2_Demo_Android/app/src/main/java/com/alilive/alilivesdk_demo/listener/OnItemFuncClickListener.java | aliyunvideo/Queen_SDK_Android | e46e32e16f8a6ecf3746a5c397a6a1f36189e93c | [
"Apache-2.0"
] | 1 | 2022-03-31T09:07:26.000Z | 2022-03-31T09:07:26.000Z | 19.333333 | 45 | 0.724138 | 1,000,049 | package com.alilive.alilivesdk_demo.listener;
/**
* 功能模块点击click
* @param <T>
*/
public interface OnItemFuncClickListener<T> {
void onItemFuncClick(T bean, int pos);
} |
923ccb1ddeb1a06cd2728f48a8a16d0ea8e14257 | 522 | java | Java | src/main/java/io/dummymaker/annotation/simple/GenBoolean.java | GoodforGod/dummymaker | 190625c85deea185d41d64a13532cd4c9c8f6708 | [
"MIT"
] | 12 | 2017-06-08T10:58:30.000Z | 2021-08-31T18:04:27.000Z | src/main/java/io/dummymaker/annotation/simple/GenBoolean.java | GoodforGod/dummymaker | 190625c85deea185d41d64a13532cd4c9c8f6708 | [
"MIT"
] | 28 | 2018-03-10T14:59:17.000Z | 2022-01-09T13:35:05.000Z | src/main/java/io/dummymaker/annotation/simple/GenBoolean.java | GoodforGod/dummymaker | 190625c85deea185d41d64a13532cd4c9c8f6708 | [
"MIT"
] | 4 | 2018-03-08T22:24:18.000Z | 2021-08-31T00:36:43.000Z | 24.857143 | 55 | 0.806513 | 1,000,050 | package io.dummymaker.annotation.simple;
import io.dummymaker.annotation.core.PrimeGen;
import io.dummymaker.generator.simple.BooleanGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author GoodforGod
* @see BooleanGenerator
* @since 21.02.2018
*/
@PrimeGen(BooleanGenerator.class)
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface GenBoolean {
}
|
923cccb7f958325ed6702491d72e0472a636db11 | 7,960 | java | Java | main/java/application/MyBenchmark.java | EazyRob97/-A-Song-of-Ice-and-Fire-Game-of-Thrones-Route-Finder | 71d89c1ab7a0f17019f7206b20f8b5e459b1760c | [
"MIT"
] | 1 | 2020-09-07T19:43:12.000Z | 2020-09-07T19:43:12.000Z | main/java/application/MyBenchmark.java | EazyRob97/-A-Song-of-Ice-and-Fire-Game-of-Thrones-Route-Finder | 71d89c1ab7a0f17019f7206b20f8b5e459b1760c | [
"MIT"
] | null | null | null | main/java/application/MyBenchmark.java | EazyRob97/-A-Song-of-Ice-and-Fire-Game-of-Thrones-Route-Finder | 71d89c1ab7a0f17019f7206b20f8b5e459b1760c | [
"MIT"
] | null | null | null | 36.181818 | 137 | 0.689698 | 1,000,051 | /*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package application;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.Main;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.RunnerException;
@Measurement(iterations = 5,time=1)
@Warmup(iterations = 5,time=1)
@Fork(value=1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MyBenchmark {
private City myCity [] = new City[10];
@SuppressWarnings("unchecked")
private Node<City> nodeList [] = new Node[10];
@Setup
public void initilize() {
City a = new City("Castle Black", 963.635818309064, 530.110264371092);
City b = new City("The Dreadfort", 1026.68305627889, 808.213014253298);
City c = new City("Winterfell",820,850);
City d = new City("Barrow Town", 670.564197559144, 1027.94592708038);
City e = new City("White Harbor",930,1050);
City f = new City("Moat Cailin",820,1100);
City g = new City("The Twins",790,1320);
City h = new City("The Eyrie",1040,1390);
City i = new City("Riverrun",750,1490);
City j = new City("Harrenhal", 910.50243570366, 1538.13039134556);
myCity[0] = a;
myCity[1] = b;
myCity[2] = c;
myCity[3] = d;
myCity[4] = e;
myCity[5] = f;
myCity[6] = g;
myCity[7] = h;
myCity[8] = i;
myCity[9] = i;
Node<City> a1 = new Node<>(a);
Node<City> b1 = new Node<>(b);
Node<City> c1 = new Node<>(c);
Node<City> d1 = new Node<>(d);
Node<City> e1 = new Node<>(e);
Node<City> f1 = new Node<>(f);
Node<City> g1 = new Node<>(g);
Node<City> h1 = new Node<>(h);
Node<City> i1 = new Node<>(i);
nodeList[0] = a1;
nodeList[1] = b1;
nodeList[2] = c1;
nodeList[3] = d1;
nodeList[4] = e1;
nodeList[5] = f1;
nodeList[6] = g1;
nodeList[7] = h1;
nodeList[8] = i1;
nodeList[9] = i1;
}
public static void main(String[]args) throws RunnerException, IOException{
Main.main(args);
}
public static List<Node<City>> findPathDepthFirst(Node<City> from, List<Node<City>> encountered, City lookingfor){
List<Node<City>> result;
if(from.node.equals(lookingfor)) { //Found it
result=new ArrayList<>(); //Create new list to store the path info (any List implementation could be used)
result.add(from); //Add the current node as the only/last entry in the path list
return result; //Return the path list
}
if(encountered==null)
encountered=new ArrayList<>(); //First node so create new (empty) encountered list
encountered.add(from);
for(Edge ed : from.adjList) {
if(!encountered.contains(ed.destNode)) {
result=findPathDepthFirst(ed.destNode,encountered,lookingfor);
if(result!=null) { //Result of the last recursive call contains a path to the solution node
result.add(0,from); //Add the current node to the front of the path list
return result; //Return the path list
}
}
}
return null;
}
@Benchmark
public void findingPathDepthFirst() {
Node<City> n = new Node<City>();
City c = new City("Harrenhal", 910.50243570366, 1538.13039134556);
for(int i= 0;i<nodeList.length;i++) {
n = nodeList[0];
}
List<Node<City>> path = findPathDepthFirst(n,null,c);
if( path != null) {
for(Node<City> route : path) {
//drawPath(d,path,s);
System.out.println(route.node.getCityName() + " ->");
}
}
}
public static void traverseGraphDepthFirst(Node<City> from, List<Node<City>> encountered ){
System.out.println(from.node.cityName);
if(encountered==null) encountered=new ArrayList<>(); //First node so create new (empty) encountered list
encountered.add(from);
for(Node<City> adjNode : encountered)
if(!encountered.contains(adjNode)) traverseGraphDepthFirst(adjNode, encountered );
}
/*
* Testing for access every node object that is a city attribute stored in ArrayList and performing some operations like printing them.
*/
//=============BENCHMARKING FOR TRAVERSINGGRAPH TO STILL WRITE\
/*
*
*/
@Benchmark
public void testFindAllPathsDepthFirst() {
Node<City> nc = new Node<City>();
City n = new City("Harrenhal", 910.50243570366, 1538.13039134556);
List<Node<City>> encountered = null;
for(int i= 0;i<nodeList.length;i++) {
nc = nodeList[0];
}
findAllPathsDepthFirst(nc,encountered,n);
}
public static List<List<Node<City>>> findAllPathsDepthFirst(Node<City> from, List<Node<City>> encountered, City lookingfor){
List<List<Node<City>>> result=null, temp2;
if(from.node.equals(lookingfor)) { //Found it
List<Node<City>> temp=new ArrayList<>(); //Create new single solution path list
temp.add(from); //Add current node to the new single path list
result=new ArrayList<>(); //Create new "list of lists" to store path permutations
result.add(temp); //Add the new single path list to the path permutations list
return result; //Return the path permutations list
}
if(encountered==null) encountered=new ArrayList<>(); //First node so create new (empty) encountered list
encountered.add(from); //Add current node to encountered list
for(Edge ed : from.adjList){
if(!encountered.contains(ed.destNode)) {
temp2=findAllPathsDepthFirst(ed.destNode,new ArrayList<>(encountered),lookingfor); //Use clone of encountered list
//for recursive call!
if(temp2!=null) { //Result of the recursive call contains one or more paths to the solution node
for(List<Node<City>> x : temp2) //For each partial path list returned
x.add(0,from); //Add the current node to the front of each path list
if(result==null) result=temp2; //If this is the first set of solution paths found use it as the result
else result.addAll(temp2); //Otherwise append them to the previously found paths
}
}
}
return result;
}
}
|
923cce2f8f7197210d64947601ed78c33b35dbbd | 14,522 | java | Java | src/main/java/com/pazdev/authserver/model/Profile.java | omahaprogrammer/authserver | 52148f356db044c397d8fc8e9e67f2f94bb05ebd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/pazdev/authserver/model/Profile.java | omahaprogrammer/authserver | 52148f356db044c397d8fc8e9e67f2f94bb05ebd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/pazdev/authserver/model/Profile.java | omahaprogrammer/authserver | 52148f356db044c397d8fc8e9e67f2f94bb05ebd | [
"Apache-2.0"
] | null | null | null | 31.647059 | 283 | 0.651315 | 1,000,052 | /*
* Copyright 2016 Jonathan Paz <kenaa@example.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pazdev.authserver.model;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Jonathan Paz <kenaa@example.com>
*/
@Entity
@Table(name = "profile", uniqueConstraints = {
@UniqueConstraint(columnNames = {"sub"})})
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Profile.findAll", query = "SELECT p FROM Profile p")
, @NamedQuery(name = "Profile.findById", query = "SELECT p FROM Profile p WHERE p.id = :id")
, @NamedQuery(name = "Profile.findBySub", query = "SELECT p FROM Profile p WHERE p.sub = :sub")
, @NamedQuery(name = "Profile.findByPreferredUsername", query = "SELECT p FROM Profile p WHERE p.preferredUsername = :preferredUsername")
, @NamedQuery(name = "Profile.findByWebsite", query = "SELECT p FROM Profile p WHERE p.website = :website")
, @NamedQuery(name = "Profile.findByEmail", query = "SELECT p FROM Profile p WHERE p.email = :email")
, @NamedQuery(name = "Profile.findByEmailVerified", query = "SELECT p FROM Profile p WHERE p.emailVerified = :emailVerified")
, @NamedQuery(name = "Profile.findByGender", query = "SELECT p FROM Profile p WHERE p.gender = :gender")
, @NamedQuery(name = "Profile.findByBirthdate", query = "SELECT p FROM Profile p WHERE p.birthdate = :birthdate")
, @NamedQuery(name = "Profile.findByZoneinfo", query = "SELECT p FROM Profile p WHERE p.zoneinfo = :zoneinfo")
, @NamedQuery(name = "Profile.findByLocale", query = "SELECT p FROM Profile p WHERE p.locale = :locale")
, @NamedQuery(name = "Profile.findByPhoneNumber", query = "SELECT p FROM Profile p WHERE p.phoneNumber = :phoneNumber")
, @NamedQuery(name = "Profile.findByPhoneNumberVerified", query = "SELECT p FROM Profile p WHERE p.phoneNumberVerified = :phoneNumberVerified")
, @NamedQuery(name = "Profile.findByAddressFormatted", query = "SELECT p FROM Profile p WHERE p.addressFormatted = :addressFormatted")
, @NamedQuery(name = "Profile.findByAddressStreetAddress", query = "SELECT p FROM Profile p WHERE p.addressStreetAddress = :addressStreetAddress")
, @NamedQuery(name = "Profile.findByAddressLocality", query = "SELECT p FROM Profile p WHERE p.addressLocality = :addressLocality")
, @NamedQuery(name = "Profile.findByAddressRegion", query = "SELECT p FROM Profile p WHERE p.addressRegion = :addressRegion")
, @NamedQuery(name = "Profile.findByAddressPostalCode", query = "SELECT p FROM Profile p WHERE p.addressPostalCode = :addressPostalCode")
, @NamedQuery(name = "Profile.findByAddressCountry", query = "SELECT p FROM Profile p WHERE p.addressCountry = :addressCountry")
, @NamedQuery(name = "Profile.findByUpdatedAt", query = "SELECT p FROM Profile p WHERE p.updatedAt = :updatedAt")})
public class Profile implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Integer id;
@Basic(optional = false)
@NotNull
@Column(name = "sub", nullable = false)
private String sub;
@Column(name = "profile_name")
private String profileName;
@Column(name = "given_name")
private String givenName;
@Column(name = "family_name")
private String familyName;
@Column(name = "middle_name")
private String middleName;
@Column(name = "nickname")
private String nickname;
@Basic(optional = false)
@NotNull
@Column(name = "preferred_username", nullable = false)
private String preferredUsername;
@Basic(optional = false)
@NotNull
@Lob
@Column(name = "password_bytes", nullable = false)
private byte[] passwordBytes;
@Basic(optional = false)
@NotNull
@Lob
@Column(name = "salt", nullable = false)
private byte[] salt;
@Basic(optional = false)
@NotNull
@Column(name = "rounds")
private int rounds;
@JoinColumn(name = "picture", referencedColumnName = "id")
@ManyToOne(optional = false)
private UploadedContent picture;
@Column(name = "website")
private String website;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Column(name = "email")
private String email;
@Basic(optional = false)
@NotNull
@Column(name = "email_verified", nullable = false)
private boolean emailVerified;
@Column(name = "gender")
private String gender;
@Column(name = "birthdate")
private LocalDate birthdate;
@Column(name = "zoneinfo")
private String zoneinfo;
@Column(name = "locale")
private String locale;
@Column(name = "phone_number")
private String phoneNumber;
@Basic(optional = false)
@NotNull
@Column(name = "phone_number_verified", nullable = false)
private boolean phoneNumberVerified;
@Column(name = "address_formatted")
private String addressFormatted;
@Column(name = "address_street_address")
private String addressStreetAddress;
@Column(name = "address_locality")
private String addressLocality;
@Column(name = "address_region")
private String addressRegion;
@Column(name = "address_postal_code")
private String addressPostalCode;
@Column(name = "address_country")
private String addressCountry;
@Column(name = "updated_at")
private Instant updatedAt;
@OneToMany(mappedBy = "accountId")
private Set<ProfileAttribute> profileAttributeSet;
@OneToMany(mappedBy = "profileId")
private Set<ProfileAddress> profileAddressSet;
@OneToMany(mappedBy = "profileId")
private Set<Client> clientSet;
@OneToMany(mappedBy = "profileId")
private Set<SessionInfo> sessionInfoSet;
public Profile() {
}
public Profile(Integer id) {
this.id = id;
}
public Profile(Integer id, String sub, String preferredUsername, byte[] passwordBytes, byte[] salt, Integer rounds, boolean emailVerified, boolean phoneNumberVerified) {
this.id = id;
this.sub = sub;
this.preferredUsername = preferredUsername;
this.passwordBytes = passwordBytes;
this.salt = salt;
this.rounds = rounds;
this.emailVerified = emailVerified;
this.phoneNumberVerified = phoneNumberVerified;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
public String getPreferredUsername() {
return preferredUsername;
}
public void setPreferredUsername(String preferredUsername) {
this.preferredUsername = preferredUsername;
}
public byte[] getPasswordBytes() {
return passwordBytes;
}
public void setPasswordBytes(byte[] passwordBytes) {
this.passwordBytes = passwordBytes;
}
public byte[] getSalt() {
return salt;
}
public void setSalt(byte[] salt) {
this.salt = salt;
}
public int getRounds() {
return rounds;
}
public void setRounds(int rounds) {
this.rounds = rounds;
}
public UploadedContent getPicture() {
return picture;
}
public void setPicture(UploadedContent picture) {
this.picture = picture;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getEmailVerified() {
return emailVerified;
}
public void setEmailVerified(boolean emailVerified) {
this.emailVerified = emailVerified;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public LocalDate getBirthdate() {
return birthdate;
}
public void setBirthdate(LocalDate birthdate) {
this.birthdate = birthdate;
}
public String getZoneinfo() {
return zoneinfo;
}
public void setZoneinfo(String zoneinfo) {
this.zoneinfo = zoneinfo;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public boolean getPhoneNumberVerified() {
return phoneNumberVerified;
}
public void setPhoneNumberVerified(boolean phoneNumberVerified) {
this.phoneNumberVerified = phoneNumberVerified;
}
public String getAddressFormatted() {
return addressFormatted;
}
public void setAddressFormatted(String addressFormatted) {
this.addressFormatted = addressFormatted;
}
public String getAddressStreetAddress() {
return addressStreetAddress;
}
public void setAddressStreetAddress(String addressStreetAddress) {
this.addressStreetAddress = addressStreetAddress;
}
public String getAddressLocality() {
return addressLocality;
}
public void setAddressLocality(String addressLocality) {
this.addressLocality = addressLocality;
}
public String getAddressRegion() {
return addressRegion;
}
public void setAddressRegion(String addressRegion) {
this.addressRegion = addressRegion;
}
public String getAddressPostalCode() {
return addressPostalCode;
}
public void setAddressPostalCode(String addressPostalCode) {
this.addressPostalCode = addressPostalCode;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Instant updatedAt) {
this.updatedAt = updatedAt;
}
@XmlTransient
public Set<ProfileAttribute> getProfileAttributeSet() {
return profileAttributeSet;
}
public void setProfileAttributeSet(Set<ProfileAttribute> profileAttributeSet) {
this.profileAttributeSet = profileAttributeSet;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Profile)) {
return false;
}
Profile other = (Profile) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
@Override
public String toString() {
return "com.pazdev.authserver.Profile[ id=" + id + " ]";
}
@XmlTransient
public Set<ProfileAddress> getProfileAddressSet() {
return profileAddressSet;
}
public void setProfileAddressSet(Set<ProfileAddress> profileAddressSet) {
this.profileAddressSet = profileAddressSet;
}
@XmlTransient
public Set<Client> getClientSet() {
return clientSet;
}
public void setClientSet(Set<Client> clientSet) {
this.clientSet = clientSet;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@XmlTransient
public Set<SessionInfo> getSessionInfoSet() {
return sessionInfoSet;
}
public void setSessionInfoSet(Set<SessionInfo> sessionInfoSet) {
this.sessionInfoSet = sessionInfoSet;
}
}
|
923ccf13cc9c1c5a64af962ba8d0e94b07af8292 | 5,030 | java | Java | gear-monitor/gear-monitor-core/src/main/java/cn/howardliu/gear/monitor/core/unit/ByteSizeUnit.java | howardliu-cn/my-gear | e81448ed01964b5d6f30cfbf36afd6f7b66c78be | [
"Apache-2.0"
] | 1 | 2018-07-31T11:59:44.000Z | 2018-07-31T11:59:44.000Z | gear-monitor/gear-monitor-core/src/main/java/cn/howardliu/gear/monitor/core/unit/ByteSizeUnit.java | howardliu-cn/my-gear | e81448ed01964b5d6f30cfbf36afd6f7b66c78be | [
"Apache-2.0"
] | 6 | 2020-02-28T01:12:40.000Z | 2021-08-09T20:42:34.000Z | gear-monitor/gear-monitor-core/src/main/java/cn/howardliu/gear/monitor/core/unit/ByteSizeUnit.java | howardliu-cn/my-gear | e81448ed01964b5d6f30cfbf36afd6f7b66c78be | [
"Apache-2.0"
] | 2 | 2017-06-15T08:46:03.000Z | 2018-06-20T05:52:35.000Z | 21.313559 | 94 | 0.46163 | 1,000,053 | package cn.howardliu.gear.monitor.core.unit;
/**
* <br>created at 16-12-27
*
* @author liuxh
* @since 1.0.2
*/
public enum ByteSizeUnit {
BYTES {
@Override
public long toBytes(long size) {
return size;
}
@Override
public long toKB(long size) {
return size >> 10;
}
@Override
public long toMB(long size) {
return size >> 10 >> 10;
}
@Override
public long toGB(long size) {
return size >> 10 >> 10 >> 10;
}
@Override
public long toTB(long size) {
return size >> 10 >> 10 >> 10 >> 10;
}
@Override
public long toPB(long size) {
return size >> 10 >> 10 >> 10 >> 10 >> 10;
}
},
KB {
@Override
public long toBytes(long size) {
return x(size, C1, MAX / C1);
}
@Override
public long toKB(long size) {
return size;
}
@Override
public long toMB(long size) {
return size >> 10;
}
@Override
public long toGB(long size) {
return size >> 10 >> 10;
}
@Override
public long toTB(long size) {
return size >> 10 >> 10 >> 10;
}
@Override
public long toPB(long size) {
return size >> 10 >> 10 >> 10 >> 10;
}
},
MB {
@Override
public long toBytes(long size) {
return x(size, C2, MAX / C2);
}
@Override
public long toKB(long size) {
return x(size, C1, MAX / C1);
}
@Override
public long toMB(long size) {
return size;
}
@Override
public long toGB(long size) {
return size >> 10;
}
@Override
public long toTB(long size) {
return size >> 10 >> 10;
}
@Override
public long toPB(long size) {
return size >> 10 >> 10 >> 10;
}
},
GB {
@Override
public long toBytes(long size) {
return x(size, C3, MAX / C3);
}
@Override
public long toKB(long size) {
return x(size, C2, MAX / C2);
}
@Override
public long toMB(long size) {
return x(size, C1, MAX / C1);
}
@Override
public long toGB(long size) {
return size;
}
@Override
public long toTB(long size) {
return size >> 10;
}
@Override
public long toPB(long size) {
return size >> 10 >> 10;
}
},
TB {
@Override
public long toBytes(long size) {
return x(size, C4, MAX / C4);
}
@Override
public long toKB(long size) {
return x(size, C3, MAX / C3);
}
@Override
public long toMB(long size) {
return x(size, C2, MAX / C2);
}
@Override
public long toGB(long size) {
return x(size, C1, MAX / C1);
}
@Override
public long toTB(long size) {
return size;
}
@Override
public long toPB(long size) {
return size >> 10;
}
},
PB {
@Override
public long toBytes(long size) {
return x(size, C5, MAX / C5);
}
@Override
public long toKB(long size) {
return x(size, C4, MAX / C4);
}
@Override
public long toMB(long size) {
return x(size, C3, MAX / C3);
}
@Override
public long toGB(long size) {
return x(size, C2, MAX / C2);
}
@Override
public long toTB(long size) {
return x(size, C1, MAX / C1);
}
@Override
public long toPB(long size) {
return size;
}
};
static final long C0 = 1L;
static final long C1 = C0 << 10;
static final long C2 = C1 << 10;
static final long C3 = C2 << 10;
static final long C4 = C3 << 10;
static final long C5 = C4 << 10;
static final long MIN = Long.MIN_VALUE;
static final long MAX = Long.MAX_VALUE;
public abstract long toBytes(long size);
public abstract long toKB(long size);
public abstract long toMB(long size);
public abstract long toGB(long size);
public abstract long toTB(long size);
public abstract long toPB(long size);
public static ByteSizeUnit fromId(int id) {
if (id < 0 || id >= values().length) {
throw new IllegalArgumentException("No byte size unit found for id [" + id + "]");
}
return values()[id];
}
static long x(long d, long m, long over) {
if (d > over) {
return MAX;
}
if (d < -over) {
return MIN;
}
return d * m;
}
}
|
923ccfb7822525a298fc36a7aaa16d67d7550a79 | 1,419 | java | Java | order/src/test/java/com/imooc/order/mapper/OrderMasterMapperTest.java | QiaoYingD/sell | 34cc0a5875f1333ca9061f8263ab0372bd41c873 | [
"MIT"
] | null | null | null | order/src/test/java/com/imooc/order/mapper/OrderMasterMapperTest.java | QiaoYingD/sell | 34cc0a5875f1333ca9061f8263ab0372bd41c873 | [
"MIT"
] | null | null | null | order/src/test/java/com/imooc/order/mapper/OrderMasterMapperTest.java | QiaoYingD/sell | 34cc0a5875f1333ca9061f8263ab0372bd41c873 | [
"MIT"
] | null | null | null | 30.847826 | 103 | 0.756166 | 1,000,054 | package com.imooc.order.mapper;
import com.imooc.order.OrderApplicationTests;
import com.imooc.order.enums.OrderStatusEnum;
import com.imooc.order.enums.PayStatusEnum;
import com.imooc.order.model.OrderMasterModel;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
@Component
public class OrderMasterMapperTest extends OrderApplicationTests {
@Autowired
private OrderMasterMapper orderMasterMapper;
@Test
public void save(){
OrderMasterModel orderMasterModel=new OrderMasterModel();
orderMasterModel.setOrderId("2");
orderMasterModel.setBuyerName("zs");
orderMasterModel.setBuyerPhone("123456");
orderMasterModel.setBuyerAddress("中国");
orderMasterModel.setBuyerOpenid("1974218313");
orderMasterModel.setOrderAmount(new BigDecimal(0.02));
orderMasterModel.setOrderStatus(OrderStatusEnum.NEW.getCode());
orderMasterModel.setPayStatus(PayStatusEnum.WAIT.getCode());
orderMasterModel.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
orderMasterMapper.save(orderMasterModel);
}
@Test
public void getList(){
}
} |
923cd02630d23060e1b2f1c229ae78db32b62478 | 2,372 | java | Java | src/main/java/browsers/customs/CustomChrome.java | ReadyUser46/sca_selenium3_framework | c2f55a6f7da170bf32dd8d6891273c8eda56ba0b | [
"Apache-2.0"
] | null | null | null | src/main/java/browsers/customs/CustomChrome.java | ReadyUser46/sca_selenium3_framework | c2f55a6f7da170bf32dd8d6891273c8eda56ba0b | [
"Apache-2.0"
] | null | null | null | src/main/java/browsers/customs/CustomChrome.java | ReadyUser46/sca_selenium3_framework | c2f55a6f7da170bf32dd8d6891273c8eda56ba0b | [
"Apache-2.0"
] | null | null | null | 34.882353 | 102 | 0.730607 | 1,000,055 | package browsers.customs;
import browsers.Browsers;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import java.util.HashMap;
public class CustomChrome extends Browsers {
private static final ChromeOptions chromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
public CustomChrome(String proxyPac, String nodeName, String seleniumVersion, boolean validatePDF) {
super(chromeOptions);
chromeOptions.setCapability("browserName", "chrome");
chromeOptions.setCapability("platform", Platform.LINUX);
proxy.setProxyAutoconfigUrl(proxyPac);
chromeOptions.setCapability(CapabilityType.PROXY, proxy);
if (nodeName.isEmpty()) {
chromeOptions.setCapability("platform", Platform.ANY);
chromeOptions.setCapability("version", "78.0");
} else {
chromeOptions.setCapability("platform", Platform.ANY);
chromeOptions.setCapability("applicationName", nodeName);
chromeOptions.setCapability("version", "78.0_debug");
}
/*download pdf instead of open in default browser viewer pdf*/
if (validatePDF) {
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", "/home/seluser/Downloads/");
chromePrefs.put("plugins.always_open_pdf_externally", true);
chromePrefs.put("plugins.download.prompt_for_download", false);
chromeOptions.setExperimentalOption("prefs", chromePrefs);
chromeOptions.setCapability("applicationName", "zChromeNodePdf30");
chromeOptions.setCapability("version", "78.0_debug_pdf");
}
/*Needed to avoid initial screen 'your connection is not private..'*/
if (seleniumVersion.equals("4")) {
chromeOptions.addArguments("--ignore-ssl-errors=yes");
chromeOptions.addArguments("--ignore-certificate-errors");
}
/*Install extensions when proxypac is different than http://wpad.intrcustom.es/proxysrv.pac
if (!proxyPac.contains("proxysrv")) {
chromeOptions.addExtensions(new File("src/test/resources/Proxy_Auto_Auth_2.0.0.0.crx"));
}*/
}
@Override
public WebDriver getLocalDriver() {
return null;
}
@Override
public String getBrowserName() {
return null;
}
}
|
923cd06dca4df2a2669261dcbbd8bfbcd4e7ec34 | 181 | java | Java | asm-core-plugin/src/main/java/it/sephiroth/android/library/asm/plugin/core/BuildConfig.java | sephiroth74/AndroidDebugLog | 98cc6dc1a8ddc940a94c7872d71ea64a5abdd385 | [
"MIT"
] | null | null | null | asm-core-plugin/src/main/java/it/sephiroth/android/library/asm/plugin/core/BuildConfig.java | sephiroth74/AndroidDebugLog | 98cc6dc1a8ddc940a94c7872d71ea64a5abdd385 | [
"MIT"
] | null | null | null | asm-core-plugin/src/main/java/it/sephiroth/android/library/asm/plugin/core/BuildConfig.java | sephiroth74/AndroidDebugLog | 98cc6dc1a8ddc940a94c7872d71ea64a5abdd385 | [
"MIT"
] | null | null | null | 22.625 | 55 | 0.78453 | 1,000,056 | package it.sephiroth.android.library.asm.plugin.core;
import org.objectweb.asm.Opcodes;
public final class BuildConfig {
public static final int ASM_VERSION = Opcodes.ASM9;
}
|
923cd0ec007a06cb0ae00b22cf171f124d809f95 | 342 | java | Java | java-example/src/test/java/ru/stqa/training/selenium/pages/Page.java | nmochalova/selenium-training-po | 31c526743b034479d6b2c7cd944761ea058578ca | [
"Apache-2.0"
] | 14 | 2017-04-07T10:35:16.000Z | 2020-11-29T04:09:48.000Z | java-example/src/test/java/ru/stqa/training/selenium/pages/Page.java | nmochalova/selenium-training-po | 31c526743b034479d6b2c7cd944761ea058578ca | [
"Apache-2.0"
] | null | null | null | java-example/src/test/java/ru/stqa/training/selenium/pages/Page.java | nmochalova/selenium-training-po | 31c526743b034479d6b2c7cd944761ea058578ca | [
"Apache-2.0"
] | 25 | 2017-04-19T01:39:30.000Z | 2022-03-17T12:41:22.000Z | 21.375 | 52 | 0.716374 | 1,000,057 | package ru.stqa.training.selenium.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Page {
protected WebDriver driver;
protected WebDriverWait wait;
public Page(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, 10);
}
}
|
923cd0f76f7d5166ba923f57b6e2672eaf661ab4 | 1,695 | java | Java | app/src/main/java/wizardpager/model/Page.java | VizLoreLabs/phasmaFoodMobileApp | 111fc89b9abddb6f1c5b547ec15ffda7699748a3 | [
"Apache-1.1"
] | null | null | null | app/src/main/java/wizardpager/model/Page.java | VizLoreLabs/phasmaFoodMobileApp | 111fc89b9abddb6f1c5b547ec15ffda7699748a3 | [
"Apache-1.1"
] | null | null | null | app/src/main/java/wizardpager/model/Page.java | VizLoreLabs/phasmaFoodMobileApp | 111fc89b9abddb6f1c5b547ec15ffda7699748a3 | [
"Apache-1.1"
] | null | null | null | 19.709302 | 81 | 0.715044 | 1,000,058 | package wizardpager.model;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
/**
* Represents a single page in the wizard.
*/
public abstract class Page implements PageTreeNode {
/**
* The key into {@link #getData()} used for wizards with simple (single) values.
*/
public static final String SIMPLE_DATA_KEY = "_";
protected ModelCallbacks mCallbacks;
/**
* Current wizard values/selections.
*/
protected Bundle mData = new Bundle();
protected String mTitle;
protected boolean mRequired = false;
protected String mParentKey;
protected Page(ModelCallbacks callbacks, String title) {
mCallbacks = callbacks;
mTitle = title;
}
public Bundle getData() {
return mData;
}
public String getTitle() {
return mTitle;
}
public boolean isRequired() {
return mRequired;
}
void setParentKey(String parentKey) {
mParentKey = parentKey/* + new Date().getTime()*/;
}
@Override
public Page findByKey(String key) {
return getKey().equals(key) ? this : null;
}
@Override
public void flattenCurrentPageSequence(ArrayList<Page> dest) {
dest.add(this);
}
private static final String TAG = "SMEDIC";
public abstract Fragment createFragment();
public String getKey() {
return (mParentKey != null) ? mParentKey + ":" + mTitle : mTitle;
}
public abstract void getReviewItems(ArrayList<ReviewItem> dest);
public boolean isCompleted() {
return true;
}
public void resetData(Bundle data) {
mData = data;
notifyDataChanged();
}
public void notifyDataChanged() {
mCallbacks.onPageDataChanged(this);
}
public Page setRequired(boolean required) {
mRequired = required;
return this;
}
}
|
923cd1815a4dab0ff17409641eb48e27f041086a | 4,273 | java | Java | src/main/java/com/oxygenxml/git/auth/ResolvingProxyDataFactory.java | alexdinisor98/oxygen-git-plugin | dbe84ec6ab146b7c57b874f4c44b2e77fcd45375 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/oxygenxml/git/auth/ResolvingProxyDataFactory.java | alexdinisor98/oxygen-git-plugin | dbe84ec6ab146b7c57b874f4c44b2e77fcd45375 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/oxygenxml/git/auth/ResolvingProxyDataFactory.java | alexdinisor98/oxygen-git-plugin | dbe84ec6ab146b7c57b874f4c44b2e77fcd45375 | [
"Apache-2.0"
] | null | null | null | 27.928105 | 101 | 0.618301 | 1,000,059 | package com.oxygenxml.git.auth;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.jgit.transport.sshd.ProxyData;
import org.eclipse.jgit.transport.sshd.ProxyDataFactory;
/**
* Obtain {@link ProxyData} to connect through some proxy.
*
* An attempt will be made to resolve the host name into an InetAddress.
*/
public class ResolvingProxyDataFactory implements ProxyDataFactory {
/**
* Logger for logging.
*/
private static final Logger logger = Logger.getLogger(ResolvingProxyDataFactory.class);
/**
* The 'socket' URI scheme.
*/
private static final String SOCKET_URI_SCHEME = "socket";
/**
* org.eclipse.jgit.transport.sshd.ProxyDataFactory.get(InetSocketAddress)
*/
@Override
public ProxyData get(InetSocketAddress remoteAddress) {
ProxyData proxyData = getInternal(remoteAddress);
return newData(proxyData);
}
/**
* Create new proxy data over the given.
*
* @param data PRoxy data.
*
* @return new proxy data or <code>null</code> if the given data is <code>null</code>.
*/
private ProxyData newData(ProxyData data) {
if (data == null) {
return null;
}
Proxy proxy = data.getProxy();
if (proxy.type() == Proxy.Type.DIRECT || !(proxy.address() instanceof InetSocketAddress)) {
return data;
}
InetSocketAddress address = (InetSocketAddress) proxy.address();
char[] password = null;
InetSocketAddress proxyAddress = new InetSocketAddress(address.getHostName(), address.getPort());
try {
password = data.getPassword() == null ? null : data.getPassword();
switch (proxy.type()) {
case HTTP:
proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
return new ProxyData(proxy, data.getUser(), password);
case SOCKS:
proxy = new Proxy(Proxy.Type.SOCKS, proxyAddress);
return new ProxyData(proxy, data.getUser(), password);
default:
return null;
}
} finally {
if (password != null) {
Arrays.fill(password, '\000');
}
}
}
/**
* Just a copy of super.get() that avoids an NPE and creates proper "socket://" URIs
* instead of wrong "socks://" URIs.
*
* @param remoteAddress Remote address.
*
* @return An object containing proxy data or <code>null</code>.
*/
ProxyData getInternal(InetSocketAddress remoteAddress) {
try {
if (logger.isDebugEnabled()) {
logger.debug("Use proxy selector " + ProxySelector.getDefault());
}
List<Proxy> proxies = ProxySelector.getDefault()
.select(new URI(SOCKET_URI_SCHEME,
"//" + remoteAddress.getHostString(), null)); //$NON-NLS-1$
if (logger.isDebugEnabled()) {
logger.debug("Got SOCKS proxies " + proxies);
}
if (proxies == null) {
proxies = new ArrayList<>();
}
ProxyData data = getData(proxies, Proxy.Type.SOCKS);
if (data == null) {
proxies = ProxySelector.getDefault()
.select(new URI(Proxy.Type.HTTP.name(),
"//" + remoteAddress.getHostString(), //$NON-NLS-1$
null));
if (logger.isDebugEnabled()) {
logger.debug("Got HTTP " + proxies);
}
if (proxies == null) {
proxies = new ArrayList<>();
}
data = getData(proxies, Proxy.Type.HTTP);
}
return data;
} catch (URISyntaxException e) {
return null;
}
}
private ProxyData getData(List<Proxy> proxies, Proxy.Type type) {
Proxy proxy = proxies.stream().filter(p -> type == p.type()).findFirst()
.orElse(null);
if (proxy == null) {
return null;
}
SocketAddress address = proxy.address();
if (!(address instanceof InetSocketAddress)) {
return null;
}
switch (type) {
case HTTP:
return new ProxyData(proxy);
case SOCKS:
return new ProxyData(proxy);
default:
return null;
}
}
}
|
923cd3307abe908f0a7097f7a491e642d2493698 | 3,876 | java | Java | ControlBank/app/src/main/java/com/example/controlbank/activity/ListViewActivity.java | 701Szc/MyTools | a7bfdf1737158050b09cfae8824bf4d214fb44fd | [
"Apache-2.0"
] | null | null | null | ControlBank/app/src/main/java/com/example/controlbank/activity/ListViewActivity.java | 701Szc/MyTools | a7bfdf1737158050b09cfae8824bf4d214fb44fd | [
"Apache-2.0"
] | null | null | null | ControlBank/app/src/main/java/com/example/controlbank/activity/ListViewActivity.java | 701Szc/MyTools | a7bfdf1737158050b09cfae8824bf4d214fb44fd | [
"Apache-2.0"
] | null | null | null | 40.8 | 128 | 0.654025 | 1,000,060 | package com.example.controlbank.activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.example.controlbank.R;
import com.example.controlbank.activity.base.BaseActivity;
import com.example.controlbank.activity.detail.AutoScrollViewPageActivity;
import com.example.controlbank.activity.detail.AutoScrollViewPagerActivity;
import com.example.controlbank.activity.detail.ButtonActivity;
import com.example.controlbank.activity.detail.DialogActivity;
import com.example.controlbank.activity.detail.ImageActivity;
import com.example.controlbank.activity.detail.TextActivity;
import com.example.controlbank.activity.detail.VideoPlayActivity;
import com.example.controlbank.activity.detail.ViewPagerActivity;
public class ListViewActivity extends BaseActivity {
private ListView listView;
private String[] data = {"Button","TextView","ImageView","ViewPager","AutoScrollViewPagers","VideoPlay","Dialog"};
private final int BUTTONACTIVITY = 0;
private final int TEXTVIEWACTIVITY = 1;
private final int IMAGEVIEE = 2;
private final int VIEWPAGER = 3;//横向滚动view
private final int AUTOSCROLLVIEWPAGER = 4;//自动横向滚动
private final int VIDEOPLAY = 5;//自动横向滚动
private final int DIALOG = 6;//自动横向滚动
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListViewActivity.this,android.R.layout.simple_list_item_1,data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch(i){
case BUTTONACTIVITY:
Intent intent_btn = new Intent(ListViewActivity.this,ButtonActivity.class);
startActivity(intent_btn);
break;
case TEXTVIEWACTIVITY:
Intent intent_text = new Intent(ListViewActivity.this, TextActivity.class);
startActivity(intent_text);
break;
case IMAGEVIEE:
Intent intent_img = new Intent(ListViewActivity.this, ImageActivity.class);
startActivity(intent_img);
break;
case VIEWPAGER:
Intent intent_viewpager = new Intent(ListViewActivity.this, ViewPagerActivity.class);
startActivity(intent_viewpager);
break;
case AUTOSCROLLVIEWPAGER:
Intent intent_autoViewPager = new Intent(ListViewActivity.this, AutoScrollViewPagerActivity.class);
startActivity(intent_autoViewPager);
break;
case VIDEOPLAY:
Intent intent_VideoPLay = new Intent(ListViewActivity.this, VideoPlayActivity.class);
startActivity(intent_VideoPLay);
break;
case DIALOG:
Intent intent_Dialog = new Intent(ListViewActivity.this, DialogActivity.class);
startActivity(intent_Dialog);
break;
}
}
});
}
}
|
923cd3bec3ae90d4cc3c002d9c019597cba9c7db | 395 | java | Java | src/main/java/se/kth/iv1201/grupp13/recruiterapplication/domain/CompetenceDTO.java | anga13/recruiter-application | b05ae475429313306555cab2d59a9c673a4178e9 | [
"MIT"
] | null | null | null | src/main/java/se/kth/iv1201/grupp13/recruiterapplication/domain/CompetenceDTO.java | anga13/recruiter-application | b05ae475429313306555cab2d59a9c673a4178e9 | [
"MIT"
] | 3 | 2019-02-07T10:38:01.000Z | 2019-02-27T15:12:33.000Z | src/main/java/se/kth/iv1201/grupp13/recruiterapplication/domain/CompetenceDTO.java | anga13/recruiter-application | b05ae475429313306555cab2d59a9c673a4178e9 | [
"MIT"
] | 1 | 2019-03-05T10:58:19.000Z | 2019-03-05T10:58:19.000Z | 20.789474 | 79 | 0.658228 | 1,000,061 | package se.kth.iv1201.grupp13.recruiterapplication.domain;
/**
* Defines all operation that can be performed on an {@link Competence} outside
* the application and domain layers.
*/
public interface CompetenceDTO {
/**
* Returns the competence Id.
*/
public Long getCompetenceId();
/**
* Returns the competence name.
*/
public String getName();
}
|
923cd44bffa76692052f3e0817d138480bca0b5a | 1,520 | java | Java | app/src/main/java/na/nust/fci_app/Publications.java | Ihekandjo/FCI-APP | 1f82d651aed0da0b4b85abac1b477ccd561e4ce2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/na/nust/fci_app/Publications.java | Ihekandjo/FCI-APP | 1f82d651aed0da0b4b85abac1b477ccd561e4ce2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/na/nust/fci_app/Publications.java | Ihekandjo/FCI-APP | 1f82d651aed0da0b4b85abac1b477ccd561e4ce2 | [
"Apache-2.0"
] | null | null | null | 33.043478 | 63 | 0.714474 | 1,000,062 | package na.nust.fci_app;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Publications extends AppCompatActivity {
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_publications);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
webview =(WebView)findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("http://fci.nust.na/?q=publications");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
|
923cd45ea4c57c844320fba3f1771be17ee9f334 | 2,910 | java | Java | jpa/src/main/java/org/example/app/Person.java | OpenLiberty/devfile-stack-samples | 3e97a77f1d694effb84bc3fa02ed7e176afcfad3 | [
"Apache-2.0"
] | null | null | null | jpa/src/main/java/org/example/app/Person.java | OpenLiberty/devfile-stack-samples | 3e97a77f1d694effb84bc3fa02ed7e176afcfad3 | [
"Apache-2.0"
] | 7 | 2020-08-14T20:54:56.000Z | 2021-08-06T15:22:53.000Z | jpa/src/main/java/org/example/app/Person.java | OpenLiberty/devfile-stack-samples | 3e97a77f1d694effb84bc3fa02ed7e176afcfad3 | [
"Apache-2.0"
] | 4 | 2020-08-03T18:59:19.000Z | 2021-02-19T16:31:13.000Z | 26.216216 | 116 | 0.664261 | 1,000,063 | /*
* Copyright (c) 2019, 2021 IBM Corporation and others
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* 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.example.app;
import java.io.Serializable;
import java.util.Objects;
import java.util.Random;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
@Entity
@Table(name = "Person")
@NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p")
@NamedQuery(name = "Person.findPerson", query = "SELECT p FROM Person p WHERE " + "p.name = :name AND p.age = :age")
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private static final Random r = new Random();
@NotNull
@Id
@Column(name = "personId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
@NotNull
@Size(min = 2, max = 50)
@Column(name = "name")
String name;
@NotNull
@PositiveOrZero
@Column(name = "age")
int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setId(long personId) {
this.id = personId;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Person() {
}
public Person(String name, int age) {
this(name, age, null);
}
public Person(String name, int age, Long id) {
this.name = name;
this.age = age;
this.id = id == null ? r.nextLong() : id;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Person))
return false;
Person other = (Person) obj;
return Objects.equals(id, other.id) && Objects.equals(name, other.name) && Objects.equals(age, other.age);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
}
|
923cd4a1113b2826a61d0eed7aecedaeacd50e16 | 407 | java | Java | retrokit/src/main/java/com/theah64/retrokit/utils/APIInterface.java | theapache64/RetroKit | 40b9f560273d9a97c54dc0e17b359bc17f10f450 | [
"Apache-2.0"
] | null | null | null | retrokit/src/main/java/com/theah64/retrokit/utils/APIInterface.java | theapache64/RetroKit | 40b9f560273d9a97c54dc0e17b359bc17f10f450 | [
"Apache-2.0"
] | null | null | null | retrokit/src/main/java/com/theah64/retrokit/utils/APIInterface.java | theapache64/RetroKit | 40b9f560273d9a97c54dc0e17b359bc17f10f450 | [
"Apache-2.0"
] | null | null | null | 18.5 | 76 | 0.783784 | 1,000,064 | package com.theah64.retrokit.utils;
import com.theah64.retrokit.retro.BaseAPIResponse;
import com.theah64.retrokit.api.response.VersionCheckerResponse;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by theapache64 on 12/9/17.
*/
public interface APIInterface {
@GET("get_latest_version_details")
Call<BaseAPIResponse<VersionCheckerResponse>> getVersionCheckResponse();
}
|
923cd4c479416be96bc20419a75a7332e41a3c37 | 431 | java | Java | src/main/java/com/groupdocs/ui/common/entity/web/UploadedDocumentEntity.java | qultoltd/GroupDocs.Annotation-for-Java-Dropwizard | df4205a8ae949ae47dc8698ede8d080f7b0869b6 | [
"MIT"
] | 10 | 2019-04-22T09:58:53.000Z | 2021-12-23T01:09:55.000Z | src/main/java/com/groupdocs/ui/common/entity/web/UploadedDocumentEntity.java | qultoltd/GroupDocs.Annotation-for-Java-Dropwizard | df4205a8ae949ae47dc8698ede8d080f7b0869b6 | [
"MIT"
] | 17 | 2017-01-14T00:43:20.000Z | 2021-12-28T15:31:10.000Z | src/main/java/com/groupdocs/ui/common/entity/web/UploadedDocumentEntity.java | qultoltd/GroupDocs.Annotation-for-Java-Dropwizard | df4205a8ae949ae47dc8698ede8d080f7b0869b6 | [
"MIT"
] | 14 | 2016-09-22T07:18:26.000Z | 2021-11-22T07:28:43.000Z | 15.962963 | 43 | 0.563805 | 1,000,065 | package com.groupdocs.ui.common.entity.web;
/**
* UploadedDocumentEntity
*
* @author Aspose Pty Ltd
*/
public class UploadedDocumentEntity {
private String guid;
/**
* Get guid (file id)
* @return guid
*/
public String getGuid() {
return guid;
}
/**
* Set guid (file id)
* @param guid guid
*/
public void setGuid(String guid) {
this.guid = guid;
}
}
|
923cd4e4812252b7a73d3d3e9fcce560ddd7dca8 | 445 | java | Java | gmall-sms/src/main/java/com/atguigu/gmall/sms/service/HomeAdvService.java | kirinzhuo/gmall | 2e2c13f52ac79547de3098d48d843336a36848d8 | [
"Apache-2.0"
] | null | null | null | gmall-sms/src/main/java/com/atguigu/gmall/sms/service/HomeAdvService.java | kirinzhuo/gmall | 2e2c13f52ac79547de3098d48d843336a36848d8 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:01:53.000Z | 2021-09-20T20:54:20.000Z | gmall-sms/src/main/java/com/atguigu/gmall/sms/service/HomeAdvService.java | kirinzhuo/gmall | 2e2c13f52ac79547de3098d48d843336a36848d8 | [
"Apache-2.0"
] | null | null | null | 21.190476 | 65 | 0.768539 | 1,000,066 | package com.atguigu.gmall.sms.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gmall.sms.entity.HomeAdvEntity;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
/**
* 首页轮播广告
*
* @author kirin
* @email anpch@example.com
* @date 2019-12-02 20:19:58
*/
public interface HomeAdvService extends IService<HomeAdvEntity> {
PageVo queryPage(QueryCondition params);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.