hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
50b025b8bec1574db1484c2001794ffbaa095d60
3,398
package life.calgo.storage; import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import java.util.logging.Logger; import life.calgo.commons.core.LogsCenter; import life.calgo.commons.exceptions.DataConversionException; import life.calgo.commons.exceptions.IllegalValueException; import life.calgo.commons.util.FileUtil; import life.calgo.commons.util.JsonUtil; import life.calgo.model.ReadOnlyConsumptionRecord; /** * A class to access ConsumptionRecord data stored as a json file on the hard disk. */ public class JsonConsumptionRecordStorage implements ConsumptionRecordStorage { private static final Logger logger = LogsCenter.getLogger(ConsumptionRecordStorage.class); private Path filePath; public JsonConsumptionRecordStorage(Path filePath) { this.filePath = filePath; } @Override public Path getConsumptionRecordFilePath() { return filePath; } /** * Returns a ReadOnlyConsumptionRecord wrapped in an Optional after reading from a json file. * * @return A {@code ReadOnlyConsumptionRecord} object that was read from file path, * wrapped within an {@code Optional}. * @throws DataConversionException If the file is not in the correct format. */ @Override public Optional<ReadOnlyConsumptionRecord> readConsumptionRecord() throws DataConversionException { return readConsumptionRecord(filePath); } /** * Similar to {@link #readConsumptionRecord()}, but now reads from an specified file path. * * @param filePath Location of the data. Cannot be null. */ @Override public Optional<ReadOnlyConsumptionRecord> readConsumptionRecord(Path filePath) throws DataConversionException { requireNonNull(filePath); Optional<JsonSerializableConsumptionRecord> jsonConsumptionRecord = JsonUtil.readJsonFile( filePath, JsonSerializableConsumptionRecord.class); if (jsonConsumptionRecord.isEmpty()) { return Optional.empty(); } try { return Optional.of(jsonConsumptionRecord.get().toModelType()); } catch (IllegalValueException ive) { logger.info("Illegal values found in " + filePath + ": " + ive.getMessage()); throw new DataConversionException(ive); } } /** * Writes the ConsumptionRecord to the pre-specified file path. * * @param consumptionRecord The consumptionRecord to be saved, which cannot be null. * @throws IOException If there's any error when writing to the file. */ public void saveConsumptionRecord(ReadOnlyConsumptionRecord consumptionRecord) throws IOException { saveConsumptionRecord(consumptionRecord, filePath); } /** /** * Similar to {@link #saveConsumptionRecord(ReadOnlyConsumptionRecord)}, but now saves to a specified file path. * * @param filePath Location of the data. Cannot be null. */ public void saveConsumptionRecord(ReadOnlyConsumptionRecord consumptionRecord, Path filePath) throws IOException { requireNonNull(consumptionRecord); requireNonNull(filePath); FileUtil.createIfMissing(filePath); JsonUtil.saveJsonFile(new JsonSerializableConsumptionRecord(consumptionRecord), filePath); } }
34.673469
118
0.715127
97ea49759bd60184b582d59616c9bd4830509b80
1,802
package org.biologer.biologer.model.network; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.biologer.biologer.model.Stage; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "name", "created_at", "updated_at", "pivot" }) public class Stage6 { @JsonProperty("id") private long id; @JsonProperty("name") private String name; @JsonProperty("created_at") private String createdAt; @JsonProperty("updated_at") private String updatedAt; @JsonProperty("pivot") private Pivot pivot; // public Stage toStage(long taxonId){ // Stage stage = new Stage(id, name, taxonId); // return stage; // } @JsonProperty("id") public long getId() { return id; } @JsonProperty("id") public void setId(long id) { this.id = id; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("created_at") public String getCreatedAt() { return createdAt; } @JsonProperty("created_at") public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } @JsonProperty("updated_at") public String getUpdatedAt() { return updatedAt; } @JsonProperty("updated_at") public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @JsonProperty("pivot") public Pivot getPivot() { return pivot; } @JsonProperty("pivot") public void setPivot(Pivot pivot) { this.pivot = pivot; } }
20.712644
58
0.634295
92ba47d265bcce6e0096dfe4eec531b2f688f33a
2,275
package ru.job4j.cinema; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * the class for preparing requests from servlets to database and responses from database to servlets. */ public class Service { /** * the instance of the service class. */ private static final Service INSTANCE = new Service(); /** * the instance of the class for connecting to the database. */ private final DBConnector dbCon = DBConnector.getInstance(); /** * the main constructor. */ private Service() { } /** * the getter of the service instance. * * @return the instance. */ public static Service getInstance() { return INSTANCE; } /** * the method for getting cinema hall schema and returning it to the servlet. * * @param hallId - the hall id. * @return the map of the places with their status. */ public Map<Integer, Boolean> getHallSchema(int hallId) { Map<Integer, Boolean> occupiedPlaces = new HashMap<>(); Set<HallPlace> hall = this.dbCon.getHallSchema(hallId); for (HallPlace hallPlace : hall) { int row = hallPlace.getRow(); int place = hallPlace.getPlace(); int accountId = hallPlace.getAccountId(); int sitNum = row * 10 + place; if (accountId >= 0) { occupiedPlaces.put(sitNum, true); } else { occupiedPlaces.put(sitNum, false); } } return occupiedPlaces; } /** * the method for booking the place. * * @param name - customer name. * @param phone - customer phone. * @param hall - hall id. * @param row - row number in the hall. * @param place - place number on the row. * @return true if the place was booked; otherwise false. */ public boolean doPayment(String name, String phone, String hall, String row, String place) { int userPhone = Integer.parseInt(phone); int hallId = Integer.parseInt(hall); int rowNum = Integer.parseInt(row); int placeNum = Integer.parseInt(place); return this.dbCon.doTransaction(name, userPhone, hallId, rowNum, placeNum); } }
28.797468
102
0.60044
c240e7f994d78ad09fcfe2c9d519b56c331e56a8
2,889
package com.lzpeng.minimal.system.service; import cn.hutool.core.io.FileUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.lzpeng.minimal.common.core.response.QueryResult; import com.lzpeng.minimal.system.domain.entity.Notice; import lombok.extern.slf4j.Slf4j; 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.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import javax.annotation.Generated; import java.nio.charset.Charset; import java.util.Collection; import static org.junit.jupiter.api.Assertions.*; /** * 通知 业务层单元测试 * @author: JpaCodeGenerator */ @Slf4j @ExtendWith(SpringExtension.class) @Generated(value = "com.lzpeng.minimal.generate.jpa.JpaCodeGenerator", date = "2020-6-27 12:07:44", comments = "通知 业务层单元测试") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class NoticeServiceTest { /** * 通知Service */ @Autowired private NoticeService noticeService; /** * 保存通知测试 */ @Test public void testSave() { Notice notice = new Notice(); notice = noticeService.save(notice); assertNotNull(notice.getId()); } /** * 删除通知测试 */ @Test public void testDelete() { String id = "{}"; noticeService.delete(id); } /** * 更新通知测试 */ @Test public void testUpdate() { String id = "{}"; Notice notice = new Notice(); notice = noticeService.update(id, notice); assertEquals(notice.getId(), id); } /** * 根据id查询通知测试 */ @Test public void testFindById() { String id = "{}"; Notice notice = noticeService.findById(id); assertEquals(notice.getId(), id); } /** * 分页查询通知测试 */ @Test public void testQuery() { Notice notice = new Notice(); QueryResult<Notice> result = noticeService.query(0, 10, notice); assertNotNull(result.getList()); } /** * 读取JSON文件测试 */ @Test public void testReadDataFromJson() throws JsonProcessingException { String path = ""; // json File Path String json = FileUtil.readString(path, Charset.defaultCharset()); Collection<Notice> notices = noticeService.readDataFromJson(json); assertNotNull(notices); log.info("{}", notices); } /** * 从JSON文件导入通知测试 */ @Test public void testImportDataFromJson() throws JsonProcessingException { String path = ""; // json File Path String json = FileUtil.readString(path, Charset.defaultCharset()); Collection<Notice> notices = noticeService.importDataFromJson(json); assertNotNull(notices); log.info("{}", notices); } }
26.027027
124
0.654898
decedaae2709f9228da869577a3ae61582461d17
2,616
package team.fjut.cf.controller.admin; import org.springframework.web.bind.annotation.*; import team.fjut.cf.config.interceptor.annotation.PermissionRequired; import team.fjut.cf.pojo.enums.PermissionType; import team.fjut.cf.pojo.enums.ResultCode; import team.fjut.cf.pojo.vo.ResultJson; import team.fjut.cf.pojo.vo.response.BorderHonorRankVO; import team.fjut.cf.service.BorderHonorRankService; import javax.annotation.Resource; /** * @author axiang [2019/11/11] */ @RestController @CrossOrigin @RequestMapping("/admin/border") public class BorderManagerController { @Resource BorderHonorRankService borderHonorRankService; /** * @param id * @return */ @PermissionRequired(permissions = {PermissionType.RANK_MANAGER}) @GetMapping("/info") public ResultJson getHonor(@RequestParam("id") Integer id) { ResultJson resultJson = new ResultJson(); BorderHonorRankVO borderHonorRankVO = borderHonorRankService.selectById(id); resultJson.addInfo(borderHonorRankVO); return resultJson; } /** * @param id * @return */ @PermissionRequired(permissions = {PermissionType.RANK_MANAGER}) @DeleteMapping("/delete") public ResultJson deleteHonor(@RequestParam("id") Integer id) { ResultJson resultJson = new ResultJson(ResultCode.REQUIRED_SUCCESS); int result = borderHonorRankService.deleteHonor(id); if (result != 1) { resultJson.setStatus(ResultCode.BUSINESS_FAIL); } return resultJson; } /** * @param borderHonorRankVO * @return */ @PermissionRequired(permissions = {PermissionType.RANK_MANAGER}) @RequestMapping("/update") public ResultJson updateHonor(@RequestBody BorderHonorRankVO borderHonorRankVO) { ResultJson resultJson = new ResultJson(ResultCode.REQUIRED_SUCCESS); int result = borderHonorRankService.updateHonor(borderHonorRankVO); if (result != 1) { resultJson.setStatus(ResultCode.BUSINESS_FAIL); } return resultJson; } /** * @param borderHonorRankVO * @return */ @PermissionRequired(permissions = {PermissionType.RANK_MANAGER}) @RequestMapping("/create") public ResultJson createHonor(@RequestBody BorderHonorRankVO borderHonorRankVO) { ResultJson resultJson = new ResultJson(ResultCode.REQUIRED_SUCCESS); int result = borderHonorRankService.insertHonor(borderHonorRankVO); if (result != 1) { resultJson.setStatus(ResultCode.BUSINESS_FAIL); } return resultJson; } }
31.518072
85
0.697248
ab3857a9ef11b480b4983547f53fe172c7b7fc33
639
package io.github.alphagodzilla.authentication.core.service; import io.github.alphagodzilla.authentication.core.exception.AuthenticationSubjectNotExistException; import io.github.alphagodzilla.authentication.core.model.UserInformation; import java.io.Serializable; /** * @author AlphaGodzilla * @date 2021/10/14 11:22 */ public interface AuthenticationUserService { /** * 获取用户信息 * @param uid 用户ID,可以是用户的数字型ID,也可以直接是用户的用户名 * @return 用户信息 * @throws AuthenticationSubjectNotExistException 没有找到用户异常 */ UserInformation getUserInformation(Serializable uid) throws AuthenticationSubjectNotExistException; }
30.428571
103
0.788732
e33fd92c20ff17fb8cc0bacb18f133f210039f76
481
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package computing; /** * * @author jacek */ public abstract class uOperator extends Expression { private Expression exp; public void setExp (Expression exp) { this.exp = exp; } public Expression getExp () { return this.exp; } }
19.24
80
0.629938
0927a3b42705b69d807c23cdcf3f8830a52f5ef7
552
package com.example.uzvend.OperationRetrofitApi; import com.google.gson.annotations.SerializedName; public class Users { @SerializedName("response") public String Response; @SerializedName("user_id") private String UserId; @SerializedName("username") private String Username; public String getUsername() { return Username; } public String getResponse() { return Response; } public String getUserId() { return UserId; } }
19.034483
50
0.606884
22c092917185f5481568594a3098f4789d0245dc
5,156
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.converter.json; import com.fasterxml.jackson.annotation.ObjectIdGenerator; import com.fasterxml.jackson.annotation.ObjectIdResolver; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.deser.ValueInstantiator; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter; import com.fasterxml.jackson.databind.util.Converter; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.util.Assert; /** * Allows for creating Jackson ({@link JsonSerializer}, {@link JsonDeserializer}, * {@link KeyDeserializer}, {@link TypeResolverBuilder}, {@link TypeIdResolver}) * beans with autowiring against a Spring {@link ApplicationContext}. * * <p>As of Spring 4.3, this overrides all factory methods in {@link HandlerInstantiator}, * including non-abstract ones and recently introduced ones from Jackson 2.4 and 2.5: * for {@link ValueInstantiator}, {@link ObjectIdGenerator}, {@link ObjectIdResolver}, * {@link PropertyNamingStrategy}, {@link Converter}, {@link VirtualBeanPropertyWriter}. * * @author Sebastien Deleuze * @author Juergen Hoeller * @since 4.1.3 * @see Jackson2ObjectMapperBuilder#handlerInstantiator(HandlerInstantiator) * @see ApplicationContext#getAutowireCapableBeanFactory() * @see HandlerInstantiator */ public class SpringHandlerInstantiator extends HandlerInstantiator { private final AutowireCapableBeanFactory beanFactory; /** * Create a new SpringHandlerInstantiator for the given BeanFactory. * @param beanFactory the target BeanFactory */ public SpringHandlerInstantiator(AutowireCapableBeanFactory beanFactory) { Assert.notNull(beanFactory, "BeanFactory must not be null"); this.beanFactory = beanFactory; } @Override public JsonDeserializer<?> deserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> implClass) { return (JsonDeserializer<?>) this.beanFactory.createBean(implClass); } @Override public KeyDeserializer keyDeserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> implClass) { return (KeyDeserializer) this.beanFactory.createBean(implClass); } @Override public JsonSerializer<?> serializerInstance(SerializationConfig config, Annotated annotated, Class<?> implClass) { return (JsonSerializer<?>) this.beanFactory.createBean(implClass); } @Override public TypeResolverBuilder<?> typeResolverBuilderInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (TypeResolverBuilder<?>) this.beanFactory.createBean(implClass); } @Override public TypeIdResolver typeIdResolverInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (TypeIdResolver) this.beanFactory.createBean(implClass); } /** @since 4.3 */ @Override public ValueInstantiator valueInstantiatorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (ValueInstantiator) this.beanFactory.createBean(implClass); } /** @since 4.3 */ @Override public ObjectIdGenerator<?> objectIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (ObjectIdGenerator<?>) this.beanFactory.createBean(implClass); } /** @since 4.3 */ @Override public ObjectIdResolver resolverIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (ObjectIdResolver) this.beanFactory.createBean(implClass); } /** @since 4.3 */ @Override public PropertyNamingStrategy namingStrategyInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (PropertyNamingStrategy) this.beanFactory.createBean(implClass); } /** @since 4.3 */ @Override public Converter<?, ?> converterInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) { return (Converter<?, ?>) this.beanFactory.createBean(implClass); } /** @since 4.3 */ @Override public VirtualBeanPropertyWriter virtualPropertyWriterInstance(MapperConfig<?> config, Class<?> implClass) { return (VirtualBeanPropertyWriter) this.beanFactory.createBean(implClass); } }
35.315068
112
0.779286
61cdb7b1c52f3bf36bce0603aced4af8461b3922
2,100
/* * Copyright 2011-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core; import java.util.Arrays; import java.util.List; import java.util.Set; import io.lettuce.core.internal.LettuceSets; import io.lettuce.test.settings.TestSettings; /** * @author Mark Paluch * @author Tugdual Grall */ public abstract class TestSupport { public static final String host = TestSettings.hostAddr(); public static final int port = TestSettings.port(); public static final String username = TestSettings.username(); public static final String passwd = TestSettings.password(); public static final String aclUsername = TestSettings.aclUsername(); public static final String aclPasswd = TestSettings.aclPassword(); public static final String key = "key"; public static final String value = "value"; protected static List<String> list(String... args) { return Arrays.asList(args); } protected static List<Object> list(Object... args) { return Arrays.asList(args); } protected static List<ScoredValue<String>> svlist(ScoredValue<String>... args) { return Arrays.asList(args); } protected static KeyValue<String, String> kv(String key, String value) { return KeyValue.fromNullable(key, value); } protected static ScoredValue<String> sv(double score, String value) { return ScoredValue.fromNullable(score, value); } protected static Set<String> set(String... args) { return LettuceSets.newHashSet(args); } }
31.818182
84
0.713333
6c7c83ce9d9d83f3d1e495ad31e91b5d166e293c
22,436
/* * This file is part of dependency-check-core. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) 2015 Institute for Defense Analyses. All Rights Reserved. */ package org.owasp.dependencycheck.analyzer; import com.github.packageurl.MalformedPackageURLException; import com.github.packageurl.PackageURL; import com.github.packageurl.PackageURLBuilder; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.concurrent.ThreadSafe; import org.apache.commons.io.FileUtils; import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.dependency.Confidence; import org.owasp.dependencycheck.dependency.CvssV2; import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.EvidenceType; import org.owasp.dependencycheck.dependency.Reference; import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.VulnerableSoftware; import org.owasp.dependencycheck.dependency.VulnerableSoftwareBuilder; import org.owasp.dependencycheck.dependency.naming.GenericIdentifier; import org.owasp.dependencycheck.dependency.naming.PurlIdentifier; import org.owasp.dependencycheck.exception.InitializationException; import org.owasp.dependencycheck.utils.FileFilterBuilder; import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import us.springett.parsers.cpe.exceptions.CpeValidationException; import us.springett.parsers.cpe.values.Part; /** * Used to analyze Ruby Bundler Gemspec.lock files utilizing the 3rd party * bundle-audit tool. * * @author Dale Visser */ @ThreadSafe public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { /** * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzer.class); /** * A descriptor for the type of dependencies processed or added by this * analyzer. */ public static final String DEPENDENCY_ECOSYSTEM = "ruby"; /** * The name of the analyzer. */ private static final String ANALYZER_NAME = "Ruby Bundle Audit Analyzer"; /** * The phase that this analyzer is intended to run in. */ private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.PRE_INFORMATION_COLLECTION; /** * The filter defining which files will be analyzed. */ private static final FileFilter FILTER = FileFilterBuilder.newInstance().addFilenames("Gemfile.lock").build(); /** * Name. */ public static final String NAME = "Name: "; /** * Version. */ public static final String VERSION = "Version: "; /** * Advisory. */ public static final String ADVISORY = "Advisory: "; /** * Criticality. */ public static final String CRITICALITY = "Criticality: "; /** * The DAL. */ private CveDB cvedb = null; /** * If {@link #analyzeDependency(Dependency, Engine)} is called, then we have * successfully initialized, and it will be necessary to disable * {@link RubyGemspecAnalyzer}. */ private boolean needToDisableGemspecAnalyzer = true; /** * @return a filter that accepts files named Gemfile.lock */ @Override protected FileFilter getFileFilter() { return FILTER; } /** * Launch bundle-audit. * * @param folder directory that contains bundle audit * @return a handle to the process * @throws AnalysisException thrown when there is an issue launching bundle * audit */ private Process launchBundleAudit(File folder) throws AnalysisException { if (!folder.isDirectory()) { throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath())); } final List<String> args = new ArrayList<>(); final String bundleAuditPath = getSettings().getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH); File bundleAudit = null; if (bundleAuditPath != null) { bundleAudit = new File(bundleAuditPath); if (!bundleAudit.isFile()) { LOGGER.warn("Supplied `bundleAudit` path is incorrect: {}", bundleAuditPath); bundleAudit = null; } } args.add(bundleAudit != null && bundleAudit.isFile() ? bundleAudit.getAbsolutePath() : "bundle-audit"); args.add("check"); args.add("--verbose"); final ProcessBuilder builder = new ProcessBuilder(args); builder.directory(folder); try { LOGGER.info("Launching: {} from {}", args, folder); return builder.start(); } catch (IOException ioe) { throw new AnalysisException("bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. " + "Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified", ioe); } } /** * Initialize the analyzer. * * @param engine a reference to the dependency-check engine * @throws InitializationException if anything goes wrong */ @Override public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException { // Now, need to see if bundle-audit actually runs from this location. if (engine != null) { this.cvedb = engine.getDatabase(); } Process process = null; try { process = launchBundleAudit(getSettings().getTempDirectory()); } catch (AnalysisException ae) { setEnabled(false); final String msg = String.format("Exception from bundle-audit process: %s. Disabling %s", ae.getCause(), ANALYZER_NAME); throw new InitializationException(msg, ae); } catch (IOException ex) { setEnabled(false); throw new InitializationException("Unable to create temporary file, the Ruby Bundle Audit Analyzer will be disabled", ex); } final int exitValue; try { exitValue = process.waitFor(); } catch (InterruptedException ex) { setEnabled(false); final String msg = String.format("Bundle-audit process was interrupted. Disabling %s", ANALYZER_NAME); Thread.currentThread().interrupt(); throw new InitializationException(msg); } if (0 == exitValue) { setEnabled(false); final String msg = String.format("Unexpected exit code from bundle-audit process. Disabling %s: %s", ANALYZER_NAME, exitValue); throw new InitializationException(msg); } else { try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) { if (!reader.ready()) { LOGGER.warn("Bundle-audit error stream unexpectedly not ready. Disabling {}", ANALYZER_NAME); setEnabled(false); throw new InitializationException("Bundle-audit error stream unexpectedly not ready."); } else { final String line = reader.readLine(); if (line == null || !line.contains("Errno::ENOENT")) { LOGGER.warn("Unexpected bundle-audit output. Disabling {}: {}", ANALYZER_NAME, line); setEnabled(false); throw new InitializationException("Unexpected bundle-audit output."); } } } catch (UnsupportedEncodingException ex) { setEnabled(false); throw new InitializationException("Unexpected bundle-audit encoding.", ex); } catch (IOException ex) { setEnabled(false); throw new InitializationException("Unable to read bundle-audit output.", ex); } } if (isEnabled()) { LOGGER.info("{} is enabled. It is necessary to manually run \"bundle-audit update\" " + "occasionally to keep its database up to date.", ANALYZER_NAME); } } /** * Returns the name of the analyzer. * * @return the name of the analyzer. */ @Override public String getName() { return ANALYZER_NAME; } /** * Returns the phase that the analyzer is intended to run in. * * @return the phase that the analyzer is intended to run in. */ @Override public AnalysisPhase getAnalysisPhase() { return ANALYSIS_PHASE; } /** * Returns the key used in the properties file to reference the analyzer's * enabled property. * * @return the analyzer's enabled property setting key */ @Override protected String getAnalyzerEnabledSettingKey() { return Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED; } /** * Determines if the analyzer can analyze the given file type. * * @param dependency the dependency to determine if it can analyze * @param engine the dependency-check engine * @throws AnalysisException thrown if there is an analysis exception. */ @Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { if (needToDisableGemspecAnalyzer) { boolean failed = true; final String className = RubyGemspecAnalyzer.class.getName(); for (FileTypeAnalyzer analyzer : engine.getFileTypeAnalyzers()) { if (analyzer instanceof RubyBundlerAnalyzer) { ((RubyBundlerAnalyzer) analyzer).setEnabled(false); LOGGER.info("Disabled {} to avoid noisy duplicate results.", RubyBundlerAnalyzer.class.getName()); } else if (analyzer instanceof RubyGemspecAnalyzer) { ((RubyGemspecAnalyzer) analyzer).setEnabled(false); LOGGER.info("Disabled {} to avoid noisy duplicate results.", className); failed = false; } } if (failed) { LOGGER.warn("Did not find {}.", className); } needToDisableGemspecAnalyzer = false; } final File parentFile = dependency.getActualFile().getParentFile(); final Process process = launchBundleAudit(parentFile); final int exitValue; try { exitValue = process.waitFor(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new AnalysisException("bundle-audit process interrupted", ie); } if (exitValue < 0 || exitValue > 1) { final String msg = String.format("Unexpected exit code from bundle-audit process; exit code: %s", exitValue); throw new AnalysisException(msg); } try { try (BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) { while (errReader.ready()) { final String error = errReader.readLine(); LOGGER.warn(error); } } try (BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { processBundlerAuditOutput(dependency, engine, rdr); } } catch (IOException | CpeValidationException ioe) { LOGGER.warn("bundle-audit failure", ioe); } } /** * Processes the bundler audit output. * * @param original the dependency * @param engine the dependency-check engine * @param rdr the reader of the report * @throws IOException thrown if the report cannot be read * @throws CpeValidationException if there is an error building the * CPE/VulnerableSoftware object */ private void processBundlerAuditOutput(Dependency original, Engine engine, BufferedReader rdr) throws IOException, CpeValidationException { final String parentName = original.getActualFile().getParentFile().getName(); final String fileName = original.getFileName(); final String filePath = original.getFilePath(); Dependency dependency = null; Vulnerability vulnerability = null; String gem = null; final Map<String, Dependency> map = new HashMap<>(); boolean appendToDescription = false; while (rdr.ready()) { final String nextLine = rdr.readLine(); if (null == nextLine) { break; } else if (nextLine.startsWith(NAME)) { appendToDescription = false; gem = nextLine.substring(NAME.length()); if (!map.containsKey(gem)) { map.put(gem, createDependencyForGem(engine, parentName, fileName, filePath, gem)); } dependency = map.get(gem); LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine); } else if (nextLine.startsWith(VERSION)) { vulnerability = createVulnerability(parentName, dependency, gem, nextLine); } else if (nextLine.startsWith(ADVISORY)) { setVulnerabilityName(parentName, dependency, vulnerability, nextLine); } else if (nextLine.startsWith(CRITICALITY)) { addCriticalityToVulnerability(parentName, vulnerability, nextLine); } else if (nextLine.startsWith("URL: ")) { addReferenceToVulnerability(parentName, vulnerability, nextLine); } else if (nextLine.startsWith("Description:")) { appendToDescription = true; if (null != vulnerability) { vulnerability.setDescription("*** Vulnerability obtained from bundle-audit verbose report. " + "Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 " + " indicates unknown). See link below for full details. *** "); } } else if (appendToDescription && null != vulnerability) { vulnerability.setDescription(vulnerability.getDescription() + nextLine + "\n"); } } } /** * Sets the vulnerability name. * * @param parentName the parent name * @param dependency the dependency * @param vulnerability the vulnerability * @param nextLine the line to parse */ private void setVulnerabilityName(String parentName, Dependency dependency, Vulnerability vulnerability, String nextLine) { final String advisory = nextLine.substring(ADVISORY.length()); if (null != vulnerability) { vulnerability.setName(advisory); } if (null != dependency) { dependency.addVulnerability(vulnerability); } LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine); } /** * Adds a reference to the vulnerability. * * @param parentName the parent name * @param vulnerability the vulnerability * @param nextLine the line to parse */ private void addReferenceToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) { final String url = nextLine.substring("URL: ".length()); if (null != vulnerability) { final Reference ref = new Reference(); ref.setName(vulnerability.getName()); ref.setSource("bundle-audit"); ref.setUrl(url); vulnerability.getReferences().add(ref); } LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine); } /** * Adds the criticality to the vulnerability * * @param parentName the parent name * @param vulnerability the vulnerability * @param nextLine the line to parse */ private void addCriticalityToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) { if (null != vulnerability) { final String criticality = nextLine.substring(CRITICALITY.length()).trim(); float score = -1.0f; Vulnerability v = null; if (cvedb != null) { try { v = cvedb.getVulnerability(vulnerability.getName()); } catch (DatabaseException ex) { LOGGER.debug("Unable to look up vulnerability {}", vulnerability.getName()); } } if (v != null && (v.getCvssV2() != null || v.getCvssV3() != null)) { if (v.getCvssV2() != null) { vulnerability.setCvssV2(v.getCvssV2()); } if (v.getCvssV3() != null) { vulnerability.setCvssV3(v.getCvssV3()); } } else { if ("High".equalsIgnoreCase(criticality)) { score = 8.5f; } else if ("Medium".equalsIgnoreCase(criticality)) { score = 5.5f; } else if ("Low".equalsIgnoreCase(criticality)) { score = 2.0f; } vulnerability.setCvssV2(new CvssV2(score, "-", "-", "-", "-", "-", "-", criticality)); } } LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine); } /** * Creates a vulnerability. * * @param parentName the parent name * @param dependency the dependency * @param gem the gem name * @param nextLine the line to parse * @return the vulnerability * @throws CpeValidationException thrown if there is an error building the * CPE vulnerability object */ private Vulnerability createVulnerability(String parentName, Dependency dependency, String gem, String nextLine) throws CpeValidationException { Vulnerability vulnerability = null; if (null != dependency) { final String version = nextLine.substring(VERSION.length()); dependency.addEvidence(EvidenceType.VERSION, "bundler-audit", "Version", version, Confidence.HIGHEST); dependency.setVersion(version); dependency.setName(gem); try { final PackageURL purl = PackageURLBuilder.aPackageURL().withType("gem").withName(dependency.getName()) .withVersion(dependency.getVersion()).build(); dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST)); } catch (MalformedPackageURLException ex) { LOGGER.debug("Unable to build package url for python", ex); final GenericIdentifier id = new GenericIdentifier("gem:" + dependency.getName() + "@" + dependency.getVersion(), Confidence.HIGHEST); dependency.addSoftwareIdentifier(id); } vulnerability = new Vulnerability(); // don't add to dependency until we have name set later final VulnerableSoftwareBuilder builder = new VulnerableSoftwareBuilder(); final VulnerableSoftware vs = builder.part(Part.APPLICATION) .vendor(gem) .product(String.format("%s_project", gem)) .version(version).build(); vulnerability.addVulnerableSoftware(vs); vulnerability.setMatchedVulnerableSoftware(vs); vulnerability.setCvssV2(new CvssV2(-1, "-", "-", "-", "-", "-", "-", "unknown")); } LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine); return vulnerability; } /** * Creates the dependency based off of the gem. * * @param engine the engine used for scanning * @param parentName the gem parent * @param fileName the file name * @param filePath the file path * @param gem the gem name * @return the dependency to add * @throws IOException thrown if a temporary gem file could not be written */ private Dependency createDependencyForGem(Engine engine, String parentName, String fileName, String filePath, String gem) throws IOException { final File gemFile; try { gemFile = File.createTempFile(gem, "_Gemfile.lock", getSettings().getTempDirectory()); } catch (IOException ioe) { throw new IOException("Unable to create temporary gem file"); } final String displayFileName = String.format("%s%c%s:%s", parentName, File.separatorChar, fileName, gem); FileUtils.write(gemFile, displayFileName, Charset.defaultCharset()); // unique contents to avoid dependency bundling final Dependency dependency = new Dependency(gemFile); dependency.setEcosystem(DEPENDENCY_ECOSYSTEM); dependency.addEvidence(EvidenceType.PRODUCT, "bundler-audit", "Name", gem, Confidence.HIGHEST); //TODO add package URL - note, this may require parsing the gemfile.lock and getting the version for each entry dependency.setDisplayFileName(displayFileName); dependency.setFileName(fileName); dependency.setFilePath(filePath); engine.addDependency(dependency); return dependency; } }
42.412098
148
0.627741
7ff50e23481f75d659b2b0315cdaf28e4ce91157
3,415
import javax.swing.*; import javax.swing.SwingUtilities; import java.text.*; /** * Class to make it easy to do output to the user * using JOptionPane * <br> * Copyright Georgia Institute of Technology 2004 * @author Barb Ericson ericson@cc.gatech.edu * * 14 May 2009: Edited by Dorn to ensure all JOptionPane calls to show are threadsafe. */ public class SimpleOutput { /** * Method to show a warning to a user * @param message the message to display */ public static void showWarning(String message) { message = addNewLines(message); safeOutputDialog(message, "Warning Display", JOptionPane.WARNING_MESSAGE); } /** * Method to show an error to a user * @param message the message to display */ public static void showError(String message) { message = addNewLines(message); safeOutputDialog(message, "Error Display", JOptionPane.ERROR_MESSAGE); } /** * Method to show information to the user * @param message the message to display */ public static void showInformation(String message) { message = addNewLines(message); safeOutputDialog(message, "Information Display", JOptionPane.INFORMATION_MESSAGE); } /** * Method to add new line character if the message * is too long * @param message the input message * @return the message with new lines added if needed */ public static String addNewLines(String message) { BreakIterator boundary = BreakIterator.getLineInstance(); boundary.setText(message); int start = boundary.first(); String result = ""; String currLine = ""; String temp = null; // loop till no more possible line breaks for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) { // get string between start and end temp = message.substring(start, end); /* if adding that to the current line * would make it too long then add current * to result followed by a newline and * reset current */ if (temp.length() + currLine.length() > 100) { result = result + currLine + "\n"; currLine = temp; } // else add the segment to the current line else { currLine = currLine + temp; } } // if no line breaks use the original message if (result.length() == 0) { result = message; } // else add any leftover parts else { result = result + currLine; } return result; } private static void safeOutputDialog(final String message, final String title, final int messageType) { Runnable promptStringRunner = new Runnable() { public void run() { JOptionPane.showMessageDialog(null, message, title, messageType); } }; try { if (SwingUtilities.isEventDispatchThread()) { promptStringRunner.run(); } else { SwingUtilities.invokeAndWait(promptStringRunner); } } catch (Exception e) { //do nothing } } } // end of SimpleOutput class
29.95614
107
0.579209
6490154453f5e44213fa35898f71f931229076e3
2,347
package org.springframework.samples.petclinic.component; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.samples.petclinic.constant.ValidationConstant; import org.springframework.samples.petclinic.model.NumCamiseta; import org.springframework.samples.petclinic.service.NumCamisetaService; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; @Component @NoArgsConstructor @AllArgsConstructor public class NumCamisetaValidator implements Validator{ private static final Log LOG = LogFactory.getLog(CapitanValidator.class); @Autowired private NumCamisetaService numCamisetaService; @Override public void validate(Object target, Errors errors) { NumCamiseta numCamiseta = (NumCamiseta) target; //Número de camiseta validación if (numCamiseta.getNumero()==null) { LOG.warn(ValidationConstant.NUM_CAMISETA_ERORR); errors.rejectValue("numero", "error",ValidationConstant.NUM_CAMISETA_ERORR); }else if(numCamiseta.getNumero()<1){ LOG.warn(ValidationConstant.NUM_CAMISETA_MENOR_QUE_1); errors.rejectValue("numero", "error",ValidationConstant.NUM_CAMISETA_MENOR_QUE_1); }else if(numCamiseta.getNumero()>99) { LOG.warn(ValidationConstant.NUM_CAMISETA_MAYOR_QUE_99); errors.rejectValue("numero", "error",ValidationConstant.NUM_CAMISETA_MAYOR_QUE_99); }else{ List<NumCamiseta> nums = numCamisetaService.findByEquipo(numCamiseta.getEquipo().getId()); if(nums != null && nums.stream().map(x->x.getNumero()).collect(Collectors.toList()).contains(numCamiseta.getNumero())) { for(int i = 0; i< nums.size();i++) { if(nums.get(i).getNumero() == numCamiseta.getNumero() && nums.get(i).getId() != numCamiseta.getId()) { LOG.warn(ValidationConstant.NUM_CAMISETA_REPETIDO); errors.rejectValue("numero", "error",ValidationConstant.NUM_CAMISETA_REPETIDO); } } } } } @Override public boolean supports(Class<?> clazz) { // TODO Auto-generated method stub return false; } }
37.854839
124
0.760545
b23beb63b7c856fba8e65493ab0c113afe465db3
6,516
package com.wavemaker.connector.jasper; import java.io.*; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = JasperConnectorTestConfiguration.class) public class JasperConnectorTest { private static String userHome = System.getProperty("user.dir"); private static File reportDir; static { reportDir = new File(userHome + "/target/reports"); reportDir.mkdir(); } @Autowired private JasperConnector connectorInstance; @Autowired private DataSourceProvider dataSourceProvider; @Test public void generatePDFReport() { String data = getStringFromResource("department/department.json"); File pdffile = new File(reportDir + "/dept.pdf"); connectorInstance.generateReport(JasperExportType.PDF, "department/dept.jrxml", new HashMap<>(), data, pdffile); System.out.println("PDF report generated successfully"); } @Test public void generateHTMLReport() { String data = getStringFromResource("department/department.json"); File htmlFile = new File(reportDir + "/dept.html"); connectorInstance.generateReport(JasperExportType.HTML, "department/dept.jrxml", new HashMap<>(), data, htmlFile); System.out.println("HTML report generated successfully"); } @Test public void generateXLSReport() { String data = getStringFromResource("department/department.json"); File xlsFile = new File(reportDir + "/dept.xls"); connectorInstance.generateReport(JasperExportType.XLS, "department/dept.jrxml", new HashMap<>(), data, xlsFile); System.out.println("XLS report generated successfully"); } @Test public void generateCSVReport() { String data = getStringFromResource("department/department.json"); File csvFile = new File(reportDir + "/dept.csv"); connectorInstance.generateReport(JasperExportType.CSV, "department/dept.jrxml", new HashMap<>(), data, csvFile); System.out.println("CSV report generated successfully"); } @Test public void generateDocReport() { String data = getStringFromResource("department/department.json"); File xmlFile = new File(reportDir + "/dept.doc"); connectorInstance.generateReport(JasperExportType.DOC, "department/dept.jrxml", new HashMap<>(), data, xmlFile); System.out.println("DOC report generated successfully"); } @Test public void generatePDFReportByDataSource() { File pdffile = new File(reportDir + "/employee.pdf"); connectorInstance.generateReport(JasperExportType.PDF, "employee/emp.jrxml", new HashMap<>(), dataSourceProvider.getDataSource(), pdffile); System.out.println("PDF report generated successfully using data source"); } @Test public void generatePDFReportByDataSourceHavingPlacceholders() { File pdffile = new File(reportDir + "/employee_ph.pdf"); HashMap<String, Object> objectObjectHashMap = new HashMap<>(); objectObjectHashMap.put("age",60); connectorInstance.generateReport(JasperExportType.PDF, "employeeWithPlaceholders/emp.jrxml", objectObjectHashMap , dataSourceProvider.getDataSource(), pdffile); System.out.println("PDF report generated successfully using data source"); } @Test public void generateXLSReportByDataSource() { File reportFile = new File(reportDir + "/employee.xls"); connectorInstance.generateReport(JasperExportType.XLS, "employee/emp.jrxml", new HashMap<>(), dataSourceProvider.getDataSource(), reportFile); System.out.println("XLS report generated successfully using data source"); } @Test public void generateCSVReportByDataSource() { File reportFile = new File(reportDir + "/employee.csv"); try { File.createTempFile("tmp", ".txt"); } catch (IOException e) { e.printStackTrace(); } connectorInstance.generateReport(JasperExportType.CSV, "employee/emp.jrxml", new HashMap<>(), dataSourceProvider.getDataSource(), reportFile); System.out.println("CSV report generated successfully using connector data source"); } @Test public void generatePDFWithParamatersReport() { String data = getStringFromResource("deptwithparams/department.json"); File pdffile = new File(reportDir + "/deptwithparam.pdf"); Map<String,Object> parameters = new HashMap<>(); parameters.put("REPORTHEADER", "Departments by City"); parameters.put("PAGEHEADER", "Departments Report"); connectorInstance.generateReport(JasperExportType.PDF, "deptwithparams/deptwithparam.jrxml", parameters, data, pdffile); System.out.println("PDF report generated successfully"); } @Test public void generateReportWithStream() { File pdffile = new File(reportDir + "/emp.pdf"); ByteArrayOutputStream outputStream = (ByteArrayOutputStream) connectorInstance.generateReport(JasperExportType.PDF, "employee/emp.jrxml", new HashMap<>(),dataSourceProvider.getDataSource()); byte[] bytes = outputStream.toByteArray(); writeByte(bytes,pdffile); try { if(outputStream!= null) outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } private String getStringFromResource(String resource) { try { InputStream jrxmlInput = this.getClass().getClassLoader().getResource(resource).openStream(); StringWriter writer = new StringWriter(); IOUtils.copy(jrxmlInput, writer, "UTF-8"); return writer.toString(); } catch (IOException e) { throw new RuntimeException("Failed to convert resource to string", e); } } private static void writeByte(byte[] bytes, File file) { try { OutputStream os = new FileOutputStream(file); os.write(bytes); System.out.println("Successfully" + " byte inserted"); os.close(); } catch (Exception e) { System.out.println("Exception: " + e); } } }
40.981132
198
0.68232
b35434ac7d415e1e61ddd5bdf44d1cff98b71516
2,393
import java.util.*; import org.junit.Test; import static org.junit.Assert.*; // LC291: https://leetcode.com/problems/word-pattern-ii/ // // Given a pattern and a string str, find if str follows the same pattern. // Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str. public class WordPattern2 { // DFS + Backtracking + Recursion // beats 94.31%(8 ms for 22 tests) public boolean wordPatternMatch(String pattern, String str) { return match(pattern.toCharArray(), 0, str.toCharArray(), 0, new String[26], new HashSet<>()); } private boolean match(char[] pattern, int pIndex, char[] str, int sIndex, String[] map, Set<String> mappedSet) { int patLen = pattern.length - pIndex; int len = str.length - sIndex; if (patLen == 0) return len == 0; if (len < patLen) return false; char first = pattern[pIndex]; String mapped = map[first - 'a']; if (mapped != null) { return new String(str, sIndex, len).startsWith(mapped) && match(pattern, pIndex + 1, str, sIndex + mapped.length(), map, mappedSet); } for (int i = 1; i <= len; i++) { String substr = new String(str, sIndex, i); if (mappedSet.contains(substr)) continue; map[first - 'a'] = substr; mappedSet.add(substr); if (match(pattern, pIndex + 1, str, sIndex + i, map, mappedSet)) return true; map[first - 'a'] = null; mappedSet.remove(substr); } return false; } // TODO: improve performance by more pruning void test(String pattern, String str, boolean expected) { assertEquals(expected, wordPatternMatch(pattern, str)); } @Test public void test1() { test("d", "e", true); test("aba", "aaaa", true); test("ab", "cc", false); test("ab", "redred", true); test("abab", "redblueredblue", true); test("aaaa", "asdasdasdasd", true); test("aabb", "xyzabcxzyabc", false); test("abba", "dogcatcatdog", true); test("itwasthebestoftimes", "ittwaastthhebesttoofttimes", true); } public static void main(String[] args) { org.junit.runner.JUnitCore.main("WordPattern2"); } }
34.681159
127
0.581279
86824b384d1962822df3ce653014fed0bad81518
1,800
package com.spotinst.sdkjava.model.api.gcp; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.spotinst.sdkjava.client.rest.IPartialUpdateEntity; import java.util.HashSet; import java.util.List; import java.util.Set; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonFilter("PartialUpdateEntityFilter") public class ApiInstanceTypesGcp implements IPartialUpdateEntity { //region members @JsonIgnore private Set<String> isSet; private List<String> preemptible; private String ondemand; //endregion //region Constructor public ApiInstanceTypesGcp() { isSet = new HashSet<>(); } //endregion //region Getters & Setters public Set<String> getIsSet() { return isSet; } public void setIsSet(Set<String> isSet) { this.isSet = isSet; } public List<String> getPreemptible() { return preemptible; } public void setPreemptible(List<String> preemptible) { isSet.add("preemptible"); this.preemptible = preemptible; } public String getOndemand() { return ondemand; } public void setOndemand(String ondemand) { isSet.add("ondemand"); this.ondemand = ondemand; } //endregion //region isSet methods // Is preemptible Set boolean method @JsonIgnore public boolean isPreemptibleSet() { return isSet.contains("preemptible"); } // Is ondemand Set boolean method @JsonIgnore public boolean isOndemandSet() { return isSet.contains("ondemand"); } //endregion }
25
66
0.69
b5463f690f990bc8f763470f2323c3152b16fbed
889
package app.roana0229.org.android_screentracker_sample.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import app.roana0229.org.android_screentracker_sample.R; public class EmptyTabFragment extends Fragment { public static EmptyTabFragment newInstance() { EmptyTabFragment tabContentFragment = new EmptyTabFragment(); return tabContentFragment; } public EmptyTabFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tab_empty, container, false); return view; } }
26.147059
103
0.750281
95c117cba2e52e6e60242d939f8eed6586c57bdc
114
package io.craftgate.model; public enum SettlementType { SETTLEMENT, BOUNCED_SETTLEMENT, WITHDRAW }
12.666667
28
0.72807
066ba2259db77cb99c6ef09b19e5255ffa8ae94a
1,917
package de.yannicklem.shoppinglist.core.user.security.service; import de.yannicklem.shoppinglist.core.exception.UnauthorizedException; import de.yannicklem.shoppinglist.core.user.entity.SLUser; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import java.util.HashSet; import javax.servlet.http.HttpSession; @Service public class CurrentUserService { public boolean currentUserIsAdminOrSystemUser() { SLUser currentUser = getCurrentUser(); return currentUser == null || currentUser.isAdmin(); } public SLUser getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return null; } Object currentUser = authentication.getPrincipal(); if (currentUser instanceof SLUser) { return (SLUser) currentUser; } if (isAnonymousUser(currentUser)) { return getAnonymousUser(); } throw new UnauthorizedException("User was not of type SLUser"); } private boolean isAnonymousUser(Object currentUser) { return "anonymousUser".equals(currentUser); } private SLUser getAnonymousUser() { return new SLUser("anonymousUser", "", "", "", "", true, null, new HashSet<>()); } public void invalidateCurrentUsersSession() { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(false); if (session != null) { session.invalidate(); } } }
25.905405
115
0.703704
93bfc228bcf967fc099397f199333a9232de49da
3,720
/* * 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.skife.jdbi.v2.sqlobject; import com.fasterxml.classmate.members.ResolvedMethod; import net.sf.cglib.proxy.MethodProxy; import org.skife.jdbi.v2.ConcreteStatementContext; import org.skife.jdbi.v2.GeneratedKeys; import org.skife.jdbi.v2.Update; import org.skife.jdbi.v2.exceptions.UnableToCreateSqlObjectException; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.tweak.ResultSetMapper; class UpdateHandler extends CustomizingStatementHandler { private final String sql; private final Returner returner; UpdateHandler(Class<?> sqlObjectType, ResolvedMethod method) { super(sqlObjectType, method); boolean isGetGeneratedKeys = method.getRawMember().isAnnotationPresent(GetGeneratedKeys.class); if (!isGetGeneratedKeys && returnTypeIsInvalid(method.getRawMember().getReturnType()) ) { throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method)); } this.sql = SqlObject.getSql(method.getRawMember().getAnnotation(SqlUpdate.class), method.getRawMember()); if (isGetGeneratedKeys) { final ResultReturnThing magic = ResultReturnThing.forType(method); final GetGeneratedKeys ggk = method.getRawMember().getAnnotation(GetGeneratedKeys.class); final ResultSetMapper mapper; try { mapper = ggk.value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate result set mapper for statement", e); } this.returner = new Returner() { @Override public Object value(Update update, HandleDing baton) { GeneratedKeys o = update.executeAndReturnGeneratedKeys(mapper, ggk.columnName()); return magic.result(o, baton); } }; } else { this.returner = new Returner() { @Override public Object value(Update update, HandleDing baton) { return update.execute(); } }; } } @Override public Object invoke(HandleDing h, Object target, Object[] args, MethodProxy mp) { Update q = h.getHandle().createStatement(sql); applyCustomizers(q, args); applyBinders(q, args); return this.returner.value(q, h); } private interface Returner { Object value(Update update, HandleDing baton); } private boolean returnTypeIsInvalid(Class<?> type) { return !Number.class.isAssignableFrom(type) && !type.equals(Integer.TYPE) && !type.equals(Long.TYPE) && !type.equals(Void.TYPE); } private String invalidReturnTypeMessage(ResolvedMethod method) { return method.getDeclaringType() + "." + method + " method is annotated with @SqlUpdate so should return void or Number but is returning: " + method.getReturnType(); } }
36.470588
119
0.644624
7cea5e6376aec5e15054c22ee3cedc63cab38666
494
package com.cricket.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface TableTextSelector{ public String selector() default ""; public String scope() default "global"; public String regex() default ""; public String heading() default ""; public int adjustment() default 0; }
23.52381
44
0.777328
349740c013e9a028be15e1b5e1bdae66a7228d18
2,867
package com.google.android.gms.samples.vision.barcodereader; import android.content.Intent; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Map; public class SelectHall extends AppCompatActivity { private ArrayList<String> arraySpinner; private final String TAG = "Select Hall"; private final String HALL = "hall";//hall array from json @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_hall); // String json = "{\"hall\":[\"Hall 1\", \"Hall 2\", \"Hall 3\", \"Hall 4\", \"Hall 5\", \"Hall 6\"]}"; String json = readFile(); Gson gson = new Gson(); Type type = new TypeToken<Map<String, Object>>(){}.getType(); try { Map<String, Object> myMap = gson.fromJson(json, type); arraySpinner = (ArrayList<String>) myMap.get(HALL); } catch (Exception e){ Log.e(TAG, e.toString()); } final Spinner spinner = (Spinner) findViewById(R.id.spinner_select_hall); final Button selectHall = (Button) findViewById(R.id.btn_select_hall); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, arraySpinner); spinner.setAdapter(adapter); selectHall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SelectHall.this, BarcodeCaptureActivity.class); intent.putExtra("hall", spinner.getSelectedItem().toString()); startActivity(intent); } }); } private String readFile(){ File documentsPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "BarcodeReader"); documentsPath = new File(documentsPath, "agenda"); File file = new File(documentsPath, "agenda.txt"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (Exception e) { Log.e("Read Error", e.toString()); } return text.toString(); } }
32.579545
116
0.631671
b57798d70c16ab5775219547f36b3e89c601c2f6
13,549
package domainapp.modules.simple.dom.impl.reservaVehiculo; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.datanucleus.query.typesafe.TypesafeQuery; import org.joda.time.LocalDate; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.ParameterLayout; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.query.QueryDefault; import org.apache.isis.applib.services.eventbus.ActionDomainEvent; import org.apache.isis.applib.services.jdosupport.IsisJdoSupport; import org.apache.isis.applib.services.message.MessageService; import org.apache.isis.applib.services.repository.RepositoryService; import org.apache.isis.applib.value.Blob; import domainapp.modules.simple.dom.impl.SimpleObjects; import domainapp.modules.simple.dom.impl.enums.EstadoReserva; import domainapp.modules.simple.dom.impl.enums.EstadoVehiculo; import domainapp.modules.simple.dom.impl.persona.Persona; import domainapp.modules.simple.dom.impl.persona.PersonaRepository; import domainapp.modules.simple.dom.impl.reportes.EjecutarReportes; import domainapp.modules.simple.dom.impl.vehiculo.Vehiculo; import domainapp.modules.simple.dom.impl.vehiculo.VehiculoRepository; import lombok.AccessLevel; import net.sf.jasperreports.engine.JRException; @DomainService( nature = NatureOfService.DOMAIN, repositoryFor = ReservaVehiculo.class ) @DomainServiceLayout( named = "Reserva Vehiculos", menuOrder = "10" ) /** * Esta clase es el servicio de dominio de la clase ReservaVehiculo * que define los metodos * que van a aparecer en el menu del sistema * * @author Cintia Millacura */ public class ReservaVehiculoRepository { /** * Identificacion del nombre del icono que aparecera en la UI * * @return String */ public String iconName() { return "Reserva"; } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "1") @Programmatic /** * Este metodo lista todas las reservas de vehiculos que hay cargados * en el sistema * * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> listarReservasDeVehiculos() { return repositoryService.allMatches( new QueryDefault<>( ReservaVehiculo.class, "find")); } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "2") @Programmatic /** * Este metodo lista todos las Reservas Activas que hay cargados * en el sistema * * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> listarReservasDeVehiculosActivas() { return this.listarReservasPorEstado(EstadoReserva.ACTIVA); } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "3") @Programmatic /** * Este metodo lista todos las Reservas Canceladas que hay cargados * en el sistema * * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> listarReservasDeVehiculosCanceladas() { return this.listarReservasPorEstado(EstadoReserva.CANCELADA); } /** * Este metodo permite recuperar en una lista todos las reservas realizadas * dado un estado en particular * * @param estado * @return List<ReservaVehiculo> */ @Programmatic public List<ReservaVehiculo> listarReservasPorEstado( @ParameterLayout(named="Estado") final EstadoReserva estado ) { TypesafeQuery<ReservaVehiculo> tq = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); List<ReservaVehiculo> reservas = tq.filter( cand.estado.eq(tq.stringParameter("estado"))) .setParameter("estado",estado).executeList(); return reservas; } /** * Este metodo permite encontrar todas las reservas * realizadas por un usuario en particular * * @param persona * @return List<ReservaVehiculo> */ //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "4") @Programmatic public List<ReservaVehiculo> listarReservasPorPersona( final Persona persona ) { List<ReservaVehiculo> reservas; TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas= q.filter( cand.persona.dni.eq(q.stringParameter("dniIngresado"))) .setParameter("dniIngresado",persona.getDni()) .executeList(); return reservas; } /** * Este metodo permite encontrar todas las reservas * realizadas por un usuario en particular dado su dni * * @param dni * @return List<ReservaVehiculo> */ @Programmatic public List<ReservaVehiculo> listarReservasPorDni( final String dni ) { List<ReservaVehiculo> reservas; TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas= q.filter( cand.persona.dni.eq(q.stringParameter("dniIngresado"))) .setParameter("dniIngresado",dni) .executeList(); return reservas; } /** * Este metodo permite encontrar todas las reservas * realizadas dado un numero en particular * * @param matricula * @return List<ReservaVehiculo> */ @Programmatic public List<ReservaVehiculo> listarReservasPorMatricula( final String matricula ) { List<ReservaVehiculo> reservas; TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas= q.filter( cand.vehiculo.matricula.eq(q.stringParameter("matriculaIngresado"))) .setParameter("matriculaIngresado",matricula) .executeList(); return reservas; } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "5") @Programmatic /** * Este metodo lista todas las reservas de vehiculos que hay cargados * en el sistema en el dia de la fecha * * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> listarReservasQueInicianHoy() { List<ReservaVehiculo> reservas; TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas = q.filter( cand.fechaInicio.eq(LocalDate.now())) .executeList(); return reservas; } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "6") @Programmatic /** * Este metodo lista todas las reservas de vehiculos que hay cargados * en el sistema finalizan en el dia de la fecha * * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> listarReservasQueFinalizanHoy() { List<ReservaVehiculo> reservas; TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas = q.filter( cand.fechaFin.eq(LocalDate.now())) .executeList(); return reservas; } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "7") @Programmatic /** * Este metodo permite listar todas las reservas de vehiculos * dada una fecha de reserva * * @param fechaReseva * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> buscarReservasPorFechaDeReserva( final LocalDate fechaReserva ) { List<ReservaVehiculo> reservas; TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas = q.filter( cand.fechaReserva.eq(q.stringParameter("fecha"))) .setParameter("fecha",fechaReserva) .executeList(); return reservas; } @Programmatic public Persona recuperarPersonaPorEmail(String email){ Persona persona=new Persona(); boolean band=false; List<Persona> listaPersonas=new ArrayList<Persona>(); listaPersonas=personaRepository.listarPersonas(); int i=0; while(i<listaPersonas.size()&&(!band)){ Persona aux=listaPersonas.get(i); if(aux.getEmail().equals(email)){ persona=aux; band=true; } i++; } if(band==false){ persona=null; } return persona; } public static class CreateDomainEvent extends ActionDomainEvent<SimpleObjects> {} //@Action(domainEvent = SimpleObjects.CreateDomainEvent.class) //@MemberOrder(sequence = "8") @Programmatic /** * Este metodo permite crear la entidad de dominio ReservaVehiculo * con los datos que va a ingresar el usuario * * @param fechaInicio * @param fechaFin * @param email * */ public void crearReserva( final LocalDate fechaInicio, final LocalDate fechaFin, final String email ) { Persona persona=new Persona(); persona=recuperarPersonaPorEmail(email); int i=vehiculoRepository.listarVehiculosPorEstado(EstadoVehiculo.DISPONIBLE).size(); if(i>=1) { ReservaVehiculo reservaVehiculo=new ReservaVehiculo(); Vehiculo vehiculo = vehiculoRepository.listarVehiculosPorEstado(EstadoVehiculo.DISPONIBLE).get(0); vehiculo.setEstado(EstadoVehiculo.OCUPADO); reservaVehiculo.setFechaReserva(LocalDate.now()); reservaVehiculo.setFechaInicio(fechaInicio); reservaVehiculo.setFechaFin(fechaFin); reservaVehiculo.setPersona(persona); reservaVehiculo.setVehiculo(vehiculo); reservaVehiculo.setEstado(EstadoReserva.ACTIVA); repositoryService.persist(reservaVehiculo); String mensaje="¡¡¡ LA OPERACIÓN DE LA RESERVA DEL VEHÍCULO FUE REALIZADA CON EXITO !!!"; messageService.informUser(mensaje); }else { String mensaje="¡¡¡ NO HAY VEHÍCULOS DISPONIBLES EN EL SISTEMA PARA REALIZAR LA RESERVA !!!"; messageService.warnUser(mensaje); } } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@ActionLayout(named = "Exportar PDF Lista de Resevas Activas") //@MemberOrder(sequence = "9") @Programmatic public Blob generarReporteReservasVehiculosActivas( ) throws JRException, IOException { List<ReservaVehiculo> reservasVehiculos = new ArrayList<ReservaVehiculo>(); reservasVehiculos = repositoryService.allInstances(ReservaVehiculo.class); EjecutarReportes ejecutarReportes=new EjecutarReportes(); return ejecutarReportes.ListadoReservasVehiculosPDF(reservasVehiculos); } //@Action(semantics = SemanticsOf.SAFE) //@ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT) //@MemberOrder(sequence = "10") @Programmatic /** * Este metodo lista todas las reservas de vehiculos que finalizaron * y de esta forma actualizar la disponibilidad de cada uno de los Vehiculos * * @return List<ReservaVehiculo> */ public List<ReservaVehiculo> actualizarVehiculosDisponibles() { List<ReservaVehiculo> reservas=new ArrayList<ReservaVehiculo>(); LocalDate fechaAyer=LocalDate.now().minusDays(1); TypesafeQuery<ReservaVehiculo> q = isisJdoSupport.newTypesafeQuery(ReservaVehiculo.class); final QReservaVehiculo cand = QReservaVehiculo.candidate(); reservas = q.filter( cand.fechaFin.eq((LocalDate)fechaAyer)) .executeList(); return reservas; } @javax.inject.Inject EjecutarReportes ejecutarReportes; @javax.inject.Inject RepositoryService repositoryService; @javax.inject.Inject IsisJdoSupport isisJdoSupport; @javax.inject.Inject org.apache.isis.applib.DomainObjectContainer container; @javax.inject.Inject PersonaRepository personaRepository; @javax.inject.Inject VehiculoRepository vehiculoRepository; @javax.inject.Inject @javax.jdo.annotations.NotPersistent @lombok.Getter(AccessLevel.NONE) @lombok.Setter(AccessLevel.NONE) MessageService messageService; }
30.723356
115
0.670751
6c01da311eefa708520ba9c375482e0a88e495f3
2,040
/* * 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.alipay.common.tracer.core.span; /** * 一些通用的 SpanTags * @author luoguimu123 * @version $Id: CommonSpanTags.java, v 0.1 2018年01月29日 下午12:10 luoguimu123 Exp $ */ public class CommonSpanTags { //************** String 类型 ************** /*** * 当前应用名称,注意和 RPC 保持一致 com.alipay.sofa.rpc.tracer.log.tags.RpcSpanTags#LOCAL_APP */ public static final String LOCAL_APP = "local.app"; /** * opposite end appName such as source or target appName */ public static final String REMOTE_APP = "remote.app"; /** * 结果码, 具体含义根据实际每个中间件的约定不同而不同 */ public static final String RESULT_CODE = "result.code"; /*** * 当前线程名字 */ public static final String CURRENT_THREAD_NAME = "current.thread.name"; /*** * 请求 url */ public static final String REQUEST_URL = "request.url"; /*** * 方法名称 */ public static final String METHOD = "method"; //************** Number 类型 ************** /*** * 请求大小 */ public static final String REQ_SIZE = "req.size.bytes"; /*** * 响应大小 */ public static final String RESP_SIZE = "resp.size.bytes"; }
29.565217
84
0.629412
82c925ce3dcb9174a58e521c6830a7c3b333d605
2,667
/* * Copyright 2017 Apereo * * 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.tle.admin.itemdefinition.mapping; import com.tle.admin.schema.SchemaModel; import com.tle.admin.schema.SingleTargetChooser; import java.awt.Component; import java.util.EventListener; import javax.swing.AbstractCellEditor; import javax.swing.JTable; import javax.swing.table.TableCellEditor; public class SchemaCellEditor extends AbstractCellEditor implements TableCellEditor { private static final long serialVersionUID = 1L; private SingleTargetChooser chooser; public SchemaCellEditor(SchemaModel model) { chooser = new SingleTargetChooser(model, null); chooser.setOpaque(true); } public void setNonLeafSelection(boolean bool) { chooser.setNonLeafSelection(bool); } public void addCellEditedListener(CellEditedListener listener) { listenerList.add(CellEditedListener.class, listener); } private void fireCellEditing(int row, int column) { EventListener[] listeners = listenerList.getListeners(CellEditedListener.class); for (EventListener element : listeners) { ((CellEditedListener) element).edited(this, row, column); } } /* * (non-Javadoc) * @see * javax.swing.table.TableCellEditor#getTableCellEditorComponent(javax.swing * .JTable, java.lang.Object, boolean, int, int) */ @Override public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column) { fireCellEditing(row, column); chooser.setTarget((String) value); if (isSelected) { chooser.setBackground(table.getSelectionBackground()); chooser.setForeground(table.getSelectionForeground()); } else { chooser.setBackground(table.getBackground()); chooser.setForeground(table.getForeground()); } return chooser; } /* * (non-Javadoc) * @see javax.swing.CellEditor#getCellEditorValue() */ @Override public Object getCellEditorValue() { return chooser.getTarget(); } public interface CellEditedListener extends EventListener { void edited(SchemaCellEditor editor, int row, int column); } }
30.655172
85
0.740157
692a098cace0578356d21efb648ca99d33821f2f
776
package uk.ac.ebi.fg.annotare2.web.gwt.common.shared.update; import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.SingleCellExtractAttributesRow; public class UpdateSingleCellExtractAttributesRowCommand implements ExperimentUpdateCommand { private SingleCellExtractAttributesRow row; @SuppressWarnings("unused") UpdateSingleCellExtractAttributesRowCommand() { /* used by GWT serialization */ } public UpdateSingleCellExtractAttributesRowCommand(SingleCellExtractAttributesRow row) { this.row = row; } @Override public void execute(ExperimentUpdatePerformer performer) { performer.updateSingleCellExtractAttributes(row); } @Override public boolean isCritical() { return false; } }
28.740741
94
0.751289
beffacc88725321191398cf8a70b96acc74a8946
2,905
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 投保基本信息 * * @author auto create * @since 1.0, 2021-07-06 10:27:44 */ public class ApplyBasicInfo extends AlipayObject { private static final long serialVersionUID = 6762351131333996222L; /** * 保额 */ @ApiField("amount") private String amount; /** * 投保人信息 */ @ApiField("apply_info") private InsurancePersonInfo applyInfo; /** * 受益人信息 */ @ApiField("beneficiary_info") private InsurancePersonInfo beneficiaryInfo; /** * 保险条款信息 */ @ApiField("insurance_clause") private InsuranceClauseInfo insuranceClause; /** * 保险止期 */ @ApiField("insure_end_date") private String insureEndDate; /** * 保险起期 */ @ApiField("insure_start_date") private String insureStartDate; /** * 被保人信息 */ @ApiField("insured_info") private InsurancePersonInfo insuredInfo; /** * 保费 */ @ApiField("premium") private String premium; /** * 费率,最多兼容9位小数 */ @ApiField("rate") private String rate; /** * 关联业务订单号 */ @ApiField("related_order_no") private String relatedOrderNo; public String getAmount() { return this.amount; } public void setAmount(String amount) { this.amount = amount; } public InsurancePersonInfo getApplyInfo() { return this.applyInfo; } public void setApplyInfo(InsurancePersonInfo applyInfo) { this.applyInfo = applyInfo; } public InsurancePersonInfo getBeneficiaryInfo() { return this.beneficiaryInfo; } public void setBeneficiaryInfo(InsurancePersonInfo beneficiaryInfo) { this.beneficiaryInfo = beneficiaryInfo; } public InsuranceClauseInfo getInsuranceClause() { return this.insuranceClause; } public void setInsuranceClause(InsuranceClauseInfo insuranceClause) { this.insuranceClause = insuranceClause; } public String getInsureEndDate() { return this.insureEndDate; } public void setInsureEndDate(String insureEndDate) { this.insureEndDate = insureEndDate; } public String getInsureStartDate() { return this.insureStartDate; } public void setInsureStartDate(String insureStartDate) { this.insureStartDate = insureStartDate; } public InsurancePersonInfo getInsuredInfo() { return this.insuredInfo; } public void setInsuredInfo(InsurancePersonInfo insuredInfo) { this.insuredInfo = insuredInfo; } public String getPremium() { return this.premium; } public void setPremium(String premium) { this.premium = premium; } public String getRate() { return this.rate; } public void setRate(String rate) { this.rate = rate; } public String getRelatedOrderNo() { return this.relatedOrderNo; } public void setRelatedOrderNo(String relatedOrderNo) { this.relatedOrderNo = relatedOrderNo; } }
19.761905
71
0.695009
cc18ca81eca7bc1fb9b4e04fb211bb5da8c44ab8
2,306
package com.liao.mybatisdemo.jdbc; import java.sql.*; public class JdbcDemo { private static final String SQLITE_DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false"; private static final String USER_NAME = "root"; private static final String PASSWORD = "123456"; private static final String SQL_SELECT = "select name from t_user where id=?"; private static final String SQL_INSERT = "insert into t_user(id,name) values(?,?)"; public static void main(String[] args) { insert(1, "hahaha"); String name = selectNameById(1); System.out.println(name); } /** * 获取JDBC连接 */ private static Connection getConnection() { Connection conn = null; try { Class.forName(SQLITE_DRIVER); conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } private static Integer insert(Integer id, String name) { Connection connection = getConnection(); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(SQL_INSERT); preparedStatement.setInt(1, id); preparedStatement.setString(2, name); return preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return -1; } private static String selectNameById(Integer id) { String name = null; Connection connection = getConnection(); PreparedStatement statement = null; try { statement = connection.prepareStatement(SQL_SELECT); statement.setInt(1, id); ResultSet resultSet = statement.executeQuery(); if(resultSet.next()) { name = resultSet.getString("name"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return name; } }
25.065217
123
0.64961
e86883526652c3ea3498811f6db9b04474394873
481
package org.oulipo.browser.editor.remote; import org.oulipo.streams.RemoteFileManager; import javafx.scene.Node; public class EmptyRemoteImage<S> implements RemoteImage<S> { @Override public Node createNode(RemoteFileManager fileManager) { throw new AssertionError("Unreachable code"); } @Override public String getHash() { return ""; } @Override public S getStyle() { return null; } @Override public RemoteImage<S> setStyle(S style) { return null; } }
16.033333
60
0.735967
c9e5049cf72b535c05b2fe700f8559c56ea63844
555
package io.github.riesenpilz.nmsUtilities.packet; public enum PacketType { HANDSHAKING_IN("handshaking", "server"), LOGIN_IN("login", "server"), LOGIN_OUT("login", "client"), PLAY_IN("play", "server"), PLAY_OUT("play", "client"), STATUS_IN("status", "server"), STATUS_OUT("status", "client"); private final String boundTo; private final String state; PacketType(String state, String boundTo) { this.state = state; this.boundTo = boundTo; } public String getBoundTo() { return boundTo; } public String getState() { return state; } }
24.130435
100
0.704505
50d3c5b187bfa08b8475e1a44b50625b316e28f7
7,695
/* * Copyright (c) 2020, JavaFamily Technology Corp, All Rights Reserved. * * The software and information contained herein are copyrighted and * proprietary to JavaFamily Technology Corp. This software is furnished * pursuant to a written license agreement and may be used, copied, * transmitted, and stored only in accordance with the terms of such * license and with the inclusion of the above copyright notice. Please * refer to the file "COPYRIGHT" for further copyright and licensing * information. This software and information or any other copies * thereof may not be provided or otherwise made available to any other * person. */ package club.javafamily.runner.service.impl; import club.javafamily.commons.enums.*; import club.javafamily.runner.annotation.Audit; import club.javafamily.runner.annotation.AuditObject; import club.javafamily.runner.common.MessageException; import club.javafamily.runner.dao.RoleDao; import club.javafamily.runner.domain.*; import club.javafamily.runner.enums.ResourceEnum; import club.javafamily.runner.service.*; import club.javafamily.runner.util.*; import club.javafamily.runner.web.em.settings.model.*; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; @Service("roleService") public class RoleServiceImpl implements RoleService { @Autowired public RoleServiceImpl(UserHandler userHandler, LogService logService, RoleDao roleDao) { this.userHandler = userHandler; this.logService = logService; this.roleDao = roleDao; } @Transactional(readOnly = true) @Override public List<Role> getRoles() { return roleDao.getAll(); } @Transactional(readOnly = true) @Override public List<ResourceItemSettingModel> getRolesByResource(Integer resourceId) { ResourceEnum resource = ResourceEnum.parse(resourceId); if(resource == null || resource == ResourceEnum.Unknown) { LOGGER.info("Resource is not found: {}", resourceId); return null; } List<Role> roles = getRoles(); Map<Integer, ResourceItemSettingModel> map = new HashMap<>(); // role id for(Role role : roles) { for(Permission permission : role.getPermissions()) { if(!Objects.equals(permission.getResource(), resourceId)) { continue; } EnumSet<PermissionEnum> permissionEnums = SecurityUtil.parsePermissionOperator(permission.getOperator()); map.computeIfAbsent(role.getId(), (k) -> { ResourceItemSettingModel item = new ResourceItemSettingModel(); item.setId(permission.getId()); item.setRoleId(role.getId()); item.setName(role.getName()); item.setType(ResourceSettingType.Role); item.setRead(permissionEnums.contains(PermissionEnum.READ)); item.setWrite(permissionEnums.contains(PermissionEnum.WRITE)); item.setDelete(permissionEnums.contains(PermissionEnum.DELETE)); item.setAccess(permissionEnums.contains(PermissionEnum.ACCESS)); item.setAdmin(permissionEnums.contains(PermissionEnum.ADMIN)); return item; }); } } return new ArrayList<>(map.values()); } @Transactional(readOnly = true) @Override public Role getRole(Integer id) { Role role = roleDao.get(id); if(role == null) { LOGGER.info("Role is not found: {}", id); } return role; } @Transactional(readOnly = true) @Override public Role getRoleByName(String name) { return roleDao.getByName(name); } @Audit( value = ResourceEnum.Role, actionType = ActionType.DELETE ) @Transactional @Override public void deleteRole(@AuditObject("getName()") Role role) { roleDao.delete(role); } @Transactional @Override public void deleteRoles(Integer[] ids) { if(ArrayUtils.isEmpty(ids)) { return; } Role role; for(Integer id : ids) { role = roleDao.get(id); if(role == null) { throw new MessageException(I18nUtil.getString("em.role.idRoleNotExist", id)); } roleDao.delete(role); Log log = new Log(); log.setResource(ResourceEnum.Role.getLabel() + ":" + role.getName()); log.setAction(ActionType.DELETE.getLabel()); log.setCustomer(userHandler.getAuditUser()); log.setDate(new Date()); logService.insertLog(log); } } @Audit( value = ResourceEnum.Role ) @Transactional @Override public Integer addRole(@AuditObject("getName()") Role role) { return roleDao.insert(role); } @Audit( value = ResourceEnum.Role, actionType = ActionType.MODIFY ) @Transactional @Override public void updateRole(@AuditObject("getName()") Role role) { roleDao.update(role); } @Audit( value = ResourceEnum.Role, actionType = ActionType.MODIFY ) @Transactional @Override public void updateRole(@AuditObject("getRole().getName()") RoleEditViewModel model) { RoleVo roleModel = model.getRole(); if(roleModel.getId() == null) { LOGGER.warn("Role not found."); return; } Integer id = roleModel.getId(); Role role = getRole(id); // update role info roleModel.updateDomain(role); // update role users RoleAssignedToModel assignedToModel = model.getAssignedToModel(); // TODO update assignedTo model updateRole(role); } @Transactional @Override public void insertPermission(Integer roleId, Permission permission) { Role role = getRole(roleId); if(roleId == null) { return; } Log log = createLog(role); try { Set<Permission> permissions = role.getPermissions(); if(permissions == null) { permissions = new HashSet<>(); role.setPermissions(permissions); } permissions.add(permission); updateRole(role); } catch(Exception e) { log.setMessage("Failed: " + e.getMessage()); throw e; } finally { logService.insertLog(log); } } private Log createLog(Role role) { Log log = new Log(); try { log.setAction(ActionType.Authorization.getLabel()); log.setDate(new Date()); log.setResource(ResourceEnum.Role.getLabel() + ":" + role.getName()); log.setCustomer(userHandler.getAuditUser()); log.setIp(WebMvcUtil.getIP()); } catch(Exception ex) { LOGGER.error("Create Log obj error", ex); } return log; } @Transactional @Override public void clearPermission(Integer roleId) { Role role = getRole(roleId); if(roleId == null) { return; } Log log = createLog(role); try { role.clearPermissions(); updateRole(role); } catch (Exception e) { log.fillErrorMessage(e); throw e; } finally { logService.insertLog(log); } } private final UserHandler userHandler; private final LogService logService; private final RoleDao roleDao; private static final Logger LOGGER = LoggerFactory.getLogger(RoleServiceImpl.class); }
27.09507
89
0.636387
bbe899bd28eef56b6d8ca5bb5233f4c55b024140
2,127
/* * Copyright 2015 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.core.jms; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.validation.constraints.NotBlank; import com.adaptris.annotation.AdapterComponent; import com.adaptris.annotation.ComponentProfile; import com.adaptris.annotation.DisplayOrder; import com.adaptris.core.CoreException; import com.thoughtworks.xstream.annotations.XStreamAlias; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * <p> * JMS Queue implementation of {@link com.adaptris.core.AdaptrisMessageConsumer} * </p> * * @config jms-queue-consumer * */ @XStreamAlias("jms-queue-consumer") @AdapterComponent @ComponentProfile(summary = "Listen for JMS messages on the specified queue", tag = "consumer,jms", recommended = {JmsConnection.class}) @DisplayOrder( order = {"queue", "messageSelector", "acknowledgeMode", "messageTranslator"}) @NoArgsConstructor public class PtpConsumer extends JmsConsumerImpl { /** * The JMS Queue * */ @Getter @Setter @NotBlank private String queue; @Override protected String configuredEndpoint() { return getQueue(); } @Override protected MessageConsumer createConsumer() throws JMSException, CoreException { VendorImplementation jmsImpl = retrieveConnection(JmsConnection.class).configuredVendorImplementation(); return jmsImpl.createQueueReceiver(getQueue(), getMessageSelector(), this); } public PtpConsumer withQueue(String queue) { setQueue(queue); return this; } }
27.623377
99
0.752233
cec27cfceaf526e136c918b7d6ed79690e8eb637
227
package com.camnter.gradle.plugin.toytime; import java.io.Serializable; /** * Copy from gradle 4.1 */ public interface TimeProvider extends Serializable { long getCurrentTime(); long getCurrentTimeForDuration(); }
17.461538
52
0.744493
48a25667dee5340d9f582a21b41c13a887e0b6ce
2,902
/* * Copyright 2020 Krzysztof Slusarski * * 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.krzysztofslusarski.asyncprofiler; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.Comparator; import java.util.List; import java.util.function.BiPredicate; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPOutputStream; import lombok.extern.slf4j.Slf4j; @Slf4j class ContinuousAsyncProfilerCompressor implements Runnable { private final Path continuousDir; private final BiPredicate<Path, BasicFileAttributes> predicate; private final Comparator<Path> oldestFirst; public ContinuousAsyncProfilerCompressor(ContinuousAsyncProfilerNotManageableProperties notManageableProperties) { this.continuousDir = Paths.get(notManageableProperties.getContinuousOutputDir()); this.predicate = (p, ignore) -> p.getFileName().toString().endsWith("jfr"); this.oldestFirst = (o1, o2) -> { long firstModified = o1.toFile().lastModified(); long secondModified = o2.toFile().lastModified(); return Long.compare(firstModified, secondModified); }; } @Override public void run() { try (Stream<Path> pathStream = Files.find(continuousDir, 1, predicate)) { List<Path> notCompressedFiles = pathStream .sorted(oldestFirst) .collect(Collectors.toList()); int counter = notCompressedFiles.size() - 2; for (Path source : notCompressedFiles) { if (counter <= 0) { break; } Path target = Paths.get(source.toAbsolutePath().toString() + ".gz"); log.info("Compressing: {}", source); compressGzip(source, target); Files.delete(source); counter--; } } catch (IOException e) { log.error("Some IO failed", e); } } public static void compressGzip(Path source, Path target) throws IOException { try (GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream(target.toFile()))) { Files.copy(source, gos); } } }
38.184211
118
0.668504
cb9f42782ee54ec976209f5fdcc4222fcf4839d5
602
package gsim; /**http://graphstream-project.org/doc/Tutorials/Storing-retrieving-and-displaying-data-in-graphs_1.0/ * Edge Details Struct for importing of graph * @author brandon * */ public class ImportEdgeDetails { public String v1; public String v2; public String e; /** * Constructor * @param v1 - From vertex id * @param v2 - To vertex id * @param e - Edge id */ public ImportEdgeDetails(String v1, String v2, String e) { this.v1 = v1; this.v2 = v2; this.e = e; } /** * toString function */ public String toString() { return v1 + "->" + v2 + ":" + e; } }
17.2
101
0.639535
26401b40c74ec6165d55d5fc5fedc1cff5867fcb
4,190
/** * Copyright (C) 2006-2021 Talend Inc. - www.talend.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.talend.sdk.component.runtime.manager; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.nio.file.Path; import java.util.HashMap; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.talend.sdk.component.runtime.manager.asm.PluginGenerator; import org.talend.sdk.component.runtime.output.ProcessorImpl; class ConfigurationMigrationTest { private final PluginGenerator pluginGenerator = new PluginGenerator(); @Test void run(@TempDir final Path temporaryFolder) throws Exception { final File pluginFolder = new File(temporaryFolder.toFile(), "test-plugins_" + UUID.randomUUID().toString()); pluginFolder.mkdirs(); final File jar = pluginGenerator.createChainPlugin(temporaryFolder.toFile(), "comps.jar"); try (final ComponentManager manager = new ComponentManager(new File("target/test-dependencies"), "META-INF/test/dependencies", "org.talend.test:type=plugin,value=%s")) { manager.addPlugin(jar.getAbsolutePath()); { final Object nested = ProcessorImpl.class .cast(manager.findProcessor("chain", "configured1", 0, new HashMap<String, String>() { { put("config.__version", "-1"); } }).orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); assertNotNull(config); assertEquals("ok", get(config, "getName")); } { final Object nested = ProcessorImpl.class .cast(manager.findProcessor("chain", "configured2", 0, new HashMap<String, String>() { { put("config.__version", "0"); put("value.__version", "-1"); } }).orElseThrow(IllegalStateException::new)) .getDelegate(); assertEquals("set", get(nested, "getValue")); final Object config = get(nested, "getConfig"); assertNotNull(config); assertEquals("ok", get(config, "getName")); } { final Object nested = ProcessorImpl.class .cast(manager.findProcessor("chain", "migrationtest", -1, new HashMap<String, String>() { { put("config.__version", "1"); put("config.datastore.__version", "1"); } }).orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); assertNotNull(config); assertEquals("dataset", get(config, "getName")); final Object datastore = get(config, "getDatastore"); assertNotNull(datastore); assertEquals("datastore", get(datastore, "getName")); assertEquals("yes", get(datastore, "getComponent")); } } } private Object get(final Object root, final String getter) throws Exception { return root.getClass().getMethod(getter).invoke(root); } }
41.485149
117
0.575656
0352715047e0e2b0e26603891577e2620bf0f135
475
package com.zsun.java.tij.chapter10.innerclasses; /** * Created by zsun. * DateTime: 2019/05/05 13:15 */ public class Parcel8 { public Wrapping wrapping(int x) { return new Wrapping(x) { public int value() { return super.value() * 47; } }; } public static void main(String[] args) { Parcel8 p = new Parcel8(); Wrapping w = p.wrapping(10); System.out.println(w.value()); } }
21.590909
49
0.545263
71f64814d6216544e61981985084f67c7f443477
3,816
/** * */ package de.fh_dortmund.inf.cw.phaseten.server.entities; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; /** * Lobby Entity. * * @author Dennis Schöneborn * @author Marc Mettke * @author Daniela Kaiser * @author Sebastian Seitz * @author Björn Merschmeier */ @NamedQueries({ @NamedQuery(name = Lobby.LOBBY_SELECT_LOBBY_BY_USER_ID, query = "SELECT l FROM Lobby l " + "JOIN Player p " + "WHERE p.id = :playerId"), @NamedQuery(name = Lobby.LOBBY_SELECT_LATEST, query = "SELECT l FROM Lobby l"), @NamedQuery(name = Lobby.SELECT_LOBBY_BY_SPECTATOR_ID, query = "SELECT l FROM Lobby l " + "JOIN Spectator s " + "WHERE s.id = :spectatorId"), @NamedQuery(name = Lobby.LOBBY_FIND_BY_ID, query = "SELECT l FROM Lobby l WHERE l.id = :lobbyId") }) @Entity public class Lobby implements Serializable { protected static final String LOBBY_FIND_BY_ID = "lobby.findById"; protected static final String SELECT_LOBBY_BY_SPECTATOR_ID = "selectLobbyBySpectatorId"; protected static final String LOBBY_SELECT_LATEST = "lobby.selectLatest"; protected static final String LOBBY_SELECT_LOBBY_BY_USER_ID = "lobby.selectLobbyByUserId"; /** * */ private static final long serialVersionUID = 5336567507324327686L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @OneToMany(mappedBy = "lobby") @JoinColumn(nullable = false) private Set<Player> players; @OneToMany @JoinTable private Set<Spectator> spectators; /** * Konstruktor. */ public Lobby() { this.players = new HashSet<>(); this.spectators = new HashSet<>(); } /** * max. Anzahl Spieler erreicht * * @return isFull */ public boolean isFull() { if (this.players.size() < Game.MAX_PLAYER) { return false; } return true; } /** * Liefert Anazhl Spieler. * * @return size */ public int getNumberOfPlayers() { return this.players.size(); } /** * Liefert Anzahl Spectator. * * @return size */ public int getNumberOfSpectators() { return this.spectators.size(); } /** * Fügt Spieler hinzu, wenn möglich. * * @param player */ public void addPlayer(Player player) { if (this.players.size() < Game.MAX_PLAYER) { this.players.add(player); player.setLobby(this); } } /** * Fügt Spectator hinzu. * * @param spectator */ public void addSpectator(Spectator spectator) { this.spectators.add(spectator); } /** * entfernt Spieler. * * @param player */ public void removePlayer(Player player) { this.players.remove(player); player.removeLobby(); } /** * entfernt Spectator. * * @param spectator */ public void removeSpectator(Spectator spectator) { this.spectators.remove(spectator); } /** * Liefert spieler * * @return players */ public Set<Player> getPlayers() { return players; } /** * Liefert Spectator. * * @return */ public Set<Spectator> getSpectators() { return spectators; } /** * Vorbereiten auf Schließen */ public void preRemove() { removeSpectators(); removePlayers(); } /** * Entfernt Spieler. */ private void removePlayers() { for (Player p : new ArrayList<>(players)) { removePlayer(p); } } /** * Entfernt Spectator. */ public void removeSpectators() { for (Spectator s : new ArrayList<>(spectators)) { removeSpectator(s); } } /** * Liefert id * * @return id */ public long getId() { return id; } }
19.370558
111
0.684486
0a558c2dd07ef02623305aa203b148d673873e95
12,634
package wtf.cattyn.ferret.api.feature.script.lua.utils; import com.google.common.io.Files; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.gui.DrawableHelper; import net.minecraft.client.render.*; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Box; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3f; import wtf.cattyn.ferret.common.Globals; import wtf.cattyn.ferret.common.impl.Vec2d; import java.awt.*; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class LuaRenderer extends DrawableHelper implements Globals { private static LuaRenderer instance; LuaRenderer() { } public void text(MatrixStack stack, String text, Vec2d vec2d, Color color) { mc.textRenderer.draw(stack, text, ( float ) vec2d.x(), ( float ) vec2d.y(), color.hashCode()); } public void text(MatrixStack stack, Text text, Vec2d vec2d, Color color) { mc.textRenderer.draw(stack, text, ( float ) vec2d.x(), ( float ) vec2d.y(), color.hashCode()); } public void textWithShadow(MatrixStack stack, String text, Vec2d vec2d, Color color) { mc.textRenderer.drawWithShadow(stack, text, ( float ) vec2d.x(), ( float ) vec2d.y(), color.hashCode()); } public void textWithShadow(MatrixStack stack, Text text, Vec2d vec2d, Color color) { mc.textRenderer.drawWithShadow(stack, text, ( float ) vec2d.x(), ( float ) vec2d.y(), color.hashCode()); } public void rect(MatrixStack stack, Vec2d from, Vec2d to, Color color) { int x1 = ( int ) from.x(), x2 = ( int ) to.x(), y1 = ( int ) from.y(), y2 = ( int ) to.y(); this.drawHorizontalLine(stack, x1, x2, y1, color.hashCode()); this.drawVerticalLine(stack, x2, y1, y2, color.hashCode()); this.drawHorizontalLine(stack, x1, x2, y2, color.hashCode()); this.drawVerticalLine(stack, x1, y1, y2, color.hashCode()); } public void rectFilled(MatrixStack stack, Vec2d from, Vec2d to, Color color) { DrawableHelper.fill(stack, ( int ) from.x(), ( int ) from.y(), ( int ) to.x(), ( int ) to.y(), color.hashCode()); } public void rectFilledFade(MatrixStack stack, Vec2d from, Vec2d to, Color color1, Color color2) { this.fillGradient(stack, ( int ) from.x(), ( int ) from.y(), ( int ) to.x(), ( int ) to.y(), color1.hashCode(), color2.hashCode()); } public void line(MatrixStack stack, Vec2d from, Vec2d to, Color color) { float i2 = (float)(color.hashCode() >> 24 & 0xFF) / 255.0f; float f = (float)(color.hashCode() >> 16 & 0xFF) / 255.0f; float g = (float)(color.hashCode() >> 8 & 0xFF) / 255.0f; float h = (float)(color.hashCode() & 0xFF) / 255.0f; BufferBuilder bufferBuilder = Tessellator.getInstance().getBuffer(); RenderSystem.enableBlend(); RenderSystem.disableTexture(); RenderSystem.defaultBlendFunc(); RenderSystem.setShader(GameRenderer::getPositionColorShader); bufferBuilder.begin(VertexFormat.DrawMode.LINES, VertexFormats.POSITION_COLOR); bufferBuilder.vertex(stack.peek().getPositionMatrix(), ( float ) from.x(), ( float ) from.y(), 0.0f).color(f, g, h, i2).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), ( float ) to.x(), ( float ) to.y(), 0.0f).color(f, g, h, i2).next(); bufferBuilder.end(); BufferRenderer.draw(bufferBuilder); RenderSystem.enableTexture(); RenderSystem.disableBlend(); } public int width(String text) { return mc.textRenderer.getWidth(text); } public int width(Text text) { return mc.textRenderer.getWidth(text); } public double windowWidth() { return mc.getWindow().getScaledWidth(); } public double windowHeight() { return mc.getWindow().getScaledHeight(); } //3D public void drawBoxFilled(MatrixStack stack, Box box, Color c) { float minX = (float) (box.minX - mc.getEntityRenderDispatcher().camera.getPos().getX()); float minY = (float) (box.minY - mc.getEntityRenderDispatcher().camera.getPos().getY()); float minZ = (float) (box.minZ - mc.getEntityRenderDispatcher().camera.getPos().getZ()); float maxX = (float) (box.maxX - mc.getEntityRenderDispatcher().camera.getPos().getX()); float maxY = (float) (box.maxY - mc.getEntityRenderDispatcher().camera.getPos().getY()); float maxZ = (float) (box.maxZ - mc.getEntityRenderDispatcher().camera.getPos().getZ()); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferBuilder = tessellator.getBuffer(); setup3D(); RenderSystem.setShader(GameRenderer::getPositionColorShader); bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, minY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), maxX, maxY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, minZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, minY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, maxZ).color(c.getRGB()).next(); bufferBuilder.vertex(stack.peek().getPositionMatrix(), minX, maxY, minZ).color(c.getRGB()).next(); tessellator.draw(); clean3D(); } public void drawBoxFilled(MatrixStack stack, Vec3d vec, Color c) { drawBoxFilled(stack, Box.from(vec), c); } public void drawBoxFilled(MatrixStack stack, BlockPos bp, Color c) { drawBoxFilled(stack, new Box(bp), c); } public void drawBox(MatrixStack stack, Box box, Color c, double lineWidth) { float minX = (float) (box.minX - mc.getEntityRenderDispatcher().camera.getPos().getX()); float minY = (float) (box.minY - mc.getEntityRenderDispatcher().camera.getPos().getY()); float minZ = (float) (box.minZ - mc.getEntityRenderDispatcher().camera.getPos().getZ()); float maxX = (float) (box.maxX - mc.getEntityRenderDispatcher().camera.getPos().getX()); float maxY = (float) (box.maxY - mc.getEntityRenderDispatcher().camera.getPos().getY()); float maxZ = (float) (box.maxZ - mc.getEntityRenderDispatcher().camera.getPos().getZ()); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferBuilder = tessellator.getBuffer(); setup3D(); RenderSystem.lineWidth(( float ) lineWidth); RenderSystem.setShader(GameRenderer::getRenderTypeLinesShader); RenderSystem.defaultBlendFunc(); bufferBuilder.begin(VertexFormat.DrawMode.LINES, VertexFormats.LINES); WorldRenderer.drawBox(stack, bufferBuilder, minX, minY, minZ, maxX, maxY, maxZ, c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, c.getAlpha() / 255f); tessellator.draw(); clean3D(); } public void drawBox(MatrixStack stack, Vec3d vec, Color c, double lineWidth) { drawBox(stack, Box.from(vec), c, lineWidth); } public void drawBox(MatrixStack stack, BlockPos bp, Color c, double lineWidth) { drawBox(stack, new Box(bp), c, lineWidth); } public void drawSemi2dRect(Vec3d pos, Vec2d offset, Vec2d offset2, double scale, Color color) { MatrixStack matrices = matrixFrom(pos); Camera camera = mc.gameRenderer.getCamera(); matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(-camera.getYaw())); matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(camera.getPitch())); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); matrices.translate(offset.x(), offset.y(), 0); matrices.scale(-0.025f * (float) scale, -0.025f * (float) scale, 1); int halfWidth = (int) (offset2.x() / 2); VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer()); DrawableHelper.fill(matrices, -halfWidth, 0, (int) (offset2.x() - halfWidth), ( int ) offset2.y(), color.getRGB()); } public void drawSemi2dText(String text, Vec3d pos, Vec2d offset, Vec2d offset2, double scale, Color color, boolean shadow) { MatrixStack matrices = matrixFrom(pos); Camera camera = mc.gameRenderer.getCamera(); matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(-camera.getYaw())); matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(camera.getPitch())); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); matrices.translate(offset.x(), offset.y(), 0); matrices.scale(-0.025f * (float) scale, -0.025f * (float) scale, 1); VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer()); if (shadow) { mc.textRenderer.drawWithShadow(matrices, text, ( float ) offset2.x(), ( float ) offset2.y(), color.getRGB()); } else { mc.textRenderer.draw(matrices, text, ( float ) offset2.x(), ( float ) offset2.y(), color.getRGB()); } immediate.draw(); RenderSystem.disableBlend(); } public static MatrixStack matrixFrom(Vec3d pos) { MatrixStack matrices = new MatrixStack(); Camera camera = mc.gameRenderer.getCamera(); matrices.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(camera.getPitch())); matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(camera.getYaw() + 180.0F)); matrices.translate(pos.getX() - camera.getPos().x, pos.getY() - camera.getPos().y, pos.getZ() - camera.getPos().z); return matrices; } public void setup() { RenderSystem.disableTexture(); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); } public void setup3D() { setup(); RenderSystem.disableDepthTest(); RenderSystem.depthMask(false); RenderSystem.disableCull(); } public void clean() { RenderSystem.disableBlend(); RenderSystem.enableTexture(); } public void clean3D() { clean(); RenderSystem.enableDepthTest(); RenderSystem.depthMask(true); RenderSystem.enableCull(); } public static LuaRenderer getDefault() { if(instance == null) instance = new LuaRenderer(); return instance; } }
48.592308
169
0.665743
e19abd761d422d574c1592490351eae8a0ce7925
4,224
package on_tool.gui.dialogo; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.util.Arrays; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class PainelFonte extends JPanel implements ListSelectionListener { JList lsNome; JList lsTamanho; JList lsEstilo; String[] nomes; String[] tamanhos; String[] estilos; JTextArea txExemplo; public static int OK = JOptionPane.OK_OPTION; public static int CANCEL = JOptionPane.CANCEL_OPTION; public PainelFonte() { super(); construir(); } public PainelFonte(Font f) { super(); construir(); mudaFonte(f); } protected void construir() { this.setLayout(new BorderLayout()); nomes = GraphicsEnvironment.getLocalGraphicsEnvironment( ).getAvailableFontFamilyNames(); String[] tamanhos = {"8", "10", "12", "14", "18", "24", "36"}; this.tamanhos = tamanhos; String[] estilos = {"Normal", "Negrito", "It\u00e1lico"}; this.estilos = estilos; FlowLayout layout = new FlowLayout(FlowLayout.CENTER); layout.setHgap(10); JPanel p = new JPanel(layout); JPanel p1 = new JPanel(new BorderLayout()); p1.add(new JLabel("Fonte:"), BorderLayout.PAGE_START); lsNome = new JList(nomes); lsNome.setSelectedIndex(0); lsNome.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); lsNome.setVisibleRowCount(7); lsNome.addListSelectionListener(this); p1.add(new JScrollPane(lsNome), BorderLayout.CENTER); p.add(p1); p1 = new JPanel(new BorderLayout()); p1.add(new JLabel("Tamanho:"), BorderLayout.PAGE_START); lsTamanho = new JList(tamanhos); lsTamanho.setSelectedIndex(0); lsTamanho.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); lsTamanho.setVisibleRowCount(7); lsTamanho.addListSelectionListener(this); p1.add(new JScrollPane(lsTamanho), BorderLayout.CENTER); p.add(p1); p1 = new JPanel(new BorderLayout()); p1.add(new JLabel("Estilo:"), BorderLayout.PAGE_START); lsEstilo = new JList(estilos); lsEstilo.setSelectedIndex(0); lsEstilo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); lsEstilo.setVisibleRowCount(7); lsEstilo.addListSelectionListener(this); p1.add(new JScrollPane(lsEstilo), BorderLayout.CENTER); p.add(p1); this.add(p, BorderLayout.PAGE_START); p = new JPanel(); p.setBorder(BorderFactory.createTitledBorder( "Exemplo:")); txExemplo = new JTextArea(); txExemplo.setPreferredSize(new Dimension(200, 50)); txExemplo.append("AaBbYyZz"); p.add(txExemplo); this.add(p, BorderLayout.PAGE_END); } public void mudaFonte(Font f) { int i = Arrays.binarySearch(nomes, f.getName()); if (i < 0) i = 0; lsNome.setSelectedIndex(i); lsNome.ensureIndexIsVisible(i); i = Arrays.binarySearch(tamanhos, String.valueOf(f.getSize())); if (i < 0) i = 0; lsTamanho.setSelectedIndex(i); lsTamanho.ensureIndexIsVisible(i); switch (f.getStyle()) { case Font.BOLD: lsEstilo.setSelectedIndex(1); break; case Font.ITALIC: lsEstilo.setSelectedIndex(2); break; default: lsEstilo.setSelectedIndex(0); break; } txExemplo.setFont(f); } public Font pegaFonte() { int estilo = 0; switch (lsEstilo.getSelectedIndex()) { case 1: estilo = Font.BOLD; break; case 2: estilo = Font.ITALIC; break; default: estilo = Font.PLAIN; break; } return new Font( (String)lsNome.getSelectedValue(), estilo, Integer.parseInt((String)lsTamanho.getSelectedValue())); } public void valueChanged(ListSelectionEvent evt) { int estilo = 0; switch (lsEstilo.getSelectedIndex()) { case 1: estilo = Font.BOLD; break; case 2: estilo = Font.ITALIC; break; default: estilo = Font.PLAIN; break; } txExemplo.setFont(new Font( (String)lsNome.getSelectedValue(), estilo, Integer.parseInt((String)lsTamanho.getSelectedValue()))); } }
25.756098
66
0.717803
89207f819a08d9a89345a4b5486bb840fa551963
2,279
/* * Copyright (C) 2014 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.google.gct.idea.elysium; import com.google.gct.idea.ui.GoogleCloudToolsIcons; import com.intellij.ui.components.JBLabel; import org.jetbrains.annotations.NotNull; import java.awt.Color; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; /** * Displays UI similar to "loading..." when an elysium call is in progress. */ class ProjectSelectorLoadingItem extends JPanel { private JLabel myProgressIcon; public ProjectSelectorLoadingItem(@NotNull Color backgroundNonSelectionColor, @NotNull Color textNonSelectionColor) { this.setLayout(new FlowLayout()); this.setOpaque(false); setBorder(BorderFactory.createEmptyBorder(2, 15, 2, 0)); JLabel loadText = new JBLabel(); loadText.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0)); loadText.setHorizontalAlignment(SwingConstants.LEFT); loadText.setVerticalAlignment(SwingConstants.CENTER); loadText.setOpaque(false); loadText.setBackground(backgroundNonSelectionColor); loadText.setForeground(textNonSelectionColor); loadText.setText("Loading..."); myProgressIcon = new JBLabel(); myProgressIcon.setOpaque(false); this.add(myProgressIcon); this.add(loadText); } // This is called to animate the spinner. It snaps a frame of the spinner based on current timer ticks. public void snap() { long currentMilliseconds = System.nanoTime() / 1000000; int frame = (int)(currentMilliseconds / 100) % GoogleCloudToolsIcons.STEP_ICONS.length; myProgressIcon.setIcon(GoogleCloudToolsIcons.STEP_ICONS[frame]); } }
34.530303
119
0.756911
97a6015af3973616a52f57db5e65658b721e6ae3
5,143
package com.ltdd.calculator; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import androidx.fragment.app.Fragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; public class LengthFragment extends Fragment { private Spinner spUnit; private EditText txtInput; private TextView txtFeet, txtInches, txtCm, txtM, txtKm, txtMm; private Button btConvert; private ArrayList<String> listUnitName; double r1, r2, r3, r4, r5, r6; public LengthFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_length, container, false); FloatingActionButton btReset = view.findViewById(R.id.btReset); btReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txtInput.getText().clear(); txtInches.setText(""); txtFeet.setText(""); txtMm.setText(""); txtCm.setText(""); txtM.setText(""); txtKm.setText(""); Snackbar.make(view, "Clear all your results", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); Mapping(view); FillData(); CreateBtnFunction(); return view; } private void Mapping(@NotNull View view) { spUnit = view.findViewById(R.id.spUnit); txtInput = view.findViewById(R.id.txtValue); txtFeet = view.findViewById(R.id.txtFeet); txtInches = view.findViewById(R.id.txtInches); txtCm = view.findViewById(R.id.txtCm); txtM = view.findViewById(R.id.txtM); txtKm = view.findViewById(R.id.txtKm); txtMm = view.findViewById(R.id.txtMm); listUnitName = new ArrayList<String>(Arrays.asList("feet", "ich", "mm", "cm", "m", "km")); btConvert = view.findViewById(R.id.btConvert); } private void CreateBtnFunction() { btConvert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Convert(); } }); } private void Convert() { double temp = Double.parseDouble(txtInput.getText().toString()); String unit = spUnit.getSelectedItem().toString(); if (unit == "ich"){ r1 = (temp * 1); //inches r2 = (temp * 0.083); //feet r3 = (temp * 25.4); //mm r4 = (temp * 2.54); //cm r5 = (temp * 0.0254); //m r6 = (temp * 0.0000254); //km } else if (unit == "feet"){ r1 = (temp * 12); //inches r2 = (temp * 1); //feet r3 = (temp * 304.8); //mm r4 = (temp * 30.48); //cm r5 = (temp * 0.3048); //m r6 = (temp * 0.0003048); //km }if (unit == "mm"){ r1 = (temp * 0.0393701); //inches r2 = (temp * 0.00328084); //feet r3 = (temp * 1); //mm r4 = (temp * 0.1); //cm r5 = (temp * 0.001); //m r6 = (temp * 0.000001); //km } else if (unit == "cm") { r1 = (temp * 0.393701); //inches r2 = (temp * 0.0328084); //feet r3 = (temp * 10); //mm r4 = (temp * 1); //cm r5 = (temp * 0.01); //m r6 = (temp * 0.00001); //km } else if (unit == "m") { r1 = (temp * 39.3700787); //inches r2 = (temp * 3.2808399 ); //feet r3 = (temp * 10000); //mm r4 = (temp * 100); //cm r5 = (temp * 1); //m r6 = (temp * 0.001); //km } else if (unit == "km") { r1 = (temp * 39.3701); //inches r2 = (temp * 3.28084); //feet r3 = (temp * 1000000); //mm r4 = (temp * 100000); //cm r5 = (temp * 1000); //m r6 = (temp * 1); //km } txtInches.setText(String.valueOf(r1)+" inches"); txtFeet.setText(String.valueOf(r2)+" feet"); txtMm.setText(String.valueOf(r3)+" mm"); txtCm.setText(String.valueOf(r4)+" cm"); txtM.setText(String.valueOf(r5)+" m"); txtKm.setText(String.valueOf(r6)+" km"); } private void FillData() { ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, listUnitName); arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spUnit.setAdapter(arrayAdapter); } }
35.468966
119
0.550846
76ac82f900fe886ecd79d457ee4c0ab3b86afbb6
1,731
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core; /** * Exception thrown when the Constants class is asked for an invalid * constant name. * @author Rod Johnson * @since 28-Apr-2003 * @see org.springframework.core.Constants */ public class ConstantException extends IllegalArgumentException { /** * Thrown when an invalid constant name is requested. * @param className name of the class containing the constant definitions * @param field invalid constant name * @param message description of the problem */ public ConstantException(String className, String field, String message) { super("Field '" + field + "' " + message + " in class [" + className + "]"); } /** * Thrown when an invalid constant value is looked up. * @param className name of the class containing the constant definitions * @param namePrefix prefix of the searched constant names * @param value the looked up constant value */ public ConstantException(String className, String namePrefix, Object value) { super("No '" + namePrefix + "' field with value '" + value + "' found in class [" + className + "]"); } }
35.326531
103
0.721548
d483b101e4d81c48d0444404349efddb6bb82e74
12,224
/* * 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. */ /* * JFXApplicationClassChooser.java * * Created on 18.8.2011, 14:26:27 */ package org.netbeans.modules.javafx2.project.ui; import java.awt.Component; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.source.ClasspathInfo; import org.netbeans.api.java.source.CompilationController; import org.netbeans.api.java.source.JavaSource; import org.netbeans.api.java.source.ScanUtils; import org.netbeans.api.java.source.SourceUtils; import org.netbeans.api.java.source.Task; import org.netbeans.api.project.Project; import org.netbeans.modules.java.api.common.project.ProjectProperties; import org.netbeans.modules.javafx2.project.JFXProjectProperties; import org.netbeans.modules.javafx2.project.JFXProjectUtils; import org.netbeans.spi.project.support.ant.PropertyEvaluator; import org.openide.awt.MouseUtils; import org.openide.filesystems.FileObject; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; /** * * @author Petr Somol * @author Milan Kubec * @author Jiri Rechtacek */ public class JFXApplicationClassChooser extends javax.swing.JPanel { private static final RequestProcessor RP = new RequestProcessor(JFXApplicationClassChooser.class); private static final Logger LOG = Logger.getLogger(JFXApplicationClassChooser.class.getName()); /*test*/ static final String LOG_INIT = "INIT"; //NOI18N /*test*/ static final String LOG_MAIN_CLASSES = "MAIN-CLASSES: {0} SCAN: {1}"; //NOI18N private final PropertyEvaluator evaluator; private final Project project; private ChangeListener changeListener; private final boolean isFXinSwing; /** Creates new form JFXApplicationClassChooser */ public JFXApplicationClassChooser(final @NonNull Project p, final @NonNull PropertyEvaluator pe) { this.evaluator = pe; this.project = p; this.isFXinSwing = JFXProjectUtils.isFXinSwingProject(p); initComponents(); if(!SourceUtils.isScanInProgress()) labelScanning.setVisible(false); listAppClasses.setCellRenderer(new AppClassRenderer()); initClassesView(); initClassesModel(); } /** 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() { java.awt.GridBagConstraints gridBagConstraints; labelAppClasses = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); listAppClasses = new javax.swing.JList(); labelScanning = new javax.swing.JLabel(); setPreferredSize(new java.awt.Dimension(380, 300)); setLayout(new java.awt.GridBagLayout()); labelAppClasses.setLabelFor(listAppClasses); org.openide.awt.Mnemonics.setLocalizedText(labelAppClasses, org.openide.util.NbBundle.getMessage(JFXApplicationClassChooser.class, "LBL_JFXApplicationClassChooser.labelAppClasses.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 2, 10); add(labelAppClasses, gridBagConstraints); labelAppClasses.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(JFXApplicationClassChooser.class, "AN_JFXApplicationClassChooser.labelAppClasses.text")); // NOI18N labelAppClasses.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(JFXApplicationClassChooser.class, "AD_JFXApplicationClassChooser.labelAppClasses.text")); // NOI18N jScrollPane1.setViewportView(listAppClasses); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); add(jScrollPane1, gridBagConstraints); labelScanning.setFont(labelScanning.getFont().deriveFont((labelScanning.getFont().getStyle() | java.awt.Font.ITALIC), labelScanning.getFont().getSize()+1)); labelScanning.setText(org.openide.util.NbBundle.getMessage(JFXApplicationClassChooser.class, "LBL_ChooseMainClass_SCANNING_MESSAGE")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 10, 0, 0); add(labelScanning, gridBagConstraints); labelScanning.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(JFXApplicationClassChooser.class, "LBL_ChooseMainClass_SCANNING_MESSAGE")); // NOI18N }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel labelAppClasses; private javax.swing.JLabel labelScanning; private javax.swing.JList listAppClasses; // End of variables declaration//GEN-END:variables private static final class AppClassRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String displayName; if (value instanceof String) { displayName = (String) value; } else { displayName = value.toString (); } return super.getListCellRendererComponent (list, displayName, index, isSelected, cellHasFocus); } } public void addChangeListener (ChangeListener l) { changeListener = l; } public void removeChangeListener (ChangeListener l) { changeListener = null; } private Object[] getWarmupList () { return new Object[] {NbBundle.getMessage (JFXApplicationClassChooser.class, "Item_ChooseMainClass_WARMUP_MESSAGE")}; // NOI18N } private void initClassesView () { listAppClasses.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); listAppClasses.setListData (getWarmupList ()); listAppClasses.addListSelectionListener (new ListSelectionListener () { @Override public void valueChanged (ListSelectionEvent evt) { if (changeListener != null) { changeListener.stateChanged (new ChangeEvent (evt)); } } }); // support for double click to finish dialog with selected class listAppClasses.addMouseListener (new MouseListener () { @Override public void mouseClicked (MouseEvent e) { if (MouseUtils.isDoubleClick (e)) { if (getSelectedClass () != null) { if (changeListener != null) { changeListener.stateChanged (new ChangeEvent (e)); } } } } @Override public void mousePressed (MouseEvent e) {} @Override public void mouseReleased (MouseEvent e) {} @Override public void mouseEntered (MouseEvent e) {} @Override public void mouseExited (MouseEvent e) {} }); } private void initClassesModel() { final Map<FileObject,Map<String,ClassPath>> classpathMap = JFXProjectUtils.getClassPathMap(project); if (classpathMap.isEmpty()) { //No sources at all. return; } RP.post(new Runnable() { @Override public void run() { LOG.log(Level.FINE, LOG_INIT); final ClasspathInfo cpInfo = ClasspathInfo.create(classpathMap.keySet().iterator().next()); final JavaSource js = JavaSource.create(cpInfo); ScanUtils.postUserActionTask(js, new Task<CompilationController>() { @Override public void run(CompilationController parameter) throws Exception { final boolean barrier = SourceUtils.isScanInProgress(); final Set<String> appClassNames = isFXinSwing ? JFXProjectUtils.getMainClassNames(project) : JFXProjectUtils.getAppClassNames(classpathMap.keySet(), "javafx.application.Application"); //NOI18N LOG.log( Level.FINE, LOG_MAIN_CLASSES, new Object[]{ appClassNames, barrier }); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!barrier) { labelScanning.setVisible(false); } listAppClasses.setListData(appClassNames.toArray()); String appClassName = evaluator.getProperty(isFXinSwing ? ProjectProperties.MAIN_CLASS : JFXProjectProperties.MAIN_CLASS); if (appClassName != null && appClassNames.contains(appClassName)) { listAppClasses.setSelectedValue(appClassName, true); } } }); if (barrier) { ScanUtils.signalIncompleteData(parameter, null); } } }); } }); } /** Returns the selected class. * * @return name of class or null if no class is selected */ public String getSelectedClass () { Object sel = listAppClasses.getSelectedValue(); if(sel == null) { return null; } if(sel instanceof String) { return (String)sel; } return null; } }
44.289855
208
0.653796
8272a502d25a11652cfc20f931d0895e12419ca1
2,611
package org.eclipse.paho.client.mqttv3; public interface IMqttAsyncClient { void close() throws MqttException; IMqttToken connect() throws MqttException, MqttSecurityException; IMqttToken connect(Object obj, IMqttActionListener iMqttActionListener) throws MqttException, MqttSecurityException; IMqttToken connect(MqttConnectOptions mqttConnectOptions) throws MqttException, MqttSecurityException; IMqttToken connect(MqttConnectOptions mqttConnectOptions, Object obj, IMqttActionListener iMqttActionListener) throws MqttException, MqttSecurityException; IMqttToken disconnect() throws MqttException; IMqttToken disconnect(long j) throws MqttException; IMqttToken disconnect(long j, Object obj, IMqttActionListener iMqttActionListener) throws MqttException; IMqttToken disconnect(Object obj, IMqttActionListener iMqttActionListener) throws MqttException; void disconnectForcibly() throws MqttException; void disconnectForcibly(long j) throws MqttException; void disconnectForcibly(long j, long j2) throws MqttException; String getClientId(); IMqttDeliveryToken[] getPendingDeliveryTokens(); String getServerURI(); boolean isConnected(); IMqttDeliveryToken publish(String str, MqttMessage mqttMessage) throws MqttException, MqttPersistenceException; IMqttDeliveryToken publish(String str, MqttMessage mqttMessage, Object obj, IMqttActionListener iMqttActionListener) throws MqttException, MqttPersistenceException; IMqttDeliveryToken publish(String str, byte[] bArr, int i, boolean z) throws MqttException, MqttPersistenceException; IMqttDeliveryToken publish(String str, byte[] bArr, int i, boolean z, Object obj, IMqttActionListener iMqttActionListener) throws MqttException, MqttPersistenceException; void setCallback(MqttCallback mqttCallback); IMqttToken subscribe(String str, int i) throws MqttException; IMqttToken subscribe(String str, int i, Object obj, IMqttActionListener iMqttActionListener) throws MqttException; IMqttToken subscribe(String[] strArr, int[] iArr) throws MqttException; IMqttToken subscribe(String[] strArr, int[] iArr, Object obj, IMqttActionListener iMqttActionListener) throws MqttException; IMqttToken unsubscribe(String str) throws MqttException; IMqttToken unsubscribe(String str, Object obj, IMqttActionListener iMqttActionListener) throws MqttException; IMqttToken unsubscribe(String[] strArr) throws MqttException; IMqttToken unsubscribe(String[] strArr, Object obj, IMqttActionListener iMqttActionListener) throws MqttException; }
42.112903
174
0.808502
8c2ed23c64b567d2254c3d82e07afc3b5a352451
1,939
package com.bluecyan.controller; import com.bluecyan.pojo.ResultJson; import com.bluecyan.pojo.SearchCondition; import com.bluecyan.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; /** * @Author bluecyan * @DateTime 2021-04-19 19:23 * @Description **/ @Controller @RequestMapping("/clothing") public class ClothingController { @Autowired ClothingService clothingService; @Autowired BrandService brandService; @Autowired CategoryService categoryService; @Autowired StyleService styleService; @Autowired OrderService orderService; @RequestMapping(value = "/search/{keyword}", method = RequestMethod.GET) public String search(@PathVariable String keyword, Model model) { model.addAttribute("keyword",keyword); model.addAttribute("brandList", brandService.getBrandList()); model.addAttribute("categoryList", categoryService.getCategoryList()); model.addAttribute("styleList", styleService.getStyleList()); return "searchPage"; } // @RequestBody必须接收post请求,故不能符合restful风格 @ResponseBody @RequestMapping(value = "/search") public ResultJson getClothingWithListsBySearch(@RequestBody SearchCondition searchCondition) { return ResultJson.success().addObject("clothingListBySearchPageInfo",clothingService.getClothingListBySearch(searchCondition,60,5)); } @RequestMapping(value = "/to-clothingDetails/{clotingId}", method = RequestMethod.GET) public String toClothingDetails(@PathVariable String clotingId, Model model) { model.addAttribute("clothingWithList",clothingService.getClothingWithList(clotingId)); model.addAttribute("orderList",orderService.getAllByClothing(clotingId)); return "clothingDetails"; } }
32.316667
140
0.74884
255ef90e55394cd7efacf51599e4e7cca9695a77
751
package com.mana_wars.ui.textures; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class FixedSizeMirroredTexture extends AdaptiveTexture { public FixedSizeMirroredTexture(String fileName, ImageFormat format) { super(fileName, format); } @Override public String getFileName() { return super.getFileName() + "~mirrored"; } @Override protected TextureRegion adapt(FileHandle file) { TextureRegion region = new TextureRegion(new Texture(file)); region.flip(true, false); return region; } }
26.821429
74
0.727031
d4a23c117d79d4da7fae0e3527ad152a10bdeae9
2,500
package com.example.foodapp; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class AnasayfaRecyclerAdapter extends RecyclerView.Adapter<AnasayfaRecyclerAdapter.ViewHolder> { public int pozisyon; ArrayList<AnasayfaModel> mainModels; Context context; Anasayfa mainActivity; public AnasayfaRecyclerAdapter(Context context,ArrayList<AnasayfaModel> mainModels,Anasayfa mainActivity){ this.context=context; this.mainModels=mainModels; this.mainActivity = mainActivity; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()) .inflate(R.layout.category_row_item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) { String urlImg =mainModels.get(position).langLogoArka; Picasso.get().load(urlImg).into(holder.imageView); holder.textView.setText(mainModels.get(position).langName); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pozisyon = position; mainActivity.setle(mainModels.get(position).langName); notifyDataSetChanged(); } }); if (pozisyon!=position){ urlImg=mainModels.get(position).langLogo; Picasso.get().load(urlImg).into(holder.imageView); }else { urlImg=mainModels.get(position).langLogoArka; Picasso.get().load(urlImg).into(holder.imageView); } } @Override public int getItemCount() { return mainModels.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView textView; public ViewHolder(@NonNull View itemView) { super(itemView); imageView=itemView.findViewById(R.id.image_view); textView=itemView.findViewById(R.id.text_view); } } }
30.120482
110
0.6828
c05b4edffc06652b3e933e30d0a0095d8e44481d
871
package ru.pinkgoosik.kitsun.command.moderation; import ru.pinkgoosik.kitsun.command.Command; import ru.pinkgoosik.kitsun.command.CommandUseContext; import ru.pinkgoosik.kitsun.permission.Permissions; import ru.pinkgoosik.kitsun.util.Embeds; public class PermissionsList extends Command { @Override public String getName() { return "permissions"; } @Override public String getDescription() { return "Sends list of permissions."; } @Override public void respond(CommandUseContext ctx) { if (disallowed(ctx, Permissions.PERMISSIONS)) return; StringBuilder text = new StringBuilder(); for (String permission : Permissions.LIST) { text.append(permission).append("\n"); } ctx.channel.createMessage(Embeds.info("Available Permissions", text.toString())).block(); } }
28.096774
97
0.694604
cf091f2a5e90a6fb92f9376ce5f613c52a897189
1,028
/** * Copyright (c) 2009 Jozef Izso. All Rights Reserved. */ package net.izsak.sandcastle.configuration; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; /** * @author Jozef Izso * */ public class DocletOptions extends Options { public static final Option OUTPUT_FILE = new Option("doc", true, "Documentation output file name."); public static final Option PROJECT_NAME = new Option("project", true, "Project name."); public static final Option METADATA_FILE = new Option("metadata", true, "Path to file with metadata configuration."); public static final Option CONFIG_FILE = new Option("config", true, "Path to the configuration file."); private static final long serialVersionUID = 1L; public DocletOptions() { //this.addOption((Option)OUTPUT_FILE.clone()); //this.addOption((Option)PROJECT_NAME.clone()); //this.addOption((Option)METADATA_FILE.clone()); CONFIG_FILE.setRequired(true); this.addOption((Option)CONFIG_FILE.clone()); } }
33.16129
119
0.715953
e5dd0b1646d2299fa3ddd71549cf21741afbccff
1,555
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1beta1/cluster_service.proto package com.google.container.v1beta1; public interface NodeManagementOrBuilder extends // @@protoc_insertion_point(interface_extends:google.container.v1beta1.NodeManagement) com.google.protobuf.MessageOrBuilder { /** * <pre> * Whether the nodes will be automatically upgraded. * </pre> * * <code>bool auto_upgrade = 1;</code> * @return The autoUpgrade. */ boolean getAutoUpgrade(); /** * <pre> * Whether the nodes will be automatically repaired. * </pre> * * <code>bool auto_repair = 2;</code> * @return The autoRepair. */ boolean getAutoRepair(); /** * <pre> * Specifies the Auto Upgrade knobs for the node pool. * </pre> * * <code>.google.container.v1beta1.AutoUpgradeOptions upgrade_options = 10;</code> * @return Whether the upgradeOptions field is set. */ boolean hasUpgradeOptions(); /** * <pre> * Specifies the Auto Upgrade knobs for the node pool. * </pre> * * <code>.google.container.v1beta1.AutoUpgradeOptions upgrade_options = 10;</code> * @return The upgradeOptions. */ com.google.container.v1beta1.AutoUpgradeOptions getUpgradeOptions(); /** * <pre> * Specifies the Auto Upgrade knobs for the node pool. * </pre> * * <code>.google.container.v1beta1.AutoUpgradeOptions upgrade_options = 10;</code> */ com.google.container.v1beta1.AutoUpgradeOptionsOrBuilder getUpgradeOptionsOrBuilder(); }
27.280702
90
0.686174
9e67bd54ec0df4e77bdd5a7dfd24e2748003d314
12,285
package oope2017ht; import apulaiset.In; import oope2017ht.omalista.OmaLista; /** * Käyttöliittymä vastaa vuorovaikutuksesta käyttäjän kanssa. Käyttäjä antaa käyttöliittymän välityksellä * ohjelmalle komentoja, jotka käyttöliittymä välittää tulkille toteutettavaksi. * <p> * Harjoitustyö, Olio-ohjelmoinnin perusteet, kevät 2017. * <p> * Viimeksi muokattu 24.4.2017. * <p> * @author Heidi Lammi-Mihaljov, Lammi-Mihaljov.Heidi.J@student.uta.fi. */ public class Kayttoliittyma { /* * Vakiot. */ // Käyttäjän antamat komennot. /** Komennolla listataan nykyisen hakemiston hakemistopuu rekursiivisesti esijärjestyksessä. */ private static final String REKURSIIVINEN_LISTAAMINEN = "find"; /** Komennolla vaihdetaan hakemistoa.*/ private static final String HAKEMISTON_VAIHTAMINEN = "cd"; /** Komennolla poistetaan hakemisto tai tiedosto.*/ private static final String POISTAMINEN = "rm"; /** Komennolla kopioidaan hakemisto tai tiedosto.*/ private static final String KOPIOIMINEN = "cp"; /** Komennolla nimetään hakemisto tai tiedosto uudelleen.*/ private static final String UUDELLEEN_NIMEAMINEN = "mv"; /** Komennolla luodaan tiedosto.*/ private static final String TIEDOSTON_LUOMINEN = "mf"; /** Komennolla luodaan hakemisto.*/ private static final String HAKEMISTON_LUOMINEN = "md"; /** Komennolla listataan hakemiston sisältö tai tulostetaan parametrina annetun tiedon merkkijonoesitys.*/ private static final String LISTAAMINEN = "ls"; /** Komennolla poistutaan ohjelmasta.*/ private static final String LOPETUS = "exit"; // Tulosteet käyttäjälle. /** Merkin jälkeen odotetaan käyttäjän syötettä.*/ private static final String KEHOTE = ">"; /** Tervehdysteksti ohjelman alussa.*/ private static final String TERVEHDYS = "Welcome to SOS."; /** Lopetusviesti poistumiskomennon jälkeen.*/ private static final String LOPETUSVIESTI = "Shell terminated."; /** Virheilmoitus.*/ private static final String VIRHEILMOITUS = "Error!"; /* * Attribuutit. */ /** Käyttöliittymä komentaa tulkkia, joka toteuttaa ohjelman komennot.*/ private Tulkki tulkki; /* * Rakentajat. */ public Kayttoliittyma() { this.tulkki = new Tulkki(); } /** Metodi pyytää käyttäjältä komentoja ja kutsuu komentoja vastaavia tulkkiluokan metodeja. * Metodin suoritusta jatketaan, kunnes käyttäjä syöttää lopetuskomennon. */ public void suorita() { // Kun ohjelma käynnistyy tulostetaan tervehdysviesti. System.out.println(TERVEHDYS); // Luodaan muuttuja käyttäjän antamalle syötteelle. String syote; do { // Kutsutaan metodia, tulostaa näytölle nykyisen työhakemiston hakemistopolun sekä kehotteen ja // lukee käyttäjän antaman syötteen syote-muuttujaan. System.out.print(tulkki.tyohakemisto().hakemistopolku() + KEHOTE); syote = In.readString(); // Pilkotaan syöte osiin välilyöntien kohdalta ja tallennetaan syötteen osat taulukkoon. String osat[] = syote.split(" "); try { // Jos syöte alkaa tai loppuu välilyöntiin, kutsutaan error-metodia, joka tulostaa virheilmoituksen. if (syote.endsWith(" ") || syote.startsWith(" ")) { error(); // Jos käyttäjä haluaa poistua ohjelmasta tulostetaan lopetusviesti. } else if (osat[0].equals(LOPETUS) && osat.length == 1) { System.out.println(LOPETUSVIESTI); // Jos käyttäjä haluaa listata hakemiston sisällön, komento ei sisällä komentoriviparametreja. } else if (osat[0].equals(LISTAAMINEN) && osat.length == 1) { // Kutsutaan metodia, joka listaa hakemiston sisällön. listaaHakemistonSisalto(); // Jos käyttäjä haluaa tulostaa näytölle tiedon merkkijonoesityksen, hän antaa // tiedon nimen komentoriviparametrina. } else if (osat[0].equals(LISTAAMINEN) && osat.length == 2) { // Tiedon nimi. String nimi = osat[1]; tulostaTietoMjonona(nimi); // Jos käyttäjä haluaa luoda hakemiston komentoriviparametrina antamallansa nimellä: } else if (osat[0].equals(HAKEMISTON_LUOMINEN) && osat.length == 2) { // Tiedon nimi. String nimi = osat[1]; // Jos tulkin luoHakemisto-metodi palauttaa falsen, hakemiston luominen ei onnistunut, // ja tulostetaan virheilmoitus. if (!tulkki.luoHakemisto(nimi)) { error(); } // Jos käyttäjä haluaa luoda tiedoston komentoriviparametreinaan antamillaan nimellä ja koolla: } else if (osat[0].equals(TIEDOSTON_LUOMINEN) && osat.length == 3) { // Luotavan tiedoston nimi. String nimi = osat[1]; // Luotavan tiedoston koko. int koko = Integer.parseInt(osat[2]); // Kutsutaan tulkin luoTiedosto-metodia, joka saa parametreinaan nimen ja koon. // Jos paluuarvo on false, tiedoston luominen epäonnistui ja tulostetaan virheilmoitus. if (!tulkki.luoTiedosto(nimi, koko)) { error(); } // Jos käyttäjä haluaa uudelleennimetä olemassa olevan tiedon: } else if (osat[0].equals(UUDELLEEN_NIMEAMINEN) && osat.length == 3) { // Ensimmäinen komentoriviparametri on vaihdettavan tiedon nimi. String vaihdettavaNimi = osat[1]; // Toinen komentoriviparametri on uusi nimi tiedolle. String uusiNimi = osat[2]; // Kutsutaan tulkin metodia, joka nimeää tiedon uudelleen. // Jos paluuarvo on false, uudelleennimeäminen epäonnistui ja tulostetaan virheilmoitus. if (!tulkki.nimeaUudelleen(vaihdettavaNimi, uusiNimi)) { error(); } // Jos käyttäjä haluaa kopioida tiedoston: } else if (osat[0].equals(KOPIOIMINEN) && osat.length == 3) { // Kopioitavan tiedoston nimi on ensimmäinen komentoriviparametri. String nimi = osat[1]; // Kopion nimi on toinen komentoriviparametri. String kopioNimi = osat[2]; // Kutsutaan tulkin metodia, joka kopioi tiedon, jonka saa ensimmäisenä parametrina // ja antaa uudelle tiedolle nimen, jonka saa toisena parametrina. // Jos paluuarvo on false, kopiointi epäonnistui ja tulostetaan virheilmoitus. if (!tulkki.kopioiTiedosto(nimi, kopioNimi)) { error(); } // Jos käyttäjä haluaa poistaa tiedon, jonka nimen antaa ensimmäisenä komentoriviparametrina: } else if (osat[0].equals(POISTAMINEN) && osat.length == 2) { // Poistettavan tiedon nimi. String poistettava = osat[1]; // Jos poisto ei onnistunut, tulostetaan virheilmoitus. if (!tulkki.poista(poistettava)) { error(); } // Jos käyttäjä haluaa siirtyä takaisin juurihakemistoon, kutsutaan tulkin metodia, joka // vaihtaa työhakemistoksi juurihakemiston. } else if (osat[0].equals(HAKEMISTON_VAIHTAMINEN) && osat.length == 1) { tulkki.siirryJuurihakemistoon(); // Jos käyttäjä haluaa siirtyä johonkin alihakemistoistaan, // ensimmäinen komentoriviparametri on sen alihakemiston nimi, johon halutaan siirtyä. // Tarkistetaan kuitenkin ettei parametri ole "..", jolla siirrytään ylihakemistoon. } else if (osat[0].equals(HAKEMISTON_VAIHTAMINEN) && !osat[1].equals("..") && osat.length == 2) { // Alihakemiston nimi. String nimi = osat[1]; // Kutsutaan tulkin metodia, joka saa parametrina alihakemiston nimen, jonne siirrytään. // Jos paluuarvo on false, siirtyminen ei onnistunut ja tulostetaan virheimoitus. if (!tulkki.siirryAlihakemistoon(nimi)) { error(); } // Jos käyttäjä haluaa siirtyä nykyisen hakemiston ylihakemistoon, komentoriviparametri on "..". } else if (osat[0].equals(HAKEMISTON_VAIHTAMINEN) && osat[1].equals("..") && osat.length == 2) { // Kutsutaan tulkin metodia, joka vaihtaa työhakemistoksi nykyisen hakemiston ylihakemiston. // Jos paluuarvo on false, siirtyminen ei onnistunut ja tulostetaan virheilmoitus. if (!tulkki.siirryYlihakemistoon()) { error(); } // Jos käyttäjä haluaa listata nykyisen hakemiston hakemistopuun: } else if (osat[0].equals(REKURSIIVINEN_LISTAAMINEN) && osat.length == 1) { // Kutsutaan metodia, joka listaa hakemistopuun rekursiivisesti. listaaRekursiivisesti(); // Jos syöte ei ole mikään hyväksytyistä syötteistä tulostetaan // virheilmoitus. } else { error(); } // Napataan rakentajan tai setterin heittämä poikkeus, jos yritetään luoda tietoa virheellisellä nimellä. // Tulostetaan virheilmoitus. } catch(IllegalArgumentException e) { error(); } // Suoritetaan silmukkaa kunnes käyttäjä syöttää lopetuskomennon. } while (!syote.equals(LOPETUS)); } /* * Apumetodit suorita-metodin käytettäväksi. */ /** Metodi tulostaa hakemistopuun sisällön rekursiivisesti niin, * että ylihakemisto tulostetaan ennen alihakemistojaan. */ private void listaaRekursiivisesti() { // Kutsutaan tulkin metodia, joka tallentaa OmaLista-tyyppiseen muuttujaan // viitteen hakemistopuun sisältöön. OmaLista hakemistopuu = tulkki.hakemistopuunSisalto(tulkki.tyohakemisto()); // Tulostetaan hakemistopuun sisältö alkio kerrallaan. for (int i = 0; i < hakemistopuu.koko(); i++) { System.out.println(hakemistopuu.alkio(i).toString()); } } /** Metodi tulostaa parametrina saamaansa nimeä vastaavan tiedon merkkijonoesityksen. * * @param nimi viittaa tietoon, joka tulostetaan merkkijonona. */ private void tulostaTietoMjonona(String nimi) { if (nimi == null) { error(); } else { // Kutsutaan tulkin metodia, joka saa parametrina tiedon nimen // ja palauttaa sen merkkijonoesityksen. String mjono = tulkki.tietoMjonona(nimi); // Jos metodi palautti nullin eli tietoa ei saatu merkkijonona, tulostetaan virheilmoitus. if (mjono == null) { error(); // Jos tiedon merkkijonoesitys saatiin paluuarvona, tulostetaan se. } else { System.out.println(mjono); } } } /** Metodi tulostaa näytölle hakemiston sisällön nousevassa aakkosjärjestyksessä * (koska tiedot ovat hakemistossa valmiiksi aakkosjärjestyksessä). */ private void listaaHakemistonSisalto() { // Kutsutaan tulkin metodia, joka antaa hakemiston sisällön paluuarvona. OmaLista sisalto = tulkki.hakemistonSisalto(); // Käydään paluuarvona saatu lista läpi ja tulostetaan listan alkiot. for (int i = 0; i < sisalto.koko(); i++) { System.out.println(sisalto.alkio(i).toString()); } } /** Metodi tulostaa virheilmoituksen.*/ private void error() { System.out.println(VIRHEILMOITUS); } }
46.011236
117
0.60114
a6adbb550ef40bc33a2f5a6a19ceaef36d4105ad
5,959
package org.richardinnocent.propertiestoolkit; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; /** * The default settings express the default return value and optional behaviour that should be * applied when encountering specified {@link DefaultCondition}s. * @param <T> The type for the return value. * @since 1.0.0 * @author RichardInnocent */ @SuppressWarnings("WeakerAccess") public class DefaultSettings<T> { private final Map<DefaultCondition, ReturnBehaviour> behaviourMap = new HashMap<>(1); /** * Creates a new {@code Setting} object which contains the expected behaviour for these specified * conditions. As a result, it's possible to specify different behaviour for different * conditions, e.g.:<br> * <pre> * DefaultSettings&lt;Integer&gt; settings = new DefaultSettings&lt;&gt;() * .when(DefaultCondition.IS_EMPTY, DefaultCondition.PARSE_FAILS) * .thenReturn(0) * .when(DefaultCondition.IS_INVALID) * .thenDo((key, value) -&gt; * LOGGER.warn("Value for key, " + key + " is invalid: " + value)) * .thenReturn(10);</pre> * This behaviour is only applied if the {@link Setting#thenReturn(Object)} method is * subsequently called. * * <pre> * // Nothing happens * new DefaultSettings&lt;Integer&gt;().when(DefaultCondition.IS_EMPTY); * * // Nothing happens * new DefaultSettings&lt;Integer&gt;().when(DefaultCondition.IS_EMPTY) * .thenDo(key, value -&gt; LOGGER.debug(Key + ": " + value)); * * // Successfully added to the settings * new DefaultSettings&lt;Integer&gt;().when(DefaultCondition.IS_EMPTY) * .thenReturn(0d);</pre> * * Note that, if the same {@code DefaultCondition} is specified multiple times, the most recent * {@code Setting} that was applied will dictate the behaviour if this condition is met. * @param conditions The conditions for which the soon-to-be-specified task (if appropriate) and * return value should be applied. * @return The new {@code Setting}s object, for chaining. */ public Setting when(DefaultCondition... conditions) { return new Setting(conditions); } /** * Checks to see if the behaviour for this condition has been specified in {@code this} settings * instance. If it has, the task is executed, if present, and then the default value is returned. * If the behaviour for this condition has not been expressed, the exception, {@code e}, is * thrown. * @param condition The condition that has been triggered. * @param key The key to pass to the task, if appropriate. * @param value The value, in its raw {@code String} form, that can be passed to the task, if * appropriate. * @param e The exception to throw if behaviour for this condition has not been defined. * @return The appropriate return value for this condition. * @throws PropertiesException Thrown if behaviour for this condition has not been defined. */ T apply(DefaultCondition condition, String key, String value, PropertiesException e) throws PropertiesException { ReturnBehaviour behaviour = behaviourMap.get(condition); if (behaviour == null) throw e; if (behaviour.task != null) behaviour.task.accept(key, value); return behaviour.returnValue; } private void saveBehaviourMap(Setting setting) { setting.getConditions() .forEach(condition -> behaviourMap.put(condition, new ReturnBehaviour(setting.getTask(), setting.getReturnValue()))); } /** * Object to contain the behaviour for specified {@link DefaultCondition}s. */ public class Setting { private final Set<DefaultCondition> conditions = new HashSet<>(1); private BiConsumer<String, String> task; private T returnValue; Setting(DefaultCondition... conditions) { if (conditions == null || conditions.length < 1) throw new IllegalArgumentException("Conditions cannot be null or empty"); Stream.of(conditions) .filter(Objects::nonNull) .forEach(this.conditions::add); } Set<DefaultCondition> getConditions() { return conditions; } BiConsumer<String, String> getTask() { return task; } T getReturnValue() { return returnValue; } /** * Sets the task to execute when the specific condition is met, before the return value is * returned. This might be to log a warning to a {@code Logger}, for example. Only one task may * be specified. * @param task The task to complete. This is a consumer that takes two {@code String}s: first * the key name, then the raw {@code String} value received from the {@code Properties} file. * @return {@code this} settings object, for chaining. */ public Setting thenDo(BiConsumer<String, String> task) { this.task = task; return this; } /** * Sets the value that should be returned, in the event that any of the conditions are met. * This method is a required call, in order to add this {@code Setting} to the {@code * DefaultSettings} instance. * @param returnValue The value that should be returned. * @return {@code this} {@code DefaultSettings} object, so that additional cases can be * appended. */ public DefaultSettings<T> thenReturn(T returnValue) { this.returnValue = returnValue; DefaultSettings.this.saveBehaviourMap(this); return DefaultSettings.this; } } private class ReturnBehaviour { private final BiConsumer<String, String> task; private final T returnValue; ReturnBehaviour(BiConsumer<String, String> task, T returnValue) { this.task = task; this.returnValue = returnValue; } } }
36.783951
99
0.680315
527711a80d83eb29eabdb6c981cc3563b0f85ea4
5,535
/** * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2021 School of Management and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ package com.wegas.app.jsf.controllers; import com.wegas.app.jsf.controllers.utils.HttpParam; import com.wegas.core.ejb.GameFacade; import com.wegas.core.ejb.GameModelFacade; import com.wegas.core.ejb.PlayerFacade; import com.wegas.core.ejb.RequestManager; import com.wegas.core.persistence.game.DebugGame; import com.wegas.core.persistence.game.DebugTeam; import com.wegas.core.persistence.game.Game; import com.wegas.core.persistence.game.GameModel; import com.wegas.core.persistence.game.Populatable.Status; import com.wegas.core.persistence.game.Team; import com.wegas.core.security.ejb.UserFacade; import java.io.IOException; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Controls player access to games * * @author Francois-Xavier Aeberhard (fx at red-agent.com) */ @Named("gameController") @RequestScoped public class GameController extends AbstractGameController { private static final long serialVersionUID = 1563759464312489408L; private static final Logger logger = LoggerFactory.getLogger(GameController.class); /** * */ @Inject @HttpParam private Long gameId; /** * */ @Inject @HttpParam private Long gameModelId; /** * */ @Inject private PlayerFacade playerFacade; /** * */ @Inject private UserFacade userFacade; /** * */ @Inject private GameModelFacade gameModelFacade; @Inject private GameFacade gameFacade; /** * */ @Inject ErrorController errorController; @Inject private RequestManager requestManager; /** * */ @PostConstruct public void init() { final ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); long currentUserId = userFacade.getCurrentUser().getId(); if (this.playerId != null) { // use the player which matches playerId currentPlayer = playerFacade.find(this.getPlayerId()); } if (this.gameId != null) { Game game = gameFacade.find(this.gameId); if (game != null) { if (game instanceof DebugGame) { // use the debug player currentPlayer = game.getPlayers().get(0); } else { // use the player owned by the current user currentPlayer = playerFacade.findPlayer(this.gameId, currentUserId); if (currentPlayer == null) { // fallback: use the test player for (Team t : game.getTeams()) { if (t instanceof DebugTeam) { currentPlayer = t.getAnyLivePlayer(); break; } } } } } } if (this.gameModelId != null) { GameModel gameModel = gameModelFacade.find(this.gameModelId); if (gameModel != null) { if (gameModel.isScenario() || gameModel.isModel()) { // use the debug player from the debug game currentPlayer = gameModel.getTestPlayer(); } else { currentPlayer = playerFacade.findPlayerInGameModel(this.gameModelId, currentUserId); if (currentPlayer == null) { // fallback: use a test player currentPlayer = gameModel.getTestPlayer(); } } } } if (currentPlayer == null) { // If no player could be found, we redirect to an error page errorController.gameNotFound(); } else if (currentPlayer.getStatus().equals(Status.SURVEY)) { errorController.accessForSurveyOnly(); } else if (!currentPlayer.getStatus().equals(Status.LIVE)) { try { externalContext.dispatch("/wegas-app/jsf/error/waiting.xhtml"); } catch (IOException ex) { logger.error("Dispatch error: {}", ex); } } else if (currentPlayer.getGame().getStatus().equals(Game.Status.DELETE) || currentPlayer.getGame().getStatus().equals(Game.Status.SUPPRESSED)) { currentPlayer = null; errorController.gameDeleted(); } else if (!requestManager.hasPlayerRight(currentPlayer)) { currentPlayer = null; errorController.accessDenied(); } } /** * @return the gameId */ public Long getGameId() { return gameId; } /** * @param gameId the gameId to set */ public void setGameId(Long gameId) { this.gameId = gameId; } /** * @return the gameModelId */ public Long getGameModelId() { return gameModelId; } /** * @param gameModelId the gameModelId to set */ public void setGameModelId(Long gameModelId) { this.gameModelId = gameModelId; } }
29.758065
140
0.583921
bfbbe8d2966b26cedc43f86c37511db1262b405b
5,828
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.util.databasechange; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.openmrs.util.DatabaseUpdater; import org.openmrs.util.DatabaseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import liquibase.change.custom.CustomTaskChange; import liquibase.database.Database; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.CustomChangeException; import liquibase.exception.DatabaseException; import liquibase.exception.SetupException; import liquibase.exception.ValidationErrors; import liquibase.resource.ResourceAccessor; /** * Liquibase custom changeset used to identify and resolve duplicate EncounterType names. If a * duplicate EncounterType name is identified, it will be edited to include a suffix term which * makes it unique, and identifies it as a value to be manually changed during later review */ public class DuplicateEncounterTypeNameChangeSet implements CustomTaskChange { private static final Logger log = LoggerFactory.getLogger(DuplicateEncounterTypeNameChangeSet.class); @Override public String getConfirmationMessage() { return "Completed updating duplicate EncounterType names"; } @Override public void setFileOpener(ResourceAccessor arg0) { } @Override public void setUp() throws SetupException { // No setup actions } @Override public ValidationErrors validate(Database arg0) { return null; } /** * Method to perform validation and resolution of duplicate EncounterType names */ @Override public void execute(Database database) throws CustomChangeException { JdbcConnection connection = (JdbcConnection) database.getConnection(); Map<String, HashSet<Integer>> duplicates = new HashMap<>(); Statement stmt = null; PreparedStatement pStmt = null; ResultSet rs = null; Boolean initialAutoCommit = null; try { initialAutoCommit = connection.getAutoCommit(); // set auto commit mode to false for UPDATE action connection.setAutoCommit(false); stmt = connection.createStatement(); rs = stmt .executeQuery("SELECT * FROM encounter_type INNER JOIN (SELECT name FROM encounter_type GROUP BY name HAVING count(name) > 1) dup ON encounter_type.name = dup.name"); Integer id; String name; while (rs.next()) { id = rs.getInt("encounter_type_id"); name = rs.getString("name"); if (duplicates.get(name) == null) { HashSet<Integer> results = new HashSet<>(); results.add(id); duplicates.put(name, results); } else { HashSet<Integer> results = duplicates.get(name); results.add(id); } } for (Object o : duplicates.entrySet()) { Map.Entry pairs = (Map.Entry) o; HashSet values = (HashSet) pairs.getValue(); List<Integer> ids = new ArrayList<Integer>(values); int duplicateNameId = 1; for (int i = 1; i < ids.size(); i++) { String newName = pairs.getKey() + "_" + duplicateNameId; List<List<Object>> duplicateResult; boolean duplicateName; Connection con = DatabaseUpdater.getConnection(); do { String sqlValidatorString = "select * from encounter_type where name = '" + newName + "'"; duplicateResult = DatabaseUtil.executeSQL(con, sqlValidatorString, true); if (!duplicateResult.isEmpty()) { duplicateNameId += 1; newName = pairs.getKey() + "_" + duplicateNameId; duplicateName = true; } else { duplicateName = false; } } while (duplicateName); pStmt = connection.prepareStatement("update encounter_type set name = ? where encounter_type_id = ?"); pStmt.setString(1, newName); pStmt.setInt(2, ids.get(i)); duplicateNameId += 1; pStmt.executeUpdate(); } } } catch (BatchUpdateException e) { log.warn("Error generated while processsing batch insert", e); try { log.debug("Rolling back batch", e); connection.rollback(); } catch (Exception rbe) { log.warn("Error generated while rolling back batch insert", e); } // marks the changeset as a failed one throw new CustomChangeException("Failed to update one or more duplicate EncounterType names", e); } catch (Exception e) { throw new CustomChangeException(e); } finally { // set auto commit to its initial state try { if (initialAutoCommit != null) { connection.setAutoCommit(initialAutoCommit); } } catch (DatabaseException e) { log.warn("Failed to set auto commit to ids initial state", e); } if (rs != null) { try { rs.close(); } catch (SQLException e) { log.warn("Failed to close the resultset object"); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { log.warn("Failed to close the select statement used to identify duplicate EncounterType object names"); } } if (pStmt != null) { try { pStmt.close(); } catch (SQLException e) { log.warn("Failed to close the prepared statement used to update duplicate EncounterType object names"); } } } } }
28.70936
177
0.69698
1b9f0a02842b1c96a081e60f9d750e46ed7e2107
2,573
package and.sample.deckbuilder.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import java.util.ArrayList; import and.sample.deckbuilder.R; // ref. recipes4dev.tistory.com public class SimpleTextAdapter extends RecyclerView.Adapter<SimpleTextAdapter.ViewHolder> { private ArrayList<String> mData = null; public SimpleTextAdapter(ArrayList<String> list) { mData = list; } public interface OnItemClickListener { void onItemClick(View v, int position); } private OnItemClickListener mListener = null; // OnItemClickListener 리스너 객체 참조를 어댑터에 전달하는 메서드 public void setOnItemClickListener(OnItemClickListener listener) { this.mListener = listener; } // 아이템 뷰를 저장하는 뷰홀더 클래스. public class ViewHolder extends RecyclerView.ViewHolder { Button button; public ViewHolder(View itemView) { super(itemView); button = itemView.findViewById(R.id.btn_unit); //itemView.setOnClickListener(new View.OnClickListener() { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { // 리스너 객체의 메서드 호출. if (mListener != null) { mListener.onItemClick(v, pos); } } } }); } } // onCreateViewHolder() - 아이템 뷰를 위한 뷰홀더 객체 생성하여 리턴. @Override public SimpleTextAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.recycle_item, parent, false); SimpleTextAdapter.ViewHolder vh = new SimpleTextAdapter.ViewHolder(view); return vh; } // onBindViewHolder() - position에 해당하는 데이터를 뷰홀더의 아이템뷰에 표시. @Override public void onBindViewHolder(SimpleTextAdapter.ViewHolder holder, int position) { String text = mData.get(position); holder.button.setText(text); } // getItemCount() - 전체 데이터 갯수 리턴. @Override public int getItemCount() { return mData.size(); } }
29.574713
109
0.638943
0f764cf991492735bfe7d709408822a804f48e0f
5,130
/* * 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.cassandra.distributed.test; import java.util.function.Consumer; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.apache.cassandra.distributed.Cluster; import org.apache.cassandra.distributed.api.IInstanceConfig; import org.apache.cassandra.distributed.impl.UnsafeGossipHelper; import static org.apache.cassandra.distributed.api.ConsistencyLevel.ANY; import static org.apache.cassandra.distributed.api.ConsistencyLevel.QUORUM; import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows; import static org.apache.cassandra.distributed.shared.AssertUtils.row; public class LegacyCASTest extends CASCommonTestCases { private static Cluster CLUSTER; @BeforeClass public static void beforeClass() throws Throwable { TestBaseImpl.beforeClass(); CLUSTER = init(Cluster.create(3, config())); } @AfterClass public static void afterClass() { if (CLUSTER != null) CLUSTER.close(); } private static Consumer<IInstanceConfig> config() { return config -> config .set("paxos_variant", "v1") .set("write_request_timeout_in_ms", 5000L) .set("cas_contention_timeout_in_ms", 5000L) .set("request_timeout_in_ms", 5000L); } /** * This particular variant is unique to legacy Paxos because of the differing quorums for consensus, read and commit. * It is also unique to range movements with an even-numbered RF under legacy paxos. * * Range movements do not necessarily complete; they may be aborted. * CAS consistency should not be affected by this. * * - Range moving from {1, 2} to {2, 3}; witnessed by all * - Promised and Accepted on {2, 3}; Commits are delayed and arrive after next commit (or perhaps vanish) * - Range move cancelled; a new one starts moving {1, 2} to {2, 4}; witnessed by all * - Promised, Accepted and Committed on {1, 4} */ @Ignore // known to be unsafe, just documents issue @Test public void testAbortedRangeMovement() throws Throwable { try (Cluster cluster = Cluster.create(4, config())) { cluster.schemaChange("CREATE KEYSPACE " + KEYSPACE + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3};"); cluster.schemaChange("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v1 int, v2 int, PRIMARY KEY (pk, ck))"); int pk = pk(cluster, 1, 2); // set {3} bootstrapping, {4} not in ring for (int i = 1 ; i <= 4 ; ++i) cluster.get(i).acceptsOnInstance(UnsafeGossipHelper::removeFromRing).accept(cluster.get(3)); for (int i = 1 ; i <= 4 ; ++i) cluster.get(i).acceptsOnInstance(UnsafeGossipHelper::removeFromRing).accept(cluster.get(4)); for (int i = 1 ; i <= 4 ; ++i) cluster.get(i).acceptsOnInstance(UnsafeGossipHelper::addToRingBootstrapping).accept(cluster.get(3)); // {3} promises and accepts on !{1} => {2, 3} // {3} commits do not YET arrive on either of {1, 2} (must be either due to read quorum differing on legacy Paxos) drop(cluster, 3, to(1), to(), to(1), to(1, 2)); assertRows(cluster.coordinator(3).execute("INSERT INTO " + KEYSPACE + ".tbl (pk, ck, v1) VALUES (?, 1, 1) IF NOT EXISTS", ANY, pk), row(true)); // abort {3} bootstrap, start {4} bootstrap for (int i = 1 ; i <= 4 ; ++i) cluster.get(i).acceptsOnInstance(UnsafeGossipHelper::removeFromRing).accept(cluster.get(3)); for (int i = 1 ; i <= 4 ; ++i) cluster.get(i).acceptsOnInstance(UnsafeGossipHelper::addToRingBootstrapping).accept(cluster.get(4)); // {4} promises and accepts on !{2} => {1, 4} // {4} commits on {1, 2, 4} drop(cluster, 4, to(2), to(), to(2), to()); assertRows(cluster.coordinator(4).execute("INSERT INTO " + KEYSPACE + ".tbl (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", QUORUM, pk), row(false, pk, 1, 1, null)); } } protected Cluster getCluster() { return CLUSTER; } }
43.109244
146
0.645029
72769dd73195db188d79c38d1a8d9524046da683
6,325
package com.fgonzalez.categorycalendar; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.fgonzalez.categorycalendar.persistance.entity.Category; import com.fgonzalez.categorycalendar.persistance.entity.CategorySchedule; import com.fgonzalez.categorycalendar.persistance.repository.CategoryScheduleRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @SpringBootTest public class CategoryScheduleControllerTest extends AbstractControllerTest { @MockBean private CategoryScheduleRepository categoryScheduleRepository; private Category defaultCategory; private CategorySchedule categorySchedule1; private CategorySchedule categorySchedule2; private CategorySchedule newCategorySchedule; @BeforeEach protected void setUp() { super.setUp(); mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); defaultCategory = Category.builder().id(1).name("vacations").color("ff5050").active(true).build(); categorySchedule1 = new CategorySchedule(1, 20210313, defaultCategory, true); categorySchedule2 = new CategorySchedule(2, 20210313, defaultCategory, true); newCategorySchedule = new CategorySchedule(3, 20210313, defaultCategory, true); doReturn(Arrays.asList(categorySchedule1, categorySchedule2)).when(categoryScheduleRepository) .findAll(); when(categoryScheduleRepository.findById(1)).thenReturn(Optional.of(categorySchedule1)); when(categoryScheduleRepository.findById(2)).thenReturn(Optional.of(categorySchedule2)); when(categoryScheduleRepository.save(newCategorySchedule)).thenReturn(newCategorySchedule); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { return null; } }).when(categoryScheduleRepository).save(any()); } @Test @DisplayName("Test get all schedules") public void testGetCategories() throws Exception { MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get("/categoryschedule/getcategoryschedules/") .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); String content = mvcResult.getResponse().getContentAsString(); Assertions.assertArrayEquals(new CategorySchedule[] { categorySchedule1, categorySchedule2 }, mapFromJson(content, CategorySchedule[].class), "The retuns must be all the categories"); } @Test @DisplayName("Remove category controller test") public void testRemoveCategorySchedule() throws Exception { MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders .post("/categoryschedule/removecategoryschedule") .contentType(MediaType.APPLICATION_JSON_VALUE).content(mapToJson(categorySchedule1))) .andReturn(); Assertions.assertEquals(HttpStatus.OK.value(), mvcResult.getResponse().getStatus(), "Expected operation was correct"); } @Test @DisplayName("Add new Category Schedule test") public void testAddcategorySchedule() throws Exception { MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/categoryschedule/addcategoryschedule") .contentType(MediaType.APPLICATION_JSON_VALUE).content(mapToJson(newCategorySchedule))) .andReturn(); Assertions.assertEquals(HttpStatus.OK.value(), mvcResult.getResponse().getStatus(), "Expected operation was correct"); Map<String, Object> payload = new HashMap<String, Object>(); payload.put("scheduleDate", null); payload.put("active", true); mvcResult = mvc.perform(MockMvcRequestBuilders.post("/categoryschedule/addcategoryschedule") .contentType(MediaType.APPLICATION_JSON_VALUE).content(mapToJson(payload))).andReturn(); Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), mvcResult.getResponse().getStatus(), "Expected error on server side"); } @Test @DisplayName("Test getcategoryschedulesbyyear") void testGetCategorySchedulesByYear() throws Exception { List<CategorySchedule> expected = Arrays.asList(categorySchedule1, categorySchedule2); when(categoryScheduleRepository.findCategorySchedulesByYear(2021)).thenReturn(expected); MvcResult mvcResult = mvc .perform(MockMvcRequestBuilders.get("/categoryschedule/getcategoryschedulesbyyear") .contentType(MediaType.APPLICATION_JSON_VALUE).param("year", "2021")) .andReturn(); Assertions.assertEquals(HttpStatus.OK.value(), mvcResult.getResponse().getStatus(), "Expected operation was correct"); } }
51.422764
120
0.658024
c66cac596060ff4330aa275168bd653abae93830
1,143
package com.daiwj.invoker.demo.okhttp; import com.daiwj.invoker.runtime.ISource; /** * author: daiwj on 2020/12/3 19:05 */ public class TestSource implements ISource { private static final int SUCCESS = 1; private int status; private String code; private Object data; private String message; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getCode() { return code == null ? "" : code; } public void setCode(String code) { this.code = code; } public void setData(String data) { this.data = data; } public Object getData() { return data; } public String getMessage() { return message == null ? "" : message; } public void setMessage(String message) { this.message = message; } @Override public boolean isSuccessful() { return status == SUCCESS; } @Override public String data() { final Object object = getData(); return object == null ? "" : object.toString(); } }
19.05
55
0.588801
127ee24670259fc1d5c965766c6e782812968a48
11,101
package com.botian.yihu.fragment; import android.Manifest; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.text.Html; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.WebView; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.botian.yihu.R; import com.botian.yihu.activity.VideoActivity; import com.botian.yihu.activity.VideoBuyActivity; import com.botian.yihu.api.ApiMethods; import com.botian.yihu.beans.UserInfo; import com.botian.yihu.beans.VodeoBuyList; import com.botian.yihu.eventbus.VideoBuyEvent; import com.botian.yihu.rxjavautil.MyObserver; import com.botian.yihu.rxjavautil.ObserverOnNextListener; import com.botian.yihu.rxjavautil.ProgressObserver; import com.botian.yihu.util.ACache; import com.botian.yihu.util.SubjectUtil; import com.trello.rxlifecycle2.components.support.RxAppCompatActivity; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; /** * Created by Administrator on 2018/1/12 0012. */ //资讯 public class VideoIntroduceFragment extends Fragment { String title1; String price1; String content1; String id; Unbinder unbinder; @BindView(R.id.price) TextView price; @BindView(R.id.phone) Button phone; @BindView(R.id.buy) Button buy; @BindView(R.id.show) WebView show; private ACache mCache; private UserInfo userInfo; VideoActivity activity; private String[] perms = {Manifest.permission.CALL_PHONE}; private final int PERMS_REQUEST_CODE = 200; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_video_introduce, container, false); unbinder = ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); EventBus.getDefault().register(this); mCache = ACache.get(getActivity()); //从缓存读取用户信息 userInfo = (UserInfo) mCache.getAsObject("userInfo"); activity = (VideoActivity) getActivity(); Bundle bundle = getArguments(); title1 = bundle.getString("ARGS"); price1 = bundle.getString("ARGS1"); content1 = bundle.getString("ARGS2"); id = bundle.getString("ARGS3"); String strPrice = price1+"金币"; price.setText(strPrice); searchBuy(); String text = Html.fromHtml(content1).toString(); //http://btsc.botian120.com String cc = text.replaceAll("<img src=\"", "<img src=\"http://btsc.botian120.com"); show.loadDataWithBaseURL(null, getNewContent(cc), "text/html", "utf-8", null); } /** * 将html文本内容中包含img标签的图片,宽度变为屏幕宽度,高度根据宽度比例自适应 **/ public static String getNewContent(String htmltext) { try { Document doc = Jsoup.parse(htmltext); Elements elements = doc.getElementsByTag("img"); for (Element element : elements) { element.attr("width", "100%").attr("height", "auto"); } return doc.toString(); } catch (Exception e) { return htmltext; } } public static VideoIntroduceFragment newInstance(String title, String price, String content, String id) { Bundle args = new Bundle(); args.putString("ARGS", title); args.putString("ARGS1", price); args.putString("ARGS2", content); args.putString("ARGS3", id); VideoIntroduceFragment fragment = new VideoIntroduceFragment(); fragment.setArguments(args); return fragment; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @OnClick({R.id.phone, R.id.buy}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.phone: final Dialog dialog2 = new Dialog(getActivity(), R.style.NormalDialogStyle); View view2 = View.inflate(getActivity(), R.layout.dialog_buy, null); LinearLayout lnPhone = view2.findViewById(R.id.ln_phone); LinearLayout lnQq = view2.findViewById(R.id.ln_qq); dialog2.setContentView(view2); //使得点击对话框外部消失对话框 dialog2.setCanceledOnTouchOutside(true); //设置对话框的大小 Window dialogWindow2 = dialog2.getWindow(); dialogWindow2.setWindowAnimations(R.style.bottom_menu_animation); WindowManager.LayoutParams lp2 = dialogWindow2.getAttributes(); //lp2.width = (int) (ScreenSizeUtils.getInstance(this).getScreenWidth() * 0.85f); lp2.height = WindowManager.LayoutParams.WRAP_CONTENT; lp2.gravity = Gravity.BOTTOM; //dialogWindow2.setAttributes(lp2); lnPhone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog2.dismiss(); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {//Android 6.0以上版本需要获取权限 requestPermissions(perms, PERMS_REQUEST_CODE);//请求权限 } else { callPhone(); } /** * 拨打电话(直接拨打电话) * * @param phoneNum 电话号码 */ } }); lnQq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog2.dismiss(); if (isQQClientAvailable(getActivity())) { final String qqUrl = "mqqwpa://im/chat?chat_type=wpa&uin=408685957&version=1"; startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl))); } else { Toast.makeText(getActivity(), "请安装QQ客户端", Toast.LENGTH_SHORT).show(); } } }); dialog2.show(); break; case R.id.buy: ObserverOnNextListener<VodeoBuyList> listenerllf = new ObserverOnNextListener<VodeoBuyList>() { @Override public void onNext(VodeoBuyList data) { if (data.getData().size() <= 0) { //buy.setText("已购买"); Intent intent = new Intent(getActivity(), VideoBuyActivity.class); intent.putExtra("id", id); intent.putExtra("money", price1); intent.putExtra("title", title1); startActivity(intent); } else { Toast.makeText(getActivity(), "已经购买过,无需再次购买", Toast.LENGTH_SHORT).show(); } } }; String filter = "userid,eq," + userInfo.getId(); String filter2 = "column_id,eq," + SubjectUtil.getSubjectNo2(); String filter3 = "video_id,eq," + id; ApiMethods.getVideoBuyList2(new ProgressObserver<VodeoBuyList>(getActivity(), listenerllf), filter, filter2, filter3, (RxAppCompatActivity) getActivity()); break; } } public void searchBuy() { ObserverOnNextListener<VodeoBuyList> listenerll = new ObserverOnNextListener<VodeoBuyList>() { @Override public void onNext(VodeoBuyList data) { if (data.getData().size() > 0) { buy.setText("已购买"); activity.setBuy("1"); } } }; String filter = "userid,eq," + userInfo.getId(); String filter2 = "column_id,eq," + SubjectUtil.getSubjectNo2(); String filter3 = "video_id,eq," + id; ApiMethods.getVideoBuyList(new MyObserver<VodeoBuyList>(listenerll), filter, filter2, filter3, (RxAppCompatActivity) getActivity()); } /** * 获取权限回调方法 * * @param permsRequestCode * @param permissions * @param grantResults */ @Override public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) { switch (permsRequestCode) { case PERMS_REQUEST_CODE: boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (storageAccepted) { callPhone(); } else { //Log.i("MainActivity", "没有权限操作这个请求"); } break; } } //拨打电话 private void callPhone() { //检查拨打电话权限 if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + "0371-56871616")); startActivity(intent); } } //判断qq客户端是否安装 public static boolean isQQClientAvailable(Context context) { final PackageManager packageManager = context.getPackageManager(); List<PackageInfo> pinfo = packageManager.getInstalledPackages(0); if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { String pn = pinfo.get(i).packageName; if (pn.equals("com.tencent.mobileqq")) { return true; } } } return false; } @Subscribe(threadMode = ThreadMode.MAIN) public void Event(VideoBuyEvent messageEvent) { buy.setText("已购买"); activity.setBuy("1"); } @Override public void onDestroy() { super.onDestroy(); if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } } }
36.636964
171
0.595172
4f77c36b4d65004aab9aadfdc49f3d4b4b3f07ba
1,699
package leetcode.zidianshu; /** * @description: * @author: LiYuan * @version: 1.0 * @create: 2020-06-28 **/ public class Trie { class TrieNode { boolean end; TrieNode []nodes; TrieNode() { end = false; nodes = new TrieNode[26]; } } TrieNode root; /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode node = root; TrieNode next; char []arr = word.toCharArray(); for (char c : arr) { next = node.nodes[c - 'a']; if (next == null) { next = new TrieNode(); node.nodes[c - 'a'] = next; } node = next; } node.end = true; } /** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode node = root; TrieNode next; char []arr = word.toCharArray(); for (char c : arr) { next = node.nodes[c - 'a']; if (next == null) { return false; } node = next; } return node.end; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode node = root; TrieNode next; char []arr = prefix.toCharArray(); for (char c : arr) { next = node.nodes[c - 'a']; if (next == null) { return false; } node = next; } return true; } }
23.929577
86
0.466745
86591c9211eec17c9a009ccec07cfcd6d34e4b06
548
package sharpen.xobotos.api.interop.glue; public class CastExpression extends Expression { private final AbstractTypeReference _type; private final Expression _expr; public CastExpression(AbstractTypeReference type, Expression expr) { this._type = type; this._expr = expr; } @Override protected boolean needParens() { return true; } public AbstractTypeReference getType() { return _type; } public Expression getExpression() { return _expr; } @Override public void accept(Visitor visitor) { visitor.visit(this); } }
17.677419
69
0.748175
e421ec5b76a5bb2bd64b728ce3e6d2a0ada8225d
2,096
package com.sxzheng.tasklibrary; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * @author zheng. */ public class TaskManager { private AtomicInteger mSequenceGenerator = new AtomicInteger(); private final Map<String, Queue<Task<?>>> mWaitingTasks = new HashMap<>(); private final Set<Task<?>> mCurrentTasks = new HashSet<>(); private final PriorityBlockingQueue<Task<?>> mQueue = new PriorityBlockingQueue<>(); private static final int DEFAULT_THREAD_POOL_SIZE = 4; private TaskDispatcher[] mTaskDispatchers; public TaskManager() { mTaskDispatchers = new TaskDispatcher[DEFAULT_THREAD_POOL_SIZE]; } public TaskManager(int threadPoolSize) { mTaskDispatchers = new TaskDispatcher[threadPoolSize]; } public void offer(Task<?> task) { if (task != null) { try { task.setTaskManager(this); } catch (Exception e) { e.printStackTrace(); return; } task.setSequence(getSequenceNumber()); mQueue.offer(task); } } public void start() { stop(); for (int i = 0; i < mTaskDispatchers.length; i++) { TaskDispatcher taskDispatcher = new TaskDispatcher(mQueue); taskDispatcher.setName("TaskDispatcher " + i); mTaskDispatchers[i] = taskDispatcher; mTaskDispatchers[i].start(); } } private void stop() { for (TaskDispatcher mTaskDispatcher : mTaskDispatchers) { if (mTaskDispatcher != null) mTaskDispatcher.quit(); } } public int getSequenceNumber(){ return mSequenceGenerator.incrementAndGet(); } public void cancelAll() { synchronized (mCurrentTasks) { for (Task task : mCurrentTasks) { task.cancel(); } } } }
26.2
72
0.609256
cba3400775be69271fee2f9c3d783997f5e827df
15,540
// Copyright 2016 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package com.firebase.jobdispatcher; import static android.content.Context.BIND_AUTO_CREATE; import static com.firebase.jobdispatcher.TestUtil.getContentUriTrigger; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.annotation.NonNull; import com.firebase.jobdispatcher.JobService.JobResult; import com.google.common.util.concurrent.SettableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; /** Tests for the {@link ExecutionDelegator}. */ @SuppressWarnings("WrongConstant") @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, sdk = 21) public class ExecutionDelegatorTest { private TestJobReceiver receiver; private ExecutionDelegator executionDelegator; private IRemoteJobService.Stub noopBinder; @Captor private ArgumentCaptor<Intent> intentCaptor; @Captor private ArgumentCaptor<JobServiceConnection> connCaptor; @Captor private ArgumentCaptor<IJobCallback> jobCallbackCaptor; @Captor private ArgumentCaptor<Bundle> bundleCaptor; @Mock private Context mockContext; @Mock private IRemoteJobService jobServiceMock; @Mock private IBinder iBinderMock; @Mock ConstraintChecker constraintChecker; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(mockContext.getPackageName()).thenReturn("com.example.foo"); when(constraintChecker.areConstraintsSatisfied(any(JobInvocation.class))).thenReturn(true); receiver = new TestJobReceiver(); executionDelegator = new ExecutionDelegator(mockContext, receiver, constraintChecker); ExecutionDelegator.cleanServiceConnections(); noopBinder = new IRemoteJobService.Stub() { @Override public void start(Bundle invocationData, IJobCallback callback) {} @Override public void stop(Bundle invocationData, boolean needToSendResult) {} }; } @After public void tearDown() { ExecutionDelegator.cleanServiceConnections(); } @Test public void jobFinished() throws RemoteException { JobInvocation jobInvocation = new JobInvocation.Builder() .setTag("tag") .setService("service") .setTrigger(Trigger.NOW) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(true); executionDelegator.executeJob(jobInvocation); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); JobServiceConnection connection = connCaptor.getValue(); when(iBinderMock.queryLocalInterface(IRemoteJobService.class.getName())) .thenReturn(jobServiceMock); connection.onServiceConnected(null, iBinderMock); verify(jobServiceMock).start(bundleCaptor.capture(), jobCallbackCaptor.capture()); jobCallbackCaptor .getValue() .jobFinished(bundleCaptor.getValue(), JobService.RESULT_FAIL_NORETRY); assertNull(ExecutionDelegator.getJobServiceConnection("service")); assertEquals(JobService.RESULT_FAIL_NORETRY, receiver.lastResult); assertTrue(connection.wasUnbound()); } @Test public void testExecuteJob_sendsBroadcastWithJobAndMessage() throws Exception { for (JobInvocation input : TestUtil.getJobInvocationCombinations()) { verifyExecuteJob(input); // Reset mocks for the next invocation reset(mockContext); receiver.lastResult = -1; } } @Test public void executeJob_constraintsUnsatisfied_schedulesJobRetry() throws RemoteException { // Simulate job constraints not being met. JobInvocation jobInvocation = new JobInvocation.Builder() .setTag("tag") .setService("service") .setTrigger(Trigger.NOW) .build(); when(constraintChecker.areConstraintsSatisfied(eq(jobInvocation))).thenReturn(false); executionDelegator.executeJob(jobInvocation); // Confirm that service not bound verify(mockContext, never()) .bindService(any(Intent.class), any(JobServiceConnection.class), anyInt()); assertThat(ExecutionDelegator.getJobServiceConnection("service")).isNull(); // Verify that job is set for a retry later. assertThat(receiver.lastResult).isEqualTo(JobService.RESULT_FAIL_RETRY); } @Test public void executeJob_alreadyRunning_doesNotBindSecondTime() { JobInvocation jobInvocation = new JobInvocation.Builder() .setTag("tag") .setService("service") .setTrigger(Trigger.NOW) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(true); executionDelegator.executeJob(jobInvocation); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); connCaptor.getValue().onServiceConnected(null, noopBinder); assertFalse(connCaptor.getValue().wasUnbound()); assertTrue(connCaptor.getValue().isConnected()); reset(mockContext); executionDelegator.executeJob(jobInvocation); assertFalse(connCaptor.getValue().wasUnbound()); verify(mockContext, never()).unbindService(connCaptor.getValue()); verify(mockContext, never()) .bindService(any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE)); } @Test public void executeJob_startedButNotConnected_doNotStartAgain() { JobInvocation jobInvocation = new JobInvocation.Builder() .setTag("tag") .setService("service") .setTrigger(Trigger.NOW) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(true); executionDelegator.executeJob(jobInvocation); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); reset(mockContext); executionDelegator.executeJob(jobInvocation); verify(mockContext, never()) .bindService(any(Intent.class), any(JobServiceConnection.class), eq(BIND_AUTO_CREATE)); } @Test public void executeJob_wasStartedButDisconnected_startAgain() { JobInvocation jobInvocation = new JobInvocation.Builder() .setTag("tag") .setService("service") .setTrigger(Trigger.NOW) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(true); executionDelegator.executeJob(jobInvocation); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); JobServiceConnection jobServiceConnection = connCaptor.getValue(); jobServiceConnection.onServiceConnected(null, noopBinder); jobServiceConnection.unbind(); verify(mockContext).unbindService(jobServiceConnection); reset(mockContext); executionDelegator.executeJob(jobInvocation); verify(mockContext) .bindService(any(Intent.class), any(JobServiceConnection.class), eq(BIND_AUTO_CREATE)); } private void verifyExecuteJob(JobInvocation input) throws Exception { when(mockContext.getPackageName()).thenReturn("com.example.foo"); receiver.setLatch(new CountDownLatch(1)); when(mockContext.bindService( any(Intent.class), any(JobServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(true); executionDelegator.executeJob(input); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); final Intent result = intentCaptor.getValue(); // verify the intent was sent to the right place assertEquals(input.getService(), result.getComponent().getClassName()); assertEquals(JobService.ACTION_EXECUTE, result.getAction()); final JobServiceConnection connection = connCaptor.getValue(); final AtomicReference<JobParameters> jobParametersAtomicReference = new AtomicReference<>(); IRemoteJobService.Stub jobServiceBinder = new IRemoteJobService.Stub() { @Override public void start(Bundle invocationData, IJobCallback callback) { jobParametersAtomicReference.set( GooglePlayReceiver.getJobCoder().decode(invocationData).build()); } @Override public void stop(Bundle invocationData, boolean needToSendResult) {} }; connection.onServiceConnected(null, jobServiceBinder); TestUtil.assertJobsEqual(input, jobParametersAtomicReference.get()); // Clean up started job. Otherwise new job won't be started. ExecutionDelegator.stopJob(input, false); } @Test public void testExecuteJob_handlesNull() { executionDelegator.executeJob(null); verifyZeroInteractions(mockContext); } @Test public void testHandleMessage_doesntCrashOnBadJobData() { JobInvocation j = new JobInvocation.Builder() .setService(TestJobService.class.getName()) .setTag("tag") .setTrigger(Trigger.NOW) .build(); executionDelegator.executeJob(j); // noinspection WrongConstant verify(mockContext).bindService(intentCaptor.capture(), connCaptor.capture(), anyInt()); Intent executeReq = intentCaptor.getValue(); assertEquals(JobService.ACTION_EXECUTE, executeReq.getAction()); } @Test public void onStop_mock() throws Exception { JobInvocation job = new JobInvocation.Builder() .setTag("TAG") .setTrigger(getContentUriTrigger()) .setService(TestJobService.class.getName()) .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(true); executionDelegator.executeJob(job); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); final Intent bindIntent = intentCaptor.getValue(); // verify the intent was sent to the right place assertEquals(job.getService(), bindIntent.getComponent().getClassName()); assertEquals(JobService.ACTION_EXECUTE, bindIntent.getAction()); final SettableFuture<JobParameters> startedJobFuture = SettableFuture.create(); final SettableFuture<JobParameters> stoppedJobFuture = SettableFuture.create(); IRemoteJobService.Stub jobServiceBinder = new IRemoteJobService.Stub() { @Override public void start(Bundle invocationData, IJobCallback callback) { startedJobFuture.set(GooglePlayReceiver.getJobCoder().decode(invocationData).build()); } @Override public void stop(Bundle invocationData, boolean needToSendResult) { stoppedJobFuture.set(GooglePlayReceiver.getJobCoder().decode(invocationData).build()); } }; final ServiceConnection connection = connCaptor.getValue(); connection.onServiceConnected(null, jobServiceBinder); ExecutionDelegator.stopJob(job, /* needToSendResult= */ false); TestUtil.assertJobsEqual(job, startedJobFuture.get(0, TimeUnit.SECONDS)); verify(mockContext, timeout(1_000)).unbindService(connection); } @Test public void failedToBind_unbind() throws Exception { JobInvocation job = new JobInvocation.Builder() .setTag("TAG") .setTrigger(getContentUriTrigger()) .setService(TestJobService.class.getName()) .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenReturn(false); executionDelegator.executeJob(job); verify(mockContext) .bindService(intentCaptor.capture(), connCaptor.capture(), eq(BIND_AUTO_CREATE)); verify(mockContext).unbindService(connCaptor.getValue()); assertEquals(JobService.RESULT_FAIL_RETRY, receiver.lastResult); } @Test public void securityException_unbinds() throws Exception { JobInvocation job = new JobInvocation.Builder() .setTag("TAG") .setTrigger(getContentUriTrigger()) .setService(TestJobService.class.getName()) .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) .build(); when(mockContext.bindService( any(Intent.class), any(ServiceConnection.class), eq(BIND_AUTO_CREATE))) .thenThrow(new SecurityException("should have gracefully handled this security exception")); executionDelegator.executeJob(job); // Verify that bindService was actually called verify(mockContext).bindService(any(Intent.class), connCaptor.capture(), eq(BIND_AUTO_CREATE)); // And that unbindService was called in response to the security exception verify(mockContext).unbindService(connCaptor.getValue()); // And that we should have sent RESULT_FAIL_RETRY back to the calling component assertEquals(JobService.RESULT_FAIL_RETRY, receiver.lastResult); } private static final class TestJobReceiver implements ExecutionDelegator.JobFinishedCallback { int lastResult = -1; private CountDownLatch latch; @Override public void onJobFinished(@NonNull JobInvocation js, @JobResult int result) { lastResult = result; if (latch != null) { latch.countDown(); } } /** Convenience method for tests. */ public void setLatch(CountDownLatch latch) { this.latch = latch; } } }
35.889145
100
0.717889
4fed907c834d0faf6dc3bf1deb589806a707400b
1,343
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: RefreshException.java,v 1.3 2010/01/04 15:50:55 cwl Exp $ */ package com.sleepycat.persist.impl; /** * Thrown and handled internally when metadata must be refreshed on a Replica. * See the refresh() method below. */ public class RefreshException extends RuntimeException { private final Store store; private final PersistCatalog catalog; private final int formatId; RefreshException(final Store store, final PersistCatalog catalog, final int formatId) { this.store = store; this.catalog = catalog; this.formatId = formatId; } /** * This method must be called to handle this exception in the binding * methods, after the stack has rewound. The binding methods should retry * the operation once after calling this method. If the operation fails * again, then corruption rather than stale metadata is the likely cause * of the problem, and an exception will be thrown to that effect. * [#16655] */ PersistCatalog refresh() { return store.refresh(catalog, formatId); } @Override public String getMessage() { return "formatId=" + formatId; } }
29.195652
78
0.662695
4fada79c6d14fe63b51f263723098c60279f04a1
4,950
package com.pi4j.plugin.mock; /*- * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: PLUGIN :: Mock Platform & Providers * FILENAME : Mock.java * * This file is part of the Pi4J project. More information about * this project can be found here: https://pi4j.com/ * ********************************************************************** * * This program 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 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * <p>Mock class.</p> * * @author Robert Savage (<a href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) * @version $Id: $Id */ public class Mock { /** Constant <code>NAME="Mock"</code> */ public static final String NAME = "Mock"; /** Constant <code>ID="mock"</code> */ public static final String ID = "mock"; // Platform name and unique ID /** Constant <code>PLATFORM_NAME="NAME + Platform"</code> */ public static final String PLATFORM_NAME = NAME + " Platform"; /** Constant <code>PLATFORM_ID="ID + -platform"</code> */ public static final String PLATFORM_ID = ID + "-platform"; /** Constant <code>PLATFORM_DESCRIPTION="Pi4J platform used for mock testing."</code> */ public static final String PLATFORM_DESCRIPTION = "Pi4J platform used for mock testing."; // Analog Input (GPIO) Provider name and unique ID /** Constant <code>ANALOG_INPUT_PROVIDER_NAME="NAME + Analog Input (GPIO) Provider"</code> */ public static final String ANALOG_INPUT_PROVIDER_NAME = NAME + " Analog Input (GPIO) Provider"; /** Constant <code>ANALOG_INPUT_PROVIDER_ID="ID + -analog-input"</code> */ public static final String ANALOG_INPUT_PROVIDER_ID = ID + "-analog-input"; // Analog Output (GPIO) Provider name and unique ID /** Constant <code>ANALOG_OUTPUT_PROVIDER_NAME="NAME + Analog Output (GPIO) Provider"</code> */ public static final String ANALOG_OUTPUT_PROVIDER_NAME = NAME + " Analog Output (GPIO) Provider"; /** Constant <code>ANALOG_OUTPUT_PROVIDER_ID="ID + -analog-output"</code> */ public static final String ANALOG_OUTPUT_PROVIDER_ID = ID + "-analog-output"; // Digital Input (GPIO) Provider name and unique ID /** Constant <code>DIGITAL_INPUT_PROVIDER_NAME="NAME + Digital Input (GPIO) Provider"</code> */ public static final String DIGITAL_INPUT_PROVIDER_NAME = NAME + " Digital Input (GPIO) Provider"; /** Constant <code>DIGITAL_INPUT_PROVIDER_ID="ID + -digital-input"</code> */ public static final String DIGITAL_INPUT_PROVIDER_ID = ID + "-digital-input"; // Digital Output (GPIO) Provider name and unique ID /** Constant <code>DIGITAL_OUTPUT_PROVIDER_NAME="NAME + Digital Output (GPIO) Provider"</code> */ public static final String DIGITAL_OUTPUT_PROVIDER_NAME = NAME + " Digital Output (GPIO) Provider"; /** Constant <code>DIGITAL_OUTPUT_PROVIDER_ID="ID + -digital-output"</code> */ public static final String DIGITAL_OUTPUT_PROVIDER_ID = ID + "-digital-output"; // PWM Provider name and unique ID /** Constant <code>PWM_PROVIDER_NAME="NAME + PWM Provider"</code> */ public static final String PWM_PROVIDER_NAME = NAME + " PWM Provider"; /** Constant <code>PWM_PROVIDER_ID="ID + -pwm"</code> */ public static final String PWM_PROVIDER_ID = ID + "-pwm"; // I2C Provider name and unique ID /** Constant <code>I2C_PROVIDER_NAME="NAME + I2C Provider"</code> */ public static final String I2C_PROVIDER_NAME = NAME + " I2C Provider"; /** Constant <code>I2C_PROVIDER_ID="ID + -i2c"</code> */ public static final String I2C_PROVIDER_ID = ID + "-i2c"; // SPI Provider name and unique ID /** Constant <code>SPI_PROVIDER_NAME="NAME + SPI Provider"</code> */ public static final String SPI_PROVIDER_NAME = NAME + " SPI Provider"; /** Constant <code>SPI_PROVIDER_ID="ID + -spi"</code> */ public static final String SPI_PROVIDER_ID = ID + "-spi"; // Serial Provider name and unique ID /** Constant <code>SERIAL_PROVIDER_NAME="NAME + Serial Provider"</code> */ public static final String SERIAL_PROVIDER_NAME = NAME + " Serial Provider"; /** Constant <code>SERIAL_PROVIDER_ID="ID + -serial"</code> */ public static final String SERIAL_PROVIDER_ID = ID + "-serial"; }
50.510204
112
0.673737
b08f153b4fd6d30fd0c272ab23490a607e766612
1,761
package seedu.address.logic.commands; import static seedu.address.logic.parser.CliSyntax.PREFIX_MODULE_CODE; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.module.Module; import seedu.address.model.module.ModuleCode; import seedu.address.model.module.ModuleManager; /** * Views the details of a module in Trajectory. */ public class ModuleViewCommand extends Command { public static final String COMMAND_WORD = "module view"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Views the details of a module in Trajectory. " + "Parameters: " + PREFIX_MODULE_CODE + "MODULE_CODE\n" + "Example: " + COMMAND_WORD + " " + PREFIX_MODULE_CODE + "CS2113"; public static final String MESSAGE_SUCCESS = "Viewing details of %1$s."; private static final String MESSAGE_MODULE_NOT_FOUND = "Module with code %s doesn't exist in Trajectory!"; private final ModuleCode moduleCode; public ModuleViewCommand(ModuleCode moduleCode) { this.moduleCode = moduleCode; } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { if (!ModuleManager.getInstance().doesModuleExist(moduleCode.moduleCode)) { throw new CommandException(String.format(MESSAGE_MODULE_NOT_FOUND, moduleCode.moduleCode)); } Module module = ModuleManager.getInstance().getModuleByModuleCode(moduleCode.moduleCode); return new CommandResult(String.format(MESSAGE_SUCCESS, moduleCode.moduleCode), ModuleManager.getInstance().getModuleAsHtmlRepresentation(module)); } }
38.282609
111
0.735945
95239da1d92528f867b2804af85d98ba23548555
894
package com.coracle.dms.service.impl; import com.coracle.dms.dao.mybatis.DmsExceptionClaimsMapper; import com.coracle.dms.po.DmsExceptionClaims; import com.coracle.dms.service.DmsExceptionClaimsService; import com.coracle.yk.xdatabase.base.mybatis.intf.IMybatisDao; import com.coracle.yk.xservice.base.BaseServiceImpl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DmsExceptionClaimsServiceImpl extends BaseServiceImpl<DmsExceptionClaims> implements DmsExceptionClaimsService { private static final Logger logger = Logger.getLogger(DmsExceptionClaimsServiceImpl.class); @Autowired private DmsExceptionClaimsMapper dmsExceptionClaimsMapper; @Override public IMybatisDao<DmsExceptionClaims> getBaseDao() { return dmsExceptionClaimsMapper; } }
38.869565
125
0.829978
cc12c590dd7f9be4a7a48c2cc17332532d0ff206
174
package io.github.ReadyMadeProgrammer.ByteTrigger.Common; public interface BTVariableStorageFactory { BTVariableStorage create(String id, ByteTriggerRuntime runtime); }
29
68
0.83908
f4f910d544ccf780d8c7f9b3ac2bdaa144e48a92
7,776
package com.yupaits.msg.controller; import com.yupaits.msg.entity.Message; import com.yupaits.msg.entity.MessageUser; import com.yupaits.msg.entity.Template; import com.yupaits.msg.service.IMessageService; import com.yupaits.msg.service.IMessageUserService; import com.yupaits.msg.service.ITemplateService; import com.yupaits.msg.vo.TemplateVO; import com.yupaits.msg.dto.TemplateCreate; import com.yupaits.msg.dto.TemplateUpdate; import com.yupaits.commons.utils.ValidateUtils; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import java.util.Map; import org.apache.commons.collections4.MapUtils; import com.yupaits.commons.result.Result; import com.yupaits.commons.result.ResultWrapper; import com.yupaits.commons.result.ResultCode; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import io.swagger.annotations.*; import java.util.List; import java.util.stream.Collectors; /** * <p> * 消息模板 前端控制器 * </p> * * @author yupaits * @since 2018-11-08 */ @Slf4j @Api(tags = "消息模板接口") @RestController @RequestMapping("/msg/template") public class TemplateController { private final ITemplateService templateService; private final IMessageUserService messageUserService; private final IMessageService messageService; @Autowired public TemplateController(ITemplateService templateService, IMessageUserService messageUserService, IMessageService messageService) { this.templateService = templateService; this.messageUserService = messageUserService; this.messageService = messageService; } @ApiOperation("创建消息模板") @PostMapping("") public Result addTemplate(@RequestBody TemplateCreate templateCreate) { if (!templateCreate.isValid()) { return ResultWrapper.fail(ResultCode.PARAMS_ERROR); } Template template = new Template(); BeanUtils.copyProperties(templateCreate, template); return templateService.save(template) ? ResultWrapper.success() : ResultWrapper.fail(ResultCode.CREATE_FAIL); } @ApiOperation("编辑消息模板") @PutMapping("/{id:\\d{19}}") public Result updateTemplate(@RequestBody TemplateUpdate templateUpdate) { if (!templateUpdate.isValid()) { return ResultWrapper.fail(ResultCode.PARAMS_ERROR); } Template template = new Template(); BeanUtils.copyProperties(templateUpdate, template); return templateService.updateById(template) ? ResultWrapper.success() : ResultWrapper.fail(ResultCode.UPDATE_FAIL); } @ApiOperation("批量保存消息模板") @PutMapping("/batch-save") public Result batchSaveTemplate(@RequestBody List<TemplateUpdate> templateUpdateList) { if (!TemplateUpdate.isValid(templateUpdateList)) { return ResultWrapper.fail(ResultCode.PARAMS_ERROR); } List<Template> templateList = templateUpdateList.stream().map(templateUpdate -> { Template template = new Template(); BeanUtils.copyProperties(templateUpdate, template); return template; }).collect(Collectors.toList()); return templateService.saveOrUpdateBatch(templateList) ? ResultWrapper.success() : ResultWrapper.fail(ResultCode.SAVE_FAIL); } @ApiOperation("根据ID删除消息模板") @DeleteMapping("/{id:\\d{19}}") public Result deleteTemplate(@PathVariable Long id) { if (!ValidateUtils.idValid(id)) { return ResultWrapper.fail(ResultCode.PARAMS_ERROR); } List<Object> messageIds = messageUserService.listObjs(new QueryWrapper<MessageUser>().select("message_id").groupBy("message_id")); if (CollectionUtils.isNotEmpty(messageIds) && messageService.count(new QueryWrapper<Message>() .in("id", messageIds).eq("use_template", true).eq("msg_template_id", id)) > 0) { return ResultWrapper.fail(ResultCode.DATA_CANNOT_DELETE); } return templateService.removeById(id) ? ResultWrapper.success() : ResultWrapper.fail(ResultCode.DELETE_FAIL); } @ApiOperation("根据ID获取消息模板信息") @GetMapping("/{id:\\d{19}}") public Result getTemplate(@PathVariable Long id) { if (!ValidateUtils.idValid(id)) { return ResultWrapper.fail(ResultCode.PARAMS_ERROR); } Template template = templateService.getById(id); if (template == null) { return ResultWrapper.fail(ResultCode.DATA_NOT_FOUND); } TemplateVO templateVO = new TemplateVO(); BeanUtils.copyProperties(template, templateVO); return ResultWrapper.success(templateVO); } @ApiOperation("按条件获取消息模板列表") @PostMapping("/list") public Result getTemplateList(@RequestBody(required = false) Map<String, Object> query) { QueryWrapper<Template> queryWrapper = new QueryWrapper<>(); if (MapUtils.isNotEmpty(query)) { query.forEach((key, value) -> { //TODO 设置查询条件 }); } List<TemplateVO> templateVOList = templateService.list(queryWrapper).stream().map(template -> { TemplateVO templateVO = new TemplateVO(); BeanUtils.copyProperties(template, templateVO); return templateVO; }).collect(Collectors.toList()); return ResultWrapper.success(templateVOList); } @ApiOperation("获取消息模板分页信息") @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataType = "int", paramType = "query"), @ApiImplicitParam(name = "size", value = "每页数量", defaultValue = "10", dataType = "int", paramType = "query")}) @PostMapping("/page") public Result getTemplatePage(@RequestParam(required = false, defaultValue = "1") int page, @RequestParam(required = false, defaultValue = "10") int size, @RequestParam(required = false) @ApiParam(value = "降序字段") List<String> descs, @RequestParam(required = false) @ApiParam(value = "升序字段") List<String> ascs, @RequestBody(required = false) Map<String, Object> query) { Page<Template> pager = new Page<>(page, size); if (CollectionUtils.isNotEmpty(descs)) { pager.setDescs(descs); } if (CollectionUtils.isNotEmpty(ascs)) { pager.setAscs(ascs); } QueryWrapper<Template> queryWrapper = new QueryWrapper<>(); if (MapUtils.isNotEmpty(query)) { query.forEach((key, value) -> { if (StringUtils.equals(key, "keyword")) { queryWrapper.and(i -> i.like("name", value).or().like("template_pattern", value)); } if (StringUtils.equals(key, "msgType") && value != null) { queryWrapper.eq("msg_type", value); } }); } IPage<TemplateVO> templateVOPage = new Page<>(); BeanUtils.copyProperties(templateService.page(pager, queryWrapper), templateVOPage); templateVOPage.setRecords(pager.getRecords().stream().map(template -> { TemplateVO templateVO = new TemplateVO(); BeanUtils.copyProperties(template, templateVO); return templateVO; }).collect(Collectors.toList())); return ResultWrapper.success(templateVOPage); } }
43.441341
138
0.673868
1c1f0bfff2deb22c972c09122001be69f7ec6371
1,918
package com.navigation.dialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.navigation.R; import com.navigation.androidx.AwesomeFragment; import com.navigation.androidx.FragmentHelper; import com.navigation.androidx.PresentAnimation; public class NestedFragmentDialogFragment extends AwesomeFragment { @Override public boolean isParentFragment() { return true; } // @Override // protected AwesomeFragment childFragmentForAppearance() { // return getContentFragment(); // } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_nested_dialog, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState == null) { if (contentFragment == null) { throw new IllegalArgumentException("必须先通过 `setContentFragment` 指定 contentFragment"); } FragmentHelper.addFragmentToBackStack(getChildFragmentManager(), R.id.nested_content, contentFragment, PresentAnimation.None); } } private AwesomeFragment contentFragment; public void setContentFragment(AwesomeFragment fragment) { if (isAdded()) { throw new IllegalStateException("NavigationFragment 已经出于 added 状态,不可以再设置 rootFragment"); } contentFragment = fragment; } public AwesomeFragment getContentFragment() { if (isAdded()) { return (AwesomeFragment) getChildFragmentManager().findFragmentById(R.id.nested_content); } return null; } }
30.935484
139
0.714807
796fcbe28a02197ddec8c4d12a7c7a9930fb8e05
245
package org.gflogger; /** * @author Denis Gburg */ public interface FormattingStrategy { boolean isPlaceholder(String pattern, int position); boolean isEscape(String pattern, int position); boolean autocommitEnabled(); }
16.333333
54
0.710204
a3bbed6c5f567f09c40ee1990cd3340f08d3cc16
2,187
package org.ethereum.jsonrpc.model; import org.ethereum.core.Transaction; import static org.ethereum.jsonrpc.Utils.bytes2Long; import static org.ethereum.jsonrpc.Utils.toHexStringNullSafe; public class TransactionData { private String hash; private String nonce; private String value; private String to; private String gasPrice; private long gas; private String input; private String from; public TransactionData(Transaction tx) { if(tx == null) { return; } hash = "0x" + toHexStringNullSafe(tx.getHash()); nonce = "0x" + toHexStringNullSafe(tx.getNonce()); value = "0x" + toHexStringNullSafe(tx.getValue()); to = "0x" + (toHexStringNullSafe(tx.getReceiveAddress()) == null ? "0000000000000000000000000000000000000000" : toHexStringNullSafe(tx.getReceiveAddress())); gasPrice = "0x" + toHexStringNullSafe(tx.getGasPrice()); gas = bytes2Long(tx.getGasLimit()); input = "0x" + toHexStringNullSafe(tx.getData()); from = "0x" + toHexStringNullSafe(tx.getSender()); } @Override public String toString() { final StringBuffer sb = new StringBuffer("TransactionData{"); sb.append("hash='").append(hash).append('\''); sb.append(", nonce='").append(nonce).append('\''); sb.append(", value='").append(value).append('\''); sb.append(", receiveAddress='").append(to).append('\''); sb.append(", gasPrice='").append(gasPrice).append('\''); sb.append(", data='").append(input).append('\''); sb.append(", sender='").append(from).append('\''); sb.append('}'); return sb.toString(); } public String getHash() { return hash; } public String getNonce() { return nonce; } public String getValue() { return value; } public String getTo() { return to; } public String getGasPrice() { return gasPrice; } public long getGas() { return gas; } public String getInput() { return input; } public String getFrom() { return from; } }
26.349398
119
0.594422
e217a4f53e3dc97faf8267028b1f4543bee07a67
2,044
package com.zhongti.huacailauncher.model.entity; /** * Create by ShuHeMing on 18/6/8 */ public class LottiDetailEntity { /** * reward : 5000000 * standard : 12 * backImg : http://101.200.52.248/file/15240219831243467.JPEG * playInfo : 666 * frontImg : http://101.200.52.248/file/15240219831243467.JPEG * price : 50 * name : 富贵有余 * id : 35 * sales : 0 */ private int reward; private int standard; private String backImg; private String playInfo; private String frontImg; private String img; private String price; private String name; private long id; private int sales; public int getReward() { return reward; } public void setReward(int reward) { this.reward = reward; } public int getStandard() { return standard; } public void setStandard(int standard) { this.standard = standard; } public String getBackImg() { return backImg; } public void setBackImg(String backImg) { this.backImg = backImg; } public String getPlayInfo() { return playInfo; } public void setPlayInfo(String playInfo) { this.playInfo = playInfo; } public String getFrontImg() { return frontImg; } public void setFrontImg(String frontImg) { this.frontImg = frontImg; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; } }
18.414414
67
0.575342
2f4e4ae4a4dd92b79b6c7d51afa0be60e5f2bf4e
1,469
package com.olerass.pfexample.android.geoquiz.domain.question; import com.olerass.pfexample.android.geoquiz.domain.event.Event; import com.olerass.pfexample.android.geoquiz.domain.event.EventListener; import com.olerass.pfexample.android.geoquiz.domain.state.StateLoader; import com.olerass.pfexample.android.geoquiz.domain.state.StateSaver; public class StandardQuestionModel implements QuestionModel { private final String KEY_INDEX = "index"; private Question[] questions; private int currentIndex = 0; private Event questionTextChangedEvent = new Event(); public StandardQuestionModel(Question[] questions) { this.questions = questions; } @Override public String getQuestionText() { return questions[currentIndex].getText(); } @Override public boolean isCorrectAnswer(boolean answer) { return answer == questions[currentIndex].getCorrectAnswer(); } @Override public void gotoNextQuestion() { currentIndex = (currentIndex + 1) % questions.length; questionTextChangedEvent.dispatch(); } @Override public void whenQuestionTextChanged(EventListener listener) { questionTextChangedEvent.addListener(listener); } public void saveState(StateSaver stateSaver) { stateSaver.saveInt(KEY_INDEX, currentIndex); } public void loadState(StateLoader stateLoader) { currentIndex = stateLoader.loadInt(KEY_INDEX, 0); } }
31.255319
72
0.730429
040b11c02ec49bec46ebb57d59f614c817361e94
1,642
package com.melotic.api.service; import com.melotic.api.dto.DealOrder; import com.melotic.api.dto.DummyMarketMap; import com.melotic.api.dto.DummyPriceTicker; import com.melotic.api.dto.MarketDepth; import com.melotic.api.dto.MarketMap; import com.melotic.api.dto.PriceTicker; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.http.Path; import rx.Observable; import rx.schedulers.Schedulers; class DummyMeloticServiceRxRetrofit implements MeloticServiceRxRetrofit { private static final int DEFAULT_DELAY_MILLISEC = 500; @Override public Observable<MarketMap> getMarkets() { return Observable.<MarketMap>just(new DummyMarketMap()) .observeOn(Schedulers.io()) .delay(DEFAULT_DELAY_MILLISEC, TimeUnit.MILLISECONDS); } @Override public Observable<PriceTicker> getMarketPrice( @Path("marketId") String marketId) { return Observable.<PriceTicker>just(new DummyPriceTicker()); } @Override public Observable<List<MarketDepth>> getBuyDepth( String marketId, Integer count) { throw new IllegalArgumentException("Not implemented"); } @Override public Observable<List<MarketDepth>> getSellDepth( String marketId, Integer count) { throw new IllegalArgumentException("Not implemented"); } @Override public Observable<List<DealOrder>> getDealOrders( String marketId, String orderBy, Integer count, Integer startAt) { throw new IllegalArgumentException("Not implemented"); } }
29.321429
71
0.692448
6b84fbf94636f633dd2cbcd7958de70abe02bedd
343
package com.github.andreashosbach.chat.cucumber; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/resources/feature", glue = "com.github.andreashosbach.chat.cucumber.steps", strict = true) public class CucumberTests { }
28.583333
128
0.801749
4f5f589bd65dce6ad584b7843f9adaa2e2eb5935
3,593
/* * Infinitest, a Continuous Test Runner. * * Copyright (C) 2010-2013 * "Ben Rady" <benrady@gmail.com>, * "Rod Coffin" <rfciii@gmail.com>, * "Ryan Breidenbach" <ryan.breidenbach@gmail.com> * "David Gageot" <david@gageot.net>, et al. * * 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.infinitest.plugin; import static org.infinitest.environment.FakeEnvironments.currentJavaHome; import static org.infinitest.environment.FakeEnvironments.fakeBuildPaths; import static org.infinitest.environment.FakeEnvironments.fakeEnvironment; import static org.infinitest.environment.FakeEnvironments.fakeWorkingDirectory; import static org.infinitest.environment.FakeEnvironments.systemClasspath; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import org.infinitest.FakeEventQueue; import org.infinitest.InfinitestCore; import org.infinitest.InfinitestCoreBuilder; import org.infinitest.environment.RuntimeEnvironment; import org.infinitest.filter.TestFilter; import org.infinitest.parser.TestDetector; import org.junit.Before; import org.junit.Test; public class WhenConfiguringBuilder { protected InfinitestCoreBuilder builder; private TestFilter filterUsedToCreateCore; @Before public final void mustProvideRuntimeEnvironmentAndEventQueue() { RuntimeEnvironment environment = new RuntimeEnvironment(currentJavaHome(), fakeWorkingDirectory(), systemClasspath(), systemClasspath(), fakeBuildPaths(), systemClasspath()); builder = new InfinitestCoreBuilder(environment, new FakeEventQueue()); } @Test public void canUseCustomFilterToRemoveTestsFromTestRun() { TestFilter testFilter = mock(TestFilter.class); builder = new InfinitestCoreBuilder(fakeEnvironment(), new FakeEventQueue()) { @Override protected TestDetector createTestDetector(TestFilter testFilter) { filterUsedToCreateCore = testFilter; return super.createTestDetector(testFilter); } }; builder.setFilter(testFilter); builder.createCore(); assertSame(filterUsedToCreateCore, testFilter); } @Test public void canSetCoreName() { builder.setName("myCoreName"); InfinitestCore core = builder.createCore(); assertEquals("myCoreName", core.getName()); } @Test public void shouldUseBlankCoreNameByDefault() { InfinitestCore core = builder.createCore(); assertEquals("", core.getName()); } @Test public void shouldSetRuntimeEnvironment() { InfinitestCore core = builder.createCore(); assertEquals(fakeEnvironment(), core.getRuntimeEnvironment()); } }
39.054348
176
0.787643
e5b606b2aa510865d54694fcb9a6884d7b9aee50
2,137
package com.alibaba.smart.framework.engine.service.query.impl; import java.util.List; import java.util.Map; import com.alibaba.smart.framework.engine.configuration.ProcessEngineConfiguration; import com.alibaba.smart.framework.engine.configuration.aware.ProcessEngineConfigurationAware; import com.alibaba.smart.framework.engine.extension.annoation.ExtensionBinding; import com.alibaba.smart.framework.engine.extension.constant.ExtensionConstant; import com.alibaba.smart.framework.engine.hook.LifeCycleHook; import com.alibaba.smart.framework.engine.instance.storage.TaskAssigneeStorage; import com.alibaba.smart.framework.engine.model.instance.TaskAssigneeInstance; import com.alibaba.smart.framework.engine.service.query.TaskAssigneeQueryService; /** * Created by 高海军 帝奇 74394 on 2017 October 07:46. */ @ExtensionBinding(group = ExtensionConstant.SERVICE, bindKey = TaskAssigneeQueryService.class) public class DefaultTaskAssigneeQueryService implements TaskAssigneeQueryService, LifeCycleHook, ProcessEngineConfigurationAware { private ProcessEngineConfiguration processEngineConfiguration; private TaskAssigneeStorage taskAssigneeStorage; @Override public void start() { this.taskAssigneeStorage = processEngineConfiguration.getAnnotationScanner().getExtensionPoint(ExtensionConstant.COMMON, TaskAssigneeStorage.class); } @Override public void stop() { } @Override public List<TaskAssigneeInstance> findList(String taskInstanceId) { List<TaskAssigneeInstance> taskAssigneeStorageList = taskAssigneeStorage.findList(taskInstanceId, processEngineConfiguration); return taskAssigneeStorageList; } @Override public Map<String, List<TaskAssigneeInstance>> findAssigneeOfInstanceList(List<String> taskInstanceIdList) { return taskAssigneeStorage.findAssigneeOfInstanceList(taskInstanceIdList,processEngineConfiguration ); } @Override public void setProcessEngineConfiguration(ProcessEngineConfiguration processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } }
35.032787
156
0.810014
f24637e5b3f785d5bfbf2b8543bf16e65841326a
757
package com.venkat.teamtemp.config; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import com.venkat.teamtemp.util.APIError; @RequestMapping(produces = "application/vnd.error+json") @Profile("!dev") public class AppControllerAdvice { @ExceptionHandler() public ResponseEntity<Object> databaseError(final Exception exception){ return new ResponseEntity<Object>(new APIError("Error occurred"),HttpStatus.BAD_REQUEST); } }
30.28
94
0.791281
bfd22246720c56695fcbdbb0c57e243f42b2a98e
2,413
package com.infdot.wicket; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import com.infdot.wicket.property.PropertySet; import com.infdot.wicket.property.PropertyValueSet; import com.infdot.wicket.view.ViewDataProvider; /** * Base class for panels that deal with a single object. * * @author Raivo Laanemets */ public abstract class ElementPanel extends Panel { private final PropertySet properties = new PropertySet(); private final ViewDataProvider dataProvider; private PropertyValueSet key; private transient Object element; public ElementPanel(String id, ViewDataProvider dataProvider) { super(id); this.dataProvider = dataProvider; setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); } public void setKey(PropertyValueSet key) { this.key = key; this.element = null; } public PropertyValueSet getKey() { return key; } public PropertySet getProperties() { return properties; } public IModel<Object> getReadonlyPropertyModel(String property) { properties.add(property); return new ReadonlyPropertyModel<Object>(property); } public <T> IModel<T> getReadonlyPropertyModel(String property, Class<T> type) { properties.add(property); return new ReadonlyPropertyModel<T>(property); } public Object getElement() { if (element == null) { if (key != null) { element = getElement(key); } } return element; } public ViewDataProvider getDataProvider() { return dataProvider; } /** * Specialized method {@link Panel#isVisible()} that also requires the view * object key to be non-null. */ @Override public boolean isVisible() { return super.isVisible() && key != null; } private Object getElement(PropertyValueSet key) { return dataProvider.get(key, getProperties().getNames()); } /** * Implementation of {@link AbstractReadOnlyModel} that uses * {@link ElementPanel#getElement()} and * {@link PropertySet#getValue(Object, String)}. * * @author Raivo Laanemets */ private class ReadonlyPropertyModel<T> extends AbstractReadOnlyModel<T> { private final String property; public ReadonlyPropertyModel(String property) { this.property = property; } @SuppressWarnings("unchecked") @Override public T getObject() { return (T) properties.getValue(getElement(), property); } } }
23.201923
80
0.735184
dff0f5fe8b67b02e1c6803c7ca289c8b6732cd4f
4,533
package org.disges.thrift.plugin.testdata.pojo.package1; public class TestMapStructPojo implements java.io.Serializable { public enum Fields{ RefMap, RefValueMap, RefKeyMap, SimpleMap, RefOtherPackage }; private java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> refMap; private java.util.Map<java.lang.Integer, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> refValueMap; private java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, java.lang.Integer> refKeyMap; private java.util.Map<java.lang.String, java.lang.Integer> simpleMap; private java.util.Map<org.disges.thrift.plugin.testdata.pojo.package2.SimpleStructPackage2Pojo, java.lang.Integer> refOtherPackage; public TestMapStructPojo() { super(); } public TestMapStructPojo(java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> refMap,java.util.Map<java.lang.Integer, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> refValueMap,java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, java.lang.Integer> refKeyMap,java.util.Map<java.lang.String, java.lang.Integer> simpleMap,java.util.Map<org.disges.thrift.plugin.testdata.pojo.package2.SimpleStructPackage2Pojo, java.lang.Integer> refOtherPackage) { super(); this.refMap = refMap; this.refValueMap = refValueMap; this.refKeyMap = refKeyMap; this.simpleMap = simpleMap; this.refOtherPackage = refOtherPackage; } // Getters and Setters public java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> getRefMap() { return refMap; } public void setRefMap(java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> refMap) { this.refMap = refMap; } public java.util.Map<java.lang.Integer, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> getRefValueMap() { return refValueMap; } public void setRefValueMap(java.util.Map<java.lang.Integer, org.disges.thrift.plugin.testdata.pojo.package1.MapValuePojo> refValueMap) { this.refValueMap = refValueMap; } public java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, java.lang.Integer> getRefKeyMap() { return refKeyMap; } public void setRefKeyMap(java.util.Map<org.disges.thrift.plugin.testdata.pojo.package1.MapKeyPojo, java.lang.Integer> refKeyMap) { this.refKeyMap = refKeyMap; } public java.util.Map<java.lang.String, java.lang.Integer> getSimpleMap() { return simpleMap; } public void setSimpleMap(java.util.Map<java.lang.String, java.lang.Integer> simpleMap) { this.simpleMap = simpleMap; } public java.util.Map<org.disges.thrift.plugin.testdata.pojo.package2.SimpleStructPackage2Pojo, java.lang.Integer> getRefOtherPackage() { return refOtherPackage; } public void setRefOtherPackage(java.util.Map<org.disges.thrift.plugin.testdata.pojo.package2.SimpleStructPackage2Pojo, java.lang.Integer> refOtherPackage) { this.refOtherPackage = refOtherPackage; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestMapStructPojo that = (TestMapStructPojo) o; if (refMap != null ? !refMap.equals(that.refMap) : that.refMap != null) return false; if (refValueMap != null ? !refValueMap.equals(that.refValueMap) : that.refValueMap != null) return false; if (refKeyMap != null ? !refKeyMap.equals(that.refKeyMap) : that.refKeyMap != null) return false; if (simpleMap != null ? !simpleMap.equals(that.simpleMap) : that.simpleMap != null) return false; if (refOtherPackage != null ? !refOtherPackage.equals(that.refOtherPackage) : that.refOtherPackage != null) return false; return true; } @Override public int hashCode() { int result = (refMap != null ? (refMap.hashCode() * 31) : 0); result = 31 * result + (refValueMap != null ? refValueMap.hashCode() : 0); result = 31 * result + (refKeyMap != null ? refKeyMap.hashCode() : 0); result = 31 * result + (simpleMap != null ? simpleMap.hashCode() : 0); result = 31 * result + (refOtherPackage != null ? refOtherPackage.hashCode() : 0); return result; } }
51.511364
565
0.737922
14f2217664d6d9f89919e2444d9058aa612c741a
11,986
package ca.cgjennings.graphics.filters; import ca.cgjennings.algo.SplitJoin; import static ca.cgjennings.graphics.filters.AbstractImageFilter.getARGBSynch; import static ca.cgjennings.graphics.filters.AbstractImageFilter.setARGBSynch; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; /** * This filter performs 90 degree rotations and horizontal or vertical flips on * an image. * * <p> * <b>In-place filtering:</b> This class <b>does not</b> support in-place * filtering (the source and destination images must be different). * * @author Chris Jennings <https://cgjennings.ca/contact> */ public final class TurnAndFlipFilter extends AbstractImageFilter { /** * Neither turned nor flipped: this value simply copies the source image. */ public static final int TURN_0 = 0; /** * Rotate 90 degrees anticlockwise. */ public static final int TURN_90_LEFT = 1; /** * Rotate 180 degrees. */ public static final int TURN_180 = 2; /** * Rotate 90 degrees clockwise. */ public static final int TURN_90_RIGHT = 3; /** * Flip horizontally without turning. */ public static final int TURN_0_FLIP_HORZ = 4; /** * Rotate 90 degrees anticlockwise and flip horizontally. */ public static final int TURN_90_LEFT_FLIP_HORZ = 5; /** * Rotate 180 degrees and flip horizontally. . */ public static final int TURN_180_FLIP_HORZ = 6; /** * Rotate 90 degrees clockwise and flip horizontally. */ public static final int TURN_90_RIGHT_FLIP_HORZ = 7; /** * Flip vertically without turning (same as {@code TURN_180_FLIP}). */ public static final int TURN_0_FLIP_VERT = 6; /** * Rotate 90 degrees anticlockwise and flip vertically (same as * {@code TURN_90_RIGHT_FLIP_HORZ}). */ public static final int TURN_90_LEFT_FLIP_VERT = 7; /** * Rotate 180 degrees and flip vertically (same as {@code TURN_0_FLIP}). */ public static final int TURN_180_FLIP_VERT = 4; /** * Rotate 90 degrees clockwise and flip vertically (same as * {@code TURN_90_LEFT_FLIP_HORZ}). */ public static final int TURN_90_RIGHT_FLIP_VERT = 5; /** * Flip both axes without turning (same as {@code TURN_180}). */ public static final int TURN_0_FLIP_BOTH = 2; /** * Rotate 90 degrees anticlockwise and flip both axes (same as * {@code TURN_90_RIGHT}). */ public static final int TURN_90_LEFT_FLIP_BOTH = 3; /** * Rotate 180 degrees and flip both axes (same as {@code TURN_0}). */ public static final int TURN_180_FLIP_BOTH = 0; /** * Rotate 90 degrees clockwise and flip both axes (same as * {@code TURN_90_LEFT}). */ public static final int TURN_90_RIGHT_FLIP_BOTH = 1; private int orient = TURN_0_FLIP_HORZ; /** * Creates a new filter that is initially set to the * {@link #TURN_0_FLIP_HORZ} orientation. */ public TurnAndFlipFilter() { } /** * Creates a new filter that is initially set to the specified orientation. * * @param orientation the initial orientation */ public TurnAndFlipFilter(int orientation) { setOrientation(orientation); } /** * Returns the current orientation setting that describes how output images * should be turned and flipped relative to input images. * * @return the {@code TURN_*} orientation value */ public int getOrientation() { return orient; } /** * Sets the orientation of output images relative to source images. * * @param orientation the {@code TURN_*} value that encodes how the image * should be rotated and flipped */ public void setOrientation(int orientation) { if (orientation < TURN_0 || orientation > TURN_90_RIGHT_FLIP_HORZ) { throw new IllegalArgumentException("orientation: " + orientation); } this.orient = orientation; } @Override public BufferedImage createCompatibleDestImage(BufferedImage source, ColorModel destinationColorModel) { final int sw = source.getWidth(); final int sh = source.getHeight(); final int or = getOrientation(); int dw, dh; if ((or & 1) == 0) { dw = sw; dh = sh; } else { dw = sh; dh = sw; } if (destinationColorModel == null) { destinationColorModel = source.getColorModel(); } return new BufferedImage( destinationColorModel, destinationColorModel.createCompatibleWritableRaster(dw, dh), destinationColorModel.isAlphaPremultiplied(), null ); } @Override public Rectangle2D getBounds2D(BufferedImage source) { final int sw = source.getWidth(); final int sh = source.getHeight(); final int or = getOrientation(); int dw, dh; if ((or & 1) == 0) { dw = sw; dh = sh; } else { dw = sh; dh = sw; } return new Rectangle(0, 0, dw, dh); } @Override public BufferedImage filter(BufferedImage src, BufferedImage dest) { final int w = src.getWidth(); final int h = src.getHeight(); if (dest == null) { dest = createCompatibleDestImage(src, null); } if ((w * h) >= Tuning.FLIP) { filterParallel(src, dest); } else { filterSerial(src, dest); } return dest; } private void filterSerial(BufferedImage src, BufferedImage dest) { final int y1 = src.getHeight() - 1; final int or = getOrientation(); switch (or) { case 0: t0(src, dest, 0, y1); break; case 1: t1(src, dest, 0, y1); break; case 2: t2(src, dest, 0, y1); break; case 3: t3(src, dest, 0, y1); break; case 4: t4(src, dest, 0, y1); break; case 5: t5(src, dest, 0, y1); break; case 6: t6(src, dest, 0, y1); break; case 7: t7(src, dest, 0, y1); break; default: throw new AssertionError(); } } private void filterParallel(BufferedImage src, BufferedImage dest) { final int h = src.getHeight(); final int or = getOrientation(); SplitJoin sj = SplitJoin.getInstance(); final int n = Math.min(h, sj.getIdealSplitCount()); final int rowCount = h / n; final int remainder = h - n * rowCount; final Runnable[] units = new Runnable[n]; int y = 0; for (int i = 0; i < n; ++i) { int rows = rowCount; if (i < remainder) { ++rows; } units[i] = new FlipUnit(src, dest, y, rows, or); y += rows; } sj.runUnchecked(units); } private static class FlipUnit implements Runnable { private final int orientation; private final BufferedImage source; private BufferedImage dest; private final int y0; private int rows; public FlipUnit(BufferedImage source, BufferedImage dest, int y0, int rows, int orientation) { this.source = source; this.dest = dest; this.y0 = y0; this.rows = rows; this.orientation = orientation; } @Override public void run() { switch (orientation) { case 0: t0(source, dest, y0, y0 + rows - 1); break; case 1: t1(source, dest, y0, y0 + rows - 1); break; case 2: t2(source, dest, y0, y0 + rows - 1); break; case 3: t3(source, dest, y0, y0 + rows - 1); break; case 4: t4(source, dest, y0, y0 + rows - 1); break; case 5: t5(source, dest, y0, y0 + rows - 1); break; case 6: t6(source, dest, y0, y0 + rows - 1); break; case 7: t7(source, dest, y0, y0 + rows - 1); break; default: throw new AssertionError(); } } } static void t0(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int[] p = new int[width]; for (int y = y0; y <= y1; ++y) { getARGBSynch(src, 0, y, width, 1, p); setARGBSynch(dst, 0, y, width, 1, p); } } static void t1(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int[] p = new int[width]; for (int y = y0; y <= y1; ++y) { getARGBSynch(src, 0, y, width, 1, p); reverse(p); setARGBSynch(dst, y, 0, 1, width, p); } } static void t2(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int height = src.getHeight(); int[] p = new int[width]; for (int y = y0, dy = height - y0 - 1; y <= y1; ++y, --dy) { getARGBSynch(src, 0, y, width, 1, p); reverse(p); setARGBSynch(dst, 0, dy, width, 1, p); } } static void t3(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int height = src.getHeight(); int[] p = new int[width]; for (int y = y0, dx = height - y0 - 1; y <= y1; ++y, --dx) { getARGBSynch(src, 0, y, width, 1, p); setARGBSynch(dst, dx, 0, 1, width, p); } } static void t4(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int[] p = new int[width]; for (int y = y0; y <= y1; ++y) { getARGBSynch(src, 0, y, width, 1, p); reverse(p); setARGBSynch(dst, 0, y, width, 1, p); } } static void t5(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int height = src.getHeight(); int[] p = new int[width]; for (int y = y0, dx = height - y0 - 1; y <= y1; ++y, --dx) { getARGBSynch(src, 0, y, width, 1, p); reverse(p); setARGBSynch(dst, dx, 0, 1, width, p); } } static void t6(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int height = src.getHeight(); final int[] p = new int[width]; for (int y = y0, dy = height - y0 - 1; y <= y1; ++y, --dy) { getARGBSynch(src, 0, y, width, 1, p); setARGBSynch(dst, 0, dy, width, 1, p); } } static void t7(BufferedImage src, BufferedImage dst, int y0, int y1) { final int width = src.getWidth(); final int[] p = new int[width]; for (int y = y0; y <= y1; ++y) { getARGBSynch(src, 0, y, width, 1, p); setARGBSynch(dst, y, 0, 1, width, p); } } static void reverse(int[] p) { int max = p.length / 2; for (int i = 0, o = p.length - 1; i < max; ++i, --o) { int temp = p[i]; p[i] = p[o]; p[o] = temp; } } }
31.295039
108
0.530285
8da26383e7d88e0371475fed38cac3e2eec66a8f
5,334
/** * 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.geronimo.console.jmsmanager; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; import javax.portlet.PortletContext; import javax.portlet.PortletException; import javax.portlet.PortletRequestDispatcher; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import org.apache.geronimo.console.BasePortlet; import org.apache.geronimo.console.jmsmanager.handlers.CreateDestinationHandler; import org.apache.geronimo.console.jmsmanager.handlers.PortletResponseHandler; import org.apache.geronimo.console.jmsmanager.handlers.RemoveDestinationHandler; import org.apache.geronimo.console.jmsmanager.handlers.StatisticsHandler; import org.apache.geronimo.console.jmsmanager.renderers.CreateDestinationRenderer; import org.apache.geronimo.console.jmsmanager.renderers.PortletRenderer; import org.apache.geronimo.console.jmsmanager.renderers.StatisticsRenderer; import org.apache.geronimo.console.jmsmanager.renderers.ViewDLQRenderer; import org.apache.geronimo.console.jmsmanager.renderers.ViewDestinationsRenderer; import org.apache.geronimo.console.jmsmanager.renderers.ViewMessagesRenderer; public class JMSManagerPortlet extends BasePortlet { private PortletRequestDispatcher edit; private PortletRequestDispatcher help; private ConnectionFactory cf; private Map handlers; private Map renderers; private PortletContext context; public void init(PortletConfig portletConfig) throws PortletException { super.init(portletConfig); context = portletConfig.getPortletContext(); help = context .getRequestDispatcher("/WEB-INF/view/jmsmanager/help.jsp"); edit = context .getRequestDispatcher("/WEB-INF/view/jmsmanager/edit.jsp"); renderers = new HashMap(); renderers.put("createDestination", new CreateDestinationRenderer()); renderers.put("viewDestinations", new ViewDestinationsRenderer()); renderers.put("statistics", new StatisticsRenderer()); renderers.put("viewMessages", new ViewMessagesRenderer()); renderers.put("viewDLQ", new ViewDLQRenderer()); handlers = new HashMap(); handlers.put("createDestination", new CreateDestinationHandler()); handlers.put("removeDestination", new RemoveDestinationHandler()); handlers.put("statistics", new StatisticsHandler()); } public void doHelp(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException { help.include(renderRequest, renderResponse); } public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) { return; } String view = renderRequest.getParameter("processAction"); if (view == null) { // no specific content requested - show the destinations list view = "viewDestinations"; } PortletRenderer renderer = (PortletRenderer) renderers.get(view); if (renderer == null) { throw new PortletException("Invalid view parameter specified: " + view); } String include = renderer.render(renderRequest, renderResponse); if (include != null) { PortletRequestDispatcher requestDispatcher = context .getRequestDispatcher(include); requestDispatcher.include(renderRequest, renderResponse); } } public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String processAction = actionRequest.getParameter("processaction"); PortletResponseHandler handler = (PortletResponseHandler) handlers .get(processAction); if (handler == null) { // throw new RuntimeException( "no handlers for processAction = " + // processAction ); handler = (PortletResponseHandler) handlers.get("viewDestinations"); } handler.processAction(actionRequest, actionResponse); } public void destroy() { help = null; edit = null; super.destroy(); } }
37.56338
82
0.72216
8b0d1829ce922abd019bfbecede27e17b96ad164
2,058
package solution; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KStreamBuilder; public class StreamsExercise { public static void main(String[] args) throws Exception { Properties streamsConfiguration = new Properties(); // Give the Streams application a unique name. The name must be unique in the Kafka cluster streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-exercise1"); streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "broker1:9092"); streamsConfiguration.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "zookeeper1:2181"); streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // Specify default (de)serializers for record keys and for record values. streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); KStreamBuilder builder = new KStreamBuilder(); // Read the input Kafka topic into a KStream instance. KStream<String, String> shakesLines = builder.stream("shakespeare_topic"); // Convert the values to upper case KStream<String, String> uppercasedBill = shakesLines.mapValues(String::toUpperCase); // Use filter() to get just the messages from Macbeth KStream<String, String> justTheScottishPlay = shakesLines.filter((k, v) -> k.equals("Macbeth")); // Write the uppercased results to a new Kafka topic called "UppercasedShakespeare". uppercasedBill.to("UppercasedShakespeare"); // Write the Macbeth messages to a topic called "ScottishPlay" justTheScottishPlay.to("ScottishPlay"); KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration); streams.start(); } }
39.576923
105
0.783285
5090db986c800f6db8eb2143466ca5783c122c9d
261
package com.iva.VoiceAsvSpoofDetect; public class AsvSpoofDetectOptions { String config = " --enable-log=true"; public String getConfig() { return config; } public void setConfig(String config) { this.config = config; } }
18.642857
42
0.64751
fb72589ff0893e488118003e3e967bcbe5c54b54
5,155
package org.recap.service; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; import org.recap.PropertyKeyConstants; import org.recap.ScsbCommonConstants; import org.recap.model.export.S3RecentDataExportInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; @Service public class RecentDataExportsInfoService { private static final Logger logger = LoggerFactory.getLogger(RecentDataExportsInfoService.class); @Autowired AmazonS3 s3client; @Value("${" + PropertyKeyConstants.SCSB_BUCKET_NAME + "}") private String scsbBucketName; @Value("${" + PropertyKeyConstants.S3_DATA_DUMP_DIR + "}") private String s3DataExportBasePath; @Value("${" + PropertyKeyConstants.RECENT_DATA_EXPORT_LIMIT + "}") private String recentDataExportInfoLimit; public List<S3RecentDataExportInfo> generateRecentDataExportsInfo(List<String> allInstitutionCodeExceptSupportInstitution, String institution, String bibDataFormat) { List<S3RecentDataExportInfo> recentDataExportInfoList = new ArrayList<>(); ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); try { listObjectsRequest.setBucketName(scsbBucketName); for (String institutionPrefix : allInstitutionCodeExceptSupportInstitution) { listObjectsRequest.setPrefix(s3DataExportBasePath + institution + "/" + bibDataFormat + "Xml/Full/" + institutionPrefix); ObjectListing objectListing = s3client.listObjects(listObjectsRequest); for (S3ObjectSummary os : objectListing.getObjectSummaries()) { Map<String, String> records = getObjectContent(os.getKey()); S3RecentDataExportInfo s3RecentDataExportInfo = new S3RecentDataExportInfo(); s3RecentDataExportInfo.setKeyName(os.getKey()); s3RecentDataExportInfo.setInstitution(institution); s3RecentDataExportInfo.setBibDataFormat(bibDataFormat); s3RecentDataExportInfo.setGcd(records.get("Collection Group Id(s)")); s3RecentDataExportInfo.setBibCount(records.get("No of Bibs Exported")); s3RecentDataExportInfo.setItemCount(records.get("No of Items Exported")); s3RecentDataExportInfo.setKeySize(os.getSize()); s3RecentDataExportInfo.setKeyLastModified(os.getLastModified()); recentDataExportInfoList.add(s3RecentDataExportInfo); logger.info("File with the key -->" + os.getKey() + " " + os.getSize() + " " + os.getLastModified()); } } } catch (Exception e) { logger.error(ScsbCommonConstants.LOG_ERROR, e); } recentDataExportInfoList.sort(Comparator.comparing(S3RecentDataExportInfo::getKeyLastModified).reversed()); return recentDataExportInfoList.stream().limit(Integer.parseInt(recentDataExportInfoLimit)).collect(Collectors.toList()); } public Map<String, String> getObjectContent(String fileName) { List<String> str = new ArrayList<>(); String[] records = null; String[] headers = null; try { String basepath = fileName.substring(0, fileName.lastIndexOf('/')); String csvFileName = fileName.substring(fileName.lastIndexOf('/')); csvFileName = csvFileName.substring(1, csvFileName.lastIndexOf('.')); S3Object s3Object = s3client.getObject(scsbBucketName, basepath + "/" + "ExportDataDump_Full_" + csvFileName + ".csv"); S3ObjectInputStream inputStream = s3Object.getObjectContent(); Scanner fileIn = new Scanner(inputStream); if (null != fileIn) { while (fileIn.hasNext()) { str.add(fileIn.nextLine()); } headers = str.get(0).replace("\"", "").split(","); records = str.get(1).replace("\"", "").split(","); } } catch (Exception e) { logger.error(ScsbCommonConstants.LOG_ERROR, e); } return mapResult(headers, records); } private Map<String, String> mapResult(String[] headers, String[] records) { Map<String, String> result = new HashMap<>(); if(headers != null && headers.length > 0) { for (int i = 0; i < headers.length; i++) { result.put(headers[i], records[i]); } } return result; } }
47.731481
170
0.665955
dcdc23dd02efd169295bf19167d906fc1fe253ae
11,033
package com.my.project.jaxws; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.EventFilter; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.XMLEvent; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class TestStax { /** XMLStreamConstants中的常量值到常量名的映射 */ private static Map<Integer, String> CONST_TO_NAME; /** * 基于光标模型的操作 */ @Test public void stream() { XMLInputFactory factory = XMLInputFactory.newInstance(); InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); XMLStreamReader reader = factory.createXMLStreamReader(is); while(reader.hasNext()) { int type = reader.next(); if(type == XMLStreamConstants.START_ELEMENT) { if("title".equals(reader.getName().toString())) { String typeName = CONST_TO_NAME.get(type) + ": "; String lang = reader.getAttributeValue(0).toString(); System.out.print(typeName + reader.getElementText() + "(" + lang + ") "); } else if("author".equals(reader.getName().toString())) { System.out.print(reader.getElementText() + " "); } else if("year".equals(reader.getName().toString())) { System.out.print(reader.getElementText() + " "); } else if("price".equals(reader.getName().toString())) { System.out.println(reader.getElementText()); } } } } catch (XMLStreamException e) { e.printStackTrace(); } finally { try { if(is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 基于迭代模型的操作 */ @Test public void event() { XMLInputFactory factory = XMLInputFactory.newInstance(); InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); XMLEventReader reader = factory.createXMLEventReader(is); int eventNum = 0; // 迭代次数 while(reader.hasNext()) { XMLEvent event = reader.nextEvent(); // 通过XMLEvent来获取节点类型 String lang = null; if(event.isStartElement()) { // 通过event.asXXX()获取节点 if("title".equals(event.asStartElement().getName().toString())) { lang = event.asStartElement().getAttributeByName(new QName("lang")).getValue().toString(); System.out.print(reader.getElementText() + "(" + lang + ") "); } else if("author".equals(event.asStartElement().getName().toString())) { System.out.print(reader.getElementText() + " "); } else if("year".equals(event.asStartElement().getName().toString())) { System.out.print(reader.getElementText() + " "); } else if("price".equals(event.asStartElement().getName().toString())) { System.out.println(reader.getElementText()); } } eventNum ++; } System.out.println("迭代次数: " + eventNum); } catch (XMLStreamException e) { e.printStackTrace(); } finally { try { if(is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 基于过滤器的操作 */ @Test public void filter() { XMLInputFactory factory = XMLInputFactory.newInstance(); InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); XMLEventReader reader = factory.createXMLEventReader(is); // 使用过滤器排除不关心的节点,可以提高效率,减少迭代次数 XMLEventReader filterReader = factory.createFilteredReader(reader, new EventFilter(){ @Override public boolean accept(XMLEvent event) { if(event.isStartElement()) { String name = event.asStartElement().getName().toString(); if("title".equals(name) || "author".equals(name) || "year".equals(name) || "price".equals(name)) { return true; } else { return false; } } return false; } }); int eventNum = 0; // 迭代次数 while(filterReader.hasNext()) { XMLEvent event = filterReader.nextEvent(); String lang = null; if(event.isStartElement()) { if("title".equals(event.asStartElement().getName().toString())) { lang = event.asStartElement().getAttributeByName(new QName("lang")).getValue().toString(); System.out.print(filterReader.getElementText() + "(" + lang + ") "); } else if("author".equals(event.asStartElement().getName().toString())) { System.out.print(filterReader.getElementText() + " "); } else if("year".equals(event.asStartElement().getName().toString())) { System.out.print(filterReader.getElementText() + " "); } else if("price".equals(event.asStartElement().getName().toString())) { System.out.println(filterReader.getElementText()); } } eventNum ++; } System.out.println("迭代次数: " + eventNum); } catch (XMLStreamException e) { e.printStackTrace(); } finally { try { if(is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 基于XPath的操作(查找category="web"的book节点,输出title和price信息) */ @Test public void xpath() { InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(is); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList list = (NodeList)xpath.evaluate("//book[@category='web']", doc, XPathConstants.NODESET); for(int i=0; i<list.getLength(); i++) { Element e = (Element)list.item(i); Node titleNode = e.getElementsByTagName("title").item(0); String lang = titleNode.getAttributes().getNamedItem("lang").getNodeValue(); String title = titleNode.getTextContent(); String price = e.getElementsByTagName("price").item(0).getTextContent(); System.out.println(title + "(" + lang + ") " + price); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } finally { try { if(is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 使用XMLStreamWriter创建XML */ @Test public void writer() { try { XMLOutputFactory factory = XMLOutputFactory.newInstance(); // 设置输出的XML内容中添加命名空间 factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); XMLStreamWriter writer = factory.createXMLStreamWriter(System.out); writer.writeStartDocument("UTF-8", "1.0"); writer.writeEndDocument(); // 指定节点的命名空间 String namespace = "http://www.example.org/facet"; writer.writeStartElement("ns", "person", namespace); writer.writeAttribute("gender", "female"); writer.writeStartElement(namespace, "name"); writer.writeCharacters("Lily"); writer.writeEndElement(); writer.writeStartElement(namespace, "age"); writer.writeCharacters("8"); writer.writeEndElement(); writer.writeStartElement(namespace, "email"); writer.writeCharacters("lily@example.com"); writer.writeEndElement(); writer.writeEndElement(); writer.writeCharacters("\n"); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (FactoryConfigurationError e) { e.printStackTrace(); } } /** * 使用Transformer更新节点信息 */ @Test public void update() { InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(is); // 使用XPath查找并修改price节点的值 XPath xpath = XPathFactory.newInstance().newXPath(); NodeList list = (NodeList)xpath.evaluate("//book[title='Harry Potter']", doc, XPathConstants.NODESET); Element book = (Element)list.item(0); Element price = (Element)(book.getElementsByTagName("price").item(0)); price.setTextContent("39.99"); // 将修改后的值输出到控制台 Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); Result result = new StreamResult(System.out); transformer.transform(new DOMSource(doc), result); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } finally { try { if(is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 将XMLStreamConstants中的常量添加到Map中,方便查看输出 */ @Before public void before() { try { Class<?> clazz = Class.forName("javax.xml.stream.XMLStreamConstants"); Field[] fields = clazz.getDeclaredFields(); CONST_TO_NAME = new HashMap<Integer, String>(); for(Field field : fields) { CONST_TO_NAME.put(field.getInt(clazz), field.getName()); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
32.738872
106
0.666999
20c017d08966631aa709471641a989747371bed7
6,270
package ic2015.password_keeper; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.view.Window; import android.widget.TextView; import android.widget.Toast; import com.gc.materialdesign.views.ButtonRectangle; import com.gc.materialdesign.widgets.ProgressDialog; import com.rengwuxian.materialedittext.MaterialEditText; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import es.dmoral.toasty.Toasty; import io.objectbox.Box; import io.objectbox.BoxStore; public class LoginActivity extends AppCompatActivity { private static final int REQUEST_SIGNUP = 0; @BindView(R.id.input_login_email) MaterialEditText login_email_input; @BindView(R.id.input_login_password) MaterialEditText login_password_input; @BindView(R.id.button_login) ButtonRectangle login_button; @BindView(R.id.link_signup) TextView signup_link; //注册者 属性 Box private Box<RegisterEntity> registerEntityBox; //缓存 ACache mCache; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); //隐藏 title bar setContentView(R.layout.activity_login); //黄油刀 ButterKnife.bind(this); //数据库和 Box 初始化 BoxStore boxStore = ((App)getApplication()).getBoxStore(); registerEntityBox = boxStore.boxFor(RegisterEntity.class); //缓存 mCache = ACache.get(this); //登录按钮 login_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //调用登录过程方法 login(); } }); //跳转到注册界面 signup_link.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LoginActivity.this, SignUpActivity.class); startActivityForResult(intent, REQUEST_SIGNUP); } }); } //登录过程 private void login(){ //停用登录按钮功能 login_button.setEnabled(false); //输入有效性检查失败 if (!validate()){ this.loginFailed(); return; } //登录进度对话框 final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this, "登录中..."); progressDialog.show(); //定时器 new android.os.Handler().postDelayed( new Runnable() { @Override public void run() { if (progressDialog.isShowing()) { //防止内存泄露 progressDialog.dismiss(); if (checkRegister()) { loginSuccess(); } else { loginFailed(); } } } }, 500); } //注册界面返回参数检测 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); //注册界面返回 if (resultCode == RESULT_OK){ if (requestCode == REQUEST_SIGNUP){ Toasty.success(getBaseContext(), "注册成功,请登录!", Toast.LENGTH_SHORT, true).show(); } } } //登录成功 private void loginSuccess(){ login_button.setEnabled(true); Intent intent = new Intent(LoginActivity.this, HomePageActivity.class); mCache.put("email", login_email_input.getText().toString().trim(), ACache.TIME_HOUR); //利用缓存传递用户邮箱信息 startActivityForResult(intent, REQUEST_SIGNUP); login_email_input.setText(""); login_password_input.setText(""); } //登录失败提示 private void loginFailed(){ Toasty.error(getBaseContext(), "登录失败,请检查!", Toast.LENGTH_SHORT, true).show(); login_button.setEnabled(true); } //登录失败提示(没有此邮箱) private void loginFailed_noEmailSame(){ Toasty.error(getBaseContext(), "邮箱地址错误!", Toast.LENGTH_SHORT, true).show(); login_button.setEnabled(true); } //登录失败提示(密码错误) private void loginFailed_wrongPwd(){ Toasty.error(getBaseContext(), "密码错误", Toast.LENGTH_SHORT, true).show(); login_button.setEnabled(true); } //输入有效性检查 private boolean validate(){ boolean valid = true; String email = login_email_input.getText().toString().trim(); String password = login_password_input.getText().toString().trim(); if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()){ login_email_input.setError("请输入有效的邮箱地址!"); valid = false; } if (password.isEmpty() || password.length() < 6 || password.length() > 16){ login_password_input.setError("密码长度应在 6 ~ 16 位之间!"); valid = false; } return valid; } //登录信息查询 private boolean checkRegister(){ boolean isSuccessful = false; String email = login_email_input.getText().toString().trim(); String password_sha256 = Encrypt.SHA(login_password_input.getText().toString().trim()); //信息正确 if (registerQuery(email, password_sha256)){ isSuccessful = true; } return isSuccessful; } //数据库检索,对比输入信息 private boolean registerQuery(String email, String password_sha256){ boolean isRegister = true; List<RegisterEntity> registerEntityList; registerEntityList = registerEntityBox.query().equal(RegisterEntity_.email, email).build().find(); //邮箱不存在 if (registerEntityList.isEmpty()){ loginFailed_noEmailSame(); isRegister = false; } //密码错误 else { String password_sha256_ob = registerEntityList.get(0).getPassword_sha256().trim(); if (!password_sha256.equals(password_sha256_ob)) { loginFailed_wrongPwd(); isRegister = false; } } return isRegister; } }
28.761468
108
0.602552
2f9cc5cd66b5e1e7ddd2875ea836205d8fdb826e
659
package es.upm.miw.apaw_practice.domain.models.garage; import java.util.List; public interface DriverBuilder { interface Id { Dni id(String id); } interface Dni { Name dni(String dni); } interface Name { Telephone name(String name); } interface Telephone { Email telephone(String telephone); } interface Email { GarageMember email(String email); } interface GarageMember { Vehicles garageMember(Boolean garageMember); } interface Vehicles { Build vehicles(List<Vehicle> vehicles); } interface Build { Driver build(); } }
16.897436
54
0.611533
cf31455a34dbb4681e47080b88d804d1595396d9
694
/******************************************************************************* * Copyright (c) 2012 Manning * See the file license.txt for copying permission. ******************************************************************************/ package com.manning.androidhacks.hack034; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.content.Intent; public class MainActivityJava extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void buttonClick(View v) { startActivity(new Intent(this, ScalaActivity.class)); } }
27.76
80
0.586455
717117af7be81f62c8d05452239a54c0e5886327
243
package html; /** * Represents literal text. * @version 1.0 */ public class Text implements Content { private final String text; public Text(String text) { this.text = text; } @Override public String toString() { return text; } }
14.294118
42
0.679012
e9979ccdecf92bf7904ec9c4940699ed3afcc76d
2,636
package com.biomatters.plugins.biocode.labbench.fims.geome; import com.biomatters.geneious.publicapi.databaseservice.DatabaseServiceException; import com.biomatters.plugins.biocode.BiocodePlugin; import com.biomatters.plugins.biocode.labbench.LoginOptions; import com.biomatters.plugins.biocode.labbench.PasswordOptions; import com.biomatters.plugins.biocode.utilities.PasswordOption; import com.biomatters.plugins.biocode.utilities.SharedCookieHandler; import javax.ws.rs.ProcessingException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * @author Matthew Cheung * <p /> * Created on 1/02/14 10:50 AM */public class geomeFIMSConnectionOptions extends PasswordOptions { private StringOption hostOption; private StringOption usernameOption; private PasswordOption passwordOption; private BooleanOption includePublicProjectsOption; public geomeFIMSConnectionOptions() { super(BiocodePlugin.class); hostOption = addStringOption("host", "Host:", geomeFIMSConnection.GEOME_URL); usernameOption = addStringOption("username", "Username:", ""); passwordOption = addCustomOption(new PasswordOption("password", "Password:", true)); includePublicProjectsOption = addBooleanOption("includePublic", "Include data from public projects", false); } public void login(String host, String username, String password) throws MalformedURLException, ProcessingException, DatabaseServiceException { try { URL url = new URL(host); SharedCookieHandler.registerHost(url.getHost()); geomeFIMSClient client = new geomeFIMSClient(host, LoginOptions.DEFAULT_TIMEOUT); client.login(username, password); } catch (IOException e) { throw new DatabaseServiceException(e, e.getMessage(), false); } } public String getHost() { return hostOption.getValue(); } public String getUserName() { return usernameOption.getValue(); } public void setUserName(String name) { usernameOption.setValue(name); } public String getPassword() { return passwordOption.getPassword(); } public void setPassword(String password) { passwordOption.setPassword(password); } public boolean includePublicProjects() { return includePublicProjectsOption.getValue(); } public void setIncludePublicProjectsOption(Boolean publicOption) { includePublicProjectsOption.setValue(publicOption); } public void setHostOption(String host) { this.hostOption.setValue(host); } }
36.611111
146
0.729894
a0ea37dc80555f373058213946c0a6b54997f174
4,928
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 package aws.proserve.bcs.ce.service; import aws.proserve.bcs.dr.aws.AwsInstance; import aws.proserve.bcs.dr.aws.ImmutableAwsInstance; import aws.proserve.bcs.dr.project.Project; import aws.proserve.bcs.dr.project.Side; import aws.proserve.bcs.dr.secret.Credential; import aws.proserve.bcs.dr.secret.SecretManager; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.AttachedPolicy; import com.amazonaws.services.identitymanagement.model.GetInstanceProfileRequest; import com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.inject.Named; import java.util.ArrayList; @Named public class CloudEndureInstanceService { private final Logger log = LoggerFactory.getLogger(getClass()); private final SecretManager secretManager; CloudEndureInstanceService(SecretManager secretManager) { this.secretManager = secretManager; } /** * @return machines: * <ol> * <li>with instance profile which contains <code>AmazonSSMManagedInstanceCore</code>.</li> * <li>resides in the designated VPC.</li> * </ol> */ public AwsInstance[] findAllQualifiedInstances(Project project, Side side) { return findAllQualifiedInstances(project.getRegion(side).getName(), secretManager.getCredential(project), project.getCloudEndureProject().getVpcId(side)); } public AwsInstance[] findAllQualifiedInstances(String region, Credential credential, String vpcId) { final var ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(credential.toProvider()) .withRegion(region) .build(); final var iam = AmazonIdentityManagementClientBuilder.standard() .withCredentials(credential.toProvider()) .withRegion(region) .build(); final var instances = new ArrayList<AwsInstance>(); final var request = new DescribeInstancesRequest(); DescribeInstancesResult result; do { result = ec2.describeInstances(request); request.setNextToken(result.getNextToken()); for (var reservation : result.getReservations()) { for (var instance : reservation.getInstances()) { if (!isQualified(instance, vpcId, iam)) { continue; } instances.add(ImmutableAwsInstance.builder() .from(AwsInstance.convert(instance)) .region(region) .build()); } } } while (result.getNextToken() != null); return instances.toArray(new AwsInstance[0]); } public boolean isQualified( Instance instance, @Nullable String vpcId, AmazonIdentityManagement iam) { final var profile = instance.getIamInstanceProfile(); if (profile == null) { log.info("Instance [{}] has no instance profile.", instance.getInstanceId()); return false; } final var arn = profile.getArn(); if (arn.lastIndexOf('/') == -1) { log.info("Instance [{}]: invalid instance profile arn {}.", instance.getInstanceId(), arn); return false; } final var role = iam.getInstanceProfile(new GetInstanceProfileRequest() .withInstanceProfileName(arn.substring(arn.lastIndexOf('/') + 1))) .getInstanceProfile().getRoles().get(0); // has exactly one role if (iam.listAttachedRolePolicies(new ListAttachedRolePoliciesRequest() .withRoleName(role.getRoleName())) .getAttachedPolicies() .stream() .map(AttachedPolicy::getPolicyName) .noneMatch("AmazonSSMManagedInstanceCore"::equals)) { log.info("Instance [{}] profile has no AmazonSSMManagedInstanceCore policy attached", instance.getInstanceId()); return false; } if (vpcId != null && !instance.getVpcId().equals(vpcId)) { log.info("Instance [{}] is not running inside the source VPC [{}]", instance.getInstanceId(), vpcId); return false; } return true; } }
39.111111
113
0.649554
812c1c8c3b9668f140abcb2959b809dd46742f66
2,977
package info.bitrich.xchange.coinmate; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import info.bitrich.xchange.coinmate.dto.CoinmateWebSocketTrade; import info.bitrich.xchangestream.core.StreamingMarketDataService; import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper; import info.bitrich.xchangestream.service.pusher.PusherStreamingService; import io.reactivex.Observable; import org.knowm.xchange.coinmate.CoinmateAdapters; import org.knowm.xchange.coinmate.CoinmateUtils; import org.knowm.xchange.coinmate.dto.marketdata.CoinmateOrderBook; import org.knowm.xchange.coinmate.dto.marketdata.CoinmateOrderBookData; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import java.util.List; public class CoinmateStreamingMarketDataService implements StreamingMarketDataService { private final PusherStreamingService service; CoinmateStreamingMarketDataService(PusherStreamingService service) { this.service = service; } @Override public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) { String channelName = "order_book-" + CoinmateStreamingAdapter.getChannelPostfix(currencyPair); return service.subscribeChannel(channelName, "order_book") .map(s -> { ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); CoinmateOrderBookData orderBookData = mapper.readValue(s, CoinmateOrderBookData.class); CoinmateOrderBook coinmateOrderBook = new CoinmateOrderBook(false, null, orderBookData); return CoinmateAdapters.adaptOrderBook(coinmateOrderBook, currencyPair); }); } @Override public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) { // No live ticker throw new NotAvailableFromExchangeException(); } @Override public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) { String channelName = "trades-" + CoinmateStreamingAdapter.getChannelPostfix(currencyPair); return service.subscribeChannel(channelName, "new_trades") .map(s -> { ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); List<CoinmateWebSocketTrade> list = mapper.readValue(s, new TypeReference<List<CoinmateWebSocketTrade>>() {}); return list; }) .flatMapIterable(coinmateWebSocketTrades -> coinmateWebSocketTrades) .map(coinmateWebSocketTrade -> CoinmateAdapters.adaptTrade(coinmateWebSocketTrade.toTransactionEntry(CoinmateUtils.getPair(currencyPair)))); } }
45.8
156
0.745381
eb6ae5a339a259dd1e9c879509988c0ffb9a374e
1,162
package lista_agregacao; public class TestePC { public static void main(String[] args) { Teclado tc1 = new Teclado(105, "br-abnt2", "LG", "Usb", false); Teclado tc2 = new Teclado(105, "us-acentos", "exbom", "BK-A1100", true); Teclado tc3 = null; WebCam wc1 = new WebCam("Logitech", "C920", 1920, 1080, true); WebCam wc2 = new WebCam("Logitech", "C270", 1280, 720, true); WebCam wc3 = null; PC pc = null; try { pc = new PC("João Maoel", "Leadership", tc3); } catch (NullPointerException e) { System.err.println(e.getMessage()); } try { pc = new PC("João Maoel", "Leadership", tc1, wc3); } catch (NullPointerException e) { System.err.println(e.getMessage()); } try { pc = new PC("João Maoel", "Leadership", tc1, wc1); } catch (NullPointerException e) { System.err.println(e.getMessage()); } System.out.println(pc); pc.addWebCam(wc2); System.out.println(pc); pc.removeWebCam(wc1); System.out.println(pc); pc.addWebCam(wc2); System.out.println(pc); pc.trocaTeclado(tc2); System.out.println(pc); pc.trocaTeclado(tc3); System.out.println(pc); } }
19.366667
74
0.623064
bb96904f2c3b7c62efe1e5cf706d76df92f2c64b
6,010
package org.jgroups; import org.jgroups.util.UUID; /** * Global is a JGroups internal class defining global variables. * * @since 2.0 * @author Bela Ban */ public final class Global { public static final int BYTE_SIZE = Byte.SIZE / 8; // 1 public static final int SHORT_SIZE = Short.SIZE / 8; // 2 public static final int INT_SIZE = Integer.SIZE / 8; // 4 public static final int LONG_SIZE = Long.SIZE / 8; // 8 public static final int DOUBLE_SIZE = Double.SIZE / 8; // 8; public static final int FLOAT_SIZE = Float.SIZE / 8; // 4; public static final int MAX_DATAGRAM_PACKET_SIZE=1 << 16; public static final Address NULL_ADDRESS=new UUID(0,0); public static final String IPv4="java.net.preferIPv4Stack"; public static final String IPv6="java.net.preferIPv6Addresses"; public static final String NON_LOOPBACK_ADDRESS="NON_LOOPBACK_ADDRESS"; public static final String BIND_ADDR="jgroups.bind_addr"; public static final String EXTERNAL_ADDR="jgroups.external_addr"; public static final String EXTERNAL_PORT="jgroups.external_port"; public static final String TCP_CLIENT_BIND_ADDR="jgroups.tcp.client_bind_addr"; public static final String BIND_INTERFACE="jgroups.bind_interface"; public static final String TCPPING_INITIAL_HOSTS="jgroups.tcpping.initial_hosts"; public static final String UDP_MCAST_ADDR="jgroups.udp.mcast_addr"; public static final String UDP_MCAST_PORT="jgroups.udp.mcast_port"; public static final String UDP_IP_TTL="jgroups.udp.ip_ttl"; public static final String MPING_MCAST_ADDR="jgroups.mping.mcast_addr"; public static final String MPING_MCAST_PORT="jgroups.mping.mcast_port"; public static final String MPING_IP_TTL="jgroups.mping.ip_ttl"; public static final String BPING_BIND_PORT="jgroups.bping.bind_port"; public static final String STOMP_BIND_ADDR="jgroups.stomp.bind_addr"; public static final String STOMP_ENDPOINT_ADDR="jgroups.stomp.endpoint_addr"; public static final String MAGIC_NUMBER_FILE="jgroups.conf.magic_number_file"; public static final String PROTOCOL_ID_FILE="jgroups.conf.protocol_id_file"; public static final String RESOLVE_DNS="jgroups.resolve_dns"; public static final String PRINT_UUIDS="jgroups.print_uuids"; public static final String UUID_CACHE_MAX_ELEMENTS="jgroups.uuid_cache.max_elements"; public static final String UUID_CACHE_MAX_AGE="jgroups.uuid_cache.max_age"; public static final String IPV6_MCAST_PREFIX="jgroups.ipmcast.prefix"; public static final String TIMER_NUM_THREADS="jgroups.timer.num_threads"; public static final String USE_JDK_LOGGER="jgroups.use.jdk_logger"; // forces use of the JDK logger public static final String CUSTOM_LOG_FACTORY="jgroups.logging.log_factory_class"; /** System prop for defining the default number of headers in a Message */ public static final String DEFAULT_HEADERS="jgroups.msg.default_headers"; public static final long DEFAULT_FIRST_UNICAST_SEQNO = 1; /** First ID assigned for building blocks (defined in jg-protocols.xml) */ public static final short BLOCKS_START_ID=200; public static final long THREADPOOL_SHUTDOWN_WAIT_TIME=3000; public static final long THREAD_SHUTDOWN_WAIT_TIME=300; public static final String DUMMY="dummy-"; public static final String MATCH_ADDR="match-address"; public static final String MATCH_HOST="match-host"; public static final String MATCH_INTF="match-interface"; public static final String PREFIX="org.jgroups.protocols."; public static final String XML_VALIDATION="jgroups.xml.validation"; // for TestNG public static final String FUNCTIONAL="functional"; public static final String TIME_SENSITIVE="time-sensitive"; public static final String STACK_DEPENDENT="stack-dependent"; public static final String STACK_INDEPENDENT="stack-independent"; public static final String GOSSIP_ROUTER="gossip-router"; public static final String FLUSH="flush"; public static final String BYTEMAN="byteman"; public static final String EAP_EXCLUDED="eap-excluded"; // tests not supported by EAP public static final String INITIAL_MCAST_ADDR="INITIAL_MCAST_ADDR"; public static final String INITIAL_MCAST_PORT="INITIAL_MCAST_PORT"; public static final String INITIAL_TCP_PORT="INITIAL_TCP_PORT"; public static final String CCHM_INITIAL_CAPACITY="cchm.initial_capacity"; public static final String CCHM_LOAD_FACTOR="cchm.load_factor"; public static final String CCHM_CONCURRENCY_LEVEL="cchm.concurrency_level"; public static final String MAX_LIST_PRINT_SIZE="max.list.print_size"; public static final String SUPPRESS_VIEW_SIZE="suppress.view_size"; public static final int IPV4_SIZE=4; public static final int IPV6_SIZE=16; private Global() { throw new InstantiationError( "Must not instantiate this class" ); } public static boolean getPropertyAsBoolean(String property, boolean defaultValue) { boolean result = defaultValue; try{ String tmp = System.getProperty(property); if(tmp != null) result = Boolean.parseBoolean(tmp); } catch(Throwable t) { } return result; } public static long getPropertyAsLong(String property, long defaultValue) { long result = defaultValue; try{ String tmp = System.getProperty(property); if(tmp != null) result = Long.parseLong(tmp); } catch(Throwable t){ } return result; } public static int getPropertyAsInteger(String property, int defaultValue) { int result = defaultValue; try{ String tmp = System.getProperty(property); if(tmp != null) result = Integer.parseInt(tmp); } catch(Throwable t){ } return result; } }
41.164384
103
0.72629
117f49bf502ee31f24cc809a9d4b971891d4acf1
2,684
package blatt02; import java.util.Random; public class InsertionSort { public static void rand(int[] array) { Random random = new Random(); for(int i = 0; i < array.length;i++) { array[i] = random.nextInt(); } } public static void auf(int [] array) { array[0] = 1; for(int i = 1; i < array.length;i++) { array[i] = array[i-1]+1; } } public static void ab(int[] array) { int num = Integer.MAX_VALUE; for(int i = 0; i < array.length;i++) { array[i] = num - 1; } } public static boolean isSorted(int [] array) { for(int i = 0; i < array.length-1;i++) { if(array[i] < array[i+1]) { return false; } } return true; } public static void insertionSort(int [] array) { for(int j = 1; j < array.length;j++) { int key = array[j]; int i = j-1; while(i >= 0 && array[i] < key) { array[i+1] = array[i]; i = i - 1; } array[i+1] = key; } } public static void main(String[] args) { int size = 0; try { size = Integer.parseInt(args[0]); }catch(NumberFormatException e) { System.err.println("Please Enter a Number!"); System.exit(1); }catch(ArrayIndexOutOfBoundsException e) { System.err.println("You have to give at least one input"); System.exit(1); } int[] array = new int[size]; if(args.length < 2) { rand(array); }else if(args.length == 2) { String art = args[1]; if(art.equals("auf")) { auf(array); }else if(art.equals("ab")) { ab(array); }else if(art.equals("rand")) { rand(array); }else { throw new IllegalArgumentException(); } }else { throw new IllegalArgumentException(); } if(array.length <= 100) { for(int i = 0; i < array.length;i++) { System.out.print(array[i]+" "); } System.out.println(); long start = System.currentTimeMillis(); insertionSort(array); long end = System.currentTimeMillis(); assert isSorted(array):"FEHLER:Feld is nicht Sortiert!"; for(int i = 0; i < array.length;i++) { System.out.print(array[i]+" "); } System.out.println(); System.out.println("Feld is Sortiert"); System.out.println("Das Sortieren des Arrays hat "+(end-start)+"ms gedauert."); }else { long start = System.currentTimeMillis(); insertionSort(array); long end = System.currentTimeMillis(); assert isSorted(array):"FEHLER:Feld ist nicht sortiert!"; System.out.println("Feld ist sortiert!"); System.out.println("Das Sortieren des Arrays hat "+(end-start)+"ms gedauert."); } }//end main }// end class
22.940171
83
0.568554
4a1376759138f6ff9b019c4886743f057449797c
732
package io.fabric.sdk.android.services.b; public abstract class j { private final String a; private final String b; public j(String paramString1, String paramString2) { this.a = paramString1; this.b = paramString2; } public String a() { return this.a; } public String b() { return this.b; } public static class a extends j { public a(String paramString1, String paramString2) { super(paramString2); } } public static class b extends j { public b(String paramString1, String paramString2) { super(paramString2); } } } /* Location: ~/io/fabric/sdk/android/services/b/j.class * * Reversed by: J */
15.574468
68
0.602459
f5b185ba16b808f96ee8c0ce1586a3cd8c863887
199
package net.sf.l2j.gameserver.enums; public enum TeamType { NONE(0), BLUE(1), RED(2); private int _id; private TeamType(int id) { _id = id; } public int getId() { return _id; } }
9.95
36
0.61809