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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1794528be72f1c2406a8a1b377670fd5849d40 | 5,148 | java | Java | test/com/facebook/buck/jvm/java/JavaBinaryTest.java | FightJames/buck | ae2347e05da6f0ef9e0ec21497a654757aca7ad5 | [
"Apache-2.0"
] | 8,027 | 2015-01-02T05:31:44.000Z | 2022-03-31T07:08:09.000Z | test/com/facebook/buck/jvm/java/JavaBinaryTest.java | FightJames/buck | ae2347e05da6f0ef9e0ec21497a654757aca7ad5 | [
"Apache-2.0"
] | 2,355 | 2015-01-01T15:30:53.000Z | 2022-03-30T20:21:16.000Z | test/com/facebook/buck/jvm/java/JavaBinaryTest.java | FightJames/buck | ae2347e05da6f0ef9e0ec21497a654757aca7ad5 | [
"Apache-2.0"
] | 1,280 | 2015-01-09T03:29:04.000Z | 2022-03-30T15:14:14.000Z | 42.545455 | 100 | 0.720668 | 10,039 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.jvm.java;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.model.UnconfiguredTargetConfiguration;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetGraphFactory;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.TestBuildRuleParams;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.Level;
import org.junit.Test;
public class JavaBinaryTest {
private static final Path PATH_TO_GUAVA_JAR = Paths.get("third_party/guava/guava-10.0.1.jar");
private static final Path PATH_TO_GENERATOR_JAR = Paths.get("third_party/guava/generator.jar");
@Test
public void testGetExecutableCommand() {
// prebuilt_jar //third_party/generator:generator
PrebuiltJarBuilder.createBuilder(
BuildTargetFactory.newInstance("//third_party/generator:generator"))
.setBinaryJar(PATH_TO_GENERATOR_JAR)
.build();
// prebuilt_jar //third_party/guava:guava
TargetNode<?> guavaNode =
PrebuiltJarBuilder.createBuilder(
BuildTargetFactory.newInstance("//third_party/guava:guava"))
.setBinaryJar(PATH_TO_GUAVA_JAR)
.build();
// java_library //java/com/facebook/base:base
TargetNode<?> libraryNode =
JavaLibraryBuilder.createBuilder(
BuildTargetFactory.newInstance("//java/com/facebook/base:base"))
.addSrc(Paths.get("java/com/facebook/base/Base.java"))
.addDep(guavaNode.getBuildTarget())
.build();
TargetGraph targetGraph = TargetGraphFactory.newInstance(guavaNode, libraryNode);
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
SourcePathResolverAdapter pathResolver = graphBuilder.getSourcePathResolver();
BuildRule libraryRule = graphBuilder.requireRule(libraryNode.getBuildTarget());
BuildTarget target = BuildTargetFactory.newInstance("//java/com/facebook/base:Main");
BuildRuleParams params =
TestBuildRuleParams.create().withDeclaredDeps(ImmutableSortedSet.of(libraryRule));
// java_binary //java/com/facebook/base:Main
JavaBinary javaBinary =
graphBuilder.addToIndex(
new JavaBinary(
target,
new FakeProjectFilesystem(),
params,
JavaCompilationConstants.DEFAULT_JAVA_OPTIONS.getJavaRuntimeLauncher(
graphBuilder, UnconfiguredTargetConfiguration.INSTANCE),
"com.facebook.base.Main",
null,
/* merge manifests */ true,
false,
null,
/* blacklist */ ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
/* cache */ true,
Level.INFO));
// Strip the trailing "." from the absolute path to the current directory.
final String basePath = new File(".").getAbsolutePath().replaceFirst("\\.$", "");
// Each classpath entry is specified via its absolute path so that the executable command can be
// run from a /tmp directory, if necessary.
String expectedClasspath =
basePath + pathResolver.getRelativePath(javaBinary.getSourcePathToOutput());
List<String> expectedCommand = ImmutableList.of("java", "-jar", expectedClasspath);
assertEquals(
expectedCommand,
javaBinary.getExecutableCommand(OutputLabel.defaultLabel()).getCommandPrefix(pathResolver));
assertFalse(
"Library rules that are used exclusively by genrules should not be part of the classpath.",
expectedClasspath.contains(PATH_TO_GENERATOR_JAR.toString()));
}
}
|
3e1794973ebfbc95e64404da0eaa7c65e82c15bc | 1,070 | java | Java | src/main/java/me/bob/leetcode/editor/cn/MajorityElement.java | sakiila/algorithm | 917dfd808867834f3110da8a5d4ae97ebb560cd9 | [
"Apache-2.0"
] | null | null | null | src/main/java/me/bob/leetcode/editor/cn/MajorityElement.java | sakiila/algorithm | 917dfd808867834f3110da8a5d4ae97ebb560cd9 | [
"Apache-2.0"
] | null | null | null | src/main/java/me/bob/leetcode/editor/cn/MajorityElement.java | sakiila/algorithm | 917dfd808867834f3110da8a5d4ae97ebb560cd9 | [
"Apache-2.0"
] | null | null | null | 17.540984 | 70 | 0.51028 | 10,040 | //给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
//
// 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
//
//
//
// 示例 1:
//
//
//输入:[3,2,3]
//输出:3
//
// 示例 2:
//
//
//输入:[2,2,1,1,1,2,2]
//输出:2
//
//
//
//
// 进阶:
//
//
// 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
//
// Related Topics 位运算 数组 分治算法
// 👍 834 👎 0
package me.bob.leetcode.editor.cn;
/**
* 169 多数元素
* 2021-01-11 15:04:55
* 思路:摩尔投票法
*/
public class MajorityElement {
public static void main(String[] args) {
Solution solution = new MajorityElement().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
res = nums[i];
}
count = res == nums[i] ? count + 1 : count - 1;
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} |
3e179553bd23cc6b2f550a6aa3624f1bb9157b30 | 345 | java | Java | guns-film/src/main/java/com/stylefeng/guns/rest/common/persistence/dao/MoocSourceDictTMapper.java | han-xuefeng/guns | d3994474c7f9be5fd3008da82cbf01dfdcdfb964 | [
"Apache-2.0"
] | 3 | 2020-09-17T09:49:27.000Z | 2020-11-09T03:52:28.000Z | guns-film/src/main/java/com/stylefeng/guns/rest/common/persistence/dao/MoocSourceDictTMapper.java | han-xuefeng/guns | d3994474c7f9be5fd3008da82cbf01dfdcdfb964 | [
"Apache-2.0"
] | 1 | 2021-04-22T17:01:13.000Z | 2021-04-22T17:01:13.000Z | guns-film/src/main/java/com/stylefeng/guns/rest/common/persistence/dao/MoocSourceDictTMapper.java | han-xuefeng/guns | d3994474c7f9be5fd3008da82cbf01dfdcdfb964 | [
"Apache-2.0"
] | null | null | null | 20.294118 | 76 | 0.756522 | 10,041 | package com.stylefeng.guns.rest.common.persistence.dao;
import com.stylefeng.guns.rest.common.persistence.model.MoocSourceDictT;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 区域信息表 Mapper 接口
* </p>
*
* @author woods
* @since 2020-01-06
*/
public interface MoocSourceDictTMapper extends BaseMapper<MoocSourceDictT> {
}
|
3e17971d93fbd9f495ea6abda829948a349a2ba3 | 1,331 | java | Java | ecommerce/src/main/java/com/educative/ecommerce/service/CategoryService.java | clembnl/E-Commerce-Application | ef2a23ed2056ca60939adaff5296a5c89df2e63c | [
"Apache-2.0"
] | 1 | 2022-01-05T22:57:58.000Z | 2022-01-05T22:57:58.000Z | ecommerce/src/main/java/com/educative/ecommerce/service/CategoryService.java | clembnl/E-Commerce-Application | ef2a23ed2056ca60939adaff5296a5c89df2e63c | [
"Apache-2.0"
] | null | null | null | ecommerce/src/main/java/com/educative/ecommerce/service/CategoryService.java | clembnl/E-Commerce-Application | ef2a23ed2056ca60939adaff5296a5c89df2e63c | [
"Apache-2.0"
] | null | null | null | 27.729167 | 71 | 0.814425 | 10,042 | package com.educative.ecommerce.service;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.educative.ecommerce.model.Category;
import com.educative.ecommerce.repository.CategoryRepository;
@Service
@Transactional
public class CategoryService {
private final CategoryRepository categoryRepository;
public CategoryService(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
public List<Category> listCategories() {
return categoryRepository.findAll();
}
public void createCategory(Category category) {
categoryRepository.save(category);
}
public Category readCategory(String categoryName) {
return categoryRepository.findByCategoryName(categoryName);
}
public Optional<Category> readCategory(Integer categoryId) {
return categoryRepository.findById(categoryId);
}
public void updateCategory(Integer categoryID, Category newCategory) {
Category category = categoryRepository.findById(categoryID).get();
category.setCategoryName(newCategory.getCategoryName());
category.setDescription(newCategory.getDescription());
category.setProducts(newCategory.getProducts());
category.setImageUrl(newCategory.getImageUrl());
categoryRepository.save(category);
}
} |
3e17976e23b2f6503f14552136c701fea326f844 | 116 | java | Java | dms/src/main/java/com/dwman/log/bean/PowerBean.java | dwman/DMSLib | ca37b4ed0e5b55838eb45bcb69b9791684824127 | [
"Apache-2.0"
] | null | null | null | dms/src/main/java/com/dwman/log/bean/PowerBean.java | dwman/DMSLib | ca37b4ed0e5b55838eb45bcb69b9791684824127 | [
"Apache-2.0"
] | null | null | null | dms/src/main/java/com/dwman/log/bean/PowerBean.java | dwman/DMSLib | ca37b4ed0e5b55838eb45bcb69b9791684824127 | [
"Apache-2.0"
] | null | null | null | 12.888889 | 43 | 0.698276 | 10,043 | package com.dwman.log.bean;
/**
* Created by ldw on 2018/3/20.
*/
public class PowerBean extends BaseLogBean{
}
|
3e17981160b149c1d25c5303dc34de0f6346ca78 | 4,434 | java | Java | src/integrationTest/java/uk/gov/hmcts/reform/blobrouter/controllers/StaleBlobControllerTest.java | hmcts/blob-router-service | 47098fcb4c6605e7416d01c654047f6ed95330d3 | [
"MIT"
] | 1 | 2021-01-12T10:57:31.000Z | 2021-01-12T10:57:31.000Z | src/integrationTest/java/uk/gov/hmcts/reform/blobrouter/controllers/StaleBlobControllerTest.java | hmcts/blob-router-service | 47098fcb4c6605e7416d01c654047f6ed95330d3 | [
"MIT"
] | 771 | 2019-10-28T08:08:01.000Z | 2022-03-30T08:13:09.000Z | src/integrationTest/java/uk/gov/hmcts/reform/blobrouter/controllers/StaleBlobControllerTest.java | hmcts/blob-router-service | 47098fcb4c6605e7416d01c654047f6ed95330d3 | [
"MIT"
] | 2 | 2020-09-18T13:25:21.000Z | 2021-04-10T22:36:51.000Z | 39.238938 | 108 | 0.685611 | 10,044 | package uk.gov.hmcts.reform.blobrouter.controllers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import uk.gov.hmcts.reform.blobrouter.model.out.BlobInfo;
import uk.gov.hmcts.reform.blobrouter.services.storage.StaleBlobFinder;
import uk.gov.hmcts.reform.blobrouter.util.DateFormatter;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@WebMvcTest(StaleBlobController.class)
public class StaleBlobControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private StaleBlobFinder staleBlobFinder;
@Test
void should_return_list_of_stale_blobs_when_there_is_with_request_param() throws Exception {
Instant createdAt = Instant.now();
given(staleBlobFinder.findStaleBlobs(60))
.willReturn(Arrays.asList(
new BlobInfo("container1", "file_name_1", createdAt),
new BlobInfo("container2", "file_name_2", createdAt))
);
mockMvc
.perform(
get("/stale-blobs")
.queryParam("stale_time", "60")
)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(2))
.andExpect(jsonPath("$.data", hasSize(2)))
.andExpect(jsonPath("$.data.[0].container").value("container1"))
.andExpect(jsonPath("$.data.[0].file_name").value("file_name_1"))
.andExpect(jsonPath("$.data.[0].created_at").value(DateFormatter.getSimpleDateTime(createdAt)))
.andExpect(jsonPath("$.data.[1].container").value("container2"))
.andExpect(jsonPath("$.data.[1].file_name").value("file_name_2"))
.andExpect(jsonPath("$.data.[1].created_at").value(DateFormatter.getSimpleDateTime(createdAt)));
verify(staleBlobFinder).findStaleBlobs(60);
}
@Test
void should_return_list_of_stale_blobs_when_there_is_by_default_param_value() throws Exception {
Instant createdAt = Instant.now();
given(staleBlobFinder.findStaleBlobs(120))
.willReturn(Arrays.asList(new BlobInfo("container1", "file_name_1", createdAt)));
mockMvc
.perform(get("/stale-blobs"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(1))
.andExpect(jsonPath("$.data", hasSize(1)))
.andExpect(jsonPath("$.data.[0].container").value("container1"))
.andExpect(jsonPath("$.data.[0].file_name").value("file_name_1"))
.andExpect(jsonPath("$.data.[0].created_at").value(DateFormatter.getSimpleDateTime(createdAt)));
verify(staleBlobFinder).findStaleBlobs(120);
}
@Test
void should_return_empty_data_when_there_is_no_stale_blob() throws Exception {
given(staleBlobFinder.findStaleBlobs(120)).willReturn(Collections.emptyList());
mockMvc
.perform(get("/stale-blobs"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(0))
.andExpect(jsonPath("$.data").isEmpty());
verify(staleBlobFinder).findStaleBlobs(120);
}
@Test
void should_return_400_for_invalid_time() throws Exception {
mockMvc
.perform(get("/stale-blobs").queryParam("stale_time", "1x"))
.andDo(print())
.andExpect(status().isBadRequest());
verifyNoMoreInteractions(staleBlobFinder);
}
}
|
3e17985de44c0ce2d544d439656979a8e43a7be5 | 411 | java | Java | src/main/java/de/kaffeemann/jpm/PersonService.java | macevil/java-postgres-minio | 15cd146dbca33f367b6ac1e7d6445aba3f124f3e | [
"MIT"
] | null | null | null | src/main/java/de/kaffeemann/jpm/PersonService.java | macevil/java-postgres-minio | 15cd146dbca33f367b6ac1e7d6445aba3f124f3e | [
"MIT"
] | null | null | null | src/main/java/de/kaffeemann/jpm/PersonService.java | macevil/java-postgres-minio | 15cd146dbca33f367b6ac1e7d6445aba3f124f3e | [
"MIT"
] | null | null | null | 19.571429 | 62 | 0.788321 | 10,045 | package de.kaffeemann.jpm;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
@Autowired
PersonRepository personRepository;
public Person addPerson(Person person) {
return personRepository.save(person);
}
public List<Person> getAll() {
return personRepository.findAll();
}
} |
3e17990b7ef859c92a262fda4636df49d22c9c22 | 1,099 | java | Java | schemaOrgGson/src/org/kyojo/schemaorg/m3n5/gson/healthLifesci/medicalSpecialty/PrimaryCareDeserializer.java | nagaikenshin/schemaOrg | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | [
"Apache-2.0"
] | 1 | 2020-02-18T01:55:36.000Z | 2020-02-18T01:55:36.000Z | schemaOrgGson/src/org/kyojo/schemaorg/m3n5/gson/healthLifesci/medicalSpecialty/PrimaryCareDeserializer.java | nagaikenshin/schemaOrg | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | [
"Apache-2.0"
] | null | null | null | schemaOrgGson/src/org/kyojo/schemaorg/m3n5/gson/healthLifesci/medicalSpecialty/PrimaryCareDeserializer.java | nagaikenshin/schemaOrg | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | [
"Apache-2.0"
] | null | null | null | 34.34375 | 103 | 0.820746 | 10,046 | package org.kyojo.schemaorg.m3n5.gson.healthLifesci.medicalSpecialty;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import org.kyojo.gson.JsonDeserializationContext;
import org.kyojo.gson.JsonDeserializer;
import org.kyojo.gson.JsonElement;
import org.kyojo.gson.JsonParseException;
import org.kyojo.schemaorg.m3n5.healthLifesci.medicalSpecialty.PRIMARY_CARE;
import org.kyojo.schemaorg.m3n5.healthLifesci.MedicalSpecialty.PrimaryCare;
import org.kyojo.schemaorg.m3n5.gson.DeserializerTemplate;
public class PrimaryCareDeserializer implements JsonDeserializer<PrimaryCare> {
public static Map<String, Field> fldMap = new HashMap<>();
@Override
public PrimaryCare deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
throws JsonParseException {
if(jsonElement.isJsonPrimitive()) {
return new PRIMARY_CARE(jsonElement.getAsString());
}
return DeserializerTemplate.deserializeSub(jsonElement, type, context,
new PRIMARY_CARE(), PrimaryCare.class, PRIMARY_CARE.class, fldMap);
}
}
|
3e179970a0b9e088dd76226df0e5f5eb880f7607 | 3,932 | java | Java | proFL-plugin-2.0.3/groovy/inspect/swingui/ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/groovy/inspect/swingui/ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/groovy/inspect/swingui/ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | 49.772152 | 266 | 0.738301 | 10,047 | //
// Decompiled by Procyon v0.5.36
//
package groovy.inspect.swingui;
import org.codehaus.groovy.runtime.callsite.CallSiteArray;
import groovy.lang.MetaClass;
import groovy.lang.GroovyObject;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import groovy.lang.Reference;
import java.lang.ref.SoftReference;
import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.runtime.GeneratedClosure;
import groovy.lang.Closure;
class ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28 extends Closure implements GeneratedClosure
{
private static /* synthetic */ SoftReference $callSiteArray;
private static /* synthetic */ Class $class$groovy$inspect$Inspector;
private static /* synthetic */ Class $class$java$lang$Object;
public ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28(final Object _outerInstance, final Object _thisObject) {
$getCallSiteArray();
super(_outerInstance, _thisObject);
}
public Object doCall(final Object it) {
final Object it2 = new Reference(it);
final CallSite[] $getCallSiteArray = $getCallSiteArray();
return $getCallSiteArray[0].call(((Reference<Object>)it2).get(), $getCallSiteArray[1].callGetProperty($get$$class$groovy$inspect$Inspector()));
}
public Object doCall() {
return $getCallSiteArray()[2].callCurrent(this, ScriptBytecodeAdapter.createPojoWrapper(null, $get$$class$java$lang$Object()));
}
private static /* synthetic */ CallSiteArray $createCallSiteArray() {
final String[] names = new String[3];
$createCallSiteArray_1(names);
return new CallSiteArray($get$$class$groovy$inspect$swingui$ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28(), names);
}
private static /* synthetic */ CallSite[] $getCallSiteArray() {
CallSiteArray $createCallSiteArray;
if (ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$callSiteArray == null || ($createCallSiteArray = ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$callSiteArray.get()) == null) {
$createCallSiteArray = $createCallSiteArray();
ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$callSiteArray = new SoftReference($createCallSiteArray);
}
return $createCallSiteArray.array;
}
private static /* synthetic */ Class $get$$class$groovy$inspect$Inspector() {
Class $class$groovy$inspect$Inspector;
if (($class$groovy$inspect$Inspector = ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$class$groovy$inspect$Inspector) == null) {
$class$groovy$inspect$Inspector = (ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$class$groovy$inspect$Inspector = class$("groovy.inspect.Inspector"));
}
return $class$groovy$inspect$Inspector;
}
private static /* synthetic */ Class $get$$class$java$lang$Object() {
Class $class$java$lang$Object;
if (($class$java$lang$Object = ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$class$java$lang$Object) == null) {
$class$java$lang$Object = (ObjectBrowser$_run_closure1_closure3_closure7_closure10_closure23_closure24_closure28.$class$java$lang$Object = class$("java.lang.Object"));
}
return $class$java$lang$Object;
}
static /* synthetic */ Class class$(final String className) {
try {
return Class.forName(className);
}
catch (ClassNotFoundException ex) {
throw new NoClassDefFoundError(ex.getMessage());
}
}
}
|
3e17998d32e68e25c8dfb242472f0935684757b3 | 16,699 | java | Java | src/studentmanagement/PaymentEdior.java | fixylk/Tution_master-1.0 | c0b79cac4ebf6726972c766787a6242bbff0466d | [
"Apache-2.0"
] | null | null | null | src/studentmanagement/PaymentEdior.java | fixylk/Tution_master-1.0 | c0b79cac4ebf6726972c766787a6242bbff0466d | [
"Apache-2.0"
] | null | null | null | src/studentmanagement/PaymentEdior.java | fixylk/Tution_master-1.0 | c0b79cac4ebf6726972c766787a6242bbff0466d | [
"Apache-2.0"
] | null | null | null | 48.970674 | 165 | 0.660578 | 10,048 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package studentmanagement;
import coursesmanagement.PaymentManager;
import java.awt.Dimension;
import java.awt.Toolkit;
/**
*
* @author Nadun
*/
public class PaymentEdior extends javax.swing.JFrame {
/**
* Creates new form PaymentEdior
*/
private int payment;
private String name, barcode, course, institute, city;
private static PaymentEdior instance=new PaymentEdior();
public PaymentEdior() {
initComponents();
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int width=(int) dimension.getWidth();
int height=(int) dimension.getHeight();
this.setLocation((width/2)-199,(height/2)-156);
}
public static PaymentEdior getInstance(){
return instance;
}
public void showInterface(String name,String barcode,String course,String institute,String city,int payment){
this.name=name;
this.barcode=barcode;
this.course=course;
this.institute=institute;
this.city=city;
this.payment=payment;
instance.setVisible(true);
addData();
}
private void addData(){
stuName.setText(name);
barcodetxt.setText(barcode +" (barcode)");
courseNameTxt.setText(course);
institution.setText(institute+"-"+city);
if(payment==1){
paymentMarkBtn.setSelected(true);
}else if(payment==0){
paymentMarkBtn.setSelected(false);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
okBtn = new javax.swing.JButton();
cancelBtn1 = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
stuName = new javax.swing.JLabel();
courseNameTxt = new javax.swing.JLabel();
institution = new javax.swing.JLabel();
barcodetxt = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
paymentMarkBtn = new javax.swing.JToggleButton();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(21, 21, 41));
jPanel1.setPreferredSize(new java.awt.Dimension(500, 350));
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jPanel1MouseClicked(evt);
}
});
jLabel1.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(153, 153, 153));
jLabel1.setText("Change Payment");
jPanel2.setBackground(new java.awt.Color(21, 21, 41));
jPanel2.setLayout(new java.awt.GridLayout());
okBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/okCircle.png"))); // NOI18N
okBtn.setBorder(null);
okBtn.setBorderPainted(false);
okBtn.setFocusPainted(false);
okBtn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/okCircleSelected.png"))); // NOI18N
okBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okBtnActionPerformed(evt);
}
});
jPanel2.add(okBtn);
cancelBtn1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/CloseCircle.png"))); // NOI18N
cancelBtn1.setBorder(null);
cancelBtn1.setBorderPainted(false);
cancelBtn1.setFocusPainted(false);
cancelBtn1.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/CloseCircle-selected.png"))); // NOI18N
cancelBtn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelBtn1ActionPerformed(evt);
}
});
jPanel2.add(cancelBtn1);
jSeparator1.setBackground(new java.awt.Color(36, 36, 64));
jSeparator1.setForeground(new java.awt.Color(36, 36, 64));
stuName.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 19)); // NOI18N
stuName.setForeground(new java.awt.Color(153, 153, 153));
stuName.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
stuName.setText("Student Name");
courseNameTxt.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 19)); // NOI18N
courseNameTxt.setForeground(new java.awt.Color(153, 153, 153));
courseNameTxt.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
courseNameTxt.setText("Course");
institution.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 19)); // NOI18N
institution.setForeground(new java.awt.Color(153, 153, 153));
institution.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
institution.setText("Institute Name-City");
barcodetxt.setFont(new java.awt.Font("Swis721 LtEx BT", 0, 19)); // NOI18N
barcodetxt.setForeground(new java.awt.Color(153, 153, 153));
barcodetxt.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
barcodetxt.setText("Barcode");
jLabel15.setFont(new java.awt.Font("Swis721 LtEx BT", 1, 19)); // NOI18N
jLabel15.setForeground(new java.awt.Color(153, 153, 153));
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel15.setText("Payment");
paymentMarkBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/false-small.png"))); // NOI18N
paymentMarkBtn.setBorder(null);
paymentMarkBtn.setFocusPainted(false);
paymentMarkBtn.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/image/true-small.png"))); // NOI18N
paymentMarkBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
paymentMarkBtnActionPerformed(evt);
}
});
jPanel3.setOpaque(false);
jPanel3.setLayout(new java.awt.GridLayout(4, 1));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/bullet.png"))); // NOI18N
jPanel3.add(jLabel3);
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/bullet.png"))); // NOI18N
jPanel3.add(jLabel6);
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/bullet.png"))); // NOI18N
jPanel3.add(jLabel7);
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/bullet.png"))); // NOI18N
jPanel3.add(jLabel8);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(institution, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel15)
.addGap(18, 18, 18)
.addComponent(paymentMarkBtn))
.addComponent(stuName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(barcodetxt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(courseNameTxt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(stuName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(barcodetxt, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(courseNameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(institution, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(paymentMarkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(20, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 397, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okBtnActionPerformed
int payme=0;
boolean selected = paymentMarkBtn.isSelected();
if(selected){
payme=1;
}else {
payme=0;
}
PaymentManager.getInstance().changePayment(payme);
this.dispose();
}//GEN-LAST:event_okBtnActionPerformed
private void cancelBtn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtn1ActionPerformed
this.dispose();
}//GEN-LAST:event_cancelBtn1ActionPerformed
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked
}//GEN-LAST:event_jPanel1MouseClicked
private void paymentMarkBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_paymentMarkBtnActionPerformed
}//GEN-LAST:event_paymentMarkBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PaymentEdior.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PaymentEdior.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PaymentEdior.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PaymentEdior.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PaymentEdior().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel barcodetxt;
private javax.swing.JButton cancelBtn1;
private javax.swing.JLabel courseNameTxt;
private javax.swing.JLabel institution;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton okBtn;
private javax.swing.JToggleButton paymentMarkBtn;
private javax.swing.JLabel stuName;
// End of variables declaration//GEN-END:variables
}
|
3e1799bc367dc40cb49580ced6ec37b29df394eb | 6,598 | java | Java | src/data/RecipeSentenceSegmenterLearner.java | atcbosselut/recipe-interpretation | 3a316cceb5953b7248cf9ef03ea07d4caff9553c | [
"MIT"
] | 12 | 2017-01-11T15:18:11.000Z | 2020-11-11T16:10:22.000Z | src/data/RecipeSentenceSegmenterLearner.java | atcbosselut/recipe-interpretation | 3a316cceb5953b7248cf9ef03ea07d4caff9553c | [
"MIT"
] | 1 | 2017-06-28T08:22:31.000Z | 2020-04-29T11:30:20.000Z | src/data/RecipeSentenceSegmenterLearner.java | atcbosselut/recipe-interpretation | 3a316cceb5953b7248cf9ef03ea07d4caff9553c | [
"MIT"
] | 4 | 2017-03-07T14:00:24.000Z | 2020-10-13T01:05:45.000Z | 34.726316 | 136 | 0.685662 | 10,049 | package data;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import utils.Measurements;
import utils.Pair;
import utils.Utils;
/**
* This class trains RecipeSentenceSegmenter models using hard EM for a chosen # of iterations.
*
* @author chloe
*
*/
public class RecipeSentenceSegmenterLearner {
private int NUM_ITERS = 5;
private List<File> files_;
public RecipeSentenceSegmenterLearner(String training_dir) {
try {
files_ = Utils.getInputFiles(training_dir, "txt");
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public RecipeSentenceSegmenter run(String verbs_filename) {
RecipeSentenceSegmenter segmenter = new RecipeSentenceSegmenter(true, verbs_filename);
for (int i = 1; i <= NUM_ITERS; i++) {
System.out.println("Iteration: " + i);
segmenter = runOneIterHardEM(segmenter, i);
}
return segmenter;
}
private RecipeSentenceSegmenter runOneIterHardEM(RecipeSentenceSegmenter old_segmenter, int iter) {
RecipeSentenceSegmenter new_segmenter = new RecipeSentenceSegmenter();
Map<String, Map<String, Integer>> arg_bigram_cnt = new HashMap<String, Map<String, Integer>>();
Map<String, Integer> arg_tkn_ttl_cnt_ = new HashMap<String, Integer>();
Map<String, Integer> verb_cnt = new HashMap<String, Integer>();
Map<String, Integer> verb_arg_num_sum = new HashMap<String, Integer>();
Map<String, Map<Integer, Integer>> verb_arg_num_cnts = new HashMap<String, Map<Integer, Integer>>();
Set<String> tokens = new HashSet<String>();
tokens.add(RecipeSentenceSegmenter.END);
int num_sentences = 0;
int ttl_num_verbs = 0;
int file_no = 1;
for (File sentence_file: files_) {
System.out.println("Segmenting file " + file_no + " of " + files_.size());
file_no++;
List<String> sentences = Utils.splitStepSentences(sentence_file);
for (String sentence : sentences) {
sentence = sentence.replaceAll("\\*", "");
sentence = sentence.replaceAll(" ", " ");
num_sentences++;
String[] words = sentence.split(" ");
List<String> best_tags = old_segmenter.getMostProbableSequence(words);
if (best_tags == null) {
continue;
}
List<Pair<String, List<String>>> pred_args = old_segmenter.extractPredArgStructures(words, best_tags);
for (Pair<String, List<String>> pair : pred_args) {
String pred = pair.getFirst();
List<String> args = pair.getSecond();
ttl_num_verbs++;
Utils.incrementStringMapCount(verb_cnt, pred);
Integer cnt = verb_arg_num_sum.get(pred);
if (cnt == null) {
verb_arg_num_sum.put(pred, args.size());
} else {
verb_arg_num_sum.put(pred, cnt.intValue() + args.size());
}
Integer arg_cnt = args.size();
if (arg_cnt.intValue() > 3) {
arg_cnt = 3;
}
Utils.incrementIntMapValueCount(verb_arg_num_cnts, pred, arg_cnt);
for (String arg : args) {
tokens.add(arg);
String[] split = arg.split(" ");
Utils.incrementStringMapCount(arg_tkn_ttl_cnt_, RecipeSentenceSegmenter.PRED + pred);
Utils.incrementStringMapCount(arg_tkn_ttl_cnt_, RecipeSentenceSegmenter.END);
for (int i = 0; i < split.length; i++) {
String tkn = split[i];
String prev = null;
if (i != 0) {
prev = split[i-1];
if (Measurements.isNumericString(prev)) {
prev = "NUM#";
}
}
if (Measurements.isNumericString(tkn)) {
tkn = "NUM#";
}
Utils.incrementStringMapCount(arg_tkn_ttl_cnt_, tkn);
if (i == 0) {
Utils.incrementStringMapValueCount(arg_bigram_cnt, RecipeSentenceSegmenter.PRED + pred, tkn);
if (i == split.length - 1) {
Utils.incrementStringMapValueCount(arg_bigram_cnt, tkn, RecipeSentenceSegmenter.END);
}
} else if (i == split.length - 1) {
Utils.incrementStringMapValueCount(arg_bigram_cnt, tkn, RecipeSentenceSegmenter.END);
Utils.incrementStringMapValueCount(arg_bigram_cnt, prev, tkn);
} else {
Utils.incrementStringMapValueCount(arg_bigram_cnt, prev, tkn);
}
}
}
}
}
}
new_segmenter.setSentGeo((double)num_sentences / (ttl_num_verbs + num_sentences));
new_segmenter.setTotalVerbsCount(ttl_num_verbs);
for (String verb : verb_cnt.keySet()) {
Integer ttl_cnt = verb_cnt.get(verb);
Integer arg_sum = verb_arg_num_sum.get(verb);
new_segmenter.setVerbGeo(verb, ttl_cnt.doubleValue() / (arg_sum.doubleValue() + ttl_cnt.doubleValue()));
new_segmenter.setVerbCount(verb, ttl_cnt);
Map<Integer, Integer> arg_num_cnt = verb_arg_num_cnts.get(verb);
double denom = -1 * Math.log(ttl_cnt + 4);
for (int i = 0; i <= 3; i++) {
Integer cnt = arg_num_cnt.get(i);
if (cnt == null) {
new_segmenter.setVerbArgNumProb(verb, i, denom);
} else {
new_segmenter.setVerbArgNumProb(verb, i, Math.log(cnt.doubleValue() + 1) + denom);
}
}
}
new_segmenter.setArgBigramProb(RecipeSentenceSegmenter.OTHER, RecipeSentenceSegmenter.OTHER, -1 * Math.log(tokens.size() + 1));
for (String token : arg_bigram_cnt.keySet()) {
if (token.equals("END")) {
continue;
}
Integer token_cnt = arg_tkn_ttl_cnt_.get(token);
if (token_cnt == null) {
System.out.println(token);
System.exit(1);
}
Map<String, Integer> next_cnt = arg_bigram_cnt.get(token);
double denom = -1 * Math.log(token_cnt + tokens.size() + 1);
new_segmenter.setArgBigramProb(token, RecipeSentenceSegmenter.OTHER, denom);
for (String next : next_cnt.keySet()) {
Integer cnt = next_cnt.get(next);
new_segmenter.setArgBigramProb(token, next, Math.log(cnt.doubleValue() + 1) + denom);
}
}
try {
new_segmenter.writeToFile(ProjectParameters.DEFAULT_DATA_DIRECTORY + "segmenter_iter" + iter + ".model");
} catch (IOException ex) {
ex.printStackTrace();
}
return new_segmenter;
}
public static void main(String args[]) {
if (args.length < 2 || args.length > 3) {
System.out.println("Incorrect command line arguments.");
System.out.println("Use: java RecipeSentenceSegmenterLearner training_file_dir verbs_file number_of_iterations(optional,default=5)");
}
String training_file_dir = args[0];
String verbs_file = args[1];
RecipeSentenceSegmenterLearner learner = new RecipeSentenceSegmenterLearner(training_file_dir);
RecipeSentenceSegmenter segmenter = learner.run(verbs_file);
if (args.length == 3) {
learner.NUM_ITERS = Integer.parseInt(args[2]);
}
segmenter.tryOut();
}
}
|
3e179aea1eeebe9fc331e9afe0e701edcb3e45f7 | 9,613 | java | Java | pkix/src/main/java/org/bouncycastle/tsp/TSPUtil.java | matheus-eyng/bc-java | b35d626619a564db860e59e1cda353dec8d7a4fa | [
"MIT"
] | 1,604 | 2015-01-01T16:53:59.000Z | 2022-03-31T13:21:39.000Z | pkix/src/main/java/org/bouncycastle/tsp/TSPUtil.java | matheus-eyng/bc-java | b35d626619a564db860e59e1cda353dec8d7a4fa | [
"MIT"
] | 1,015 | 2015-01-08T08:15:43.000Z | 2022-03-31T11:05:41.000Z | pkix/src/main/java/org/bouncycastle/tsp/TSPUtil.java | matheus-eyng/bc-java | b35d626619a564db860e59e1cda353dec8d7a4fa | [
"MIT"
] | 885 | 2015-01-01T16:54:08.000Z | 2022-03-31T22:46:25.000Z | 44.09633 | 129 | 0.686674 | 10,050 | package org.bouncycastle.tsp;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.ExtensionsGenerator;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Integers;
public class TSPUtil
{
private static List EMPTY_LIST = Collections.unmodifiableList(new ArrayList());
private static final Map digestLengths = new HashMap();
private static final Map digestNames = new HashMap();
static
{
digestLengths.put(PKCSObjectIdentifiers.md5.getId(), Integers.valueOf(16));
digestLengths.put(OIWObjectIdentifiers.idSHA1.getId(), Integers.valueOf(20));
digestLengths.put(NISTObjectIdentifiers.id_sha224.getId(), Integers.valueOf(28));
digestLengths.put(NISTObjectIdentifiers.id_sha256.getId(), Integers.valueOf(32));
digestLengths.put(NISTObjectIdentifiers.id_sha384.getId(), Integers.valueOf(48));
digestLengths.put(NISTObjectIdentifiers.id_sha512.getId(), Integers.valueOf(64));
digestLengths.put(TeleTrusTObjectIdentifiers.ripemd128.getId(), Integers.valueOf(16));
digestLengths.put(TeleTrusTObjectIdentifiers.ripemd160.getId(), Integers.valueOf(20));
digestLengths.put(TeleTrusTObjectIdentifiers.ripemd256.getId(), Integers.valueOf(32));
digestLengths.put(CryptoProObjectIdentifiers.gostR3411.getId(), Integers.valueOf(32));
digestLengths.put(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.getId(), Integers.valueOf(32));
digestLengths.put(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.getId(), Integers.valueOf(64));
digestLengths.put(GMObjectIdentifiers.sm3.getId(), Integers.valueOf(32));
digestNames.put(PKCSObjectIdentifiers.md5.getId(), "MD5");
digestNames.put(OIWObjectIdentifiers.idSHA1.getId(), "SHA1");
digestNames.put(NISTObjectIdentifiers.id_sha224.getId(), "SHA224");
digestNames.put(NISTObjectIdentifiers.id_sha256.getId(), "SHA256");
digestNames.put(NISTObjectIdentifiers.id_sha384.getId(), "SHA384");
digestNames.put(NISTObjectIdentifiers.id_sha512.getId(), "SHA512");
digestNames.put(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), "SHA1");
digestNames.put(PKCSObjectIdentifiers.sha224WithRSAEncryption.getId(), "SHA224");
digestNames.put(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), "SHA256");
digestNames.put(PKCSObjectIdentifiers.sha384WithRSAEncryption.getId(), "SHA384");
digestNames.put(PKCSObjectIdentifiers.sha512WithRSAEncryption.getId(), "SHA512");
digestNames.put(TeleTrusTObjectIdentifiers.ripemd128.getId(), "RIPEMD128");
digestNames.put(TeleTrusTObjectIdentifiers.ripemd160.getId(), "RIPEMD160");
digestNames.put(TeleTrusTObjectIdentifiers.ripemd256.getId(), "RIPEMD256");
digestNames.put(CryptoProObjectIdentifiers.gostR3411.getId(), "GOST3411");
digestNames.put(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.getId(), "GOST3411-2012-256");
digestNames.put(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.getId(), "GOST3411-2012-512");
digestNames.put(GMObjectIdentifiers.sm3.getId(), "SM3");
}
/**
* Fetches the signature time-stamp attributes from a SignerInformation object.
* Checks that the MessageImprint for each time-stamp matches the signature field.
* (see RFC 3161 Appendix A).
*
* @param signerInfo a SignerInformation to search for time-stamps
* @param digCalcProvider provider for digest calculators
* @return a collection of TimeStampToken objects
* @throws TSPValidationException
*/
public static Collection getSignatureTimestamps(SignerInformation signerInfo, DigestCalculatorProvider digCalcProvider)
throws TSPValidationException
{
List timestamps = new ArrayList();
AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
if (unsignedAttrs != null)
{
ASN1EncodableVector allTSAttrs = unsignedAttrs.getAll(
PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
for (int i = 0; i < allTSAttrs.size(); ++i)
{
Attribute tsAttr = (Attribute)allTSAttrs.get(i);
ASN1Set tsAttrValues = tsAttr.getAttrValues();
for (int j = 0; j < tsAttrValues.size(); ++j)
{
try
{
ContentInfo contentInfo = ContentInfo.getInstance(tsAttrValues.getObjectAt(j));
TimeStampToken timeStampToken = new TimeStampToken(contentInfo);
TimeStampTokenInfo tstInfo = timeStampToken.getTimeStampInfo();
DigestCalculator digCalc = digCalcProvider.get(tstInfo.getHashAlgorithm());
OutputStream dOut = digCalc.getOutputStream();
dOut.write(signerInfo.getSignature());
dOut.close();
byte[] expectedDigest = digCalc.getDigest();
if (!Arrays.constantTimeAreEqual(expectedDigest, tstInfo.getMessageImprintDigest()))
{
throw new TSPValidationException("Incorrect digest in message imprint");
}
timestamps.add(timeStampToken);
}
catch (OperatorCreationException e)
{
throw new TSPValidationException("Unknown hash algorithm specified in timestamp");
}
catch (Exception e)
{
throw new TSPValidationException("Timestamp could not be parsed");
}
}
}
}
return timestamps;
}
/**
* Validate the passed in certificate as being of the correct type to be used
* for time stamping. To be valid it must have an ExtendedKeyUsage extension
* which has a key purpose identifier of id-kp-timeStamping.
*
* @param cert the certificate of interest.
* @throws TSPValidationException if the certificate fails on one of the check points.
*/
public static void validateCertificate(
X509CertificateHolder cert)
throws TSPValidationException
{
if (cert.toASN1Structure().getVersionNumber() != 3)
{
throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension.");
}
Extension ext = cert.getExtension(Extension.extendedKeyUsage);
if (ext == null)
{
throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension.");
}
if (!ext.isCritical())
{
throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");
}
ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(ext.getParsedValue());
if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1)
{
throw new TSPValidationException("ExtendedKeyUsage not solely time stamping.");
}
}
static int getDigestLength(
String digestAlgOID)
throws TSPException
{
Integer length = (Integer)digestLengths.get(digestAlgOID);
if (length != null)
{
return length.intValue();
}
throw new TSPException("digest algorithm cannot be found.");
}
static List getExtensionOIDs(Extensions extensions)
{
if (extensions == null)
{
return EMPTY_LIST;
}
return Collections.unmodifiableList(java.util.Arrays.asList(extensions.getExtensionOIDs()));
}
static void addExtension(ExtensionsGenerator extGenerator, ASN1ObjectIdentifier oid, boolean isCritical, ASN1Encodable value)
throws TSPIOException
{
try
{
extGenerator.addExtension(oid, isCritical, value);
}
catch (IOException e)
{
throw new TSPIOException("cannot encode extension: " + e.getMessage(), e);
}
}
}
|
3e179c55d0b2ee97969c670e1f12b15fe760bea7 | 1,684 | java | Java | src/main/java/org/geoint/logging/splunk/NativeSplunkFormatter.java | GEOINT/splunk-jul | 2086260333f11a3d28f30dc09a000703e78711fa | [
"Apache-2.0"
] | null | null | null | src/main/java/org/geoint/logging/splunk/NativeSplunkFormatter.java | GEOINT/splunk-jul | 2086260333f11a3d28f30dc09a000703e78711fa | [
"Apache-2.0"
] | 1 | 2015-01-26T22:17:33.000Z | 2015-05-07T21:44:59.000Z | src/main/java/org/geoint/logging/splunk/NativeSplunkFormatter.java | GEOINT/splunk-jul | 2086260333f11a3d28f30dc09a000703e78711fa | [
"Apache-2.0"
] | null | null | null | 31.773585 | 98 | 0.609857 | 10,051 | package org.geoint.logging.splunk;
import java.time.format.DateTimeFormatter;
/**
* Formats a {@link SplunkEvent} as a String which is natively readable by
* splunk.
*/
public class NativeSplunkFormatter implements SplunkEventFormatter {
private static final String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss.SSS Z";
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern(DATE_FORMAT);
private static final char KV_SEPARATOR = '=';
private static final String FIELD_SEPARATOR = ", ";
private static final char QUOTE = '"';
@Override
public String format(SplunkEvent event) {
StringBuilder sb = new StringBuilder();
sb.append(DATE_FORMATTER.format(event.getEventTime()));
event.getFields().entrySet().stream()
.sorted((o1, o2) -> o1.getKey().compareTo(o2.getKey()))
.forEach((e) -> appendKV(sb, escape(e.getKey()), e.getValue()));
sb.append(System.lineSeparator());
return sb.toString();
}
private void appendKV(StringBuilder sb, String key, String value) {
sb.append(FIELD_SEPARATOR)
.append(key) //normally don't need to normalize keys -- do this manually as needed
.append(KV_SEPARATOR)
.append(QUOTE)
.append(escape(value))
.append(QUOTE);
}
/**
* "Escapes" splunk field IAW their best practices.
*
* Escaping, for splunk, is actually substitutions.
*
* @param value
*/
private String escape(String value) {
return value.replace("\"", "'");
}
}
|
3e179c6a55c6f3107e487fe01cfd7b662552aca4 | 2,106 | java | Java | src/main/java/net/kodar/restaurantapi/business/processor/ProcessorGenericImpl.java | kamentr/API_Restaurant | d8b448c984b87c1a723b17ee366bddeb94b59eae | [
"MIT"
] | 1 | 2021-01-27T14:55:29.000Z | 2021-01-27T14:55:29.000Z | src/main/java/net/kodar/restaurantapi/business/processor/ProcessorGenericImpl.java | kamentr/API_Restaurant | d8b448c984b87c1a723b17ee366bddeb94b59eae | [
"MIT"
] | null | null | null | src/main/java/net/kodar/restaurantapi/business/processor/ProcessorGenericImpl.java | kamentr/API_Restaurant | d8b448c984b87c1a723b17ee366bddeb94b59eae | [
"MIT"
] | null | null | null | 24.206897 | 68 | 0.581671 | 10,052 | package net.kodar.restaurantapi.business.processor;
import org.springframework.beans.factory.annotation.Autowired;
import net.kodar.restaurantapi.business.validator.GenericValidator;
import net.kodar.restaurantapi.dataaccess.dao.DaoGenericImpl;
import javax.validation.ValidationException;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
public abstract class ProcessorGenericImpl
<IN, OUT, PK, ENT,
DAO extends DaoGenericImpl<ENT, PK>,
PTR extends BiFunction<IN, ENT, ENT>,
RTR extends Function<ENT, OUT>,
VAL extends GenericValidator<IN>>
implements Processor<IN, OUT, PK> {
public abstract PK getID(IN param);
@Autowired
protected DAO dao;
@Autowired
protected PTR ptr;
@Autowired
protected RTR rtr;
@Autowired
protected VAL val;
@Override
public OUT get(PK id) {
OUT out = rtr.apply(dao.get(id));
return out;
}
@Override
public List<OUT> getAll() {
List<ENT> list = dao.getAll();
List<OUT> entResults = list
.stream()
.map(s -> rtr.apply(s))
.collect(Collectors.toList());
return entResults;
}
@Override
public OUT save(IN param) throws ValidationException {
val.validate(param);
ENT entToSave = ptr.apply(param, null);
ENT save = dao.save(entToSave);
return rtr.apply(save);
}
@Override
public void update(IN param) throws ValidationException {
val.validate(param);
ENT entity = dao.get(getID(param));
if (null != entity) {
ENT entToUpdate = ptr.apply(param, entity);
dao.update(entToUpdate);
} else {
throw new NullPointerException();
}
}
@Override
public void delete(PK id) {
dao.delete(id);
}
}
|
3e179d75612a08a7125696e0840bd044dfd0237f | 188 | java | Java | igloo/igloo-components/igloo-component-jpa-migration/src/main/java/org/iglooproject/jpa/migration/util/IBatchMigrationInformation.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 17 | 2017-10-19T07:03:44.000Z | 2022-01-17T20:44:22.000Z | igloo/igloo-components/igloo-component-jpa-migration/src/main/java/org/iglooproject/jpa/migration/util/IBatchMigrationInformation.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 38 | 2018-01-22T15:57:35.000Z | 2022-01-14T16:28:45.000Z | igloo/igloo-components/igloo-component-jpa-migration/src/main/java/org/iglooproject/jpa/migration/util/IBatchMigrationInformation.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 6 | 2017-10-19T07:03:50.000Z | 2020-08-06T16:12:35.000Z | 23.5 | 110 | 0.856383 | 10,053 | package org.iglooproject.jpa.migration.util;
public interface IBatchMigrationInformation extends IMigrationInformation, IPreloadAwareMigrationInformation {
String getSqlCountRows();
}
|
3e179d90266c3412a34d1e4235fe6fd5969dbf68 | 17,729 | java | Java | src/main/java/com/faforever/client/theme/UiService.java | hellomouse/downlords-faf-client | ff9ec872bc572cfba9244bbc63038a656a3be43d | [
"MIT"
] | 1 | 2019-04-22T08:04:17.000Z | 2019-04-22T08:04:17.000Z | src/main/java/com/faforever/client/theme/UiService.java | hellomouse/downlords-faf-client | ff9ec872bc572cfba9244bbc63038a656a3be43d | [
"MIT"
] | null | null | null | src/main/java/com/faforever/client/theme/UiService.java | hellomouse/downlords-faf-client | ff9ec872bc572cfba9244bbc63038a656a3be43d | [
"MIT"
] | null | null | null | 37.801706 | 131 | 0.745445 | 10,054 | package com.faforever.client.theme;
import ch.micheljung.fxborderlessscene.borderless.BorderlessScene;
import com.faforever.client.config.CacheNames;
import com.faforever.client.fx.Controller;
import com.faforever.client.fx.JavaFxUtil;
import com.faforever.client.i18n.I18n;
import com.faforever.client.preferences.PreferencesService;
import com.github.nocatch.NoCatch.NoCatchRunnable;
import com.jfoenix.assets.JFoenixResources;
import com.jfoenix.controls.JFXDialog;
import com.jfoenix.controls.JFXDialog.DialogTransition;
import com.jfoenix.controls.JFXDialogLayout;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.MessageSourceResourceBundle;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.invoke.MethodHandles;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import static com.faforever.client.io.FileUtils.deleteRecursively;
import static com.faforever.client.preferences.Preferences.DEFAULT_THEME_NAME;
import static com.github.nocatch.NoCatch.noCatch;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
@Lazy
@Service
public class UiService implements InitializingBean, DisposableBean {
public static final String UNKNOWN_MAP_IMAGE = "theme/images/unknown_map.png";
//TODO: Create Images for News Categories
public static final String SERVER_UPDATE_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String LADDER_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String TOURNAMENT_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String FA_UPDATE_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String LOBBY_UPDATE_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String BALANCE_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String WEBSITE_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String CAST_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String PODCAST_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String FEATURED_MOD_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String DEVELOPMENT_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String DEFAULT_NEWS_IMAGE = "theme/images/news_fallback.jpg";
public static final String STYLE_CSS = "theme/style.css";
public static final String WEBVIEW_CSS_FILE = "theme/style-webview.css";
public static final String DEFAULT_ACHIEVEMENT_IMAGE = "theme/images/default_achievement.png";
public static final String MENTION_SOUND = "theme/sounds/mention.mp3";
public static final String CSS_CLASS_ICON = "icon";
public static final String LADDER_1V1_IMAGE = "theme/images/ranked1v1_notification.png";
public static final String CHAT_CONTAINER = "theme/chat/chat_container.html";
public static final String CHAT_SECTION_EXTENDED = "theme/chat/extended/chat_section.html";
public static final String CHAT_SECTION_COMPACT = "theme/chat/compact/chat_section.html";
public static final String CHAT_TEXT_EXTENDED = "theme/chat/extended/chat_text.html";
public static final String CHAT_TEXT_COMPACT = "theme/chat/compact/chat_text.html";
public static Theme DEFAULT_THEME = new Theme() {
{
setAuthor("Downlord");
setCompatibilityVersion(1);
setDisplayName("Default");
setThemeVersion("1.0");
}
};
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
/**
* This value needs to be updated whenever theme-breaking changes were made to the client.
*/
private static final int THEME_VERSION = 1;
private static final String METADATA_FILE_NAME = "theme.properties";
private final Set<Scene> scenes;
private final Set<WeakReference<WebView>> webViews;
private final PreferencesService preferencesService;
private final ThreadPoolExecutor threadPoolExecutor;
private final CacheManager cacheManager;
private final MessageSource messageSource;
private final ApplicationContext applicationContext;
private final I18n i18n;
private WatchService watchService;
private ObservableMap<String, Theme> themesByFolderName;
private Map<Theme, String> folderNamesByTheme;
private Map<Path, WatchKey> watchKeys;
private ObjectProperty<Theme> currentTheme;
private Path currentTempStyleSheet;
private MessageSourceResourceBundle resources;
public UiService(PreferencesService preferencesService, ThreadPoolExecutor threadPoolExecutor,
CacheManager cacheManager, MessageSource messageSource, ApplicationContext applicationContext,
I18n i18n) {
this.i18n = i18n;
this.preferencesService = preferencesService;
this.threadPoolExecutor = threadPoolExecutor;
this.cacheManager = cacheManager;
this.messageSource = messageSource;
this.applicationContext = applicationContext;
scenes = Collections.synchronizedSet(new HashSet<>());
webViews = new HashSet<>();
watchKeys = new HashMap<>();
currentTheme = new SimpleObjectProperty<>(DEFAULT_THEME);
folderNamesByTheme = new HashMap<>();
themesByFolderName = FXCollections.observableHashMap();
themesByFolderName.addListener((MapChangeListener<String, Theme>) change -> {
if (change.wasRemoved()) {
folderNamesByTheme.remove(change.getValueRemoved());
}
if (change.wasAdded()) {
folderNamesByTheme.put(change.getValueAdded(), change.getKey());
}
});
}
@Override
public void afterPropertiesSet() throws IOException {
resources = new MessageSourceResourceBundle(messageSource, i18n.getUserSpecificLocale());
Path themesDirectory = preferencesService.getThemesDirectory();
startWatchService(themesDirectory);
deleteStylesheetsCacheDirectory();
loadThemes();
String storedTheme = preferencesService.getPreferences().getThemeName();
setTheme(themesByFolderName.get(storedTheme));
loadWebViewsStyleSheet(getWebViewStyleSheet());
}
private void deleteStylesheetsCacheDirectory() throws IOException {
Path cacheStylesheetsDirectory = preferencesService.getCacheStylesheetsDirectory();
if (Files.exists(cacheStylesheetsDirectory)) {
deleteRecursively(cacheStylesheetsDirectory);
}
}
private void startWatchService(Path themesDirectory) throws IOException {
watchService = themesDirectory.getFileSystem().newWatchService();
threadPoolExecutor.execute(() -> {
try {
while (!Thread.interrupted()) {
WatchKey key = watchService.take();
onWatchEvent(key);
key.reset();
}
} catch (InterruptedException | ClosedWatchServiceException e) {
logger.debug("Watcher service terminated");
}
});
}
private void addThemeDirectory(Path path) {
Path metadataFile = path.resolve(METADATA_FILE_NAME);
if (Files.notExists(metadataFile)) {
return;
}
try (Reader reader = Files.newBufferedReader(metadataFile)) {
String folderName = path.getFileName().toString();
themesByFolderName.put(folderName, readTheme(reader));
} catch (IOException e) {
logger.warn("Theme could not be read: " + metadataFile.toAbsolutePath(), e);
}
}
private Theme readTheme(Reader reader) throws IOException {
Properties properties = new Properties();
properties.load(reader);
return Theme.fromProperties(properties);
}
@Override
public void destroy() throws IOException {
IOUtils.closeQuietly(watchService);
deleteStylesheetsCacheDirectory();
}
private void stopWatchingTheme(Theme theme) {
Path path = getThemeDirectory(theme);
if (watchKeys.containsKey(path)) {
watchKeys.remove(path).cancel();
}
}
/**
* Watches all contents in the specified theme for changes and reloads the theme if a change is detected.
*/
private void watchTheme(Theme theme) {
Path themePath = getThemeDirectory(theme);
logger.debug("Watching theme directory for changes: {}", themePath.toAbsolutePath());
noCatch(() -> Files.walkFileTree(themePath, new DirectoryVisitor(path -> watchDirectory(themePath, watchService))));
}
private void onWatchEvent(WatchKey key) {
for (WatchEvent<?> watchEvent : key.pollEvents()) {
Path path = (Path) watchEvent.context();
if (watchEvent.kind() == ENTRY_CREATE && Files.isDirectory(path)) {
watchDirectory(path, watchService);
} else if (watchEvent.kind() == ENTRY_DELETE && Files.isDirectory(path)) {
watchKeys.remove(path);
}
}
reloadStylesheet();
}
private void watchDirectory(Path directory, WatchService watchService) {
if (watchKeys.containsKey(directory)) {
return;
}
logger.debug("Watching directory: {}", directory.toAbsolutePath());
noCatch(() -> watchKeys.put(directory, directory.register(watchService, ENTRY_MODIFY, ENTRY_CREATE, ENTRY_DELETE)));
}
private void reloadStylesheet() {
String[] styleSheets = getStylesheets();
logger.debug("Changes detected, reloading stylesheets: {}", (Object[]) styleSheets);
scenes.forEach(scene -> setSceneStyleSheet(scene, styleSheets));
loadWebViewsStyleSheet(getWebViewStyleSheet());
}
private void setSceneStyleSheet(Scene scene, String[] styleSheets) {
Platform.runLater(() -> scene.getStylesheets().setAll(styleSheets));
}
private String getSceneStyleSheet() {
return getThemeFile(STYLE_CSS);
}
public String getThemeFile(String relativeFile) {
String strippedRelativeFile = relativeFile.replace("theme/", "");
Path externalFile = getThemeDirectory(currentTheme.get()).resolve(strippedRelativeFile);
if (Files.notExists(externalFile)) {
return noCatch(() -> new ClassPathResource("/" + relativeFile).getURL().toString());
}
return noCatch(() -> externalFile.toUri().toURL().toString());
}
/**
* Loads an image from the current theme.
*/
@Cacheable(CacheNames.THEME_IMAGES)
public Image getThemeImage(String relativeImage) {
return new Image(getThemeFile(relativeImage), true);
}
public URL getThemeFileUrl(String relativeFile) {
String themeFile = getThemeFile(relativeFile);
if (themeFile.startsWith("file:") || themeFile.startsWith("jar:")) {
return noCatch(() -> new URL(themeFile));
}
return noCatch(() -> new ClassPathResource(getThemeFile(relativeFile)).getURL());
}
public void setTheme(Theme theme) {
stopWatchingTheme(theme);
if (theme == DEFAULT_THEME) {
preferencesService.getPreferences().setThemeName(DEFAULT_THEME_NAME);
} else {
watchTheme(theme);
preferencesService.getPreferences().setThemeName(getThemeDirectory(theme).getFileName().toString());
}
preferencesService.storeInBackground();
reloadStylesheet();
currentTheme.set(theme);
cacheManager.getCache(CacheNames.THEME_IMAGES).clear();
}
/**
* Unregisters a scene so it's no longer updated when the theme (or its CSS) changes.
*/
private void unregisterScene(Scene scene) {
scenes.remove(scene);
}
/**
* Registers a scene against the theme service so it can be updated whenever the theme (or its CSS) changes.
*/
private void registerScene(Scene scene) {
scenes.add(scene);
JavaFxUtil.addListener(scene.windowProperty(), (windowProperty, oldWindow, newWindow) -> {
if (oldWindow != null) {
throw new UnsupportedOperationException("Not supposed to happen");
}
if (newWindow != null) {
JavaFxUtil.addListener(newWindow.showingProperty(), (observable, oldValue, newValue) -> {
if (!newValue) {
unregisterScene(scene);
} else {
registerScene(scene);
}
});
}
});
scene.getStylesheets().setAll(getStylesheets());
}
public String[] getStylesheets() {
return new String[]{
JFoenixResources.load("css/jfoenix-fonts.css").toExternalForm(),
JFoenixResources.load("css/jfoenix-design.css").toExternalForm(),
getThemeFile("theme/jfoenix.css"),
getSceneStyleSheet()
};
}
/**
* Registers a WebView against the theme service so it can be updated whenever the theme changes.
*/
public void registerWebView(WebView webView) {
webViews.add(new WeakReference<>(webView));
webView.getEngine().setUserStyleSheetLocation(getWebViewStyleSheet());
}
public void loadThemes() {
themesByFolderName.clear();
themesByFolderName.put(DEFAULT_THEME_NAME, DEFAULT_THEME);
noCatch(() -> {
Files.createDirectories(preferencesService.getThemesDirectory());
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(preferencesService.getThemesDirectory())) {
directoryStream.forEach(this::addThemeDirectory);
}
});
}
public Collection<Theme> getAvailableThemes() {
return new ArrayList<>(themesByFolderName.values());
}
public ReadOnlyObjectProperty<Theme> currentThemeProperty() {
return currentTheme;
}
/**
* Loads an FXML file and returns its controller instance. The controller instance is retrieved from the application
* context, so its scope (which should always be "prototype") depends on the bean definition.
*/
public <T extends Controller<?>> T loadFxml(String relativePath) {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(applicationContext::getBean);
loader.setLocation(getThemeFileUrl(relativePath));
loader.setResources(resources);
noCatch((NoCatchRunnable) loader::load);
return loader.getController();
}
private Path getThemeDirectory(Theme theme) {
return preferencesService.getThemesDirectory().resolve(folderNamesByTheme.get(theme));
}
private String getWebViewStyleSheet() {
return getThemeFileUrl(WEBVIEW_CSS_FILE).toString();
}
@SneakyThrows
private void loadWebViewsStyleSheet(String styleSheetUrl) {
// Always copy to a new file since WebView locks the loaded one
Path stylesheetsCacheDirectory = preferencesService.getCacheStylesheetsDirectory();
Files.createDirectories(stylesheetsCacheDirectory);
Path newTempStyleSheet = Files.createTempFile(stylesheetsCacheDirectory, "style-webview", ".css");
try (InputStream inputStream = new URL(styleSheetUrl).openStream()) {
Files.copy(inputStream, newTempStyleSheet, StandardCopyOption.REPLACE_EXISTING);
}
if (currentTempStyleSheet != null) {
Files.delete(currentTempStyleSheet);
}
currentTempStyleSheet = newTempStyleSheet;
webViews.removeIf(reference -> reference.get() != null);
webViews.stream()
.map(Reference::get)
.filter(Objects::nonNull)
.forEach(webView -> Platform.runLater(
() -> webView.getEngine().setUserStyleSheetLocation(noCatch(() -> currentTempStyleSheet.toUri().toURL()).toString())));
logger.debug("{} created and applied to all web views", newTempStyleSheet.getFileName());
}
public BorderlessScene createScene(Stage stage, Parent mainRoot) {
BorderlessScene scene = new BorderlessScene(stage, mainRoot, 0, 0);
scene.setMoveControl(mainRoot);
registerScene(scene);
return scene;
}
public JFXDialog showInDialog(StackPane parent, Node content, String title) {
JFXDialogLayout dialogLayout = new JFXDialogLayout();
dialogLayout.setHeading(new Label(title));
dialogLayout.setBody(content);
JFXDialog dialog = new JFXDialog();
dialog.setContent(dialogLayout);
dialog.setTransitionType(DialogTransition.TOP);
parent.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ESCAPE) {
dialog.close();
}
});
dialog.show(parent);
return dialog;
}
}
|
3e179dd3b07700e1607c5fae922c43d58f87b4ef | 6,466 | java | Java | tools/maven-bundle-plugin/src/test/java/org/apache/maven/shared/osgi/Maven2OsgiConverterTest.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 73 | 2020-02-28T19:50:03.000Z | 2022-03-31T14:40:18.000Z | tools/maven-bundle-plugin/src/test/java/org/apache/maven/shared/osgi/Maven2OsgiConverterTest.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 50 | 2020-03-02T10:53:06.000Z | 2022-03-25T13:23:51.000Z | tools/maven-bundle-plugin/src/test/java/org/apache/maven/shared/osgi/Maven2OsgiConverterTest.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 97 | 2020-03-02T10:40:18.000Z | 2022-03-25T01:13:32.000Z | 36.325843 | 81 | 0.651253 | 10,055 | package org.apache.maven.shared.osgi;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import org.apache.maven.plugin.testing.stubs.ArtifactStub;
import org.codehaus.plexus.PlexusTestCase;
/**
* Test for {@link DefaultMaven2OsgiConverter}
*
* @author <a href="mailto:lyhxr@example.com">Carlos Sanchez</a>
* @version $Id$
*/
public class Maven2OsgiConverterTest
extends PlexusTestCase
{
private Maven2OsgiConverter maven2Osgi = new DefaultMaven2OsgiConverter();
public void testGetBundleSymbolicName()
{
ArtifactStub artifact = getTestArtifact();
String s;
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "org.apache.commons.logging", s );
artifact.setGroupId( "org.apache.commons" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "org.apache.commons.logging", s );
artifact.setGroupId( "org.apache.commons.commons-logging" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "org.apache.commons.commons-logging", s );
artifact.setGroupId( "org.apache" );
artifact.setArtifactId( "org.apache.commons-logging" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "org.apache.commons-logging", s );
artifact.setFile( getTestFile( "junit-3.8.2.jar" ) );
artifact.setGroupId( "junit" );
artifact.setArtifactId( "junit" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "junit", s );
artifact.setFile( getTestFile( "xml-apis-1.0.b2.jar" ) );
artifact.setGroupId( "xml-apis" );
artifact.setArtifactId( "a" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "xml-apis.a", s );
artifact.setFile( getTestFile( "test-1.jar" ) );
artifact.setGroupId( "test" );
artifact.setArtifactId( "test" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "test", s );
artifact.setFile( getTestFile( "xercesImpl-2.6.2.jar" ) );
artifact.setGroupId( "xerces" );
artifact.setArtifactId( "xercesImpl" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "xerces.Impl", s );
artifact.setFile( getTestFile( "aopalliance-1.0.jar" ) );
artifact.setGroupId( "org.aopalliance" );
artifact.setArtifactId( "aopalliance" );
s = maven2Osgi.getBundleSymbolicName( artifact );
assertEquals( "org.aopalliance", s );
}
public void testGetBundleFileName()
{
ArtifactStub artifact = getTestArtifact();
String s;
s = maven2Osgi.getBundleFileName( artifact );
assertEquals( "org.apache.commons.logging_1.1.0.jar", s );
artifact.setGroupId( "org.aopalliance" );
artifact.setArtifactId( "aopalliance" );
s = maven2Osgi.getBundleFileName( artifact );
assertEquals( "org.aopalliance_1.1.0.jar", s );
}
public void testGetVersion()
{
ArtifactStub artifact = getTestArtifact();
String s = maven2Osgi.getVersion( artifact );
assertEquals( "1.1.0", s );
}
public void testConvertVersionToOsgi()
{
String osgiVersion;
osgiVersion = maven2Osgi.getVersion( "2.1.0-SNAPSHOT" );
assertEquals( "2.1.0.SNAPSHOT", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "2.1-SNAPSHOT" );
assertEquals( "2.1.0.SNAPSHOT", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "0.1-SNAPSHOT" );
assertEquals( "0.1.0.SNAPSHOT", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "2-SNAPSHOT" );
assertEquals( "2.0.0.SNAPSHOT", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "2" );
assertEquals( "2.0.0", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "2.1" );
assertEquals( "2.1.0", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "2.1.3" );
assertEquals( "2.1.3", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "2.1.3.4" );
assertEquals( "2.1.3.4", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "4aug2000r7-dev" );
assertEquals( "0.0.0.4aug2000r7-dev", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "1.1-alpha-2" );
assertEquals( "1.1.0.alpha-2", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "1.0-alpha-16-20070122.203121-13" );
assertEquals( "1.0.0.alpha-16-20070122_203121-13", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "1.0-20070119.021432-1" );
assertEquals( "1.0.0.20070119_021432-1", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "1-20070119.021432-1" );
assertEquals( "1.0.0.20070119_021432-1", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "1.4.1-20070217.082013-7" );
assertEquals( "1.4.1.20070217_082013-7", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "0.0.0.4aug2000r7-dev" );
assertEquals( "0.0.0.4aug2000r7-dev", osgiVersion );
osgiVersion = maven2Osgi.getVersion( "4aug2000r7-dev" );
assertEquals( "0.0.0.4aug2000r7-dev", osgiVersion );
}
private ArtifactStub getTestArtifact()
{
ArtifactStub a = new ArtifactStub();
a.setGroupId( "commons-logging" );
a.setArtifactId( "commons-logging" );
a.setVersion( "1.1" );
a.setFile( getTestFile( "commons-logging-1.1.jar" ) );
return a;
}
public static File getTestFile( String fileName )
{
return PlexusTestCase.getTestFile( "src/test/resources/" + fileName );
}
}
|
3e179e94a3020a1d0d2cef9788220c40f6547d02 | 8,481 | java | Java | src/testcases/CWE129_Improper_Validation_of_Array_Index/s02/CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75a.java | diktat-static-analysis/juliet-benchmark-java | 7e55922d154c26ef34ff3327073f030ff7393b2a | [
"MIT"
] | null | null | null | src/testcases/CWE129_Improper_Validation_of_Array_Index/s02/CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75a.java | diktat-static-analysis/juliet-benchmark-java | 7e55922d154c26ef34ff3327073f030ff7393b2a | [
"MIT"
] | null | null | null | src/testcases/CWE129_Improper_Validation_of_Array_Index/s02/CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75a.java | diktat-static-analysis/juliet-benchmark-java | 7e55922d154c26ef34ff3327073f030ff7393b2a | [
"MIT"
] | null | null | null | 35.190871 | 155 | 0.58802 | 10,056 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75a.java
Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml
Template File: sources-sinks-75a.tmpl.java
*/
/*
* @description
* CWE: 129 Improper Validation of Array Index
* BadSource: getCookies_Servlet Read data from the first cookie using getCookies()
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: array_read_no_check
* GoodSink: Read from array after verifying index
* BadSink : Read from array without any verification of index
* Flow Variant: 75 Data flow: data passed in a serialized object from one method to another in different source files in the same package
*
* */
package testcases.CWE129_Improper_Validation_of_Array_Index.s02;
import testcasesupport.*;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import javax.servlet.http.*;
public class CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75a extends AbstractTestCaseServlet
{
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int data;
data = Integer.MIN_VALUE; /* initialize data in case there are no cookies */
/* Read data from cookies */
{
Cookie cookieSources[] = request.getCookies();
if (cookieSources != null)
{
/* POTENTIAL FLAW: Read data from the first cookie value */
String stringNumber = cookieSources[0].getValue();
try
{
data = Integer.parseInt(stringNumber.trim());
}
catch(NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception reading data from cookie", exceptNumberFormat);
}
}
}
/* serialize data to a byte array */
ByteArrayOutputStream streamByteArrayOutput = null;
ObjectOutput outputObject = null;
try
{
streamByteArrayOutput = new ByteArrayOutputStream() ;
outputObject = new ObjectOutputStream(streamByteArrayOutput) ;
outputObject.writeObject(data);
byte[] dataSerialized = streamByteArrayOutput.toByteArray();
(new CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75b()).badSink(dataSerialized , request, response );
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
}
finally
{
/* clean up stream writing objects */
try
{
if (outputObject != null)
{
outputObject.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
}
try
{
if (streamByteArrayOutput != null)
{
streamByteArrayOutput.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
}
}
}
public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
goodG2B(request, response);
goodB2G(request, response);
}
/* goodG2B() - use GoodSource and BadSink */
private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int data;
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
/* serialize data to a byte array */
ByteArrayOutputStream streamByteArrayOutput = null;
ObjectOutput outputObject = null;
try
{
streamByteArrayOutput = new ByteArrayOutputStream() ;
outputObject = new ObjectOutputStream(streamByteArrayOutput) ;
outputObject.writeObject(data);
byte[] dataSerialized = streamByteArrayOutput.toByteArray();
(new CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75b()).goodG2BSink(dataSerialized , request, response );
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
}
finally
{
/* clean up stream writing objects */
try
{
if (outputObject != null)
{
outputObject.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
}
try
{
if (streamByteArrayOutput != null)
{
streamByteArrayOutput.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
}
}
}
/* goodB2G() - use BadSource and GoodSink */
private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int data;
data = Integer.MIN_VALUE; /* initialize data in case there are no cookies */
/* Read data from cookies */
{
Cookie cookieSources[] = request.getCookies();
if (cookieSources != null)
{
/* POTENTIAL FLAW: Read data from the first cookie value */
String stringNumber = cookieSources[0].getValue();
try
{
data = Integer.parseInt(stringNumber.trim());
}
catch(NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception reading data from cookie", exceptNumberFormat);
}
}
}
/* serialize data to a byte array */
ByteArrayOutputStream streamByteArrayOutput = null;
ObjectOutput outputObject = null;
try
{
streamByteArrayOutput = new ByteArrayOutputStream() ;
outputObject = new ObjectOutputStream(streamByteArrayOutput) ;
outputObject.writeObject(data);
byte[] dataSerialized = streamByteArrayOutput.toByteArray();
(new CWE129_Improper_Validation_of_Array_Index__getCookies_Servlet_array_read_no_check_75b()).goodB2GSink(dataSerialized , request, response );
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "IOException in serialization", exceptIO);
}
finally
{
/* clean up stream writing objects */
try
{
if (outputObject != null)
{
outputObject.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ObjectOutputStream", exceptIO);
}
try
{
if (streamByteArrayOutput != null)
{
streamByteArrayOutput.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ByteArrayOutputStream", exceptIO);
}
}
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
3e179eb007ddae9fca3c7cce192f5cc01533fc71 | 226 | java | Java | src/main/Main.java | hmart027/XBeeComms | bccaf7b394b43f566a4e305343ed4c21f31ed66f | [
"MIT"
] | null | null | null | src/main/Main.java | hmart027/XBeeComms | bccaf7b394b43f566a4e305343ed4c21f31ed66f | [
"MIT"
] | null | null | null | src/main/Main.java | hmart027/XBeeComms | bccaf7b394b43f566a4e305343ed4c21f31ed66f | [
"MIT"
] | null | null | null | 18.833333 | 64 | 0.659292 | 10,057 | package main;
public class Main {
public static void main(String[] args){
// new Serial().start();
tank.wifi.WiFiInterface tank = new tank.wifi.WiFiInterface();
System.out.println(tank.getDevices());
}
}
|
3e179f7e97025f287dd571abe22d4e8498ef092b | 562 | java | Java | chapter_003/src/main/java/generics/UserConvert.java | y-dubovitsky/dubovitsky | 4a264f0a904ee8092f91eb38f1397c2c98ee8ca0 | [
"Apache-2.0"
] | 1 | 2019-02-15T16:29:39.000Z | 2019-02-15T16:29:39.000Z | chapter_003/src/main/java/generics/UserConvert.java | y-dubovitsky/dubovitsky | 4a264f0a904ee8092f91eb38f1397c2c98ee8ca0 | [
"Apache-2.0"
] | 1 | 2021-12-14T20:43:51.000Z | 2021-12-14T20:43:51.000Z | chapter_003/src/main/java/generics/UserConvert.java | y-dubovitsky/dubovitsky | 4a264f0a904ee8092f91eb38f1397c2c98ee8ca0 | [
"Apache-2.0"
] | null | null | null | 21.615385 | 69 | 0.604982 | 10,058 | package generics;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Класс конвертации списка в Map.
*/
public class UserConvert {
/**
* Метод принимает в себя список пользователей и конвертирует его
* в Map с ключом Integer id и соответствующим ему User.
* @param list
* @return
*/
public Map<Integer, User> process(List<User> list) {
Map<Integer, User> map = new HashMap<>();
for (User user : list) {
map.put(user.getId(), user);
}
return map;
}
}
|
3e179fe6c91e0e12b4d0d298e2c8348b91ccad22 | 4,198 | java | Java | src/main/java/org/xmlobjects/gml/adapter/geometry/complexes/CompositeCurveAdapter.java | citygml4j/gml-objects | 7581b3332dc12ae661aeec14ae71ca3ba6f6f9ac | [
"Apache-2.0"
] | 1 | 2019-07-27T14:30:07.000Z | 2019-07-27T14:30:07.000Z | src/main/java/org/xmlobjects/gml/adapter/geometry/complexes/CompositeCurveAdapter.java | citygml4j/gml-objects | 7581b3332dc12ae661aeec14ae71ca3ba6f6f9ac | [
"Apache-2.0"
] | null | null | null | src/main/java/org/xmlobjects/gml/adapter/geometry/complexes/CompositeCurveAdapter.java | citygml4j/gml-objects | 7581b3332dc12ae661aeec14ae71ca3ba6f6f9ac | [
"Apache-2.0"
] | null | null | null | 45.673913 | 167 | 0.772013 | 10,059 | /*
* gml-objects - A Java mapping for the OGC Geography Markup Language (GML)
* https://github.com/xmlobjects/gml-objects
*
* Copyright 2019-2021 Claus Nagel <ychag@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xmlobjects.gml.adapter.geometry.complexes;
import org.xmlobjects.annotation.XMLElement;
import org.xmlobjects.annotation.XMLElements;
import org.xmlobjects.builder.ObjectBuildException;
import org.xmlobjects.gml.adapter.GMLBuilderHelper;
import org.xmlobjects.gml.adapter.GMLSerializerHelper;
import org.xmlobjects.gml.adapter.geometry.primitives.AbstractCurveAdapter;
import org.xmlobjects.gml.adapter.geometry.primitives.CurvePropertyAdapter;
import org.xmlobjects.gml.model.geometry.complexes.CompositeCurve;
import org.xmlobjects.gml.model.geometry.primitives.CurveProperty;
import org.xmlobjects.gml.util.GMLConstants;
import org.xmlobjects.serializer.ObjectSerializeException;
import org.xmlobjects.stream.XMLReadException;
import org.xmlobjects.stream.XMLReader;
import org.xmlobjects.stream.XMLWriteException;
import org.xmlobjects.stream.XMLWriter;
import org.xmlobjects.xml.Attributes;
import org.xmlobjects.xml.Element;
import org.xmlobjects.xml.Namespaces;
import javax.xml.namespace.QName;
@XMLElements({
@XMLElement(name = "CompositeCurve", namespaceURI = GMLConstants.GML_3_2_NAMESPACE),
@XMLElement(name = "CompositeCurve", namespaceURI = GMLConstants.GML_3_1_NAMESPACE)
})
public class CompositeCurveAdapter extends AbstractCurveAdapter<CompositeCurve> {
@Override
public CompositeCurve createObject(QName name, Object parent) throws ObjectBuildException {
return new CompositeCurve();
}
@Override
public void initializeObject(CompositeCurve object, QName name, Attributes attributes, XMLReader reader) throws ObjectBuildException, XMLReadException {
super.initializeObject(object, name, attributes, reader);
GMLBuilderHelper.buildAggregationAttributes(object, attributes);
}
@Override
public void buildChildObject(CompositeCurve object, QName name, Attributes attributes, XMLReader reader) throws ObjectBuildException, XMLReadException {
if (GMLBuilderHelper.isGMLNamespace(name.getNamespaceURI())) {
if ("curveMember".equals(name.getLocalPart()))
object.getCurveMembers().add(reader.getObjectUsingBuilder(CurvePropertyAdapter.class));
else
super.buildChildObject(object, name, attributes, reader);
}
}
@Override
public Element createElement(CompositeCurve object, Namespaces namespaces) throws ObjectSerializeException {
return Element.of(GMLSerializerHelper.getGMLBaseNamespace(namespaces), "CompositeCurve");
}
@Override
public void initializeElement(Element element, CompositeCurve object, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
super.initializeElement(element, object, namespaces, writer);
GMLSerializerHelper.serializeAggregationAttributes(element, object, namespaces);
}
@Override
public void writeChildElements(CompositeCurve object, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
super.writeChildElements(object, namespaces, writer);
String baseNamespace = GMLSerializerHelper.getGMLBaseNamespace(namespaces);
if (object.isSetCurveMembers()) {
for (CurveProperty property : object.getCurveMembers())
writer.writeElementUsingSerializer(Element.of(baseNamespace, "curveMember"), property, CurvePropertyAdapter.class, namespaces);
}
}
}
|
3e17a2337e9c7a37b94088e34281655069a6091e | 3,679 | java | Java | aliyun-java-sdk-sae/src/main/java/com/aliyuncs/sae/model/v20190506/ListApplicationsRequest.java | yndu13/aliyun-openapi-java-sdk | 8040c0414d18abcf4c3d1257c721732c7402d087 | [
"Apache-2.0"
] | 1 | 2022-02-12T06:01:36.000Z | 2022-02-12T06:01:36.000Z | aliyun-java-sdk-sae/src/main/java/com/aliyuncs/sae/model/v20190506/ListApplicationsRequest.java | yndu13/aliyun-openapi-java-sdk | 8040c0414d18abcf4c3d1257c721732c7402d087 | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-sae/src/main/java/com/aliyuncs/sae/model/v20190506/ListApplicationsRequest.java | yndu13/aliyun-openapi-java-sdk | 8040c0414d18abcf4c3d1257c721732c7402d087 | [
"Apache-2.0"
] | null | null | null | 22.99375 | 118 | 0.706986 | 10,060 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.sae.model.v20190506;
import com.aliyuncs.RoaAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.sae.Endpoint;
/**
* @author auto create
* @version
*/
public class ListApplicationsRequest extends RoaAcsRequest<ListApplicationsResponse> {
private String appName;
private String namespaceId;
private Integer pageSize;
private String orderBy;
private Integer currentPage;
private String fieldValue;
private Boolean reverse;
private String fieldType;
private String tags;
public ListApplicationsRequest() {
super("sae", "2019-05-06", "ListApplications", "serverless");
setUriPattern("/pop/v1/sam/app/listApplications");
setMethod(MethodType.GET);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
if(appName != null){
putQueryParameter("AppName", appName);
}
}
public String getNamespaceId() {
return this.namespaceId;
}
public void setNamespaceId(String namespaceId) {
this.namespaceId = namespaceId;
if(namespaceId != null){
putQueryParameter("NamespaceId", namespaceId);
}
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
if(pageSize != null){
putQueryParameter("PageSize", pageSize.toString());
}
}
public String getOrderBy() {
return this.orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
if(orderBy != null){
putQueryParameter("OrderBy", orderBy);
}
}
public Integer getCurrentPage() {
return this.currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
if(currentPage != null){
putQueryParameter("CurrentPage", currentPage.toString());
}
}
public String getFieldValue() {
return this.fieldValue;
}
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
if(fieldValue != null){
putQueryParameter("FieldValue", fieldValue);
}
}
public Boolean getReverse() {
return this.reverse;
}
public void setReverse(Boolean reverse) {
this.reverse = reverse;
if(reverse != null){
putQueryParameter("Reverse", reverse.toString());
}
}
public String getFieldType() {
return this.fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
if(fieldType != null){
putQueryParameter("FieldType", fieldType);
}
}
public String getTags() {
return this.tags;
}
public void setTags(String tags) {
this.tags = tags;
if(tags != null){
putQueryParameter("Tags", tags);
}
}
@Override
public Class<ListApplicationsResponse> getResponseClass() {
return ListApplicationsResponse.class;
}
}
|
3e17a26d9cc164a7ae14a999027ba6da96af3744 | 409 | java | Java | corn/src/main/java/com/xiazhenyu/corn/coreTec/daemon/Run.java | chenyusharp/corp | fe86d9d4778ca58cc38655d8ca9e0d1dac0c1b33 | [
"Apache-2.0"
] | null | null | null | corn/src/main/java/com/xiazhenyu/corn/coreTec/daemon/Run.java | chenyusharp/corp | fe86d9d4778ca58cc38655d8ca9e0d1dac0c1b33 | [
"Apache-2.0"
] | null | null | null | corn/src/main/java/com/xiazhenyu/corn/coreTec/daemon/Run.java | chenyusharp/corp | fe86d9d4778ca58cc38655d8ca9e0d1dac0c1b33 | [
"Apache-2.0"
] | null | null | null | 15.730769 | 72 | 0.616137 | 10,061 | package com.xiazhenyu.corn.coreTec.daemon;
/**
* Date: 2022/1/2
* <p>
* Description:
*
* @author xiazhenyu
*/
public class Run {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.setDaemon(true);
myThread.start();
Thread.sleep(5000);
System.out.println("daemon thread is end");
}
} |
3e17a2d1f1a7613671cf80523df0d8f03c178290 | 10,220 | java | Java | loadingdrawable/src/main/java/com/github/shareme/greenandroid/loadingdrawable/LevelLoadingRenderer.java | shareme/GreenAndroid | f9f9db8317c0d5e26855e891b31883bf5f18fc64 | [
"Apache-2.0"
] | 2 | 2016-11-28T09:57:01.000Z | 2017-01-24T10:20:48.000Z | loadingdrawable/src/main/java/com/github/shareme/greenandroid/loadingdrawable/LevelLoadingRenderer.java | shareme/GreenAndroid | f9f9db8317c0d5e26855e891b31883bf5f18fc64 | [
"Apache-2.0"
] | null | null | null | loadingdrawable/src/main/java/com/github/shareme/greenandroid/loadingdrawable/LevelLoadingRenderer.java | shareme/GreenAndroid | f9f9db8317c0d5e26855e891b31883bf5f18fc64 | [
"Apache-2.0"
] | null | null | null | 32.547771 | 146 | 0.721722 | 10,062 | /*
Copyright 2015-2019 dinus
Modifications Copyright(C) 2016 Fred Grott(GrottWorkSpace)
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.github.shareme.greenandroid.loadingdrawable;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
@SuppressWarnings("unused")
public class LevelLoadingRenderer extends LoadingRenderer{
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
private static final Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();
private static final Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator();
private static final int NUM_POINTS = 5;
private static final int DEGREE_360 = 360;
private static final float FULL_ROTATION = 1080.0f;
private static final float ROTATION_FACTOR = 0.25f;
private static final float MAX_PROGRESS_ARC = 0.8f;
private static final float LEVEL2_SWEEP_ANGLE_OFFSET = 7.0f / 8.0f;
private static final float LEVEL3_SWEEP_ANGLE_OFFSET = 5.0f / 8.0f;
private static final float START_TRIM_DURATION_OFFSET = 0.5f;
private static final float END_TRIM_START_DELAY_OFFSET = 0.5f;
private static final int DEFAULT_COLOR = Color.WHITE;
private final Paint mPaint = new Paint();
private final RectF mTempBounds = new RectF();
private final Animator.AnimatorListener mAnimatorListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationRepeat(Animator animator) {
super.onAnimationRepeat(animator);
storeOriginals();
mStartTrim = mEndTrim;
mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
}
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
mRotationCount = 0;
}
};
private boolean mIsRenderingFirstHalf;
private int mLevel1Color;
private int mLevel2Color;
private int mLevel3Color;
private float mStrokeInset;
private float mEndTrim;
private float mRotation;
private float mStartTrim;
private float mRotationCount;
private float mGroupRotation;
private float mOriginEndTrim;
private float mOriginRotation;
private float mOriginStartTrim;
public LevelLoadingRenderer(Context context) {
super(context);
setupPaint();
addRenderListener(mAnimatorListener);
}
private void setupPaint() {
mLevel1Color = oneThirdAlphaColor(DEFAULT_COLOR);
mLevel2Color = twoThirdAlphaColor(DEFAULT_COLOR);
mLevel3Color = DEFAULT_COLOR;
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(getStrokeWidth());
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
setInsets((int) getWidth(), (int) getHeight());
}
@Override
public void draw(Canvas canvas, Rect bounds) {
int saveCount = canvas.save();
canvas.rotate(mGroupRotation, bounds.exactCenterX(), bounds.exactCenterY());
RectF arcBounds = mTempBounds;
arcBounds.set(bounds);
arcBounds.inset(mStrokeInset, mStrokeInset);
if (mStartTrim == mEndTrim) {
mStartTrim = mEndTrim + getMinProgressArc();
}
float startAngle = (mStartTrim + mRotation) * DEGREE_360;
float endAngle = (mEndTrim + mRotation) * DEGREE_360;
float sweepAngle = endAngle - startAngle;
if (mIsRenderingFirstHalf) {
float renderPercentage = Math.abs(mStartTrim - mEndTrim) / MAX_PROGRESS_ARC;
float topIncrement = DECELERATE_INTERPOLATOR.getInterpolation(renderPercentage) - LINEAR_INTERPOLATOR.getInterpolation(renderPercentage);
float bottomIncrement = ACCELERATE_INTERPOLATOR.getInterpolation(renderPercentage) - LINEAR_INTERPOLATOR.getInterpolation(renderPercentage);
mPaint.setColor(mLevel1Color);
canvas.drawArc(arcBounds, endAngle, -sweepAngle * (1 + topIncrement), false, mPaint);
mPaint.setColor(mLevel2Color);
canvas.drawArc(arcBounds, endAngle, -sweepAngle * LEVEL2_SWEEP_ANGLE_OFFSET, false, mPaint);
mPaint.setColor(mLevel3Color);
canvas.drawArc(arcBounds, endAngle, -sweepAngle * LEVEL3_SWEEP_ANGLE_OFFSET * (1 + bottomIncrement), false, mPaint);
} else {
float renderPercentage = Math.abs(mStartTrim - mEndTrim) / MAX_PROGRESS_ARC;
float totalSweepAngle = MAX_PROGRESS_ARC * DEGREE_360;
if (renderPercentage > LEVEL2_SWEEP_ANGLE_OFFSET) {
mPaint.setColor(mLevel1Color);
canvas.drawArc(arcBounds, endAngle, -sweepAngle, false, mPaint);
mPaint.setColor(mLevel2Color);
canvas.drawArc(arcBounds, endAngle, totalSweepAngle * LEVEL2_SWEEP_ANGLE_OFFSET, false, mPaint);
mPaint.setColor(mLevel3Color);
canvas.drawArc(arcBounds, endAngle, totalSweepAngle * LEVEL3_SWEEP_ANGLE_OFFSET, false, mPaint);
} else if (renderPercentage > LEVEL3_SWEEP_ANGLE_OFFSET) {
mPaint.setColor(mLevel2Color);
canvas.drawArc(arcBounds, endAngle, -sweepAngle, false, mPaint);
mPaint.setColor(mLevel3Color);
canvas.drawArc(arcBounds, endAngle, totalSweepAngle * LEVEL3_SWEEP_ANGLE_OFFSET, false, mPaint);
} else {
mPaint.setColor(mLevel3Color);
canvas.drawArc(arcBounds, endAngle, -sweepAngle, false, mPaint);
}
}
canvas.restoreToCount(saveCount);
}
@Override
public void computeRender(float renderProgress) {
final float minProgressArc = getMinProgressArc();
final float originEndTrim = mOriginEndTrim;
final float originStartTrim = mOriginStartTrim;
final float originRotation = mOriginRotation;
// Moving the start trim only occurs in the first 50% of a
// single ring animation
if (renderProgress <= START_TRIM_DURATION_OFFSET) {
float startTrimProgress = (renderProgress) / START_TRIM_DURATION_OFFSET;
mStartTrim = originStartTrim + ((MAX_PROGRESS_ARC - minProgressArc) * MATERIAL_INTERPOLATOR.getInterpolation(startTrimProgress));
mIsRenderingFirstHalf = true;
}
// Moving the end trim starts after 50% of a single ring
// animation completes
if (renderProgress > END_TRIM_START_DELAY_OFFSET) {
float endTrimProgress = (renderProgress - START_TRIM_DURATION_OFFSET) / (1.0f - START_TRIM_DURATION_OFFSET);
mEndTrim = originEndTrim + ((MAX_PROGRESS_ARC - minProgressArc) * MATERIAL_INTERPOLATOR.getInterpolation(endTrimProgress));
mIsRenderingFirstHalf = false;
}
mGroupRotation = ((FULL_ROTATION / NUM_POINTS) * renderProgress) + (FULL_ROTATION * (mRotationCount / NUM_POINTS));
mRotation = originRotation + (ROTATION_FACTOR * renderProgress);
invalidateSelf();
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
invalidateSelf();
}
@Override
public void reset() {
resetOriginals();
}
public void setColor(int color) {
mLevel1Color = oneThirdAlphaColor(color);
mLevel2Color = twoThirdAlphaColor(color);
mLevel3Color = color;
}
@Override
public void setStrokeWidth(float strokeWidth) {
super.setStrokeWidth(strokeWidth);
mPaint.setStrokeWidth(strokeWidth);
invalidateSelf();
}
public void setStartTrim(float startTrim) {
mStartTrim = startTrim;
invalidateSelf();
}
public float getStartTrim() {
return mStartTrim;
}
public void setEndTrim(float endTrim) {
mEndTrim = endTrim;
invalidateSelf();
}
public float getEndTrim() {
return mEndTrim;
}
public void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
public float getRotation() {
return mRotation;
}
public void setInsets(int width, int height) {
final float minEdge = (float) Math.min(width, height);
float insets;
if (getCenterRadius() <= 0 || minEdge < 0) {
insets = (float) Math.ceil(getStrokeWidth() / 2.0f);
} else {
insets = minEdge / 2.0f - getCenterRadius();
}
mStrokeInset = insets;
}
public float getOriginRotation() {
return mOriginRotation;
}
public void storeOriginals() {
mOriginStartTrim = mStartTrim;
mOriginEndTrim = mEndTrim;
mOriginRotation = mRotation;
}
public void resetOriginals() {
mOriginStartTrim = 0;
mOriginEndTrim = 0;
mOriginRotation = 0;
setStartTrim(0);
setEndTrim(0);
setRotation(0);
}
private float getMinProgressArc() {
return (float) Math.toRadians(getStrokeWidth() / (2 * Math.PI * getCenterRadius()));
}
private int oneThirdAlphaColor(int colorValue) {
int startA = (colorValue >> 24) & 0xff;
int startR = (colorValue >> 16) & 0xff;
int startG = (colorValue >> 8) & 0xff;
int startB = colorValue & 0xff;
return (startA / 3 << 24)
| (startR << 16)
| (startG << 8)
| startB;
}
private int twoThirdAlphaColor(int colorValue) {
int startA = (colorValue >> 24) & 0xff;
int startR = (colorValue >> 16) & 0xff;
int startG = (colorValue >> 8) & 0xff;
int startB = colorValue & 0xff;
return (startA * 2 / 3 << 24)
| (startR << 16)
| (startG << 8)
| startB;
}
}
|
3e17a30a86f591811e894aace3175ebf52a91129 | 2,591 | java | Java | editor/src/main/java/io/github/rosemoe/sora/widget/component/CompletionLayout.java | Rose2073/CodeEditor | 962e3c00f6ae3ff915e49a5f8c1b72b36b37586d | [
"Apache-2.0"
] | 22 | 2020-02-27T09:28:41.000Z | 2020-07-10T08:05:25.000Z | editor/src/main/java/io/github/rosemoe/sora/widget/component/CompletionLayout.java | Rose2073/CodeEditor | 962e3c00f6ae3ff915e49a5f8c1b72b36b37586d | [
"Apache-2.0"
] | 4 | 2020-05-07T05:19:09.000Z | 2020-06-13T11:40:38.000Z | editor/src/main/java/io/github/rosemoe/sora/widget/component/CompletionLayout.java | Rose2073/CodeEditor | 962e3c00f6ae3ff915e49a5f8c1b72b36b37586d | [
"Apache-2.0"
] | 3 | 2020-05-09T10:59:30.000Z | 2020-06-14T12:27:42.000Z | 33.649351 | 147 | 0.706291 | 10,063 | /*
* sora-editor - the awesome code editor for Android
* https://github.com/Rosemoe/sora-editor
* Copyright (C) 2020-2022 Rosemoe
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
* Please contact Rosemoe by email dycjh@example.com if you need
* additional information or have any questions
*/
package io.github.rosemoe.sora.widget.component;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import io.github.rosemoe.sora.widget.schemes.EditorColorScheme;
/**
* Manages layout of {@link EditorAutoCompletion}
* Can be set by {@link EditorAutoCompletion#setLayout(CompletionLayout)}
*
* The implementation of this class must call {@link EditorAutoCompletion#select(int)} to select the
* item in completion list when the user clicks one.
*/
@SuppressWarnings("rawtypes")
public interface CompletionLayout {
/**
* Color scheme changed
*/
void onApplyColorScheme(EditorColorScheme colorScheme);
/**
* Attach the {@link EditorAutoCompletion}.
* This is called first before other methods are called.
*/
void setEditorCompletion(EditorAutoCompletion completion);
/**
* Inflate the layout, return the view root.
*/
View inflate(Context context);
/**
* Get the {@link AdapterView} to display completion items
*/
AdapterView getCompletionList();
/**
* Set loading state.
* You may update your layout to show other contents
*/
void setLoading(boolean loading);
/**
* Make the given position visible
* @param position Item index
* @param incrementPixels If you scroll the layout, this is a recommended value of each scroll. {@link EditorCompletionAdapter#getItemHeight()}
*/
void ensureListPositionVisible(int position, int incrementPixels);
}
|
3e17a33e21e97d2174e282a37dc00252b66bc2bf | 1,948 | java | Java | app/src/main/java/cc/dobot/crtcpdemo/data/AlarmData.java | Dobot-Arm/TCP-IP-Android | d96fd52d2e1e08782fcf409c0d1c02ea85e23346 | [
"MIT"
] | null | null | null | app/src/main/java/cc/dobot/crtcpdemo/data/AlarmData.java | Dobot-Arm/TCP-IP-Android | d96fd52d2e1e08782fcf409c0d1c02ea85e23346 | [
"MIT"
] | null | null | null | app/src/main/java/cc/dobot/crtcpdemo/data/AlarmData.java | Dobot-Arm/TCP-IP-Android | d96fd52d2e1e08782fcf409c0d1c02ea85e23346 | [
"MIT"
] | null | null | null | 20.082474 | 97 | 0.5077 | 10,064 | package cc.dobot.crtcpdemo.data;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by x on 2018/8/6.
*/
public class AlarmData {
String id = "";
String type = "";
String level = "";
String reason = "";
String solution = "";
public AlarmData() {
}
public AlarmData(String id) {
this.id=id;
}
public AlarmData(String id, String type) {
this.id = id;
this.type = type;
}
public AlarmData(String id, String type, String level, String reason, String solution) {
this.id = id;
this.type = type;
this.level = level;
this.reason = reason;
this.solution = solution;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getSolution() {
return solution;
}
public void setSolution(String solution) {
this.solution = solution;
}
public String[] getStringArrays() {
return new String[]{
id,
type,
level,
reason,
solution
};
}
@Override
public String toString() {
return "TimeStamp=" +new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\n"+
"id=" + id + '\n' +
"type=" + type + '\n' +
"level=" + level + '\n' +
"reason=" + reason + '\n' +
"solution=" + solution + '\n';
}
}
|
3e17a35d0dfb95b89e648dbc3eedde4159a4cd39 | 2,107 | java | Java | cli-qpid-jms/src/main/java/com/redhat/mqe/jms/Tracing.java | jiridanek/cli-java | 9b2bdbeb334a24bed44ea486b65e469b69d6dde9 | [
"Apache-2.0"
] | 7 | 2017-10-25T10:26:21.000Z | 2020-11-28T07:05:28.000Z | cli-qpid-jms/src/main/java/com/redhat/mqe/jms/Tracing.java | rh-messaging/cli-java | a5d4264163b045628455388dea00ff779d2a5e3d | [
"Apache-2.0"
] | 200 | 2017-10-03T10:37:55.000Z | 2022-03-23T09:43:43.000Z | cli-qpid-jms/src/main/java/com/redhat/mqe/jms/Tracing.java | jiridanek/cli-java | 9b2bdbeb334a24bed44ea486b65e469b69d6dde9 | [
"Apache-2.0"
] | 8 | 2017-10-05T08:52:41.000Z | 2020-12-03T09:39:00.000Z | 35.711864 | 83 | 0.724727 | 10,065 | /*
* Copyright (c) 2019 Red Hat, Inc.
*
* 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 com.redhat.mqe.jms;
import io.jaegertracing.Configuration;
import io.jaegertracing.Configuration.ReporterConfiguration;
import io.jaegertracing.Configuration.SamplerConfiguration;
import io.jaegertracing.internal.JaegerTracer;
import io.jaegertracing.internal.samplers.ConstSampler;
import io.opentracing.util.GlobalTracer;
public final class Tracing {
private Tracing() {
}
public static JaegerTracer init(String service) {
SamplerConfiguration samplerConfig = SamplerConfiguration.fromEnv()
.withType(ConstSampler.TYPE)
.withParam(1);
ReporterConfiguration reporterConfig = ReporterConfiguration.fromEnv()
.withLogSpans(true);
Configuration config = Configuration.fromEnv(service)
.withSampler(samplerConfig)
.withReporter(reporterConfig);
String agentHost = System.getenv("JAEGER_AGENT_HOST");
if (agentHost != null) {
config.getReporter().getSenderConfiguration().withAgentHost(agentHost);
}
return config.getTracer();
}
public static JaegerTracer register(String service) {
JaegerTracer tracer = Tracing.init(service);
GlobalTracer.register(tracer);
return tracer;
}
}
|
3e17a38da2b34f90d1c0e7396ef39668654b118c | 15,166 | java | Java | pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnector.java | abhilashmandaliya/pulsar | 2e4bada632af2f15a2882e9684c6376a4d8ba2a5 | [
"Apache-2.0"
] | 9,156 | 2018-09-23T14:10:46.000Z | 2022-03-31T07:17:16.000Z | pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnector.java | abhilashmandaliya/pulsar | 2e4bada632af2f15a2882e9684c6376a4d8ba2a5 | [
"Apache-2.0"
] | 10,453 | 2018-09-22T00:31:02.000Z | 2022-03-31T20:02:09.000Z | pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/http/AsyncHttpConnector.java | abhilashmandaliya/pulsar | 2e4bada632af2f15a2882e9684c6376a4d8ba2a5 | [
"Apache-2.0"
] | 2,730 | 2018-09-25T05:46:22.000Z | 2022-03-31T06:48:59.000Z | 45.271642 | 119 | 0.615785 | 10,066 | /**
* 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.pulsar.client.admin.internal.http;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.ssl.SslContext;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response.Status;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.PulsarVersion;
import org.apache.pulsar.client.admin.internal.PulsarAdminImpl;
import org.apache.pulsar.client.api.AuthenticationDataProvider;
import org.apache.pulsar.client.api.KeyStoreParams;
import org.apache.pulsar.client.impl.PulsarServiceNameResolver;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.common.util.FutureUtil;
import org.apache.pulsar.common.util.SecurityUtility;
import org.apache.pulsar.common.util.keystoretls.KeyStoreSSLContext;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
import org.asynchttpclient.Request;
import org.asynchttpclient.Response;
import org.asynchttpclient.channel.DefaultKeepAliveStrategy;
import org.asynchttpclient.netty.ssl.JsseSslEngineFactory;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.ClientRequest;
import org.glassfish.jersey.client.ClientResponse;
import org.glassfish.jersey.client.spi.AsyncConnectorCallback;
import org.glassfish.jersey.client.spi.Connector;
/**
* Customized Jersey client connector with multi-host support.
*/
@Slf4j
public class AsyncHttpConnector implements Connector {
private static final TimeoutException READ_TIMEOUT_EXCEPTION =
FutureUtil.createTimeoutException("Read timeout", AsyncHttpConnector.class, "retryOrTimeout(...)");
@Getter
private final AsyncHttpClient httpClient;
private final Duration readTimeout;
private final int maxRetries;
private final PulsarServiceNameResolver serviceNameResolver;
private final ScheduledExecutorService delayer = Executors.newScheduledThreadPool(1,
new DefaultThreadFactory("delayer"));
public AsyncHttpConnector(Client client, ClientConfigurationData conf, int autoCertRefreshTimeSeconds) {
this((int) client.getConfiguration().getProperty(ClientProperties.CONNECT_TIMEOUT),
(int) client.getConfiguration().getProperty(ClientProperties.READ_TIMEOUT),
PulsarAdminImpl.DEFAULT_REQUEST_TIMEOUT_SECONDS * 1000,
autoCertRefreshTimeSeconds,
conf);
}
@SneakyThrows
public AsyncHttpConnector(int connectTimeoutMs, int readTimeoutMs,
int requestTimeoutMs,
int autoCertRefreshTimeSeconds, ClientConfigurationData conf) {
DefaultAsyncHttpClientConfig.Builder confBuilder = new DefaultAsyncHttpClientConfig.Builder();
confBuilder.setFollowRedirect(true);
confBuilder.setRequestTimeout(conf.getRequestTimeoutMs());
confBuilder.setConnectTimeout(connectTimeoutMs);
confBuilder.setReadTimeout(readTimeoutMs);
confBuilder.setUserAgent(String.format("Pulsar-Java-v%s", PulsarVersion.getVersion()));
confBuilder.setRequestTimeout(requestTimeoutMs);
confBuilder.setIoThreadsCount(conf.getNumIoThreads());
confBuilder.setKeepAliveStrategy(new DefaultKeepAliveStrategy() {
@Override
public boolean keepAlive(InetSocketAddress remoteAddress, Request ahcRequest,
HttpRequest request, HttpResponse response) {
// Close connection upon a server error or per HTTP spec
return (response.status().code() / 100 != 5)
&& super.keepAlive(remoteAddress, ahcRequest, request, response);
}
});
serviceNameResolver = new PulsarServiceNameResolver();
if (conf != null && StringUtils.isNotBlank(conf.getServiceUrl())) {
serviceNameResolver.updateServiceUrl(conf.getServiceUrl());
if (conf.getServiceUrl().startsWith("https://")) {
// Set client key and certificate if available
AuthenticationDataProvider authData = conf.getAuthentication().getAuthData();
if (conf.isUseKeyStoreTls()) {
KeyStoreParams params = authData.hasDataForTls() ? authData.getTlsKeyStoreParams() : null;
final SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
conf.getSslProvider(),
params != null ? params.getKeyStoreType() : null,
params != null ? params.getKeyStorePath() : null,
params != null ? params.getKeyStorePassword() : null,
conf.isTlsAllowInsecureConnection() || !conf.isTlsHostnameVerificationEnable(),
conf.getTlsTrustStoreType(),
conf.getTlsTrustStorePath(),
conf.getTlsTrustStorePassword(),
conf.getTlsCiphers(),
conf.getTlsProtocols());
JsseSslEngineFactory sslEngineFactory = new JsseSslEngineFactory(sslCtx);
confBuilder.setSslEngineFactory(sslEngineFactory);
} else {
SslContext sslCtx = null;
if (authData.hasDataForTls()) {
sslCtx = authData.getTlsTrustStoreStream() == null
? SecurityUtility.createAutoRefreshSslContextForClient(
conf.isTlsAllowInsecureConnection() || !conf.isTlsHostnameVerificationEnable(),
conf.getTlsTrustCertsFilePath(), authData.getTlsCerificateFilePath(),
authData.getTlsPrivateKeyFilePath(), null, autoCertRefreshTimeSeconds, delayer)
: SecurityUtility.createNettySslContextForClient(
conf.isTlsAllowInsecureConnection() || !conf.isTlsHostnameVerificationEnable(),
authData.getTlsTrustStoreStream(), authData.getTlsCertificates(),
authData.getTlsPrivateKey());
} else {
sslCtx = SecurityUtility.createNettySslContextForClient(
conf.isTlsAllowInsecureConnection() || !conf.isTlsHostnameVerificationEnable(),
conf.getTlsTrustCertsFilePath());
}
confBuilder.setSslContext(sslCtx);
}
}
}
httpClient = new DefaultAsyncHttpClient(confBuilder.build());
this.readTimeout = Duration.ofMillis(readTimeoutMs);
this.maxRetries = httpClient.getConfig().getMaxRequestRetry();
}
@Override
public ClientResponse apply(ClientRequest jerseyRequest) {
CompletableFuture<ClientResponse> future = new CompletableFuture<>();
apply(jerseyRequest, new AsyncConnectorCallback() {
@Override
public void response(ClientResponse response) {
future.complete(response);
}
@Override
public void failure(Throwable failure) {
future.completeExceptionally(failure);
}
});
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
log.error(e.getMessage());
}
return null;
}
private URI replaceWithNew(InetSocketAddress address, URI uri) {
String originalUri = uri.toString();
String newUri = (originalUri.split(":")[0] + "://")
+ address.getHostName() + ":"
+ address.getPort()
+ uri.getRawPath();
if (uri.getRawQuery() != null) {
newUri += "?" + uri.getRawQuery();
}
return URI.create(newUri);
}
@Override
public Future<?> apply(ClientRequest jerseyRequest, AsyncConnectorCallback callback) {
CompletableFuture<Response> responseFuture = retryOrTimeOut(jerseyRequest);
responseFuture.whenComplete(((response, throwable) -> {
if (throwable != null) {
callback.failure(throwable);
} else {
ClientResponse jerseyResponse =
new ClientResponse(Status.fromStatusCode(response.getStatusCode()), jerseyRequest);
jerseyResponse.setStatusInfo(new javax.ws.rs.core.Response.StatusType() {
@Override
public int getStatusCode() {
return response.getStatusCode();
}
@Override
public Status.Family getFamily() {
return Status.Family.familyOf(response.getStatusCode());
}
@Override
public String getReasonPhrase() {
return response.getStatusText();
}
});
response.getHeaders().forEach(e -> jerseyResponse.header(e.getKey(), e.getValue()));
if (response.hasResponseBody()) {
jerseyResponse.setEntityStream(response.getResponseBodyAsStream());
}
callback.response(jerseyResponse);
}
}));
return responseFuture;
}
private CompletableFuture<Response> retryOrTimeOut(ClientRequest request) {
final CompletableFuture<Response> resultFuture = new CompletableFuture<>();
retryOperation(resultFuture, () -> oneShot(serviceNameResolver.resolveHost(), request), maxRetries);
CompletableFuture<Response> timeoutAfter = FutureUtil.createFutureWithTimeout(readTimeout, delayer,
() -> READ_TIMEOUT_EXCEPTION);
return resultFuture.applyToEither(timeoutAfter, Function.identity());
}
private <T> void retryOperation(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final int retries) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationFuture = operation.get();
operationFuture.whenComplete(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException("Operation future was cancelled.", throwable));
} else {
if (retries > 0) {
retryOperation(
resultFuture,
operation,
retries - 1);
} else {
resultFuture.completeExceptionally(
new RetryException("Could not complete the operation. Number of retries "
+ "has been exhausted. Failed reason: " + throwable.getMessage(),
throwable));
}
}
} else {
resultFuture.complete(t);
}
});
resultFuture.whenComplete(
(t, throwable) -> operationFuture.cancel(false));
}
}
/**
* Retry Exception.
*/
public static class RetryException extends Exception {
public RetryException(String message, Throwable cause) {
super(message, cause);
}
}
private CompletableFuture<Response> oneShot(InetSocketAddress host, ClientRequest request) {
ClientRequest currentRequest = new ClientRequest(request);
URI newUri = replaceWithNew(host, currentRequest.getUri());
currentRequest.setUri(newUri);
BoundRequestBuilder builder =
httpClient.prepare(currentRequest.getMethod(), currentRequest.getUri().toString());
if (currentRequest.hasEntity()) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
currentRequest.setStreamProvider(contentLength -> outStream);
try {
currentRequest.writeEntity();
} catch (IOException e) {
CompletableFuture<Response> r = new CompletableFuture<>();
r.completeExceptionally(e);
return r;
}
builder.setBody(outStream.toByteArray());
}
currentRequest.getHeaders().forEach((key, headers) -> {
if (!HttpHeaders.USER_AGENT.equals(key)) {
builder.addHeader(key, headers);
}
});
return builder.execute().toCompletableFuture();
}
@Override
public String getName() {
return "Pulsar-Admin";
}
@Override
public void close() {
try {
httpClient.close();
delayer.shutdownNow();
} catch (IOException e) {
log.warn("Failed to close http client", e);
}
}
}
|
3e17a3ba6914cc8edecaff76982d01c654e92288 | 706 | java | Java | src/main/java/com/ab/worldcup/results/CalculatedUserBet.java | yoav200/world-cup | c6b754a48ce126cd1dd005c15992000e1e8fc1f1 | [
"MIT"
] | null | null | null | src/main/java/com/ab/worldcup/results/CalculatedUserBet.java | yoav200/world-cup | c6b754a48ce126cd1dd005c15992000e1e8fc1f1 | [
"MIT"
] | 1 | 2018-04-21T14:29:47.000Z | 2018-05-17T10:54:14.000Z | src/main/java/com/ab/worldcup/results/CalculatedUserBet.java | yoav200/world-cup | c6b754a48ce126cd1dd005c15992000e1e8fc1f1 | [
"MIT"
] | null | null | null | 19.081081 | 77 | 0.729462 | 10,067 | package com.ab.worldcup.results;
import com.ab.worldcup.bet.BetType;
import com.ab.worldcup.bet.UserBet;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class CalculatedUserBet {
UserBet userBet;
BetType betType;
int matchResultPoints;
int exactScorePoints;
int correctQualifierPoints;
BetCorrectnessTypeEnum isCorrectQualifier;
public boolean isMatchResultCorrect(){
return matchResultPoints > 0;
}
public boolean isExactScoreCorrect(){
return exactScorePoints > 0;
}
public int getTotalPoints(){
return matchResultPoints + exactScorePoints + correctQualifierPoints;
}
}
|
3e17a4360aa7c43e2063b701585e4e37e52ee0f8 | 406 | java | Java | src/main/java/com/hutquan/hut/pojo/FollowerPage.java | TanDawn1/HUT_quanquan | ccc9578fa57d77aa3a0a96f971f70e21c41396f6 | [
"BSD-2-Clause"
] | 10 | 2020-11-27T16:35:06.000Z | 2022-02-24T08:03:00.000Z | src/main/java/com/hutquan/hut/pojo/FollowerPage.java | TanDawn1/HUT_quanquan | ccc9578fa57d77aa3a0a96f971f70e21c41396f6 | [
"BSD-2-Clause"
] | 2 | 2021-03-19T20:27:36.000Z | 2021-06-04T02:58:06.000Z | src/main/java/com/hutquan/hut/pojo/FollowerPage.java | TanDawn1/HUT_quanquan | ccc9578fa57d77aa3a0a96f971f70e21c41396f6 | [
"BSD-2-Clause"
] | 2 | 2020-11-27T16:39:24.000Z | 2022-02-05T11:45:10.000Z | 14 | 37 | 0.741379 | 10,068 | package com.hutquan.hut.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FollowerPage {
private List<Follower> followers;
private long total;
private Long pageNum;
private long pages;
private int size;
private Long start;
private Long end;
}
|
3e17a522e97f6911f0df0b1de4306907af2c913a | 415 | java | Java | app/src/main/java/com/android/grafika/GrafikaApplication.java | zhmy/grafika | 48b773e91fbb17feb387497261bcefd27394ab5b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/grafika/GrafikaApplication.java | zhmy/grafika | 48b773e91fbb17feb387497261bcefd27394ab5b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/grafika/GrafikaApplication.java | zhmy/grafika | 48b773e91fbb17feb387497261bcefd27394ab5b | [
"Apache-2.0"
] | null | null | null | 17.291667 | 53 | 0.66988 | 10,069 | package com.android.grafika;
import android.app.Application;
import android.content.Context;
/**
* Created by zmy on 2018/3/26.
*/
public class GrafikaApplication extends Application {
static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
|
3e17a52e250e3cfcde6e323fa0e957d96e48498b | 9,895 | java | Java | src/main/java/com/cloudbees/lxd/client/api/ServerEnvironment.java | cloudbees/lxd-client | 4ecd9774117f0e4f49895732f727545c3024a410 | [
"MIT"
] | null | null | null | src/main/java/com/cloudbees/lxd/client/api/ServerEnvironment.java | cloudbees/lxd-client | 4ecd9774117f0e4f49895732f727545c3024a410 | [
"MIT"
] | null | null | null | src/main/java/com/cloudbees/lxd/client/api/ServerEnvironment.java | cloudbees/lxd-client | 4ecd9774117f0e4f49895732f727545c3024a410 | [
"MIT"
] | 2 | 2018-04-17T10:14:50.000Z | 2022-03-05T06:29:58.000Z | 20.193878 | 329 | 0.57241 | 10,070 |
package com.cloudbees.lxd.client.api;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
*
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"addresses",
"architectures",
"certificate",
"certificate_fingerprint",
"driver",
"driver_version",
"kernel",
"kernel_architecture",
"kernel_version",
"server",
"server_pid",
"server_version",
"storage",
"storage_version"
})
public class ServerEnvironment implements Serializable
{
/**
*
*
*/
@JsonProperty("addresses")
private List<String> addresses = new ArrayList<String>();
/**
*
*
*/
@JsonProperty("architectures")
private List<String> architectures = new ArrayList<String>();
/**
*
*
*/
@JsonProperty("certificate")
private String certificate;
/**
*
*
*/
@JsonProperty("certificate_fingerprint")
private String certificateFingerprint;
/**
*
*
*/
@JsonProperty("driver")
private String driver;
/**
*
*
*/
@JsonProperty("driver_version")
private String driverVersion;
/**
*
*
*/
@JsonProperty("kernel")
private String kernel;
/**
*
*
*/
@JsonProperty("kernel_architecture")
private String kernelArchitecture;
/**
*
*
*/
@JsonProperty("kernel_version")
private String kernelVersion;
/**
*
*
*/
@JsonProperty("server")
private String server;
/**
*
*
*/
@JsonProperty("server_pid")
private Integer serverPid;
/**
*
*
*/
@JsonProperty("server_version")
private String serverVersion;
/**
*
*
*/
@JsonProperty("storage")
private String storage;
/**
*
*
*/
@JsonProperty("storage_version")
private String storageVersion;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public ServerEnvironment() {
}
/**
*
* @param architectures
* @param certificateFingerprint
* @param server
* @param addresses
* @param serverVersion
* @param storageVersion
* @param kernel
* @param certificate
* @param kernelArchitecture
* @param storage
* @param serverPid
* @param driver
* @param driverVersion
* @param kernelVersion
*/
public ServerEnvironment(List<String> addresses, List<String> architectures, String certificate, String certificateFingerprint, String driver, String driverVersion, String kernel, String kernelArchitecture, String kernelVersion, String server, Integer serverPid, String serverVersion, String storage, String storageVersion) {
this.addresses = addresses;
this.architectures = architectures;
this.certificate = certificate;
this.certificateFingerprint = certificateFingerprint;
this.driver = driver;
this.driverVersion = driverVersion;
this.kernel = kernel;
this.kernelArchitecture = kernelArchitecture;
this.kernelVersion = kernelVersion;
this.server = server;
this.serverPid = serverPid;
this.serverVersion = serverVersion;
this.storage = storage;
this.storageVersion = storageVersion;
}
/**
*
*
* @return
* The addresses
*/
@JsonProperty("addresses")
public List<String> getAddresses() {
return addresses;
}
/**
*
*
* @param addresses
* The addresses
*/
@JsonProperty("addresses")
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
/**
*
*
* @return
* The architectures
*/
@JsonProperty("architectures")
public List<String> getArchitectures() {
return architectures;
}
/**
*
*
* @param architectures
* The architectures
*/
@JsonProperty("architectures")
public void setArchitectures(List<String> architectures) {
this.architectures = architectures;
}
/**
*
*
* @return
* The certificate
*/
@JsonProperty("certificate")
public String getCertificate() {
return certificate;
}
/**
*
*
* @param certificate
* The certificate
*/
@JsonProperty("certificate")
public void setCertificate(String certificate) {
this.certificate = certificate;
}
/**
*
*
* @return
* The certificateFingerprint
*/
@JsonProperty("certificate_fingerprint")
public String getCertificateFingerprint() {
return certificateFingerprint;
}
/**
*
*
* @param certificateFingerprint
* The certificate_fingerprint
*/
@JsonProperty("certificate_fingerprint")
public void setCertificateFingerprint(String certificateFingerprint) {
this.certificateFingerprint = certificateFingerprint;
}
/**
*
*
* @return
* The driver
*/
@JsonProperty("driver")
public String getDriver() {
return driver;
}
/**
*
*
* @param driver
* The driver
*/
@JsonProperty("driver")
public void setDriver(String driver) {
this.driver = driver;
}
/**
*
*
* @return
* The driverVersion
*/
@JsonProperty("driver_version")
public String getDriverVersion() {
return driverVersion;
}
/**
*
*
* @param driverVersion
* The driver_version
*/
@JsonProperty("driver_version")
public void setDriverVersion(String driverVersion) {
this.driverVersion = driverVersion;
}
/**
*
*
* @return
* The kernel
*/
@JsonProperty("kernel")
public String getKernel() {
return kernel;
}
/**
*
*
* @param kernel
* The kernel
*/
@JsonProperty("kernel")
public void setKernel(String kernel) {
this.kernel = kernel;
}
/**
*
*
* @return
* The kernelArchitecture
*/
@JsonProperty("kernel_architecture")
public String getKernelArchitecture() {
return kernelArchitecture;
}
/**
*
*
* @param kernelArchitecture
* The kernel_architecture
*/
@JsonProperty("kernel_architecture")
public void setKernelArchitecture(String kernelArchitecture) {
this.kernelArchitecture = kernelArchitecture;
}
/**
*
*
* @return
* The kernelVersion
*/
@JsonProperty("kernel_version")
public String getKernelVersion() {
return kernelVersion;
}
/**
*
*
* @param kernelVersion
* The kernel_version
*/
@JsonProperty("kernel_version")
public void setKernelVersion(String kernelVersion) {
this.kernelVersion = kernelVersion;
}
/**
*
*
* @return
* The server
*/
@JsonProperty("server")
public String getServer() {
return server;
}
/**
*
*
* @param server
* The server
*/
@JsonProperty("server")
public void setServer(String server) {
this.server = server;
}
/**
*
*
* @return
* The serverPid
*/
@JsonProperty("server_pid")
public Integer getServerPid() {
return serverPid;
}
/**
*
*
* @param serverPid
* The server_pid
*/
@JsonProperty("server_pid")
public void setServerPid(Integer serverPid) {
this.serverPid = serverPid;
}
/**
*
*
* @return
* The serverVersion
*/
@JsonProperty("server_version")
public String getServerVersion() {
return serverVersion;
}
/**
*
*
* @param serverVersion
* The server_version
*/
@JsonProperty("server_version")
public void setServerVersion(String serverVersion) {
this.serverVersion = serverVersion;
}
/**
*
*
* @return
* The storage
*/
@JsonProperty("storage")
public String getStorage() {
return storage;
}
/**
*
*
* @param storage
* The storage
*/
@JsonProperty("storage")
public void setStorage(String storage) {
this.storage = storage;
}
/**
*
*
* @return
* The storageVersion
*/
@JsonProperty("storage_version")
public String getStorageVersion() {
return storageVersion;
}
/**
*
*
* @param storageVersion
* The storage_version
*/
@JsonProperty("storage_version")
public void setStorageVersion(String storageVersion) {
this.storageVersion = storageVersion;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
3e17a568b0744fde1e79d91b37aade73c70eb06c | 48,103 | java | Java | proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/ExecutionConfig.java | vam-google/java-dataproc | 3d4c12581a2e7bd7b0d2673d9f88d3df8e29a897 | [
"Apache-2.0"
] | 10 | 2020-01-24T11:24:44.000Z | 2022-01-26T17:00:53.000Z | proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/ExecutionConfig.java | vam-google/java-dataproc | 3d4c12581a2e7bd7b0d2673d9f88d3df8e29a897 | [
"Apache-2.0"
] | 548 | 2019-10-31T17:54:33.000Z | 2022-03-30T08:32:18.000Z | proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/ExecutionConfig.java | vam-google/java-dataproc | 3d4c12581a2e7bd7b0d2673d9f88d3df8e29a897 | [
"Apache-2.0"
] | 23 | 2019-10-31T17:24:21.000Z | 2022-03-02T04:49:01.000Z | 29.313224 | 100 | 0.627487 | 10,071 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataproc/v1/shared.proto
package com.google.cloud.dataproc.v1;
/**
*
*
* <pre>
* Execution configuration for a workload.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.ExecutionConfig}
*/
public final class ExecutionConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.ExecutionConfig)
ExecutionConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use ExecutionConfig.newBuilder() to construct.
private ExecutionConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ExecutionConfig() {
serviceAccount_ = "";
networkTags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
kmsKey_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ExecutionConfig();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ExecutionConfig(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
serviceAccount_ = s;
break;
}
case 34:
{
java.lang.String s = input.readStringRequireUtf8();
networkCase_ = 4;
network_ = s;
break;
}
case 42:
{
java.lang.String s = input.readStringRequireUtf8();
networkCase_ = 5;
network_ = s;
break;
}
case 50:
{
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
networkTags_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000001;
}
networkTags_.add(s);
break;
}
case 58:
{
java.lang.String s = input.readStringRequireUtf8();
kmsKey_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
networkTags_ = networkTags_.getUnmodifiableView();
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataproc.v1.SharedProto
.internal_static_google_cloud_dataproc_v1_ExecutionConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.SharedProto
.internal_static_google_cloud_dataproc_v1_ExecutionConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.ExecutionConfig.class,
com.google.cloud.dataproc.v1.ExecutionConfig.Builder.class);
}
private int networkCase_ = 0;
private java.lang.Object network_;
public enum NetworkCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
NETWORK_URI(4),
SUBNETWORK_URI(5),
NETWORK_NOT_SET(0);
private final int value;
private NetworkCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static NetworkCase valueOf(int value) {
return forNumber(value);
}
public static NetworkCase forNumber(int value) {
switch (value) {
case 4:
return NETWORK_URI;
case 5:
return SUBNETWORK_URI;
case 0:
return NETWORK_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public NetworkCase getNetworkCase() {
return NetworkCase.forNumber(networkCase_);
}
public static final int SERVICE_ACCOUNT_FIELD_NUMBER = 2;
private volatile java.lang.Object serviceAccount_;
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The serviceAccount.
*/
@java.lang.Override
public java.lang.String getServiceAccount() {
java.lang.Object ref = serviceAccount_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceAccount_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for serviceAccount.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceAccountBytes() {
java.lang.Object ref = serviceAccount_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceAccount_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NETWORK_URI_FIELD_NUMBER = 4;
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the networkUri field is set.
*/
public boolean hasNetworkUri() {
return networkCase_ == 4;
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The networkUri.
*/
public java.lang.String getNetworkUri() {
java.lang.Object ref = "";
if (networkCase_ == 4) {
ref = network_;
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (networkCase_ == 4) {
network_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for networkUri.
*/
public com.google.protobuf.ByteString getNetworkUriBytes() {
java.lang.Object ref = "";
if (networkCase_ == 4) {
ref = network_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (networkCase_ == 4) {
network_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SUBNETWORK_URI_FIELD_NUMBER = 5;
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the subnetworkUri field is set.
*/
public boolean hasSubnetworkUri() {
return networkCase_ == 5;
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The subnetworkUri.
*/
public java.lang.String getSubnetworkUri() {
java.lang.Object ref = "";
if (networkCase_ == 5) {
ref = network_;
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (networkCase_ == 5) {
network_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for subnetworkUri.
*/
public com.google.protobuf.ByteString getSubnetworkUriBytes() {
java.lang.Object ref = "";
if (networkCase_ == 5) {
ref = network_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (networkCase_ == 5) {
network_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NETWORK_TAGS_FIELD_NUMBER = 6;
private com.google.protobuf.LazyStringList networkTags_;
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the networkTags.
*/
public com.google.protobuf.ProtocolStringList getNetworkTagsList() {
return networkTags_;
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of networkTags.
*/
public int getNetworkTagsCount() {
return networkTags_.size();
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The networkTags at the given index.
*/
public java.lang.String getNetworkTags(int index) {
return networkTags_.get(index);
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the networkTags at the given index.
*/
public com.google.protobuf.ByteString getNetworkTagsBytes(int index) {
return networkTags_.getByteString(index);
}
public static final int KMS_KEY_FIELD_NUMBER = 7;
private volatile java.lang.Object kmsKey_;
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The kmsKey.
*/
@java.lang.Override
public java.lang.String getKmsKey() {
java.lang.Object ref = kmsKey_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
kmsKey_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for kmsKey.
*/
@java.lang.Override
public com.google.protobuf.ByteString getKmsKeyBytes() {
java.lang.Object ref = kmsKey_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
kmsKey_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceAccount_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, serviceAccount_);
}
if (networkCase_ == 4) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, network_);
}
if (networkCase_ == 5) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, network_);
}
for (int i = 0; i < networkTags_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, networkTags_.getRaw(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kmsKey_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 7, kmsKey_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceAccount_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, serviceAccount_);
}
if (networkCase_ == 4) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, network_);
}
if (networkCase_ == 5) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, network_);
}
{
int dataSize = 0;
for (int i = 0; i < networkTags_.size(); i++) {
dataSize += computeStringSizeNoTag(networkTags_.getRaw(i));
}
size += dataSize;
size += 1 * getNetworkTagsList().size();
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kmsKey_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, kmsKey_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dataproc.v1.ExecutionConfig)) {
return super.equals(obj);
}
com.google.cloud.dataproc.v1.ExecutionConfig other =
(com.google.cloud.dataproc.v1.ExecutionConfig) obj;
if (!getServiceAccount().equals(other.getServiceAccount())) return false;
if (!getNetworkTagsList().equals(other.getNetworkTagsList())) return false;
if (!getKmsKey().equals(other.getKmsKey())) return false;
if (!getNetworkCase().equals(other.getNetworkCase())) return false;
switch (networkCase_) {
case 4:
if (!getNetworkUri().equals(other.getNetworkUri())) return false;
break;
case 5:
if (!getSubnetworkUri().equals(other.getSubnetworkUri())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + SERVICE_ACCOUNT_FIELD_NUMBER;
hash = (53 * hash) + getServiceAccount().hashCode();
if (getNetworkTagsCount() > 0) {
hash = (37 * hash) + NETWORK_TAGS_FIELD_NUMBER;
hash = (53 * hash) + getNetworkTagsList().hashCode();
}
hash = (37 * hash) + KMS_KEY_FIELD_NUMBER;
hash = (53 * hash) + getKmsKey().hashCode();
switch (networkCase_) {
case 4:
hash = (37 * hash) + NETWORK_URI_FIELD_NUMBER;
hash = (53 * hash) + getNetworkUri().hashCode();
break;
case 5:
hash = (37 * hash) + SUBNETWORK_URI_FIELD_NUMBER;
hash = (53 * hash) + getSubnetworkUri().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.ExecutionConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dataproc.v1.ExecutionConfig prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Execution configuration for a workload.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.ExecutionConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.ExecutionConfig)
com.google.cloud.dataproc.v1.ExecutionConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataproc.v1.SharedProto
.internal_static_google_cloud_dataproc_v1_ExecutionConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.SharedProto
.internal_static_google_cloud_dataproc_v1_ExecutionConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.ExecutionConfig.class,
com.google.cloud.dataproc.v1.ExecutionConfig.Builder.class);
}
// Construct using com.google.cloud.dataproc.v1.ExecutionConfig.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
serviceAccount_ = "";
networkTags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
kmsKey_ = "";
networkCase_ = 0;
network_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dataproc.v1.SharedProto
.internal_static_google_cloud_dataproc_v1_ExecutionConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ExecutionConfig getDefaultInstanceForType() {
return com.google.cloud.dataproc.v1.ExecutionConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ExecutionConfig build() {
com.google.cloud.dataproc.v1.ExecutionConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ExecutionConfig buildPartial() {
com.google.cloud.dataproc.v1.ExecutionConfig result =
new com.google.cloud.dataproc.v1.ExecutionConfig(this);
int from_bitField0_ = bitField0_;
result.serviceAccount_ = serviceAccount_;
if (networkCase_ == 4) {
result.network_ = network_;
}
if (networkCase_ == 5) {
result.network_ = network_;
}
if (((bitField0_ & 0x00000001) != 0)) {
networkTags_ = networkTags_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000001);
}
result.networkTags_ = networkTags_;
result.kmsKey_ = kmsKey_;
result.networkCase_ = networkCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dataproc.v1.ExecutionConfig) {
return mergeFrom((com.google.cloud.dataproc.v1.ExecutionConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataproc.v1.ExecutionConfig other) {
if (other == com.google.cloud.dataproc.v1.ExecutionConfig.getDefaultInstance()) return this;
if (!other.getServiceAccount().isEmpty()) {
serviceAccount_ = other.serviceAccount_;
onChanged();
}
if (!other.networkTags_.isEmpty()) {
if (networkTags_.isEmpty()) {
networkTags_ = other.networkTags_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureNetworkTagsIsMutable();
networkTags_.addAll(other.networkTags_);
}
onChanged();
}
if (!other.getKmsKey().isEmpty()) {
kmsKey_ = other.kmsKey_;
onChanged();
}
switch (other.getNetworkCase()) {
case NETWORK_URI:
{
networkCase_ = 4;
network_ = other.network_;
onChanged();
break;
}
case SUBNETWORK_URI:
{
networkCase_ = 5;
network_ = other.network_;
onChanged();
break;
}
case NETWORK_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.dataproc.v1.ExecutionConfig parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.dataproc.v1.ExecutionConfig) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int networkCase_ = 0;
private java.lang.Object network_;
public NetworkCase getNetworkCase() {
return NetworkCase.forNumber(networkCase_);
}
public Builder clearNetwork() {
networkCase_ = 0;
network_ = null;
onChanged();
return this;
}
private int bitField0_;
private java.lang.Object serviceAccount_ = "";
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The serviceAccount.
*/
public java.lang.String getServiceAccount() {
java.lang.Object ref = serviceAccount_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceAccount_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for serviceAccount.
*/
public com.google.protobuf.ByteString getServiceAccountBytes() {
java.lang.Object ref = serviceAccount_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceAccount_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The serviceAccount to set.
* @return This builder for chaining.
*/
public Builder setServiceAccount(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
serviceAccount_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearServiceAccount() {
serviceAccount_ = getDefaultInstance().getServiceAccount();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Service account that used to execute workload.
* </pre>
*
* <code>string service_account = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for serviceAccount to set.
* @return This builder for chaining.
*/
public Builder setServiceAccountBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
serviceAccount_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the networkUri field is set.
*/
@java.lang.Override
public boolean hasNetworkUri() {
return networkCase_ == 4;
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The networkUri.
*/
@java.lang.Override
public java.lang.String getNetworkUri() {
java.lang.Object ref = "";
if (networkCase_ == 4) {
ref = network_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (networkCase_ == 4) {
network_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for networkUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNetworkUriBytes() {
java.lang.Object ref = "";
if (networkCase_ == 4) {
ref = network_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (networkCase_ == 4) {
network_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The networkUri to set.
* @return This builder for chaining.
*/
public Builder setNetworkUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
networkCase_ = 4;
network_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearNetworkUri() {
if (networkCase_ == 4) {
networkCase_ = 0;
network_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Optional. Network URI to connect workload to.
* </pre>
*
* <code>string network_uri = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for networkUri to set.
* @return This builder for chaining.
*/
public Builder setNetworkUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
networkCase_ = 4;
network_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the subnetworkUri field is set.
*/
@java.lang.Override
public boolean hasSubnetworkUri() {
return networkCase_ == 5;
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The subnetworkUri.
*/
@java.lang.Override
public java.lang.String getSubnetworkUri() {
java.lang.Object ref = "";
if (networkCase_ == 5) {
ref = network_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (networkCase_ == 5) {
network_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for subnetworkUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSubnetworkUriBytes() {
java.lang.Object ref = "";
if (networkCase_ == 5) {
ref = network_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (networkCase_ == 5) {
network_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The subnetworkUri to set.
* @return This builder for chaining.
*/
public Builder setSubnetworkUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
networkCase_ = 5;
network_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearSubnetworkUri() {
if (networkCase_ == 5) {
networkCase_ = 0;
network_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Optional. Subnetwork URI to connect workload to.
* </pre>
*
* <code>string subnetwork_uri = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for subnetworkUri to set.
* @return This builder for chaining.
*/
public Builder setSubnetworkUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
networkCase_ = 5;
network_ = value;
onChanged();
return this;
}
private com.google.protobuf.LazyStringList networkTags_ =
com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureNetworkTagsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
networkTags_ = new com.google.protobuf.LazyStringArrayList(networkTags_);
bitField0_ |= 0x00000001;
}
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the networkTags.
*/
public com.google.protobuf.ProtocolStringList getNetworkTagsList() {
return networkTags_.getUnmodifiableView();
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of networkTags.
*/
public int getNetworkTagsCount() {
return networkTags_.size();
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The networkTags at the given index.
*/
public java.lang.String getNetworkTags(int index) {
return networkTags_.get(index);
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the networkTags at the given index.
*/
public com.google.protobuf.ByteString getNetworkTagsBytes(int index) {
return networkTags_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index to set the value at.
* @param value The networkTags to set.
* @return This builder for chaining.
*/
public Builder setNetworkTags(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureNetworkTagsIsMutable();
networkTags_.set(index, value);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The networkTags to add.
* @return This builder for chaining.
*/
public Builder addNetworkTags(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureNetworkTagsIsMutable();
networkTags_.add(value);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param values The networkTags to add.
* @return This builder for chaining.
*/
public Builder addAllNetworkTags(java.lang.Iterable<java.lang.String> values) {
ensureNetworkTagsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, networkTags_);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearNetworkTags() {
networkTags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Tags used for network traffic control.
* </pre>
*
* <code>repeated string network_tags = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes of the networkTags to add.
* @return This builder for chaining.
*/
public Builder addNetworkTagsBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureNetworkTagsIsMutable();
networkTags_.add(value);
onChanged();
return this;
}
private java.lang.Object kmsKey_ = "";
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The kmsKey.
*/
public java.lang.String getKmsKey() {
java.lang.Object ref = kmsKey_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
kmsKey_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for kmsKey.
*/
public com.google.protobuf.ByteString getKmsKeyBytes() {
java.lang.Object ref = kmsKey_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
kmsKey_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The kmsKey to set.
* @return This builder for chaining.
*/
public Builder setKmsKey(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
kmsKey_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearKmsKey() {
kmsKey_ = getDefaultInstance().getKmsKey();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Cloud KMS key to use for encryption.
* </pre>
*
* <code>string kms_key = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for kmsKey to set.
* @return This builder for chaining.
*/
public Builder setKmsKeyBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
kmsKey_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dataproc.v1.ExecutionConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.ExecutionConfig)
private static final com.google.cloud.dataproc.v1.ExecutionConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.ExecutionConfig();
}
public static com.google.cloud.dataproc.v1.ExecutionConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ExecutionConfig> PARSER =
new com.google.protobuf.AbstractParser<ExecutionConfig>() {
@java.lang.Override
public ExecutionConfig parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ExecutionConfig(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ExecutionConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ExecutionConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ExecutionConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
3e17a5a4cf93ebd33116248cce91df804ab9a33a | 1,525 | java | Java | eladmin-system/src/main/java/com/hqhop/modules/company/service/AccountService.java | TomZhang187/mdm | de3b400a263e63b014f8c4cb63e3ad7410a2d9cc | [
"Apache-2.0"
] | null | null | null | eladmin-system/src/main/java/com/hqhop/modules/company/service/AccountService.java | TomZhang187/mdm | de3b400a263e63b014f8c4cb63e3ad7410a2d9cc | [
"Apache-2.0"
] | null | null | null | eladmin-system/src/main/java/com/hqhop/modules/company/service/AccountService.java | TomZhang187/mdm | de3b400a263e63b014f8c4cb63e3ad7410a2d9cc | [
"Apache-2.0"
] | null | null | null | 21.478873 | 82 | 0.660328 | 10,072 | package com.hqhop.modules.company.service;
import com.hqhop.common.dingtalk.dingtalkVo.DingUser;
import com.hqhop.modules.company.domain.Account;
import com.hqhop.modules.company.service.dto.AccountDTO;
import com.hqhop.modules.company.service.dto.AccountQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import java.util.List;
/**
* @author zf
* @date 2019-11-06
*/
//@CacheConfig(cacheNames = "account")
public interface AccountService {
/**
* 查询数据分页
* @param criteria
* @param pageable
* @return
*/
//@Cacheable
Map<String,Object> queryAll(AccountQueryCriteria criteria, Pageable pageable);
/**
* 查询所有数据不分页
* @param criteria
* @return
*/
//@Cacheable
List<AccountDTO> queryAll(AccountQueryCriteria criteria);
/**
* 根据ID查询
* @param accountKey
* @return
*/
//@Cacheable(key = "#p0")
AccountDTO findById(Long accountKey);
/**
* 创建
* @param resources
* @return
*/
//@CacheEvict(allEntries = true)
Account create(Account resources);
/**
* 编辑
* @param resources
*/
//@CacheEvict(allEntries = true)
void update(Account resources);
/**
* 删除
* @param accountKey
*/
//@CacheEvict(allEntries = true)
void delete(Long accountKey);
@Transactional(rollbackFor = Exception.class)
String getDingUrl(Account resources, DingUser dingUser);
}
|
3e17a6d119c1cc7d195fdf856123bca87691f10b | 6,864 | java | Java | src/main/java/frc/robot/subsystems/MecanumDrivetrain.java | 1504/RapidReact2022 | 5b9a990589271c1031ac16282739683f12e9b4f0 | [
"BSD-3-Clause"
] | 1 | 2022-01-11T04:07:38.000Z | 2022-01-11T04:07:38.000Z | src/main/java/frc/robot/subsystems/MecanumDrivetrain.java | 1504/RapidReact2022 | 5b9a990589271c1031ac16282739683f12e9b4f0 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/subsystems/MecanumDrivetrain.java | 1504/RapidReact2022 | 5b9a990589271c1031ac16282739683f12e9b4f0 | [
"BSD-3-Clause"
] | 1 | 2022-01-11T23:21:38.000Z | 2022-01-11T23:21:38.000Z | 40.140351 | 125 | 0.758013 | 10,073 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.kauailabs.navx.frc.AHRS;
import com.revrobotics.CANSparkMax;
import com.revrobotics.RelativeEncoder;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import frc.robot.Constants.DriveConstants;
import frc.robot.Constants.BuildConstants;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.controller.SimpleMotorFeedforward;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.MecanumDriveKinematics;
import edu.wpi.first.math.kinematics.MecanumDriveOdometry;
import edu.wpi.first.math.kinematics.MecanumDriveWheelSpeeds;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.wpilibj.SPI;
import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard;
import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
public class MecanumDrivetrain extends SubsystemBase {
//Motor Controllers
private final CANSparkMax _front_left_motor;
private final CANSparkMax _front_right_motor;
private final CANSparkMax _back_right_motor;
private final CANSparkMax _back_left_motor;
//Encoders
private final RelativeEncoder _front_left_encoder;
private final RelativeEncoder _front_right_encoder;
private final RelativeEncoder _back_right_encoder;
private final RelativeEncoder _back_left_encoder;
//Wheel locations
private final Translation2d _front_left_location;
private final Translation2d _front_right_location;
private final Translation2d _back_right_location;
private final Translation2d _back_left_location;
//PIDs
private final PIDController _front_left_PID;
private final PIDController _front_right_PID;
private final PIDController _back_left_PID;
private final PIDController _back_right_PID;
//Feed Forward
private final SimpleMotorFeedforward _feedforward;
private final AHRS _gyro;
private final MecanumDriveKinematics _kinematics;
private final MecanumDriveOdometry _odometry;
private Pose2d _robot_position;
ShuffleboardTab o_tab = Shuffleboard.getTab("Odometry");
NetworkTableEntry position;
public MecanumDrivetrain() {
_front_left_motor = new CANSparkMax(DriveConstants.FRONT_LEFT, MotorType.kBrushless);
_front_right_motor = new CANSparkMax(DriveConstants.FRONT_RIGHT, MotorType.kBrushless);
_back_right_motor = new CANSparkMax(DriveConstants.BACK_RIGHT, MotorType.kBrushless);
_back_left_motor = new CANSparkMax(DriveConstants.BACK_LEFT, MotorType.kBrushless);
_front_left_encoder = _front_left_motor.getEncoder();
_front_right_encoder = _front_right_motor.getEncoder();
_back_left_encoder = _back_left_motor.getEncoder();
_back_right_encoder = _back_right_motor.getEncoder();
_front_left_location = new Translation2d(BuildConstants.WHEEL_TO_CENTER_SIDE_INCHES * BuildConstants.INCHES_TO_METERS,
BuildConstants.WHEEL_TO_CENTER_FRONT_INCHES * BuildConstants.INCHES_TO_METERS);
_front_right_location = new Translation2d(BuildConstants.WHEEL_TO_CENTER_SIDE_INCHES * BuildConstants.INCHES_TO_METERS,
-BuildConstants.WHEEL_TO_CENTER_FRONT_INCHES * BuildConstants.INCHES_TO_METERS);
_back_left_location = new Translation2d(-BuildConstants.WHEEL_TO_CENTER_SIDE_INCHES * BuildConstants.INCHES_TO_METERS,
BuildConstants.WHEEL_TO_CENTER_FRONT_INCHES * BuildConstants.INCHES_TO_METERS);
_back_right_location = new Translation2d(-BuildConstants.WHEEL_TO_CENTER_SIDE_INCHES * BuildConstants.INCHES_TO_METERS,
-BuildConstants.WHEEL_TO_CENTER_FRONT_INCHES * BuildConstants.INCHES_TO_METERS);
_front_left_PID = new PIDController(0, 0, 0);
_front_right_PID = new PIDController(0, 0, 0);
_back_left_PID = new PIDController(0, 0, 0);
_back_right_PID = new PIDController(0, 0, 0);
_feedforward = new SimpleMotorFeedforward(0, 0);
_kinematics = new MecanumDriveKinematics(_front_left_location,
_front_right_location,
_back_left_location,
_back_right_location);
_gyro = new AHRS(SPI.Port.kMXP);
_odometry = new MecanumDriveOdometry(_kinematics, _gyro.getRotation2d());
_gyro.reset();
position = o_tab.add("Position", _robot_position)
.withPosition(0, 0)
.getEntry();
}
public MecanumDriveWheelSpeeds getCurrentState() {
return new MecanumDriveWheelSpeeds(
_front_left_encoder.getVelocity() / BuildConstants.GR * BuildConstants.WHEEL_CIRCUMFERENCE,
_front_right_encoder.getVelocity() / BuildConstants.GR * BuildConstants.WHEEL_CIRCUMFERENCE,
_back_left_encoder.getVelocity() / BuildConstants.GR * BuildConstants.WHEEL_CIRCUMFERENCE,
_back_right_encoder.getVelocity() / BuildConstants.GR * BuildConstants.WHEEL_CIRCUMFERENCE
);
}
public void setSpeeds(MecanumDriveWheelSpeeds speeds) {
double flff = _feedforward.calculate(speeds.frontLeftMetersPerSecond);
double frff = _feedforward.calculate(speeds.frontRightMetersPerSecond);
double blff = _feedforward.calculate(speeds.rearLeftMetersPerSecond);
double brff = _feedforward.calculate(speeds.rearRightMetersPerSecond);
double fl = _front_left_PID.calculate(
_front_left_encoder.getVelocity(), speeds.frontLeftMetersPerSecond
);
double fr = _front_right_PID.calculate(
_front_right_encoder.getVelocity(), speeds.frontRightMetersPerSecond
);
double bl = _back_left_PID.calculate(
_back_left_encoder.getVelocity(), speeds.rearLeftMetersPerSecond
);
double br = _back_right_PID.calculate(
_back_right_encoder.getVelocity(), speeds.rearRightMetersPerSecond
);
}
public Pose2d updateOdometry() {
return _odometry.update(_gyro.getRotation2d(), getCurrentState());
}
public Pose2d getPose() {
return _odometry.getPoseMeters();
}
public void resetOdometry(Pose2d pose) {
_odometry.resetPosition(pose, _gyro.getRotation2d());
}
public double getHeading() {
return _gyro.getRotation2d().getDegrees();
}
public double getTurnRate() {
return -_gyro.getRate();
}
public MecanumDriveKinematics getKinematics() {
return _kinematics;
}
public SimpleMotorFeedforward getFeedForward() {
return _feedforward;
}
@Override
public void periodic() {
_robot_position = updateOdometry();
position.setValue(_robot_position);
}
}
|
3e17a6d5b79af7c164c7577648fb99999d2c3f2a | 32,868 | java | Java | Needle-core/src/main/java/com/codido/needle/core/model/CfgChannelExample.java | bpascal/needle | 3ad5eea028fcce9f89086db3bd10272237b45c35 | [
"Apache-2.0"
] | null | null | null | Needle-core/src/main/java/com/codido/needle/core/model/CfgChannelExample.java | bpascal/needle | 3ad5eea028fcce9f89086db3bd10272237b45c35 | [
"Apache-2.0"
] | 2 | 2020-12-22T14:54:27.000Z | 2020-12-22T15:11:15.000Z | Needle-core/src/main/java/com/codido/needle/core/model/CfgChannelExample.java | bpascal/needle | 3ad5eea028fcce9f89086db3bd10272237b45c35 | [
"Apache-2.0"
] | null | null | null | 35.64859 | 105 | 0.621608 | 10,074 | package com.codido.needle.core.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CfgChannelExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public CfgChannelExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andChannelIdIsNull() {
addCriterion("CHANNEL_ID is null");
return (Criteria) this;
}
public Criteria andChannelIdIsNotNull() {
addCriterion("CHANNEL_ID is not null");
return (Criteria) this;
}
public Criteria andChannelIdEqualTo(Long value) {
addCriterion("CHANNEL_ID =", value, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdNotEqualTo(Long value) {
addCriterion("CHANNEL_ID <>", value, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdGreaterThan(Long value) {
addCriterion("CHANNEL_ID >", value, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdGreaterThanOrEqualTo(Long value) {
addCriterion("CHANNEL_ID >=", value, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdLessThan(Long value) {
addCriterion("CHANNEL_ID <", value, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdLessThanOrEqualTo(Long value) {
addCriterion("CHANNEL_ID <=", value, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdIn(List<Long> values) {
addCriterion("CHANNEL_ID in", values, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdNotIn(List<Long> values) {
addCriterion("CHANNEL_ID not in", values, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdBetween(Long value1, Long value2) {
addCriterion("CHANNEL_ID between", value1, value2, "channelId");
return (Criteria) this;
}
public Criteria andChannelIdNotBetween(Long value1, Long value2) {
addCriterion("CHANNEL_ID not between", value1, value2, "channelId");
return (Criteria) this;
}
public Criteria andChannelNameIsNull() {
addCriterion("CHANNEL_NAME is null");
return (Criteria) this;
}
public Criteria andChannelNameIsNotNull() {
addCriterion("CHANNEL_NAME is not null");
return (Criteria) this;
}
public Criteria andChannelNameEqualTo(String value) {
addCriterion("CHANNEL_NAME =", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameNotEqualTo(String value) {
addCriterion("CHANNEL_NAME <>", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameGreaterThan(String value) {
addCriterion("CHANNEL_NAME >", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameGreaterThanOrEqualTo(String value) {
addCriterion("CHANNEL_NAME >=", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameLessThan(String value) {
addCriterion("CHANNEL_NAME <", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameLessThanOrEqualTo(String value) {
addCriterion("CHANNEL_NAME <=", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameLike(String value) {
addCriterion("CHANNEL_NAME like", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameNotLike(String value) {
addCriterion("CHANNEL_NAME not like", value, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameIn(List<String> values) {
addCriterion("CHANNEL_NAME in", values, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameNotIn(List<String> values) {
addCriterion("CHANNEL_NAME not in", values, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameBetween(String value1, String value2) {
addCriterion("CHANNEL_NAME between", value1, value2, "channelName");
return (Criteria) this;
}
public Criteria andChannelNameNotBetween(String value1, String value2) {
addCriterion("CHANNEL_NAME not between", value1, value2, "channelName");
return (Criteria) this;
}
public Criteria andChannelStsIsNull() {
addCriterion("CHANNEL_STS is null");
return (Criteria) this;
}
public Criteria andChannelStsIsNotNull() {
addCriterion("CHANNEL_STS is not null");
return (Criteria) this;
}
public Criteria andChannelStsEqualTo(String value) {
addCriterion("CHANNEL_STS =", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsNotEqualTo(String value) {
addCriterion("CHANNEL_STS <>", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsGreaterThan(String value) {
addCriterion("CHANNEL_STS >", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsGreaterThanOrEqualTo(String value) {
addCriterion("CHANNEL_STS >=", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsLessThan(String value) {
addCriterion("CHANNEL_STS <", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsLessThanOrEqualTo(String value) {
addCriterion("CHANNEL_STS <=", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsLike(String value) {
addCriterion("CHANNEL_STS like", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsNotLike(String value) {
addCriterion("CHANNEL_STS not like", value, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsIn(List<String> values) {
addCriterion("CHANNEL_STS in", values, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsNotIn(List<String> values) {
addCriterion("CHANNEL_STS not in", values, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsBetween(String value1, String value2) {
addCriterion("CHANNEL_STS between", value1, value2, "channelSts");
return (Criteria) this;
}
public Criteria andChannelStsNotBetween(String value1, String value2) {
addCriterion("CHANNEL_STS not between", value1, value2, "channelSts");
return (Criteria) this;
}
public Criteria andChannelTypeIsNull() {
addCriterion("CHANNEL_TYPE is null");
return (Criteria) this;
}
public Criteria andChannelTypeIsNotNull() {
addCriterion("CHANNEL_TYPE is not null");
return (Criteria) this;
}
public Criteria andChannelTypeEqualTo(String value) {
addCriterion("CHANNEL_TYPE =", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeNotEqualTo(String value) {
addCriterion("CHANNEL_TYPE <>", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeGreaterThan(String value) {
addCriterion("CHANNEL_TYPE >", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeGreaterThanOrEqualTo(String value) {
addCriterion("CHANNEL_TYPE >=", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeLessThan(String value) {
addCriterion("CHANNEL_TYPE <", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeLessThanOrEqualTo(String value) {
addCriterion("CHANNEL_TYPE <=", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeLike(String value) {
addCriterion("CHANNEL_TYPE like", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeNotLike(String value) {
addCriterion("CHANNEL_TYPE not like", value, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeIn(List<String> values) {
addCriterion("CHANNEL_TYPE in", values, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeNotIn(List<String> values) {
addCriterion("CHANNEL_TYPE not in", values, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeBetween(String value1, String value2) {
addCriterion("CHANNEL_TYPE between", value1, value2, "channelType");
return (Criteria) this;
}
public Criteria andChannelTypeNotBetween(String value1, String value2) {
addCriterion("CHANNEL_TYPE not between", value1, value2, "channelType");
return (Criteria) this;
}
public Criteria andChannelCreateTimeIsNull() {
addCriterion("CHANNEL_CREATE_TIME is null");
return (Criteria) this;
}
public Criteria andChannelCreateTimeIsNotNull() {
addCriterion("CHANNEL_CREATE_TIME is not null");
return (Criteria) this;
}
public Criteria andChannelCreateTimeEqualTo(Date value) {
addCriterion("CHANNEL_CREATE_TIME =", value, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeNotEqualTo(Date value) {
addCriterion("CHANNEL_CREATE_TIME <>", value, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeGreaterThan(Date value) {
addCriterion("CHANNEL_CREATE_TIME >", value, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("CHANNEL_CREATE_TIME >=", value, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeLessThan(Date value) {
addCriterion("CHANNEL_CREATE_TIME <", value, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("CHANNEL_CREATE_TIME <=", value, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeIn(List<Date> values) {
addCriterion("CHANNEL_CREATE_TIME in", values, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeNotIn(List<Date> values) {
addCriterion("CHANNEL_CREATE_TIME not in", values, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeBetween(Date value1, Date value2) {
addCriterion("CHANNEL_CREATE_TIME between", value1, value2, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("CHANNEL_CREATE_TIME not between", value1, value2, "channelCreateTime");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountIsNull() {
addCriterion("CHANNEL_RECHARGE_AMOUNT is null");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountIsNotNull() {
addCriterion("CHANNEL_RECHARGE_AMOUNT is not null");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountEqualTo(BigDecimal value) {
addCriterion("CHANNEL_RECHARGE_AMOUNT =", value, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountNotEqualTo(BigDecimal value) {
addCriterion("CHANNEL_RECHARGE_AMOUNT <>", value, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountGreaterThan(BigDecimal value) {
addCriterion("CHANNEL_RECHARGE_AMOUNT >", value, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("CHANNEL_RECHARGE_AMOUNT >=", value, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountLessThan(BigDecimal value) {
addCriterion("CHANNEL_RECHARGE_AMOUNT <", value, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountLessThanOrEqualTo(BigDecimal value) {
addCriterion("CHANNEL_RECHARGE_AMOUNT <=", value, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountIn(List<BigDecimal> values) {
addCriterion("CHANNEL_RECHARGE_AMOUNT in", values, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountNotIn(List<BigDecimal> values) {
addCriterion("CHANNEL_RECHARGE_AMOUNT not in", values, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("CHANNEL_RECHARGE_AMOUNT between", value1, value2, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelRechargeAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("CHANNEL_RECHARGE_AMOUNT not between", value1, value2, "channelRechargeAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountIsNull() {
addCriterion("CHANNEL_PAY_AMOUNT is null");
return (Criteria) this;
}
public Criteria andChannelPayAmountIsNotNull() {
addCriterion("CHANNEL_PAY_AMOUNT is not null");
return (Criteria) this;
}
public Criteria andChannelPayAmountEqualTo(BigDecimal value) {
addCriterion("CHANNEL_PAY_AMOUNT =", value, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountNotEqualTo(BigDecimal value) {
addCriterion("CHANNEL_PAY_AMOUNT <>", value, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountGreaterThan(BigDecimal value) {
addCriterion("CHANNEL_PAY_AMOUNT >", value, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("CHANNEL_PAY_AMOUNT >=", value, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountLessThan(BigDecimal value) {
addCriterion("CHANNEL_PAY_AMOUNT <", value, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountLessThanOrEqualTo(BigDecimal value) {
addCriterion("CHANNEL_PAY_AMOUNT <=", value, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountIn(List<BigDecimal> values) {
addCriterion("CHANNEL_PAY_AMOUNT in", values, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountNotIn(List<BigDecimal> values) {
addCriterion("CHANNEL_PAY_AMOUNT not in", values, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("CHANNEL_PAY_AMOUNT between", value1, value2, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelPayAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("CHANNEL_PAY_AMOUNT not between", value1, value2, "channelPayAmount");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceIsNull() {
addCriterion("CHANNEL_CURRENT_BALANCE is null");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceIsNotNull() {
addCriterion("CHANNEL_CURRENT_BALANCE is not null");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceEqualTo(BigDecimal value) {
addCriterion("CHANNEL_CURRENT_BALANCE =", value, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceNotEqualTo(BigDecimal value) {
addCriterion("CHANNEL_CURRENT_BALANCE <>", value, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceGreaterThan(BigDecimal value) {
addCriterion("CHANNEL_CURRENT_BALANCE >", value, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("CHANNEL_CURRENT_BALANCE >=", value, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceLessThan(BigDecimal value) {
addCriterion("CHANNEL_CURRENT_BALANCE <", value, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceLessThanOrEqualTo(BigDecimal value) {
addCriterion("CHANNEL_CURRENT_BALANCE <=", value, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceIn(List<BigDecimal> values) {
addCriterion("CHANNEL_CURRENT_BALANCE in", values, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceNotIn(List<BigDecimal> values) {
addCriterion("CHANNEL_CURRENT_BALANCE not in", values, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("CHANNEL_CURRENT_BALANCE between", value1, value2, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelCurrentBalanceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("CHANNEL_CURRENT_BALANCE not between", value1, value2, "channelCurrentBalance");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleIsNull() {
addCriterion("CHANNEL_INTERFACE_STYLE is null");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleIsNotNull() {
addCriterion("CHANNEL_INTERFACE_STYLE is not null");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleEqualTo(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE =", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleNotEqualTo(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE <>", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleGreaterThan(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE >", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleGreaterThanOrEqualTo(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE >=", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleLessThan(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE <", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleLessThanOrEqualTo(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE <=", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleLike(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE like", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleNotLike(String value) {
addCriterion("CHANNEL_INTERFACE_STYLE not like", value, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleIn(List<String> values) {
addCriterion("CHANNEL_INTERFACE_STYLE in", values, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleNotIn(List<String> values) {
addCriterion("CHANNEL_INTERFACE_STYLE not in", values, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleBetween(String value1, String value2) {
addCriterion("CHANNEL_INTERFACE_STYLE between", value1, value2, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andChannelInterfaceStyleNotBetween(String value1, String value2) {
addCriterion("CHANNEL_INTERFACE_STYLE not between", value1, value2, "channelInterfaceStyle");
return (Criteria) this;
}
public Criteria andOrderActionUrlIsNull() {
addCriterion("ORDER_ACTION_URL is null");
return (Criteria) this;
}
public Criteria andOrderActionUrlIsNotNull() {
addCriterion("ORDER_ACTION_URL is not null");
return (Criteria) this;
}
public Criteria andOrderActionUrlEqualTo(String value) {
addCriterion("ORDER_ACTION_URL =", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlNotEqualTo(String value) {
addCriterion("ORDER_ACTION_URL <>", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlGreaterThan(String value) {
addCriterion("ORDER_ACTION_URL >", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlGreaterThanOrEqualTo(String value) {
addCriterion("ORDER_ACTION_URL >=", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlLessThan(String value) {
addCriterion("ORDER_ACTION_URL <", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlLessThanOrEqualTo(String value) {
addCriterion("ORDER_ACTION_URL <=", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlLike(String value) {
addCriterion("ORDER_ACTION_URL like", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlNotLike(String value) {
addCriterion("ORDER_ACTION_URL not like", value, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlIn(List<String> values) {
addCriterion("ORDER_ACTION_URL in", values, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlNotIn(List<String> values) {
addCriterion("ORDER_ACTION_URL not in", values, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlBetween(String value1, String value2) {
addCriterion("ORDER_ACTION_URL between", value1, value2, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderActionUrlNotBetween(String value1, String value2) {
addCriterion("ORDER_ACTION_URL not between", value1, value2, "orderActionUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlIsNull() {
addCriterion("ORDER_QUERY_URL is null");
return (Criteria) this;
}
public Criteria andOrderQueryUrlIsNotNull() {
addCriterion("ORDER_QUERY_URL is not null");
return (Criteria) this;
}
public Criteria andOrderQueryUrlEqualTo(String value) {
addCriterion("ORDER_QUERY_URL =", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlNotEqualTo(String value) {
addCriterion("ORDER_QUERY_URL <>", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlGreaterThan(String value) {
addCriterion("ORDER_QUERY_URL >", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlGreaterThanOrEqualTo(String value) {
addCriterion("ORDER_QUERY_URL >=", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlLessThan(String value) {
addCriterion("ORDER_QUERY_URL <", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlLessThanOrEqualTo(String value) {
addCriterion("ORDER_QUERY_URL <=", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlLike(String value) {
addCriterion("ORDER_QUERY_URL like", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlNotLike(String value) {
addCriterion("ORDER_QUERY_URL not like", value, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlIn(List<String> values) {
addCriterion("ORDER_QUERY_URL in", values, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlNotIn(List<String> values) {
addCriterion("ORDER_QUERY_URL not in", values, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlBetween(String value1, String value2) {
addCriterion("ORDER_QUERY_URL between", value1, value2, "orderQueryUrl");
return (Criteria) this;
}
public Criteria andOrderQueryUrlNotBetween(String value1, String value2) {
addCriterion("ORDER_QUERY_URL not between", value1, value2, "orderQueryUrl");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
3e17a8a5824779f0b0a79c850d3a3cc67aed3b82 | 1,475 | java | Java | AndroidAnnotations/functional-test-1-5/src/main/java/org/androidannotations/test15/prefs/SomePrefs.java | lalith-b/androidannotations | 615bce863b53ec7b00b4495bd97799d5fe11bd00 | [
"Apache-2.0"
] | 2 | 2015-05-29T09:54:06.000Z | 2016-06-24T14:01:16.000Z | AndroidAnnotations/functional-test-1-5/src/main/java/org/androidannotations/test15/prefs/SomePrefs.java | saopayne/androidannotations | 6b70c3233901a21ed71f2fb6c1e49545c377d754 | [
"Apache-2.0"
] | null | null | null | AndroidAnnotations/functional-test-1-5/src/main/java/org/androidannotations/test15/prefs/SomePrefs.java | saopayne/androidannotations | 6b70c3233901a21ed71f2fb6c1e49545c377d754 | [
"Apache-2.0"
] | null | null | null | 31.382979 | 80 | 0.793898 | 10,075 | /**
* Copyright (C) 2010-2013 eBusiness Information, Excilys Group
*
* 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.androidannotations.test15.prefs;
import org.androidannotations.annotations.sharedpreferences.DefaultBoolean;
import org.androidannotations.annotations.sharedpreferences.DefaultFloat;
import org.androidannotations.annotations.sharedpreferences.DefaultInt;
import org.androidannotations.annotations.sharedpreferences.DefaultLong;
import org.androidannotations.annotations.sharedpreferences.DefaultString;
import org.androidannotations.annotations.sharedpreferences.SharedPref;
import org.androidannotations.annotations.sharedpreferences.SharedPref.Scope;
@SharedPref(Scope.UNIQUE)
public interface SomePrefs {
@DefaultString("John")
String name();
@DefaultInt(42)
int age();
@DefaultLong(400000L)
long ageLong();
@DefaultFloat(42f)
float ageFloat();
@DefaultBoolean(true)
boolean isAwesome();
long lastUpdated();
}
|
3e17a8c6b97fce910c41b5db88e6a723f13cb9f3 | 547 | java | Java | concurrency/src/main/java/ru/job4j/concurrency/second/DCLSingleton.java | Malamut54/dbobrov | 2436fa9a04d0dbde71b4a3f8af167604835afda9 | [
"Apache-2.0"
] | null | null | null | concurrency/src/main/java/ru/job4j/concurrency/second/DCLSingleton.java | Malamut54/dbobrov | 2436fa9a04d0dbde71b4a3f8af167604835afda9 | [
"Apache-2.0"
] | null | null | null | concurrency/src/main/java/ru/job4j/concurrency/second/DCLSingleton.java | Malamut54/dbobrov | 2436fa9a04d0dbde71b4a3f8af167604835afda9 | [
"Apache-2.0"
] | null | null | null | 23.782609 | 62 | 0.555759 | 10,076 | package ru.job4j.concurrency.second;
public class DCLSingleton {
private volatile static DCLSingleton inst;
public static DCLSingleton instOf() {
DCLSingleton localInstance = inst;
if (localInstance == null) {
synchronized (DCLSingleton.class) {
localInstance = inst;
if (localInstance == null) {
localInstance = inst = new DCLSingleton();
}
}
}
return localInstance;
}
private DCLSingleton() {
}
}
|
3e17a93441547be40e5b0d142aab4e8f0689c1ec | 145 | java | Java | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_783.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | 1 | 2016-01-18T17:57:21.000Z | 2016-01-18T17:57:21.000Z | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_783.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | null | null | null | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_783.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | null | null | null | 18.125 | 51 | 0.827586 | 10,077 | package fr.javatronic.blog.massive.annotation1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_783 {
}
|
3e17a9782c6785beb300bb37d2912a1b04f6326a | 2,582 | java | Java | app/src/main/java/com/example/cloud/sheep2/SubjectActivity.java | 15-2505-040-1/sheep8 | a325521aded69ad8612ee9922ed3da3fef317a9e | [
"MIT"
] | null | null | null | app/src/main/java/com/example/cloud/sheep2/SubjectActivity.java | 15-2505-040-1/sheep8 | a325521aded69ad8612ee9922ed3da3fef317a9e | [
"MIT"
] | null | null | null | app/src/main/java/com/example/cloud/sheep2/SubjectActivity.java | 15-2505-040-1/sheep8 | a325521aded69ad8612ee9922ed3da3fef317a9e | [
"MIT"
] | null | null | null | 33.102564 | 77 | 0.625097 | 10,078 | package com.example.cloud.sheep2;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import static com.example.cloud.sheep2.R.id.sub1;
import static com.example.cloud.sheep2.R.id.sub2;
import static com.example.cloud.sheep2.R.id.sub3;
public class SubjectActivity extends AppCompatActivity {
Global global;
TextView subtitle;
MediaPlayer mMediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
mMediaPlayer= MediaPlayer.create(this,R.raw.haru);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
subtitle = (TextView) findViewById(R.id.subtitle);
global=(Global)this.getApplication();
global.GlobalsAllInit();
}
public void onTapped(View view) {
mMediaPlayer.stop();
if(view==findViewById(sub1)){
global.sub=1;
global.m=1;
Mathques1.init();
Intent intent = new Intent(getApplication(), QuizActivity.class);
intent.putExtra("Mathques1", Mathques1.getQuiz(0));
startActivity(intent);
}
if(view==findViewById(sub2)){
global.sub=2;
global.x=1;
Physques1.init();
Intent intent = new Intent(getApplication(), QuizActivity.class);
intent.putExtra("Physques1", Physques1.getQuiz(0));
startActivity(intent);
}
if(view==findViewById(sub3)){
global.sub=3;
global.y=3;
Physques3.init();
Intent intent = new Intent(getApplication(), QuizActivity.class);
intent.putExtra("Physques3", Physques3.getQuiz(0));
startActivity(intent);
}
}
public void onBack(View view1) {
mMediaPlayer.stop();
Intent intent = new Intent(getApplication(), MainActivity.class);
startActivity(intent);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction()==KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
// ダイアログ表示など特定の処理を行いたい場合はここに記述
// 親クラスのdispatchKeyEvent()を呼び出さずにtrueを返す
return true;
}
}
return super.dispatchKeyEvent(event);
}
}
|
3e17a99cfc646e9b52a1efadbca43bfc68a4bbe4 | 8,452 | java | Java | common/src/test/java/com/thoughtworks/go/config/materials/ScmMaterialTest.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,865 | 2015-01-02T04:24:52.000Z | 2022-03-31T11:00:46.000Z | common/src/test/java/com/thoughtworks/go/config/materials/ScmMaterialTest.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,972 | 2015-01-02T10:20:42.000Z | 2022-03-31T20:17:09.000Z | common/src/test/java/com/thoughtworks/go/config/materials/ScmMaterialTest.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 998 | 2015-01-01T18:02:09.000Z | 2022-03-28T21:20:50.000Z | 41.326829 | 123 | 0.713055 | 10,079 | /*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.config.materials;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.SecretParam;
import com.thoughtworks.go.domain.MaterialRevision;
import com.thoughtworks.go.domain.materials.DummyMaterial;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.*;
class ScmMaterialTest {
private DummyMaterial material;
@BeforeEach
void setUp() throws Exception {
material = new DummyMaterial();
}
@Test
void shouldSmudgePasswordForDescription() throws Exception {
material.setUrl("http://user:password@localhost:8000/foo");
assertThat(material.getDescription(), is("http://user:******@localhost:8000/foo"));
}
@Test
void displayNameShouldReturnUrlWhenNameNotSet() throws Exception {
material.setUrl("http://user:password@localhost:8000/foo");
assertThat(material.getDisplayName(), is("http://user:******@localhost:8000/foo"));
}
@Test
void displayNameShouldReturnNameWhenSet() throws Exception {
material.setName(new CaseInsensitiveString("blah-name"));
assertThat(material.getDisplayName(), is("blah-name"));
}
@Test
void willNeverBeUsedInAFetchArtifact() {
assertThat(material.isUsedInFetchArtifact(new PipelineConfig()), is(false));
}
@Test
void populateEnvironmentContextShouldSetFromAndToRevisionEnvironmentVariables() {
material.setUrl("https://user:upchh@example.com");
EnvironmentVariableContext ctx = new EnvironmentVariableContext();
final ArrayList<Modification> modifications = new ArrayList<>();
modifications.add(new Modification("user2", "comment2", "email2", new Date(), "24"));
modifications.add(new Modification("user1", "comment1", "email1", new Date(), "23"));
MaterialRevision materialRevision = new MaterialRevision(material, modifications);
assertThat(ctx.getProperty(ScmMaterial.GO_FROM_REVISION), is(nullValue()));
assertThat(ctx.getProperty(ScmMaterial.GO_TO_REVISION), is(nullValue()));
assertThat(ctx.getProperty(ScmMaterial.GO_REVISION), is(nullValue()));
material.populateEnvironmentContext(ctx, materialRevision, new File("."));
assertThat(ctx.getProperty(ScmMaterial.GO_FROM_REVISION), is("23"));
assertThat(ctx.getProperty(ScmMaterial.GO_TO_REVISION), is("24"));
assertThat(ctx.getProperty(ScmMaterial.GO_REVISION), is("24"));
}
@Test
void populateEnvContextShouldSetMaterialEnvVars() {
material.setUrl("https://user:upchh@example.com");
EnvironmentVariableContext ctx = new EnvironmentVariableContext();
final ArrayList<Modification> modifications = new ArrayList<>();
modifications.add(new Modification("user2", "comment2", "email2", new Date(), "24"));
modifications.add(new Modification("user1", "comment1", "email1", new Date(), "23"));
MaterialRevision materialRevision = new MaterialRevision(material, modifications);
assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL), is(nullValue()));
material.populateEnvironmentContext(ctx, materialRevision, new File("."));
assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL), is("https://example.github.com"));
}
@Test
void shouldIncludeMaterialNameInEnvVariableNameIfAvailable() {
EnvironmentVariableContext context = new EnvironmentVariableContext();
material.setVariableWithName(context, "value", "GO_PROPERTY");
assertThat(context.getProperty("GO_PROPERTY"), is("value"));
context = new EnvironmentVariableContext();
material.setName(new CaseInsensitiveString("dummy"));
material.setVariableWithName(context, "value", "GO_PROPERTY");
assertThat(context.getProperty("GO_PROPERTY_DUMMY"), is("value"));
assertThat(context.getProperty("GO_PROPERTY"), is(nullValue()));
}
@Test
void shouldIncludeDestFolderInEnvVariableNameIfMaterialNameNotAvailable() {
EnvironmentVariableContext context = new EnvironmentVariableContext();
material.setVariableWithName(context, "value", "GO_PROPERTY");
assertThat(context.getProperty("GO_PROPERTY"), is("value"));
context = new EnvironmentVariableContext();
material.setFolder("foo_dir");
material.setVariableWithName(context, "value", "GO_PROPERTY");
assertThat(context.getProperty("GO_PROPERTY_FOO_DIR"), is("value"));
assertThat(context.getProperty("GO_PROPERTY"), is(nullValue()));
}
@Test
void shouldEscapeHyphenFromMaterialNameWhenUsedInEnvVariable() {
EnvironmentVariableContext context = new EnvironmentVariableContext();
material.setName(new CaseInsensitiveString("material-name"));
material.setVariableWithName(context, "value", "GO_PROPERTY");
assertThat(context.getProperty("GO_PROPERTY_MATERIAL_NAME"), is("value"));
assertThat(context.getProperty("GO_PROPERTY"), is(nullValue()));
}
@Test
void shouldEscapeHyphenFromFolderNameWhenUsedInEnvVariable() {
EnvironmentVariableContext context = new EnvironmentVariableContext();
material.setFolder("folder-name");
material.setVariableWithName(context, "value", "GO_PROPERTY");
assertThat(context.getProperty("GO_PROPERTY_FOLDER_NAME"), is("value"));
assertThat(context.getProperty("GO_PROPERTY"), is(nullValue()));
}
@Test
void shouldReturnTrueForAnScmMaterial_supportsDestinationFolder() throws Exception {
assertThat(material.supportsDestinationFolder(), is(true));
}
@Test
void shouldGetMaterialNameForEnvironmentMaterial() {
assertThat(material.getMaterialNameForEnvironmentVariable(), is(""));
material.setFolder("dest-folder");
assertThat(material.getMaterialNameForEnvironmentVariable(), is("DEST_FOLDER"));
material.setName(new CaseInsensitiveString("some-material"));
assertThat(material.getMaterialNameForEnvironmentVariable(), is("SOME_MATERIAL"));
}
@Nested
class hasSecretParams {
@Test
void shouldBeTrueIfPasswordHasSecretParam() {
DummyMaterial dummyMaterial = new DummyMaterial();
dummyMaterial.setPassword("{{SECRET:[secret_config_id][lookup_password]}}");
assertTrue(dummyMaterial.hasSecretParams());
}
@Test
void shouldBeFalseIfMaterialUrlAndPasswordDoesNotHaveSecretParams() {
DummyMaterial dummyMaterial = new DummyMaterial();
assertFalse(dummyMaterial.hasSecretParams());
}
}
@Nested
class getSecretParams {
@Test
void shouldReturnAListOfSecretParams() {
DummyMaterial dummyMaterial = new DummyMaterial();
dummyMaterial.setPassword("{{SECRET:[secret_config_id][lookup_password]}}");
assertThat(dummyMaterial.getSecretParams().size(), is(1));
assertThat(dummyMaterial.getSecretParams().get(0), is(new SecretParam("secret_config_id", "lookup_password")));
}
@Test
void shouldBeAnEmptyListInAbsenceOfSecretParamsinMaterialPassword() {
DummyMaterial dummyMaterial = new DummyMaterial();
assertThat(dummyMaterial.getSecretParams(), is(nullValue()));
}
}
}
|
3e17a9b1fa81bd50f9177a429d52286a034f8e45 | 173 | java | Java | src/test/java/sample/hello/MainTest.java | vega113/vegabase | 72e9a119cdf72ef1e41b274450009ea4351166af | [
"Apache-2.0"
] | null | null | null | src/test/java/sample/hello/MainTest.java | vega113/vegabase | 72e9a119cdf72ef1e41b274450009ea4351166af | [
"Apache-2.0"
] | null | null | null | src/test/java/sample/hello/MainTest.java | vega113/vegabase | 72e9a119cdf72ef1e41b274450009ea4351166af | [
"Apache-2.0"
] | null | null | null | 11.533333 | 33 | 0.693642 | 10,080 | package sample.hello;
import static org.junit.Assert.*;
import org.junit.Test;
public class MainTest {
@Test
public void test() {
fail("Not yet implemented");
}
}
|
3e17a9ec684ca6b7f6862c74b2c631ca2e9b70b5 | 970 | java | Java | src/Statements/loop/For.java | nesh170/SLogo | 8d60361921f50ec4238458fd87436a121f98d68e | [
"MIT"
] | null | null | null | src/Statements/loop/For.java | nesh170/SLogo | 8d60361921f50ec4238458fd87436a121f98d68e | [
"MIT"
] | null | null | null | src/Statements/loop/For.java | nesh170/SLogo | 8d60361921f50ec4238458fd87436a121f98d68e | [
"MIT"
] | null | null | null | 22.55814 | 93 | 0.66701 | 10,081 | package Statements.loop;
import java.util.List;
import Model.VariableManager;
import Statements.Statement;
import Statements.Variable;
/**
* @author Yancheng, Sierra
*/
public class For extends Loop {
/**
* Constructor for For.
* @param params List<List<Statement>>
* @param manager VariableManager
*/
public For(List<List<Statement>> params, VariableManager manager) {
super(params, manager);
}
/**
* Method execute.
* @return double
*/
@Override
public double execute() {
int start = (int) getMyParams().get(0).get(1).execute();
int end = (int) getMyParams().get(0).get(2).execute();
int increment = (int) getMyParams().get(0).get(3).execute();
double result = 0;
for(int i = start; i <= end; i += increment){
getMyManager().addVariable(((Variable)getMyParams().get(0).get(0)).getName(), (double) i);
for(Statement curStatement: getMyParams().get(1)){
result = curStatement.execute();
}
}
return result;
}
}
|
3e17aa37916d84d4cd92aa5a0c0e0fd07edca284 | 2,675 | java | Java | Project/src/membership/MemberManager.java | 1yena/JAVA-study | 4a115b3efe2670646a21131c9e00f2ecff696b24 | [
"MIT"
] | null | null | null | Project/src/membership/MemberManager.java | 1yena/JAVA-study | 4a115b3efe2670646a21131c9e00f2ecff696b24 | [
"MIT"
] | null | null | null | Project/src/membership/MemberManager.java | 1yena/JAVA-study | 4a115b3efe2670646a21131c9e00f2ecff696b24 | [
"MIT"
] | null | null | null | 16.823899 | 69 | 0.435514 | 10,082 | package membership;
import java.util.Vector;
import java.util.Scanner;
public class MemberManager {
Scanner scan = new Scanner(System.in);
Vector<Member> members = new Vector<Member>();
public void Run() {
int key = 0;
while((key = selectMenu())!=0) {
switch(key){
case 1: addMember(); break;
case 2: removeMember(); break;
case 3: searchMember(); break;
case 4: listMember(); break;
default: System.out.println("잘못 선택하였습니다."); break;
}
}
System.out.println("시스템 종료.");
}
int selectMenu() {
System.out.println("1:추가 / 2:삭제 / 3:검색 / 4:목록 / 0:종료");
int key = scan.nextInt();
scan.nextLine();
return key;
}
void addMember() {
int num = 0;
String name="";
System.out.print("추가할 회원 번호: ");
num = scan.nextInt();
scan.nextLine();
System.out.print("회원 이름: ");
name = scan.nextLine();
Member member =new Member(num,name);
members.add(member);
System.out.println(member.toString()+"을 생성하였습니다.");
}
void removeMember() {
int num = 0;
System.out.print("삭제할 회원 번호: ");
num = scan.nextInt();
scan.nextLine();
Member member = Find(num);
if(member == null){
System.out.println("존재하지 않습니다.");
return;
}
members.remove(member);
System.out.println(member.toString()+"을 삭제하였습니다.");
}
void searchMember() {
int num = 0;
System.out.print("검색할 회원 번호: ");
num = scan.nextInt();
scan.nextLine();
Member member = Find(num);
if(member == null){
System.out.println("존재하지 않습니다.");
return;
}
System.out.println("검색 결과>> "+member.toString());
}
void listMember() {
System.out.println("전체 목록");
int cnt = members.size();
System.out.println("회원 수: " + cnt + "명");
for(Member member : members) {
System.out.println(member.toString());
}
}
Member Find(int num) {
for(Member member : members) {
if(member.getNum() == num) {
return member;
}
}
return null;
}
}
|
3e17aa8362a46039ac67b3a227e489f865aa6651 | 4,072 | java | Java | ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/InstanceBuilder.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 73 | 2020-02-28T19:50:03.000Z | 2022-03-31T14:40:18.000Z | ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/InstanceBuilder.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 50 | 2020-03-02T10:53:06.000Z | 2022-03-25T13:23:51.000Z | ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/InstanceBuilder.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 97 | 2020-03-02T10:40:18.000Z | 2022-03-25T01:13:32.000Z | 38.415094 | 105 | 0.670432 | 10,083 | /*
* 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.felix.ipojo.extender;
import org.osgi.framework.BundleContext;
/**
* Support class for fluent instance declaration building.
* This class can be used to specify instance details like naming, component's type, component's version.
* The {@link #context(org.osgi.framework.BundleContext)} method can be used to override the default
* {@link org.osgi.framework.BundleContext} used for declaration service registration.
*
* @since 1.11.2
*/
public interface InstanceBuilder {
/**
* Specify the instance name. Using {@literal null} will result in an anonymous instance.
* @param name instance name or {@literal null}
* @return this builder
*/
InstanceBuilder name(String name);
/**
* Specify the component's type of this instance.
* @param type type of the instance (cannot be {@literal null}).
* @return this builder
*/
InstanceBuilder type(String type);
/**
* Specify the component's type of this instance.
* @param type type of the instance (cannot be {@literal null}).
* @return this builder
*/
InstanceBuilder type(Class<?> type);
/**
* Specify the component's version of this instance. If {@literal null} is used,
* the factory without any version attribute will be used.
* @param version component's version (can be {@literal null}).
* @return this builder
*/
InstanceBuilder version(String version);
/**
* Override the default BundleContext used for declaration service registration.
* Use this with <bold>caution</bold>, for example, if the bundle does not import the
* <code>{@link org.apache.felix.ipojo.extender}</code> package, declarations may not be
* linked and activated properly.
* @param context new context to be used.
* @return this builder
*/
InstanceBuilder context(BundleContext context);
/**
* Access the dedicated builder for configuration (properties).
* Notice that when this method is used, the called must use {@link ConfigurationBuilder#build()}
* to build the instance declaration configured with the right set of properties. Any attempt
* to use {@link #build()} will result in a new declaration with no properties associated.
*
* Good usage (produced declaration has the associated properties):
* <pre>
* DeclarationHandle handle = builder.configure()
* .property("hello", "world")
* .build();
* </pre>
*
* Bad usage (produced declaration does not have the associated properties):
* <pre>
* builder.configure()
* .property("hello", "world");
*
* DeclarationHandle handle = builder.build();
* </pre>
*
* @return the instance configuration builder
*/
ConfigurationBuilder configure();
/**
* Build the declaration handle (never contains any configuration).
* Notice that the declaration is not yet published (no automatic activation).
* The client has to do it through {@link DeclarationHandle#publish()}
* @return the handle to the declaration
*/
DeclarationHandle build();
}
|
3e17ab24b39cf4057641091c6f9dd2f769da328f | 135 | java | Java | src/main/java/com/darcy/auxiliary/extractions/JiebaDemo.java | MyDarcy/SSE | 080c0310796ba0b8df1c41ea159dcc5594624445 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/darcy/auxiliary/extractions/JiebaDemo.java | MyDarcy/SSE | 080c0310796ba0b8df1c41ea159dcc5594624445 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/darcy/auxiliary/extractions/JiebaDemo.java | MyDarcy/SSE | 080c0310796ba0b8df1c41ea159dcc5594624445 | [
"Apache-2.0"
] | null | null | null | 12.272727 | 40 | 0.681481 | 10,084 | package com.darcy.auxiliary.extractions;
/*
* author: darcy
* date: 2018/1/24 11:16
* description:
*/
public class JiebaDemo {
}
|
3e17ab350bcff9b472495f791e7be50d8abda6d6 | 683 | java | Java | example-00-hello/src/main/java/io/sfe/hello/Note.java | vrudas/spring-framework-examples | ae4052ddbf5b541730bd0ec2952cc937ac70a17e | [
"MIT"
] | 21 | 2021-02-23T18:26:29.000Z | 2022-02-21T16:41:44.000Z | example-00-hello/src/main/java/io/sfe/hello/Note.java | vrudas/spring-framework-examples | ae4052ddbf5b541730bd0ec2952cc937ac70a17e | [
"MIT"
] | 20 | 2021-03-11T03:32:21.000Z | 2022-03-01T03:19:36.000Z | example-00-hello/src/main/java/io/sfe/hello/Note.java | vrudas/spring-framework-examples | ae4052ddbf5b541730bd0ec2952cc937ac70a17e | [
"MIT"
] | 5 | 2021-01-31T12:54:51.000Z | 2022-03-27T16:08:00.000Z | 18.459459 | 66 | 0.527086 | 10,085 | package io.sfe.hello;
import java.util.Objects;
public class Note {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Note note = (Note) o;
return Objects.equals(text, note.text);
}
@Override
public int hashCode() {
return Objects.hash(text);
}
@Override
public String toString() {
return "Note{" +
"text='" + text + '\'' +
'}';
}
}
|
3e17ac20d068159e32d8f4e199a8a840570d29fd | 41,193 | java | Java | javacompiler/src/main/java/com/android/sdklib/repository/descriptors/PkgDesc.java | PranavPurwar/java-n-IDE-for-Android | 0edddf146fcc8540049268aee76c5bc9a5a516b2 | [
"Apache-2.0"
] | 2 | 2020-06-22T19:52:49.000Z | 2021-01-09T22:40:30.000Z | javacompiler/src/main/java/com/android/sdklib/repository/descriptors/PkgDesc.java | PranavPurwar/java-n-IDE-for-Android | 0edddf146fcc8540049268aee76c5bc9a5a516b2 | [
"Apache-2.0"
] | null | null | null | javacompiler/src/main/java/com/android/sdklib/repository/descriptors/PkgDesc.java | PranavPurwar/java-n-IDE-for-Android | 0edddf146fcc8540049268aee76c5bc9a5a516b2 | [
"Apache-2.0"
] | 1 | 2020-11-04T07:55:37.000Z | 2020-11-04T07:55:37.000Z | 35.882404 | 120 | 0.538417 | 10,086 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.android.sdklib.repository.descriptors;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.annotations.VisibleForTesting;
import com.android.annotations.VisibleForTesting.Visibility;
import com.android.sdklib.AndroidTargetHash;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.SystemImage;
import com.android.sdklib.internal.repository.packages.License;
import com.android.sdklib.internal.repository.packages.Package;
import com.android.sdklib.io.FileOp;
import com.android.sdklib.repository.FullRevision;
import com.android.sdklib.repository.FullRevision.PreviewComparison;
import com.android.sdklib.repository.MajorRevision;
import com.android.sdklib.repository.NoPreviewRevision;
import java.io.File;
import java.util.Locale;
/**
* {@link PkgDesc} keeps information on individual SDK packages
* (both local or remote packages definitions.)
* <br/>
* Packages have different attributes depending on their type.
* <p/>
* To create a new {@link PkgDesc}, use one of the package-specific constructors
* provided here.
* <p/>
* To query packages capabilities, rely on {@link #getType()} and the {@code PkgDesc.hasXxx()}
* methods provided in the base {@link PkgDesc}.
*/
public class PkgDesc implements IPkgDesc {
private final PkgType mType;
private final FullRevision mFullRevision;
private final MajorRevision mMajorRevision;
private final AndroidVersion mAndroidVersion;
private final String mPath;
private final IdDisplay mTag;
private final IdDisplay mVendor;
private final FullRevision mMinToolsRev;
private final FullRevision mMinPlatformToolsRev;
private final IIsUpdateFor mCustomIsUpdateFor;
private final IGetPath mCustomPath;
private final License mLicense;
private final String mListDisplay;
private final String mDescriptionShort;
private final String mDescriptionUrl;
private final boolean mIsObsolete;
protected PkgDesc(@NonNull PkgType type,
@Nullable License license,
@Nullable String listDisplay,
@Nullable String descriptionShort,
@Nullable String descriptionUrl,
boolean isObsolete,
@Nullable FullRevision fullRevision,
@Nullable MajorRevision majorRevision,
@Nullable AndroidVersion androidVersion,
@Nullable String path,
@Nullable IdDisplay tag,
@Nullable IdDisplay vendor,
@Nullable FullRevision minToolsRev,
@Nullable FullRevision minPlatformToolsRev,
@Nullable IIsUpdateFor customIsUpdateFor,
@Nullable IGetPath customPath) {
mType = type;
mIsObsolete = isObsolete;
mLicense = license;
mListDisplay = listDisplay;
mDescriptionShort = descriptionShort;
mDescriptionUrl = descriptionUrl;
mFullRevision = fullRevision;
mMajorRevision = majorRevision;
mAndroidVersion = androidVersion;
mPath = path;
mTag = tag;
mVendor = vendor;
mMinToolsRev = minToolsRev;
mMinPlatformToolsRev = minPlatformToolsRev;
mCustomIsUpdateFor = customIsUpdateFor;
mCustomPath = customPath;
}
@NonNull
@Override
public PkgType getType() {
return mType;
}
@Override
@Nullable
public String getListDisplay() {
return mListDisplay;
}
@Override
@Nullable
public String getDescriptionShort() {
return mDescriptionShort;
}
@Override
@Nullable
public String getDescriptionUrl() {
return mDescriptionUrl;
}
@Override
@Nullable
public License getLicense() {
return mLicense;
}
@Override
public boolean isObsolete() {
return mIsObsolete;
}
@Override
public final boolean hasFullRevision() {
return getType().hasFullRevision();
}
@Override
public final boolean hasMajorRevision() {
return getType().hasMajorRevision();
}
@Override
public final boolean hasAndroidVersion() {
return getType().hasAndroidVersion();
}
@Override
public final boolean hasPath() {
return getType().hasPath();
}
@Override
public final boolean hasTag() {
return getType().hasTag();
}
@Override
public boolean hasVendor() {
return getType().hasVendor();
}
@Override
public final boolean hasMinToolsRev() {
return getType().hasMinToolsRev();
}
@Override
public final boolean hasMinPlatformToolsRev() {
return getType().hasMinPlatformToolsRev();
}
@Nullable
@Override
public FullRevision getFullRevision() {
return mFullRevision;
}
@Nullable
@Override
public MajorRevision getMajorRevision() {
return mMajorRevision;
}
@Nullable
@Override
public AndroidVersion getAndroidVersion() {
return mAndroidVersion;
}
@Nullable
@Override
public String getPath() {
if (mCustomPath != null) {
return mCustomPath.getPath(this);
} else {
return mPath;
}
}
@Nullable
@Override
public IdDisplay getTag() {
return mTag;
}
@Nullable
@Override
public IdDisplay getVendor() {
return mVendor;
}
@Nullable
@Override
public FullRevision getMinToolsRev() {
return mMinToolsRev;
}
@Nullable
@Override
public FullRevision getMinPlatformToolsRev() {
return mMinPlatformToolsRev;
}
@Override
public String getInstallId() {
StringBuilder sb = new StringBuilder();
/* iid patterns:
tools, platform-tools => FOLDER / FOLDER-preview
build-tools => FOLDER-REV
doc, sample, source => ENUM-API
extra => ENUM-VENDOR.id-PATH
platform => android-API
add-on => addon-NAME.id-VENDOR.id-API
platform sys-img => sys-img-ABI-TAG|android-API
add-on sys-img => sys-img-ABI-addon-NAME.id-VENDOR.id-API
*/
switch (mType) {
case PKG_TOOLS:
case PKG_PLATFORM_TOOLS:
sb.append(mType.getFolderName());
if (getFullRevision().isPreview()) {
sb.append("-preview");
}
break;
case PKG_BUILD_TOOLS:
sb.append(mType.getFolderName());
sb.append('-').append(getFullRevision().toString());
break;
case PKG_DOC:
case PKG_SAMPLE:
case PKG_SOURCE:
sb.append(mType.toString().toLowerCase(Locale.US).replace("pkg_", ""));
sb.append('-').append(getAndroidVersion().getApiString());
break;
case PKG_EXTRA:
sb.append("extra-")
.append(getVendor().getId())
.append('-')
.append(getPath());
break;
case PKG_PLATFORM:
sb.append(AndroidTargetHash.PLATFORM_HASH_PREFIX).append(getAndroidVersion().getApiString());
break;
case PKG_ADDON:
sb.append("addon-")
.append(((IPkgDescAddon) this).getName().getId())
.append('-')
.append(getVendor().getId())
.append('-')
.append(getAndroidVersion().getApiString());
break;
case PKG_SYS_IMAGE:
sb.append("sys-img-")
.append(getPath()) // path==ABI for sys-img
.append('-')
.append(SystemImage.DEFAULT_TAG.equals(getTag()) ? "android" : getTag().getId())
.append('-')
.append(getAndroidVersion().getApiString());
break;
case PKG_ADDON_SYS_IMAGE:
sb.append("sys-img-")
.append(getPath()) // path==ABI for sys-img
.append("-addon-")
.append(SystemImage.DEFAULT_TAG.equals(getTag()) ? "android" : getTag().getId())
.append('-')
.append(getVendor().getId())
.append('-')
.append(getAndroidVersion().getApiString());
break;
default:
throw new IllegalArgumentException("IID not defined for type " + mType.toString());
}
return sanitize(sb.toString());
}
@Override
public File getCanonicalInstallFolder(@NonNull File sdkLocation) {
File f = FileOp.append(sdkLocation, mType.getFolderName());
/* folder patterns:
tools, platform-tools, doc => FOLDER
build-tools, add-on => FOLDER/IID
platform, sample, source => FOLDER/android-API
platform sys-img => FOLDER/android-API/TAG/ABI
add-on sys-img => FOLDER/addon-NAME.id-VENDOR.id-API/ABI
extra => FOLDER/VENDOR.id/PATH
*/
switch (mType) {
case PKG_TOOLS:
case PKG_PLATFORM_TOOLS:
case PKG_DOC:
// no-op, top-folder is all what is needed here
break;
case PKG_BUILD_TOOLS:
case PKG_ADDON:
f = FileOp.append(f, getInstallId());
break;
case PKG_PLATFORM:
case PKG_SAMPLE:
case PKG_SOURCE:
f = FileOp.append(f, AndroidTargetHash.PLATFORM_HASH_PREFIX + sanitize(getAndroidVersion().getApiString()));
break;
case PKG_SYS_IMAGE:
f = FileOp.append(f,
AndroidTargetHash.PLATFORM_HASH_PREFIX + sanitize(getAndroidVersion().getApiString()),
sanitize(SystemImage.DEFAULT_TAG.equals(getTag()) ? "android" : getTag().getId()),
sanitize(getPath())); // path==abi
break;
case PKG_ADDON_SYS_IMAGE:
String name = "addon-"
+ (SystemImage.DEFAULT_TAG.equals(getTag()) ? "android" : getTag().getId())
+ '-'
+ getVendor().getId()
+ '-'
+ getAndroidVersion().getApiString();
f = FileOp.append(f,
sanitize(name),
sanitize(getPath())); // path==abi
break;
case PKG_EXTRA:
f = FileOp.append(f,
sanitize(getVendor().getId()),
sanitize(getPath()));
break;
default:
throw new IllegalArgumentException("CanonicalFolder not defined for type " + mType.toString());
}
return f;
}
//---- Updating ----
/**
* Computes the most general case of {@link #isUpdateFor(IPkgDesc)}.
* Individual package types use this and complement with their own specific cases
* as needed.
*
* @param existingDesc A non-null package descriptor to compare with.
* @return True if this package descriptor would generally update the given one.
*/
@Override
public boolean isUpdateFor(@NonNull IPkgDesc existingDesc) {
if (mCustomIsUpdateFor != null) {
return mCustomIsUpdateFor.isUpdateFor(this, existingDesc);
} else {
return isGenericUpdateFor(existingDesc);
}
}
/**
* Computes the most general case of {@link #isUpdateFor(IPkgDesc)}.
* Individual package types use this and complement with their own specific cases
* as needed.
*
* @param existingDesc A non-null package descriptor to compare with.
* @return True if this package descriptor would generally update the given one.
*/
private boolean isGenericUpdateFor(@NonNull IPkgDesc existingDesc) {
if (existingDesc == null || !getType().equals(existingDesc.getType())) {
return false;
}
// Packages that have an Android version can generally only be updated
// for the same Android version (otherwise it's a new artifact.)
if (hasAndroidVersion() && !getAndroidVersion().equals(existingDesc.getAndroidVersion())) {
return false;
}
// Packages that have a vendor id need the same vendor id on both sides
if (hasVendor() && !getVendor().equals(existingDesc.getVendor())) {
return false;
}
// Packages that have a tag id need the same tag id on both sides
if (hasTag() && !getTag().getId().equals(existingDesc.getTag().getId())) {
return false;
}
// Packages that have a path can generally only be updated if both use the same path
if (hasPath()) {
if (this instanceof IPkgDescExtra) {
// Extra package handle paths differently, they need to use the old_path
// to allow upgrade compatibility.
if (!PkgDescExtra.compatibleVendorAndPath((IPkgDescExtra) this,
(IPkgDescExtra) existingDesc)) {
return false;
}
} else if (!getPath().equals(existingDesc.getPath())) {
return false;
}
}
// Packages that have a major version are generally updates if it increases.
if (hasMajorRevision() &&
getMajorRevision().compareTo(existingDesc.getMajorRevision()) > 0) {
return true;
}
// Packages that have a full revision are generally updates if it increases
// but keeps the same kind of preview (e.g. previews are only updates by previews.)
if (hasFullRevision() &&
getFullRevision().isPreview() == existingDesc.getFullRevision().isPreview()) {
// If both packages match in their preview type (both previews or both not previews)
// then is the RC/preview number an update?
return getFullRevision().compareTo(existingDesc.getFullRevision(),
PreviewComparison.COMPARE_NUMBER) > 0;
}
return false;
}
//---- Ordering ----
/**
* Compares this descriptor to another one.
* All fields must match for equality.
* <p/>
* This is must not be used an indication that a package is a suitable update for another one.
* The comparison order is however suitable for sorting packages for display purposes.
*/
@Override
public int compareTo(@NonNull IPkgDesc o) {
int t1 = getType().getIntValue();
int t2 = o.getType().getIntValue();
if (t1 != t2) {
return t1 - t2;
}
if (hasAndroidVersion() && o.hasAndroidVersion()) {
t1 = getAndroidVersion().compareTo(o.getAndroidVersion());
if (t1 != 0) {
return t1;
}
}
if (hasVendor() && o.hasVendor()) {
t1 = getVendor().compareTo(o.getVendor());
if (t1 != 0) {
return t1;
}
}
if (hasTag() && o.hasTag()) {
t1 = getTag().compareTo(o.getTag());
if (t1 != 0) {
return t1;
}
}
if (hasPath() && o.hasPath()) {
t1 = getPath().compareTo(o.getPath());
if (t1 != 0) {
return t1;
}
}
if (hasFullRevision() && o.hasFullRevision()) {
t1 = getFullRevision().compareTo(o.getFullRevision());
if (t1 != 0) {
return t1;
}
}
if (hasMajorRevision() && o.hasMajorRevision()) {
t1 = getMajorRevision().compareTo(o.getMajorRevision());
if (t1 != 0) {
return t1;
}
}
if (hasMinToolsRev() && o.hasMinToolsRev()) {
t1 = getMinToolsRev().compareTo(o.getMinToolsRev());
if (t1 != 0) {
return t1;
}
}
if (hasMinPlatformToolsRev() && o.hasMinPlatformToolsRev()) {
t1 = getMinPlatformToolsRev().compareTo(o.getMinPlatformToolsRev());
if (t1 != 0) {
return t1;
}
}
return 0;
}
// --- display description ----
@NonNull
@Override
public String getListDescription() {
if (mListDisplay != null && !mListDisplay.isEmpty()) {
return mListDisplay;
}
return patternReplaceImpl(getType().getListDisplayPattern());
}
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected String patternReplaceImpl(String result) {
// Flags for list description pattern string, used in PkgType:
// $MAJ $FULL $API $PATH $TAG $VEND $NAME (for extras)
result = result.replace("$MAJ", hasMajorRevision() ? getMajorRevision().toShortString() : "");
result = result.replace("$FULL", hasFullRevision() ? getFullRevision() .toShortString() : "");
result = result.replace("$API", hasAndroidVersion() ? getAndroidVersion().getApiString() : "");
result = result.replace("$PATH", hasPath() ? getPath() : "");
result = result.replace("$TAG", hasTag() && !getTag().equals(SystemImage.DEFAULT_TAG) ?
getTag().getDisplay() : "");
result = result.replace("$VEND", hasVendor() ? getVendor().getDisplay() : "");
String name = "";
if (this instanceof IPkgDescExtra) {
name = ((IPkgDescExtra) this).getNameDisplay();
} else if (this instanceof IPkgDescAddon) {
name = ((IPkgDescAddon) this).getName().getDisplay();
}
result = result.replace("$NAME", name);
// Evaluate replacements.
// {|choice1|choice2|...|choiceN|} gets replaced by the first non-empty choice.
for (int start = result.indexOf("{|");
start >= 0;
start = result.indexOf("{|")) {
int end = result.indexOf('}', start);
int last = start + 1;
for (int pipe = result.indexOf('|', last+1);
pipe > start;
last = pipe, pipe = result.indexOf('|', last+1)) {
if (pipe - last > 1) {
result = result.substring(0, start) +
result.substring(last+1, pipe) +
result.substring(end+1);
break;
}
}
}
// Evaluate conditions.
// {?value>1:text to use} -- uses the text if value is greater than 1.
// Simplification: this is our only test right now so hard-code it instead of
// using a generic expression evaluation.
for (int start = result.indexOf("{?");
start >= 0;
start = result.indexOf("{?")) {
int end = result.indexOf('}', start);
int op = result.indexOf(">1:");
if (op > start) {
String value = "";
try {
FullRevision i = FullRevision.parseRevision(result.substring(start+2, op));
if (i.compareTo(new FullRevision(1)) > 0) {
value = result.substring(op+3, end);
}
} catch (NumberFormatException e) {
value = "ERROR " + e.getMessage() + " in " + result.substring(start, end+1);
}
result = result.substring(0, start) +
value +
result.substring(end+1);
}
}
return result;
}
/** String representation for debugging purposes. */
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("<PkgDesc"); //NON-NLS-1$
builder.append(" Type="); //NON-NLS-1$
builder.append(getType().toString()
.toLowerCase(Locale.US)
.replace("pkg_", "")); //NON-NLS-1$ //NON-NLS-2$
if (hasAndroidVersion()) {
builder.append(" Android=").append(getAndroidVersion()); //NON-NLS-1$
}
if (hasVendor()) {
builder.append(" Vendor=").append(getVendor().toString()); //NON-NLS-1$
}
if (hasTag()) {
builder.append(" Tag=").append(getTag()); //NON-NLS-1$
}
if (hasPath()) {
builder.append(" Path=").append(getPath()); //NON-NLS-1$
}
if (hasFullRevision()) {
builder.append(" FullRev=").append(getFullRevision()); //NON-NLS-1$
}
if (hasMajorRevision()) {
builder.append(" MajorRev=").append(getMajorRevision()); //NON-NLS-1$
}
if (hasMinToolsRev()) {
builder.append(" MinToolsRev=").append(getMinToolsRev()); //NON-NLS-1$
}
if (hasMinPlatformToolsRev()) {
builder.append(" MinPlatToolsRev=").append(getMinPlatformToolsRev()); //NON-NLS-1$
}
if (mListDisplay != null) {
builder.append(" ListDisp=").append(mListDisplay); //NON-NLS-1$
}
if (mDescriptionShort != null) {
builder.append(" DescShort=").append(mDescriptionShort); //NON-NLS-1$
}
if (mDescriptionUrl != null) {
builder.append(" DescUrl=").append(mDescriptionUrl); //NON-NLS-1$
}
if (mLicense != null) {
builder.append(" License['").append(mLicense.getLicenseRef()) //NON-NLS-1$
.append("]=") //NON-NLS-1$
.append(mLicense.getLicense().length()).append(" chars"); //NON-NLS-1$
}
if (isObsolete()) {
builder.append(" Obsolete=yes"); //NON-NLS-1$
}
builder.append('>');
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (hasAndroidVersion() ? getAndroidVersion().hashCode() : 0);
result = prime * result + (hasVendor() ? getVendor() .hashCode() : 0);
result = prime * result + (hasTag() ? getTag() .hashCode() : 0);
result = prime * result + (hasPath() ? getPath() .hashCode() : 0);
result = prime * result + (hasFullRevision() ? getFullRevision() .hashCode() : 0);
result = prime * result + (hasMajorRevision() ? getMajorRevision() .hashCode() : 0);
result = prime * result + (hasMinToolsRev() ? getMinToolsRev() .hashCode() : 0);
result = prime * result + (hasMinPlatformToolsRev() ?
getMinPlatformToolsRev().hashCode() : 0);
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof IPkgDesc)) return false;
IPkgDesc rhs = (IPkgDesc) obj;
if (hasAndroidVersion() != rhs.hasAndroidVersion()) {
return false;
}
if (hasAndroidVersion() && !getAndroidVersion().equals(rhs.getAndroidVersion())) {
return false;
}
if (hasTag() != rhs.hasTag()) {
return false;
}
if (hasTag() && !getTag().equals(rhs.getTag())) {
return false;
}
if (hasPath() != rhs.hasPath()) {
return false;
}
if (hasPath() && !getPath().equals(rhs.getPath())) {
return false;
}
if (hasFullRevision() != rhs.hasFullRevision()) {
return false;
}
if (hasFullRevision() && !getFullRevision().equals(rhs.getFullRevision())) {
return false;
}
if (hasMajorRevision() != rhs.hasMajorRevision()) {
return false;
}
if (hasMajorRevision() && !getMajorRevision().equals(rhs.getMajorRevision())) {
return false;
}
if (hasMinToolsRev() != rhs.hasMinToolsRev()) {
return false;
}
if (hasMinToolsRev() && !getMinToolsRev().equals(rhs.getMinToolsRev())) {
return false;
}
if (hasMinPlatformToolsRev() != rhs.hasMinPlatformToolsRev()) {
return false;
}
if (hasMinPlatformToolsRev() &&
!getMinPlatformToolsRev().equals(rhs.getMinPlatformToolsRev())) {
return false;
}
return true;
}
// ---- Constructors -----
public interface IIsUpdateFor {
public boolean isUpdateFor(@NonNull PkgDesc thisPkgDesc, @NonNull IPkgDesc existingDesc);
}
public interface IGetPath {
public String getPath(@NonNull PkgDesc thisPkgDesc);
}
public static class Builder {
private final PkgType mType;
private FullRevision mFullRevision;
private MajorRevision mMajorRevision;
private AndroidVersion mAndroidVersion;
private String mPath;
private IdDisplay mTag;
private IdDisplay mVendor;
private FullRevision mMinToolsRev;
private FullRevision mMinPlatformToolsRev;
private IIsUpdateFor mCustomIsUpdateFor;
private IGetPath mCustomPath;
private String[] mOldPaths;
private String mNameDisplay;
private IdDisplay mNameIdDisplay;
private License mLicense;
private String mListDisplay;
private String mDescriptionShort;
private String mDescriptionUrl;
private boolean mIsObsolete;
private Builder(PkgType type) {
mType = type;
}
/**
* Creates a new tool package descriptor.
*
* @param revision The revision of the tool package.
* @param minPlatformToolsRev The {@code min-platform-tools-rev}.
* Use {@link FullRevision#NOT_SPECIFIED} to indicate there is no requirement.
* @return A {@link PkgDesc} describing this tool package.
*/
@NonNull
public static Builder newTool(@NonNull FullRevision revision,
@NonNull FullRevision minPlatformToolsRev) {
Builder p = new Builder(PkgType.PKG_TOOLS);
p.mFullRevision = revision;
p.mMinPlatformToolsRev = minPlatformToolsRev;
return p;
}
/**
* Creates a new platform-tool package descriptor.
*
* @param revision The revision of the platform-tool package.
* @return A {@link PkgDesc} describing this platform-tool package.
*/
@NonNull
public static Builder newPlatformTool(@NonNull FullRevision revision) {
Builder p = new Builder(PkgType.PKG_PLATFORM_TOOLS);
p.mFullRevision = revision;
return p;
}
/**
* Creates a new build-tool package descriptor.
*
* @param revision The revision of the build-tool package.
* @return A {@link PkgDesc} describing this build-tool package.
*/
@NonNull
public static Builder newBuildTool(@NonNull FullRevision revision) {
Builder p = new Builder(PkgType.PKG_BUILD_TOOLS);
p.mFullRevision = revision;
p.mCustomIsUpdateFor = new IIsUpdateFor() {
@Override
public boolean isUpdateFor(PkgDesc thisPkgDesc, IPkgDesc existingDesc) {
// Generic test checks that the preview type is the same (both previews or not).
// Build tool is different in that the full revision must be an exact match
// and not an increase.
return thisPkgDesc.isGenericUpdateFor(existingDesc) &&
thisPkgDesc.getFullRevision().compareTo(
existingDesc.getFullRevision(),
PreviewComparison.COMPARE_TYPE) == 0;
}
};
return p;
}
/**
* Creates a new doc package descriptor.
*
* @param revision The revision of the doc package.
* @return A {@link PkgDesc} describing this doc package.
*/
@NonNull
public static Builder newDoc(@NonNull AndroidVersion version,
@NonNull MajorRevision revision) {
Builder p = new Builder(PkgType.PKG_DOC);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
p.mCustomIsUpdateFor = new IIsUpdateFor() {
@Override
public boolean isUpdateFor(PkgDesc thisPkgDesc, IPkgDesc existingDesc) {
if (existingDesc == null ||
!thisPkgDesc.getType().equals(existingDesc.getType())) {
return false;
}
// This package is unique in the SDK. It's an update if the API is newer
// or the revision is newer for the same API.
int diff = thisPkgDesc.getAndroidVersion().compareTo(
existingDesc.getAndroidVersion());
return diff > 0 ||
(diff == 0 && thisPkgDesc.getMajorRevision().compareTo(
existingDesc.getMajorRevision()) > 0);
}
};
return p;
}
/**
* Creates a new extra package descriptor.
*
* @param vendor The vendor id string of the extra package.
* @param path The path id string of the extra package.
* @param displayName The display name. If missing, caller should build one using the path.
* @param oldPaths An optional list of older paths for this extra package.
* @param revision The revision of the extra package.
* @return A {@link PkgDesc} describing this extra package.
*/
@NonNull
public static Builder newExtra(@NonNull IdDisplay vendor,
@NonNull String path,
@NonNull String displayName,
@Nullable String[] oldPaths,
@NonNull NoPreviewRevision revision) {
Builder p = new Builder(PkgType.PKG_EXTRA);
p.mFullRevision = revision;
p.mVendor = vendor;
p.mPath = path;
p.mNameDisplay = displayName;
p.mOldPaths = oldPaths;
return p;
}
/**
* Creates a new platform package descriptor.
*
* @param version The android version of the platform package.
* @param revision The revision of the extra package.
* @param minToolsRev An optional {@code min-tools-rev}.
* Use {@link FullRevision#NOT_SPECIFIED} to indicate
* there is no requirement.
* @return A {@link PkgDesc} describing this platform package.
*/
@NonNull
public static Builder newPlatform(@NonNull AndroidVersion version,
@NonNull MajorRevision revision,
@NonNull FullRevision minToolsRev) {
Builder p = new Builder(PkgType.PKG_PLATFORM);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
p.mMinToolsRev = minToolsRev;
p.mCustomPath = new IGetPath() {
@Override
public String getPath(PkgDesc thisPkgDesc) {
/** The "path" of a Platform is its Target Hash. */
return AndroidTargetHash.getPlatformHashString(thisPkgDesc.getAndroidVersion());
}
};
return p;
}
/**
* Create a new add-on package descriptor.
* <p/>
* The vendor id and the name id provided are used to compute the add-on's
* target hash.
*
* @param version The android version of the add-on package.
* @param revision The revision of the add-on package.
* @param addonVendor The vendor id/display of the add-on package.
* @param addonName The name id/display of the add-on package.
* @return A {@link PkgDesc} describing this add-on package.
*/
@NonNull
public static Builder newAddon(@NonNull AndroidVersion version,
@NonNull MajorRevision revision,
@NonNull IdDisplay addonVendor,
@NonNull IdDisplay addonName) {
Builder p = new Builder(PkgType.PKG_ADDON);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
p.mVendor = addonVendor;
p.mNameIdDisplay = addonName;
return p;
}
/**
* Create a new platform system-image package descriptor.
* <p/>
* For system-images, {@link PkgDesc#getPath()} returns the ABI.
*
* @param version The android version of the system-image package.
* @param tag The tag of the system-image package.
* @param abi The ABI of the system-image package.
* @param revision The revision of the system-image package.
* @return A {@link PkgDesc} describing this system-image package.
*/
@NonNull
public static Builder newSysImg(@NonNull AndroidVersion version,
@NonNull IdDisplay tag,
@NonNull String abi,
@NonNull MajorRevision revision) {
Builder p = new Builder(PkgType.PKG_SYS_IMAGE);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
p.mTag = tag;
p.mPath = abi;
p.mVendor = null;
return p;
}
/**
* Create a new add-on system-image package descriptor.
* <p/>
* For system-images, {@link PkgDesc#getPath()} returns the ABI.
*
* @param version The android version of the system-image package.
* @param addonVendor The vendor id/display of an associated add-on.
* @param addonName The tag of the system-image package is the add-on name.
* @param abi The ABI of the system-image package.
* @param revision The revision of the system-image package.
* @return A {@link PkgDesc} describing this system-image package.
*/
@NonNull
public static Builder newAddonSysImg(@NonNull AndroidVersion version,
@NonNull IdDisplay addonVendor,
@NonNull IdDisplay addonName,
@NonNull String abi,
@NonNull MajorRevision revision) {
Builder p = new Builder(PkgType.PKG_ADDON_SYS_IMAGE);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
p.mTag = addonName;
p.mPath = abi;
p.mVendor = addonVendor;
return p;
}
/**
* Create a new source package descriptor.
*
* @param version The android version of the source package.
* @param revision The revision of the source package.
* @return A {@link PkgDesc} describing this source package.
*/
@NonNull
public static Builder newSource(@NonNull AndroidVersion version,
@NonNull MajorRevision revision) {
Builder p = new Builder(PkgType.PKG_SOURCE);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
return p;
}
/**
* Create a new sample package descriptor.
*
* @param version The android version of the sample package.
* @param revision The revision of the sample package.
* @param minToolsRev An optional {@code min-tools-rev}.
* Use {@link FullRevision#NOT_SPECIFIED} to indicate
* there is no requirement.
* @return A {@link PkgDesc} describing this sample package.
*/
@NonNull
public static Builder newSample(@NonNull AndroidVersion version,
@NonNull MajorRevision revision,
@NonNull FullRevision minToolsRev) {
Builder p = new Builder(PkgType.PKG_SAMPLE);
p.mAndroidVersion = version;
p.mMajorRevision = revision;
p.mMinToolsRev = minToolsRev;
return p;
}
public Builder setDescriptions(@NonNull Package pkg) {
mDescriptionShort = pkg.getShortDescription();
mDescriptionUrl = pkg.getDescUrl();
mListDisplay = pkg.getListDisplay();
mIsObsolete = pkg.isObsolete();
mLicense = pkg.getLicense();
return this;
}
public Builder setLicense(@Nullable License license) {
mLicense = license;
return this;
}
public Builder setListDisplay(@Nullable String text) {
mListDisplay = text;
return this;
}
public Builder setDescriptionShort(@Nullable String text) {
mDescriptionShort = text;
return this;
}
public Builder setDescriptionUrl(@Nullable String text) {
mDescriptionUrl = text;
return this;
}
public Builder setIsObsolete(boolean isObsolete) {
mIsObsolete = isObsolete;
return this;
}
public IPkgDesc create() {
if (mType == PkgType.PKG_ADDON) {
return new PkgDescAddon(
mType,
mLicense,
mListDisplay,
mDescriptionShort,
mDescriptionUrl,
mIsObsolete,
mMajorRevision,
mAndroidVersion,
mVendor,
mNameIdDisplay);
}
if (mType == PkgType.PKG_EXTRA) {
return new PkgDescExtra(
mType,
mLicense,
mListDisplay,
mDescriptionShort,
mDescriptionUrl,
mIsObsolete,
mFullRevision,
mMajorRevision,
mAndroidVersion,
mPath,
mTag,
mVendor,
mMinToolsRev,
mMinPlatformToolsRev,
mNameDisplay,
mOldPaths);
}
return new PkgDesc(
mType,
mLicense,
mListDisplay,
mDescriptionShort,
mDescriptionUrl,
mIsObsolete,
mFullRevision,
mMajorRevision,
mAndroidVersion,
mPath,
mTag,
mVendor,
mMinToolsRev,
mMinPlatformToolsRev,
mCustomIsUpdateFor,
mCustomPath);
}
}
// ---- Helpers -----
@NonNull
private static String sanitize(@NonNull String str) {
str = str.toLowerCase(Locale.US).replaceAll("[^a-z0-9_.-]+", "_").replaceAll("_+", "_");
return str;
}
}
|
3e17acd19b4982d4381d0464007e5f32678e55b3 | 1,421 | java | Java | algorithm/src/main/java/com/aninda/graph/GraphCycle.java | aninda08/Algorithms | d4d038520829ab5157f730e78467f833bb321662 | [
"Apache-2.0"
] | null | null | null | algorithm/src/main/java/com/aninda/graph/GraphCycle.java | aninda08/Algorithms | d4d038520829ab5157f730e78467f833bb321662 | [
"Apache-2.0"
] | null | null | null | algorithm/src/main/java/com/aninda/graph/GraphCycle.java | aninda08/Algorithms | d4d038520829ab5157f730e78467f833bb321662 | [
"Apache-2.0"
] | null | null | null | 21.530303 | 61 | 0.465869 | 10,087 | package com.aninda.graph;
public class GraphCycle {
int V, E;
Edge edge[];
int edgeCount = 0;
class Edge {
int src, dest;
}
public GraphCycle(int v, int e) {
this.V = v;
this.E = e;
this.edge = new Edge[e];
for (int i = 0; i < e; i++) {
edge[i] = new Edge();
}
}
public void addEdge(int src, int dest) throws Exception {
if(this.edgeCount > this.E)
throw new Exception("Edge count is full");
this.edge[edgeCount].src = src;
this.edge[edgeCount].dest = dest;
this.edgeCount++;
}
public int find(int parent[], int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
public void union(int parent[], int x, int y) {
parent[x] = y;
}
public boolean isCycle() throws Exception {
if (edgeCount < this.E - 1) {
throw new Exception("Edge count is not full");
}
int[] parent = new int[this.V];
for (int i = 0; i < this.V; i++) {
parent[i] = -1;
}
for (int i = 0; i < this.E; i++) {
int x = find(parent, this.edge[i].src);
int y = find(parent, this.edge[i].dest);
if (x == y)
return true;
union(parent, x, y);
}
return false;
}
}
|
3e17acd6e46aea3e39572db11bd946f8a5c6d869 | 1,136 | java | Java | violin-test/src/main/java/com/wolf/test/jibx/Account.java | liyork/violin | 4f99d5461796df9debf33838d2ea7a16c1cb63c3 | [
"Apache-2.0"
] | null | null | null | violin-test/src/main/java/com/wolf/test/jibx/Account.java | liyork/violin | 4f99d5461796df9debf33838d2ea7a16c1cb63c3 | [
"Apache-2.0"
] | 24 | 2020-03-04T22:07:41.000Z | 2022-01-21T23:50:53.000Z | violin-test/src/main/java/com/wolf/test/jibx/Account.java | liyork/violin | 4f99d5461796df9debf33838d2ea7a16c1cb63c3 | [
"Apache-2.0"
] | 1 | 2017-06-27T09:15:50.000Z | 2017-06-27T09:15:50.000Z | 17.75 | 103 | 0.566021 | 10,088 | package com.wolf.test.jibx;
/**
* Description:
* <br/> Created on 2018/2/6 9:40
*
* @author 李超
* @since 1.0.0
*/
public class Account {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter、setter
@Override
public String toString() {
return this.id + "#" + this.name + "#" + this.email + "#" + this.address + "#" + this.birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
}
|
3e17ae50d5745e1e02da7e433072edf0b8c7ac62 | 1,835 | java | Java | litemall-date/src/main/java/org/linlinjava/litemall/db/service/impl/CartServiceImpl.java | dreamGitCJB/phosphor | 6e27fd81d972f6f0105b0cdd1a0fd3625b49c403 | [
"MIT"
] | 1 | 2020-05-13T09:06:16.000Z | 2020-05-13T09:06:16.000Z | litemall-date/src/main/java/org/linlinjava/litemall/db/service/impl/CartServiceImpl.java | dreamGitCJB/phosphor | 6e27fd81d972f6f0105b0cdd1a0fd3625b49c403 | [
"MIT"
] | null | null | null | litemall-date/src/main/java/org/linlinjava/litemall/db/service/impl/CartServiceImpl.java | dreamGitCJB/phosphor | 6e27fd81d972f6f0105b0cdd1a0fd3625b49c403 | [
"MIT"
] | null | null | null | 34.622642 | 155 | 0.716076 | 10,089 | package org.linlinjava.litemall.db.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.linlinjava.litemall.db.entity.Cart;
import org.linlinjava.litemall.db.mapper.CartMapper;
import org.linlinjava.litemall.db.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 购物车商品表 服务实现类
* </p>
*
* @author chenjinbao
* @since 2020-05-03
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
@Override
public List<Cart> queryByUid(Integer userId) {
List<Cart> cartList = this.list(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, userId));
return cartList;
}
@Override
public Cart queryExist(Integer goodsId, Integer productId, Integer userId) {
return this.getOne(new LambdaQueryWrapper<Cart>().eq(Cart::getGoodsId, goodsId).eq(Cart::getProductId, productId).eq(Cart::getUserId, userId));
}
@Override
public Cart findById(Integer userId, Integer id) {
return this.getOne(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, userId).eq(Cart::getId, id));
}
@Override
public boolean updateCheck(Integer userId, List<Integer> idsList, Boolean checked) {
Cart cart = new Cart();
cart.setChecked(checked);
boolean update = this.update(cart, new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, userId).in(idsList.size() > 0, Cart::getProductId, idsList));
return update;
}
@Override
public List<Cart> queryByUidAndChecked(Integer userId) {
List<Cart> cartList = this.list(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, userId).eq(Cart::getChecked, true));
return cartList;
}
}
|
3e17ae9dc88babad6631e87bdad27f17e3a4e89d | 2,275 | java | Java | javers-core/src/main/java/org/javers/core/diff/custom/CustomPropertyComparator.java | andreiamariei/javers | 41813d0f140abe7a0f5ab6554b399b34dfc2c5dc | [
"Apache-2.0"
] | 887 | 2015-01-05T21:31:44.000Z | 2022-03-30T08:28:23.000Z | javers-core/src/main/java/org/javers/core/diff/custom/CustomPropertyComparator.java | andreiamariei/javers | 41813d0f140abe7a0f5ab6554b399b34dfc2c5dc | [
"Apache-2.0"
] | 764 | 2015-01-02T08:27:56.000Z | 2022-03-28T08:31:43.000Z | javers-core/src/main/java/org/javers/core/diff/custom/CustomPropertyComparator.java | andreiamariei/javers | 41813d0f140abe7a0f5ab6554b399b34dfc2c5dc | [
"Apache-2.0"
] | 349 | 2015-02-15T11:46:05.000Z | 2022-02-25T15:02:36.000Z | 39.224138 | 165 | 0.702418 | 10,090 | package org.javers.core.diff.custom;
import org.javers.core.diff.changetype.PropertyChange;
import org.javers.core.diff.changetype.PropertyChangeMetadata;
import org.javers.core.diff.changetype.ValueChange;
import org.javers.core.metamodel.property.Property;
import org.javers.core.metamodel.type.CustomType;
import org.javers.core.metamodel.type.ValueType;
import java.util.Optional;
/**
* Property-scope comparator bounded to {@link CustomType}.
* <br/><br/>
*
* <b>
* Custom Types are not easy to manage, use it as a last resort,<br/>
* only for corner cases like comparing custom Collection types.</b>
* <br/><br/>
*
* Typically, Custom Types are large structures (like Multimap).<br/>
* Implementation should calculate diff between two objects of given Custom Type.
* <br/><br/>
*
* <b>Usage</b>:
* <pre>
* JaversBuilder.javers()
* .registerCustomType( Multimap.class, new GuavaCustomComparator())
* .build()
* </pre>
*
* @param <T> Custom Type
* @param <C> Concrete type of PropertyChange returned by a comparator
* @see <a href="https://javers.org/documentation/diff-configuration/#custom-comparators">https://javers.org/documentation/diff-configuration/#custom-comparators</a>
* @see CustomValueComparator
*/
public interface CustomPropertyComparator<T, C extends PropertyChange> extends CustomValueComparator<T> {
/**
* Called by JaVers to calculate property-to-property diff
* between two Custom Type objects. Can calculate any of concrete {@link PropertyChange}.
*
* <br/><br/>
* Implementation of <code>compare()</code> should be consistent with
* {@link #equals(Object, Object)}.
* When <code>compare()</code> returns <code>Optional.empty()</code>,
* <code>equals()</code> should return false.
*
* @param left left (or old) value
* @param right right (or current) value
* @param metadata call {@link PropertyChangeMetadata#getAffectedCdoId()} to get
* Id of domain object being compared
* @param property property being compared
*
* @return should return Optional.empty() if compared objects are the same
*/
Optional<C> compare(T left, T right, PropertyChangeMetadata metadata, Property property);
}
|
3e17ae9de58f929f0f572d058e30e3ed3227087d | 5,044 | java | Java | compiler/src/test-integration/java/io/neow3j/compiler/StorageMapIntegrationTest2.java | hurui200320/neow3j | 74e31bde5dcb947df205d1d1a43bb465c1f8e6cf | [
"Apache-2.0"
] | null | null | null | compiler/src/test-integration/java/io/neow3j/compiler/StorageMapIntegrationTest2.java | hurui200320/neow3j | 74e31bde5dcb947df205d1d1a43bb465c1f8e6cf | [
"Apache-2.0"
] | null | null | null | compiler/src/test-integration/java/io/neow3j/compiler/StorageMapIntegrationTest2.java | hurui200320/neow3j | 74e31bde5dcb947df205d1d1a43bb465c1f8e6cf | [
"Apache-2.0"
] | null | null | null | 39.100775 | 97 | 0.698454 | 10,091 | package io.neow3j.compiler;
import io.neow3j.devpack.ByteString;
import io.neow3j.devpack.Hash160;
import io.neow3j.devpack.Hash256;
import io.neow3j.devpack.Storage;
import io.neow3j.devpack.StorageContext;
import io.neow3j.devpack.StorageMap;
import io.neow3j.protocol.core.response.InvocationResult;
import io.neow3j.types.ContractParameter;
import io.neow3j.wallet.Account;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.io.IOException;
import static io.neow3j.devpack.StringLiteralHelper.hexToBytes;
import static io.neow3j.types.ContractParameter.byteArray;
import static io.neow3j.types.ContractParameter.hash160;
import static io.neow3j.types.ContractParameter.hash256;
import static io.neow3j.types.ContractParameter.string;
import static io.neow3j.utils.Numeric.reverseHexString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class StorageMapIntegrationTest2 {
@Rule
public TestName testName = new TestName();
@ClassRule
public static ContractTestRule ct = new ContractTestRule(
StorageMapIntegrationTest2.StorageMapIntegrationTestContract.class.getName());
@Test
public void putByteArrayKeyHash160Value() throws IOException {
Account v = ct.getDefaultAccount();
ContractParameter key = byteArray("02");
ContractParameter value = hash160(v);
InvocationResult res = ct.callInvokeFunction(testName, key, value).getInvocationResult();
assertThat(res.getStack().get(0).getAddress(), is(v.getAddress()));
}
@Test
public void putByteArrayKeyHash256Value() throws IOException {
String v = ct.getDeployTxHash().toString();
ContractParameter key = byteArray("02");
ContractParameter value = hash256(v);
InvocationResult res = ct.callInvokeFunction(testName, key, value).getInvocationResult();
assertThat(res.getStack().get(0).getHexString(), is(reverseHexString(v)));
}
@Test
public void putByteStringKeyHash160Value() throws IOException {
Account v = ct.getDefaultAccount();
ContractParameter key = byteArray("02");
ContractParameter value = hash160(v);
InvocationResult res = ct.callInvokeFunction(testName, key, value).getInvocationResult();
assertThat(res.getStack().get(0).getAddress(), is(v.getAddress()));
}
@Test
public void putByteStringKeyHash256Value() throws IOException {
String v = ct.getDeployTxHash().toString();
ContractParameter key = byteArray("02");
ContractParameter value = hash256(v);
InvocationResult res = ct.callInvokeFunction(testName, key, value).getInvocationResult();
assertThat(res.getStack().get(0).getHexString(), is(reverseHexString(v)));
}
@Test
public void putStringKeyHash160Value() throws IOException {
Account v = ct.getDefaultAccount();
ContractParameter key = string("aa");
ContractParameter value = hash160(v);
InvocationResult res = ct.callInvokeFunction(testName, key, value).getInvocationResult();
assertThat(res.getStack().get(0).getAddress(), is(v.getAddress()));
}
@Test
public void putStringKeyHash256Value() throws IOException {
String v = ct.getDeployTxHash().toString();
ContractParameter key = string("aa");
ContractParameter value = hash256(v);
InvocationResult res = ct.callInvokeFunction(testName, key, value).getInvocationResult();
assertThat(res.getStack().get(0).getHexString(), is(reverseHexString(v)));
}
static class StorageMapIntegrationTestContract {
static ByteString prefix = hexToBytes("0001");
static StorageContext ctx = Storage.getStorageContext();
static StorageMap map = new StorageMap(ctx, prefix.toByteArray());
public static ByteString putByteArrayKeyHash160Value(byte[] key, Hash160 value) {
map.put(key, value);
return Storage.get(ctx, prefix.concat(key));
}
public static ByteString putByteArrayKeyHash256Value(byte[] key, Hash256 value) {
map.put(key, value);
return Storage.get(ctx, prefix.concat(key));
}
public static ByteString putByteStringKeyHash160Value(ByteString key, Hash160 value) {
map.put(key, value);
return Storage.get(ctx, prefix.concat(key));
}
public static ByteString putByteStringKeyHash256Value(ByteString key, Hash256 value) {
map.put(key, value);
return Storage.get(ctx, prefix.concat(key));
}
public static ByteString putStringKeyHash160Value(String key, Hash160 value) {
map.put(key, value);
return Storage.get(ctx, prefix.concat(key));
}
public static ByteString putStringKeyHash256Value(String key, Hash256 value) {
map.put(key, value);
return Storage.get(ctx, prefix.concat(key));
}
}
}
|
3e17af0a7b5744223a9cc2f26861d4424e6554e9 | 1,413 | java | Java | src/main/java/securibench/micro/factories/Factories1.java | tudo-aqua/securibench-micro | 0ad29be499fa9c602de83583a660c099294a6093 | [
"Apache-2.0"
] | 1 | 2022-03-17T20:56:44.000Z | 2022-03-17T20:56:44.000Z | src/main/java/securibench/micro/factories/Factories1.java | tudo-aqua/securibench-micro | 0ad29be499fa9c602de83583a660c099294a6093 | [
"Apache-2.0"
] | null | null | null | src/main/java/securibench/micro/factories/Factories1.java | tudo-aqua/securibench-micro | 0ad29be499fa9c602de83583a660c099294a6093 | [
"Apache-2.0"
] | null | null | null | 31.711111 | 93 | 0.674142 | 10,092 | // SPDX-FileCopyrightText: 2006 Benjamin Livshits lyhxr@example.com
// SPDX-License-Identifier: Apache-2.0
// This file is part of the SV-Benchmarks collection of verification tasks:
// https://gitlab.com/sosy-lab/benchmarking/sv-benchmarks
/*
@author Benjamin Livshits <lyhxr@example.com>
$Id: Factories1.java,v 1.3 2006/04/04 20:00:41 livshits Exp $
*/
package securibench.micro.factories;
import java.io.IOException;
import java.io.PrintWriter;
import mockx.servlet.http.HttpServletRequest;
import mockx.servlet.http.HttpServletResponse;
import securibench.micro.BasicTestCase;
import securibench.micro.MicroTestCase;
/**
* @servlet description="simple factory problem with toLowerCase"
* @servlet vuln_count = "1"
**/
public class Factories1 extends BasicTestCase implements MicroTestCase {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String s1 = req.getParameter("name");
String s2 = s1.toLowerCase();
String s3 = "abc".toLowerCase();
PrintWriter writer = resp.getWriter();
writer.println(s2); /* BAD */
writer.println(s3); /* OK */
}
public String getDescription() {
return "simple factory problem with toLowerCase";
}
public int getVulnerabilityCount() {
return 1;
}
} |
3e17af79dc4ee7a33285ee08efd71c842aefc86a | 693 | java | Java | backend/src/main/java/io/licensemanager/backend/model/request/LicenseRequest.java | birdman98/LicenseManager-backend | 5669c0be4712eeb54d7bd1d566a1bdc653ec8e0c | [
"MIT"
] | 1 | 2021-04-17T16:02:38.000Z | 2021-04-17T16:02:38.000Z | backend/src/main/java/io/licensemanager/backend/model/request/LicenseRequest.java | pmatras/LicenseManager-backend | 5669c0be4712eeb54d7bd1d566a1bdc653ec8e0c | [
"MIT"
] | null | null | null | backend/src/main/java/io/licensemanager/backend/model/request/LicenseRequest.java | pmatras/LicenseManager-backend | 5669c0be4712eeb54d7bd1d566a1bdc653ec8e0c | [
"MIT"
] | 1 | 2021-01-28T19:03:45.000Z | 2021-01-28T19:03:45.000Z | 25.666667 | 59 | 0.694084 | 10,093 | package io.licensemanager.backend.model.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class LicenseRequest {
private String name;
private String expirationDate;
private Long templateId;
private Long customerId;
private Map<String, Object> values;
public boolean isValid() {
return !StringUtils.isBlank(name) &&
!StringUtils.isBlank(expirationDate) &&
templateId != null && customerId != null &&
values != null && !values.isEmpty();
}
}
|
3e17af8dfaa0a89c1b6b644c5248cde69a75afb0 | 1,115 | java | Java | week12/part1/src/main/java/io/kimmking/cache/pubsub/IotCallBackController.java | sqifun/javaTrainingCamp | c537d21a8361ca83135b0af289b80f35108e3ca5 | [
"Apache-2.0"
] | 1 | 2022-02-11T15:53:30.000Z | 2022-02-11T15:53:30.000Z | week12/part1/src/main/java/io/kimmking/cache/pubsub/IotCallBackController.java | sqifun/javaTrainingCamp | c537d21a8361ca83135b0af289b80f35108e3ca5 | [
"Apache-2.0"
] | null | null | null | week12/part1/src/main/java/io/kimmking/cache/pubsub/IotCallBackController.java | sqifun/javaTrainingCamp | c537d21a8361ca83135b0af289b80f35108e3ca5 | [
"Apache-2.0"
] | null | null | null | 32.794118 | 88 | 0.727354 | 10,094 | package io.kimmking.cache.pubsub;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author da
* @version 1.0
* @description: TODO
* @date 2022年03月27日 14:59
*/
@RestController
@RequestMapping("/iot")
public class IotCallBackController {
//引入Redis客户端操作对象
@Autowired
StringRedisTemplate stringRedisTemplate;
@RequestMapping(value = "/unLockCallBack", method = RequestMethod.POST)
public boolean unLockCallBack(@RequestParam(value = "thingName") String thingName,
@RequestParam(value = "requestId") String requestId) {
//生成监听频道Key
String key = "IOT_" + thingName + "_" + requestId;
//模拟实现消息回调
stringRedisTemplate.convertAndSend(key, "this is a redis callback");
return true;
}
}
|
3e17b03c448e1341d9d4ab47ab7cd55c5e7aef99 | 441 | java | Java | src/main/test/itextjfreechartpoi/ListSizeDemo.java | hua-hnust/myssmdemo | c9d169d4396b4ec0b4389a2394798884ed4fee4b | [
"Apache-2.0"
] | null | null | null | src/main/test/itextjfreechartpoi/ListSizeDemo.java | hua-hnust/myssmdemo | c9d169d4396b4ec0b4389a2394798884ed4fee4b | [
"Apache-2.0"
] | null | null | null | src/main/test/itextjfreechartpoi/ListSizeDemo.java | hua-hnust/myssmdemo | c9d169d4396b4ec0b4389a2394798884ed4fee4b | [
"Apache-2.0"
] | null | null | null | 19.173913 | 52 | 0.655329 | 10,095 | package itextjfreechartpoi;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by xhua on 2018-09-13.
* Describe: 初始化list大小
*/
public class ListSizeDemo {
@Test
public void test(){
List<Date> dataList = new ArrayList<Date>();
System.out.println(dataList.size());
dataList.add(new Date());
System.out.println(dataList.size());
}
}
|
3e17b0a798d2592425abf77b9b350ef9bde1b3cd | 883 | java | Java | src/main/java/com/emarte/regurgitator/core/CoreTypes.java | talmeym/regurgitator-test-common | 98518181fa281462afbd018111abe1242a3233b3 | [
"MIT"
] | null | null | null | src/main/java/com/emarte/regurgitator/core/CoreTypes.java | talmeym/regurgitator-test-common | 98518181fa281462afbd018111abe1242a3233b3 | [
"MIT"
] | null | null | null | src/main/java/com/emarte/regurgitator/core/CoreTypes.java | talmeym/regurgitator-test-common | 98518181fa281462afbd018111abe1242a3233b3 | [
"MIT"
] | null | null | null | 49.055556 | 95 | 0.775764 | 10,096 | /*
* Copyright (C) 2017 Miles Talmey.
* Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
package com.emarte.regurgitator.core;
public class CoreTypes {
public static final StringType STRING = new StringType();
public static final NumberType NUMBER = new NumberType();
public static final DecimalType DECIMAL = new DecimalType();
public static final ListOfStringType LIST_OF_STRING = new ListOfStringType();
public static final ListOfNumberType LIST_OF_NUMBER = new ListOfNumberType();
public static final ListOfDecimalType LIST_OF_DECIMAL = new ListOfDecimalType();
public static final SetOfStringType SET_OF_STRING = new SetOfStringType();
public static final SetOfNumberType SET_OF_NUMBER = new SetOfNumberType();
public static final SetOfDecimalType SET_OF_DECIMAL = new SetOfDecimalType();
}
|
3e17b154062e47494ca3744f528aa29b672b901c | 895 | java | Java | String_Handling/searching_str_3.java | piyush168713/Core-Java | 53a3edddeda0cea977e422f38a7cbaa94432cd44 | [
"Apache-2.0"
] | 1 | 2022-02-02T06:35:50.000Z | 2022-02-02T06:35:50.000Z | String_Handling/searching_str_3.java | piyush168713/Core-Java | 53a3edddeda0cea977e422f38a7cbaa94432cd44 | [
"Apache-2.0"
] | null | null | null | String_Handling/searching_str_3.java | piyush168713/Core-Java | 53a3edddeda0cea977e422f38a7cbaa94432cd44 | [
"Apache-2.0"
] | 1 | 2022-02-02T06:35:55.000Z | 2022-02-02T06:35:55.000Z | 47.105263 | 82 | 0.575419 | 10,097 | package String_Handling;
public class searching_str_3 {
// Demonstrate indexOf() and lastIndexOf().
public static void main(String[] args) {
String s = "Now is the time for all good men " +
"to come to the aid of their country";
System.out.println(s);
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}
|
3e17b15b3c9deb5c5655ac85fc13063ad45e4eb4 | 4,641 | java | Java | android/src/androidTest/java/com/byteowls/capacitor/oauth2/ConfigUtilsTest.java | onexip/capacitor-oauth2 | 89c14b462809543d3022fdac34b8f2d17bcf91bf | [
"MIT"
] | null | null | null | android/src/androidTest/java/com/byteowls/capacitor/oauth2/ConfigUtilsTest.java | onexip/capacitor-oauth2 | 89c14b462809543d3022fdac34b8f2d17bcf91bf | [
"MIT"
] | null | null | null | android/src/androidTest/java/com/byteowls/capacitor/oauth2/ConfigUtilsTest.java | onexip/capacitor-oauth2 | 89c14b462809543d3022fdac34b8f2d17bcf91bf | [
"MIT"
] | 1 | 2019-06-25T18:48:13.000Z | 2019-06-25T18:48:13.000Z | 34.125 | 126 | 0.684766 | 10,098 | package com.byteowls.capacitor.oauth2;
import android.util.Log;
import com.getcapacitor.JSObject;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Map;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.byteowls.capacitor.oauth2.test.R;
public class ConfigUtilsTest {
private JSObject jsObject;
@Before
public void setUp() {
try (InputStream in = getInstrumentation().getContext().getResources().openRawResource(R.raw.config_utils_features)) {
this.jsObject = new JSObject(IOUtils.toString(in, UTF_8));
} catch (Exception e) {
Log.e("OAuth2", "", e);
}
}
@Test
public void getParamString() {
String stringValue = ConfigUtils.getParamString(jsObject, "stringValue");
Assert.assertNotNull(stringValue);
Assert.assertEquals("string", stringValue);
String booleanValue = ConfigUtils.getParamString(jsObject, "booleanValue");
Assert.assertEquals("true", booleanValue);
}
@Test
public void getParam() {
String stringValue = ConfigUtils.getParam(String.class, jsObject, "stringValue");
Assert.assertNotNull(stringValue);
Assert.assertEquals("string", stringValue);
Double doubleValue = ConfigUtils.getParam(Double.class, jsObject, "doubleValue");
Assert.assertNotNull(doubleValue);
}
@Test
public void getParamMap() {
Map<String, String> map = ConfigUtils.getParamMap(jsObject, "map");
Assert.assertNotNull(map);
Assert.assertEquals("value1", map.get("key1"));
}
@Test
public void getDeepestKey() {
String deepestKey = ConfigUtils.getDeepestKey("com.example.deep");
Assert.assertEquals("deep", deepestKey);
deepestKey = ConfigUtils.getDeepestKey("com");
Assert.assertEquals("com", deepestKey);
}
@Test
public void getDeepestObject() {
JSObject object = ConfigUtils.getDeepestObject(jsObject, "first.second.third");
Assert.assertNotNull(object.getJSObject("third"));
}
@Test
public void getOverwrittenAndroidParam() {
String overwrittenString = ConfigUtils.getOverwrittenAndroidParam(String.class, jsObject, "stringValue");
Assert.assertEquals("stringAndroid", overwrittenString);
int intValue = ConfigUtils.getOverwrittenAndroidParam(Integer.class, jsObject, "intValue");
Assert.assertEquals(1, intValue);
}
@Test
public void getOverwrittenAndroidParamMap() {
Map<String, String> map = ConfigUtils.getOverwrittenAndroidParamMap(jsObject, "map");
Assert.assertNotNull(map);
Assert.assertEquals("value1Android", map.get("key1"));
Assert.assertEquals("value2", map.get("key2"));
Assert.assertEquals("value3Android", map.get("key3"));
}
@Test
public void overwriteWithEmpty() {
String accessTokenEndpoint = "accessTokenEndpoint";
Assert.assertNotNull(ConfigUtils.getParamString(jsObject, accessTokenEndpoint));
Assert.assertEquals("", ConfigUtils.getOverwrittenAndroidParam(String.class, jsObject, accessTokenEndpoint));
String inMapNullable = "inMapNullable";
Map<String, String> paramMap = ConfigUtils.getParamMap(jsObject, "map");
Assert.assertNotNull(paramMap.get(inMapNullable));
Map<String, String> androidParamMap = ConfigUtils.getOverwrittenAndroidParamMap(jsObject, "map");
Assert.assertEquals("", androidParamMap.get(inMapNullable));
}
@Test
public void getRandomString() {
String randomString = ConfigUtils.getRandomString(8);
Assert.assertNotNull(randomString);
Assert.assertEquals(8, randomString.length());
}
@Test
public void empty() {
// make sure the empty value stays empty
String emptyValue = ConfigUtils.getParamString(jsObject, "empty");
Assert.assertEquals(0, emptyValue.length());
}
@Test
public void blank() {
// make sure the blank value stays blank
String blankValue = ConfigUtils.getParamString(jsObject, "blank");
Assert.assertEquals(" ", blankValue);
}
@Test
public void trimToNull() {
Assert.assertNull(ConfigUtils.trimToNull(" "));
Assert.assertNull(ConfigUtils.trimToNull(" "));
Assert.assertNull(ConfigUtils.trimToNull(""));
Assert.assertEquals("a", ConfigUtils.trimToNull("a"));
}
}
|
3e17b1feb2f4950a8fc7d9ab55bf27d3bc35333f | 5,428 | java | Java | sm-core/src/main/java/com/salesmanager/core/business/services/voucher/VoucherServiceImpl.java | vfsc2018/shopizer | cc1e34a5985b3733be3b92f0049a7e5f7aeb8d08 | [
"Apache-2.0"
] | null | null | null | sm-core/src/main/java/com/salesmanager/core/business/services/voucher/VoucherServiceImpl.java | vfsc2018/shopizer | cc1e34a5985b3733be3b92f0049a7e5f7aeb8d08 | [
"Apache-2.0"
] | null | null | null | sm-core/src/main/java/com/salesmanager/core/business/services/voucher/VoucherServiceImpl.java | vfsc2018/shopizer | cc1e34a5985b3733be3b92f0049a7e5f7aeb8d08 | [
"Apache-2.0"
] | 1 | 2020-09-29T08:16:14.000Z | 2020-09-29T08:16:14.000Z | 31.929412 | 157 | 0.719418 | 10,099 | package com.salesmanager.core.business.services.voucher;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;
import com.salesmanager.core.business.constants.Constants;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.repositories.voucher.VoucherRepository;
import com.salesmanager.core.business.services.common.generic.SalesManagerEntityServiceImpl;
import com.salesmanager.core.business.services.vouchercode.VoucherCodeService;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.voucher.Voucher;
import com.salesmanager.core.model.voucher.VoucherCriteria;
import com.salesmanager.core.model.voucher.VoucherList;
import com.salesmanager.core.model.vouchercode.VoucherCode;
@Service("voucherService")
public class VoucherServiceImpl extends SalesManagerEntityServiceImpl<Long, Voucher> implements VoucherService {
@Inject
private VoucherRepository voucherRepository;
@Inject
private VoucherCodeService voucherCodeService;
private String sha1(String input)
{
try {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}catch (NoSuchAlgorithmException e) {
return null;
}
}
private String sha1extra(String code)
{
String hash = sha1(code);
if(hash==null) return null;
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
return sha1(day + hash + month);
}
private boolean invalid(Voucher voucher){
return (voucher==null || voucher.getBlocked()>0);
}
private boolean invalid(Voucher voucher, long id){
return (voucher==null || voucher.getId().longValue()!=id || voucher.getBlocked()>0);
}
private boolean invalidDate(Voucher voucher){
return (voucher.getEndDate()==null || voucher.getEndDate().before(new Date()) || voucher.getStartDate()==null || voucher.getStartDate().after(new Date()));
}
private boolean invalidTime(Voucher voucher){
Calendar cal = Calendar.getInstance();
if(voucher.getDayOfMonth()!=null){
int dayMonth = cal.get(Calendar.DAY_OF_MONTH);
String days = "," + voucher.getDayOfMonth().replace(" ", "") + ",";
if(days.indexOf("," + dayMonth + ",")<0) return false;
}
if(voucher.getWeekDays()!=null){
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
String days = "," + voucher.getWeekDays().replace(" ", "") + ",";
if(days.indexOf("," + dayWeek + ",")<0) return false;
}
if(voucher.getStartTime()!=null){
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour<voucher.getStartTime().intValue()) return false;
}
if(voucher.getEndTime()!=null){
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour>voucher.getEndTime().intValue()) return false;
}
return true;
}
@Override
public VoucherCode getVoucher(String code, String securecode) {
if (code != null && securecode!=null){
String hash = sha1extra(code);
System.out.println("getVoucher Hash:" + hash);
if(hash!=null && hash.equals(securecode)){
if(code.length()>=Constants.CODE_SINGLE_MINLEN && code.length()<Constants.CODE_MINLEN){
Voucher voucher = voucherRepository.getVoucher(code);
if(invalid(voucher)){
return null;
}
VoucherCode voucherCode = new VoucherCode();
voucherCode.setCode(code);
voucherCode.setSecurecode(securecode);
voucherCode.setVoucher(voucher);
return voucherCode;
}
long[] k = voucherCodeService.decode(code);
if(k.length==3 && k[0]==VoucherCodeService.TYPE_ORDER_PAYMENT){
int index = ((Long)k[2]).intValue();
VoucherCode voucherCode = voucherCodeService.getVoucherCode(code);
if(voucherCode!=null && voucherCode.getIndex()==index && voucherCode.getBlocked()==0 && voucherCode.getUsed()==null){
Voucher voucher = voucherCode.getVoucher();
if (invalid(voucher, k[1]) || invalidDate(voucher) || invalidTime(voucher)){
return null;
}
return voucherCode;
}
}
}
}
return null;
}
@Override
public VoucherList getListByStore(MerchantStore store, VoucherCriteria criteria) {
return voucherRepository.listByStore(store, criteria);
}
@Override
public List<Voucher> getActiveVoucher(){
return voucherRepository.getActiveVoucher();
}
@Override
public List<Voucher> getMemberVoucher(){
return voucherRepository.getMemberVoucher();
}
// @Override
// public Voucher getCodeByVoucher(String code){
// return voucherRepository.getCodeByVoucher(code);
// }
@Inject
public VoucherServiceImpl(VoucherRepository voucherRepository) {
super(voucherRepository);
this.voucherRepository = voucherRepository;
}
public Voucher saveVoucher(Voucher form) throws BindException {
return voucherRepository.saveAndFlush(form);
}
public boolean deleteVoucher(Long id) throws ServiceException {
voucherRepository.deleteById(id);
return true;
}
}
|
3e17b2630bd7c0f607818382e9f0ccc792ab10a0 | 1,172 | java | Java | mall-admin/src/main/java/com/macro/mall/service/SmsFlashPromotionProductRelationService.java | wangwang2019-web/single-mall | cfcb45712ce0b5b9202cf8493dd5f9992895faf5 | [
"Apache-2.0"
] | 1 | 2021-09-08T08:19:51.000Z | 2021-09-08T08:19:51.000Z | mall-admin/src/main/java/com/macro/mall/service/SmsFlashPromotionProductRelationService.java | wateraw/background | e691ffac229c66b5a098b8593532ca50e4a9642c | [
"Apache-2.0"
] | null | null | null | mall-admin/src/main/java/com/macro/mall/service/SmsFlashPromotionProductRelationService.java | wateraw/background | e691ffac229c66b5a098b8593532ca50e4a9642c | [
"Apache-2.0"
] | 2 | 2021-09-14T03:34:45.000Z | 2021-12-20T06:12:55.000Z | 22.980392 | 128 | 0.69198 | 10,100 | package com.macro.mall.service;
import com.macro.mall.dto.SmsFlashPromotionProduct;
import com.macro.mall.model.SmsFlashPromotionProductRelation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 限时购商品关联管理Service
* Created on 2018/11/16.
*/
public interface SmsFlashPromotionProductRelationService {
/**
* 批量添加关联
*/
@Transactional
int create(List<SmsFlashPromotionProductRelation> relationList);
/**
* 修改关联相关信息
*/
int update(Long id, SmsFlashPromotionProductRelation relation);
/**
* 删除关联
*/
int delete(Long id);
/**
* 获取关联详情
*/
SmsFlashPromotionProductRelation getItem(Long id);
/**
* 分页查询相关商品及促销信息
*
* @param flashPromotionId 限时购id
* @param flashPromotionSessionId 限时购场次id
*/
List<SmsFlashPromotionProduct> list(Long flashPromotionId, Long flashPromotionSessionId, Integer pageSize, Integer pageNum);
/**
* 根据活动和场次id获取商品关系数量
* @param flashPromotionId
* @param flashPromotionSessionId
* @return
*/
long getCount(Long flashPromotionId,Long flashPromotionSessionId);
}
|
3e17b349ab18ba75e4fbc09da481813a2e1d6e0e | 4,090 | java | Java | src/org/musicbrainz/model/entity/PlaceWs2.java | bobsmith947/musicbrainzws2-java-mod | 0e772298f1c16ead0d7f8f9cff1f633967dde2a0 | [
"BSD-3-Clause"
] | null | null | null | src/org/musicbrainz/model/entity/PlaceWs2.java | bobsmith947/musicbrainzws2-java-mod | 0e772298f1c16ead0d7f8f9cff1f633967dde2a0 | [
"BSD-3-Clause"
] | null | null | null | src/org/musicbrainz/model/entity/PlaceWs2.java | bobsmith947/musicbrainzws2-java-mod | 0e772298f1c16ead0d7f8f9cff1f633967dde2a0 | [
"BSD-3-Clause"
] | null | null | null | 22.472527 | 76 | 0.537897 | 10,101 | package org.musicbrainz.model.entity;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.musicbrainz.model.LifeSpanWs2;
import org.musicbrainz.utils.MbUtils;
/**
* <p>A Place definition.
* A place is a building or outdoor area used for performing or
* producing music.
* </p>
*/
public class PlaceWs2 extends EntityWs2
{
private static Logger log = Logger.getLogger(PlaceWs2.class.getName());
private String typeUri;
private String name;
private String disambiguation;
private String address;
private String latitude;
private String longitude;
private AreaWs2 area;
private LifeSpanWs2 lifespan;
/**
* @return the typeUri
*/
public String getTypeUri() {
return typeUri;
}
public String getType() {
if (getTypeUri()== null) return "";
if (getTypeUri().isEmpty()) return "";
return MbUtils.extractTypeFromURI(getTypeUri());
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the disambiguation
*/
public String getDisambiguation() {
return disambiguation;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @return the latitude
*/
public String getLatitude() {
return latitude;
}
/**
* @return the longitude
*/
public String getLongitude() {
return longitude;
}
/**
* @return the area
*/
public AreaWs2 getArea() {
return area;
}
/**
* @return the lifespan
*/
public LifeSpanWs2 getLifespan() {
return lifespan;
}
/**
* @param type the typeUri to set
*/
public void setTypeUri(String typeUri) {
this.typeUri = typeUri;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @param disambiguation the disambiguation to set
*/
public void setDisambiguation(String disambiguation) {
this.disambiguation = disambiguation;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(String latitude) {
this.latitude = latitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(String longitude) {
this.longitude = longitude;
}
/**
* @param area the area to set
*/
public void setArea(AreaWs2 area) {
this.area = area;
}
/**
* @param lifespan the lifespan to set
*/
public void setLifespan(LifeSpanWs2 lifespan) {
this.lifespan = lifespan;
}
public String getFullAddress() {
String out = name;
if (getAddress() != null && !getAddress().isEmpty())
out = out+" ("+getAddress();
if (getArea() == null) return out+")";
String complete = getArea().getCompleteString();
if (complete.isEmpty()) return out+")";
out = out+", "+complete+")";
return out;
}
public String getUniqueName(){
if (StringUtils.isNotBlank(disambiguation)) {
return name + " (" + disambiguation + ")";
}
return name;
}
@Override
public String toString() {
return getFullAddress();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof PlaceWs2)) {
return false;
}
PlaceWs2 other = (PlaceWs2) object;
if (this.getIdUri().equals(other.getIdUri()))
{
return true;
}
return false;
}
} |
3e17b5fd9e1da496bb1f7e2ee4f60e306d32e8b2 | 125 | java | Java | java/info/rlwhitcomb/util/package-info.java | rlwhitcomb/utilities | 8da2881f1de891f46293c55f04e8b8f9fd863a8a | [
"MIT"
] | null | null | null | java/info/rlwhitcomb/util/package-info.java | rlwhitcomb/utilities | 8da2881f1de891f46293c55f04e8b8f9fd863a8a | [
"MIT"
] | 237 | 2021-01-21T17:05:00.000Z | 2022-03-31T17:30:09.000Z | java/info/rlwhitcomb/util/package-info.java | rlwhitcomb/utilities | 8da2881f1de891f46293c55f04e8b8f9fd863a8a | [
"MIT"
] | 1 | 2021-11-25T16:31:23.000Z | 2021-11-25T16:31:23.000Z | 20.833333 | 85 | 0.752 | 10,102 | /**
* A collection of many utility classes providing a wide variety of useful functions.
*/
package info.rlwhitcomb.util;
|
3e17b80680a51f6853e3ef29e6bcf3e099e095f7 | 21,243 | java | Java | java/revenj-core/src/main/java/org/revenj/database/postgres/jinq/RevenjQueryComposer.java | zrajnis/revenj | b84c6c8292741fd463ea4c02f026b641cc4ac5fc | [
"BSD-3-Clause"
] | 280 | 2015-02-08T22:57:18.000Z | 2022-03-30T05:00:51.000Z | java/revenj-core/src/main/java/org/revenj/database/postgres/jinq/RevenjQueryComposer.java | zrajnis/revenj | b84c6c8292741fd463ea4c02f026b641cc4ac5fc | [
"BSD-3-Clause"
] | 97 | 2015-03-08T20:59:29.000Z | 2021-12-21T05:27:18.000Z | java/revenj-core/src/main/java/org/revenj/database/postgres/jinq/RevenjQueryComposer.java | zrajnis/revenj | b84c6c8292741fd463ea4c02f026b641cc4ac5fc | [
"BSD-3-Clause"
] | 44 | 2015-07-08T12:38:22.000Z | 2022-03-23T14:27:35.000Z | 37.268421 | 184 | 0.702302 | 10,103 | package org.revenj.database.postgres.jinq;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import org.postgresql.core.Oid;
import org.postgresql.util.PGobject;
import org.revenj.patterns.DataSource;
import org.revenj.patterns.Specification;
import org.revenj.database.postgres.ObjectConverter;
import org.revenj.database.postgres.PostgresWriter;
import org.revenj.database.postgres.converters.ArrayTuple;
import org.revenj.database.postgres.jinq.jpqlquery.GeneratedQueryParameter;
import org.revenj.database.postgres.jinq.jpqlquery.JinqPostgresQuery;
import org.revenj.Utils;
import org.revenj.database.postgres.converters.PostgresTuple;
import org.revenj.database.postgres.converters.TimestampConverter;
import org.revenj.database.postgres.jinq.transform.RevenjMultiLambdaQueryTransform;
import org.revenj.database.postgres.jinq.transform.RevenjNoLambdaQueryTransform;
import org.revenj.database.postgres.jinq.transform.RevenjOneLambdaQueryTransform;
import org.revenj.database.postgres.jinq.transform.RevenjQueryTransformConfiguration;
import org.revenj.database.postgres.jinq.transform.LambdaAnalysis;
import org.revenj.database.postgres.jinq.transform.LambdaInfo;
import org.revenj.database.postgres.jinq.transform.LimitSkipTransform;
import org.revenj.database.postgres.jinq.transform.MetamodelUtil;
import org.revenj.database.postgres.jinq.transform.QueryTransformException;
import org.revenj.database.postgres.jinq.transform.SortingTransform;
import org.revenj.database.postgres.jinq.transform.WhereTransform;
import org.revenj.database.postgres.PostgresReader;
import org.revenj.patterns.ServiceLocator;
public final class RevenjQueryComposer<T> {
private static final Map<Class<?>, String> typeMapping = new HashMap<>();
private static final Map<String, Integer> sqlIdMapping = new HashMap<>();
private static void addMapping(Class<?> manifest, String dbType, int oid, int sqlId) {
typeMapping.put(manifest, dbType);
sqlIdMapping.put(manifest.getName(), sqlId);
}
static {
addMapping(int.class, "int", Oid.INT4, Types.INTEGER);
addMapping(Integer.class, "int", Oid.INT4, Types.INTEGER);
addMapping(String.class, "varchar", Oid.VARCHAR, Types.VARCHAR);
addMapping(long.class, "bigint", Oid.INT8, Types.BIGINT);
addMapping(Long.class, "bigint", Oid.INT8, Types.BIGINT);
addMapping(BigDecimal.class, "numeric", Oid.NUMERIC, Types.NUMERIC);
addMapping(float.class, "real", Oid.FLOAT4, Types.FLOAT);
addMapping(Float.class, "real", Oid.FLOAT4, Types.FLOAT);
addMapping(double.class, "float", Oid.FLOAT8, Types.DOUBLE);
addMapping(Double.class, "float", Oid.FLOAT8, Types.DOUBLE);
addMapping(boolean.class, "bool", Oid.BOOL, Types.BOOLEAN);
addMapping(Boolean.class, "bool", Oid.BOOL, Types.BOOLEAN);
addMapping(LocalDate.class, "date", Oid.DATE, Types.DATE);
addMapping(OffsetDateTime.class, "timestamptz", Oid.TIMESTAMPTZ, Types.TIMESTAMP_WITH_TIMEZONE);
addMapping(UUID.class, "uuid", Oid.UUID, Types.OTHER);
addMapping(Map.class, "hstore", -1, Types.OTHER);
addMapping(byte[].class, "bytea", Oid.BYTEA, Types.BLOB);
}
@FunctionalInterface
public interface GetConnection {
Connection get() throws SQLException;
}
@FunctionalInterface
public interface ReleaseConnection {
void release(Connection connection) throws SQLException;
}
private final MetamodelUtil metamodel;
private final ClassLoader loader;
private final RevenjQueryComposerCache cachedQueries;
private final Connection connection;
private final ServiceLocator locator;
private final GetConnection getConnection;
private final ReleaseConnection releaseConnection;
private final JinqPostgresQuery<T> query;
private final Class<T> manifest;
/**
* Holds the chain of lambdas that were used to create this query. This is needed
* because query parameters (which are stored in the lambda objects) are only
* substituted into the query during query execution, which occurs much later
* than query generation.
*/
private final List<LambdaInfo> lambdas = new ArrayList<>();
public int getLambdaCount() {
return lambdas.size();
}
private RevenjQueryComposer(
RevenjQueryComposer<?> base,
Class<T> manifest,
JinqPostgresQuery<T> query,
List<LambdaInfo> chainedLambdas,
LambdaInfo... additionalLambdas) {
this(base.metamodel, base.loader, manifest, base.cachedQueries, base.connection, base.locator, base.getConnection, base.releaseConnection, query, chainedLambdas, additionalLambdas);
}
private RevenjQueryComposer(
MetamodelUtil metamodel,
ClassLoader loader,
Class<T> manifest,
RevenjQueryComposerCache cachedQueries,
Connection connection,
ServiceLocator locator,
GetConnection getConnection,
ReleaseConnection releaseConnection,
JinqPostgresQuery<T> query,
List<LambdaInfo> chainedLambdas,
LambdaInfo... additionalLambdas) {
this.metamodel = metamodel;
this.loader = loader;
this.manifest = manifest;
this.cachedQueries = cachedQueries;
this.connection = connection;
this.locator = locator;
this.getConnection = getConnection;
this.releaseConnection = releaseConnection;
this.query = query;
lambdas.addAll(chainedLambdas);
for (LambdaInfo newLambda : additionalLambdas) {
lambdas.add(newLambda);
}
}
public static <T extends DataSource> RevenjQuery<T> findAll(
MetamodelUtil metamodel,
ClassLoader loader,
Class<T> manifest,
RevenjQueryComposerCache cachedQueries,
Connection conn,
ServiceLocator locator,
GetConnection getConnection,
ReleaseConnection releaseConnection) {
String sqlSource = metamodel.dataSourceNameFromClass(manifest);
Optional<JinqPostgresQuery<?>> cachedQuery = cachedQueries.findCachedFindAll(sqlSource);
if (cachedQuery == null) {
JinqPostgresQuery<T> query = JinqPostgresQuery.findAll(sqlSource);
cachedQuery = Optional.of(query);
cachedQuery = cachedQueries.cacheFindAll(sqlSource, cachedQuery);
}
JinqPostgresQuery<T> findAllQuery = (JinqPostgresQuery<T>) cachedQuery.get();
RevenjQueryComposer<T> queryComposer =
new RevenjQueryComposer(
metamodel,
loader,
manifest,
cachedQueries,
conn,
locator,
getConnection,
releaseConnection,
findAllQuery,
new ArrayList<>());
return new RevenjQuery<>(queryComposer);
}
private static String getTypeFor(Class<?> manifest) {
return typeMapping.get(manifest);
}
private static String getElementTypeFor(Object[] elements) {
for (Object item : elements) {
if (item != null) {
String type = getTypeFor(item.getClass());
if (type != null) {
return type;
}
}
}
return "unknown";
}
private static final PGobject EMPTY_ARRAY;
static {
EMPTY_ARRAY = new PGobject();
EMPTY_ARRAY.setType("record[]");
try {
EMPTY_ARRAY.setValue("{}");
} catch (SQLException ignore) {
}
}
public static void fillQueryParameters(
Connection connection,
ServiceLocator locator,
PreparedStatement ps,
int parameterOffset,
List<GeneratedQueryParameter> parameters,
List<LambdaInfo> lambdas) throws SQLException {
PostgresWriter writer = null;
for (int i = 0; i < parameters.size(); i++) {
GeneratedQueryParameter param = parameters.get(i);
Object value = param.getValue.apply(lambdas.get(param.lambdaIndex));
if (value == null) {
Integer sqlId = sqlIdMapping.get(param.javaType);
if (sqlId == null || sqlId == -1) {
if (param.sqlType != null) {
PGobject pgo = new PGobject();
pgo.setType(param.sqlType);
pgo.setValue("null");
ps.setObject(i + 1 + parameterOffset, pgo);
} else {
ps.setObject(i + 1 + parameterOffset, null);
}
} else {
ps.setNull(i + 1 + parameterOffset, sqlId);
}
continue;
}
Object[] elements = null;
if (value instanceof Collection) {
Collection collection = (Collection) value;
elements = new Object[collection.size()];
int x = 0;
for (Object item : collection) {
elements[x++] = item;
}
} else if (value instanceof Object[]) {
elements = (Object[]) value;
}
if (elements == null) {
Class<?> manifest = value.getClass();
Optional<ObjectConverter> converter = getConverterFor(locator, manifest);
if (converter.isPresent()) {
PGobject pgo = new PGobject();
if (writer == null) writer = PostgresWriter.create();
writer.reset();
PostgresTuple tuple = converter.get().to(value);
tuple.buildTuple(writer, false);
pgo.setValue(writer.toString());
pgo.setType(converter.get().getDbName());
ps.setObject(i + 1 + parameterOffset, pgo);
} else if (value instanceof LocalDate) {
ps.setDate(i + 1 + parameterOffset, java.sql.Date.valueOf((LocalDate) value));
//if (writer == null) writer = PostgresWriter.create();
//DateConverter.setParameter(writer, ps, i + 1, (LocalDate) value);
} else if (value instanceof LocalDateTime) {
if (writer == null) writer = PostgresWriter.create();
TimestampConverter.setParameter(writer, ps, i + 1, (LocalDateTime) value);
} else if (value instanceof OffsetDateTime) {
if (writer == null) writer = PostgresWriter.create();
TimestampConverter.setParameter(writer, ps, i + 1, (OffsetDateTime) value);
} else {
ps.setObject(i + 1 + parameterOffset, value);
}
} else {
Class<?> manifest = null;
for (Object item : elements) {
if (item != null) {
manifest = item.getClass();
break;
}
}
Optional<ObjectConverter> converter = manifest != null ? getConverterFor(locator, manifest) : Optional.<ObjectConverter>empty();
if (converter.isPresent()) {
ObjectConverter<Object> oc = converter.get();
if (writer == null) writer = PostgresWriter.create();
writer.reset();
PostgresTuple tuple = ArrayTuple.create(elements, oc::to);
PGobject pgo = new PGobject();
pgo.setType(oc.getDbName() + "[]");
tuple.buildTuple(writer, false);
pgo.setValue(writer.toString());
ps.setObject(i + 1 + parameterOffset, pgo);
} else {
String type = getElementTypeFor(elements);
if ("unknown".equals(type)) {
if (elements.length == 0) {
//TODO: provide null instead !?
if (param.sqlType != null) {
PGobject pgo = new PGobject();
pgo.setType(param.sqlType);
pgo.setValue("{}");
ps.setObject(i + 1 + parameterOffset, pgo);
} else {
ps.setObject(i + 1 + parameterOffset, EMPTY_ARRAY);
}
continue;
} else {
// throw meaningfull error!?
}
}
java.sql.Array array = connection.createArrayOf(type, elements);
ps.setArray(i + 1 + parameterOffset, array);
}
}
}
if (writer != null) writer.close();
}
private static final ConcurrentMap<Class<?>, Optional<ObjectConverter>> objectConverters = new ConcurrentHashMap<>();
private static Optional<ObjectConverter> getConverterFor(ServiceLocator locator, Class<?> manifest) {
return objectConverters.computeIfAbsent(manifest, clazz ->
{
try {
ObjectConverter result = (ObjectConverter) locator.resolve(Utils.makeGenericType(ObjectConverter.class, clazz));
return Optional.of(result);
} catch (Exception ignore) {
return Optional.empty();
}
});
}
private Connection getConnection() throws SQLException {
if (connection != null) return connection;
return getConnection.get();
}
private void releaseConnection(Connection connection) throws SQLException {
if (this.connection == null) releaseConnection.release(connection);
}
public long count() throws SQLException {
final String queryString = query.getQueryString();
Connection connection = getConnection();
try (PreparedStatement ps = connection.prepareStatement("SELECT COUNT(*) FROM (" + queryString + ") sq")) {
fillQueryParameters(connection, locator, ps, 0, query.getQueryParameters(), lambdas);
try (final ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getLong(1);
}
}
} finally {
releaseConnection(connection);
}
return 0;
}
public boolean any() throws SQLException {
final String queryString = query.getQueryString();
Connection connection = getConnection();
try (PreparedStatement ps = connection.prepareStatement("SELECT EXISTS(" + queryString + ")")) {
fillQueryParameters(connection, locator, ps, 0, query.getQueryParameters(), lambdas);
try (final ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getBoolean(1);
}
}
} finally {
releaseConnection(connection);
}
return false;
}
//TODO: optimize
public boolean all(LambdaInfo lambda) throws SQLException {
long filter = this.where(lambda).count();
long all = this.count();
return filter == all && all > 0;
}
public boolean none() throws SQLException {
final String queryString = query.getQueryString();
Connection connection = getConnection();
try (PreparedStatement ps = connection.prepareStatement("SELECT NOT EXISTS(" + queryString + ")")) {
fillQueryParameters(connection, locator, ps, 0, query.getQueryParameters(), lambdas);
try (final ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getBoolean(1);
}
}
} finally {
releaseConnection(connection);
}
return true;
}
public Optional<T> first() throws SQLException {
final String queryString = query.getQueryString();
Connection connection = getConnection();
try (PreparedStatement ps = connection.prepareStatement(queryString)) {
fillQueryParameters(connection, locator, ps, 0, query.getQueryParameters(), lambdas);
final PostgresReader pr = new PostgresReader(locator);
try {
final ObjectConverter<T> converter = getConverterFor(locator, manifest).get();
try (final ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
pr.process(rs.getString(1));
return Optional.of(converter.from(pr));
}
}
} catch (IOException e) {
throw new SQLException(e);
} finally {
releaseConnection(connection);
}
return Optional.empty();
}
}
public List<T> toList() throws SQLException {
final String queryString = query.getQueryString();
Connection connection = getConnection();
try (PreparedStatement ps = connection.prepareStatement(queryString)) {
fillQueryParameters(connection, locator, ps, 0, query.getQueryParameters(), lambdas);
final PostgresReader pr = new PostgresReader(locator);
final ArrayList<T> result = new ArrayList<>();
try {
final ObjectConverter<T> converter = getConverterFor(locator, manifest).get();
try (final ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
pr.process(rs.getString(1));
result.add(converter.from(pr));
}
}
} catch (IOException e) {
throw new SQLException(e);
} finally {
releaseConnection(connection);
}
return result;
}
}
private <U> RevenjQueryComposer<U> applyTransformWithLambda(
Class<U> newManifest,
RevenjNoLambdaQueryTransform transform) {
Optional<JinqPostgresQuery<?>> cachedQuery = cachedQueries.findInCache(query, transform.getTransformationTypeCachingTag(), null);
if (cachedQuery == null) {
cachedQuery = Optional.empty();
JinqPostgresQuery<U> newQuery = null;
try {
newQuery = transform.apply(query, null);
} catch (QueryTransformException e) {
throw new RuntimeException(e);
} finally {
// Always cache the resulting query, even if it is an error
cachedQuery = Optional.ofNullable(newQuery);
cachedQuery = cachedQueries.cacheQuery(query, transform.getTransformationTypeCachingTag(), null, cachedQuery);
}
}
if (!cachedQuery.isPresent()) {
return null;
}
return new RevenjQueryComposer<>(this, newManifest, (JinqPostgresQuery<U>) cachedQuery.get(), lambdas);
}
public <U> RevenjQueryComposer<U> applyTransformWithLambda(
Class<U> newManifest,
RevenjOneLambdaQueryTransform transform,
LambdaInfo lambdaInfo) {
if (lambdaInfo == null) {
return null;
}
Optional<JinqPostgresQuery<?>> cachedQuery =
cachedQueries.findInCache(
query,
transform.getTransformationTypeCachingTag(),
new String[]{lambdaInfo.getLambdaSourceString()});
if (cachedQuery == null) {
JinqPostgresQuery<U> newQuery = null;
try {
LambdaAnalysis lambdaAnalysis = lambdaInfo.fullyAnalyze(metamodel, loader, true, true, true, true);
if (lambdaAnalysis == null) {
return null;
}
getConfig().checkLambdaSideEffects(lambdaAnalysis);
newQuery = transform.apply(query, lambdaAnalysis, null);
} catch (QueryTransformException e) {
throw new RuntimeException(e);
} finally {
// Always cache the resulting query, even if it is an error
cachedQuery = Optional.ofNullable(newQuery);
cachedQuery = cachedQueries.cacheQuery(query, transform.getTransformationTypeCachingTag(), new String[]{lambdaInfo.getLambdaSourceString()}, cachedQuery);
}
}
if (!cachedQuery.isPresent()) {
return null;
}
return new RevenjQueryComposer<>(this, newManifest, (JinqPostgresQuery<U>) cachedQuery.get(), lambdas, lambdaInfo);
}
public <U> RevenjQueryComposer<U> applyTransformWithLambdas(
Class<U> newManifest,
RevenjMultiLambdaQueryTransform transform,
Object[] groupingLambdas) {
LambdaInfo[] lambdaInfos = new LambdaInfo[groupingLambdas.length];
String[] lambdaSources = new String[lambdaInfos.length];
for (int n = 0; n < groupingLambdas.length; n++) {
lambdaInfos[n] = LambdaInfo.analyze(groupingLambdas[n], lambdas.size() + n, true);
if (lambdaInfos[n] == null) {
return null;
}
lambdaSources[n] = lambdaInfos[n].getLambdaSourceString();
}
Optional<JinqPostgresQuery<?>> cachedQuery =
cachedQueries.findInCache(query, transform.getTransformationTypeCachingTag(), lambdaSources);
if (cachedQuery == null) {
JinqPostgresQuery<U> newQuery = null;
try {
LambdaAnalysis[] lambdaAnalyses = new LambdaAnalysis[lambdaInfos.length];
for (int n = 0; n < lambdaInfos.length; n++) {
lambdaAnalyses[n] = lambdaInfos[n].fullyAnalyze(metamodel, null, true, true, true, true);
if (lambdaAnalyses[n] == null) {
return null;
}
getConfig().checkLambdaSideEffects(lambdaAnalyses[n]);
}
newQuery = transform.apply(query, lambdaAnalyses, null);
} catch (QueryTransformException e) {
throw new RuntimeException(e);
} finally {
// Always cache the resulting query, even if it is an error
cachedQuery = Optional.ofNullable(newQuery);
cachedQuery = cachedQueries.cacheQuery(query, transform.getTransformationTypeCachingTag(), lambdaSources, cachedQuery);
}
}
if (!cachedQuery.isPresent()) {
return null;
}
return new RevenjQueryComposer<>(this, newManifest, (JinqPostgresQuery<U>) cachedQuery.get(), lambdas, lambdaInfos);
}
/**
* Holds configuration information used when transforming this composer to a new composer.
* Since a RevenjQueryComposer can only be transformed once, we only need one transformationConfig
* (and it is instantiated lazily).
*/
private RevenjQueryTransformConfiguration transformationConfig = null;
public RevenjQueryTransformConfiguration getConfig() {
if (transformationConfig == null) {
transformationConfig = new RevenjQueryTransformConfiguration();
transformationConfig.metamodel = metamodel;
transformationConfig.alternateClassLoader = null;
transformationConfig.isObjectEqualsSafe = true;
transformationConfig.isCollectionContainsSafe = true;
}
return transformationConfig;
}
public Specification rewrite(Specification filter) {
Function<Specification, Specification> conversion = metamodel.lookupRewrite(filter);
return conversion != null ? conversion.apply(filter) : filter;
}
public <E extends Exception> RevenjQueryComposer<T> where(LambdaInfo lambdaInfo) {
return applyTransformWithLambda(manifest, new WhereTransform(getConfig(), false), lambdaInfo);
}
public <V extends Comparable<V>> RevenjQueryComposer<T> sortedBy(LambdaInfo lambdaInfo, boolean isAscending) {
return applyTransformWithLambda(manifest, new SortingTransform(getConfig(), isAscending), lambdaInfo);
}
public RevenjQueryComposer<T> limit(long n) {
return applyTransformWithLambda(manifest, new LimitSkipTransform(getConfig(), true, n));
}
public RevenjQueryComposer<T> skip(long n) {
return applyTransformWithLambda(manifest, new LimitSkipTransform(getConfig(), false, n));
}
}
|
3e17b8654a9f603262a0be3e0c8e33dd7202ae66 | 4,805 | java | Java | app/src/main/java/fr/acinq/eclair/wallet/customviews/DataRow.java | araspitzu/eclair-mobile | c036cc82fc04c578109e6946b289c9498fac68f0 | [
"Apache-2.0"
] | 137 | 2019-01-04T19:15:15.000Z | 2022-03-21T01:01:55.000Z | app/src/main/java/fr/acinq/eclair/wallet/customviews/DataRow.java | araspitzu/eclair-mobile | c036cc82fc04c578109e6946b289c9498fac68f0 | [
"Apache-2.0"
] | 147 | 2019-01-04T18:04:05.000Z | 2022-03-12T12:25:32.000Z | app/src/main/java/fr/acinq/eclair/wallet/customviews/DataRow.java | araspitzu/eclair-mobile | c036cc82fc04c578109e6946b289c9498fac68f0 | [
"Apache-2.0"
] | 32 | 2019-01-08T17:07:02.000Z | 2021-12-27T13:07:02.000Z | 34.818841 | 141 | 0.716337 | 10,104 | /*
* Copyright 2019 ACINQ SAS
*
* 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 fr.acinq.eclair.wallet.customviews;
import android.content.Context;
import android.content.res.TypedArray;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import android.text.Html;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import fr.acinq.eclair.wallet.R;
public class DataRow extends ConstraintLayout {
public LinearLayout contentLayout;
public Button actionButton;
private TextView valueTextView;
public DataRow(Context context) {
super(context);
init(null, 0);
}
public DataRow(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public DataRow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
final TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.DataRow, defStyle, 0);
try {
final View root = LayoutInflater.from(getContext()).inflate(R.layout.custom_data_row, this);
final int vPadding = getResources().getDimensionPixelSize(R.dimen.space_sm);
final int hPadding = getResources().getDimensionPixelSize(R.dimen.space_md);
root.setPadding(hPadding, vPadding, hPadding, vPadding);
// label
final TextView labelTextView = findViewById(R.id.data_label);
if (arr.hasValue(R.styleable.DataRow_label)) {
labelTextView.setText(arr.getString(R.styleable.DataRow_label));
} else {
labelTextView.setVisibility(GONE);
}
// value
contentLayout = findViewById(R.id.data_content);
valueTextView = findViewById(R.id.data_value);
final boolean hasValue = arr.hasValue(R.styleable.DataRow_value);
if (hasValue) {
valueTextView.setText(arr.getString(R.styleable.DataRow_value));
} else {
valueTextView.setVisibility(GONE);
}
// border
final boolean hasBorder = arr.getBoolean(R.styleable.DataRow_has_border, false);
final boolean isBottomRounded = arr.getBoolean(R.styleable.DataRow_is_bottom_rounded, false);
if (hasBorder) {
setBackground(getResources().getDrawable(R.drawable.white_with_bottom_border));
} else if (isBottomRounded) {
setBackground(getResources().getDrawable(R.drawable.rounded_corner_white_bottom_sm));
} else {
setBackgroundColor(ContextCompat.getColor(getContext(), R.color.almost_white));
}
// button
actionButton = findViewById(R.id.data_action);
final boolean hasAction = arr.getBoolean(R.styleable.DataRow_has_action, false);
if (hasAction) {
if (hasValue) {
findViewById(R.id.separator).setVisibility(VISIBLE);
}
actionButton.setVisibility(VISIBLE);
actionButton.setText(arr.getString(R.styleable.DataRow_action_label));
actionButton.setTextColor(arr.getColor(R.styleable.DataRow_action_text_color, ContextCompat.getColor(getContext(), R.color.grey_3)));
}
} finally {
arr.recycle();
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (contentLayout == null) {
super.addView(child, index, params);
} else {
contentLayout.addView(child);
}
}
/**
* Do not use to display value coming from external sources.
*/
public void setHtmlValue(final String value) {
valueTextView.setVisibility(VISIBLE);
valueTextView.setText(Html.fromHtml(value));
if (actionButton.getVisibility() == View.VISIBLE) {
findViewById(R.id.separator).setVisibility(VISIBLE);
}
}
public void setValue(final String value) {
valueTextView.setVisibility(VISIBLE);
valueTextView.setText(value);
if (actionButton.getVisibility() == View.VISIBLE) {
findViewById(R.id.separator).setVisibility(VISIBLE);
}
}
public void setActionLabel(final String label) {
actionButton.setVisibility(VISIBLE);
actionButton.setText(label);
}
}
|
3e17b9dd592a8687b33623ae6f812faad14d9894 | 1,821 | java | Java | RobotCodeJava/commandFrankie/src/main/java/frc/robot/subsystems/BallSucker.java | eduardorasgado/FRC_Codigo_2019Team7018 | c4ed066077c946621d8c372631d26f6c8727d120 | [
"MIT"
] | null | null | null | RobotCodeJava/commandFrankie/src/main/java/frc/robot/subsystems/BallSucker.java | eduardorasgado/FRC_Codigo_2019Team7018 | c4ed066077c946621d8c372631d26f6c8727d120 | [
"MIT"
] | null | null | null | RobotCodeJava/commandFrankie/src/main/java/frc/robot/subsystems/BallSucker.java | eduardorasgado/FRC_Codigo_2019Team7018 | c4ed066077c946621d8c372631d26f6c8727d120 | [
"MIT"
] | null | null | null | 31.396552 | 80 | 0.623833 | 10,105 | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.subsystems;
import edu.wpi.first.wpilibj.command.Subsystem;
// Libreria para los victor spx
import edu.wpi.first.wpilibj.VictorSP;
/**
* Add your docs here.
*/
public class BallSucker extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
private double STOP_MOTOR = 0.0;
//Puerto para los victor del ball Sucker
//private final int MECANNO_MOTOR_PORT = 7;
private final int MECANNO_MOTOR_PORT = 7;
//private final int ARM_MOTOR_PORT = 8;
// los dos motores del Ball Sucker
private VictorSP MecSuckerMotor;
//private VictorSP ArmSuckerMotor;
@Override
public void initDefaultCommand() {
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
// 2) Sucker
MecSuckerMotor = new VictorSP(MECANNO_MOTOR_PORT);
//ArmSuckerMotor = new VictorSP(ARM_MOTOR_PORT);
}
public void DrivePressed(double MAX_POWER_MOTOR, double MIN_POWER_MOTOR,
boolean stopmotion)
{
// cuando se presiona el boton del ball sucker
if(!stopmotion){MecSuckerMotor.set(MAX_POWER_MOTOR);}
else {MecSuckerMotor.set(STOP_MOTOR);}
//ArmSuckerMotor.set(MIN_POWER_MOTOR);
}
public void DriveRelease()
{
MecSuckerMotor.set(STOP_MOTOR);
//ArmSuckerMotor.set(STOP_MOTOR);
}
}
|
3e17ba7a575e16eda6f2fce98225edeaa6fa1f69 | 1,476 | java | Java | springbootmq/src/test/java/com/springbootmq/springbootmq/SpringbootmqApplicationTests.java | tianyaruobilin/ideaproject | 690b47e261acf550db3158c4ec22d4fcf09a7a8a | [
"Apache-2.0"
] | null | null | null | springbootmq/src/test/java/com/springbootmq/springbootmq/SpringbootmqApplicationTests.java | tianyaruobilin/ideaproject | 690b47e261acf550db3158c4ec22d4fcf09a7a8a | [
"Apache-2.0"
] | null | null | null | springbootmq/src/test/java/com/springbootmq/springbootmq/SpringbootmqApplicationTests.java | tianyaruobilin/ideaproject | 690b47e261acf550db3158c4ec22d4fcf09a7a8a | [
"Apache-2.0"
] | null | null | null | 23.428571 | 62 | 0.654472 | 10,106 | package com.springbootmq.springbootmq;
import com.springbootmq.springbootmq.config.HelloSender;
import com.springbootmq.springbootmq.entity.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootmqApplicationTests {
@Autowired
private HelloSender helloSender;
/* @Autowired
@Test
public void contextLoads() {
}
@Test//这是一对一发送消息
public void hello() throws Exception{
helloSender.send();
}
@Test//一对多
public void oneTomany() throws Exception{
for (int i = 0; i < 100; i++) {
helloSender.send(i);
}
}
@Test//多对多
public void manyTomany() throws Exception{
for (int i = 0; i < 100; i++) {
helloSender.send(i);
helloSender.sendTwice(i);
}
}
@Test
public void objectSendReciver() throws Exception{
Book book1=new Book(1,"jpm");
Book book2=new Book(2, "xxj");
helloSender.sendObject(book1);
helloSender.sendObject(book2);
}*/
@Test
public void topicExchange() throws Exception{
helloSender.send1();
helloSender.send2();
}
@Test
public void fanout() throws Exception{
helloSender.send3();
}
}
|
3e17ba8ce708d0df4489ce41a373952b536c9255 | 3,671 | java | Java | src/main/java/com/almuradev/droplet/component/range/DoubleRange.java | AlmuraDev/Droplet | 929af2c2920323567af1aae144aa1fb5e09189f8 | [
"MIT"
] | 1 | 2018-04-04T00:51:27.000Z | 2018-04-04T00:51:27.000Z | src/main/java/com/almuradev/droplet/component/range/DoubleRange.java | AlmuraDev/Droplet | 929af2c2920323567af1aae144aa1fb5e09189f8 | [
"MIT"
] | null | null | null | src/main/java/com/almuradev/droplet/component/range/DoubleRange.java | AlmuraDev/Droplet | 929af2c2920323567af1aae144aa1fb5e09189f8 | [
"MIT"
] | null | null | null | 31.646552 | 158 | 0.684282 | 10,107 | /*
* This file is part of droplet, licensed under the MIT License.
*
* Copyright (c) 2017-2018 AlmuraDev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.almuradev.droplet.component.range;
import net.kyori.fragment.filter.FilterQuery;
import net.kyori.lunar.collection.MoreIterables;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Random;
public interface DoubleRange {
/**
* Gets the minimum value.
*
* <p>This may be the same as {@link #max()}.</p>
*
* @return the minimum value
*/
double min();
/**
* Gets the maximum value.
*
* <p>This may be the same as {@link #min()}.</p>
*
* @return the maximum value
*/
double max();
/**
* Tests if this range contains {@code that}.
*
* @param that the other range
* @return {@code true} if this range contains {@code that}, {@code false} otherwise
*/
default boolean contains(final DoubleRange that) {
return that.min() >= this.min() && that.max() <= this.max();
}
/**
* Tests if this range contains {@code value}.
*
* @param value the value
* @return {@code true} if this range contains the value, {@code false} otherwise
*/
default boolean contains(final double value) {
return value >= this.min() && value <= this.max();
}
/**
* Gets a random value within this range.
*
* @param random the random
* @return the value
*/
double random(final Random random);
/**
* Gets a floored random value within this range.
*
* @param random the random
* @return the floored value
*/
default int flooredRandom(final Random random) {
final double doubleValue = this.random(random);
final int intValue = (int) doubleValue;
return doubleValue < (double) intValue ? intValue - 1 : intValue;
}
interface Filtered extends DoubleRange, com.almuradev.droplet.component.filter.Filtered {
@Nullable
static <T> DoubleRange cachingSearch(final DefaultedFilteredDoubleRangeList list, final Map<T, DoubleRange> map, final T biome, final FilterQuery query) {
/* @Nullable */ DoubleRange found = list.oneOrDefault(query);
if(found == null) {
found = list.oneOrDefault(query);
if(found != null) {
map.put(biome, found);
}
}
return found;
}
}
static Filtered matchQueryOrRandom(final List<Filtered> items, final FilterQuery query) {
for(final Filtered filtered : items) {
if(filtered.filter().allowed(query)) {
return filtered;
}
}
return MoreIterables.random(items);
}
}
|
3e17bb3d5a7b093732700e71bfc85797be4c211f | 1,421 | java | Java | jworkflow.kernel/src/main/java/net/jworkflow/kernel/models/WorkflowDefinition.java | insad/jworkflow | c364e8c7a8c27394b909dc6fa51e5eda8d111926 | [
"MIT"
] | 60 | 2018-11-13T01:28:54.000Z | 2022-03-19T23:57:17.000Z | jworkflow.kernel/src/main/java/net/jworkflow/kernel/models/WorkflowDefinition.java | insad/jworkflow | c364e8c7a8c27394b909dc6fa51e5eda8d111926 | [
"MIT"
] | 7 | 2020-01-08T22:08:23.000Z | 2021-11-12T08:48:17.000Z | jworkflow.kernel/src/main/java/net/jworkflow/kernel/models/WorkflowDefinition.java | insad/jworkflow | c364e8c7a8c27394b909dc6fa51e5eda8d111926 | [
"MIT"
] | 25 | 2018-06-13T03:47:24.000Z | 2021-12-06T11:50:39.000Z | 19.202703 | 52 | 0.581281 | 10,108 | package net.jworkflow.kernel.models;
import java.util.ArrayList;
import java.util.List;
public final class WorkflowDefinition {
private String id;
private int version;
private String description;
private List<WorkflowStep> steps;
private Class dataType;
public WorkflowDefinition() {
setSteps(new ArrayList<>());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<WorkflowStep> getSteps() {
return steps;
}
public void setSteps(List<WorkflowStep> steps) {
this.steps = steps;
}
/**
* @return the dataType
*/
public Class getDataType() {
return dataType;
}
/**
* @param dataType the dataType to set
*/
public void setDataType(Class dataType) {
this.dataType = dataType;
}
public WorkflowStep findStep(int findId) {
for (WorkflowStep step: steps) {
if (step.getId() == findId)
return step;
}
return null;
}
}
|
3e17bb655247e8e2f566dc194459f8a595fdf2d5 | 1,160 | java | Java | spock-core/src/main/java/org/spockframework/mock/runtime/DynamicProxyMockFactory.java | jprinet/spock | 52ec8beabca3566025f3192bba78d3b2acb5f823 | [
"Apache-2.0"
] | 1 | 2022-03-27T06:39:27.000Z | 2022-03-27T06:39:27.000Z | spock-core/src/main/java/org/spockframework/mock/runtime/DynamicProxyMockFactory.java | jprinet/spock | 52ec8beabca3566025f3192bba78d3b2acb5f823 | [
"Apache-2.0"
] | null | null | null | spock-core/src/main/java/org/spockframework/mock/runtime/DynamicProxyMockFactory.java | jprinet/spock | 52ec8beabca3566025f3192bba78d3b2acb5f823 | [
"Apache-2.0"
] | null | null | null | 35.151515 | 127 | 0.755172 | 10,109 | package org.spockframework.mock.runtime;
import org.spockframework.mock.ISpockMockObject;
import org.spockframework.mock.runtime.DynamicProxyMockInterceptorAdapter;
import org.spockframework.mock.runtime.IProxyBasedMockInterceptor;
import org.spockframework.runtime.InvalidSpecException;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
class DynamicProxyMockFactory {
private static final Class<?>[] CLASSES = new Class<?>[0];
static Object createMock(Class<?> mockType, List<Class<?>> additionalInterfaces,
List<Object> constructorArgs, IProxyBasedMockInterceptor mockInterceptor, ClassLoader classLoader) {
if (constructorArgs != null) {
throw new InvalidSpecException("Interface based mocks may not have constructor arguments");
}
List<Class<?>> interfaces = new ArrayList<>();
interfaces.add(mockType);
interfaces.addAll(additionalInterfaces);
interfaces.add(ISpockMockObject.class);
return Proxy.newProxyInstance(
classLoader,
interfaces.toArray(CLASSES),
new DynamicProxyMockInterceptorAdapter(mockInterceptor)
);
}
}
|
3e17bbfd4a9a922d1bfedc2608ca714714cc10c7 | 2,334 | java | Java | GridEnhancements/src/main/java/org/vaadin/grid/enhancements/client/navigation/BodyNaviagtionHandler.java | bonprix/vaadin-grid-enhancements | 46e380e0c7ebe7b3ae933708137da4c391235670 | [
"Apache-2.0"
] | 1 | 2016-09-15T18:14:41.000Z | 2016-09-15T18:14:41.000Z | GridEnhancements/src/main/java/org/vaadin/grid/enhancements/client/navigation/BodyNaviagtionHandler.java | bonprix/vaadin-grid-enhancements | 46e380e0c7ebe7b3ae933708137da4c391235670 | [
"Apache-2.0"
] | null | null | null | GridEnhancements/src/main/java/org/vaadin/grid/enhancements/client/navigation/BodyNaviagtionHandler.java | bonprix/vaadin-grid-enhancements | 46e380e0c7ebe7b3ae933708137da4c391235670 | [
"Apache-2.0"
] | null | null | null | 27.785714 | 85 | 0.696658 | 10,110 | package org.vaadin.grid.enhancements.client.navigation;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Command;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.widget.grid.CellReference;
import com.vaadin.client.widget.grid.events.BodyKeyDownHandler;
import com.vaadin.client.widget.grid.events.GridKeyDownEvent;
public class BodyNaviagtionHandler implements BodyKeyDownHandler {
@Override
public void onKeyDown(GridKeyDownEvent event) {
switch (event.getNativeKeyCode()) {
case KeyCodes.KEY_ENTER:
if (isCellContainingComponent(event.getFocusedCell())) {
// Don't propagate enter to component
event.preventDefault();
event.stopPropagation();
final Element componentElement = extractComponentElement(event.getFocusedCell());
// Run focus as deferred command so the Navigation handler
// doesn't catch the event.
Scheduler .get()
.scheduleDeferred(new Command() {
@Override
public void execute() {
WidgetUtil.focus(componentElement);
NavigationUtil.focusInputField(componentElement);
}
});
}
break;
}
}
private Element extractComponentElement(CellReference cell) {
// Only check recursively if we are looking at a table
if (cell.getElement()
.getNodeName()
.equals("TD")) {
return NavigationUtil.getInputElement(cell .getElement()
.getChildNodes());
}
return null;
}
private boolean isCellContainingComponent(CellReference cell) {
// Only check recursively if we are looking at a table
if (cell.getElement()
.getNodeName()
.equals("TD")) {
return containsInput(cell .getElement()
.getChildNodes());
}
return false;
}
private boolean containsInput(NodeList<Node> nodes) {
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.getItem(i);
if (node.getNodeName()
.equals("INPUT")
|| node .getNodeName()
.equals("BUTTON")) {
return true;
} else if (node .getChildNodes()
.getLength() > 0) {
if (containsInput(node.getChildNodes())) {
return true;
}
}
}
return false;
}
} |
3e17bd2b4a0978f2002f85d2c656dfbf0ae84234 | 1,320 | java | Java | projects/batfish/src/main/java/org/batfish/vendor/a10/grammar/A10Preprocessor.java | ton31337/batfish | f8591e0c4578b655632648fb8e26bc814844d05c | [
"Apache-2.0"
] | 1 | 2018-11-07T19:31:03.000Z | 2018-11-07T19:31:03.000Z | projects/batfish/src/main/java/org/batfish/vendor/a10/grammar/A10Preprocessor.java | ton31337/batfish | f8591e0c4578b655632648fb8e26bc814844d05c | [
"Apache-2.0"
] | 2 | 2017-10-23T19:10:07.000Z | 2018-09-25T03:51:02.000Z | projects/batfish/src/main/java/org/batfish/vendor/a10/grammar/A10Preprocessor.java | ton31337/batfish | f8591e0c4578b655632648fb8e26bc814844d05c | [
"Apache-2.0"
] | 2 | 2017-08-11T14:04:59.000Z | 2017-10-23T19:04:51.000Z | 30 | 99 | 0.743939 | 10,111 | package org.batfish.vendor.a10.grammar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import org.batfish.vendor.a10.representation.A10Configuration;
/**
* Given a parse tree, extracts metadata for an {@link A10Configuration}.
*
* <p>This includes extracting things like ethernet interface default enable/disable status.
*/
public final class A10Preprocessor extends A10ParserBaseListener {
@Override
public void exitA10_configuration(A10Parser.A10_configurationContext ctx) {
_c.setMajorVersionNumber(getAcosMajorVersionNumber());
}
/** Infer ACOS version from the configuration text. */
private Integer getAcosMajorVersionNumber() {
Matcher matcher = ACOS_VERSION_PATTERN.matcher(_text);
if (!matcher.find()) {
return null;
}
return Integer.parseUnsignedInt(matcher.group(1));
}
public A10Preprocessor(String text, A10Configuration configuration) {
_text = text;
_c = configuration;
}
/**
* Pattern matching ACOS version strings, in leading comments in config dumps. Extracts the major
* version number in match group 1.
*/
private static Pattern ACOS_VERSION_PATTERN = Pattern.compile("!.*version (\\d+).\\d+.\\d+");
@Nonnull private A10Configuration _c;
@Nonnull private String _text;
}
|
3e17bd31555db25190e1b8c566235ac189d3e899 | 5,439 | java | Java | src/main/java/org/incendo/permission/bukkit/CustomPermissibleBase.java | Sauilitired/IncendoPermissions | 93ac86b96e11cae7644160d7f807e8ed8e46acfc | [
"MIT"
] | 7 | 2019-01-02T16:34:59.000Z | 2021-07-31T22:03:51.000Z | src/main/java/org/incendo/permission/bukkit/CustomPermissibleBase.java | Sauilitired/IncendoPermissions | 93ac86b96e11cae7644160d7f807e8ed8e46acfc | [
"MIT"
] | 1 | 2021-12-18T12:46:40.000Z | 2021-12-18T12:46:40.000Z | src/main/java/org/incendo/permission/bukkit/CustomPermissibleBase.java | Sauilitired/IncendoPermissions | 93ac86b96e11cae7644160d7f807e8ed8e46acfc | [
"MIT"
] | null | null | null | 39.70073 | 147 | 0.724214 | 10,112 | //
// MIT License
//
// Copyright (c) 2019 Alexander Söderberg
//
// 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.incendo.permission.bukkit;
import com.google.common.base.Preconditions;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissibleBase;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
final class CustomPermissibleBase extends PermissibleBase {
private final PermissionPlugin permissions;
private final PermissibleBase oldBase;
private final BukkitPlayer bukkitPlayer;
CustomPermissibleBase(@NotNull final PermissionPlugin permissions,
@NotNull final BukkitPlayer bukkitPlayer, @NotNull final Player player,
@NotNull final PermissibleBase oldBase) {
super(player);
Preconditions.checkNotNull(permissions, "permissins");
Preconditions.checkNotNull(bukkitPlayer, "bukkit player");
Preconditions.checkNotNull(player, "player");
Preconditions.checkNotNull(oldBase, "old base");
this.permissions = permissions;
this.oldBase = oldBase;
this.bukkitPlayer = bukkitPlayer;
}
@Override public boolean hasPermission(@NotNull final String permissionNode) {
if (bukkitPlayer.hasPermission(permissionNode)) {
return true;
}
return oldBase.hasPermission(permissionNode);
}
@Override public boolean hasPermission(@NotNull final Permission perm) {
return super.hasPermission(perm);
}
@Override public void removeAttachment(@NotNull final PermissionAttachment attachment) {
oldBase.removeAttachment(attachment);
}
@Override public boolean isOp() {
return oldBase.isOp();
}
@Override public void setOp(final boolean value) {
oldBase.setOp(value);
}
@Override public boolean isPermissionSet(@NotNull final String name) {
if (this.bukkitPlayer.hasPermissionSet(name)) {
return true;
}
return oldBase.isPermissionSet(name);
}
@Override public boolean isPermissionSet(@NotNull final Permission perm) {
if (this.bukkitPlayer.hasPermissionSet(perm.getName())) {
return true;
}
return oldBase.isPermissionSet(perm);
}
@Override public PermissionAttachment addAttachment(@NotNull final Plugin plugin,
@NotNull final String name, final boolean value) {
return oldBase.addAttachment(plugin, name, value);
}
@Override public PermissionAttachment addAttachment(@NotNull final Plugin plugin) {
return oldBase.addAttachment(plugin);
}
@Override public void recalculatePermissions() {
try {
oldBase.recalculatePermissions();
} catch (final Throwable ignored) {}
}
@Override public synchronized void clearPermissions() {
oldBase.clearPermissions();
}
@Override public PermissionAttachment addAttachment(@NotNull final Plugin plugin, @NotNull final String name,
final boolean value, final int ticks) {
return oldBase.addAttachment(plugin, name, value, ticks);
}
@Override public PermissionAttachment addAttachment(@NotNull final Plugin plugin, final int ticks) {
return oldBase.addAttachment(plugin, ticks);
}
@Override public Set<PermissionAttachmentInfo> getEffectivePermissions() {
// oldBase.getEffectivePermissions();
final Set<PermissionAttachmentInfo> minecraftAttachments = oldBase.getEffectivePermissions();
final Set<PermissionAttachmentInfo> infos = new HashSet<>(oldBase.getEffectivePermissions().size()
+ bukkitPlayer.getEffectivePermissions().size());
infos.addAll(minecraftAttachments);
for (final org.incendo.permission.Permission effectivePermission : this.bukkitPlayer.getEffectivePermissions()) {
final PermissionAttachmentInfo permissionAttachmentInfo = new PermissionAttachmentInfo(bukkitPlayer.getPlayer(),
effectivePermission.getRawName(), new PermissionAttachment(permissions, bukkitPlayer.getPlayer()), effectivePermission.getValue());
infos.add(permissionAttachmentInfo);
}
return infos;
}
}
|
3e17bd72ddcb445f0904a8c9378c1e73ca5e4baf | 1,676 | java | Java | archunit-example/example-plain/src/test/java/com/tngtech/archunit/exampletest/OnionArchitectureTest.java | spanierm/ArchUnit | 602080208dac2fd808cc00df0089668272fc2c0d | [
"Apache-2.0"
] | 2,143 | 2017-04-21T09:45:03.000Z | 2022-03-31T18:14:04.000Z | archunit-example/example-plain/src/test/java/com/tngtech/archunit/exampletest/OnionArchitectureTest.java | spanierm/ArchUnit | 602080208dac2fd808cc00df0089668272fc2c0d | [
"Apache-2.0"
] | 678 | 2017-04-26T19:26:48.000Z | 2022-03-31T16:34:39.000Z | archunit-example/example-plain/src/test/java/com/tngtech/archunit/exampletest/OnionArchitectureTest.java | spanierm/ArchUnit | 602080208dac2fd808cc00df0089668272fc2c0d | [
"Apache-2.0"
] | 274 | 2017-04-24T21:58:44.000Z | 2022-03-01T12:38:30.000Z | 38.976744 | 129 | 0.650358 | 10,113 | package com.tngtech.archunit.exampletest;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.example.onionarchitecture.domain.model.OrderItem;
import com.tngtech.archunit.example.onionarchitecture.domain.service.OrderQuantity;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static com.tngtech.archunit.library.Architectures.onionArchitecture;
@Category(Example.class)
public class OnionArchitectureTest {
private final JavaClasses classes = new ClassFileImporter().importPackages("com.tngtech.archunit.example.onionarchitecture");
@Test
public void onion_architecture_is_respected() {
onionArchitecture()
.domainModels("..domain.model..")
.domainServices("..domain.service..")
.applicationServices("..application..")
.adapter("cli", "..adapter.cli..")
.adapter("persistence", "..adapter.persistence..")
.adapter("rest", "..adapter.rest..")
.check(classes);
}
@Test
public void onion_architecture_is_respected_with_exception() {
onionArchitecture()
.domainModels("..domain.model..")
.domainServices("..domain.service..")
.applicationServices("..application..")
.adapter("cli", "..adapter.cli..")
.adapter("persistence", "..adapter.persistence..")
.adapter("rest", "..adapter.rest..")
.ignoreDependency(OrderItem.class, OrderQuantity.class)
.check(classes);
}
}
|
3e17bd963674ce985feec5ba8d59c173c830da34 | 10,781 | java | Java | hbase-mapreduce/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithOperationAttributes.java | bbeaudreault/hbase | 02d263e7dde146956fda0ec245aeae85926ab12f | [
"Apache-2.0"
] | 4,857 | 2015-01-02T11:45:14.000Z | 2022-03-31T14:00:55.000Z | hbase-mapreduce/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithOperationAttributes.java | bbeaudreault/hbase | 02d263e7dde146956fda0ec245aeae85926ab12f | [
"Apache-2.0"
] | 4,070 | 2015-05-01T02:52:57.000Z | 2022-03-31T23:54:50.000Z | hbase-mapreduce/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithOperationAttributes.java | bbeaudreault/hbase | 02d263e7dde146956fda0ec245aeae85926ab12f | [
"Apache-2.0"
] | 3,611 | 2015-01-02T11:33:55.000Z | 2022-03-31T11:12:19.000Z | 38.641577 | 101 | 0.717002 | 10,114 | /**
* 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.hadoop.hbase.mapreduce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionObserver;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.MapReduceTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.wal.WALEdit;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Category({MapReduceTests.class, LargeTests.class})
public class TestImportTSVWithOperationAttributes implements Configurable {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestImportTSVWithOperationAttributes.class);
private static final Logger LOG =
LoggerFactory.getLogger(TestImportTSVWithOperationAttributes.class);
protected static final String NAME = TestImportTsv.class.getSimpleName();
protected static HBaseTestingUtil util = new HBaseTestingUtil();
/**
* Delete the tmp directory after running doMROnTableTest. Boolean. Default is
* false.
*/
protected static final String DELETE_AFTER_LOAD_CONF = NAME + ".deleteAfterLoad";
/**
* Force use of combiner in doMROnTableTest. Boolean. Default is true.
*/
protected static final String FORCE_COMBINER_CONF = NAME + ".forceCombiner";
private static Configuration conf;
private static final String TEST_ATR_KEY = "test";
private final String FAMILY = "FAM";
@Rule
public TestName name = new TestName();
@Override
public Configuration getConf() {
return util.getConfiguration();
}
@Override
public void setConf(Configuration conf) {
throw new IllegalArgumentException("setConf not supported");
}
@BeforeClass
public static void provisionCluster() throws Exception {
conf = util.getConfiguration();
conf.set("hbase.coprocessor.master.classes", OperationAttributesTestController.class.getName());
conf.set("hbase.coprocessor.region.classes", OperationAttributesTestController.class.getName());
util.startMiniCluster();
}
@AfterClass
public static void releaseCluster() throws Exception {
util.shutdownMiniCluster();
}
@Test
public void testMROnTable() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName() + util.getRandomUUID());
// Prepare the arguments required for the test.
String[] args = new String[] {
"-D" + ImportTsv.MAPPER_CONF_KEY
+ "=org.apache.hadoop.hbase.mapreduce.TsvImporterCustomTestMapperForOprAttr",
"-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_ATTRIBUTES_KEY",
"-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName.getNameAsString() };
String data = "KEY\u001bVALUE1\u001bVALUE2\u001btest=>myvalue\n";
util.createTable(tableName, FAMILY);
doMROnTableTest(util, FAMILY, data, args, 1, true);
util.deleteTable(tableName);
}
@Test
public void testMROnTableWithInvalidOperationAttr() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName() + util.getRandomUUID());
// Prepare the arguments required for the test.
String[] args = new String[] {
"-D" + ImportTsv.MAPPER_CONF_KEY
+ "=org.apache.hadoop.hbase.mapreduce.TsvImporterCustomTestMapperForOprAttr",
"-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_ATTRIBUTES_KEY",
"-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName.getNameAsString() };
String data = "KEY\u001bVALUE1\u001bVALUE2\u001btest1=>myvalue\n";
util.createTable(tableName, FAMILY);
doMROnTableTest(util, FAMILY, data, args, 1, false);
util.deleteTable(tableName);
}
/**
* Run an ImportTsv job and perform basic validation on the results. Returns
* the ImportTsv <code>Tool</code> instance so that other tests can inspect it
* for further validation as necessary. This method is static to insure
* non-reliance on instance's util/conf facilities.
*
* @param args
* Any arguments to pass BEFORE inputFile path is appended.
* @param dataAvailable
* @return The Tool instance used to run the test.
*/
private Tool doMROnTableTest(HBaseTestingUtil util, String family, String data, String[] args,
int valueMultiplier, boolean dataAvailable) throws Exception {
String table = args[args.length - 1];
Configuration conf = new Configuration(util.getConfiguration());
// populate input file
FileSystem fs = FileSystem.get(conf);
Path inputPath = fs.makeQualified(new Path(util.getDataTestDirOnTestFS(table), "input.dat"));
FSDataOutputStream op = fs.create(inputPath, true);
op.write(Bytes.toBytes(data));
op.close();
LOG.debug(String.format("Wrote test data to file: %s", inputPath));
if (conf.getBoolean(FORCE_COMBINER_CONF, true)) {
LOG.debug("Forcing combiner.");
conf.setInt("mapreduce.map.combine.minspills", 1);
}
// run the import
List<String> argv = new ArrayList<>(Arrays.asList(args));
argv.add(inputPath.toString());
Tool tool = new ImportTsv();
LOG.debug("Running ImportTsv with arguments: " + argv);
assertEquals(0, ToolRunner.run(conf, tool, argv.toArray(args)));
validateTable(conf, TableName.valueOf(table), family, valueMultiplier, dataAvailable);
if (conf.getBoolean(DELETE_AFTER_LOAD_CONF, true)) {
LOG.debug("Deleting test subdirectory");
util.cleanupDataTestDirOnTestFS(table);
}
return tool;
}
/**
* Confirm ImportTsv via data in online table.
*
* @param dataAvailable
*/
private static void validateTable(Configuration conf, TableName tableName, String family,
int valueMultiplier, boolean dataAvailable) throws IOException {
LOG.debug("Validating table.");
Connection connection = ConnectionFactory.createConnection(conf);
Table table = connection.getTable(tableName);
boolean verified = false;
long pause = conf.getLong("hbase.client.pause", 5 * 1000);
int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
for (int i = 0; i < numRetries; i++) {
try {
Scan scan = new Scan();
// Scan entire family.
scan.addFamily(Bytes.toBytes(family));
if (dataAvailable) {
ResultScanner resScanner = table.getScanner(scan);
for (Result res : resScanner) {
LOG.debug("Getting results " + res.size());
assertTrue(res.size() == 2);
List<Cell> kvs = res.listCells();
assertTrue(CellUtil.matchingRows(kvs.get(0), Bytes.toBytes("KEY")));
assertTrue(CellUtil.matchingRows(kvs.get(1), Bytes.toBytes("KEY")));
assertTrue(CellUtil.matchingValue(kvs.get(0), Bytes.toBytes("VALUE" + valueMultiplier)));
assertTrue(CellUtil.matchingValue(kvs.get(1),
Bytes.toBytes("VALUE" + 2 * valueMultiplier)));
// Only one result set is expected, so let it loop.
verified = true;
}
} else {
ResultScanner resScanner = table.getScanner(scan);
Result[] next = resScanner.next(2);
assertEquals(0, next.length);
verified = true;
}
break;
} catch (NullPointerException e) {
// If here, a cell was empty. Presume its because updates came in
// after the scanner had been opened. Wait a while and retry.
}
try {
Thread.sleep(pause);
} catch (InterruptedException e) {
// continue
}
}
table.close();
connection.close();
assertTrue(verified);
}
public static class OperationAttributesTestController
implements RegionCoprocessor, RegionObserver {
@Override
public Optional<RegionObserver> getRegionObserver() {
return Optional.of(this);
}
@Override
public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit,
Durability durability) throws IOException {
Region region = e.getEnvironment().getRegion();
if (!region.getRegionInfo().isMetaRegion()
&& !region.getRegionInfo().getTable().isSystemTable()) {
if (put.getAttribute(TEST_ATR_KEY) != null) {
LOG.debug("allow any put to happen " + region.getRegionInfo().getRegionNameAsString());
} else {
e.bypass();
}
}
}
}
}
|
3e17bf108b6614a629434c27eb045bd29a610b95 | 13,886 | java | Java | src/main/java/org/jabref/JabRefGUI.java | caioasilva/T5-ES-DC-UFSCAR-TA | be1c48e6f342d5a91cd201d4674afff17d401625 | [
"MIT"
] | 2 | 2017-12-20T15:40:29.000Z | 2018-12-14T09:35:11.000Z | src/main/java/org/jabref/JabRefGUI.java | T2-ES-DC-UFSCAR-TC/jabRefImproved | 96ad162c721b59dfc0613a048e13bed32ea37e99 | [
"MIT"
] | null | null | null | src/main/java/org/jabref/JabRefGUI.java | T2-ES-DC-UFSCAR-TC/jabRefImproved | 96ad162c721b59dfc0613a048e13bed32ea37e99 | [
"MIT"
] | 1 | 2021-01-05T10:10:58.000Z | 2021-01-05T10:10:58.000Z | 44.512821 | 165 | 0.621904 | 10,115 | package org.jabref;
import java.awt.Frame;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.metal.MetalLookAndFeel;
import org.jabref.gui.BasePanel;
import org.jabref.gui.GUIGlobals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.autosaveandbackup.BackupUIManager;
import org.jabref.gui.importer.ParserResultWarningDialog;
import org.jabref.gui.importer.actions.OpenDatabaseAction;
import org.jabref.gui.shared.SharedDatabaseUIManager;
import org.jabref.gui.worker.VersionWorker;
import org.jabref.logic.autosaveandbackup.BackupManager;
import org.jabref.logic.importer.OpenDatabase;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.OS;
import org.jabref.logic.util.Version;
import org.jabref.preferences.JabRefPreferences;
import org.jabref.shared.exception.DatabaseNotSupportedException;
import org.jabref.shared.exception.InvalidDBMSConnectionPropertiesException;
import org.jabref.shared.exception.NotASharedDatabaseException;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jgoodies.looks.plastic.theme.SkyBluer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JabRefGUI {
private static final Log LOGGER = LogFactory.getLog(JabRefGUI.class);
private static JabRefFrame mainFrame;
private final List<ParserResult> bibDatabases;
private final boolean isBlank;
private final List<ParserResult> failed = new ArrayList<>();
private final List<ParserResult> toOpenTab = new ArrayList<>();
private String focusedFile;
public JabRefGUI(List<ParserResult> argsDatabases, boolean isBlank) {
this.bibDatabases = argsDatabases;
this.isBlank = isBlank;
// passed file (we take the first one) should be focused
focusedFile = argsDatabases.stream().findFirst().flatMap(ParserResult::getFile).map(File::getAbsolutePath)
.orElse(Globals.prefs.get(JabRefPreferences.LAST_FOCUSED));
openWindow();
JabRefGUI.checkForNewVersion(false);
}
public static void checkForNewVersion(boolean manualExecution) {
Version toBeIgnored = Globals.prefs.getVersionPreferences().getIgnoredVersion();
Version currentVersion = Globals.BUILD_INFO.getVersion();
new VersionWorker(JabRefGUI.getMainFrame(), manualExecution, currentVersion, toBeIgnored).execute();
}
private void openWindow() {
// This property is set to make the Mac OSX Java VM move the menu bar to the top of the screen
if (OS.OS_X) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
// Set antialiasing on everywhere. This only works in JRE >= 1.5.
// Or... it doesn't work, period.
// TODO test and maybe remove this! I found this commented out with no additional info ( efpyi@example.com )
// Enabled since JabRef 2.11 beta 4
System.setProperty("swing.aatext", "true");
// Default is "on".
// "lcd" instead of "on" because of http://wiki.netbeans.org/FaqFontRendering and http://docs.oracle.com/javase/6/docs/technotes/guides/2d/flags.html#aaFonts
System.setProperty("awt.useSystemAAFontSettings", "lcd");
// look and feel. This MUST be the first thing to do before loading any Swing-specific code!
setLookAndFeel();
// If the option is enabled, open the last edited libraries, if any.
if (!isBlank && Globals.prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) {
openLastEditedDatabases();
}
GUIGlobals.init();
LOGGER.debug("Initializing frame");
JabRefGUI.mainFrame = new JabRefFrame();
// Add all bibDatabases databases to the frame:
boolean first = false;
if (!bibDatabases.isEmpty()) {
for (Iterator<ParserResult> parserResultIterator = bibDatabases.iterator(); parserResultIterator.hasNext();) {
ParserResult pr = parserResultIterator.next();
// Define focused tab
if (pr.getFile().get().getAbsolutePath().equals(focusedFile)) {
first = true;
}
if (pr.isInvalid()) {
failed.add(pr);
parserResultIterator.remove();
} else if (pr.getDatabase().isShared()) {
try {
new SharedDatabaseUIManager(mainFrame).openSharedDatabaseFromParserResult(pr);
} catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException |
NotASharedDatabaseException e) {
pr.getDatabaseContext().clearDatabaseFile(); // do not open the original file
pr.getDatabase().clearSharedDatabaseID();
LOGGER.error("Connection error", e);
JOptionPane.showMessageDialog(mainFrame,
e.getMessage() + "\n\n" + Localization.lang("A local copy will be opened."),
Localization.lang("Connection error"), JOptionPane.WARNING_MESSAGE);
}
toOpenTab.add(pr);
} else if (pr.toOpenTab()) {
// things to be appended to an opened tab should be done after opening all tabs
// add them to the list
toOpenTab.add(pr);
} else {
JabRefGUI.getMainFrame().addParserResult(pr, first);
first = false;
}
}
}
// finally add things to the currently opened tab
for (ParserResult pr : toOpenTab) {
JabRefGUI.getMainFrame().addParserResult(pr, first);
first = false;
}
// If we are set to remember the window location, we also remember the maximised
// state. This needs to be set after the window has been made visible, so we
// do it here:
if (Globals.prefs.getBoolean(JabRefPreferences.WINDOW_MAXIMISED)) {
JabRefGUI.getMainFrame().setExtendedState(Frame.MAXIMIZED_BOTH);
}
JabRefGUI.getMainFrame().setVisible(true);
for (ParserResult pr : failed) {
String message = "<html>" + Localization.lang("Error opening file '%0'.", pr.getFile().get().getName())
+ "<p>"
+ pr.getErrorMessage() + "</html>";
JOptionPane.showMessageDialog(JabRefGUI.getMainFrame(), message, Localization.lang("Error opening file"),
JOptionPane.ERROR_MESSAGE);
}
// Display warnings, if any
int tabNumber = 0;
for (ParserResult pr : bibDatabases) {
ParserResultWarningDialog.showParserResultWarningDialog(pr, JabRefGUI.getMainFrame(), tabNumber++);
}
// After adding the databases, go through each and see if
// any post open actions need to be done. For instance, checking
// if we found new entry types that can be imported, or checking
// if the database contents should be modified due to new features
// in this version of JabRef.
// Note that we have to check whether i does not go over getBasePanelCount().
// This is because importToOpen might have been used, which adds to
// loadedDatabases, but not to getBasePanelCount()
for (int i = 0; (i < bibDatabases.size()) && (i < JabRefGUI.getMainFrame().getBasePanelCount()); i++) {
ParserResult pr = bibDatabases.get(i);
BasePanel panel = JabRefGUI.getMainFrame().getBasePanelAt(i);
OpenDatabaseAction.performPostOpenActions(panel, pr);
}
LOGGER.debug("Finished adding panels");
if (!bibDatabases.isEmpty()) {
JabRefGUI.getMainFrame().getCurrentBasePanel().getMainTable().requestFocus();
}
}
private void openLastEditedDatabases() {
if (Globals.prefs.get(JabRefPreferences.LAST_EDITED) == null) {
return;
}
List<String> lastFiles = Globals.prefs.getStringList(JabRefPreferences.LAST_EDITED);
for (String fileName : lastFiles) {
File dbFile = new File(fileName);
// Already parsed via command line parameter, e.g., "jabref.jar somefile.bib"
if (isLoaded(dbFile) || !dbFile.exists()) {
continue;
}
if (BackupManager.checkForBackupFile(dbFile.toPath())) {
BackupUIManager.showRestoreBackupDialog(mainFrame, dbFile.toPath());
}
ParserResult parsedDatabase = OpenDatabase.loadDatabase(fileName,
Globals.prefs.getImportFormatPreferences());
if (parsedDatabase.isEmpty()) {
LOGGER.error(Localization.lang("Error opening file") + " '" + dbFile.getPath() + "'");
} else {
bibDatabases.add(parsedDatabase);
}
}
}
private boolean isLoaded(File fileToOpen) {
for (ParserResult pr : bibDatabases) {
if (pr.getFile().isPresent() && pr.getFile().get().equals(fileToOpen)) {
return true;
}
}
return false;
}
private void setLookAndFeel() {
try {
String lookFeel;
String systemLookFeel = UIManager.getSystemLookAndFeelClassName();
if (Globals.prefs.getBoolean(JabRefPreferences.USE_DEFAULT_LOOK_AND_FEEL)) {
// FIXME: Problems with OpenJDK and GTK L&F
// See https://github.com/JabRef/jabref/issues/393, https://github.com/JabRef/jabref/issues/638
if (System.getProperty("java.runtime.name").contains("OpenJDK")) {
// Metal L&F
lookFeel = UIManager.getCrossPlatformLookAndFeelClassName();
LOGGER.warn(
"There seem to be problems with OpenJDK and the default GTK Look&Feel. Using Metal L&F instead. Change to another L&F with caution.");
} else {
lookFeel = systemLookFeel;
}
} else {
lookFeel = Globals.prefs.get(JabRefPreferences.WIN_LOOK_AND_FEEL);
}
// FIXME: Open JDK problem
if (UIManager.getCrossPlatformLookAndFeelClassName().equals(lookFeel)
&& !System.getProperty("java.runtime.name").contains("OpenJDK")) {
// try to avoid ending up with the ugly Metal L&F
Plastic3DLookAndFeel lnf = new Plastic3DLookAndFeel();
MetalLookAndFeel.setCurrentTheme(new SkyBluer());
com.jgoodies.looks.Options.setPopupDropShadowEnabled(true);
UIManager.setLookAndFeel(lnf);
} else {
try {
UIManager.setLookAndFeel(lookFeel);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException e) {
// specified look and feel does not exist on the classpath, so use system l&f
UIManager.setLookAndFeel(systemLookFeel);
// also set system l&f as default
Globals.prefs.put(JabRefPreferences.WIN_LOOK_AND_FEEL, systemLookFeel);
// notify the user
JOptionPane.showMessageDialog(JabRefGUI.getMainFrame(),
Localization
.lang("Unable to find the requested look and feel and thus the default one is used."),
Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE);
LOGGER.warn("Unable to find requested look and feel", e);
}
}
// On Linux, Java FX fonts look blurry per default. This can be improved by using a non-default rendering
// setting. See https://github.com/woky/javafx-hates-linux
if (Globals.prefs.getBoolean(JabRefPreferences.FX_FONT_RENDERING_TWEAK)) {
System.setProperty("prism.text", "t2k");
System.setProperty("prism.lcdtext", "true");
}
} catch (Exception e) {
LOGGER.warn("Look and feel could not be set", e);
}
// In JabRef v2.8, we did it only on NON-Mac. Now, we try on all platforms
boolean overrideDefaultFonts = Globals.prefs.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONTS);
if (overrideDefaultFonts) {
int fontSize = Globals.prefs.getInt(JabRefPreferences.MENU_FONT_SIZE);
UIDefaults defaults = UIManager.getDefaults();
Enumeration<Object> keys = defaults.keys();
for (Object key : Collections.list(keys)) {
if ((key instanceof String) && ((String) key).endsWith(".font")) {
FontUIResource font = (FontUIResource) UIManager.get(key);
font = new FontUIResource(font.getName(), font.getStyle(), fontSize);
defaults.put(key, font);
}
}
}
}
public static JabRefFrame getMainFrame() {
return mainFrame;
}
// Only used for testing, other than that do NOT set the mainFrame...
public static void setMainFrame(JabRefFrame mainFrame) {
JabRefGUI.mainFrame = mainFrame;
}
}
|
3e17bf4fbf99ef13eac4cbf483db4bf3115b4349 | 1,081 | java | Java | src/main/java/com/couchbase/client/dcp/core/CouchbaseException.java | couchbase/java-dcp-client | 692da2ea4175f796a1011050aeadf37a93705e8a | [
"Apache-2.0"
] | 29 | 2017-08-15T08:54:27.000Z | 2021-09-03T16:10:57.000Z | src/main/java/com/couchbase/client/dcp/core/CouchbaseException.java | couchbase/java-dcp-client | 692da2ea4175f796a1011050aeadf37a93705e8a | [
"Apache-2.0"
] | 6 | 2017-12-18T16:51:57.000Z | 2021-04-26T20:17:08.000Z | src/main/java/com/couchbase/client/dcp/core/CouchbaseException.java | couchbase/java-dcp-client | 692da2ea4175f796a1011050aeadf37a93705e8a | [
"Apache-2.0"
] | 10 | 2017-12-18T16:11:15.000Z | 2022-02-24T11:24:18.000Z | 27.717949 | 83 | 0.728955 | 10,116 | /*
* Copyright (c) 2016 Couchbase, 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.couchbase.client.dcp.core;
/**
* Common parent exception to build a proper exception hierarchy inside the driver.
*/
public class CouchbaseException extends RuntimeException {
public CouchbaseException() {
super();
}
public CouchbaseException(String message) {
super(message);
}
public CouchbaseException(String message, Throwable cause) {
super(message, cause);
}
public CouchbaseException(Throwable cause) {
super(cause);
}
}
|
3e17bf754a56fb44affb6ab1d04d65fe35a670ba | 636 | java | Java | Digital Menu/Master/src/connection/StatusFromJSON.java | Soare-Robert-Daniel/Project-Sarus | 38f8b5c579eda0cf941f05e35bd5063d31d06ce4 | [
"MIT"
] | null | null | null | Digital Menu/Master/src/connection/StatusFromJSON.java | Soare-Robert-Daniel/Project-Sarus | 38f8b5c579eda0cf941f05e35bd5063d31d06ce4 | [
"MIT"
] | null | null | null | Digital Menu/Master/src/connection/StatusFromJSON.java | Soare-Robert-Daniel/Project-Sarus | 38f8b5c579eda0cf941f05e35bd5063d31d06ce4 | [
"MIT"
] | null | null | null | 24.461538 | 70 | 0.646226 | 10,117 | package connection;
import data.Order;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.StringReader;
public class StatusFromJSON {
public static boolean getStatusConnection(String data){
JsonReader reader = Json.createReader(new StringReader(data));
System.out.println(data);
JsonObject statusObj = reader.readObject();
reader.close();
if(statusObj.getString("valid").equals("Yes")){
return true;
}
else{
System.out.println(statusObj.getString("log"));
return false;
}
}
}
|
3e17c102ac82d7c7ac361a1d26c06d6f6da1e4c9 | 1,793 | java | Java | src/main/java/frc/robot/commands/ManualTeleop/DriveTeleop.java | NohoRoboForever/2022-Code | 0383667aea9fd392b954efaa2bc2d9ea40aacbdb | [
"BSD-3-Clause"
] | 5 | 2022-03-05T01:10:14.000Z | 2022-03-30T02:59:22.000Z | src/main/java/frc/robot/commands/ManualTeleop/DriveTeleop.java | NohoRobo/2022-Code | 0383667aea9fd392b954efaa2bc2d9ea40aacbdb | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/ManualTeleop/DriveTeleop.java | NohoRobo/2022-Code | 0383667aea9fd392b954efaa2bc2d9ea40aacbdb | [
"BSD-3-Clause"
] | 1 | 2022-02-19T06:33:44.000Z | 2022-02-19T06:33:44.000Z | 26.367647 | 116 | 0.721138 | 10,118 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.ManualTeleop;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Constants;
import frc.robot.Robot;
import frc.robot.subsystems.Drive;
public class DriveTeleop extends CommandBase {
private Drive drive = Drive.getInstance();
/** Creates a new DriveTeleop. */
public DriveTeleop() {
addRequirements(drive);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
if (Robot.auton) return;
double leftAxisInput = Robot.robotContainer.sticky1.getLeftY();
double rightAxisInput = Robot.robotContainer.sticky1.getRightY();
double leftAxisInput2 = Robot.robotContainer.sticky2.getLeftY();
double rightAxisInput2 = Robot.robotContainer.sticky2.getRightY();
if (Math.abs(leftAxisInput) > Constants.LeftDeadzone || Math.abs(leftAxisInput2) > Constants.LeftDeadzone) {
drive.setDriveL(Constants.LeftDrive*Math.pow(leftAxisInput, 3));
} else {
drive.setDriveL(0);
}
if (Math.abs(rightAxisInput) > Constants.RightDeadzone || Math.abs(rightAxisInput2) > Constants.RightDeadzone) {
drive.setDriveR(Constants.RightDrive*Math.pow(-rightAxisInput, 3));
} else {
drive.setDriveR(0);
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return false;
}
}
|
3e17c11340829784ee8043bf714e4dc844a84c83 | 8,180 | java | Java | src/test/java/com/kioea/www/jsouputil/TianyaHongbao.java | sekift/kioea | f5de759e9242c27bec8e7ac9f45c0f4829d99a0e | [
"Apache-2.0"
] | null | null | null | src/test/java/com/kioea/www/jsouputil/TianyaHongbao.java | sekift/kioea | f5de759e9242c27bec8e7ac9f45c0f4829d99a0e | [
"Apache-2.0"
] | 7 | 2022-01-25T02:26:52.000Z | 2022-01-25T02:26:55.000Z | src/test/java/com/kioea/www/jsouputil/TianyaHongbao.java | sekift/kioea | f5de759e9242c27bec8e7ac9f45c0f4829d99a0e | [
"Apache-2.0"
] | null | null | null | 31.705426 | 132 | 0.633007 | 10,119 | package com.kioea.www.jsouputil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import com.kioea.www.regexutil.RegexUtil;
import org.apache.commons.io.FileUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kioea.www.async.SleepUtil;
import com.kioea.www.dateutil.DateUtil;
import com.kioea.www.stringutil.StringUtil;
import com.kioea.www.urlutil.HtmlUtil;
import com.kioea.www.urlutil.SendMessageTool;
/**
*
* @author:sekift
* @time:2015-2-6 上午11:29:58
* @version:
*/
public class TianyaHongbao implements Runnable {
private static final Logger logger=LoggerFactory.getLogger(TianyaHongbao.class);
private static List<String> siteList = new ArrayList<String>();
private static List<Queue<String>> queueList = new ArrayList<Queue<String>>();
private static List<String> fileList = new ArrayList<String>();
//长日期
private static final String DATE_LONG_FORMAT = "yyyy-MM-dd HH:mm:ss";
static {
getSiteList();
getQueueList();
getFileList();
}
private static List<String> getSiteList() {
siteList.add("http://bbs.otianya.cn/post-stocks-1266823-10000.shtml");// 一把火 1
siteList.add("http://bbs.otianya.cn/post-stocks-1312311-10000.shtml");// andy1976 2
/*
siteList.add("http://bbs.otianya.cn/cgi-bin/bbs.pl?url=http://bbs.tianya.cn/post-stocks-1394413-10000.shtml");// 犀利哥 3
siteList.add("http://bbs.otianya.cn/cgi-bin/bbs.pl?url=http://bbs.tianya.cn/post-stocks-1468898-10000.shtml");// 一点钟 4
siteList.add("http://bbs.otianya.cn/cgi-bin/bbs.pl?url=http://bbs.tianya.cn/post-stocks-1403333-10000.shtml");// 航海 5
siteList.add("http://bbs.otianya.cn/cgi-bin/bbs.pl?url=http://bbs.tianya.cn/post-stocks-1557984-10000.shtml");// 超短 6
siteList.add("http://bbs.otianya.cn/cgi-bin/bbs.pl?url=http://bbs.tianya.cn/post-no100-73073-10000.shtml");// 龙 7
*/
//TODO 在这里添加适当合法的网址
return siteList;
}
private static List<Queue<String>> getQueueList() {
for (int i = 0; i < siteList.size(); i++) {
queueList.add(new LinkedList<String>());
}
return queueList;
}
private static List<String> getFileList() {
String preFileName = System.getProperty("user.dir") + "\\TianyaHongbao";
String proFileName = ".txt";
File file = null;
String medFileName=null;
for (int i = 0; i < siteList.size(); i++) {
medFileName = RegexUtil.fetchStr("[-\\d-]+", siteList.get(i));
String fileName = preFileName + medFileName + proFileName;
file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
fileList.add(fileName);
}
return fileList;
}
// 从文件获取上次保存的信息
private static Queue<String> getQueue(String fileName, Queue<String> queuea) {
String str = null;
try {
str = FileUtils.readFileToString(new File(fileName), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
if (!StringUtil.isNullOrBlank(str)) {
str = str.replace("[", "").replace("]", "");
queuea.add(str.substring(0, str.indexOf(",")).trim());
queuea.add(str.substring(str.indexOf(",") + 1, str.length()).trim());
} else {
queuea.add("1970-01-01 00:00:00");
queuea.add("1970-01-01 00:00:00");
}
return queuea;
}
@Override
public void run() {
Date date = null;
String time = "";
String content = "";
Element contents= null;
String louzhu = "";
int j = 0;
Elements eles = null;
try {
while (true) {
date = new Date(System.currentTimeMillis());
logger.error(DateUtil.convertDateToStr(date, DATE_LONG_FORMAT));
for (int i = 0; i < siteList.size(); i++) {
eles = JsoupUtil.getByAttrClass(siteList.get(i), "atl-item");
//获取最后一条楼主发言
for (Element ele : eles) {
if (!ele.select("span").get(0).text().contains("作者")) {
louzhu = ele.select("span").get(0).text();// 楼主标识
time = ele.select("span").get(1).text();// 帖子时间
contents = ele.getElementsByClass("bbs-content").get(0);// 帖子内容未处理
content = contents.text();// 帖子内容
}
}
//出现eles空的情况,以当前时间为准,内容为空
if (eles.isEmpty() || eles.size() == 0) {
louzhu = "本页无内容";// 楼主标识
time = DateUtil.convertDateToStr(date, DATE_LONG_FORMAT);// 帖子时间
content = "本页无更新";// 帖子内容
}
// 转换
if (time != null && louzhu.contains("楼主")) {
String timestampA = time.replace("时间:", "");
queueList.get(i).offer(timestampA);
if (queueList.get(i).size() > 1) {
if (queueList.get(i).size() > 2) {
// 有时候会出错,稳定后删除
System.out.println(queueList.get(i));
logger.error("文件的时间数出错了,请检查…… ");
break;
}
// 写入到文件,方便线程挂后重新获取(替换方式)
FileUtils.writeStringToFile(new File(fileList.get(i)), queueList.get(i).toString(),
"utf-8", false);
// 发邮件判断
if (vatifyFlag(queueList.get(i).poll(), queueList.get(i).peek(), contents)) {
// 邮件通知
sendMessageByEmail(time, content, siteList.get(i));
// 发送短信
// sendMessageByMobile(time,content,siteList.get(i));
j++;
// 防止出了问题疯狂地发邮件
if (j > 50) {
break;
}
}
}
}
//重新赋值
louzhu = null;
time = null;
content = null;
}
//睡眠时间1-3分钟随机
SleepUtil.sleepByMinute(1, 3);
}
} catch (Exception e) {
logger.error("出错了: ",e);
// 出错后重新开始
Thread t = new Thread(new TianyaHongbao());
t.start();
e.printStackTrace();
System.out.println("线程已重新开始");
}
}
/**
* 触发判断 内容的逻辑处理
*/
private static boolean vatifyFlag(String firstTimestamp, String secondTimestamp, Element contents) {
Date firstDate = DateUtil.convertStrToDate(firstTimestamp, DATE_LONG_FORMAT);
Date secondDate = DateUtil.convertStrToDate(secondTimestamp, DATE_LONG_FORMAT);
boolean haveHongbao = contents.toString().contains("抢红包</a>】") && !contents.toString().contains("抢到了");
boolean flag = false;
if (secondDate.getTime() > firstDate.getTime()) {
if (haveHongbao) {
flag = true;
}
}
return flag;
}
//邮箱通知 内容过滤
private static void sendMessageByEmail(String time, String content, String site) {
try {
String title = "【抢红包】";
site = site.replace("bbs.otianya.cn/cgi-bin/bbs.pl?url=http://", "");
String msg = time + "<br />" + "<a href=\"" + site + "\">" + site + "</a><br />" + content;
System.out.println(site);
MailUtil.sendHTML("lyhxr@example.com", title, msg);
// MailUtil.sendHTML("dycjh@example.com", title, msg);
//TODO 添加接收邮件的邮件
// 139会有短信通知,过长不行
String contents = HtmlUtil.filterHtmlTag(content, "UTF-8").replace("\n", "");
contents = contents.replace(" ", "").replace("\t", "");
msg = time + "<br />" + "<a href=\"" + site + "\">" + site + "</a><br />" + content;
// MailUtil.sendHTML("efpyi@example.com", title, msg);
//TODO 添加接收邮件的139邮件
} catch (Exception e) {
System.out.println("可能是mail的jar包冲突,请检查……");
e.printStackTrace();
}
}
// 短信通知 内容过滤
private static void sendMessageByMobile(String time, String content, String site) {
// 短信控制在70字以内
String msg = null;
site = site.replace("bbs.otianya.cn/cgi-bin/bbs.pl?url=http://", "");
String contents = HtmlUtil.filterHtmlTag(content, "UTF-8").replace("\n", "");
contents = contents.replace(" ", "").replace("\t", "");
if (contents.length() >= 30) {
contents = contents.substring(0, 30);
}
msg = time + " " + site + " " + contents;
// TODO 添加发短信的接口
String response = SendMessageTool.sendMessageByRemoteSMS("13660708603", msg);
if (response.equals("1")) {
System.out.println("发送短信成功");
} else if (response.equals("0")) {
System.out.println("发送短信失败");
logger.error("发送短信失败" + 0);
}
}
public static void main(String[] args) {
Thread t = new Thread(new TianyaHongbao());
// 初始化上次的信息
for (int i = 0; i < fileList.size(); i++) {
queueList.set(i, getQueue(fileList.get(i), queueList.get(i)));
queueList.get(i).poll();
}
t.start();
System.out.println("线程开始");
}
} |
3e17c13085a1759de233199ed77fb8a0e1a02999 | 1,044 | java | Java | allsrc/com/ushaqi/zhuishushenqi/ui/post/aF.java | clilystudio/NetBook | a8ca6cb91e9259ed7dec70b830829d622525b4b7 | [
"Unlicense"
] | 1 | 2018-02-04T12:23:55.000Z | 2018-02-04T12:23:55.000Z | allsrc/com/ushaqi/zhuishushenqi/ui/post/aF.java | clilystudio/NetBook | a8ca6cb91e9259ed7dec70b830829d622525b4b7 | [
"Unlicense"
] | null | null | null | allsrc/com/ushaqi/zhuishushenqi/ui/post/aF.java | clilystudio/NetBook | a8ca6cb91e9259ed7dec70b830829d622525b4b7 | [
"Unlicense"
] | null | null | null | 29.828571 | 130 | 0.685824 | 10,120 | package com.ushaqi.zhuishushenqi.ui.post;
import android.os.AsyncTask.Status;
import android.support.design.widget.am;
import android.view.View;
import com.handmark.pulltorefresh.library.j;
final class aF
implements j
{
aF(BookReviewListFragment paramBookReviewListFragment)
{
}
public final void a()
{
if ((BookReviewListFragment.b(this.a) == null) || (BookReviewListFragment.b(this.a).getStatus() == AsyncTask.Status.FINISHED))
{
this.a.c.setVisibility(0);
if (!am.a(BookReviewListFragment.j(this.a)))
BookReviewListFragment.j(this.a).cancel(true);
BookReviewListFragment.a(this.a, new aH(this.a, 0));
aH localaH = BookReviewListFragment.b(this.a);
String[] arrayOfString = new String[2];
arrayOfString[0] = this.a.a();
arrayOfString[1] = this.a.f;
localaH.b(arrayOfString);
}
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.ui.post.aF
* JD-Core Version: 0.6.0
*/ |
3e17c20b2293a9438d036da5f38b42b9f633e9a8 | 710 | java | Java | example-eclipse/src/com/diffplug/talks/socketsandplugs/eclipse/Operator.java | diffplug/sockets-and-plugs | 518c8ad5ea1e03344bf1e01c91a56ac01ec2d80a | [
"Apache-2.0"
] | null | null | null | example-eclipse/src/com/diffplug/talks/socketsandplugs/eclipse/Operator.java | diffplug/sockets-and-plugs | 518c8ad5ea1e03344bf1e01c91a56ac01ec2d80a | [
"Apache-2.0"
] | null | null | null | example-eclipse/src/com/diffplug/talks/socketsandplugs/eclipse/Operator.java | diffplug/sockets-and-plugs | 518c8ad5ea1e03344bf1e01c91a56ac01ec2d80a | [
"Apache-2.0"
] | null | null | null | 33.809524 | 75 | 0.746479 | 10,121 | /*
* Copyright 2016 DiffPlug
*
* 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.diffplug.talks.socketsandplugs.eclipse;
public interface Operator {
double calculate(double... args);
}
|
3e17c26ce5ae3435f646a69c73b6e167a6fa219c | 958 | java | Java | app/src/main/java/com/weather/android/about.java | syy703/weather | a2cab343e4dfe10de558b68840ae1ac26144bdde | [
"Apache-2.0"
] | 2 | 2018-06-13T06:44:20.000Z | 2018-06-13T06:44:41.000Z | app/src/main/java/com/weather/android/about.java | syy703/weather | a2cab343e4dfe10de558b68840ae1ac26144bdde | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/weather/android/about.java | syy703/weather | a2cab343e4dfe10de558b68840ae1ac26144bdde | [
"Apache-2.0"
] | null | null | null | 30.903226 | 89 | 0.664927 | 10,122 | package com.weather.android;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class about extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
Button back=(Button)findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
3e17c34ec6bf79c2657d83fa4fff0080138d784d | 3,090 | java | Java | src/main/java/zes/openworks/intra/orderManage/wish/WishListDAO.java | tenbirds/OPENWORKS-3.0 | d9ea72589854380d7ad95a1df7e5397ad6d726a6 | [
"Apache-2.0"
] | null | null | null | src/main/java/zes/openworks/intra/orderManage/wish/WishListDAO.java | tenbirds/OPENWORKS-3.0 | d9ea72589854380d7ad95a1df7e5397ad6d726a6 | [
"Apache-2.0"
] | null | null | null | src/main/java/zes/openworks/intra/orderManage/wish/WishListDAO.java | tenbirds/OPENWORKS-3.0 | d9ea72589854380d7ad95a1df7e5397ad6d726a6 | [
"Apache-2.0"
] | null | null | null | 29.711538 | 92 | 0.601942 | 10,123 | /*
* Copyright (c) 2012 ZES Inc. All rights reserved.
* This software is the confidential and proprietary information of ZES Inc.
* You shall not disclose such Confidential Information and shall use it
* only in accordance with the terms of the license agreement you entered into
* with ZES Inc. (http://www.zesinc.co.kr/)
*/
package zes.openworks.intra.orderManage.wish;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.springframework.stereotype.Repository;
import zes.base.pager.Pager;
import zes.core.lang.Validate;
import egovframework.rte.psl.dataaccess.EgovAbstractMapper;
/**
*
*
* @version 1.0
* @since openworks-1.0 프로젝트. (After JDK 1.6)
* @author (주)제스아이엔씨 기술연구소
*<pre>
*<< 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
*-------------- -------- -------------------------------
* 2014. 10. 22. 이슬버미 신규
*</pre>
* @see
*/
@Repository
@SuppressWarnings("unchecked")
public class WishListDAO extends EgovAbstractMapper{
/**
* consultList (구매/신청관리 목록)
* @param vo
* @return
*/
public Pager<WishListVO> wishList(WishListVO vo) {
//날짜 설정 없으면 디폴트 현재 날짜
if(Validate.isEmpty(vo.getDataMap().get("q_beginDate"))){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.MONTH, -1);
vo.getDataMap().put("q_beginDate",sdf.format(c2.getTime()));
vo.getDataMap().put("q_endDate", sdf.format(c1.getTime()));
}
//엑셀적용할떄만ㅍ사용함
if(!Validate.isEmpty(vo.getUserId()) && !Validate.isEmpty(vo.getGrpSeq())){
vo.getDataMap().put("q_userId", vo.getUserId());
vo.getDataMap().put("q_grpSeq", vo.getGrpSeq());
vo.getDataMap().put("q_beginDate", "");
vo.getDataMap().put("q_endDate", "");
}
List<WishListVO> dataList = list("_wishList.wishList", vo.getDataMap());
vo.setTotalNum((Integer) selectByPk("_wishList.wishCount", vo.getDataMap()));;
return new Pager<WishListVO>(dataList, vo);
}
/**
* purchsListExcel (엑셀 다운로드)
* @param vo
* @return
*/
public List<WishListVO> wishListExcel(WishListVO vo) {
vo.getDataMap().put("userId", vo.getUserId());
vo.getDataMap().put("grpSeq", vo.getGrpSeq());
return list("_wishList.wishExcelList", vo.getDataMap());
}
/**
* wishDetailList 설명
* @param vo
* @return
*/
public Pager<WishListVO> wishDetailList(WishListVO vo) {
vo.getDataMap().put("userId", vo.getUserId());
vo.getDataMap().put("grpSeq", vo.getGrpSeq());
List<WishListVO> dataList = list("_wishList.wishDetailList", vo.getDataMap());
vo.setTotalNum((Integer) selectByPk("_wishList.wishDetailCount", vo.getDataMap()));;
return new Pager<WishListVO>(dataList, vo);
}
}
|
3e17c3c9e25242114bd6198a73b84e65385beec2 | 1,435 | java | Java | python/src/com/jetbrains/python/refactoring/surround/PyExpressionSurroundDescriptor.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | python/src/com/jetbrains/python/refactoring/surround/PyExpressionSurroundDescriptor.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2022-02-19T09:45:05.000Z | 2022-02-27T20:32:55.000Z | python/src/com/jetbrains/python/refactoring/surround/PyExpressionSurroundDescriptor.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | 39.861111 | 140 | 0.790244 | 10,124 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.refactoring.surround;
import com.intellij.lang.surroundWith.SurroundDescriptor;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.refactoring.PyRefactoringUtil;
import com.jetbrains.python.refactoring.surround.surrounders.expressions.*;
import org.jetbrains.annotations.NotNull;
public class PyExpressionSurroundDescriptor implements SurroundDescriptor {
private static final Surrounder[] SURROUNDERS = {new PyWithParenthesesSurrounder(), new PyIfExpressionSurrounder(),
new PyWhileExpressionSurrounder(), new PyIsNoneSurrounder(), new PyIsNotNoneSurrounder(), new PyLenExpressionStatementSurrounder()};
@Override
public PsiElement @NotNull [] getElementsToSurround(PsiFile file, int startOffset, int endOffset) {
final PsiElement element = PyRefactoringUtil.findExpressionInRange(file, startOffset, endOffset);
if (!(element instanceof PyExpression)) {
return PsiElement.EMPTY_ARRAY;
}
return new PsiElement[]{element};
}
@Override
public Surrounder @NotNull [] getSurrounders() {
return SURROUNDERS;
}
@Override
public boolean isExclusive() {
return false;
}
}
|
3e17c4d66d78ff5f989733f0d3183be71ddd7f46 | 4,153 | java | Java | app/src/main/java/com/waka/workspace/smalldianping/Activity/Main/Fragment/Order/Adapter/AllOrderRecyclerViewAdapter.java | BadWaka/SmallDianPing | 644b18650d750e321a561e80413a1cb69e066284 | [
"Apache-2.0"
] | 3 | 2015-12-21T09:30:28.000Z | 2015-12-21T09:30:31.000Z | app/src/main/java/com/waka/workspace/smalldianping/Activity/Main/Fragment/Order/Adapter/AllOrderRecyclerViewAdapter.java | BadWaka/SmallDianPing | 644b18650d750e321a561e80413a1cb69e066284 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/waka/workspace/smalldianping/Activity/Main/Fragment/Order/Adapter/AllOrderRecyclerViewAdapter.java | BadWaka/SmallDianPing | 644b18650d750e321a561e80413a1cb69e066284 | [
"Apache-2.0"
] | null | null | null | 37.414414 | 166 | 0.691307 | 10,125 | package com.waka.workspace.smalldianping.Activity.Main.Fragment.Order.Adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.waka.workspace.smalldianping.Activity.Main.Fragment.Order.OrderDetailActivity;
import com.waka.workspace.smalldianping.Constant;
import com.waka.workspace.smalldianping.R;
import java.util.List;
import java.util.Map;
/**
* AllOrderRecyclerViewAdapter
* Created by waka on 2016/1/7.
*/
public class AllOrderRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<Map<String, Object>> mDatas;
/**
* 构造方法
*
* @param context
* @param datas
*/
public AllOrderRecyclerViewAdapter(Context context, List<Map<String, Object>> datas) {
mContext = context;
mDatas = datas;
}
/**
* 创建ViewHolder,初始化View
*
* @param parent
* @param viewType
* @return
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder viewHolder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.recyclerview_item_food_order_in_fragment_all_order, parent, false));
return viewHolder;
}
/**
* 绑定ViewHolder,初始化数据
*
* @param holder
* @param position
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((MyViewHolder) holder).orderId = (String) mDatas.get(position).get("orderId");
((MyViewHolder) holder).tvOrderTitle.setText((String) mDatas.get(position).get("tvOrderTitle"));
((MyViewHolder) holder).tvOrderStatus.setText((String) mDatas.get(position).get("tvOrderStatus"));
// ((MyViewHolder) holder).imgOrderIcon.setBackgroundResource((Integer) mDatas.get(position).get("imgOrderIcon"));
//TODO 将int型改为bitmap
((MyViewHolder) holder).imgOrderIcon.setBackground(new BitmapDrawable((Bitmap) mDatas.get(position).get("imgOrderIcon")));
((MyViewHolder) holder).tvCreateOrderTime.setText((String) mDatas.get(position).get("tvCreateOrderTime"));
((MyViewHolder) holder).tvOrderPrice.setText((String) mDatas.get(position).get("tvOrderPrice"));
}
@Override
public int getItemCount() {
return mDatas.size();
}
/**
* 自定义ViewHolder
*/
protected class MyViewHolder extends RecyclerView.ViewHolder {
protected String orderId;
protected CardView cvFoodOrder;
protected ImageView imgOrderType, imgOrderIcon;
protected TextView tvOrderTitle, tvOrderStatus, tvCreateOrderTime, tvOrderPrice;
public MyViewHolder(View itemView) {
super(itemView);
orderId = "";
cvFoodOrder = (CardView) itemView.findViewById(R.id.cvFoodOrder);
imgOrderType = (ImageView) itemView.findViewById(R.id.imgOrderType);
imgOrderIcon = (ImageView) itemView.findViewById(R.id.imgOrderIcon);
tvOrderTitle = (TextView) itemView.findViewById(R.id.tvOrderTitle);
tvOrderStatus = (TextView) itemView.findViewById(R.id.tvOrderStatus);
tvCreateOrderTime = (TextView) itemView.findViewById(R.id.tvCreateOrderTime);
tvOrderPrice = (TextView) itemView.findViewById(R.id.tvOrderPrice);
cvFoodOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, OrderDetailActivity.class);
intent.putExtra("orderId", orderId);
((Activity) mContext).startActivityForResult(intent, Constant.ORDER_DETAIL_ACTIVITY_REQUEST_CODE);
}
});
}
}
}
|
3e17c4defe8a01eadb9bf166e67831d0851fd3de | 2,118 | java | Java | configurable-datasource/src/main/java/org/fxapps/datasource/DataSourceLoader.java | jesuino/quarkus-examples | 5f2fcaff628ffcf564d19def7ce972278352e37c | [
"Apache-2.0"
] | 7 | 2019-03-28T23:31:26.000Z | 2021-09-17T13:00:14.000Z | configurable-datasource/src/main/java/org/fxapps/datasource/DataSourceLoader.java | jesuino/quarkus-examples | 5f2fcaff628ffcf564d19def7ce972278352e37c | [
"Apache-2.0"
] | null | null | null | configurable-datasource/src/main/java/org/fxapps/datasource/DataSourceLoader.java | jesuino/quarkus-examples | 5f2fcaff628ffcf564d19def7ce972278352e37c | [
"Apache-2.0"
] | 3 | 2020-05-12T14:22:04.000Z | 2021-01-07T22:10:33.000Z | 33.09375 | 88 | 0.714825 | 10,126 | package org.fxapps.datasource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.StreamSupport;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.sql.DataSource;
import io.agroal.api.AgroalDataSource;
import io.agroal.api.configuration.supplier.AgroalPropertiesReader;
import io.quarkus.runtime.StartupEvent;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@ApplicationScoped
public class DataSourceLoader {
private static final String DATASOURCES = "datasources";
private static final String DATASOURCE = "datasource";
private static final String PREFIX_TEMPLATE = DATASOURCE + ".%s.";
@Inject
Config config;
@ConfigProperty(name = DATASOURCES, defaultValue = "")
Optional<List<String>> datasourcesProp;
Map<String, DataSource> registeredDataSources;
void load(@Observes StartupEvent startup) throws SQLException {
var allProps = new HashMap<String, String>();
var datasources = datasourcesProp.orElse(List.of());
registeredDataSources = new HashMap<>();
StreamSupport.stream(config.getPropertyNames().spliterator(), false)
.filter(p -> p.startsWith(DATASOURCE))
.forEach(k -> allProps.put(k, config.getValue(k, String.class)));
for (String ds : datasources) {
var prefix = PREFIX_TEMPLATE.formatted(ds, AgroalPropertiesReader.JDBC_URL);
var agroalProps = new AgroalPropertiesReader(prefix);
agroalProps.readProperties(allProps);
registeredDataSources.put(ds, AgroalDataSource.from(agroalProps.get()));
}
}
public Optional<DataSource> getDataSource(String name) {
return Optional.ofNullable(registeredDataSources.get(name));
}
public Set<String> datasources() {
return registeredDataSources.keySet();
}
} |
3e17c59da78f20276bd3eb79ee0022afbaeef98d | 1,991 | java | Java | hydrograph.ui/hydrograph.ui.engine/src/main/java/hydrograph/engine/jaxb/ojdbcupdate/TypeJdbcupdateRecord.java | oleksiy/Hydrograph | 52836a0b7cecb84079a3edadfdd4ac7497eb2fde | [
"Apache-2.0"
] | 129 | 2017-03-11T05:18:14.000Z | 2018-10-31T21:50:58.000Z | hydrograph.ui/hydrograph.ui.engine/src/main/java/hydrograph/engine/jaxb/ojdbcupdate/TypeJdbcupdateRecord.java | oleksiy/Hydrograph | 52836a0b7cecb84079a3edadfdd4ac7497eb2fde | [
"Apache-2.0"
] | 58 | 2017-03-14T19:55:48.000Z | 2018-09-19T15:48:31.000Z | hydrograph.ui/hydrograph.ui.engine/src/main/java/hydrograph/engine/jaxb/ojdbcupdate/TypeJdbcupdateRecord.java | oleksiy/Hydrograph | 52836a0b7cecb84079a3edadfdd4ac7497eb2fde | [
"Apache-2.0"
] | 116 | 2017-03-11T05:18:16.000Z | 2018-10-27T16:48:19.000Z | 38.288462 | 131 | 0.730286 | 10,127 |
/*
* Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.engine.jaxb.ojdbcupdate;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import hydrograph.engine.jaxb.commontypes.TypeBaseRecord;
/**
* <p>Java class for type-jdbcupdate-record complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="type-jdbcupdate-record">
* <complexContent>
* <restriction base="{hydrograph/engine/jaxb/commontypes}type-base-record">
* <choice maxOccurs="unbounded">
* <element name="field" type="{hydrograph/engine/jaxb/ojdbcupdate}type-jdbcupdate-field"/>
* <element name="record" type="{hydrograph/engine/jaxb/ojdbcupdate}type-jdbcupdate-record"/>
* <element name="includeExternalSchema" type="{hydrograph/engine/jaxb/commontypes}type-external-schema" minOccurs="0"/>
* </choice>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "type-jdbcupdate-record", namespace = "hydrograph/engine/jaxb/ojdbcupdate")
public class TypeJdbcupdateRecord
extends TypeBaseRecord
{
}
|
3e17c64d7a6fab25ad97747ea44eb96173638311 | 6,272 | java | Java | lab10/lab10_solutionOfC.java | Uncle-Road/CS203_Dsaa | f6ffa4993ea5d1505d0b8d909b49b9161b576673 | [
"MIT"
] | null | null | null | lab10/lab10_solutionOfC.java | Uncle-Road/CS203_Dsaa | f6ffa4993ea5d1505d0b8d909b49b9161b576673 | [
"MIT"
] | null | null | null | lab10/lab10_solutionOfC.java | Uncle-Road/CS203_Dsaa | f6ffa4993ea5d1505d0b8d909b49b9161b576673 | [
"MIT"
] | null | null | null | 31.20398 | 106 | 0.388712 | 10,128 | import java.io.*;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.ArrayList;
public class lab10_solutionOfC{
public static void main(String[] args)throws IOException {
Reader in = new Reader();
PrintWriter out=new PrintWriter(System.out);
double[] power = new double[20];
power[0] = 1;
for (int i=1;i<20;i++){
power[i] = 2*power[i-1];
}
int n = in.nextInt();
int m = in.nextInt();
int[][] height = new int[n+1][m+1];
double[][] speed = new double[n+1][m+1];
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
height[i][j] = in.nextInt();
}
}
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
if (height[i][j]<=height[1][1]){
speed[i][j] = power[height[1][1]-height[i][j]];
}else {
speed[i][j] = 1/power[height[i][j]-height[1][1]];
}
}
}
int[] vis = new int[n*m];
double[] dis = new double[n*m];
ArrayList<Node>[] graph = new ArrayList[n*m];
for (int i=0;i<n*m;i++){
graph[i] = new ArrayList<Node>();
}
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if (i>0){
graph[i*m+j].add(new Node((i-1)*m+j,1/speed[i+1][j+1]));
}
if (j>0){
graph[i*m+j].add(new Node(i*m+j-1,1/speed[i+1][j+1]));
}
if (i<n-1){
graph[i*m+j].add(new Node((i+1)*m+j,1/speed[i+1][j+1]));
}
if (j<m-1){
graph[i*m+j].add(new Node(i*m+j+1,1/speed[i+1][j+1]));
}
}
}
dijkstra(0,n*m,vis,dis,graph);
System.out.printf("%.2f",dis[(n-1)*m+m-1]);
out.close();
}
static void dijkstra(int start,int n,int[] vis,double[] dis,ArrayList<Node>[] graph){
for (int i=0;i<n;i++){
vis[i] = 0;
dis[i] = Double.MAX_VALUE;
}
dis[start] = 0;
PriorityQueue<Node> queue = new PriorityQueue<Node>(Comparator.comparingDouble(it -> it.weight));
queue.add(new Node(start,0));
Node cur = null;
while(!queue.isEmpty()){
cur = queue.peek();
queue.poll();
if (vis[cur.id]==1)
continue;
vis[cur.id] = 1;
for (int i=0;i<graph[cur.id].size();i++){
int j = graph[cur.id].get(i).id;
double k = graph[cur.id].get(i).weight;
if (cur.weight+k<dis[j]&&vis[j]==0){
dis[j] = cur.weight+k;
queue.add(new Node(j,dis[j]));
}
}
}
}
static class Node{
int id;
double weight;
Node(int id,double weight){
this.id = id;
this.weight = weight;
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
|
3e17c69ccb3cea000363acc8f7bbfdefe91ef398 | 2,224 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/VisionStuff/visionsub.java | Cl0ck21/CrowForce2021-2022 | 64eb60a9ceedcf5774c9a30d9ab1c5305e98a0fd | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/VisionStuff/visionsub.java | Cl0ck21/CrowForce2021-2022 | 64eb60a9ceedcf5774c9a30d9ab1c5305e98a0fd | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/VisionStuff/visionsub.java | Cl0ck21/CrowForce2021-2022 | 64eb60a9ceedcf5774c9a30d9ab1c5305e98a0fd | [
"MIT"
] | null | null | null | 24.43956 | 91 | 0.579586 | 10,129 | package org.firstinspires.ftc.teamcode.VisionStuff;
import com.SCHSRobotics.HAL9001.system.robot.Camera;
import com.SCHSRobotics.HAL9001.system.robot.HALPipeline;
import com.SCHSRobotics.HAL9001.system.robot.Robot;
import com.SCHSRobotics.HAL9001.system.robot.VisionSubSystem;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
public class visionsub extends VisionSubSystem {
private Pipeline myPipeline = new Pipeline();
public visionsub(Robot robot) {
super(robot);
}
/**
* Gets all the HAL pipelines contained within this subsystem.
*
* @return All the HAL pipelines contained within this subsystem.
*/
@Override
protected HALPipeline[] getPipelines() {
return new HALPipeline[] {new Pipeline()};
}
/**
* A method containing the code that the subsystem runs when being initialized.
*/
@Override
public void init() {
}
/**
* A method that contains code that runs in a loop on init.
*/
@Override
public void init_loop() {
}
/**
* A method containing the code that the subsystem runs when being start.
*/
@Override
public void start() {
}
/**
* A method containing the code that the subsystem runs every loop in a teleop program.
*/
@Override
public void handle() {
}
/**
* A method containing the code that the subsystem runs when the program is stopped.
*/
@Override
public void stop() {
}
@Camera(id="webcam")
public static class Pipeline extends HALPipeline {
@Override
public Mat processFrame(Mat input) {
Imgproc.rectangle(
input,
new Point(
input.cols() / 4,
input.rows() / 4),
new Point(
input.cols() * (3f / 4f),
input.rows() * (3f / 4f)),
new Scalar(0, 255, 0), 4);
return input;
}
@Override
public boolean useViewport() {
return true;
}
}
}
|
3e17c78532001f02d5eff1d5850babb3b13feb29 | 2,568 | java | Java | src/main/java/com/github/sladecek/maze/jmaze/print3d/output/OpenScadComposer.java | sladecek/jmaze | 80e7dd5a28d5f8b91548da4118c534d95545fcff | [
"Apache-2.0"
] | 1 | 2016-02-28T16:04:38.000Z | 2016-02-28T16:04:38.000Z | src/main/java/com/github/sladecek/maze/jmaze/print3d/output/OpenScadComposer.java | sladecek/jmaze | 80e7dd5a28d5f8b91548da4118c534d95545fcff | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/sladecek/maze/jmaze/print3d/output/OpenScadComposer.java | sladecek/jmaze | 80e7dd5a28d5f8b91548da4118c534d95545fcff | [
"Apache-2.0"
] | null | null | null | 26.474227 | 80 | 0.547118 | 10,130 | package com.github.sladecek.maze.jmaze.print3d.output;
//REV1
import com.github.sladecek.maze.jmaze.geometry.Point3D;
import com.github.sladecek.maze.jmaze.print.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Locale;
/*
* Compose content of Open Scad file.
*/
final class OpenScadComposer implements java.lang.AutoCloseable {
public OpenScadComposer(final OutputStream stream) throws IOException {
this.stream = stream;
out = new OutputStreamWriter(stream, "UTF8");
}
public static String formatColor(final Color color) {
final double r = 255.0;
return String.format(Locale.US, "[%.2f, %.2f, %.2f]",
color.getR() / r, color.getG() / r, color.getB() / r);
}
public void close() throws IOException {
out.close();
stream.close();
}
public void beginUnion() throws IOException {
out.write("union() {\n");
}
public void closeUnion() throws IOException {
out.write("}\n");
}
private void printPoint(final Point3D p0) throws IOException {
out.write(" [ " + p0.getX() + "," + p0.getY() + "," + p0.getZ() + "] ");
}
/**
* Print polyhedron consisting of 8 points. The points must be ordered by x
* (most important), then y, then z.
*/
public void printPolyhedron(
final ArrayList<Point3D> points,
final ArrayList<ArrayList<Integer>> faces)
throws IOException {
out.write("polyhedron (points =[");
boolean comma = false;
for (Point3D p : points) {
if (comma) {
out.write(", \n");
}
printPoint(p);
comma = true;
}
out.write("\n], \n");
out.write("faces = [ ");
comma = false;
for (ArrayList<Integer> f : faces) {
if (comma) {
out.write(", \n");
}
printFace(f);
comma = true;
}
out.write("\n ] \n");
out.write("); \n");
}
private void printFace(ArrayList<Integer> f) throws IOException {
out.write("[ ");
boolean comma = false;
for (Integer i : f) {
if (comma) {
out.write(", ");
}
out.write(String.format("%d", i));
comma = true;
}
out.write("] ");
}
private final OutputStream stream;
private Writer out;
}
|
3e17c7b28849e29e7c390d4febd85bdcb31c079b | 574 | java | Java | CristianPintoLuft/topic0/exercise2/topic0/AbstractFactoryPatternDemo.java | justomiguel/java-bootcamp-2016 | e84269b40bb46e8d10149256ec0ead2e9a933a93 | [
"Apache-2.0"
] | 1 | 2016-07-11T20:48:03.000Z | 2016-07-11T20:48:03.000Z | CristianPintoLuft/topic0/exercise2/topic0/AbstractFactoryPatternDemo.java | justomiguel/java-bootcamp-2016 | e84269b40bb46e8d10149256ec0ead2e9a933a93 | [
"Apache-2.0"
] | 33 | 2016-02-24T14:38:21.000Z | 2016-03-11T01:27:24.000Z | CristianPintoLuft/topic0/exercise2/topic0/AbstractFactoryPatternDemo.java | justomiguel/java-bootcamp-2016 | e84269b40bb46e8d10149256ec0ead2e9a933a93 | [
"Apache-2.0"
] | 3 | 2016-02-23T11:06:53.000Z | 2016-06-02T00:54:13.000Z | 30.210526 | 96 | 0.818815 | 10,131 | package topic0;
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
AbstractFactory sqlConnectorFactory = FactoryProducer.getFactory("SQLCONNECTORFACTORY");
SQLConnector mySQLConnector = sqlConnectorFactory.getSQLConnector("MYSQLCONNECTOR");
SQLConnector postgreSQLConnector = sqlConnectorFactory.getSQLConnector("POSTGRESQLCONNECTOR");
SQLConnector sqlServerConnector = sqlConnectorFactory.getSQLConnector("SQLSERVERCONNECTOR");
mySQLConnector.connect();
postgreSQLConnector.connect();
sqlServerConnector.connect();
}
}
|
3e17c7bea8356a14371538a9659f4179b383e503 | 231 | java | Java | test/asm/negInt.java | Azegor/mjc | 8b7eaca7e2079378d99a2a6fc7f6076976922dab | [
"MIT"
] | 3 | 2019-08-09T00:57:22.000Z | 2020-06-18T23:03:05.000Z | test/asm/negInt.java | Azegor/mjc | 8b7eaca7e2079378d99a2a6fc7f6076976922dab | [
"MIT"
] | null | null | null | test/asm/negInt.java | Azegor/mjc | 8b7eaca7e2079378d99a2a6fc7f6076976922dab | [
"MIT"
] | null | null | null | 15.4 | 42 | 0.484848 | 10,132 | class Foobar {
public static void main(String[] args) {
int a = 1 + (-2);
int b = 1 - 2;
if (a == b) {
System.out.println(1);
} else {
System.out.println(a);
System.out.println(b);
}
}
}
|
3e17c8f0e1c5b8acab4bd44460a4434d3464367a | 1,334 | java | Java | marineford-domain/src/main/java/one/piece/marineford/domain/User.java | evilc2012/Marineford | adc90a33438429b0ee07f6487c37f29b32a37237 | [
"Apache-2.0"
] | null | null | null | marineford-domain/src/main/java/one/piece/marineford/domain/User.java | evilc2012/Marineford | adc90a33438429b0ee07f6487c37f29b32a37237 | [
"Apache-2.0"
] | null | null | null | marineford-domain/src/main/java/one/piece/marineford/domain/User.java | evilc2012/Marineford | adc90a33438429b0ee07f6487c37f29b32a37237 | [
"Apache-2.0"
] | null | null | null | 20.523077 | 61 | 0.638681 | 10,133 | package one.piece.marineford.domain;
import one.piece.marineford.annotation.dao.springjdbc.Column;
import one.piece.marineford.annotation.dao.springjdbc.Id;
import one.piece.marineford.annotation.dao.springjdbc.Table;
/**
* Created by Administrator on 2016/5/4.
*/
@Table(name = "sys_user")
public class User extends BaseBueinessDomain {
private int id;
private String account;
private String password;
private String nickname;
private String realname;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "account")
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "nickname")
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Column(name = "realname")
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
}
|
3e17c92c8d34e61392226955a303f7a4f1bd5d89 | 25,894 | java | Java | Tema 13 - XUI Views/Ejemplo/B4J/Objects/src/b4j/example/b4xformatter.java | Lamashino/Teaching-B4J | 99862588df4c97e0aad6a8a97b1b2cf5202bd165 | [
"CC-BY-4.0"
] | 2 | 2021-03-30T20:21:58.000Z | 2021-07-07T08:41:58.000Z | Tema 13 - XUI Views/Ejemplo/B4J/Objects/src/b4j/example/b4xformatter.java | Lamashino/Teaching-B4J | 99862588df4c97e0aad6a8a97b1b2cf5202bd165 | [
"CC-BY-4.0"
] | null | null | null | Tema 13 - XUI Views/Ejemplo/B4J/Objects/src/b4j/example/b4xformatter.java | Lamashino/Teaching-B4J | 99862588df4c97e0aad6a8a97b1b2cf5202bd165 | [
"CC-BY-4.0"
] | null | null | null | 48.94896 | 370 | 0.765621 | 10,134 | package b4j.example;
import anywheresoftware.b4a.debug.*;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.B4AClass;
public class b4xformatter extends B4AClass.ImplB4AClass implements BA.SubDelegator{
public static java.util.HashMap<String, java.lang.reflect.Method> htSubs;
private void innerInitialize(BA _ba) throws Exception {
if (ba == null) {
ba = new anywheresoftware.b4a.shell.ShellBA("b4j.example", "b4j.example.b4xformatter", this);
if (htSubs == null) {
ba.loadHtSubs(this.getClass());
htSubs = ba.htSubs;
}
ba.htSubs = htSubs;
}
if (BA.isShellModeRuntimeCheck(ba))
this.getClass().getMethod("_class_globals", b4j.example.b4xformatter.class).invoke(this, new Object[] {null});
else
ba.raiseEvent2(null, true, "class_globals", false);
}
public void innerInitializeHelper(anywheresoftware.b4a.BA _ba) throws Exception{
innerInitialize(_ba);
}
public Object callSub(String sub, Object sender, Object[] args) throws Exception {
return BA.SubDelegator.SubNotFound;
}
public static class _b4xformatdata{
public boolean IsInitialized;
public String Prefix;
public String Postfix;
public int MinimumIntegers;
public int MinimumFractions;
public int MaximumFractions;
public String GroupingCharacter;
public String DecimalPoint;
public int TextColor;
public anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont FormatFont;
public double RangeStart;
public double RangeEnd;
public boolean RemoveMinusSign;
public String IntegerPaddingChar;
public String FractionPaddingChar;
public void Initialize() {
IsInitialized = true;
Prefix = "";
Postfix = "";
MinimumIntegers = 0;
MinimumFractions = 0;
MaximumFractions = 0;
GroupingCharacter = "";
DecimalPoint = "";
TextColor = 0;
FormatFont = new anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont();
RangeStart = 0;
RangeEnd = 0;
RemoveMinusSign = false;
IntegerPaddingChar = "";
FractionPaddingChar = "";
}
@Override
public String toString() {
return BA.TypeToString(this, false);
}}
public anywheresoftware.b4a.keywords.Common __c = null;
public anywheresoftware.b4a.objects.collections.List _formats = null;
public int _max_value = 0;
public int _min_value = 0;
public anywheresoftware.b4a.objects.B4XViewWrapper.XUI _xui = null;
public b4j.example.dateutils _dateutils = null;
public b4j.example.cssutils _cssutils = null;
public b4j.example.main _main = null;
public b4j.example.b4xpages _b4xpages = null;
public b4j.example.b4xcollections _b4xcollections = null;
public b4j.example.xuiviewsutils _xuiviewsutils = null;
public b4j.example.b4xformatter._b4xformatdata _getdefaultformat(b4j.example.b4xformatter __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "getdefaultformat", true))
{return ((b4j.example.b4xformatter._b4xformatdata) Debug.delegate(ba, "getdefaultformat", null));}
RDebugUtils.currentLine=26017792;
//BA.debugLineNum = 26017792;BA.debugLine="Public Sub GetDefaultFormat As B4XFormatData";
RDebugUtils.currentLine=26017793;
//BA.debugLineNum = 26017793;BA.debugLine="Return formats.Get(0)";
if (true) return (b4j.example.b4xformatter._b4xformatdata)(__ref._formats /*anywheresoftware.b4a.objects.collections.List*/ .Get((int) (0)));
RDebugUtils.currentLine=26017794;
//BA.debugLineNum = 26017794;BA.debugLine="End Sub";
return null;
}
public String _format(b4j.example.b4xformatter __ref,double _number) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "format", true))
{return ((String) Debug.delegate(ba, "format", new Object[] {_number}));}
b4j.example.b4xformatter._b4xformatdata _data = null;
anywheresoftware.b4a.keywords.StringBuilderWrapper _sb = null;
int _numberstartindex = 0;
double _factor = 0;
int _whole = 0;
double _frac = 0;
int _g = 0;
int _fracstartindex = 0;
int _lastzerocount = 0;
int _multipler = 0;
int _w = 0;
RDebugUtils.currentLine=26148864;
//BA.debugLineNum = 26148864;BA.debugLine="Public Sub Format (Number As Double) As String";
RDebugUtils.currentLine=26148865;
//BA.debugLineNum = 26148865;BA.debugLine="If Number < MIN_VALUE Or Number > MAX_VALUE Then";
if (_number<__ref._min_value /*int*/ || _number>__ref._max_value /*int*/ ) {
if (true) return "OVERFLOW";};
RDebugUtils.currentLine=26148866;
//BA.debugLineNum = 26148866;BA.debugLine="Dim data As B4XFormatData = GetFormatData (Number";
_data = __ref._getformatdata /*b4j.example.b4xformatter._b4xformatdata*/ (null,_number);
RDebugUtils.currentLine=26148867;
//BA.debugLineNum = 26148867;BA.debugLine="Dim sb As StringBuilder";
_sb = new anywheresoftware.b4a.keywords.StringBuilderWrapper();
RDebugUtils.currentLine=26148868;
//BA.debugLineNum = 26148868;BA.debugLine="sb.Initialize";
_sb.Initialize();
RDebugUtils.currentLine=26148869;
//BA.debugLineNum = 26148869;BA.debugLine="sb.Append(data.Prefix)";
_sb.Append(_data.Prefix /*String*/ );
RDebugUtils.currentLine=26148870;
//BA.debugLineNum = 26148870;BA.debugLine="Dim NumberStartIndex As Int = sb.Length";
_numberstartindex = _sb.getLength();
RDebugUtils.currentLine=26148871;
//BA.debugLineNum = 26148871;BA.debugLine="Dim factor As Double = Power(10, -data.MaximumFra";
_factor = __c.Power(10,-_data.MaximumFractions /*int*/ -1)*5;
RDebugUtils.currentLine=26148872;
//BA.debugLineNum = 26148872;BA.debugLine="If Number < -factor And data.RemoveMinusSign = Fa";
if (_number<-_factor && _data.RemoveMinusSign /*boolean*/ ==__c.False) {
RDebugUtils.currentLine=26148873;
//BA.debugLineNum = 26148873;BA.debugLine="sb.Append(\"-\")";
_sb.Append("-");
RDebugUtils.currentLine=26148874;
//BA.debugLineNum = 26148874;BA.debugLine="NumberStartIndex = NumberStartIndex + 1";
_numberstartindex = (int) (_numberstartindex+1);
};
RDebugUtils.currentLine=26148876;
//BA.debugLineNum = 26148876;BA.debugLine="Number = Abs(Number) + factor";
_number = __c.Abs(_number)+_factor;
RDebugUtils.currentLine=26148877;
//BA.debugLineNum = 26148877;BA.debugLine="Dim whole As Int = Number";
_whole = (int) (_number);
RDebugUtils.currentLine=26148878;
//BA.debugLineNum = 26148878;BA.debugLine="Dim frac As Double = Number - whole";
_frac = _number-_whole;
RDebugUtils.currentLine=26148879;
//BA.debugLineNum = 26148879;BA.debugLine="Dim g As Int";
_g = 0;
RDebugUtils.currentLine=26148880;
//BA.debugLineNum = 26148880;BA.debugLine="Do While whole > 0";
while (_whole>0) {
RDebugUtils.currentLine=26148881;
//BA.debugLineNum = 26148881;BA.debugLine="If g > 0 And g Mod 3 = 0 And data.GroupingCharac";
if (_g>0 && _g%3==0 && _data.GroupingCharacter /*String*/ .length()>0) {
RDebugUtils.currentLine=26148882;
//BA.debugLineNum = 26148882;BA.debugLine="sb.Insert(NumberStartIndex, data.GroupingCharac";
_sb.Insert(_numberstartindex,_data.GroupingCharacter /*String*/ );
};
RDebugUtils.currentLine=26148884;
//BA.debugLineNum = 26148884;BA.debugLine="g = g + 1";
_g = (int) (_g+1);
RDebugUtils.currentLine=26148885;
//BA.debugLineNum = 26148885;BA.debugLine="sb.Insert(NumberStartIndex, whole Mod 10)";
_sb.Insert(_numberstartindex,BA.NumberToString(_whole%10));
RDebugUtils.currentLine=26148886;
//BA.debugLineNum = 26148886;BA.debugLine="whole = whole / 10";
_whole = (int) (_whole/(double)10);
}
;
RDebugUtils.currentLine=26148888;
//BA.debugLineNum = 26148888;BA.debugLine="Do While sb.Length - NumberStartIndex < data.Mini";
while (_sb.getLength()-_numberstartindex<_data.MinimumIntegers /*int*/ ) {
RDebugUtils.currentLine=26148889;
//BA.debugLineNum = 26148889;BA.debugLine="sb.Insert(NumberStartIndex, data.IntegerPaddingC";
_sb.Insert(_numberstartindex,_data.IntegerPaddingChar /*String*/ );
}
;
RDebugUtils.currentLine=26148891;
//BA.debugLineNum = 26148891;BA.debugLine="If data.MaximumFractions > 0 And (data.MinimumFra";
if (_data.MaximumFractions /*int*/ >0 && (_data.MinimumFractions /*int*/ >0 || _frac>0)) {
RDebugUtils.currentLine=26148892;
//BA.debugLineNum = 26148892;BA.debugLine="Dim FracStartIndex As Int = sb.Length";
_fracstartindex = _sb.getLength();
RDebugUtils.currentLine=26148893;
//BA.debugLineNum = 26148893;BA.debugLine="Dim LastZeroCount As Int";
_lastzerocount = 0;
RDebugUtils.currentLine=26148894;
//BA.debugLineNum = 26148894;BA.debugLine="Dim Multipler As Int = 10";
_multipler = (int) (10);
RDebugUtils.currentLine=26148895;
//BA.debugLineNum = 26148895;BA.debugLine="Do While frac >= 2 * factor And sb.Length - Frac";
while (_frac>=2*_factor && _sb.getLength()-_fracstartindex<_data.MaximumFractions /*int*/ ) {
RDebugUtils.currentLine=26148896;
//BA.debugLineNum = 26148896;BA.debugLine="Dim w As Int = (frac * Multipler)";
_w = (int) ((_frac*_multipler));
RDebugUtils.currentLine=26148897;
//BA.debugLineNum = 26148897;BA.debugLine="w = w Mod 10";
_w = (int) (_w%10);
RDebugUtils.currentLine=26148898;
//BA.debugLineNum = 26148898;BA.debugLine="If w = 0 Then LastZeroCount = LastZeroCount + 1";
if (_w==0) {
_lastzerocount = (int) (_lastzerocount+1);}
else {
_lastzerocount = (int) (0);};
RDebugUtils.currentLine=26148899;
//BA.debugLineNum = 26148899;BA.debugLine="sb.Append(w)";
_sb.Append(BA.NumberToString(_w));
RDebugUtils.currentLine=26148900;
//BA.debugLineNum = 26148900;BA.debugLine="Multipler = Multipler * 10";
_multipler = (int) (_multipler*10);
}
;
RDebugUtils.currentLine=26148902;
//BA.debugLineNum = 26148902;BA.debugLine="If data.FractionPaddingChar <> \"0\" And LastZeroC";
if ((_data.FractionPaddingChar /*String*/ ).equals("0") == false && _lastzerocount>0) {
RDebugUtils.currentLine=26148903;
//BA.debugLineNum = 26148903;BA.debugLine="sb.Remove(sb.Length - LastZeroCount, sb.Length)";
_sb.Remove((int) (_sb.getLength()-_lastzerocount),_sb.getLength());
RDebugUtils.currentLine=26148904;
//BA.debugLineNum = 26148904;BA.debugLine="LastZeroCount = 0";
_lastzerocount = (int) (0);
};
RDebugUtils.currentLine=26148906;
//BA.debugLineNum = 26148906;BA.debugLine="Do While sb.Length - FracStartIndex < data.Minim";
while (_sb.getLength()-_fracstartindex<_data.MinimumFractions /*int*/ ) {
RDebugUtils.currentLine=26148907;
//BA.debugLineNum = 26148907;BA.debugLine="sb.Append(data.FractionPaddingChar)";
_sb.Append(_data.FractionPaddingChar /*String*/ );
RDebugUtils.currentLine=26148908;
//BA.debugLineNum = 26148908;BA.debugLine="LastZeroCount = 0";
_lastzerocount = (int) (0);
}
;
RDebugUtils.currentLine=26148910;
//BA.debugLineNum = 26148910;BA.debugLine="LastZeroCount = Min(LastZeroCount, sb.Length - F";
_lastzerocount = (int) (__c.Min(_lastzerocount,_sb.getLength()-_fracstartindex-_data.MinimumFractions /*int*/ ));
RDebugUtils.currentLine=26148911;
//BA.debugLineNum = 26148911;BA.debugLine="If LastZeroCount > 0 Then";
if (_lastzerocount>0) {
RDebugUtils.currentLine=26148912;
//BA.debugLineNum = 26148912;BA.debugLine="sb.Remove(sb.Length - LastZeroCount, sb.Length)";
_sb.Remove((int) (_sb.getLength()-_lastzerocount),_sb.getLength());
};
RDebugUtils.currentLine=26148914;
//BA.debugLineNum = 26148914;BA.debugLine="If sb.Length > FracStartIndex Then sb.Insert(Fra";
if (_sb.getLength()>_fracstartindex) {
_sb.Insert(_fracstartindex,_data.DecimalPoint /*String*/ );};
};
RDebugUtils.currentLine=26148916;
//BA.debugLineNum = 26148916;BA.debugLine="sb.Append(data.Postfix)";
_sb.Append(_data.Postfix /*String*/ );
RDebugUtils.currentLine=26148917;
//BA.debugLineNum = 26148917;BA.debugLine="Return sb.ToString";
if (true) return _sb.ToString();
RDebugUtils.currentLine=26148918;
//BA.debugLineNum = 26148918;BA.debugLine="End Sub";
return "";
}
public String _initialize(b4j.example.b4xformatter __ref,anywheresoftware.b4a.BA _ba) throws Exception{
__ref = this;
innerInitialize(_ba);
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "initialize", true))
{return ((String) Debug.delegate(ba, "initialize", new Object[] {_ba}));}
b4j.example.b4xformatter._b4xformatdata _d = null;
RDebugUtils.currentLine=25690112;
//BA.debugLineNum = 25690112;BA.debugLine="Public Sub Initialize";
RDebugUtils.currentLine=25690113;
//BA.debugLineNum = 25690113;BA.debugLine="formats.Initialize";
__ref._formats /*anywheresoftware.b4a.objects.collections.List*/ .Initialize();
RDebugUtils.currentLine=25690114;
//BA.debugLineNum = 25690114;BA.debugLine="Dim d As B4XFormatData = CreateDefaultFormat";
_d = __ref._createdefaultformat /*b4j.example.b4xformatter._b4xformatdata*/ (null);
RDebugUtils.currentLine=25690115;
//BA.debugLineNum = 25690115;BA.debugLine="AddFormatData(d, MIN_VALUE, MAX_VALUE, True)";
__ref._addformatdata /*String*/ (null,_d,__ref._min_value /*int*/ ,__ref._max_value /*int*/ ,__c.True);
RDebugUtils.currentLine=25690116;
//BA.debugLineNum = 25690116;BA.debugLine="End Sub";
return "";
}
public String _addformatdata(b4j.example.b4xformatter __ref,b4j.example.b4xformatter._b4xformatdata _data,double _rangestart,double _rangeend,boolean _includeedges) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "addformatdata", true))
{return ((String) Debug.delegate(ba, "addformatdata", new Object[] {_data,_rangestart,_rangeend,_includeedges}));}
double _factor = 0;
RDebugUtils.currentLine=25952256;
//BA.debugLineNum = 25952256;BA.debugLine="Public Sub AddFormatData (Data As B4XFormatData, R";
RDebugUtils.currentLine=25952257;
//BA.debugLineNum = 25952257;BA.debugLine="Dim factor As Double = Power(10, -Data.MaximumFra";
_factor = __c.Power(10,-_data.MaximumFractions /*int*/ );
RDebugUtils.currentLine=25952258;
//BA.debugLineNum = 25952258;BA.debugLine="If IncludeEdges = False Then";
if (_includeedges==__c.False) {
RDebugUtils.currentLine=25952259;
//BA.debugLineNum = 25952259;BA.debugLine="RangeStart = RangeStart + factor";
_rangestart = _rangestart+_factor;
RDebugUtils.currentLine=25952260;
//BA.debugLineNum = 25952260;BA.debugLine="RangeEnd = RangeEnd - factor";
_rangeend = _rangeend-_factor;
};
RDebugUtils.currentLine=25952262;
//BA.debugLineNum = 25952262;BA.debugLine="RangeStart = RangeStart - factor / 2";
_rangestart = _rangestart-_factor/(double)2;
RDebugUtils.currentLine=25952263;
//BA.debugLineNum = 25952263;BA.debugLine="RangeEnd = RangeEnd + factor / 2";
_rangeend = _rangeend+_factor/(double)2;
RDebugUtils.currentLine=25952264;
//BA.debugLineNum = 25952264;BA.debugLine="Data.RangeStart = RangeStart";
_data.RangeStart /*double*/ = _rangestart;
RDebugUtils.currentLine=25952265;
//BA.debugLineNum = 25952265;BA.debugLine="Data.RangeEnd = RangeEnd";
_data.RangeEnd /*double*/ = _rangeend;
RDebugUtils.currentLine=25952266;
//BA.debugLineNum = 25952266;BA.debugLine="formats.Add(Data)";
__ref._formats /*anywheresoftware.b4a.objects.collections.List*/ .Add((Object)(_data));
RDebugUtils.currentLine=25952267;
//BA.debugLineNum = 25952267;BA.debugLine="End Sub";
return "";
}
public String _class_globals(b4j.example.b4xformatter __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
RDebugUtils.currentLine=25624576;
//BA.debugLineNum = 25624576;BA.debugLine="Sub Class_Globals";
RDebugUtils.currentLine=25624577;
//BA.debugLineNum = 25624577;BA.debugLine="Type B4XFormatData (Prefix As String, Postfix As";
;
RDebugUtils.currentLine=25624581;
//BA.debugLineNum = 25624581;BA.debugLine="Private formats As List";
_formats = new anywheresoftware.b4a.objects.collections.List();
RDebugUtils.currentLine=25624582;
//BA.debugLineNum = 25624582;BA.debugLine="Public Const MAX_VALUE = 0x7fffffff, MIN_VALUE =";
_max_value = (int) (0x7fffffff);
_min_value = (int) (0x80000000);
RDebugUtils.currentLine=25624583;
//BA.debugLineNum = 25624583;BA.debugLine="Private xui As XUI";
_xui = new anywheresoftware.b4a.objects.B4XViewWrapper.XUI();
RDebugUtils.currentLine=25624584;
//BA.debugLineNum = 25624584;BA.debugLine="End Sub";
return "";
}
public b4j.example.b4xformatter._b4xformatdata _copyformatdata(b4j.example.b4xformatter __ref,b4j.example.b4xformatter._b4xformatdata _data) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "copyformatdata", true))
{return ((b4j.example.b4xformatter._b4xformatdata) Debug.delegate(ba, "copyformatdata", new Object[] {_data}));}
b4j.example.b4xformatter._b4xformatdata _d = null;
RDebugUtils.currentLine=25886720;
//BA.debugLineNum = 25886720;BA.debugLine="Public Sub CopyFormatData (Data As B4XFormatData)";
RDebugUtils.currentLine=25886721;
//BA.debugLineNum = 25886721;BA.debugLine="Dim d As B4XFormatData";
_d = new b4j.example.b4xformatter._b4xformatdata();
RDebugUtils.currentLine=25886722;
//BA.debugLineNum = 25886722;BA.debugLine="d.Initialize";
_d.Initialize();
RDebugUtils.currentLine=25886723;
//BA.debugLineNum = 25886723;BA.debugLine="d.DecimalPoint = Data.DecimalPoint";
_d.DecimalPoint /*String*/ = _data.DecimalPoint /*String*/ ;
RDebugUtils.currentLine=25886724;
//BA.debugLineNum = 25886724;BA.debugLine="If Data.FormatFont.IsInitialized Then";
if (_data.FormatFont /*anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont*/ .IsInitialized()) {
RDebugUtils.currentLine=25886726;
//BA.debugLineNum = 25886726;BA.debugLine="d.FormatFont = xui.CreateFont(Data.FormatFont.To";
_d.FormatFont /*anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont*/ = __ref._xui /*anywheresoftware.b4a.objects.B4XViewWrapper.XUI*/ .CreateFont((javafx.scene.text.Font)(_data.FormatFont /*anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont*/ .ToNativeFont().getObject()),(float) (_data.FormatFont /*anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont*/ .getSize()));
};
RDebugUtils.currentLine=25886729;
//BA.debugLineNum = 25886729;BA.debugLine="d.GroupingCharacter = Data.GroupingCharacter";
_d.GroupingCharacter /*String*/ = _data.GroupingCharacter /*String*/ ;
RDebugUtils.currentLine=25886730;
//BA.debugLineNum = 25886730;BA.debugLine="d.MaximumFractions = Data.MaximumFractions";
_d.MaximumFractions /*int*/ = _data.MaximumFractions /*int*/ ;
RDebugUtils.currentLine=25886731;
//BA.debugLineNum = 25886731;BA.debugLine="d.MinimumFractions = Data.MinimumFractions";
_d.MinimumFractions /*int*/ = _data.MinimumFractions /*int*/ ;
RDebugUtils.currentLine=25886732;
//BA.debugLineNum = 25886732;BA.debugLine="d.MinimumIntegers = Data.MinimumIntegers";
_d.MinimumIntegers /*int*/ = _data.MinimumIntegers /*int*/ ;
RDebugUtils.currentLine=25886733;
//BA.debugLineNum = 25886733;BA.debugLine="d.Postfix = Data.Postfix";
_d.Postfix /*String*/ = _data.Postfix /*String*/ ;
RDebugUtils.currentLine=25886734;
//BA.debugLineNum = 25886734;BA.debugLine="d.Prefix = Data.Prefix";
_d.Prefix /*String*/ = _data.Prefix /*String*/ ;
RDebugUtils.currentLine=25886735;
//BA.debugLineNum = 25886735;BA.debugLine="d.RangeEnd = Data.RangeEnd";
_d.RangeEnd /*double*/ = _data.RangeEnd /*double*/ ;
RDebugUtils.currentLine=25886736;
//BA.debugLineNum = 25886736;BA.debugLine="d.RangeStart = Data.RangeStart";
_d.RangeStart /*double*/ = _data.RangeStart /*double*/ ;
RDebugUtils.currentLine=25886737;
//BA.debugLineNum = 25886737;BA.debugLine="d.RemoveMinusSign = Data.RemoveMinusSign";
_d.RemoveMinusSign /*boolean*/ = _data.RemoveMinusSign /*boolean*/ ;
RDebugUtils.currentLine=25886738;
//BA.debugLineNum = 25886738;BA.debugLine="d.TextColor = Data.TextColor";
_d.TextColor /*int*/ = _data.TextColor /*int*/ ;
RDebugUtils.currentLine=25886739;
//BA.debugLineNum = 25886739;BA.debugLine="d.FractionPaddingChar = Data.FractionPaddingChar";
_d.FractionPaddingChar /*String*/ = _data.FractionPaddingChar /*String*/ ;
RDebugUtils.currentLine=25886740;
//BA.debugLineNum = 25886740;BA.debugLine="d.IntegerPaddingChar = Data.IntegerPaddingChar";
_d.IntegerPaddingChar /*String*/ = _data.IntegerPaddingChar /*String*/ ;
RDebugUtils.currentLine=25886741;
//BA.debugLineNum = 25886741;BA.debugLine="Return d";
if (true) return _d;
RDebugUtils.currentLine=25886742;
//BA.debugLineNum = 25886742;BA.debugLine="End Sub";
return null;
}
public b4j.example.b4xformatter._b4xformatdata _createdefaultformat(b4j.example.b4xformatter __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "createdefaultformat", true))
{return ((b4j.example.b4xformatter._b4xformatdata) Debug.delegate(ba, "createdefaultformat", null));}
b4j.example.b4xformatter._b4xformatdata _d = null;
RDebugUtils.currentLine=25755648;
//BA.debugLineNum = 25755648;BA.debugLine="Private Sub CreateDefaultFormat As B4XFormatData";
RDebugUtils.currentLine=25755649;
//BA.debugLineNum = 25755649;BA.debugLine="Dim d As B4XFormatData";
_d = new b4j.example.b4xformatter._b4xformatdata();
RDebugUtils.currentLine=25755650;
//BA.debugLineNum = 25755650;BA.debugLine="d.Initialize";
_d.Initialize();
RDebugUtils.currentLine=25755651;
//BA.debugLineNum = 25755651;BA.debugLine="d.GroupingCharacter = \",\"";
_d.GroupingCharacter /*String*/ = ",";
RDebugUtils.currentLine=25755652;
//BA.debugLineNum = 25755652;BA.debugLine="d.DecimalPoint = \".\"";
_d.DecimalPoint /*String*/ = ".";
RDebugUtils.currentLine=25755653;
//BA.debugLineNum = 25755653;BA.debugLine="d.MaximumFractions = 3";
_d.MaximumFractions /*int*/ = (int) (3);
RDebugUtils.currentLine=25755654;
//BA.debugLineNum = 25755654;BA.debugLine="d.MinimumIntegers = 1";
_d.MinimumIntegers /*int*/ = (int) (1);
RDebugUtils.currentLine=25755655;
//BA.debugLineNum = 25755655;BA.debugLine="d.IntegerPaddingChar = \"0\"";
_d.IntegerPaddingChar /*String*/ = "0";
RDebugUtils.currentLine=25755656;
//BA.debugLineNum = 25755656;BA.debugLine="d.FractionPaddingChar = \"0\"";
_d.FractionPaddingChar /*String*/ = "0";
RDebugUtils.currentLine=25755657;
//BA.debugLineNum = 25755657;BA.debugLine="Return d";
if (true) return _d;
RDebugUtils.currentLine=25755658;
//BA.debugLineNum = 25755658;BA.debugLine="End Sub";
return null;
}
public b4j.example.b4xformatter._b4xformatdata _getformatdata(b4j.example.b4xformatter __ref,double _number) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "getformatdata", true))
{return ((b4j.example.b4xformatter._b4xformatdata) Debug.delegate(ba, "getformatdata", new Object[] {_number}));}
int _i = 0;
b4j.example.b4xformatter._b4xformatdata _d = null;
RDebugUtils.currentLine=26083328;
//BA.debugLineNum = 26083328;BA.debugLine="Public Sub GetFormatData (Number As Double) As B4X";
RDebugUtils.currentLine=26083329;
//BA.debugLineNum = 26083329;BA.debugLine="For i = formats.Size - 1 To 1 Step - 1";
{
final int step1 = -1;
final int limit1 = (int) (1);
_i = (int) (__ref._formats /*anywheresoftware.b4a.objects.collections.List*/ .getSize()-1) ;
for (;_i >= limit1 ;_i = _i + step1 ) {
RDebugUtils.currentLine=26083330;
//BA.debugLineNum = 26083330;BA.debugLine="Dim d As B4XFormatData = formats.Get(i)";
_d = (b4j.example.b4xformatter._b4xformatdata)(__ref._formats /*anywheresoftware.b4a.objects.collections.List*/ .Get(_i));
RDebugUtils.currentLine=26083331;
//BA.debugLineNum = 26083331;BA.debugLine="If Number <= d.RangeEnd And Number >= d.RangeSta";
if (_number<=_d.RangeEnd /*double*/ && _number>=_d.RangeStart /*double*/ ) {
if (true) return _d;};
}
};
RDebugUtils.currentLine=26083333;
//BA.debugLineNum = 26083333;BA.debugLine="Return formats.Get(0)";
if (true) return (b4j.example.b4xformatter._b4xformatdata)(__ref._formats /*anywheresoftware.b4a.objects.collections.List*/ .Get((int) (0)));
RDebugUtils.currentLine=26083334;
//BA.debugLineNum = 26083334;BA.debugLine="End Sub";
return null;
}
public String _formatlabel(b4j.example.b4xformatter __ref,double _number,anywheresoftware.b4a.objects.B4XViewWrapper _label) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "formatlabel", true))
{return ((String) Debug.delegate(ba, "formatlabel", new Object[] {_number,_label}));}
b4j.example.b4xformatter._b4xformatdata _data = null;
RDebugUtils.currentLine=26214400;
//BA.debugLineNum = 26214400;BA.debugLine="Public Sub FormatLabel (Number As Double, Label As";
RDebugUtils.currentLine=26214401;
//BA.debugLineNum = 26214401;BA.debugLine="Label.Text = Format(Number)";
_label.setText(__ref._format /*String*/ (null,_number));
RDebugUtils.currentLine=26214402;
//BA.debugLineNum = 26214402;BA.debugLine="Dim data As B4XFormatData = GetFormatData(Number)";
_data = __ref._getformatdata /*b4j.example.b4xformatter._b4xformatdata*/ (null,_number);
RDebugUtils.currentLine=26214403;
//BA.debugLineNum = 26214403;BA.debugLine="If data.TextColor <> 0 Then Label.TextColor = dat";
if (_data.TextColor /*int*/ !=0) {
_label.setTextColor(_data.TextColor /*int*/ );};
RDebugUtils.currentLine=26214404;
//BA.debugLineNum = 26214404;BA.debugLine="If data.FormatFont.IsInitialized Then Label.Font";
if (_data.FormatFont /*anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont*/ .IsInitialized()) {
_label.setFont(_data.FormatFont /*anywheresoftware.b4a.objects.B4XViewWrapper.B4XFont*/ );};
RDebugUtils.currentLine=26214405;
//BA.debugLineNum = 26214405;BA.debugLine="End Sub";
return "";
}
public b4j.example.b4xformatter._b4xformatdata _newformatdata(b4j.example.b4xformatter __ref) throws Exception{
__ref = this;
RDebugUtils.currentModule="b4xformatter";
if (Debug.shouldDelegate(ba, "newformatdata", true))
{return ((b4j.example.b4xformatter._b4xformatdata) Debug.delegate(ba, "newformatdata", null));}
RDebugUtils.currentLine=25821184;
//BA.debugLineNum = 25821184;BA.debugLine="Public Sub NewFormatData As B4XFormatData";
RDebugUtils.currentLine=25821185;
//BA.debugLineNum = 25821185;BA.debugLine="Return CopyFormatData(GetDefaultFormat)";
if (true) return __ref._copyformatdata /*b4j.example.b4xformatter._b4xformatdata*/ (null,__ref._getdefaultformat /*b4j.example.b4xformatter._b4xformatdata*/ (null));
RDebugUtils.currentLine=25821186;
//BA.debugLineNum = 25821186;BA.debugLine="End Sub";
return null;
}
} |
3e17ca110a3f4b4a2a93291531a8b73d4e82e52f | 908 | java | Java | cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch16/s1/GreedyActivitySelector.java | rfarhanian/cs-review | 5e958c12f7119aaf5386c7cb7d19c646e68b5ce6 | [
"MIT"
] | 247 | 2017-05-31T21:26:44.000Z | 2022-03-14T05:27:37.000Z | cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch16/s1/GreedyActivitySelector.java | codeAligned/cs-review | 2186bddc3bca6c045becd52f363268ca663dcbd7 | [
"MIT"
] | 11 | 2018-08-18T04:51:48.000Z | 2019-06-27T11:30:59.000Z | cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch16/s1/GreedyActivitySelector.java | codeAligned/cs-review | 2186bddc3bca6c045becd52f363268ca663dcbd7 | [
"MIT"
] | 77 | 2017-06-06T21:41:19.000Z | 2022-03-02T06:34:32.000Z | 30.466667 | 92 | 0.637856 | 10,135 | package com.mmnaseri.cs.clrs.ch16.s1;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author Mohammad Milad Naseri (ychag@example.com)
* @since 1.0 (7/22/15, 10:48 PM)
*/
public class GreedyActivitySelector implements ActivitySelector {
@Override
public Set<Integer> select(Activity... activities) {
final IndexedActivity[] indexedActivities = IndexedActivity.index(activities);
Arrays.sort(indexedActivities);
final Set<Integer> indices = new HashSet<>();
indices.add(indexedActivities[0].getIndex());
int current = 0;
for (int i = 1; i < indexedActivities.length; i++) {
if (indexedActivities[i].getStart() >= indexedActivities[current].getFinish()) {
indices.add(indexedActivities[i].getIndex());
current = i;
}
}
return indices;
}
}
|
3e17ca29cee609e3a4cb695c644ff53e33a77813 | 4,376 | java | Java | play-services-base-core/src/main/java/org/microg/gms/common/ForegroundServiceContext.java | matttbe/GmsCore | 17b8371b489f919d6ff87607c4a289b0af38d159 | [
"Apache-2.0"
] | 3,181 | 2015-01-09T14:33:44.000Z | 2020-11-18T15:37:37.000Z | play-services-base-core/src/main/java/org/microg/gms/common/ForegroundServiceContext.java | kitskih/GmsCore | 96cfe2bd9b1798511ea6eb31434049c08b47584a | [
"Apache-2.0"
] | 1,182 | 2015-03-16T19:40:01.000Z | 2020-11-17T15:47:18.000Z | play-services-base-core/src/main/java/org/microg/gms/common/ForegroundServiceContext.java | kitskih/GmsCore | 96cfe2bd9b1798511ea6eb31434049c08b47584a | [
"Apache-2.0"
] | 505 | 2015-01-28T01:03:02.000Z | 2020-11-18T07:18:42.000Z | 42.901961 | 143 | 0.662706 | 10,136 | package org.microg.gms.common;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;
import androidx.annotation.RequiresApi;
import org.microg.gms.base.core.R;
public class ForegroundServiceContext extends ContextWrapper {
private static final String TAG = "ForegroundService";
public static final String EXTRA_FOREGROUND = "foreground";
public ForegroundServiceContext(Context base) {
super(base);
}
@Override
public ComponentName startService(Intent service) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !isIgnoringBatteryOptimizations()) {
Log.d(TAG, "Starting in foreground mode.");
service.putExtra(EXTRA_FOREGROUND, true);
return super.startForegroundService(service);
}
return super.startService(service);
}
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isIgnoringBatteryOptimizations() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
return powerManager.isIgnoringBatteryOptimizations(getPackageName());
}
private static String getServiceName(Service service) {
String serviceName = null;
try {
ForegroundServiceInfo annotation = service.getClass().getAnnotation(ForegroundServiceInfo.class);
if (annotation != null) {
if (annotation.res() != 0) {
try {
serviceName = service.getString(annotation.res());
} catch (Exception ignored) {
}
}
if (serviceName == null) {
serviceName = annotation.value();
}
}
} catch (Exception ignored) {
}
if (serviceName == null) {
serviceName = service.getClass().getSimpleName();
}
return serviceName;
}
public static void completeForegroundService(Service service, Intent intent, String tag) {
if (intent != null && intent.getBooleanExtra(EXTRA_FOREGROUND, false) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String serviceName = getServiceName(service);
Log.d(tag, "Started " + serviceName + " in foreground mode.");
try {
Notification notification = buildForegroundNotification(service, serviceName);
service.startForeground(serviceName.hashCode(), notification);
Log.d(tag, "Notification: " + notification.toString());
} catch (Exception e) {
Log.w(tag, e);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private static Notification buildForegroundNotification(Context context, String serviceName) {
NotificationChannel channel = new NotificationChannel("foreground-service", "Foreground Service", NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
channel.setShowBadge(false);
channel.setVibrationPattern(new long[]{0});
context.getSystemService(NotificationManager.class).createNotificationChannel(channel);
String appTitle = context.getApplicationInfo().loadLabel(context.getPackageManager()).toString();
String notifyTitle = context.getString(R.string.foreground_service_notification_title);
String firstLine = context.getString(R.string.foreground_service_notification_text, serviceName);
String secondLine = context.getString(R.string.foreground_service_notification_big_text, appTitle);
Log.d(TAG, notifyTitle + " // " + firstLine + " // " + secondLine);
return new Notification.Builder(context, channel.getId())
.setOngoing(true)
.setSmallIcon(R.drawable.ic_background_notify)
.setContentTitle(notifyTitle)
.setContentText(firstLine)
.setStyle(new Notification.BigTextStyle().bigText(firstLine + "\n" + secondLine))
.build();
}
}
|
3e17ca5609ccb2843b798a824d798f0276eefcca | 3,632 | java | Java | Java/OCR PDF/src/com/muhimbi/ws/FileMergeSettings.java | DJames239/PDF-Converter-Services | c0faab95f66aee15f199b0af00b85175e701ca27 | [
"Apache-2.0"
] | 3 | 2019-03-29T20:35:26.000Z | 2021-12-14T12:35:00.000Z | Java/OCR PDF/src/com/muhimbi/ws/FileMergeSettings.java | DJames239/PDF-Converter-Services | c0faab95f66aee15f199b0af00b85175e701ca27 | [
"Apache-2.0"
] | 1 | 2020-03-09T14:34:44.000Z | 2020-03-09T14:34:44.000Z | Java/OCR PDF/src/com/muhimbi/ws/FileMergeSettings.java | DJames239/PDF-Converter-Services | c0faab95f66aee15f199b0af00b85175e701ca27 | [
"Apache-2.0"
] | 6 | 2019-12-15T09:18:05.000Z | 2022-01-28T18:12:54.000Z | 29.290323 | 185 | 0.646476 | 10,137 |
package com.muhimbi.ws;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for FileMergeSettings complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="FileMergeSettings">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TopLevelBookmark" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="MergeMode" type="{http://schemas.datacontract.org/2004/07/Muhimbi.DocumentConverter.WebService.Data}MergeMode" minOccurs="0"/>
* <element name="UnsupportedFileBehaviour" type="{http://schemas.datacontract.org/2004/07/Muhimbi.DocumentConverter.WebService.Data}UnsupportedFileBehaviour" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FileMergeSettings", propOrder = {
"topLevelBookmark",
"mergeMode",
"unsupportedFileBehaviour"
})
public class FileMergeSettings {
@XmlElementRef(name = "TopLevelBookmark", namespace = "http://types.muhimbi.com/2009/10/06", type = JAXBElement.class, required = false)
protected JAXBElement<String> topLevelBookmark;
@XmlElement(name = "MergeMode")
@XmlSchemaType(name = "string")
protected MergeMode mergeMode;
@XmlElement(name = "UnsupportedFileBehaviour")
@XmlSchemaType(name = "string")
protected UnsupportedFileBehaviour unsupportedFileBehaviour;
/**
* Gets the value of the topLevelBookmark property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getTopLevelBookmark() {
return topLevelBookmark;
}
/**
* Sets the value of the topLevelBookmark property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setTopLevelBookmark(JAXBElement<String> value) {
this.topLevelBookmark = value;
}
/**
* Gets the value of the mergeMode property.
*
* @return
* possible object is
* {@link MergeMode }
*
*/
public MergeMode getMergeMode() {
return mergeMode;
}
/**
* Sets the value of the mergeMode property.
*
* @param value
* allowed object is
* {@link MergeMode }
*
*/
public void setMergeMode(MergeMode value) {
this.mergeMode = value;
}
/**
* Gets the value of the unsupportedFileBehaviour property.
*
* @return
* possible object is
* {@link UnsupportedFileBehaviour }
*
*/
public UnsupportedFileBehaviour getUnsupportedFileBehaviour() {
return unsupportedFileBehaviour;
}
/**
* Sets the value of the unsupportedFileBehaviour property.
*
* @param value
* allowed object is
* {@link UnsupportedFileBehaviour }
*
*/
public void setUnsupportedFileBehaviour(UnsupportedFileBehaviour value) {
this.unsupportedFileBehaviour = value;
}
}
|
3e17ca56fb9f5f8422354427facf6e0e7bf0ef4b | 77 | java | Java | src/TDPokemons/IAttaque.java | 2019-2020-IUT/M213-Bases-de-la-programmation-oriente-objet | 6c5cc3b59700861e204a139cd7d6e07493965748 | [
"CC-BY-4.0"
] | null | null | null | src/TDPokemons/IAttaque.java | 2019-2020-IUT/M213-Bases-de-la-programmation-oriente-objet | 6c5cc3b59700861e204a139cd7d6e07493965748 | [
"CC-BY-4.0"
] | null | null | null | src/TDPokemons/IAttaque.java | 2019-2020-IUT/M213-Bases-de-la-programmation-oriente-objet | 6c5cc3b59700861e204a139cd7d6e07493965748 | [
"CC-BY-4.0"
] | null | null | null | 12.833333 | 27 | 0.766234 | 10,138 | package TDPokemons;
public interface IAttaque {
void attaque(Pokemon p);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.