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
ce592941d53f5d88dea84bdd5589d7ffda39ea61
515
package org.learn.points.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; /** * 积分实体类 */ @Data @TableName("t_points") public class Points { @TableId(value = "ID", type = IdType.AUTO) private Integer id;//积分ID @TableField private String username;//用户名 @TableField private Integer points;//增加的积分 }
23.409091
54
0.751456
fefa75b39dcd42676de2c28786ecf3a24dc3357f
200
package org.pmiops.workbench.actionaudit.auditors; public interface AuthDomainAuditor { void fireSetAccountDisabledStatus( long userId, boolean newDisabledValue, boolean oldDisabledValue); }
28.571429
71
0.82
58161215229b57ff17317810d2da86900fa4ca9c
807
package com.github.imthenico.simplecommons.data.db.sql.query; import com.github.imthenico.simplecommons.data.db.sql.query.impl.QueryBuilderImpl; import java.sql.Connection; import java.sql.SQLException; public interface QueryBuilder { QueryBuilder table(String tableName); QueryBuilder addPlaceholder(String placeholder); QueryBuilder addPlaceholders(String... placeholders); QueryBuilder addParameters(int quantity); QueryBuilder replace(String toReplace, String replacement); QueryBuilder replace(String toReplace, QueryBuilder replacement); QueryBuilder useSchema(QuerySchema schema); String getQuery(); StatementValueBinder prepare(Connection connection); static QueryBuilder create(String query) { return new QueryBuilderImpl(query); } }
26.032258
82
0.775713
e6f0fc905af4583c7d9eef2b72838e4ecf36b243
2,924
/* * This file is part of GroupManager, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * 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 me.lucko.luckperms.common.cache; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; /** * An expiring supplier extension. * * <p>The delegate supplier is only called on executions of {@link #get()} if the * result isn't already calculated.</p> * * @param <T> the supplied type */ public abstract class ExpiringCache<T> implements Supplier<T> { private final long durationNanos; private volatile T value; // when to expire. 0 means "not yet initialized". private volatile long expirationNanos; protected ExpiringCache(long duration, TimeUnit unit) { this.durationNanos = unit.toNanos(duration); } protected abstract @NonNull T supply(); @Override public T get() { long nanos = this.expirationNanos; long now = System.nanoTime(); if (nanos == 0 || now - nanos >= 0) { synchronized (this) { if (nanos == this.expirationNanos) { // recheck for lost race // compute the value using the delegate T t = supply(); this.value = t; // reset expiration timer nanos = now + this.durationNanos; // In the very unlikely event that nanos is 0, set it to 1; // no one will notice 1 ns of tardiness. this.expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } return this.value; } public void invalidate() { this.expirationNanos = 0; } }
34.809524
82
0.649453
aaae541a49372762956ba15c4804c560e0e1f7c2
5,968
/*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.api.common.operators.util; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import eu.stratosphere.api.common.functions.GenericCoGrouper; import eu.stratosphere.api.common.functions.GenericCollectorMap; import eu.stratosphere.api.common.functions.GenericCrosser; import eu.stratosphere.api.common.functions.GenericGroupReduce; import eu.stratosphere.api.common.functions.GenericJoiner; import eu.stratosphere.api.common.io.FileInputFormat; import eu.stratosphere.api.common.io.FileOutputFormat; import eu.stratosphere.api.common.io.InputFormat; import eu.stratosphere.api.common.io.OutputFormat; import eu.stratosphere.api.common.operators.DualInputOperator; import eu.stratosphere.api.common.operators.base.GenericDataSinkBase; import eu.stratosphere.api.common.operators.base.GenericDataSourceBase; import eu.stratosphere.api.common.operators.Operator; import eu.stratosphere.api.common.operators.SingleInputOperator; import eu.stratosphere.api.common.operators.base.CoGroupOperatorBase; import eu.stratosphere.api.common.operators.base.CrossOperatorBase; import eu.stratosphere.api.common.operators.base.GroupReduceOperatorBase; import eu.stratosphere.api.common.operators.base.JoinOperatorBase; import eu.stratosphere.api.common.operators.base.CollectorMapOperatorBase; /** * Convenience methods when dealing with {@link Operator}s. */ public class OperatorUtil { @SuppressWarnings("rawtypes") private final static Map<Class<?>, Class<? extends Operator>> STUB_CONTRACTS = new LinkedHashMap<Class<?>, Class<? extends Operator>>(); static { STUB_CONTRACTS.put(GenericCollectorMap.class, CollectorMapOperatorBase.class); STUB_CONTRACTS.put(GenericGroupReduce.class, GroupReduceOperatorBase.class); STUB_CONTRACTS.put(GenericCoGrouper.class, CoGroupOperatorBase.class); STUB_CONTRACTS.put(GenericCrosser.class, CrossOperatorBase.class); STUB_CONTRACTS.put(GenericJoiner.class, JoinOperatorBase.class); STUB_CONTRACTS.put(FileInputFormat.class, GenericDataSourceBase.class); STUB_CONTRACTS.put(FileOutputFormat.class, GenericDataSinkBase.class); STUB_CONTRACTS.put(InputFormat.class, GenericDataSourceBase.class); STUB_CONTRACTS.put(OutputFormat.class, GenericDataSinkBase.class); } /** * Returns the associated {@link Operator} type for the given {@link eu.stratosphere.api.common.functions.Function} class. * * @param stubClass * the stub class * @return the associated Operator type */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Class<? extends Operator> getContractClass(final Class<?> stubClass) { if (stubClass == null) { return null; } final Class<?> contract = STUB_CONTRACTS.get(stubClass); if (contract != null) { return (Class<? extends Operator<?>>) contract; } Iterator<Entry<Class<?>, Class<? extends Operator>>> stubContracts = STUB_CONTRACTS.entrySet().iterator(); while (stubContracts.hasNext()) { Map.Entry<Class<?>, Class<? extends Operator>> entry = stubContracts.next(); if (entry.getKey().isAssignableFrom(stubClass)) { return entry.getValue(); } } return null; } /** * Returns the number of inputs for the given {@link Operator} type.<br> * Currently, it can be 0, 1, or 2. * * @param contractType * the type of the Operator * @return the number of input contracts */ public static int getNumInputs(final Class<? extends Operator<?>> contractType) { if (GenericDataSourceBase.class.isAssignableFrom(contractType)) { return 0; } if (GenericDataSinkBase.class.isAssignableFrom(contractType) || SingleInputOperator.class.isAssignableFrom(contractType)) { return 1; } if (DualInputOperator.class.isAssignableFrom(contractType)) { return 2; } throw new IllegalArgumentException("not supported"); } /** * Sets the inputs of the given {@link Operator}.<br> * Currently, the list can have 0, 1, or 2 elements and the number of elements must match the type of the contract. * * @param contract * the Operator whose inputs should be set * @param inputs * all input contracts to this contract */ @SuppressWarnings({ "deprecation", "rawtypes", "unchecked" }) public static void setInputs(final Operator<?> contract, final List<List<Operator>> inputs) { if (contract instanceof GenericDataSinkBase) { if (inputs.size() != 1) { throw new IllegalArgumentException("wrong number of inputs"); } ((GenericDataSinkBase) contract).setInputs(inputs.get(0)); } else if (contract instanceof SingleInputOperator) { if (inputs.size() != 1) { throw new IllegalArgumentException("wrong number of inputs"); } ((SingleInputOperator) contract).setInputs(inputs.get(0)); } else if (contract instanceof DualInputOperator) { if (inputs.size() != 2) { throw new IllegalArgumentException("wrong number of inputs"); } ((DualInputOperator) contract).setFirstInputs(inputs.get(0)); ((DualInputOperator) contract).setSecondInputs(inputs.get(1)); } } }
41.444444
123
0.726877
d920417c3acc5608ce2b2338f8668e9a897bed15
1,286
package com.xiaoyi.ssm.service; import java.util.List; import com.xiaoyi.ssm.model.TrainCourse; /** * @Description: 培训课程业务逻辑层 * @author 宋高俊 * @date 2018年9月29日 下午8:04:23 */ public interface TrainCourseService extends BaseService<TrainCourse, String> { /** * @Description: 根据培训机构ID获取培训课程 * @author 宋高俊 * @param id * @return * @date 2018年9月29日 下午8:48:31 */ List<TrainCourse> selectByTrainTeamID(String id); /** * @Description: 根据教练获取所开设的培训课程 * @author 宋高俊 * @param id * @return * @date 2018年9月30日 上午11:49:18 */ List<TrainCourse> selectByTrainCoachID(String id); /** * @Description: 根据教练统计开设课程 * @author 宋高俊 * @param id * @return * @date 2018年10月10日 下午7:21:20 */ int countByCoach(String id); /** * @Description: 根据培训机构统计开设课程 * @author 宋高俊 * @param id * @return * @date 2018年10月11日 下午8:35:00 */ int countByTeam(String id); /** * @Description: 获取我收藏的课程 * @author 宋高俊 * @param id * @return * @date 2018年10月24日 上午9:24:44 */ List<TrainCourse> selectByCollect(String id); /** * @Description: 查询该课程是否被用户收藏 * @author 宋高俊 * @param id * @param memberid * @return * @date 2018年10月25日 下午2:52:14 */ TrainCourse selectByMember(String id, String memberid); }
18.371429
78
0.639969
c650d323d1ce57662087dfe3a769b1838dcce4d7
2,433
/*L * Copyright Oracle inc, SAIC-F * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cadsr-util/LICENSE.txt for details. */ package gov.nih.nci.ncicb.cadsr.common.dto; import gov.nih.nci.ncicb.cadsr.common.dto.BaseTransferObject; import gov.nih.nci.ncicb.cadsr.common.resource.Address; import gov.nih.nci.ncicb.cadsr.common.resource.Organization; import gov.nih.nci.ncicb.cadsr.common.resource.Person; public class AddressTransferObject extends BaseTransferObject implements Address{ public String addressLine1; public String addressLine2; public String city; public String country; public String id; public String postalCode; public Integer rank; public String state; public String type; private Person person; private Organization organization; public AddressTransferObject() { } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine1() { return addressLine1; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine2() { return addressLine2; } public void setCity(String city) { this.city = city; } public String getCity() { return city; } public void setCountry(String country) { this.country = country; } public String getCountry() { return country; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getPostalCode() { return postalCode; } public void setRank(Integer rank) { this.rank = rank; } public Integer getRank() { return rank; } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setPerson(Person person) { this.person = person; } public Person getPerson() { return person; } public void setOrganization(Organization organization) { this.organization = organization; } public Organization getOrganization() { return organization; } }
20.445378
65
0.67201
e8c56e4cc0e6ba5e543a0b08a0830b135dafc80c
4,029
package com.kugou.loader.clickhouse.context; import com.google.common.collect.Maps; import com.kugou.loader.clickhouse.ClickhouseClient; import com.kugou.loader.clickhouse.ClickhouseClientHolder; import com.kugou.loader.clickhouse.config.ClickhouseConfiguration; import com.kugou.loader.clickhouse.config.ConfigurationKeys; import com.kugou.loader.clickhouse.utils.Tuple; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; /** * Created by jaykelin on 2018/1/26. */ public class ClickhouseLoaderContext { private static final Logger logger = LoggerFactory.getLogger(ClickhouseLoaderContext.class); private ClickhouseConfiguration configuration = null; private ClickhouseClient client = null; private Map<Integer, Tuple.Tuple2<String,String>> colDataType = Maps.newHashMap(); private Integer columnSize = -1; public ClickhouseLoaderContext(ClickhouseConfiguration configuration) throws SQLException { this.configuration = configuration; this.client = ClickhouseClientHolder.getClickhouseClient(configuration.get(ConfigurationKeys.CLI_P_CONNECT), configuration.get(ConfigurationKeys.CLI_P_CLICKHOUSE_USERNAME), configuration.get(ConfigurationKeys.CLI_P_CLICKHOUSE_PASSWORD)); String database ; String table; if (StringUtils.isBlank(database = getTargetLocalDatabase())){ logger.warn("can not found target_local_database, will use CLI database to replace."); database = configuration.get(ConfigurationKeys.CLI_P_DATABASE); } if (StringUtils.isBlank(table = getTargetLocalTable())){ logger.warn("can not found target_local_table, will use CLI table to replace."); table = configuration.get(ConfigurationKeys.CLI_P_TABLE); } String sql = "describe "+ database+"."+table; logger.info(sql); ResultSet resultSet = client.executeQuery(sql); int index = -1; try{ while(resultSet.next()){ String column_name = resultSet.getString(1); String column_datatype = resultSet.getString(2); logger.info(column_name +"\t"+column_datatype+"\t"+resultSet.getString(3)+"\t"+resultSet.getString(4)); index ++; colDataType.put(index, Tuple.tuple(column_name, column_datatype)); } }catch(ArrayIndexOutOfBoundsException e){ logger.error(e.getMessage(), e); } columnSize = index+1; } public ClickhouseConfiguration getConfiguration(){ return configuration; } /** * return Distributed Database * @return */ public String getTargetDistributedDatabase(){ return configuration.get(ConfigurationKeys.CL_TARGET_TABLE_DATABASE); } /** * return Distributed table * @return */ public String getTargetDistributedTable(){ return configuration.get(ConfigurationKeys.CLI_P_TABLE); } public String getTargetLocalDatabase(){ return configuration.get(ConfigurationKeys.CL_TARGET_LOCAL_DATABASE); } public String getTargetLocalTable(){ return configuration.get(ConfigurationKeys.CL_TARGET_LOCAL_TABLE); } public int getColumnSize(){ return columnSize; } /** * 当前字段是否是字符串类型 * @param col * @return */ public boolean columnIsStringType(int col){ if (col >= getColumnSize()){ throw new IllegalArgumentException(String.format("column index[s%] >= columnsize[s%]", col, getColumnSize())); } Tuple.Tuple2<String, String> tuple = colDataType.get(col); if (null != tuple && StringUtils.isNotBlank(tuple._2()) && (tuple._2().equals("String") || tuple._2().equals("Nullable(String)")) ){ return true; } else { return false; } } }
35.654867
245
0.674361
6ec141550dbc2a0ce54fcda98ab8f958b57812cc
1,374
package com.gwtfb.sdk; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.rpc.AsyncCallback; import com.gwtfb.client.Callback; /** * Class that wraps Facebook Event Handling methods * @see http://developers.facebook.com/docs/reference/javascript/#event-handling * @author ola */ public class FBEvent { /** * Wrapper method * http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe */ public native void subscribe(String event, Callback<JavaScriptObject> callback ) /*-{ var app=this; $wnd.FB.Event.subscribe(event,function(response){ app.@com.gwtfb.sdk.FBEvent::callbackSuccess(Lcom/google/gwt/user/client/rpc/AsyncCallback;Lcom/google/gwt/core/client/JavaScriptObject;)(callback,response); }); }-*/; public native void unsubscribe(String event, Callback<JavaScriptObject> callback ) /*-{ var app=this; $wnd.FB.Event.unsubscribe(event,function(response){ app.@com.gwtfb.sdk.FBEvent::callbackSuccess(Lcom/google/gwt/user/client/rpc/AsyncCallback;Lcom/google/gwt/core/client/JavaScriptObject;)(callback,response); }); }-*/; /* * Called when method succeeded. */ protected void callbackSuccess(AsyncCallback<JavaScriptObject> callback, JavaScriptObject obj) { callback.onSuccess ( obj ); } }
35.230769
169
0.708151
b15769d35435a3f73dd97359016fca183e207f0f
3,830
package relamapper.accountservice.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import relamapper.accountservice.model.Account; import relamapper.accountservice.model.Credential; import relamapper.accountservice.model.Information; import relamapper.accountservice.model.Message; import relamapper.accountservice.service.AccountsService; import relamapper.accountservice.service.ProfileService; import relamapper.accountservice.utilities.ControllerUtils; import java.util.List; @RestController public class RetrieveController { private final Logger logger = LoggerFactory.getLogger(getClass()); private final ControllerUtils utils = new ControllerUtils(); private final AccountsService accountsService; private final ProfileService profileService; @Autowired public RetrieveController(AccountsService accountsService, ProfileService profileService) { this.accountsService = accountsService; this.profileService = profileService; } /** ROUTES **************************************************************/ @RequestMapping(value = "/credentials", method = RequestMethod.POST) @ResponseBody public Credential getCredential(@RequestParam String email) { logger.debug("get credentials for : {}", email); if(!email.isEmpty()) { Account account = accountsService.getByEmail(email); if(account != null) { return new Credential(account); } } return null; } // get current @RequestMapping(value = "/get/{uuid}") @ResponseBody public Information getCurrent(@PathVariable String uuid) { logger.debug("get information for current user"); if(utils.validUUID(uuid)) { Account account = accountsService.getByUUID(uuid); return new Information(account); } return null; } // get UUID @RequestMapping(value = "/get_uuid", method = RequestMethod.POST) @ResponseBody public Message getUUID(@RequestParam String email) { logger.debug("get UUID of : {}", email); Message m = utils.defaultMessage(); if(!email.isEmpty()) { String uuid = accountsService.getUUID(email); if(uuid != null) { m.setSuccess(uuid); } else { m.setResult("not found"); } } return m; } // list accounts @RequestMapping(value = "/list") @ResponseBody public List<Information> listAll() { logger.debug("list all accounts"); List<Account> accounts = accountsService.listAll(); return utils.listTransformToInformation(accounts); } @RequestMapping(value = "/list/enabled") @ResponseBody public List<Information> listEnabled() { logger.debug("list enabled accounts"); List<Account> accounts = accountsService.listEnabled(); return utils.listTransformToInformation(accounts); } @RequestMapping(value = "/list/disabled") @ResponseBody public List<Information> listDisabled() { logger.debug("list disabled accounts"); List<Account> accounts = accountsService.listDisabled(); return utils.listTransformToInformation(accounts); } // list by role defaults to member if role is invalid @RequestMapping(value = "/list/by/{role}") @ResponseBody public List<Information> listByRole(@PathVariable String role) { role = utils.normalizeRole(role); logger.debug("list accounts by role : ", role); List<Account> accounts = accountsService.listByRole(role); return utils.listTransformToInformation(accounts); } }
34.504505
95
0.66658
5c8752a4da345d5935c97718cf0e2e6935b7331a
2,061
package core.pl.bindings; import play.data.validation.Constraints; /** * Created by nue on 2.9.2015. */ public class RegistrationData { @Constraints.Email private String email; private String password; private String passwordAgain; private String userName; private String userAddress; private String userSurname; private String userAge; private String userBirth; private String accountName; private String phone; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPasswordAgain() { return passwordAgain; } public void setPasswordAgain(String passwordAgain) { this.passwordAgain = passwordAgain; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public String getUserSurname() { return userSurname; } public void setUserSurname(String userSurname) { this.userSurname = userSurname; } public String getUserAge() { return userAge; } public void setUserAge(String userAge) { this.userAge = userAge; } public String getUserBirth() { return userBirth; } public void setUserBirth(String userBirth) { this.userBirth = userBirth; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
18.567568
56
0.633188
75a34fd1a9e74460443e7915a2c0fdf2239cabf0
23,400
/* * QR Code generator library (Java) * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/qr-code-generator-library * * 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.realityforge.gwt.qr_code; import elemental2.dom.CanvasRenderingContext2D; import elemental2.dom.HTMLCanvasElement; import java.util.Arrays; import java.util.List; import java.util.Objects; import javax.annotation.Nonnull; import jsinterop.base.Js; import org.realityforge.braincheck.BrainCheckConfig; import static org.realityforge.braincheck.Guards.*; /** * Represents an immutable square grid of black and white cells for a QR Code symbol, and * provides static functions to create a QR Code from user-supplied textual or binary data. * <p>This class covers the QR Code model 2 specification, supporting all versions (sizes) * from 1 to 40, all 4 error correction levels, and only 3 character encoding modes.</p> */ public final class QrCode { // For use in getPenaltyScore(), when evaluating which mask is best. private static final int PENALTY_N1 = 3; private static final int PENALTY_N2 = 3; private static final int PENALTY_N3 = 40; private static final int PENALTY_N4 = 10; private final int _version; private final int _size; private final Ecc _errorCorrectionLevel; private final int _mask; // Private grids of modules/pixels (conceptually immutable) private boolean[][] _modules; // The modules of this QR Code symbol (false = white, true = black) private boolean[][] _isFunction; // Indicates function modules that are not subjected to masking /** * Creates a new QR Code symbol with the specified version number, error correction level, binary data array, and mask number. * <p>This is a cumbersome low-level constructor that should not be invoked directly by the user. * To go one level up, see the {@link QrCodeTool#encodeSegments(List, Ecc)} function.</p> * * @param version the version number to use, which must be in the range 1 to 40, inclusive * @param ecl the error correction level to use * @param dataCodewords the raw binary user data to encode * @param mask the mask pattern to use, which is either -1 for automatic choice or from 0 to 7 for fixed choice * @throws NullPointerException if the byte array or error correction level is {@code null} * @throws IllegalArgumentException if the version or mask value is out of range */ QrCode( final int version, @Nonnull final Ecc ecl, @Nonnull final byte[] dataCodewords, final int mask ) { // Check arguments Objects.requireNonNull( ecl ); Objects.requireNonNull( dataCodewords ); assert QrCodeTool.isVersionValid( version ); assert QrCodeTool.isMaskValid( mask ) || QrCodeTool.AUTO_MASK == mask; // Initialize fields _version = version; _size = version * 4 + 17; _errorCorrectionLevel = ecl; _modules = new boolean[ _size ][ _size ]; // Entirely white grid _isFunction = new boolean[ _size ][ _size ]; // Draw function patterns, draw all codewords, do masking drawFunctionPatterns(); drawCodewords( appendErrorCorrection( dataCodewords ) ); _mask = handleConstructorMasking( mask ); } /** * Return the QR Code symbol's version number, which is always between 1 and 40 (inclusive). * * @return the QR Code symbol's version number, which is always between 1 and 40 (inclusive). */ public int getVersion() { return _version; } /** * The width and height of this QR Code symbol, measured in modules. * Always equal to version &times; 4 + 17, in the range 21 to 177. * * @return the width and height of this QR Code symbol, measured in modules. */ public int getSize() { return _size; } /** * The error correction level used in this QR Code symbol. * * @return the error correction level used in this QR Code symbol. */ @Nonnull public Ecc getErrorCorrectionLevel() { return _errorCorrectionLevel; } /** * The mask pattern used in this QR Code symbol, in the range 0 to 7 (i.e. unsigned 3-bit integer). * Note that even if a constructor was called with automatic masking requested * (_mask = -1), the resulting object will still have a mask value between 0 and 7. * * @return the mask */ public int getMask() { return _mask; } /** * Returns the color of the module (pixel) at the specified coordinates, which is either * false for white or true for black. The top left corner has the coordinates (x=0, y=0). * If the specified coordinates are out of bounds, then false (white) is returned. * * @param x the x coordinate, where 0 is the left edge and size&minus;1 is the right edge * @param y the y coordinate, where 0 is the top edge and size&minus;1 is the bottom edge * @return the module's color, which is either false (white) or true (black) */ public boolean getModule( final int x, final int y ) { return 0 <= x && x < _size && 0 <= y && y < _size && _modules[ y ][ x ]; } /* * Draw image on canvas representing this QR Code, with the specified module scale and number * of border modules. For example, the arguments scale=10, border=4 means to pad the QR Code symbol * with 4 white border modules on all four edges, then use 10*10 pixels to represent each module. * The resulting image only contains the hex colors 000000 and FFFFFF. * * @param scale the module scale factor, which must be positive * @param border the number of border modules to add, which must be non-negative * @return an image representing this QR Code, with padding and scaling * @throws IllegalArgumentException if the scale or border is out of range */ public void drawCanvas( final double scale, final int border, @Nonnull final HTMLCanvasElement canvas ) { if ( BrainCheckConfig.checkApiInvariants() ) { apiInvariant( () -> border >= 0, () -> "Border must be non-negative" ); apiInvariant( () -> scale >= 0, () -> "Scale must be non-negative" ); apiInvariant( () -> !( _size + border * 2L > Integer.MAX_VALUE / scale ), () -> "Scale or border too large" ); } final int dimension = (int) ( ( _size + border * 2 ) * scale ); canvas.width = dimension; canvas.height = dimension; final CanvasRenderingContext2D context = Js.cast( canvas.getContext( "2d" ) ); // Clear the canvas context.fillColor = "#FFFFFF"; context.fill(); // Set the color for all the modules context.fillColor = "#FFFFFF"; for ( int y = -border; y < _size + border; y++ ) { for ( int x = -border; x < _size + border; x++ ) { if ( getModule( x, y ) ) { context.fillRect( ( x + border ) * scale, ( y + border ) * scale, scale, scale ); } } } } /** * Based on the specified number of border modules to add as padding, this returns a * string whose contents represents an SVG XML file that depicts this QR Code symbol. * Note that Unix newlines (\n) are always used, regardless of the platform. * * @param border the number of border modules to add, which must be non-negative * @return a string representing this QR Code as an SVG document */ @Nonnull public String toSvgString( final int border ) { if ( BrainCheckConfig.checkApiInvariants() ) { apiInvariant( () -> border >= 0, () -> "Border must be non-negative" ); apiInvariant( () -> !( _size + border * 2L > Integer.MAX_VALUE ), () -> "Border too large" ); } final StringBuilder sb = new StringBuilder(); final int dimension = _size + border * 2; sb.append( "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 " ) .append( dimension ) .append( " " ) .append( dimension ) .append( "\" stroke=\"none\">\n" ) .append( "<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n" ) .append( "<path d=\"" ); boolean head = true; for ( int y = -border; y < _size + border; y++ ) { for ( int x = -border; x < _size + border; x++ ) { if ( getModule( x, y ) ) { if ( head ) { head = false; } else { sb.append( " " ); } sb.append( "M" ).append( x + border ).append( "," ).append( y + border ).append( "h1v1h-1z" ); } } } sb.append( "\" fill=\"#000000\"/>\n" ); sb.append( "</svg>\n" ); return sb.toString(); } private void drawFunctionPatterns() { // Draw horizontal and vertical timing patterns for ( int i = 0; i < _size; i++ ) { setFunctionModule( 6, i, i % 2 == 0 ); setFunctionModule( i, 6, i % 2 == 0 ); } // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) drawFinderPattern( 3, 3 ); drawFinderPattern( _size - 4, 3 ); drawFinderPattern( 3, _size - 4 ); // Draw numerous alignment patterns int[] alignPatPos = QrCodeTool.getAlignmentPatternPositions( _version ); int numAlign = alignPatPos.length; for ( int i = 0; i < numAlign; i++ ) { for ( int j = 0; j < numAlign; j++ ) { if ( ( i != 0 || j != 0 ) && ( i != 0 || j != numAlign - 1 ) && ( i != numAlign - 1 || j != 0 ) ) { drawAlignmentPattern( alignPatPos[ i ], alignPatPos[ j ] ); } } } // Draw configuration data drawFormatBits( 0 ); // Dummy mask value; overwritten later in the constructor drawVersion(); } // Draws two copies of the format bits (with its own error correction code) // based on the given mask and this object's error correction level field. private void drawFormatBits( int mask ) { // Calculate error correction code and pack bits int data = _errorCorrectionLevel.getFormatBits() << 3 | mask; // errCorrLvl is uint2, mask is uint3 int rem = data; for ( int i = 0; i < 10; i++ ) { rem = ( rem << 1 ) ^ ( ( rem >>> 9 ) * 0x537 ); } data = data << 10 | rem; data ^= 0x5412; // uint15 if ( BrainCheckConfig.checkInvariants() ) { final int d = data; invariant( () -> d >>> 15 == 0, () -> "Data alignment error" ); } // Draw first copy for ( int i = 0; i <= 5; i++ ) { setFunctionModule( 8, i, ( ( data >>> i ) & 1 ) != 0 ); } setFunctionModule( 8, 7, ( ( data >>> 6 ) & 1 ) != 0 ); setFunctionModule( 8, 8, ( ( data >>> 7 ) & 1 ) != 0 ); setFunctionModule( 7, 8, ( ( data >>> 8 ) & 1 ) != 0 ); for ( int i = 9; i < 15; i++ ) { setFunctionModule( 14 - i, 8, ( ( data >>> i ) & 1 ) != 0 ); } // Draw second copy for ( int i = 0; i <= 7; i++ ) { setFunctionModule( _size - 1 - i, 8, ( ( data >>> i ) & 1 ) != 0 ); } for ( int i = 8; i < 15; i++ ) { setFunctionModule( 8, _size - 15 + i, ( ( data >>> i ) & 1 ) != 0 ); } setFunctionModule( 8, _size - 8, true ); } // Draws two copies of the version bits (with its own error correction code), // based on this object's version field (which only has an effect for 7 <= version <= 40). private void drawVersion() { if ( _version < 7 ) { return; } // Calculate error correction code and pack bits int rem = _version; // version is uint6, in the range [7, 40] for ( int i = 0; i < 12; i++ ) { rem = ( rem << 1 ) ^ ( ( rem >>> 11 ) * 0x1F25 ); } int data = _version << 12 | rem; // uint18 if ( BrainCheckConfig.checkInvariants() ) { final int d = data; invariant( () -> d >>> 18 == 0, () -> "Data alignment error" ); } // Draw two copies for ( int i = 0; i < 18; i++ ) { boolean bit = ( ( data >>> i ) & 1 ) != 0; int a = _size - 11 + i % 3, b = i / 3; setFunctionModule( a, b, bit ); setFunctionModule( b, a, bit ); } } // Draws a 9*9 finder pattern including the border separator, with the center module at (x, y). private void drawFinderPattern( int x, int y ) { for ( int i = -4; i <= 4; i++ ) { for ( int j = -4; j <= 4; j++ ) { int dist = Math.max( Math.abs( i ), Math.abs( j ) ); // Chebyshev/infinity norm int xx = x + j, yy = y + i; if ( 0 <= xx && xx < _size && 0 <= yy && yy < _size ) { setFunctionModule( xx, yy, dist != 2 && dist != 4 ); } } } } // Draws a 5*5 alignment pattern, with the center module at (x, y). private void drawAlignmentPattern( int x, int y ) { for ( int i = -2; i <= 2; i++ ) { for ( int j = -2; j <= 2; j++ ) { setFunctionModule( x + j, y + i, Math.max( Math.abs( i ), Math.abs( j ) ) != 1 ); } } } // Sets the color of a module and marks it as a function module. // Only used by the constructor. Coordinates must be in range. private void setFunctionModule( int x, int y, boolean isBlack ) { _modules[ y ][ x ] = isBlack; _isFunction[ y ][ x ] = true; } /*---- Private helper methods for constructor: Codewords and masking ----*/ // Returns a new byte string representing the given data with the appropriate error correction // codewords appended to it, based on this object's version and error correction level. private byte[] appendErrorCorrection( @Nonnull final byte[] data ) { if ( BrainCheckConfig.checkInvariants() ) { invariant( () -> QrCodeTool.isDataLengthValid( _version, _errorCorrectionLevel, data.length ), () -> "Invalid data length for version and correction level" ); } // Calculate parameter numbers int numBlocks = QrCodeTool.NUM_ERROR_CORRECTION_BLOCKS[ _errorCorrectionLevel.ordinal() ][ _version ]; int blockEccLen = QrCodeTool.ECC_CODEWORDS_PER_BLOCK[ _errorCorrectionLevel.ordinal() ][ _version ]; int rawCodewords = QrCodeTool.getNumRawDataModules( _version ) / 8; int numShortBlocks = numBlocks - rawCodewords % numBlocks; int shortBlockLen = rawCodewords / numBlocks; // Split data into blocks and append ECC to each block byte[][] blocks = new byte[ numBlocks ][]; ReedSolomonGenerator rs = new ReedSolomonGenerator( blockEccLen ); for ( int i = 0, k = 0; i < numBlocks; i++ ) { byte[] dat = Arrays.copyOfRange( data, k, k + shortBlockLen - blockEccLen + ( i < numShortBlocks ? 0 : 1 ) ); byte[] block = Arrays.copyOf( dat, shortBlockLen + 1 ); k += dat.length; byte[] ecc = rs.getRemainder( dat ); System.arraycopy( ecc, 0, block, block.length - blockEccLen, ecc.length ); blocks[ i ] = block; } // Interleave (not concatenate) the bytes from every block into a single sequence byte[] result = new byte[ rawCodewords ]; for ( int i = 0, k = 0; i < blocks[ 0 ].length; i++ ) { for ( int j = 0; j < blocks.length; j++ ) { // Skip the padding byte in short blocks if ( i != shortBlockLen - blockEccLen || j >= numShortBlocks ) { result[ k ] = blocks[ j ][ i ]; k++; } } } return result; } // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire // data area of this QR Code symbol. Function modules need to be marked off before this is called. private void drawCodewords( @Nonnull final byte[] data ) { Objects.requireNonNull( data ); if ( BrainCheckConfig.checkInvariants() ) { invariant( () -> data.length == QrCodeTool.getNumRawDataModules( _version ) / 8, () -> "Invalid data length" ); } int i = 0; // Bit index into the data // Do the funny zigzag scan for ( int right = _size - 1; right >= 1; right -= 2 ) { // Index of right column in each column pair if ( right == 6 ) { right = 5; } for ( int vert = 0; vert < _size; vert++ ) { // Vertical counter for ( int j = 0; j < 2; j++ ) { int x = right - j; // Actual x coordinate boolean upward = ( ( right + 1 ) & 2 ) == 0; int y = upward ? _size - 1 - vert : vert; // Actual y coordinate if ( !_isFunction[ y ][ x ] && i < data.length * 8 ) { _modules[ y ][ x ] = ( ( data[ i >>> 3 ] >>> ( 7 - ( i & 7 ) ) ) & 1 ) != 0; i++; } // If there are any remainder bits (0 to 7), they are already // set to 0/false/white when the grid of modules was initialized } } } if ( BrainCheckConfig.checkInvariants() ) { final int v = i; invariant( () -> v == data.length * 8, () -> "Unexpected remainder" ); } } // XORs the data modules in this QR Code with the given mask pattern. Due to XOR's mathematical // properties, calling applyMask(m) twice with the same value is equivalent to no change at all. // This means it is possible to apply a mask, undo it, and try another mask. Note that a final // well-formed QR Code symbol needs exactly one mask applied (not zero, not two, etc.). private void applyMask( final int mask ) { assert QrCodeTool.isMaskValid( mask ); for ( int y = 0; y < _size; y++ ) { for ( int x = 0; x < _size; x++ ) { boolean invert; switch ( mask ) { case 0: invert = ( x + y ) % 2 == 0; break; case 1: invert = y % 2 == 0; break; case 2: invert = x % 3 == 0; break; case 3: invert = ( x + y ) % 3 == 0; break; case 4: invert = ( x / 3 + y / 2 ) % 2 == 0; break; case 5: invert = x * y % 2 + x * y % 3 == 0; break; case 6: invert = ( x * y % 2 + x * y % 3 ) % 2 == 0; break; default: if ( BrainCheckConfig.checkInvariants() ) { invariant( () -> 7 == mask, () -> "Unhandled mask value" ); } invert = ( ( x + y ) % 2 + x * y % 3 ) % 2 == 0; break; } _modules[ y ][ x ] ^= invert & !_isFunction[ y ][ x ]; } } } // A messy helper function for the constructors. This QR Code must be in an unmasked state when this // method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed. // This method applies and returns the actual mask chosen, from 0 to 7. private int handleConstructorMasking( final int mask ) { int actualMask = mask; if ( QrCodeTool.AUTO_MASK == mask ) { // Automatically choose best _mask int minPenalty = Integer.MAX_VALUE; for ( int i = 0; i < 8; i++ ) { drawFormatBits( i ); applyMask( i ); int penalty = getPenaltyScore(); if ( penalty < minPenalty ) { actualMask = i; minPenalty = penalty; } applyMask( i ); // Undoes the mask due to XOR } } assert QrCodeTool.isMaskValid( actualMask ); drawFormatBits( actualMask ); // Overwrite old format bits applyMask( actualMask ); // Apply the final choice of mask return actualMask; // The caller shall assign this value to the final-declared field } // Calculates and returns the penalty score based on state of this QR Code's current modules. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. private int getPenaltyScore() { int result = 0; // Adjacent modules in row having same color for ( int y = 0; y < _size; y++ ) { boolean colorX = false; for ( int x = 0, runX = 0; x < _size; x++ ) { if ( x == 0 || _modules[ y ][ x ] != colorX ) { colorX = _modules[ y ][ x ]; runX = 1; } else { runX++; if ( runX == 5 ) { result += PENALTY_N1; } else if ( runX > 5 ) { result++; } } } } // Adjacent modules in column having same color for ( int x = 0; x < _size; x++ ) { boolean colorY = false; for ( int y = 0, runY = 0; y < _size; y++ ) { if ( y == 0 || _modules[ y ][ x ] != colorY ) { colorY = _modules[ y ][ x ]; runY = 1; } else { runY++; if ( runY == 5 ) { result += PENALTY_N1; } else if ( runY > 5 ) { result++; } } } } // 2*2 blocks of modules having same color for ( int y = 0; y < _size - 1; y++ ) { for ( int x = 0; x < _size - 1; x++ ) { boolean color = _modules[ y ][ x ]; if ( color == _modules[ y ][ x + 1 ] && color == _modules[ y + 1 ][ x ] && color == _modules[ y + 1 ][ x + 1 ] ) { result += PENALTY_N2; } } } // Finder-like pattern in rows for ( int y = 0; y < _size; y++ ) { for ( int x = 0, bits = 0; x < _size; x++ ) { bits = ( ( bits << 1 ) & 0x7FF ) | ( _modules[ y ][ x ] ? 1 : 0 ); if ( x >= 10 && ( bits == 0x05D || bits == 0x5D0 ) ) // Needs 11 bits accumulated { result += PENALTY_N3; } } } // Finder-like pattern in columns for ( int x = 0; x < _size; x++ ) { for ( int y = 0, bits = 0; y < _size; y++ ) { bits = ( ( bits << 1 ) & 0x7FF ) | ( _modules[ y ][ x ] ? 1 : 0 ); if ( y >= 10 && ( bits == 0x05D || bits == 0x5D0 ) ) // Needs 11 bits accumulated { result += PENALTY_N3; } } } // Balance of black and white modules int black = 0; for ( boolean[] row : _modules ) { for ( boolean color : row ) { if ( color ) { black++; } } } int total = _size * _size; // Find smallest k such that (45-5k)% <= dark/total <= (55+5k)% for ( int k = 0; black * 20 < ( 9 - k ) * total || black * 20 > ( 11 + k ) * total; k++ ) { result += PENALTY_N4; } return result; } }
34.411765
128
0.574786
b3e3155e27bbb44d674a0ce05dd3b0e89bf28d99
2,087
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.sdo.helper.classgen; import java.util.ArrayList; import java.util.List; import junit.textui.TestRunner; public class BaseTypeTestCases extends SDOClassGenTestCases { public BaseTypeTestCases(String name) { super(name); } public static void main(String[] args) { String[] arguments = { "-c", "org.eclipse.persistence.testing.sdo.helper.classgen.BaseTypeTestCases" }; TestRunner.main(arguments); } protected String getSchemaName() { return "./org/eclipse/persistence/testing/sdo/helper/xmlhelper/CustomerWithExtension.xsd"; } protected String getSourceFolder() { return "./baseTypes"; } protected String getControlSourceFolder() { return "./org/eclipse/persistence/testing/sdo/helper/classgen/baseTypes"; } protected List getControlFileNames() { ArrayList list = new ArrayList(); list.add("CustomerType.java"); list.add("CustomerTypeImpl.java"); list.add("CdnAddressType.java"); list.add("CdnAddressTypeImpl.java"); list.add("UsAddressType.java"); list.add("UsAddressTypeImpl.java"); list.add("AddressType.java"); list.add("AddressTypeImpl.java"); list.add("TestType.java"); list.add("TestTypeImpl.java"); return list; } }
35.982759
111
0.641112
c39b964c078204388397992bf7a2fce48d4b828b
2,231
package com.microprogram.grpc.client.nameresolver; import com.google.common.collect.ImmutableList; import io.grpc.Attributes; import io.grpc.EquivalentAddressGroup; import io.grpc.NameResolver; import java.util.Collection; import java.util.List; import static java.util.Objects.requireNonNull; /** * Copyright (C), 2019-2025, Orient Securities.Org * FileName: StaticNameResolver * Author: shenzhiwei@orientsec.com.cn * Description: A {@link NameResolver} that will always respond with a static set of target addresses. */ public class StaticNameResolver extends NameResolver { private final String authority; private final List<EquivalentAddressGroup> targets; /** * Creates a static name resolver with only a single target server. * * @param authority The authority this name resolver was created for. * @param target The target address of the server to use. */ public StaticNameResolver(final String authority, final EquivalentAddressGroup target) { this(authority, ImmutableList.of(requireNonNull(target, "target"))); } /** * Creates a static name resolver with multiple target servers. * * @param authority The authority this name resolver was created for. * @param targets The target addresses of the servers to use. */ public StaticNameResolver(final String authority, final Collection<EquivalentAddressGroup> targets) { this.authority = requireNonNull(authority, "authority"); if (requireNonNull(targets, "targets").isEmpty()) { throw new IllegalArgumentException("Must have at least one target"); } this.targets = ImmutableList.copyOf(targets); } @Override public String getServiceAuthority() { return this.authority; } @Override public void start(final Listener listener) { listener.onAddresses(this.targets, Attributes.EMPTY); } @Override public void refresh() { // Does nothing } @Override public void shutdown() { // Does nothing } @Override public String toString() { return "StaticNameResolver [authority=" + this.authority + ", targets=" + this.targets + "]"; } }
30.148649
105
0.695204
e07830c6d06ceadfb929e97619c2c0ce3268f07d
1,977
package org.toilelibre.libe.soundtransform.model.converted.sound.transform; import java.io.Serializable; import org.toilelibre.libe.soundtransform.model.converted.sound.Channel; import org.toilelibre.libe.soundtransform.model.converted.spectrum.FourierTransformHelper; import org.toilelibre.libe.soundtransform.model.converted.spectrum.Spectrum; import org.toilelibre.libe.soundtransform.model.logging.AbstractLogAware; public abstract class AbstractFrequencySoundTransform<T extends Serializable> extends AbstractLogAware<AbstractFrequencySoundTransform<T>> implements SoundTransform<Channel, Channel> { private static final double LOG_2 = Math.log (2); private static final int TWO = 2; private final FourierTransformHelper<T> fourierTransformHelper; public AbstractFrequencySoundTransform (final FourierTransformHelper<T> helper1) { this.fourierTransformHelper = helper1; } public abstract int getOffsetFromASimpleLoop (int i, double step); public abstract double getStep (double defaultValue); public abstract boolean isReverseNecessary (); public abstract boolean rawSpectrumPrefered (); public abstract AbstractWindowSoundTransform getWindowTransform (); public int getWindowLength (final double freqmax) { return (int) Math.pow (AbstractFrequencySoundTransform.TWO, Math.ceil (Math.log (freqmax) / AbstractFrequencySoundTransform.LOG_2)); } public abstract Channel initSound (Channel input); @Override public final Channel transform (final Channel sound) { return this.fourierTransformHelper.transform (this, sound); } public abstract Spectrum<T> transformFrequencies (Spectrum<T> fs, int offset, int powOf2NearestLength, int length, float soundLevelInDB); public abstract void transformFrequencies (double [][] spectrumAsDoubles, final float sampleRate, int offset, int powOf2NearestLength, int length, float soundLevelInDB); }
42.978261
184
0.778452
b003dfedfb06243e9d443dfb5d64f34bd5691ffd
2,337
package org.apereo.cas.support.saml.web.idp.metadata; import org.apereo.cas.support.saml.BaseSamlIdPConfigurationTests; import org.apereo.cas.support.saml.SamlIdPTestUtils; import org.apereo.cas.support.saml.services.SamlRegisteredService; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.TestPropertySource; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link SamlRegisteredServiceCachedMetadataEndpointTests}. * * @author Misagh Moayyed * @since 6.2.0 */ @Tag("SAMLMetadata") @TestPropertySource(properties = { "management.endpoints.web.exposure.include=*", "management.endpoint.samlIdPRegisteredServiceMetadataCache.enabled=true" }) public class SamlRegisteredServiceCachedMetadataEndpointTests extends BaseSamlIdPConfigurationTests { @Autowired @Qualifier("samlRegisteredServiceCachedMetadataEndpoint") private SamlRegisteredServiceCachedMetadataEndpoint endpoint; private SamlRegisteredService samlRegisteredService; @BeforeEach public void beforeEach() { this.samlRegisteredService = SamlIdPTestUtils.getSamlRegisteredService(); servicesManager.save(samlRegisteredService); } @Test public void verifyInvalidate() { endpoint.invalidate(samlRegisteredService.getServiceId()); endpoint.invalidate(StringUtils.EMPTY); } @Test public void verifyCachedMetadataObject() { val results = endpoint.getCachedMetadataObject(samlRegisteredService.getServiceId(), StringUtils.EMPTY); assertTrue(results.containsKey(samlRegisteredService.getServiceId())); } @Test public void verifyCachedService() { val results = endpoint.getCachedMetadataObject(String.valueOf(samlRegisteredService.getId()), StringUtils.EMPTY); assertTrue(results.containsKey(samlRegisteredService.getServiceId())); } @Test public void verifyBadService() { val results = endpoint.getCachedMetadataObject("bad-service-id", StringUtils.EMPTY); assertTrue(results.containsKey("error")); } }
35.409091
121
0.773214
199ec2e4fbc7d1f963bc5294b007505bce8168a9
645
package com.example.taxihelper.mvp.model; import com.example.taxihelper.mvp.contract.OrderDetailContract; import com.example.taxihelper.mvp.entity.OrderDetailInfo; import com.example.taxihelper.mvp.model.base.BaseModelImpl; import javax.inject.Inject; import rx.Observable; /** * Created by Raven on 2017/8/26. */ public class OrderDetailModelImpl extends BaseModelImpl implements OrderDetailContract.Model { @Inject public OrderDetailModelImpl() { } @Override public Observable<OrderDetailInfo> getOrderDetailInfo(String orderId) { return filterStatus(getApi().getOrderDetail(accessToken,orderId)); } }
24.807692
94
0.773643
3159eedf133e82f6f0fa6befce9772c4a267a00a
258
package com.upai.manageallactivity.first; import android.content.Context; import com.upai.manageallactivity.second.SecondActivity; class FirstModel { void switchToSecondActivity(Context context){ SecondActivity.actionStart(context); } }
18.428571
56
0.775194
c74a0faf9da270cdb3be33fe5b83741882be5517
1,558
package com.zerowater.environment.ui.dialog; import android.content.Context; import android.os.Bundle; import android.view.WindowManager; import android.widget.ProgressBar; import com.zerowater.environment.R; import com.zerowater.environment.ui.base.BaseDialog; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by YoungSoo Kim on 2017-02-09. * 4ground Ltd * byzerowater@gmail.com * 로딩 다이얼로그 */ public class LoadingDialog extends BaseDialog { /** * 로딩 ProgressBar */ @BindView(R.id.pb_loading) ProgressBar mPbLoading; /** * 로딩 다이얼로그 * * @param context Context */ public LoadingDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getWindow() != null) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } setContentView(R.layout.dialog_loading); ButterKnife.bind(this); setCancelable(false); } @Override public void show() { try { super.show(); mPbLoading.setIndeterminate(true); } catch (Exception e) { e.printStackTrace(); } } @Override public void dismiss() { try { super.dismiss(); if (mPbLoading != null) { mPbLoading.setIndeterminate(false); } } catch (Exception e) { e.printStackTrace(); } } }
22.257143
79
0.609756
e5317062550a5e32bdd5e150e424c1f21d253a5e
4,104
package be.fgov.caamihziv.services.quickmon.interfaces.api.healthChecks.lucene; import be.fgov.caamihziv.services.quickmon.domain.healthchecks.HealthCheck; import org.springframework.beans.BeanUtils; import org.springframework.util.ReflectionUtils; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.function.Predicate; /** * Created by gs on 17.05.17. */ public class HealthChecksQueryNodeInterpreter { public Predicate<HealthCheck> toPredicate(QueryNode queryNode) { if (queryNode.isEmpty()) { return hcs -> true; } if (queryNode.isTerm()) { return term(queryNode.isDefaultField(), queryNode.getPrefix(), queryNode.getField(), queryNode.getTerm()); } else { switch (queryNode.getOperator()) { case OR: if (queryNode.getLeft() != null && queryNode.getRight() != null) { return toPredicate(queryNode.getLeft()).or(toPredicate(queryNode.getRight())); } else if (queryNode.getLeft() != null){ // We basically have a single predicate with an OR operator, which is ugly, but happens return toPredicate(queryNode.getLeft()); } else { return toPredicate(queryNode.getRight()); } case AND: return toPredicate(queryNode.getLeft()).and(toPredicate(queryNode.getRight())); case NOT: if (queryNode.getLeft() != null) { return toPredicate(queryNode.getLeft()).negate(); } else { return toPredicate(queryNode.getRight()).negate(); } default: throw new IllegalArgumentException("Unknown operator " + queryNode.getOperator()); } } } private Predicate<HealthCheck> term(boolean defaultField, String prefix, String field, String term) { // Prefix boolean negate = false; if ("-".equals(prefix)) { negate = true; } // Default field if (defaultField) { return negate ? predicateOfField("name", term).negate() : predicateOfField("name", term); } else { return negate ? predicateOfField(field, term).negate() : predicateOfField(field, term); } //TODO - Manage multivalued terms } private Predicate<HealthCheck> predicateOfField(String field, String term) { PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(HealthCheck.class, field); if (propertyDescriptor == null) { // The field is not found, so we just do as if everything matches // TODO - Maybe we could log that :) return hc -> true; } else if (String.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { if (term.contains("*")) { // We have a regex here return hc -> invoke(hc, propertyDescriptor.getReadMethod(), String.class).matches(term.replace("*", ".*")); } else { return hc -> invoke(hc, propertyDescriptor.getReadMethod(), String.class).contains(term); } } else { if (term.contains("*")) { return hc -> invoke(hc, propertyDescriptor.getReadMethod(), Object.class).toString().matches(".*" + term.replace("*", ".*") + ".*"); } else { return hc -> invoke(hc, propertyDescriptor.getReadMethod(), Object.class).toString().contains(term); } } } private <T> T invoke (Object target, Method method, Class<T> returnType) { try { return (T) method.invoke(target); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalArgumentException("Error invoking method " + method, e); } } }
41.04
148
0.583821
b5ae7ef952077f799da1139b436d32040f231cf0
1,295
package br.eti.arthurgregorio.library.domain.entities.administration; import br.eti.arthurgregorio.library.domain.entities.PersistentEntity; import lombok.*; import org.hibernate.envers.Audited; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import static br.eti.arthurgregorio.library.infrastructure.jpa.DefaultSchemes.ADMINISTRATION; /** * @author Arthur Gregorio * * @version 1.0.0 * @since 1.0.0, 09/02/2020 */ @Entity @Audited @ToString @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @Table(name = "grants", schema = ADMINISTRATION) public class Grant extends PersistentEntity { @Getter @Setter @ManyToOne(optional = false) @NotNull(message = "grant.null-authority") @JoinColumn(name = "id_authority", nullable = false) private Authority authority; @Getter @Setter @ManyToOne(optional = false) @NotNull(message = "grant.null-user") @JoinColumn(name = "id_user", nullable = false) private User user; /** * * @param user * @param authority */ public Grant(User user, Authority authority) { this.user = user; this.authority = authority; } }
24.903846
93
0.716602
b334cacfeee864e471cfd33161e5161fe4e5a87e
1,660
package com.example.project.configuration.security.service; import java.util.List; import com.example.project.domain.entities.SiteRole; import com.example.project.domain.entities.SiteUser; import com.example.project.service.SiteUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; @Component public class AuthProviderService implements AuthenticationProvider { @Autowired private SiteUserService userService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); SiteUser validUser = userService.ValidateUser(name, password); if (validUser != null) { List<SiteRole> roles = userService.rolesFrom(validUser); return new UsernamePasswordAuthenticationToken(validUser.getEmail(), // validUser.getPassword(), roles); } else { throw new UsernameNotFoundException("Login e/ou Senha inválidos."); } } @Override public boolean supports(Class<?> auth) { return auth.equals(UsernamePasswordAuthenticationToken.class); } }
37.727273
102
0.768675
c1e5199cf623ffd79ad4b71d8e929c5131fe3f76
809
package ru.kontur.vostok.hercules.meta.auth.blacklist; import ru.kontur.vostok.hercules.curator.CuratorClient; import java.util.List; /** * @author Gregory Koshelev */ public class BlacklistRepository { private final CuratorClient curatorClient; public BlacklistRepository(CuratorClient curatorClient) { this.curatorClient = curatorClient; } public List<String> list() throws Exception { List<String> entries = curatorClient.children(zPrefix); return entries; } public void add(String key) throws Exception { curatorClient.createIfAbsent(zPrefix + "/" + key); } public void remove(String key) throws Exception { curatorClient.delete(zPrefix + "/" + key); } private static String zPrefix = "/hercules/auth/blacklist"; }
25.28125
63
0.698393
793d89535bd6ef354c3db4f70edd8ded99b5e3a3
1,809
package com.taoerxue.app.qo; /** * Created by lizhihui on 2017-03-27 10:25. */ public class CourseQuery { private String order; private Integer parentTypeId; private Integer typeId; private String address; private Integer cityId; private Integer areaId; private Double lng; private Double lat; private Boolean display; private String like; public String getLike() { return like; } public void setLike(String like) { this.like = like; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Boolean getDisplay() { return display; } public void setDisplay(Boolean display) { this.display = display; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getCityId() { return cityId; } public void setCityId(Integer cityId) { this.cityId = cityId; } public Integer getAreaId() { return areaId; } public void setAreaId(Integer areaId) { this.areaId = areaId; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public Integer getParentTypeId() { return parentTypeId; } public void setParentTypeId(Integer parentTypeId) { this.parentTypeId = parentTypeId; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } }
18.459184
55
0.593698
e3da559290c504ca7669c7c1c52dc8c6fa8585a9
3,303
package br.com.fernando.chapter12_javaTransaction.part04_transactionIsolation; public class TransactionIsolation01 { // JDBC Transaction Isolation Levels // // Problems: // // Dirty reads: A dirty read occurs when a transaction is allowed to read data from a row that has been modified by another running transaction and not yet committed. // Occurs when a transaction reads uncommitted data. In other words, the transaction is allowed to read the data that has been changed by other transactions and is not yet committed. // // Non-repeatable reads: A non-repeatable read occurs, when during the course of a transaction, a row is retrieved twice and the values within the row differ between reads. // It occurs because after the first transaction reads the data in the row, other transactions are allowed to change this data. // // Phantom reads: A phantom read occurs when, in the course of a transaction, new rows are added or removed by another transaction to the records being read. // // Not all database vendors support all transaction isolation levels available in the JDBC API. // The Enterprise Server permits specifying any isolation level your database supports. // The following table defines transaction isolation levels. // // // Database and isolation levels // // Apart from MySQL (which uses REPEATABLE_READ), the default isolation level of most relational database systems is READ_COMMITTED. // All databases allow you to set the default transaction isolation level. // // Typically, the database is shared among multiple applications and each one has its own specific transaction requirements. // For most transactions, the READ_COMMITTED isolation level is the best choice and we should only override it for specific business cases. // // * Choosing a transaction isolation level doesn't affect the locks that are acquired to protect data modifications. * // // A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. // For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions. // // Conversely, a higher isolation level reduces the types of concurrency effects that users might encounter, but requires more system resources and increases the chances that one transaction will block another. // // Choosing the appropriate isolation level depends on balancing the data integrity requirements of the application against the overhead of each isolation level. // // The highest isolation level, serializable, guarantees that a transaction will retrieve exactly the same data every time it repeats a read operation, but it does this by performing a level of locking that is likely to impact other users in multi-user systems. // // The lowest isolation level, read uncommitted, can retrieve data that has been modified but not committed by other transactions. // // All concurrency side effects can happen in read uncommitted, but there's no read locking or versioning, so overhead is minimized. }
73.4
265
0.759612
c83d700aa4f597a2e2ce46f4b0fe8807b9230606
3,624
package net.pryden.accounts.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; /** * Represents the totals of the various columns computed from the month's data. It is never * serialized -- instead the values are recomputed when necessary. */ @AutoValue public abstract class ComputedTotals { /** Total of all "Local Congregation Expenses" receipts. */ @JsonProperty("total-congregation-receipts") public abstract Money totalCongregationReceipts(); /** Total of all "Worldwide Work" receipts. */ @JsonProperty("total-worldwide-receipts") public abstract Money totalWorldwideReceipts(); /** Total value of money received as receipts over the month. */ @JsonProperty("total-receipts-in") public abstract Money totalReceiptsIn(); /** Total value of money deposited or otherwise spent out of receipts over the month. */ @JsonProperty("total-receipts-out") public abstract Money totalReceiptsOut(); /** Total value of money deposited into the checking account over the month. */ @JsonProperty("total-checking-in") public abstract Money totalCheckingIn(); /** Total value of money spent out of the checking account over the month. */ @JsonProperty("total-checking-out") public abstract Money totalCheckingOut(); /** * Total value of money earmarked for the Worldwide Work and transferred to the branch. If * procedures are being followed correctly, this should always be equal to * {@link #totalWorldwideReceipts()}. */ @JsonProperty("total-worldwide-transfer") public abstract Money totalWorldwideTransfer(); /** * Total value of congregation expenses (that is, transactions with * {@link TransactionCategory#EXPENSE}) throughout the month. */ @JsonProperty("total-congregation-expenses") public abstract Money totalCongregationExpenses(); /** * Outstanding balance of receipts collected but not deposited. At the end of the month this * should always be zero. */ @JsonProperty("receipts-outstanding-balance") public abstract Money receiptsOutstandingBalance(); /** Checking account balance at the end of the month. */ @JsonProperty("checking-balance") public abstract Money checkingBalance(); /** Sum of all balances across all accounts (receipts and checking). */ @JsonProperty("total-of-all-balances") public abstract Money totalOfAllBalances(); /** Returns a new {@link Builder} instance. */ public static Builder builder() { return new AutoValue_ComputedTotals.Builder(); } /** Builder for {@link ComputedTotals} instances. */ @AutoValue.Builder public static abstract class Builder { Builder() {} public abstract Builder setTotalCongregationReceipts(Money totalCongregationReceipts); public abstract Builder setTotalWorldwideReceipts(Money totalWorldwideReceipts); public abstract Builder setTotalReceiptsIn(Money totalReceiptsIn); public abstract Builder setTotalReceiptsOut(Money totalReceiptsOut); public abstract Builder setTotalCheckingIn(Money totalCheckingIn); public abstract Builder setTotalCheckingOut(Money totalCheckingOut); public abstract Builder setTotalWorldwideTransfer(Money totalWorldwideTransfer); public abstract Builder setTotalCongregationExpenses(Money totalCongregationExpenses); public abstract Builder setReceiptsOutstandingBalance(Money receiptsOutstandingBalance); public abstract Builder setCheckingBalance(Money checkingBalance); public abstract Builder setTotalOfAllBalances(Money totalOfAllBalances); public abstract ComputedTotals build(); } }
35.881188
94
0.762969
d35751480540a7745d932e399537313603f3efe3
2,993
package org.rookit.dm.bistream; import org.apache.commons.text.RandomStringGenerator; import org.junit.jupiter.api.Test; import org.rookit.test.AbstractUnitTest; import org.rookit.test.categories.FastTest; import org.rookit.test.categories.UnitTest; import org.rookit.test.mixin.ByteArrayMixin; import org.rookit.test.preconditions.TestPreconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("javadoc") @FastTest @UnitTest public class FileBiStreamTest extends AbstractUnitTest<FileBiStream> implements ByteArrayMixin { private static final short FILENAME_LENGTH = 20; private static final int CAPACITY = 128; private static final RandomStringGenerator RANDOM_STRINGS = new RandomStringGenerator.Builder() .build(); private Path tempFile; @SuppressWarnings("CastToConcreteClass") @Override public FileBiStream createTestResource() { try { this.tempFile = this.temporaryFolder.createFile(RANDOM_STRINGS.generate(FILENAME_LENGTH)).toPath(); return new FileBiStream(this.tempFile); } catch (final IOException e) { return VALIDATOR.handleException().inputOutputException(e); } } @Test public final void testClear() throws IOException { Files.write(this.tempFile, createRandomArray(CAPACITY)); this.testResource.clear(); assertThat(Files.notExists(this.tempFile)) .as("The remaining size") .isTrue(); } @Test public final void testRead() throws IOException { TestPreconditions.assure().is(this.testResource.isEmpty(), "The test resource must be empty"); final byte[] expectedContent = createRandomArray(CAPACITY / 2); final byte[] actualContent = new byte[CAPACITY / 2]; Files.write(this.tempFile, expectedContent); try (final InputStream input = this.testResource.readFrom()) { final int readBytes = input.read(actualContent); assertThat(readBytes) .as("The number of bytes read") .isPositive(); assertThat(actualContent) .as("The content read") .containsExactly(expectedContent); } } @Test public final void testWrite() throws IOException { TestPreconditions.assure().is(this.testResource.isEmpty(), "The test resource must be empty"); final byte[] expectedContent = createRandomArray(CAPACITY / 2); try (final OutputStream output = this.testResource.writeTo()) { output.write(expectedContent); } final byte[] actualContent = Files.readAllBytes(this.tempFile); assertThat(actualContent) .as("The content writen") .containsExactly(expectedContent); } }
34.011364
111
0.676579
ac5b25f973403e47a7a40e3a7a66a7854fee700f
1,176
/* * JGCS - Group Communication Service. * Copyright (C) 2006 Nuno Carvalho, Universidade de Lisboa * * jgcs@lasige.di.fc.ul.pt * * Departamento de Informatica, Universidade de Lisboa * Bloco C6, Faculdade de Ciências, Campo Grande, 1749-016 Lisboa, Portugal. * * See COPYING for licensing details. */ package net.sf.jgcs; /** * * This class defines a UnsupportedServiceException. * * @author <a href="mailto:nunomrc@di.fc.ul.pt">Nuno Carvalho</a> * @version 1.0 */ public class UnsupportedServiceException extends JGCSException { private static final long serialVersionUID = -1665250751731240056L; /** * * Creates a new UnsupportedServiceException. */ public UnsupportedServiceException() { super(); } /** * * Creates a new UnsupportedServiceException. * @param message the error message. */ public UnsupportedServiceException(String message) { super(message); } /** * * Creates a new UnsupportedServiceException. * @param message the error message. * @param cause the throwable that caused this exception. */ public UnsupportedServiceException(String message, Throwable cause) { super(message, cause); } }
21.777778
76
0.715136
9dc7a4334911f8e0c9cd05e944132de4c47bd0d7
16,225
package com.example.bot.spring.covidcases; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.linecorp.bot.client.LineBlobClient; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.model.ReplyMessage; import com.linecorp.bot.model.action.MessageAction; import com.linecorp.bot.model.action.PostbackAction; import com.linecorp.bot.model.action.URIAction; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.PostbackEvent; import com.linecorp.bot.model.event.message.TextMessageContent; import com.linecorp.bot.model.message.Message; import com.linecorp.bot.model.message.TemplateMessage; import com.linecorp.bot.model.message.TextMessage; import com.linecorp.bot.model.message.template.*; import com.linecorp.bot.model.response.BotApiResponse; import com.linecorp.bot.spring.boot.annotation.EventMapping; import com.linecorp.bot.spring.boot.annotation.LineMessageHandler; import lombok.NonNull; import lombok.Value; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.ExecutionException; import static java.util.Collections.singletonList; @Slf4j @LineMessageHandler public class CovidCasesController { @Autowired private LineMessagingClient lineMessagingClient; @Autowired private LineBlobClient lineBlobClient; @EventMapping public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception { TextMessageContent message = event.getMessage(); handleTextContent(event.getReplyToken(), message); } public enum City { TPE_NTPC_KEL("臺北、新北、基隆、宜蘭地區", new String[]{"臺北市", "新北市", "基隆市", "宜蘭縣"}, 0), TYN_HSZ_ZMI("桃園、新竹、苗栗地區",new String[]{"桃園市", "新竹縣", "新竹市", "苗栗縣"}, 1), TXG_CHW_NTC("臺中、彰化、南投地區",new String[]{"臺中市", "彰化縣", "南投縣"}, 2), YUN_CYI_TNN("雲林、嘉義、臺南地區",new String[]{"雲林縣","嘉義縣", "嘉義市", "臺南市"}, 3), KHH_PIF("高雄、屏東地區",new String[]{"高雄市","屏東縣"}, 4), HUN_TTT("花蓮、臺東地區",new String[]{"花蓮縣", "臺東縣"}, 5), PEH_KNH_LNN("金門、連江、澎湖地區",new String[]{"澎湖縣","金門縣", "連江縣"}, 6); City(String chinese, String[] cityNames, int code){ this.chinese = chinese; this.cityNames = cityNames; this.code = code; } private final String chinese; private final String[] cityNames; private int code; public static City getCity(int i){ for(City city : values()){ if(city.getCode() == i) { return city; } } return null; } public String getChinese(){ return this.chinese; } public String[] getCityNames() { return this.cityNames; } public int getCode() { return this.code; } } @EventMapping public void handlePostbackEvent(PostbackEvent event) throws Exception { String replyToken = event.getReplyToken(); String data = event.getPostbackContent().getData(); String[] dataList = data.split("_"); Integer cityCode = Integer.parseInt(dataList[1]); String[] citiesArray = City.getCity(cityCode).getCityNames(); if (data.startsWith("Case_")){ for (int index =0; index < citiesArray.length; index++){ citiesArray[index] = citiesArray[index].replace("臺", "台"); } String respond = this.getCasesByCities(new ArrayList<String>(Arrays.asList(citiesArray))); this.replyText(replyToken, respond); } else if (data.startsWith("Vaccination_")){ String respond = this.getVaccRateByCities(new ArrayList<String>(Arrays.asList(citiesArray))); this.replyText(replyToken, respond); } else { this.replyText(replyToken,"Got postback data "+ event.getPostbackContent().getData()); } } private void handleTextContent(String replyToken, TextMessageContent content) throws Exception { final String text = content.getText(); log.info("Got text message from replyToken:{}: text:{} emojis:{}", replyToken, text, content.getEmojis()); switch (text){ case "最新消息": { URI imageUrl = createUri("/static/buttons/cdc_logo.jpg"); ButtonsTemplate buttonsTemplate = new ButtonsTemplate( imageUrl, "最新消息", "衛福部疾管署最新資訊", Arrays.asList( new URIAction("新聞稿", URI.create("https://www.cdc.gov.tw/Bulletin/List/MmgtpeidAR5Ooai4-fgHzQ"), null), new URIAction("澄清專區", URI.create("https://www.cdc.gov.tw/Bulletin/List/MmgtpeidAR5Ooai4-fgHzQ"), null) )); TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate); this.reply(replyToken, templateMessage); break; } case "查疫情": case "查台灣疫情": case "查臺灣疫情": { ArrayList<CarouselColumn> carouselColumns = new ArrayList<>(); for(int i=0; i<7; i++){ URI imageUrl = createUri("/static/buttons/map-"+ i +".png"); carouselColumns.add(new CarouselColumn(imageUrl, City.getCity(i).getChinese(), "查詢案例數,疫苗接種數", Arrays.asList( new PostbackAction("累積案例數", "Case_" + i, City.getCity(i).getChinese() + "累積案例數"), new PostbackAction("疫苗接種率", "Vaccination_" + i, City.getCity(i).getChinese() + "疫苗接種率") ))); } CarouselTemplate carouselTemplate = new CarouselTemplate(carouselColumns); TemplateMessage templateMessage = new TemplateMessage("Carousel alt text", carouselTemplate); this.reply(replyToken, templateMessage); break; } // case "查詢採檢醫院": { // String replyMsg = ""; // // TODO // ArrayList<String> response = readHospitalCsv("https://od.cdc.gov.tw/icb/指定採檢醫院清單.csv", City.TPE_NTPC_KEL.getCityNames()); // for (int i=0; i<response.size(); i++){ // replyMsg = replyMsg + "\n" + response.get(i) ; // } // this.replyText(replyToken,replyMsg); // break; // } case "查本日":{ String link = "https://od.cdc.gov.tw/eic/covid19/covid19_tw_stats.csv"; String response = readCsv(link); this.replyText(replyToken,response); break; } case "help": case "Help": case "HELP":{ String response = "\uD83D\uDC47COVID資訊+ 指令教學\uD83D\uDC47\n\n" + "1. 輸入【查本日】取得本日疫情最新,[確診數], [死亡數], [昨日新增] ... 等\n\n" + "2. 輸入【查疫情】顯示各縣市疫情狀況,包括縣市 [累積總病例數] 及 [疫苗接種率]\n\n" + "3. 輸入【最新消息】取得衛福部疾管署最新資訊\n\n" + "4. 輸入【HELP】查詢所有指令"; this.replyText(replyToken,response); break; } } } private ArrayList<Case> jsonParse(String input) throws JsonProcessingException { String reply = input; ObjectMapper mapper = new ObjectMapper(); ArrayList<Case> result = mapper.readValue(reply, new TypeReference<ArrayList<Case>>(){}); return result; } private String readCsv(String link) throws Exception{ URL url = new URL(link); HttpURLConnection http = (HttpURLConnection)url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String inputLine; String response = "⚠️【本日資訊】⚠️"; //read the first line String firstLine = in.readLine(); String titles[] = firstLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); while((inputLine=in.readLine())!=null){ String item[] = inputLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); for (int i=0; i<item.length; i++){ String data = item[i].trim().replace("\"",""); response = response + "\n"+ titles[i] + ": " + data + " 例" ; } } in.close(); http.disconnect(); return response; } private ArrayList<String> readHospitalCsv(String link, String[] cities) throws Exception{ URL url = new URL(link); HttpURLConnection http = (HttpURLConnection)url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream())); String line = reader.readLine(); ArrayList<String> response = new ArrayList<>(); while((line=reader.readLine())!=null){ String item[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); String cityName= item[2].trim(); if (Arrays.asList(cities).contains(cityName)){ } String name = item[4].trim(); String address= item[5].trim(); response.add(cityName + "-" + name + " 地址: " + address); } reader.close(); http.disconnect(); return response; } private String getCasesByCities(ArrayList<String> cities) throws Exception{ ArrayList<Integer> cases = new ArrayList<>(); for(int i=0; i < cities.size(); i++){ // data: 5001 cases data String response = queryCityStatus(cities.get(i),"5001"); ArrayList<Case> totalCase = jsonParse(response.toString()); cases.add(totalCase.size()); } String respond ="\uD83E\uDDA0【各縣市累積病例數】"; for(int j=0; j < cases.size(); j++){ respond = respond + "\n" + cities.get(j) + ": " + cases.get(j) + " 例"; } return respond; } private String getVaccRateByCities(ArrayList<String> cities) throws Exception{ ArrayList<String> cityRateList = new ArrayList<>(); String date = ""; for(int i=0; i < cities.size(); i++){ // data: 2001 >> vaccination data String response = queryCityStatus(cities.get(i),"2001"); // only need the newest data (the first element) JSONArray jsonArray = new JSONArray(response); if (jsonArray != null){ JSONObject obj = jsonArray.getJSONObject(0); date = obj.get("a01").toString(); String city = obj.get("a02").toString(); String vacciRate = obj.get("a06").toString(); cityRateList.add(city + ": " + vacciRate + " % "); } } String response ="\uD83D\uDC89【各縣市疫苗覆蓋率】\n - 截至" + date; for (int j=0; j < cityRateList.size(); j++){ response = response +"\n" + cityRateList.get(j); } return response; } private String getResponseByHttpPost(String link, String data) throws Exception { URL url = new URL(link); getTrust(); HttpURLConnection http = (HttpURLConnection)url.openConnection(); http.setRequestMethod("POST"); http.setDoOutput(true); http.setRequestProperty("Content-Type", "application/json"); byte[] out = data.getBytes(StandardCharsets.UTF_8); OutputStream stream = http.getOutputStream(); stream.write(out); log.info("Post respond code: "+ http.getResponseCode() + " " + http.getResponseMessage()); BufferedReader in = new BufferedReader( new InputStreamReader(http.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); http.disconnect(); return response.toString(); } private String queryCityStatus(String city, String queryData) throws Exception { String link ="https://covid-19.nchc.org.tw/api/covid19"; String data = "{\"CK\":\"covid-19@nchc.org.tw\", \"querydata\":\""+queryData+"\", \"limited\":\"" + city + "\"}"; String response; response = getResponseByHttpPost(link,data); return response; } private static void getTrust() { try { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } private void reply(@NonNull String replyToken, @NonNull Message message) { reply(replyToken, singletonList(message)); } private void reply(@NonNull String replyToken, @NonNull List<Message> messages) { reply(replyToken, messages, false); } private void reply(@NonNull String replyToken, @NonNull List<Message> messages, boolean notificationDisabled) { try { BotApiResponse apiResponse = lineMessagingClient .replyMessage(new ReplyMessage(replyToken, messages, notificationDisabled)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void replyText(@NonNull String replyToken, @NonNull String message) { if (replyToken.isEmpty()) { throw new IllegalArgumentException("replyToken must not be empty"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2) + "……"; } this.reply(replyToken, new TextMessage(message)); } private static URI createUri(String path) { return ServletUriComponentsBuilder.fromCurrentContextPath() .scheme("https") .path(path).build() .toUri(); } private static DownloadedContent createTempFile(String ext) { String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID() + '.' + ext; Path tempFile = CovidCasesApplication.downloadedContentDir.resolve(fileName); tempFile.toFile().deleteOnExit(); return new DownloadedContent( tempFile, createUri("/downloaded/" + tempFile.getFileName())); } @Value private static class DownloadedContent { Path path; URI uri; } }
39.285714
139
0.580832
fe9b6350ee6348aacac201d508803ff932fb1e2d
3,244
/* * Compile: javac -sourcepath src -d target src/playground/concurrency/SemaphoreDemo.java * Run: java -cp target playground.concurrency.SemaphoreDemo */ package playground.concurrency; import java.util.concurrent.Semaphore; /** * An example of using the {@code java.util.concurrent.Semaphore} class. * <p> * Example output: * * <pre> Starting thread - A Acquiring permit - A Permit acquired - A Starting thread - B Acquiring permit - B Share value increase to 6 - A Share value increase to 7 - A Share value increase to 8 - A Share value increase to 9 - A Share value increase to 10 - A Releasing permit - A Stopping thread - A Permit acquired - B Share value decreased to 9 - B Share value decreased to 8 - B Share value decreased to 7 - B Share value decreased to 6 - B Share value decreased to 5 - B Releasing permit - B Stopping thread - B * </pre> */ public class SemaphoreDemo { public static void main(String[] args) { Semaphore sem = new Semaphore(1); new IncThread(sem, "A"); new DecThread(sem, "B"); } } /** * This is an example shared resource */ class Shared { static int value = 5; private Shared() { // simply hides it from the world } } /** * Abstract worker thread to reduce code duplication */ abstract class WorkerThread implements Runnable { protected Semaphore semaphore; protected String threadName; protected WorkerThread(Semaphore sem, String threadName) { super(); semaphore = sem; this.threadName = threadName; new Thread(null, this, threadName).start(); } protected abstract void doWork(); public void run() { System.out.println("Starting thread - " + threadName); System.out.println("Acquiring permit - " + threadName); try { semaphore.acquire(); } catch (InterruptedException e) { System.out.println(String.format("Thread %s interrupted", threadName)); } System.out.println("Permit acquired - " + threadName); doWork(); System.out.println("Releasing permit - " + threadName); semaphore.release(); System.out.println("Stopping thread - " + threadName); } } /** * Worker thread that will increase the value of the shared resource. **/ class IncThread extends WorkerThread { public IncThread(Semaphore sem, String threadName) { super(sem, threadName); } @Override protected void doWork() { for (int i = 0; i < 5; i++) { Shared.value++; try { Thread.sleep(200); // to prove that it the DecThread doesn't get a timeslice } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Share value increase to " + Shared.value + " - " + threadName); } } } /** * Worker thread that will decrease the value of the shared resource. **/ class DecThread extends WorkerThread { public DecThread(Semaphore sem, String threadName) { super(sem, threadName); } @Override protected void doWork() { for (int i = 0; i < 5; i++) { Shared.value--; try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Share value decreased to " + Shared.value + " - " + threadName); } } } // jedit settings :elasticTabstops=true:encoding=UTF-8:
22.068027
89
0.689889
550d834608b5960fafd30558447a8da9152ac236
11,542
package org.jaudiotagger.tag.id3.framebody; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.tag.TagOptionSingleton; import org.jaudiotagger.tag.id3.ID3v24Frames; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; /** * Test TPOSFrameBody */ public class FrameBodyTPOSTest extends AbstractTestCase { public static FrameBodyTPOS getInitialisedBody() { FrameBodyTPOS fb = new FrameBodyTPOS(); fb.setDiscNo(1); fb.setDiscTotal(11); return fb; } public void testCreateFrameBodyStringConstructor() { TagOptionSingleton.getInstance().setPadNumbers(false); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, "1/11"); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(11,fb.getDiscTotal().intValue()); assertEquals("1/11", fb.getText()); } public void testCreateFrameBodyIntegerConstructor() { TagOptionSingleton.getInstance().setPadNumbers(false); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, 1,11); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(11,fb.getDiscTotal().intValue()); assertEquals("1/11", fb.getText()); } public void testCreateFrameBodyEmptyConstructor() { TagOptionSingleton.getInstance().setPadNumbers(false); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(); fb.setDiscNo(1); fb.setDiscTotal(11); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals("1/11", fb.getText()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(11,fb.getDiscTotal().intValue()); } public void testCreateFrameBodyDiscOnly() { TagOptionSingleton.getInstance().setPadNumbers(false); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(); fb.setDiscNo(1); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals("1", fb.getText()); assertEquals(1,fb.getDiscNo().intValue()); assertNull(fb.getDiscTotal()); } public void testCreateFrameBodyTotalOnly() { Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(); fb.setDiscTotal(11); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals("0/11", fb.getText()); assertNull(fb.getDiscNo()); assertEquals(11,fb.getDiscTotal().intValue()); } public void testCreateFrameBodyWithPadding() { TagOptionSingleton.getInstance().setPadNumbers(true); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, 1,11); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(11,fb.getDiscTotal().intValue()); assertEquals("01/11", fb.getText()); } public void testCreateFrameBodyWithPaddingTwo() { TagOptionSingleton.getInstance().setPadNumbers(true); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, 3,7); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(3,fb.getDiscNo().intValue()); assertEquals(7,fb.getDiscTotal().intValue()); assertEquals("03/07", fb.getText()); } // specify the value as a string with no padding. getText should still return with padding public void testCreateFrameBodyWithPaddedRawTextCount() { TagOptionSingleton.getInstance().setPadNumbers(false); FrameBodyTPOS fb = createFrameBodyAndAssertNumericValuesAndRawValueRetained("01/11", 1, 11); assertEquals("01",fb.getDiscNoAsText()); assertEquals("11",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithUnpaddedRawTextCount() { TagOptionSingleton.getInstance().setPadNumbers(false); FrameBodyTPOS fb = createFrameBodyAndAssertNumericValuesAndRawValueRetained("1/11", 1, 11); assertEquals("1",fb.getDiscNoAsText()); assertEquals("11",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithPaddedRawTextTotal() { TagOptionSingleton.getInstance().setPadNumbers(false); FrameBodyTPOS fb = createFrameBodyAndAssertNumericValuesAndRawValueRetained("1/03", 1, 3); assertEquals("1",fb.getDiscNoAsText()); assertEquals("03",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithPaddedRawTextTotal2() { TagOptionSingleton.getInstance().setPadNumbers(false); FrameBodyTPOS fb = createFrameBodyAndAssertNumericValuesAndRawValueRetained("01/03", 1, 3); assertEquals("01",fb.getDiscNoAsText()); assertEquals("03",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithUnpaddedRawTextTotal() { TagOptionSingleton.getInstance().setPadNumbers(false); FrameBodyTPOS fb = createFrameBodyAndAssertNumericValuesAndRawValueRetained("1/3", 1, 3); assertEquals("1",fb.getDiscNoAsText()); assertEquals("3",fb.getDiscTotalAsText()); } private FrameBodyTPOS createFrameBodyAndAssertNumericValuesAndRawValueRetained(String rawText, int expectedCount, int expectedTotal) { Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, rawText); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(expectedCount,fb.getDiscNo().intValue()); assertEquals(expectedTotal,fb.getDiscTotal().intValue()); assertEquals(rawText, fb.getText()); return fb; } public void testCreateFrameBodyWithPaddedRawTextCountIsPadded() { TagOptionSingleton.getInstance().setPadNumbers(true); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, "01/11"); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(11,fb.getDiscTotal().intValue()); assertEquals("01/11", fb.getText()); assertEquals("01",fb.getDiscNoAsText()); assertEquals("11",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithUnpaddedRawTextCountIsPadded() { TagOptionSingleton.getInstance().setPadNumbers(true); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, "1/11"); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(11,fb.getDiscTotal().intValue()); assertEquals("01/11", fb.getText()); assertEquals("01",fb.getDiscNoAsText()); assertEquals("11",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithPaddedRawTextTotalIsPadded() { TagOptionSingleton.getInstance().setPadNumbers(true); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, "1/03"); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(3,fb.getDiscTotal().intValue()); assertEquals("01/03", fb.getText()); assertEquals("01",fb.getDiscNoAsText()); assertEquals("03",fb.getDiscTotalAsText()); } public void testCreateFrameBodyWithPaddedRawTextTotal2IsPadded() { TagOptionSingleton.getInstance().setPadNumbers(true); createFrameBodyAndAssertNumericValuesAndRawValueRetained("01/03", 1, 3); } public void testCreateFrameBodyWithUnpaddedRawTextTotalIsPadded() { TagOptionSingleton.getInstance().setPadNumbers(true); Exception exceptionCaught = null; FrameBodyTPOS fb = null; try { fb = new FrameBodyTPOS(TextEncoding.ISO_8859_1, "1/3"); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertEquals(ID3v24Frames.FRAME_ID_SET, fb.getIdentifier()); assertEquals(TextEncoding.ISO_8859_1, fb.getTextEncoding()); assertEquals(1,fb.getDiscNo().intValue()); assertEquals(3,fb.getDiscTotal().intValue()); assertEquals("01/03", fb.getText()); assertEquals("01",fb.getDiscNoAsText()); assertEquals("03",fb.getDiscTotalAsText()); } }
32.240223
135
0.633686
b0674d6dc4ab401dbf5453d45b86ed9cbc07cc29
3,192
package de.sec.dns.test; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import de.sec.dns.dataset.DataSetHeader; import de.sec.dns.util.Util; /** * An implementation of an hadoop {@link Tool} used to generate the confusion * matrix of a test result produces by {@link TestTool}. * * @author Christian Banse */ public class ConfusionMatrixTool extends Configured implements Tool { /** * The action used by the job name. */ public static String ACTION = "ConfusionMatrix"; /** * The number of reduce tasks. Set to 1 in order to reduce the number of * files. */ public static int NUM_OF_REDUCE_TASKS = 1; /** * The main entry point if this class is called as a {@link Tool}. */ @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); Path testPath = new Path(conf.get(Util.CONF_TEST_PATH)); String option = conf.get(Util.CONF_OPTIONS); String testDate = conf.get(Util.CONF_TEST_DATE); String headerPath = conf.get(Util.CONF_HEADER_PATH); // TODO: might cause fault? Path inputPath = testPath.suffix("/" + conf.get(Util.CONF_SESSION_DURATION) + "/" + option + "/" + Util.PREDICTED_CLASSES_PATH + "/" + testDate); Path outputPath = new Path(conf.get(Util.CONF_MATRIX_PATH) + "/" + conf.get(Util.CONF_SESSION_DURATION) + "/" + option + "/" + testDate); // set the jobname String jobName = Util.JOB_NAME + " [" + ConfusionMatrixTool.ACTION + "] {test=" + testPath.getName() + ", option=" + option + ", testdate=" + testDate + ", session=" + conf.get(Util.CONF_SESSION_DURATION) + "}"; Util.showStatus("Running " + jobName); // read the header because we need to number of classes DataSetHeader header = new DataSetHeader(conf, new Path(headerPath)); conf.setInt(Util.CONF_NUM_CLASSES, header.getNumClasses()); conf.set("mapred.child.java.opts", "-Xmx1G"); conf.set("hadoop.job.ugi", Util.HADOOP_USER); conf.set("mapred.task.timeout", "1800000"); conf.set("mapred.map.tasks.speculative.execution", "false"); conf.set("mapred.reduce.tasks.speculative.execution", "false"); FileSystem fs = FileSystem.get(conf); Job job = new Job(conf, jobName); job.setNumReduceTasks(NUM_OF_REDUCE_TASKS); // set the mapper and reducer job.setJarByClass(ConfusionMatrixTool.class); job.setMapperClass(ConfusionMatrixMapper.class); job.setReducerClass(ConfusionMatrixReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(TextInputFormat.class); FileInputFormat.addInputPath(job, inputPath); // clear output dir fs.delete(outputPath, true); FileOutputFormat.setOutputPath(job, outputPath); job.submit(); // return 1; return job.waitForCompletion(true) ? 1 : 0; } }
31.294118
77
0.723997
24ad03f9d0231856fee927b4d33fa9fc5bd6d3a2
890
package com.weatherchecker.tool; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class DateProvider { public static String getDayOfWeek() { int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); switch (dayOfWeek){ case 2: return "Monday"; case 3: return "Tueasday"; case 4: return "Wednesday"; case 5: return "Thursday"; case 6: return "Friday"; case 7: return "Saturday"; case 1: return "Sunday"; default: return ""; } } public static String getDate() { Date date = Calendar.getInstance().getTime(); String pattern = "dd/MM/yyyy"; SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault()); return sdf.format(date); } }
27.8125
82
0.606742
21145327f957a100f74a15f42f504d4f7cfe8f7b
749
package org.firstinspires.ftc.teamcode.testOpModes; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.teamcode.subsystems.robot.Robot; @TeleOp public class GyroTest extends OpMode { Robot robot; boolean started = false; @Override public void init() { robot = new Robot(hardwareMap, telemetry); } @Override public void loop() { if(!started) { robot.odometry.imu().initialize(robot.odometry.parameters); started = true; } telemetry.addData("Navx Heading", robot.odometry.getNavxHeading()); telemetry.addData("IMU Heading", robot.odometry.getIMUHeading()); } }
25.827586
75
0.682243
a052ed19c8c547733f25d3f911406fda74ea80ee
2,052
package com.test; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; public class Test { public static class CyclicPrint implements Runnable { private final CyclicBarrier headBarrier; private final CyclicBarrier tailBarrier; private final AtomicInteger index; private final int max; public CyclicPrint(CyclicBarrier headBarrier, CyclicBarrier tailBarrier, AtomicInteger index, int max) { this.headBarrier = headBarrier; this.tailBarrier = tailBarrier; this.index = index; this.max = max; } @Override public void run() { do { try { headBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } for (int i = 0; i < 3; i++) { System.out.printf("%s:%d\n", Thread.currentThread().getName(), index.incrementAndGet()); } try { tailBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } while (index.get() < max); } } public static void main(String[] args) { AtomicInteger count = new AtomicInteger(); CyclicBarrier barrier1 = new CyclicBarrier(2); CyclicBarrier barrier2 = new CyclicBarrier(2); CyclicBarrier barrier3 = new CyclicBarrier(2); new Thread(new CyclicPrint(barrier1, barrier2, count, 3), "线程1").start(); new Thread(new CyclicPrint(barrier2, barrier3, count, 6), "线程2").start(); new Thread(new CyclicPrint(barrier3, barrier1, count, 9), "线程3").start(); try { barrier1.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } }
34.2
112
0.576511
d2a9d45d5bd5f834cbdabc477f6596cec05c72a3
2,042
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8074676 * @summary after guards in Arrays.copyOf() intrinsic, control may become top * * @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement * compiler.arraycopy.TestArrayCopyOfStopped */ package compiler.arraycopy; import java.util.Arrays; public class TestArrayCopyOfStopped { static class A { } static class B { } static final B[] array_of_bs = new B[10]; static final A[] array_of_as = new A[10]; static Object[] m1_helper(Object[] array, boolean flag) { if (flag) { return Arrays.copyOf(array, 10, A[].class); } return null; } static Object[] m1(boolean flag) { return m1_helper(array_of_bs, flag); } public static void main(String[] args) { for (int i = 0; i < 20000; i++) { m1_helper(array_of_as, (i%2) == 0); } for (int i = 0; i < 20000; i++) { m1(false); } } }
30.029412
77
0.663075
3701b7c2746f345911836c9ff5531ea6ec4baa7f
681
package Runner; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; @RunWith(Cucumber.class) @CucumberOptions( plugin = {}, features = "src/test/resources/Features", tags = {"~@ignore"}, glue = {"Steps"} ) public class RunCucumberTest { public static WebDriver driver; @BeforeClass public static void start() { driver = new ChromeDriver(); } @AfterClass public static void stop() { driver.quit(); } }
21.28125
49
0.678414
741ba41bfa405b184fc11fea6eb46d2468c6905c
4,336
package havis.llrpservice.server.service.fsm; import java.io.IOException; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.util.Collections; import java.util.Enumeration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.testng.Assert; import org.testng.annotations.Test; import test._EnvTest; public class DeviceTest { @Test public void formatAddress() throws Exception { Device device = new Device(); // FE:54:00:58:DE:3A byte[] addr = new byte[] { (byte) 0xFE, 0x54, 0, 0x58, (byte) 0xDE, 0x3A }; Assert.assertEquals(device.formatAddress(addr, ""), "FE540058DE3A"); addr = new byte[] { (byte) 0xFE, 0x54, 0 }; Assert.assertEquals(device.formatAddress(addr, ":"), "FE:54:00"); } @Test public void getLocalMacAddress() throws Exception { ExecutorService threadPool = Executors.newFixedThreadPool(1); Future<?> future = threadPool.submit(new Runnable() { @Override public void run() { try { ServerSocket ssocket = new ServerSocket(_EnvTest.SERVER_PORT_1); ssocket.accept(); try { Thread.sleep(1000); } catch (InterruptedException e) { } ssocket.close(); } catch (IOException e) { Assert.fail(); } } }); // wait for a started server Thread.sleep(500); // get first IP address with an assigned MAC address String addr = null; byte[] macAddr = null; Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(networkInterfaces)) { if (netint.getHardwareAddress() != null && netint.getInetAddresses().hasMoreElements()) { addr = netint.getInetAddresses().nextElement().getHostAddress(); macAddr = netint.getHardwareAddress(); break; } } // create a client socket with the IP address Socket socket = new Socket(addr, _EnvTest.SERVER_PORT_1); // get the MAC address Device device = new Device(); byte[] macAddr2 = device.getLocalMacAddress(socket); Assert.assertEquals(macAddr2.length, 6); Assert.assertEquals(macAddr2, macAddr); socket.close(); future.get(); threadPool.shutdown(); } @Test public void getLocalEUI64Address() throws Exception { Device device = new Device(); // no MAC address Assert.assertNull(device.getLocalEUI64Address(null)); // empty MAC address Assert.assertEquals(device.getLocalEUI64Address(new byte[0]).length, 0); // invalid MAC address try { device.getLocalEUI64Address(new byte[] { 1 }); Assert.fail(); } catch (InvalidMacAddressException e) { Assert.assertTrue(e.getMessage().contains("1/6")); } catch (Exception e) { Assert.fail(); } // valid MAC address: FE:54:00:58:DE:3A byte[] macAddr = new byte[] { (byte) 0xFE, 0x54, 0, 0x58, (byte) 0xDE, 0x3A }; byte[] eui64Addr = device.getLocalEUI64Address(macAddr); // FE:54:00:FF:FE:58:DE:3A Assert.assertEquals(eui64Addr, new byte[] { (byte) 0xFE, 0x54, 0, (byte) 0xFF, (byte) 0xFE, 0x58, (byte) 0xDE, 0x3A }); } @Test public void getIntIdentification() throws Exception { String propertyName = "mica.device.serial_no"; Device device = new Device(); System.setProperty(propertyName, ""); byte[] value = new byte[3]; device.getIntIdentification(propertyName, value); Assert.assertEquals(value, new byte[] { 0, 0, 0 }); System.setProperty(propertyName, "1"); value = new byte[1]; device.getIntIdentification(propertyName, value); Assert.assertEquals(value, new byte[] { 1 }); System.setProperty(propertyName, "255"); value = new byte[1]; device.getIntIdentification(propertyName, value); Assert.assertEquals(value, new byte[] { (byte) 0xFF }); System.setProperty(propertyName, " 258 "); value = new byte[2]; device.getIntIdentification(propertyName, value); Assert.assertEquals(value, new byte[] { 1, 2 }); System.setProperty(propertyName, "258"); value = new byte[1]; device.getIntIdentification(propertyName, value); Assert.assertEquals(value, new byte[] { 2 }); System.setProperty(propertyName, "a"); try { device.getIntIdentification(propertyName, value); Assert.fail(); } catch (NumberFormatException e) { } // remove system property System.setProperty(propertyName, ""); } }
30.971429
93
0.701568
f3dd78c075d3cba9b3a390840f419587e7eacb13
432
package io.horizon.ctp.service.monitor; import lombok.Getter; import lombok.Setter; /** * * @author yellow013 * */ @Getter @Setter public class Cpu { /** * 核心数 */ private int coreNum; /** * CPU总的使用率 */ private double total; /** * CPU系统使用率 */ private double sys; /** * CPU用户使用率 */ private double used; /** * CPU当前等待率 */ private double wait; /** * CPU当前空闲率 */ private double free; }
9.391304
39
0.590278
0ea1a3650439f262517f83b3b80577a991f844ec
3,308
/* * (c) Copyright 2007, 2008, 2009 Hewlett-Packard Development Company, LP * All rights reserved. * [See end of file] */ package com.hp.hpl.jena.sparql.engine.iterator; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.hp.hpl.jena.sparql.engine.QueryIterator; import com.hp.hpl.jena.sparql.engine.binding.Binding; import com.hp.hpl.jena.sparql.serializer.SerializationContext; import com.hp.hpl.jena.sparql.util.IndentedWriter; /** A QueryIterator that copies an iterator. * Can get a QueryIterator over the copy. */ public class QueryIteratorCopy extends QueryIteratorBase { // Not tracked. List<Binding> elements = new ArrayList<Binding>() ; QueryIterator iterator ; QueryIterator original ; // Keep for debugging - This is closed as it is copied. public QueryIteratorCopy(QueryIterator qIter) { for ( ; qIter.hasNext() ; ) elements.add(qIter.nextBinding()) ; qIter.close() ; iterator = copy() ; original = qIter ; } @Override protected Binding moveToNextBinding() { return iterator.nextBinding() ; } public void output(IndentedWriter out, SerializationContext sCxt) { out.print("QueryIteratorCopy") ; out.incIndent() ; original.output(out, sCxt) ; out.decIndent() ; } public List<Binding> elements() { return Collections.unmodifiableList(elements) ; } public QueryIterator copy() { return new QueryIterPlainWrapper(elements.iterator()) ; } @Override protected void closeIterator() { iterator.close() ; } @Override protected boolean hasNextBinding() { return iterator.hasNext() ; } } /* * (c) Copyright 2007, 2008, 2009 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
32.431373
91
0.703144
1a4249ea3bd056eae71a9019c8aee1978b9e5dd5
499
import java.util.Scanner; public class Largest3num { public static void main(String[] args) { int num1,num2,num3; System.out.print("Enter three numbers :"); Scanner sc=new Scanner(System.in); num1=sc.nextInt(); num2=sc.nextInt(); num3=sc.nextInt(); if(num1>num2 && num1>num3) System.out.println("The Largest num is :" +num1); else if(num2>num3 && num2>num3) System.out.println("The Largest num is :" +num2); else System.out.println("The Largest num is :" +num3); } }
23.761905
53
0.669339
e4ecf3fc0b0e4dc3e15d8881de7ebddb73df7a92
12,058
package org.vorthmann.zome.app.impl; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.vorthmann.ui.Controller; import org.vorthmann.ui.DefaultController; import com.vzome.api.Tool; import com.vzome.core.algebra.AlgebraicNumber; import com.vzome.core.algebra.AlgebraicVector; import com.vzome.core.construction.Color; import com.vzome.core.editor.SymmetrySystem; import com.vzome.core.editor.api.OrbitSource; import com.vzome.core.editor.api.Shapes; import com.vzome.core.math.symmetry.Axis; import com.vzome.core.math.symmetry.Direction; import com.vzome.core.math.symmetry.OrbitSet; import com.vzome.core.math.symmetry.Symmetry; import com.vzome.core.render.RenderedModel; import com.vzome.desktop.controller.CameraController; public class SymmetryController extends DefaultController { @Override public String getProperty( String string ) { switch ( string ) { case "name": return this .symmetrySystem .getName(); case "renderingStyle": return this .symmetrySystem .getStyle() .getName(); case "modelResourcePath": return this .symmetrySystem .getModelResourcePath(); default: if ( string .startsWith( "orbitColor." ) ) { String name = string .substring( "orbitColor." .length() ); Direction dir = buildOrbits .getDirection( name ); Color color = getColor( dir ); return color .toString(); } return super.getProperty( string ); } } private SymmetrySystem symmetrySystem; public OrbitSet availableOrbits; public OrbitSet snapOrbits; public OrbitSet buildOrbits; public OrbitSet renderOrbits; private final CameraController.Snapper snapper; public OrbitSetController availableController; public OrbitSetController snapController; public OrbitSetController buildController; public OrbitSetController renderController; public Map<Direction, LengthController> orbitLengths = new HashMap<>(); private final Map<String, Controller> symmetryToolFactories = new LinkedHashMap<>(); private final Map<String, Controller> transformToolFactories = new LinkedHashMap<>(); private final Map<String, Controller> linearMapToolFactories = new LinkedHashMap<>(); private final RenderedModel renderedModel; public Symmetry getSymmetry() { return this .symmetrySystem .getSymmetry(); } public CameraController.Snapper getSnapper() { return snapper; } public SymmetryController( Controller parent, SymmetrySystem model, RenderedModel mRenderedModel ) { this .symmetrySystem = model; renderedModel = mRenderedModel; Symmetry symmetry = model .getSymmetry(); availableOrbits = new OrbitSet( symmetry ); snapOrbits = new OrbitSet( symmetry ); buildOrbits = new OrbitSet( symmetry ); renderOrbits = new OrbitSet( symmetry ); snapper = new SymmetrySnapper( snapOrbits ); for (Direction orbit : symmetry .getOrbitSet()) { if ( model .orbitIsStandard( orbit ) ) { availableOrbits .add( orbit ); snapOrbits .add( orbit ); if ( model .orbitIsBuildDefault( orbit ) ) { buildOrbits .add( orbit ); } } renderOrbits .add( orbit ); } availableController = new OrbitSetController( availableOrbits, this .symmetrySystem .getOrbits(), this .symmetrySystem, false ); this .addSubController( "availableOrbits", availableController ); snapController = new OrbitSetController( snapOrbits, availableOrbits, this .symmetrySystem, false ); this .addSubController( "snapOrbits", snapController ); buildController = new OrbitSetController( buildOrbits, availableOrbits, this .symmetrySystem, true ); this .addSubController( "buildOrbits", buildController ); if ( parent .propertyIsTrue( "single.orbit" ) ) try { buildController .doAction( "oneAtATime" ); } catch (Exception e) { e.printStackTrace(); } renderController = new OrbitSetController( renderOrbits, this .symmetrySystem .getOrbits(), this .symmetrySystem, false ); this .addSubController( "renderOrbits", renderController ); for ( Direction orbit : this .symmetrySystem .getOrbits() ) { AlgebraicNumber unitLength = this .symmetrySystem .getOrbitUnitLength( orbit ); LengthController lengthModel = new LengthController( symmetry .getField(), unitLength ); buildController .addSubController( "length." + orbit .getName(), lengthModel ); orbitLengths .put( orbit, lengthModel ); } if ( parent .propertyIsTrue( "disable.known.directions" ) ) this .symmetrySystem .disableKnownDirection(); availableController .addPropertyListener( new PropertyChangeListener() { @Override public void propertyChange( PropertyChangeEvent event ) { if ( "orbits" .equals( event .getPropertyName() ) ) { // properties() .firePropertyChange( event ); // just forwarding } } } ); } @Override public String[] getCommandList( String listName ) { switch ( listName ) { case "styles": return this .symmetrySystem .getStyleNames(); case "orbits": String[] result = new String[ this .symmetrySystem .getOrbits() .size() ]; int i = 0; for (Direction orbit : this .symmetrySystem .getOrbits()) { result[ i ] = orbit .getName(); i++; } return result; case "symmetryToolFactories": // This will be called only once, before any relevant getSubController, so it is OK to do creations for ( Tool.Factory factory : this .symmetrySystem .getToolFactories( Tool.Kind.SYMMETRY ) ) this .symmetryToolFactories .put( factory .getId(), new ToolFactoryController( factory ) ); return this .symmetryToolFactories .keySet() .toArray( new String[]{} ); case "transformToolFactories": // This will be called only once, before any relevant getSubController, so it is OK to do creations for ( Tool.Factory factory : this .symmetrySystem .getToolFactories( Tool.Kind.TRANSFORM ) ) this .transformToolFactories .put( factory .getId(), new ToolFactoryController( factory ) ); return this .transformToolFactories .keySet() .toArray( new String[]{} ); case "linearMapToolFactories": // This will be called only once, before any relevant getSubController, so it is OK to do creations for ( Tool.Factory factory : this .symmetrySystem .getToolFactories( Tool.Kind.LINEAR_MAP ) ) this .linearMapToolFactories .put( factory .getId(), new ToolFactoryController( factory ) ); return this .linearMapToolFactories .keySet() .toArray( new String[]{} ); case "builtInSymmetryTools": // This will be called only once, before any relevant getSubController, so it is OK to do creations List<String> toolNames = new ArrayList<>(); for ( Tool tool : this .symmetrySystem .getPredefinedTools( Tool.Kind.SYMMETRY ) ) toolNames .add( tool .getId() ); return toolNames .toArray( new String[]{} ); case "builtInTransformTools": // This will be called only once, before any relevant getSubController, so it is OK to do creations List<String> transformToolNames = new ArrayList<>(); for ( Tool tool : this .symmetrySystem .getPredefinedTools( Tool.Kind.TRANSFORM ) ) transformToolNames .add( tool .getId() ); return transformToolNames .toArray( new String[]{} ); default: return super .getCommandList( listName ); } } @Override public Controller getSubController( String name ) { switch ( name ) { case "availableOrbits": return availableController; case "snapOrbits": return snapController; case "buildOrbits": return buildController; case "renderOrbits": return renderController; default: if ( name .startsWith( "length." ) ) { String dirName = name .substring( "length." .length() ); Direction dir = this .symmetrySystem .getOrbits() .getDirection( dirName ); return getLengthController( dir ); } Controller result = this .symmetryToolFactories .get( name ); if ( result != null ) return result; result = this .transformToolFactories .get( name ); if ( result != null ) return result; result = this .linearMapToolFactories .get( name ); if ( result != null ) return result; return super .getSubController( name ); } } @Override public void doAction( String action ) throws Exception { switch (action) { case "rZomeOrbits": case "predefinedOrbits": case "setAllDirections": availableController .doAction( action ); break; case "ReplaceWithShape": action += "/" + this .symmetrySystem .getName() + ":" + this .symmetrySystem .getStyle() .getName(); super .doAction( action ); break; default: if ( action .startsWith( "setStyle." ) ) { String styleName = action .substring( "setStyle." .length() ); this .symmetrySystem .setStyle( styleName ); this .renderedModel .setShapes( this .symmetrySystem .getShapes() ); } else { boolean handled = this .symmetrySystem .doAction( action ); if ( ! handled ) super .doAction( action ); } break; } } private LengthController getLengthController( Direction orbit ) { LengthController result = orbitLengths .get( orbit ); if ( result == null && orbit != null ) { AlgebraicNumber unitLength = this .symmetrySystem .getOrbitUnitLength( orbit ); result = new LengthController( this .symmetrySystem .getSymmetry() .getField(), unitLength ); buildController .addSubController( "length." + orbit .getName(), result ); orbitLengths .put( orbit, result ); renderOrbits .add( orbit ); availableOrbits .add( orbit ); } return result; } public OrbitSet getOrbits() { return this .symmetrySystem .getOrbits(); } // TODO: Can we get rid of this? It is only needed by PreviewStrut. // We should be able to accomplish the sync with PropertyChangeListeners public OrbitSource getOrbitSource() { return this .symmetrySystem; } // TODO this should take over all functions of symmetry.getAxis() public Axis getZone( AlgebraicVector offset ) { return this .symmetrySystem .getAxis( offset ); } public Color getColor( Direction orbit ) { return this .symmetrySystem .getColor( orbit ); } public OrbitSet getBuildOrbits() { return this .buildOrbits; } public Shapes getRenderingStyle() { return this .symmetrySystem .getRenderingStyle(); } }
37.101538
136
0.616437
9b4f72589ea83d6a6e27e96561ab7d7e9a0f0921
5,688
package com.faithfulmc.hardcorefactions.command; import com.faithfulmc.hardcorefactions.ConfigurationService; import com.faithfulmc.hardcorefactions.HCF; import com.faithfulmc.hardcorefactions.events.CaptureZone; import com.faithfulmc.hardcorefactions.events.faction.ConquestFaction; import com.faithfulmc.hardcorefactions.events.faction.KothFaction; import com.faithfulmc.hardcorefactions.faction.type.ClaimableFaction; import com.faithfulmc.hardcorefactions.faction.type.Faction; import com.faithfulmc.hardcorefactions.mountain.GlowstoneMountainManager; import com.faithfulmc.hardcorefactions.mountain.OreMountainManager; import com.faithfulmc.util.BukkitUtils; import com.faithfulmc.util.cuboid.Cuboid; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class CoordsCommand implements CommandExecutor { private final HCF hcf; private long lastCache = 0; private final List<KothFaction> koths = new ArrayList<>(); private final List<ConquestFaction> conquestFaction = new ArrayList<>(); private ChatColor MAIN_COLOR; private ChatColor SECONDARY_COLOR; private ChatColor EXTRA_COLOR; private ChatColor VALUE_COLOR; private String STAR; public CoordsCommand(HCF hcf) { this.hcf = hcf; this.MAIN_COLOR = ConfigurationService.GOLD; this.SECONDARY_COLOR = ConfigurationService.YELLOW; this.EXTRA_COLOR = ChatColor.DARK_GRAY; this.VALUE_COLOR = ConfigurationService.GRAY; STAR = ConfigurationService.GOLD + " * "; } public boolean onCommand(CommandSender sender, Command command, String cmdLabel, String[] args) { tryCache(); sender.sendMessage(EXTRA_COLOR + BukkitUtils.STRAIGHT_LINE_DEFAULT); sender.sendMessage(ConfigurationService.SCOREBOARD_TITLE); sender.sendMessage(EXTRA_COLOR + BukkitUtils.STRAIGHT_LINE_DEFAULT); if (!ConfigurationService.KIT_MAP) { GlowstoneMountainManager glowstone = hcf.getGlowstoneMountainManager(); OreMountainManager ores = hcf.getOreMountainManager(); Cuboid gscuboid = glowstone.getCuboid(); Cuboid orecuboid = ores.getCuboid(); if (gscuboid != null || orecuboid != null) { sender.sendMessage(MAIN_COLOR + ChatColor.BOLD.toString() + "Mountains"); if (gscuboid != null) { sender.sendMessage(STAR + SECONDARY_COLOR + "Glowstone Mountain: " + VALUE_COLOR + GlowstoneMountainCommand.locToCords(gscuboid.getCenter())); } if (orecuboid != null) { sender.sendMessage(STAR + SECONDARY_COLOR + "Ore Mountain: " + VALUE_COLOR + OreMountainCommand.locToCords(orecuboid.getCenter())); } } } if (!koths.isEmpty()) { sender.sendMessage(MAIN_COLOR + ChatColor.BOLD.toString() + "Koth" + (koths.size() == 1 ? "" : "s") + ":"); for (KothFaction kothFaction : koths) { CaptureZone captureZone = kothFaction.getCaptureZone(); if (captureZone == null) { continue; } Cuboid cuboid = captureZone.getCuboid(); if(cuboid == null){ continue; } World world = cuboid.getWorld(); int x = (int) (Math.round(cuboid.getCenter().getX() / 10.0) * 10); int z = (int) (Math.round(cuboid.getCenter().getZ() / 10.0) * 10); sender.sendMessage(STAR + SECONDARY_COLOR + kothFaction.getName() + ": " + VALUE_COLOR + ClaimableFaction.ENVIRONMENT_MAPPINGS.get(world.getEnvironment()) + ", " + x + " | " + z); } } if (!conquestFaction.isEmpty()) { sender.sendMessage(MAIN_COLOR + ChatColor.BOLD.toString() + "Conquest" + (conquestFaction.size() == 1 ? "" : "s") + ":"); for (ConquestFaction conquest : conquestFaction) { CaptureZone captureZone = conquest.getMain(); if (captureZone == null) { continue; } Cuboid cuboid = captureZone.getCuboid(); World world = cuboid.getWorld(); int x = (int) (Math.round(cuboid.getCenter().getX() / 10.0) * 10); int z = (int) (Math.round(cuboid.getCenter().getZ() / 10.0) * 10); sender.sendMessage(STAR + SECONDARY_COLOR + conquest.getName() + ": " + VALUE_COLOR + ClaimableFaction.ENVIRONMENT_MAPPINGS.get(world.getEnvironment()) + ", " + x + " | " + z); } } sender.sendMessage(EXTRA_COLOR + BukkitUtils.STRAIGHT_LINE_DEFAULT); return true; } public void tryCache(){ long now = System.currentTimeMillis(); if(now - lastCache > TimeUnit.HOURS.toMillis(1)) { koths.clear(); conquestFaction.clear(); for (Faction faction : new ArrayList<>(hcf.getFactionManager().getFactions())) { if (faction instanceof ClaimableFaction && ((ClaimableFaction) faction).getClaims().isEmpty()) { continue; } if (faction instanceof KothFaction) { koths.add((KothFaction) faction); } if (faction instanceof ConquestFaction) { conquestFaction.add((ConquestFaction) faction); } } lastCache = now; } } }
46.622951
196
0.625176
6998281cdc9ce6c960a5fbb86079147ab21b449e
1,742
package com.half.wowsca.model; import org.json.JSONObject; /** * Created by slai4 on 9/19/2015. */ public class BatteryStats { private int maxFrags; private int frags; private int hits; private int shots; private long maxFragsShipId; public static BatteryStats parse(JSONObject json) { BatteryStats stats = new BatteryStats(); if (json != null) { stats.setMaxFrags(json.optInt("max_frags_battle")); stats.setFrags(json.optInt("frags")); stats.setHits(json.optInt("hits")); stats.setMaxFragsShipId(json.optLong("max_frags_ship_id")); stats.setShots(json.optInt("shots")); } return stats; } @Override public String toString() { return "Battery{" + "maxFrags=" + maxFrags + ", frags=" + frags + ", hits=" + hits + ", shots=" + shots + ", maxFragsShipId=" + maxFragsShipId + '}'; } public int getMaxFrags() { return maxFrags; } public void setMaxFrags(int maxFrags) { this.maxFrags = maxFrags; } public int getFrags() { return frags; } public void setFrags(int frags) { this.frags = frags; } public int getHits() { return hits; } public void setHits(int hits) { this.hits = hits; } public int getShots() { return shots; } public void setShots(int shots) { this.shots = shots; } public long getMaxFragsShipId() { return maxFragsShipId; } public void setMaxFragsShipId(long maxFragsShipId) { this.maxFragsShipId = maxFragsShipId; } }
21.775
71
0.557979
8c309785bc1e1c281d8917ca1e1377609f062c60
507
package plb.spring.dao.jdbc; import java.sql.Connection; import java.sql.SQLException; import com.mysql.jdbc.DatabaseMetaData; public class TransactionSupport { public static void main(String[] args) throws SQLException { Connection conn = JDBCUtil.getConnection(); DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData(); System.out.println(dm.supportsTransactions()); System.out.println(dm.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)); } }
29.823529
99
0.771203
36ee39c1a50ad2ac764032cd7bcd1064d3547f5e
26,075
package com.kuaiyou.obj; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * 单条广告的属�? */ public class AdsBean implements Serializable { private static final Long serialVersionUID = 8472182013671215462L; private String idAd = null; private String adText = null; private String adPic = null; private String adLink = null; private String adSubTitle = null; private String adTitle = null; private String adInfo = null; private Integer adType = 0; private String adIcon = null; // 广告背景�? private String adBgColor = null; // 广告行为图标底色 private String adBehaveBgColor = null; // 广告图标底色 private String adIconBgColor = null; // 广告主标题颜�? private String adTitleColor = null; // 广告副标题颜�? private String adSubTitleColor = null; // 广告关键字颜�? private String adKeyWordColor = null; private String adBehavIcon = null; private String getImageUrl = null; private String serviceUrl = null; // 2013 - 9 - 26 百度添加字段 private Integer adAct = 0; private String adPhoneNum = null; private String adLogLink = null; private Integer adSource = 0; private String dAppName = null; private String dAppIcon = null; private String dPackageName = null; private Integer dAppSize = 0; private String mon_s = null; private String mon_c = null; // 2014 - 7 - 30 Inmobi private String xhtml = null; private Integer adHeight = 50; private Integer adWidth = 320; // 2014 - 8 - 18 private Integer appScore = -1; private Integer appUsers = -1; private String targetId = null; private Integer btn_render = 0; private String msg = null; private Integer resultCode = 1; private String dstlink = null; private String clickid = null; // 2014 - 8 - 21 private HashMap<String, String[]> extSRpt = null; private HashMap<String, String[]> extCRpt = null; // 2014 - 9 - 18 增加开屏字�? private Integer ruleTime = 0; private Integer delayTime = 0; private String pointArea = "(0,0,1000,1000)"; private Long cacheTime = 0l; private Integer spreadType = 2; private Integer vat = 0; private String appId = null; private Integer sdkType = 0; private Integer touchStatus = 0; private Integer sc = 0; // 2015 - 5 - 25 增加控制点击次数字段 private Integer clickNumLimit = 2; private Integer action_up_x = -1; private Integer action_up_y = -1; private Integer action_down_x = -1; private Integer action_down_y = -1; private Integer realAdWidth = -1; private Integer realAdHeight = -1; private Integer specialAdWidth = -1; private Integer specialAdHeight = -1; private NativeAdBean nativeAdBean; private long dataTime = -1; private String fallback; private String deeplink = null; private String[] faUrl = null; private String[] saUrl = null; private String[] iaUrl = null; // 新增 广告标识字段 private String adLogoUrl = null; private String adIconUrl = null; private int route = 0; private String[] videoSource = null; private int videoValidTime = 30; private String eqs = ""; // 2017.10.7 新增字段支持gdt下载类广告 private Integer alType = 0; private Integer deformationMode = 0; private String gdt_conversion_link; private String rawData; //2018.4.19 增加video字段 private int xmlType; private VideoBean videoBean; private String vastXml; // private String videoUrl; // private String iconUrl; // private String title; // private String desc; // private int duration; // private int width, height; private String[] spTrackers, mpTrackers, cpTrackers, playMonUrls; //video.ext字段 private String preImgUrl, endHtml, endImgUrl; private Integer ait; private AgDataBean agDataBean; private ArrayList<AgDataBean> agDataBeanList; private String aptAppId; private String aptOrgId; private String aptPath; private Integer aptType; public static AdsBean copyAdsBean(AdsBean adsBean) { AdsBean newAdsBean = new AdsBean(); newAdsBean.setAdAct(adsBean.getAdAct()); newAdsBean.setAdBehaveBgColor(adsBean.getAdBehaveBgColor()); newAdsBean.setAdBehavIcon(adsBean.getAdBehavIcon()); newAdsBean.setAdBgColor(adsBean.getAdBgColor()); newAdsBean.setAdHeight(adsBean.getAdHeight()); newAdsBean.setAdIcon(adsBean.getAdIcon()); newAdsBean.setAdIconBgColor(adsBean.getAdIconBgColor()); newAdsBean.setAdInfo(adsBean.getAdInfo()); newAdsBean.setAdKeyWordColor(adsBean.getAdKeyWordColor()); newAdsBean.setAdLink(adsBean.getAdLink()); newAdsBean.setAdLogLink(adsBean.getAdLogLink()); newAdsBean.setAdPhoneNum(adsBean.getAdPhoneNum()); newAdsBean.setAdPic(adsBean.getAdPic()); newAdsBean.setAdSource(adsBean.getAdSource()); newAdsBean.setAdSubTitle(adsBean.getAdSubTitle()); newAdsBean.setAdSubTitleColor(adsBean.getAdSubTitleColor()); newAdsBean.setAdText(adsBean.getAdText()); newAdsBean.setAdTitleColor(adsBean.getAdTitleColor()); newAdsBean.setAdType(adsBean.getAdType()); newAdsBean.setAdWidth(adsBean.getAdWidth()); newAdsBean.setAppScore(adsBean.getAppScore()); newAdsBean.setAppUsers(adsBean.getAppUsers()); newAdsBean.setBtn_render(adsBean.getBtn_render()); newAdsBean.setCacheTime(adsBean.getCacheTime()); newAdsBean.setClickid(adsBean.getClickid()); newAdsBean.setdAppIcon(adsBean.getdAppIcon()); newAdsBean.setdAppName(adsBean.getdAppName()); newAdsBean.setdAppSize(adsBean.getdAppSize()); newAdsBean.setDelayTime(adsBean.getDelayTime()); newAdsBean.setdPackageName(adsBean.getdPackageName()); newAdsBean.setDstlink(adsBean.getDstlink()); newAdsBean.setExtCRpt(adsBean.getExtCRpt()); newAdsBean.setExtSRpt(adsBean.getExtSRpt()); newAdsBean.setGetImageUrl(adsBean.getGetImageUrl()); newAdsBean.setIdAd(adsBean.getIdAd()); newAdsBean.setMon_c(adsBean.getMon_c()); newAdsBean.setMon_s(adsBean.getMon_s()); newAdsBean.setMsg(adsBean.getMsg()); newAdsBean.setPointArea(adsBean.getPointArea()); newAdsBean.setResultCode(adsBean.getResultCode()); newAdsBean.setRuleTime(adsBean.getRuleTime()); newAdsBean.setServicesUrl(adsBean.getServicesUrl()); newAdsBean.setServiceUrl(adsBean.getServiceUrl()); newAdsBean.setTargetId(adsBean.getTargetId()); newAdsBean.setVat(adsBean.getVat()); newAdsBean.setXhtml(adsBean.getXhtml()); newAdsBean.setTouchStatus(adsBean.getTouchStatus()); newAdsBean.setAppId(adsBean.getAppId()); newAdsBean.setSdkType(adsBean.getSdkType()); newAdsBean.setSc(adsBean.getSc()); newAdsBean.setClickNumLimit(adsBean.getClickNumLimit()); newAdsBean.setRealAdHeight(adsBean.getRealAdHeight()); newAdsBean.setRealAdWidth(adsBean.getRealAdWidth()); newAdsBean.setAction_down_x(adsBean.getAction_down_x()); newAdsBean.setAction_down_y(adsBean.getAction_down_y()); newAdsBean.setAction_up_x(adsBean.getAction_up_x()); newAdsBean.setAction_up_y(adsBean.getAction_up_y()); newAdsBean.setSpecialAdHeight(adsBean.getSpecialAdHeight()); newAdsBean.setSpecialAdWidth(adsBean.getSpecialAdWidth()); newAdsBean.setNativeAdBean(adsBean.getNativeAdBean()); newAdsBean.setDataTime(adsBean.getDataTime()); newAdsBean.setFallback(adsBean.getFallback()); newAdsBean.setDeeplink(adsBean.getDeeplink()); newAdsBean.setFaUrl(adsBean.getFaUrl()); newAdsBean.setSaUrl(adsBean.getSaUrl()); newAdsBean.setIaUrl(adsBean.getIaUrl()); newAdsBean.setAdLogoUrl(adsBean.getAdLogoUrl()); newAdsBean.setAdIconUrl(adsBean.getAdIconUrl()); newAdsBean.setRoute(adsBean.getRoute()); newAdsBean.setVideoSource(adsBean.getVideoSource()); newAdsBean.setVideoValidTime(adsBean.getVideoValidTime()); newAdsBean.setEqs(adsBean.getEqs()); newAdsBean.setAlType(adsBean.getAlType()); newAdsBean.setGdtConversionLink(adsBean.getGdtConversionLink()); newAdsBean.setDeformationMode(adsBean.getDeformationMode()); newAdsBean.setRawData(adsBean.getRawData()); newAdsBean.setXmlType(adsBean.getXmlType()); newAdsBean.setXmlType(adsBean.getXmlType()); newAdsBean.setVideoBean(adsBean.getVideoBean()); newAdsBean.setVastXml(adsBean.getVastXml()); // newAdsBean.setVideoUrl(adsBean.getVideoUrl()); // newAdsBean.setIconUrl(adsBean.getIconUrl()); // newAdsBean.setTitle(adsBean.getTitle()); // newAdsBean.setDesc(adsBean.getDesc()); // // newAdsBean.setDuration(adsBean.getDuration()); newAdsBean.setSpTrackers(adsBean.getSpTrackers()); newAdsBean.setMpTrackers(adsBean.getMpTrackers()); newAdsBean.setCpTrackers(adsBean.getCpTrackers()); newAdsBean.setPreImgUrl(adsBean.getPreImgUrl()); newAdsBean.setEndHtml(adsBean.getEndHtml()); newAdsBean.setEndImgUrl(adsBean.getEndImgUrl()); // newAdsBean.setWidth(adsBean.getWidth()); // newAdsBean.setHeight(adsBean.getHeight()); newAdsBean.setPlayMonUrls(adsBean.getPlayMonUrls()); newAdsBean.setAptAppId(adsBean.getAptAppId()); newAdsBean.setAptOrgId(adsBean.getAptOrgId()); newAdsBean.setAptPath(adsBean.getAptPath()); newAdsBean.setAptType(adsBean.getAptType()); newAdsBean.setAgDataBean(adsBean.getAgDataBean()); return newAdsBean; } public ArrayList<AgDataBean> getAgDataBeanList() { return agDataBeanList; } public void setAgDataBeanList(ArrayList<AgDataBean> agDataBeanList) { this.agDataBeanList = agDataBeanList; } public AgDataBean getAgDataBean() { return agDataBean; } public void setAgDataBean(AgDataBean agDataBean) { this.agDataBean = agDataBean; } public Integer getAit() { return ait; } public void setAit(Integer ait) { this.ait = ait; } public String[] getPlayMonUrls() { return playMonUrls; } public void setPlayMonUrls(String[] playMonUrls) { this.playMonUrls = playMonUrls; } public VideoBean getVideoBean() { return videoBean; } public void setVideoBean(VideoBean videoBean) { this.videoBean = videoBean; } public int getXmlType() { return xmlType; } public void setXmlType(int xmlType) { this.xmlType = xmlType; } public String getVastXml() { return vastXml; } public void setVastXml(String vastXml) { this.vastXml = vastXml; } // public String getVideoUrl() { // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // public String getIconUrl() { // return iconUrl; // } // // public void setIconUrl(String iconUrl) { // this.iconUrl = iconUrl; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public int getDuration() { // return duration; // } // // public void setDuration(int duration) { // this.duration = duration; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } public String getAptAppId() { return aptAppId; } public void setAptAppId(String aptAppId) { this.aptAppId = aptAppId; } public String getAptOrgId() { return aptOrgId; } public void setAptOrgId(String aptOrgId) { this.aptOrgId = aptOrgId; } public String getAptPath() { return aptPath; } public void setAptPath(String aptPath) { this.aptPath = aptPath; } public Integer getAptType() { return aptType; } public void setAptType(Integer aptType) { this.aptType = aptType; } public String[] getSpTrackers() { return spTrackers; } public void setSpTrackers(String[] spTrackers) { this.spTrackers = spTrackers; } public String[] getMpTrackers() { return mpTrackers; } public void setMpTrackers(String[] mpTrackers) { this.mpTrackers = mpTrackers; } public String[] getCpTrackers() { return cpTrackers; } public void setCpTrackers(String[] cpTrackers) { this.cpTrackers = cpTrackers; } public String getPreImgUrl() { return preImgUrl; } public void setPreImgUrl(String preImgUrl) { this.preImgUrl = preImgUrl; } public String getEndHtml() { return endHtml; } public void setEndHtml(String endHtml) { this.endHtml = endHtml; } public String getEndImgUrl() { return endImgUrl; } public void setEndImgUrl(String endImgUrl) { this.endImgUrl = endImgUrl; } public String getRawData() { return rawData; } public void setRawData(String rawData) { this.rawData = rawData; } public Integer getDeformationMode() { return deformationMode; } public void setDeformationMode(Integer deformationMode) { this.deformationMode = deformationMode; } public String getGdtConversionLink() { return gdt_conversion_link; } public void setGdtConversionLink(String gdt_conversion_link) { this.gdt_conversion_link = gdt_conversion_link; } public Integer getAlType() { return alType; } public void setAlType(Integer alType) { this.alType = alType; } public String getEqs() { return eqs; } public void setEqs(String eqs) { this.eqs = eqs; } public int getVideoValidTime() { return videoValidTime; } public void setVideoValidTime(int videoValidTime) { this.videoValidTime = videoValidTime; } public int getRoute() { return route; } public void setRoute(int route) { this.route = route; } public String[] getVideoSource() { return videoSource; } public void setVideoSource(String[] videoSource) { this.videoSource = videoSource; } public String getAdIconUrl() { return adIconUrl; } public void setAdIconUrl(String adIconUrl) { this.adIconUrl = adIconUrl; } public String getAdLogoUrl() { return adLogoUrl; } public void setAdLogoUrl(String adLogoUrl) { this.adLogoUrl = adLogoUrl; } public String[] getIaUrl() { return iaUrl; } public void setIaUrl(String[] iaUrl) { this.iaUrl = iaUrl; } public String getDeeplink() { return deeplink; } public void setDeeplink(String deeplink) { this.deeplink = deeplink; } public String[] getFaUrl() { return faUrl; } public void setFaUrl(String[] fa) { this.faUrl = fa; } public String[] getSaUrl() { return saUrl; } public void setSaUrl(String[] sa) { this.saUrl = sa; } public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public long getDataTime() { return dataTime; } public void setDataTime(long dataTime) { this.dataTime = dataTime; } public NativeAdBean getNativeAdBean() { return nativeAdBean; } public void setNativeAdBean(NativeAdBean nativeAdBean) { this.nativeAdBean = nativeAdBean; } public Integer getSpecialAdWidth() { return specialAdWidth; } public void setSpecialAdWidth(Integer specialAdWidth) { this.specialAdWidth = specialAdWidth; } public Integer getSpecialAdHeight() { return specialAdHeight; } public void setSpecialAdHeight(Integer specialAdHeight) { this.specialAdHeight = specialAdHeight; } public Integer getRealAdWidth() { return realAdWidth; } public void setRealAdWidth(Integer realAdWidth) { this.realAdWidth = realAdWidth; } public Integer getRealAdHeight() { return realAdHeight; } public void setRealAdHeight(Integer realAdHeight) { this.realAdHeight = realAdHeight; } public Integer getAction_up_x() { return action_up_x; } public void setAction_up_x(Integer action_up_x) { this.action_up_x = action_up_x; } public Integer getAction_up_y() { return action_up_y; } public void setAction_up_y(Integer action_up_y) { this.action_up_y = action_up_y; } public Integer getAction_down_x() { return action_down_x; } public void setAction_down_x(Integer action_down_x) { this.action_down_x = action_down_x; } public Integer getAction_down_y() { return action_down_y; } public void setAction_down_y(Integer action_down_y) { this.action_down_y = action_down_y; } public Integer getClickNumLimit() { return clickNumLimit; } public void setClickNumLimit(Integer clickNumLimit) { this.clickNumLimit = clickNumLimit; } public Integer getSc() { return sc; } public void setSc(Integer sc) { this.sc = sc; } public Integer getSdkType() { return sdkType; } public void setSdkType(Integer sdkType) { this.sdkType = sdkType; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public Integer getTouchStatus() { return touchStatus; } public void setTouchStatus(Integer touchStatus) { this.touchStatus = touchStatus; } public Integer getVat() { return vat; } public void setVat(Integer vat) { this.vat = vat; } public Integer getRuleTime() { return ruleTime; } public void setRuleTime(Integer ruleTime) { this.ruleTime = ruleTime; } public Integer getDelayTime() { return delayTime; } public void setDelayTime(Integer delayTime) { this.delayTime = delayTime; } public String getPointArea() { return pointArea; } public void setPointArea(String pointArea) { this.pointArea = pointArea; } public Long getCacheTime() { return cacheTime; } public void setCacheTime(Long cacheTime) { this.cacheTime = cacheTime; } public Integer getSpreadType() { return spreadType; } public void setSpreadType(Integer spreadType) { this.spreadType = spreadType; } public HashMap<String, String[]> getExtSRpt() { return extSRpt; } public void setExtSRpt(HashMap<String, String[]> extSRpt) { this.extSRpt = extSRpt; } public HashMap<String, String[]> getExtCRpt() { return extCRpt; } public void setExtCRpt(HashMap<String, String[]> extCRpt) { this.extCRpt = extCRpt; } public String getDstlink() { return dstlink; } public void setDstlink(String dstlink) { this.dstlink = dstlink; } public String getClickid() { return clickid; } public void setClickid(String clickid) { this.clickid = clickid; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Integer getResultCode() { return resultCode; } public void setResultCode(Integer resultCode) { this.resultCode = resultCode; } public Integer getBtn_render() { return btn_render; } public void setBtn_render(Integer btn_render) { this.btn_render = btn_render; } public Integer getAppScore() { return appScore; } public void setAppScore(Integer appScore) { this.appScore = appScore; } public Integer getAppUsers() { return appUsers; } public void setAppUsers(Integer appUsers) { this.appUsers = appUsers; } public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this.targetId = targetId; } public Integer getAdHeight() { return adHeight; } public void setAdHeight(Integer adHeight) { this.adHeight = adHeight; } public Integer getAdWidth() { return adWidth; } public void setAdWidth(Integer adWidth) { this.adWidth = adWidth; } public String getXhtml() { return xhtml; } public void setXhtml(String xhtml) { this.xhtml = xhtml; } public String getMon_s() { return mon_s; } public void setMon_s(String mon_s) { this.mon_s = mon_s; } public String getMon_c() { return mon_c; } public void setMon_c(String mon_c) { this.mon_c = mon_c; } public Integer getAdAct() { return adAct; } public void setAdAct(Integer adAct) { this.adAct = adAct; } public String getAdPhoneNum() { return adPhoneNum; } public void setAdPhoneNum(String adPhoneNum) { this.adPhoneNum = adPhoneNum; } public String getAdLogLink() { return adLogLink; } public void setAdLogLink(String adLogLink) { this.adLogLink = adLogLink; } public Integer getAdSource() { return adSource; } public void setAdSource(Integer adSource) { this.adSource = adSource; } public String getdAppName() { return dAppName; } public void setdAppName(String dAppName) { this.dAppName = dAppName; } public String getdAppIcon() { return dAppIcon; } public void setdAppIcon(String dAppIcon) { this.dAppIcon = dAppIcon; } public String getdPackageName() { return dPackageName; } public void setdPackageName(String dPackageName) { this.dPackageName = dPackageName; } public Integer getdAppSize() { return dAppSize; } public void setdAppSize(Integer dAppSize) { this.dAppSize = dAppSize; } public String getServicesUrl() { return serviceUrl; } public void setServicesUrl(String serviceUrl) { this.serviceUrl = serviceUrl; } public String getIdAd() { return idAd; } public void setIdAd(String idAd) { this.idAd = idAd; } public String getAdText() { return adText; } public void setAdText(String adText) { this.adText = adText; } public String getAdPic() { return adPic; } public void setAdPic(String adPic) { this.adPic = adPic; } public String getAdLink() { return adLink; } public void setAdLink(String adLink) { this.adLink = adLink; } public String getAdSubTitle() { return adSubTitle; } public void setAdSubTitle(String adSubTitle) { this.adSubTitle = adSubTitle; } public String getAdTitle() { return adTitle; } public void setAdTitle(String adTitle) { this.adTitle = adTitle; } public String getAdInfo() { return adInfo; } public void setAdInfo(String adInfo) { this.adInfo = adInfo; } public Integer getAdType() { return adType; } public void setAdType(Integer adType) { this.adType = adType; } public String getAdIcon() { return adIcon; } public void setAdIcon(String adIcon) { this.adIcon = adIcon; } public String getAdBgColor() { return adBgColor; } public void setAdBgColor(String adBgColor) { this.adBgColor = adBgColor; } public String getAdBehaveBgColor() { return adBehaveBgColor; } public void setAdBehaveBgColor(String adBehaveBgColor) { this.adBehaveBgColor = adBehaveBgColor; } public String getAdIconBgColor() { return adIconBgColor; } public void setAdIconBgColor(String adIconBgColor) { this.adIconBgColor = adIconBgColor; } public String getAdTitleColor() { return adTitleColor; } public void setAdTitleColor(String adTitleColor) { this.adTitleColor = adTitleColor; } public String getAdSubTitleColor() { return adSubTitleColor; } public void setAdSubTitleColor(String adSubTitleColor) { this.adSubTitleColor = adSubTitleColor; } public String getAdKeyWordColor() { return adKeyWordColor; } public void setAdKeyWordColor(String adKeyWordColor) { this.adKeyWordColor = adKeyWordColor; } public String getServiceUrl() { return serviceUrl; } public void setServiceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; } public String getAdBehavIcon() { return adBehavIcon; } public void setAdBehavIcon(String adBehavIcon) { this.adBehavIcon = adBehavIcon; } public String getGetImageUrl() { return getImageUrl; } public void setGetImageUrl(String getImageUrl) { this.getImageUrl = getImageUrl; } }
24.121184
73
0.636702
a41fdaf6abea549ed4ffd8cd3aac62f697c94c2e
910
package io.luna.game.model.mob.inter; import io.luna.game.model.mob.Player; import io.luna.net.msg.out.NameInputMessageWriter; import java.util.Optional; import java.util.OptionalInt; /** * An {@link InputInterface} implementation that opens an "Enter name" interface. * * @author lare96 <http://github.com/lare96> */ public abstract class NameInputInterface extends InputInterface { @Override public final void open(Player player) { player.queue(new NameInputMessageWriter()); } @Override public final void applyInput(Player player, OptionalInt amount, Optional<String> name) { name.ifPresent(value -> onNameInput(player, value)); } /** * A function invoked when the Player has entered a name. * * @param player The player. * @param value The string entered. */ public abstract void onNameInput(Player player, String value); }
27.575758
92
0.702198
900bbe33ac1e8d786610816103d45b7249829fb9
2,246
/* * Copyright (C) 2019 Lightbend Inc. <https://www.lightbend.com> */ package jdocs.akka.coordination.lease; import akka.actor.ActorSystem; import akka.cluster.Cluster; import akka.coordination.lease.LeaseSettings; import akka.coordination.lease.javadsl.Lease; import akka.coordination.lease.javadsl.LeaseProvider; import akka.testkit.javadsl.TestKit; import docs.akka.coordination.LeaseDocSpec; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; @SuppressWarnings("unused") public class LeaseDocTest { // #lease-example static class SampleLease extends Lease { private LeaseSettings settings; public SampleLease(LeaseSettings settings) { this.settings = settings; } @Override public LeaseSettings getSettings() { return settings; } @Override public CompletionStage<Boolean> acquire() { return null; } @Override public CompletionStage<Boolean> acquire(Consumer<Optional<Throwable>> leaseLostCallback) { return null; } @Override public CompletionStage<Boolean> release() { return null; } @Override public boolean checkLease() { return false; } } // #lease-example private static ActorSystem system; @BeforeClass public static void setup() { system = ActorSystem.create("LeaseDocTest", LeaseDocSpec.config()); } @AfterClass public static void teardown() { TestKit.shutdownActorSystem(system); system = null; } private void doSomethingImportant(Optional<Throwable> leaseLostReason) {} @Test public void beLoadable() { // #lease-usage Lease lease = LeaseProvider.get(system).getLease("<name of the lease>", "docs-lease", "<owner name>"); CompletionStage<Boolean> acquired = lease.acquire(); boolean stillAcquired = lease.checkLease(); CompletionStage<Boolean> released = lease.release(); // #lease-usage // #lost-callback lease.acquire(this::doSomethingImportant); // #lost-callback // #cluster-owner String owner = Cluster.get(system).selfAddress().hostPort(); // #cluster-owner } }
23.642105
96
0.705699
5e87ec20333671dc8b50ff4e71ff39c0d59063b7
15,388
// ============================================================================ // // Copyright (C) 2006-2016 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataquality.record.linkage.ui.composite.utils; import java.sql.Types; import java.text.ParseException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.eclipse.emf.common.util.EList; import org.talend.core.GlobalServiceRegister; import org.talend.core.ITDQRepositoryService; import org.talend.core.model.metadata.types.JavaTypesManager; import org.talend.cwm.relational.TdColumn; import org.talend.dataquality.PluginConstant; import org.talend.dataquality.analysis.Analysis; import org.talend.dataquality.indicators.Indicator; import org.talend.dataquality.indicators.columnset.BlockKeyIndicator; import org.talend.dataquality.indicators.columnset.ColumnsetPackage; import org.talend.dataquality.indicators.columnset.RecordMatchingIndicator; import org.talend.dataquality.record.linkage.constant.AttributeMatcherType; import org.talend.dataquality.record.linkage.constant.TokenizedResolutionMethod; import org.talend.dataquality.record.linkage.ui.composite.table.ISortComparator; import org.talend.dataquality.record.linkage.ui.composite.table.SortComparator; import org.talend.dataquality.record.linkage.ui.composite.table.SortState; import org.talend.dataquality.record.linkage.utils.DefaultSurvivorShipDataTypeEnum; import org.talend.dataquality.record.linkage.utils.HandleNullEnum; import org.talend.dataquality.record.linkage.utils.MatchAnalysisConstant; import org.talend.dataquality.record.linkage.utils.SurvivorShipAlgorithmEnum; import org.talend.dataquality.rules.AlgorithmDefinition; import org.talend.dataquality.rules.BlockKeyDefinition; import org.talend.dataquality.rules.KeyDefinition; import org.talend.dataquality.rules.MatchKeyDefinition; import org.talend.dataquality.rules.MatchRule; import org.talend.dataquality.rules.RulesFactory; import org.talend.dq.analysis.AnalysisRecordGroupingUtils; import orgomg.cwm.objectmodel.core.ModelElement; /** * created by zshen on Aug 6, 2013 Detailled comment * */ public class MatchRuleAnlaysisUtils { public static List<String> getColumnFromRuleMatcher(MatchRule ruleMatcher) { List<String> returnList = new ArrayList<String>(); return returnList; } public static List<String> getColumnFromBlockKey(BlockKeyDefinition blockKeyDefinition) { List<String> returnList = new ArrayList<String>(); return returnList; } /** * DOC zshen Comment method "createDefaultRow". * * @param columnName * @return */ public static MatchKeyDefinition createDefaultMatchRow(String columnName) { MatchKeyDefinition createMatchKeyDefinition1 = RulesFactory.eINSTANCE.createMatchKeyDefinition(); AlgorithmDefinition createAlgorithmDefinition1 = RulesFactory.eINSTANCE.createAlgorithmDefinition(); // by default the name of the match attribute rule is the name of the selected column createMatchKeyDefinition1.setName(columnName); createMatchKeyDefinition1.setColumn(columnName); createMatchKeyDefinition1.setConfidenceWeight(1); createMatchKeyDefinition1.setHandleNull(HandleNullEnum.NULL_MATCH_NULL.getValue()); createMatchKeyDefinition1.setTokenizationType(TokenizedResolutionMethod.NO.getComponentValue()); createAlgorithmDefinition1.setAlgorithmParameters(StringUtils.EMPTY); createAlgorithmDefinition1.setAlgorithmType(AttributeMatcherType.values()[0].name()); createMatchKeyDefinition1.setAlgorithm(createAlgorithmDefinition1); createMatchKeyDefinition1.setThreshold(1.0); return createMatchKeyDefinition1; } public static List<MatchRule> convertDataMapToRuleMatcher(Map<String, String> columnMap) { List<MatchRule> matcherList = new ArrayList<MatchRule>(); if (columnMap == null) { return matcherList; } MatchRule createRuleMatcher = RulesFactory.eINSTANCE.createMatchRule(); for (String columnName : columnMap.keySet()) { MatchKeyDefinition createDefaultMatchRow = createDefaultMatchRow(columnName); createRuleMatcher.getMatchKeys().add(createDefaultMatchRow); } matcherList.add(createRuleMatcher); return matcherList; } /** * DOC yyin Comment method "ruleMatcherConvert". * * @param blockKeyDef * @param columnMap * @return */ public static List<Map<String, String>> blockingKeyDataConvert(List<KeyDefinition> blockKeyDefList) { List<Map<String, String>> resultListData = new ArrayList<Map<String, String>>(); for (KeyDefinition keyDef : blockKeyDefList) { BlockKeyDefinition blockKeydef = (BlockKeyDefinition) keyDef; String column = blockKeydef.getColumn(); String preAlgo = blockKeydef.getPreAlgorithm().getAlgorithmType(); String preAlgoValue = blockKeydef.getPreAlgorithm().getAlgorithmParameters(); String algorithm = blockKeydef.getAlgorithm().getAlgorithmType(); String algorithmValue = blockKeydef.getAlgorithm().getAlgorithmParameters(); String postAlgo = blockKeydef.getPostAlgorithm().getAlgorithmType(); String postAlgValue = blockKeydef.getPostAlgorithm().getAlgorithmParameters(); Map<String, String> blockKeyDefMap = AnalysisRecordGroupingUtils.getBlockingKeyMap(column, preAlgo, preAlgoValue, algorithm, algorithmValue, postAlgo, postAlgValue); resultListData.add(blockKeyDefMap); } return resultListData; } /** * Get recording matching indicator from analysis * * @param analysis * @return */ public static RecordMatchingIndicator getRecordMatchIndicatorFromAna(Analysis analysis) { EList<Indicator> indicators = analysis.getResults().getIndicators(); for (Indicator ind : indicators) { if (ind instanceof RecordMatchingIndicator) { return (RecordMatchingIndicator) ind; } } return null; } /** * Get recording matching indicator and Blocking Indicator from analysis * * @param analysis * @return the index 0 will be RecordMatchingIndicator and index 1 will be BlockKeyIndicator */ public static Object[] getNeedIndicatorFromAna(Analysis analysis) { Object[] returnList = new Object[2]; EList<Indicator> indicators = analysis.getResults().getIndicators(); for (Indicator ind : indicators) { if (ind instanceof RecordMatchingIndicator) { returnList[0] = ind; } else if (ind instanceof BlockKeyIndicator) { returnList[1] = ind; } } // If match rule definition is null, create a default. if (returnList[0] == null) { returnList[0] = ColumnsetPackage.eINSTANCE.getColumnsetFactory().createRecordMatchingIndicator(); } // If blocking key indicator is nul, create a default. if (returnList[1] == null) { returnList[1] = ColumnsetPackage.eINSTANCE.getColumnsetFactory().createBlockKeyIndicator(); } return returnList; } /** * check if the column name equals to these additional special columns * * @param columnName * @return */ public static boolean isEqualsToAdditionalColumn(String columnName) { if (MatchAnalysisConstant.GID.equals(columnName) || MatchAnalysisConstant.GRP_QUALITY.equals(columnName) || MatchAnalysisConstant.GROUP_SIZE.equals(columnName) || MatchAnalysisConstant.SCORE.equals(columnName) || MatchAnalysisConstant.ATTRIBUTE_SCORES.equals(columnName) || MatchAnalysisConstant.BLOCK_KEY.equals(columnName)) { return true; } return false; } /** * refresh data Table. * * @param analysis * * @param matchResultConsumer */ public static void refreshDataTable(ModelElement analysis, List<Object[]> resultData) { ITDQRepositoryService tdqRepService = null; if (GlobalServiceRegister.getDefault().isServiceRegistered(ITDQRepositoryService.class)) { tdqRepService = (ITDQRepositoryService) GlobalServiceRegister.getDefault().getService(ITDQRepositoryService.class); } if (tdqRepService != null) { tdqRepService.refreshTableWithResult(analysis, resultData); } } /** * sorting the result data by GID,master * * @param allColumns * @param resultData * @return */ public static List<Object[]> sortResultByGID(String[] allColumns, List<Object[]> resultData) { int gidIndex = -1; int masterIndex = -1; for (int i = 0; i < allColumns.length; i++) { if (StringUtils.endsWithIgnoreCase(allColumns[i], MatchAnalysisConstant.GID)) { gidIndex = i; } else if (StringUtils.endsWithIgnoreCase(allColumns[i], MatchAnalysisConstant.MASTER)) { masterIndex = i; } } // Sort by master first final int masterIdx = masterIndex; Comparator<Object[]> comparator = new Comparator<Object[]>() { @Override public int compare(Object[] row1, Object[] row2) { return ((String) row2[masterIdx]).compareTo((String) row1[masterIdx]); } }; java.util.Collections.sort(resultData, comparator); insertionSort(resultData, gidIndex); return resultData; } public static void insertionSort(List<Object[]> data, int gidIdx) { int in, out; for (out = 1; out < data.size(); out++) { Object[] temp = data.get(out); in = out; while (in > 0 && !isSameGroup(data.get(in - 1)[gidIdx].toString(), (temp[gidIdx]).toString())) { data.set(in, data.get(in - 1)); --in; } data.set(in, temp); } } /** * * @param group ID one * @param group ID two. * @return true if they are the same group considering the two merged groups (groupID contains two more UUID). */ public static boolean isSameGroup(String groupID1, String groupID2) { if (groupID1 == null || groupID1.trim().equals(StringUtils.EMPTY) || groupID2 == null || groupID2.trim().equals(StringUtils.EMPTY)) { return false; } String[] ids1 = StringUtils.splitByWholeSeparatorPreserveAllTokens(groupID1, PluginConstant.COMMA_STRING); String[] ids2 = StringUtils.splitByWholeSeparatorPreserveAllTokens(groupID2, PluginConstant.COMMA_STRING); for (String id1 : ids1) { for (String id2 : ids2) { if (id1.equalsIgnoreCase(id2)) { return true; } } } return false; } public static List<Object[]> sortDataByColumn(final SortState sortState, List<Object[]> resultData, final List<ModelElement> columns) { Comparator<Object[]> comparator = new Comparator<Object[]>() { ISortComparator sortComparator = null; @Override public int compare(Object[] row1, Object[] row2) { // when the user select the special column which has no result yet if ((row1.length - 1) < sortState.getSelectedColumnIndex()) { return 0; } Object value1 = row1[sortState.getSelectedColumnIndex()]; Object value2 = row2[sortState.getSelectedColumnIndex()]; // get the sort comparator according to its type. try { if (sortComparator == null) { sortComparator = getSortComparator(value1, sortState.getSelectedColumnIndex()); } } catch (ParseException e) { return 0; } if (sortComparator == null) { return 0; } switch (sortState.getCurrentSortDirection()) { case ASC: return sortComparator.compareTwo(value1, value2); case DESC: return sortComparator.compareTwo(value2, value1); default: return 0; } } // when the columns is TdColumn, use its sqlType to compare private ISortComparator getSortComparator(Object object, int index) throws ParseException { if (!(columns.get(0) instanceof TdColumn)) {// if not a db column return SortComparator.getSortComparator(Types.VARCHAR); } if (columns.size() <= index) {// special columns if (sortState.isGroupSizeColumn()) {// group size is integer type return SortComparator.getSortComparator(Types.INTEGER); } else { return SortComparator.getSortComparator(Types.VARCHAR); } } TdColumn element = (TdColumn) columns.get(index); return SortComparator.getSortComparator(element.getSqlDataType().getJavaDataType()); } }; java.util.Collections.sort(resultData, comparator); return resultData; } public static boolean isSurvivorShipFunctionConsistentWithType(String algorithmType, String dataType) { SurvivorShipAlgorithmEnum survivorShipAlgorithm = SurvivorShipAlgorithmEnum.getTypeBySavedValue(algorithmType); switch (survivorShipAlgorithm) { case LARGEST: case SMALLEST: // compare column's talend type || compare DefaultSurvivorShipDataTypeEnum own type return JavaTypesManager.isNumber(dataType) || DefaultSurvivorShipDataTypeEnum.NUMBER.getValue().equals(dataType); case LONGEST: case SHORTEST: return JavaTypesManager.isString(dataType) || DefaultSurvivorShipDataTypeEnum.STRING.getValue().equals(dataType); case PREFER_TRUE: case PREFER_FALSE: return JavaTypesManager.isBoolean(dataType) || DefaultSurvivorShipDataTypeEnum.BOOLEAN.getValue().equals(dataType); default: return true; } } }
43.103641
128
0.637705
5e1db603d81553a7318cbe0e0f184156cd240368
161
package sti.software.engineering.reading.assistant.ui; import android.view.View; public interface Hostable { void onInflate(View view, String screen); }
16.1
54
0.770186
f3ccfb43d7a0b999f2fd056bb9273ec59541dc98
1,959
package com.scalar.kelpie.modules; import com.scalar.kelpie.config.Config; import com.scalar.kelpie.stats.Stats; /** Processor executes operations. */ public abstract class Processor extends Module { private Stats stats; public Processor(Config config) { super(config); } public abstract void execute(); /** * Returns {@link com.scalar.kelpie.stats.Stats}. * * @return stats {@link com.scalar.kelpie.stats.Stats} */ public Stats getStats() { return stats; } /** * Sets {@link com.scalar.kelpie.stats.Stats}. * * @param stats {@link com.scalar.kelpie.stats.Stats} */ public void setStats(Stats stats) { this.stats = stats; } @Override protected void logTrace(String message) { super.logTrace(prependThreadId(message)); } @Override protected void logTrace(String message, Throwable e) { super.logTrace(prependThreadId(message), e); } @Override protected void logDebug(String message) { super.logDebug(prependThreadId(message)); } @Override protected void logDebug(String message, Throwable e) { super.logDebug(prependThreadId(message), e); } @Override protected void logInfo(String message) { super.logInfo(prependThreadId(message)); } @Override protected void logInfo(String message, Throwable e) { super.logInfo(prependThreadId(message), e); } @Override protected void logWarn(String message) { super.logWarn(prependThreadId(message)); } @Override protected void logWarn(String message, Throwable e) { super.logWarn(prependThreadId(message), e); } @Override protected void logError(String message) { super.logError(prependThreadId(message)); } @Override protected void logError(String message, Throwable e) { super.logError(prependThreadId(message), e); } private String prependThreadId(String message) { return "[Thread " + Thread.currentThread().getId() + "] " + message; } }
22.261364
72
0.695253
62e13c872415bb1eace482dda240f0b858d1ac24
773
package com.nt.rest; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Produces({ "application/xml", "application/json" }) public interface PatientService { @GET @Path("/patients/{id}/") Patient getPatient(@PathParam("id") String id); @PUT @Path("/patients/") Response updatePatient(Patient patient); @POST @Path("/patients/") Response addPatient(Patient patient); @DELETE @Path("/patients/{id}/") Response deletePatients(@PathParam("id") String id); @Path("/prescriptions/{id}") Prescription getPrescription(@PathParam("id") String prescriptionId); }
23.424242
71
0.698577
0f805f0634d5f2256f2df3441eb12e34d50c1428
539
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.util; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface DiskCache { public boolean exists(String key); public File getFile(String key); public InputStream getInputStream(String key) throws IOException; public void store(String key, InputStream is); public void invalidate(String key); public void cleanup(); public void clear(); }
17.387097
69
0.714286
3f88f1d759a82417d279be155adcffeebbf23c66
2,688
package org.parseerror; import com.sun.faces.config.ConfigureListener; import com.sun.faces.config.FacesInitializer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.web.jsf.el.SpringBeanFacesELResolver; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletException; import java.util.HashSet; import java.util.Set; @SpringBootApplication(exclude = DispatcherServletAutoConfiguration.class) public class SpringJsfExampleApplication implements ServletContextInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml"); servletContext.setInitParameter("javax.faces.PARTIAL_STATE_SAVING_METHOD", "true"); servletContext.setInitParameter("javax.faces.PROJECT_STAGE", "Development"); servletContext.setInitParameter("facelets.DEVELOPMENT", "true"); servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "1"); Set<Class<?>> clazz = new HashSet<Class<?>>(); clazz.add(SpringJsfExampleApplication.class); // dummy, enables InitFacesContext FacesInitializer facesInitializer = new FacesInitializer(); facesInitializer.onStartup(clazz, servletContext); } @Bean public ServletListenerRegistrationBean<JsfApplicationObjectConfigureListener> jsfConfigureListener() { return new ServletListenerRegistrationBean<>( new JsfApplicationObjectConfigureListener()); } static class JsfApplicationObjectConfigureListener extends ConfigureListener { @Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application app = factory.getApplication(); app.addELResolver(new SpringBeanFacesELResolver()); } } public static void main(String[] args) { SpringApplication.run(SpringJsfExampleApplication.class, args); } }
38.4
122
0.779018
c08630c7c8936f1ebb2c6b8b0d5c239adbc28586
6,177
package ca.sheridancollege.vu8.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import ca.sheridancollege.vu8.beans.Announcement; import ca.sheridancollege.vu8.beans.Post; import ca.sheridancollege.vu8.beans.Topic; import ca.sheridancollege.vu8.beans.UserRegistration; import ca.sheridancollege.vu8.database.DatabaseAccess; // Student: Bao Nam Vu - Assignment 3 - Basic Description Of Application // Port 8080 // Normal Flow: index -> login(may access register) -> home(may access admin) -> topic // You can test on 2 accounts // "user" / pass:"pass" /user role // "admin" / pass:"pass" /user role and manager role // Application Functions // + Announcements -Read // -Post new one(only manager) // -Delete (only manager, NEED to use refresh button to update)- Apply JavaScript // + Topic -Read // -Post new one(only manager) // + Topic-Post -Read // -Post new one // + List User Name -Read (only manager) - Apply JavaScript // Some button you can miss: // - backToDiscuss in topic page // - adminPage (Top-Left) in home page, NormalUserPage button in admin page (Top-Left) // - delete announcement (X symbol) in admin page // - list button (list user) in admin page @Controller public class MyController { @Autowired JdbcUserDetailsManager jdbcUserDetailsManager; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private DatabaseAccess db; @GetMapping("/login") public String getLogin() { return "login"; } @GetMapping("/") public String getIndex() { return "index"; } @GetMapping("/home") public String getHome(Model model) { model.addAttribute("addedTopic", new Topic()); model.addAttribute("topicList", db.takeTopicList()); model.addAttribute("annList",db.takeAnnList()); return "home"; } // When opening a specific topic @GetMapping("/topic/{topicNo}") public String getPost(Model model, @PathVariable int topicNo) { model.addAttribute("postList", db.takePostList(topicNo)); model.addAttribute("topic", db.takeTopicById(topicNo)); model.addAttribute("addedPost", new Post()); return "topic"; } @PostMapping("/addTopic") public String addTopic(@ModelAttribute Topic addedTopic) { // Get current log-in user in Spring Security String username; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { username = ((UserDetails) principal).getUsername(); } else { username = principal.toString(); } addedTopic.setTopicCreatedPerson(username); db.addTopic(addedTopic); return "redirect:/admin"; } @PostMapping("/addPost/{topicNo}") public String addPost(@ModelAttribute Post post, @PathVariable int topicNo) { // Get current log-in user in Spring Security String username; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { username = ((UserDetails) principal).getUsername(); } else { username = principal.toString(); } post.setPostCreatedPerson(username); ; db.addPost(post, topicNo); String redirect = "redirect:/topic/" + topicNo; return redirect; } @GetMapping("/admin") public String getAdmin(Model model) { model.addAttribute("addedAnn", new Announcement()); model.addAttribute("annList",db.takeAnnList()); model.addAttribute("addedTopic", new Topic()); model.addAttribute("topicList", db.takeTopicList()); return "admin"; } @PostMapping("/addAnnouncement") public String addAnnouncement(@ModelAttribute Announcement addedAnn) { // Get current log-in user in Spring Security String username; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { username = ((UserDetails) principal).getUsername(); } else { username = principal.toString(); } addedAnn.setAnnCreatedPerson(username); db.addAnnouncement(addedAnn); return "redirect:/admin"; } @GetMapping("/deleteAnn/{id}") @ResponseBody public String deleteAnn(@PathVariable int id){ db.deleteAnnouncement(id); return "redirect:/admin"; } @GetMapping(value="/getUserList", produces = "application/json") @ResponseBody public ArrayList<String> getUserList(){ return db.getUserList(); } @GetMapping("/register") public String register(Model model, UserRegistration user) { model.addAttribute("user", user); return "register"; } @PostMapping("/register") public String processRegister(@ModelAttribute UserRegistration user) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword()); User newuser = new User(user.getUsername(), encodedPassword, authorities); jdbcUserDetailsManager.createUser(newuser); return "redirect:/"; } @GetMapping("/access-denied") public String accessDenied() { return "/error/access-denied.html"; } }
33.93956
94
0.728509
67460c854ad27cc9825190af9d4fc33242e71bb8
916
/* * 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 thump.game.play.action; import thump.game.Player; import thump.game.maplevel.MapObject; import thump.game.play.PSprite; /** * * @author mark */ public class A_PlayerScream implements Action { public A_PlayerScream() { } @Override public void doAction(MapObject mo) { // // Default death sound. // SfxEnum sound = sfx_pldeth; // // if ((game.gameMode == GameMode.COMMERCIAL) // && (mo.health < -50)) { // // IF THE PLAYER DIES // // LESS THAN -50% WITHOUT GIBBING // sound = sfx_pdiehi; // } // // game.sound.S_StartSound(mo, sound); } @Override public void doAction(Player player, PSprite psp) {} }
22.9
79
0.612445
42ffd724905154dc05abb9a88a41fecb5ed2e636
2,880
package jwt4j; import com.google.gson.JsonObject; import jwt4j.exceptions.AlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Map; import java.util.StringJoiner; public class JWTEncoder { private final Algorithm algorithm; private final byte[] secret; private final String base64JsonHeader; private final RegisteredClaimsValidator registeredClaimsValidator; public JWTEncoder(final Algorithm algorithm, final byte[] secret, final RegisteredClaimsValidator registeredClaimsValidator) { this.algorithm = algorithm; this.secret = secret; this.base64JsonHeader = encodeHeader(); this.registeredClaimsValidator = registeredClaimsValidator; } private String encodeHeader() { final JsonObject headerJsonObject = new JsonObject(); headerJsonObject.addProperty(JWTConstants.TYPE, JWTConstants.JWT); headerJsonObject.addProperty(JWTConstants.ALGORITHM, algorithm.name()); return toBase64Json(headerJsonObject); } public String encode(final Map<String, String> claims) { registeredClaimsValidator.validate(claims); final String base64JsonPayload = encodePayload(claims); final StringJoiner stringJoiner = new StringJoiner(JWTConstants.DELIMITER) .add(base64JsonHeader) .add(base64JsonPayload); if (algorithm != Algorithm.none) { stringJoiner.add(sign(stringJoiner.toString())); } else { stringJoiner.add(""); } return stringJoiner.toString(); } private String encodePayload(final Map<String, String> claims) { final JsonObject payloadJsonObject = new JsonObject(); claims.forEach((claim, value) -> { payloadJsonObject.addProperty(claim, value); }); return toBase64Json(payloadJsonObject); } private String sign(final String message) { try { final Mac mac = Mac.getInstance(algorithm.name); mac.init(new SecretKeySpec(secret, algorithm.name)); final String signature = new String(Base64.getEncoder().encodeToString(mac.doFinal(message.getBytes()))); return signature; } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalArgumentException e) { throw new AlgorithmException(e); } } private String toBase64Json(final JsonObject jsonObject) { final String base64ObjectJson = Base64.getEncoder() .encodeToString(jsonObject.toString().getBytes(StandardCharsets.UTF_8)); return base64ObjectJson; } }
33.488372
117
0.681944
c1f516f6ad5ee1f7cb3c38880d9ca94c3faec20c
2,666
package org.prosolo.services.nodes.data.organization; import org.prosolo.services.common.observable.StandardObservable; import org.prosolo.services.nodes.data.ObjectStatus; import org.prosolo.services.nodes.data.ObjectStatusTransitions; import java.io.Serializable; /** * @author stefanvuckovic * @date 2017-11-14 * @since 1.2.0 */ public class LearningStageData extends StandardObservable implements Serializable { private static final long serialVersionUID = 3654673062588736467L; private long id; private String title; private int order; private boolean used; private ObjectStatus status = ObjectStatus.UP_TO_DATE; public LearningStageData(boolean listenChanges) { if (listenChanges) { startObservingChanges(); } } public LearningStageData(long id, String title, int order, boolean used, boolean listenChanges) { this.id = id; this.title = title; this.order = order; this.used = used; if (listenChanges) { startObservingChanges(); } } public ObjectStatus getStatus() { return status; } public void setStatus(ObjectStatus status) { this.status = status; } public String getTitle() { return title; } public void setTitle(String title) { observeAttributeChange("title", this.title, title); this.title = title; if (listenChanges) { if (isTitleChanged()) { setStatus(ObjectStatusTransitions.changeTransition(getStatus())); } else if (!hasObjectChanged()) { setStatus(ObjectStatusTransitions.upToDateTransition(getStatus())); } } } public void setOrder(int order) { observeAttributeChange("order", this.order, order); this.order = order; if (listenChanges) { if (isOrderChanged()) { setStatus(ObjectStatusTransitions.changeTransition(getStatus())); } else if (!hasObjectChanged()) { setStatus(ObjectStatusTransitions.upToDateTransition(getStatus())); } } } public int getOrder() { return order; } public boolean isUsed() { return used; } public void setUsed(boolean used) { this.used = used; } public boolean isTitleChanged() { return changedAttributes.containsKey("title"); } public boolean isOrderChanged() { return changedAttributes.containsKey("order"); } public long getId() { return id; } public void setId(long id) { this.id = id; } }
25.634615
101
0.623406
6a54b4e02b0e8eb0f4ac91ee2e727b1c88b41e93
3,547
import java.util.*; import java.io.*; /* Mighty Cohadar */ public class GG { static class Ret { final int last; final long count; Ret(int last, long count) { this.last = last; this.count = count; } public String toString() { return String.format("(l=%d, c=%d)", last, count); } } private final boolean[] G; private final int n; private final int m; private final Map<String, ArrayList<Ret>> map; public GG(boolean[] G, int n, int m) { this.G = G; this.n = n; this.m = m; this.map = new HashMap<>(); } // N is always sorted ArrayList<Ret> count(int g, ArrayList<Integer> N) { String key = null; if (g < 5) { StringBuilder sb = new StringBuilder(); for (int x : N) { sb.append(x); sb.append('.'); } key = sb.toString(); ArrayList<Ret> ret = map.get(key); if (ret != null) { return ret; } } ArrayList<Ret> ret = new ArrayList<>(); if (g == 1) { if (G[0]) { ret.add(new Ret(N.get(0), 1)); } else { ret.add(new Ret(N.get(1), 1)); } if (key != null) { map.put(key, ret); } return ret; } if (G[g - 1]) { long[] cnt = new long[N.size()]; for (int i = 0; i < N.size(); i++) { ArrayList<Integer> N2 = (ArrayList<Integer>)N.clone(); N2.remove(i); ArrayList<Ret> r1 = count(g - 1, N2); boolean change = false; for (Ret r : r1) { if (r.last > N.get(i)) { cnt[i] = (cnt[i] + r.count) % m; change = true; } } if (!change) { break; } } for (int i = 0; i < cnt.length; i++) { if (cnt[i] > 0) { ret.add(new Ret(N.get(i), cnt[i])); } } if (key != null) { map.put(key, ret); } return ret; } else { long[] cnt = new long[N.size()]; for (int i = N.size() - 1; i >= 0; i--) { ArrayList<Integer> N2 = (ArrayList<Integer>)N.clone(); N2.remove(i); ArrayList<Ret> r1 = count(g - 1, N2); boolean change = false; for (Ret r : r1) { if (r.last < N.get(i)) { cnt[i] = (cnt[i] + r.count) % m; change = true; } } if (!change) { break; } } for (int i = 0; i < cnt.length; i++) { if (cnt[i] > 0) { ret.add(new Ret(N.get(i), cnt[i])); } } if (key != null) { map.put(key, ret); } return ret; } } public long count() { ArrayList<Integer> N = new ArrayList<>(); for (int i = 0; i < n; i++) { N.add(i); } ArrayList<Ret> ret = count(G.length, N); long cnt = 0; for (Ret r : ret) { cnt = (cnt + r.count) % m; debug(r); } return cnt; } // 2491930 LLGLLLGGLGLG // 302358 LLGLLLGGLGL // 39095 LLGLLLGGLG public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] _nm = scanner.nextLine().split(" "); int n = Integer.valueOf(_nm[0]); int m = Integer.valueOf(_nm[1]); assert 2 <= n && n <= 3000 : "out of range, n: " + n; assert 1 <= m && m <= 1e9 : "out of range, m: " + m; char[] S = scanner.nextLine().toCharArray(); assert S.length == n - 1; boolean[] G = new boolean[n - 1]; for (int i = 0; i < S.length; i++) { G[i] = (S[i] == 'G'); } GG o = new GG(G, n, m); System.out.println(o.count()); } static boolean DEBUG = true; static void debug(Object...os) { if (!DEBUG) { return; } System.err.printf("%.65536s\n", Arrays.deepToString(os)); } static void debug2(ArrayList<Ret> R) { if (!DEBUG) { return; } StringBuilder sb = new StringBuilder(); for (Ret r : R) { sb.append(r); } System.err.printf("\t\tret %.65536s\n", sb); } }
21.628049
59
0.524387
ca3da932b3ee33ed00b07c66834a5922a16aad96
8,319
package com.google.android.gms.internal; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.text.TextUtils; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @C1507ey /* renamed from: com.google.android.gms.internal.cc */ public final class C1364cc { /* renamed from: pQ */ public static final C1374cd f2786pQ = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { } }; /* renamed from: pR */ public static final C1374cd f2787pR = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { String str = map.get("urls"); if (TextUtils.isEmpty(str)) { C1607gr.m4709W("URLs missing in canOpenURLs GMSG."); return; } String[] split = str.split(","); HashMap hashMap = new HashMap(); PackageManager packageManager = guVar.getContext().getPackageManager(); for (String str2 : split) { String[] split2 = str2.split(";", 2); boolean z = true; if (packageManager.resolveActivity(new Intent(split2.length > 1 ? split2[1].trim() : "android.intent.action.VIEW", Uri.parse(split2[0].trim())), 65536) == null) { z = false; } hashMap.put(str2, Boolean.valueOf(z)); } guVar.mo15418a("openableURLs", (Map<String, ?>) hashMap); } }; /* renamed from: pS */ public static final C1374cd f2788pS = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { String str; PackageManager packageManager = guVar.getContext().getPackageManager(); try { try { JSONArray jSONArray = new JSONObject(map.get("data")).getJSONArray("intents"); JSONObject jSONObject = new JSONObject(); for (int i = 0; i < jSONArray.length(); i++) { try { JSONObject jSONObject2 = jSONArray.getJSONObject(i); String optString = jSONObject2.optString("id"); String optString2 = jSONObject2.optString("u"); String optString3 = jSONObject2.optString("i"); String optString4 = jSONObject2.optString("m"); String optString5 = jSONObject2.optString("p"); String optString6 = jSONObject2.optString("c"); jSONObject2.optString("f"); jSONObject2.optString("e"); Intent intent = new Intent(); if (!TextUtils.isEmpty(optString2)) { intent.setData(Uri.parse(optString2)); } if (!TextUtils.isEmpty(optString3)) { intent.setAction(optString3); } if (!TextUtils.isEmpty(optString4)) { intent.setType(optString4); } if (!TextUtils.isEmpty(optString5)) { intent.setPackage(optString5); } boolean z = true; if (!TextUtils.isEmpty(optString6)) { String[] split = optString6.split("/", 2); if (split.length == 2) { intent.setComponent(new ComponentName(split[0], split[1])); } } if (packageManager.resolveActivity(intent, 65536) == null) { z = false; } try { jSONObject.put(optString, z); } catch (JSONException e) { e = e; str = "Error constructing openable urls response."; } } catch (JSONException e2) { e = e2; str = "Error parsing the intent data."; C1607gr.m4711b(str, e); } } guVar.mo15421b("openableIntents", jSONObject); } catch (JSONException e3) { guVar.mo15421b("openableIntents", new JSONObject()); } } catch (JSONException e4) { guVar.mo15421b("openableIntents", new JSONObject()); } } }; /* renamed from: pT */ public static final C1374cd f2789pT = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { String str = map.get("u"); if (str == null) { C1607gr.m4709W("URL missing from click GMSG."); return; } Uri parse = Uri.parse(str); try { C1788k dF = guVar.mo15428dF(); if (dF != null && dF.mo15947b(parse)) { parse = dF.mo15944a(parse, guVar.getContext()); } } catch (C1828l e) { C1607gr.m4709W("Unable to append parameter to URL: " + str); } new C1605gp(guVar.getContext(), guVar.mo15429dG().f3554wS, parse.toString()).start(); } }; /* renamed from: pU */ public static final C1374cd f2790pU = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { C1445dp dC = guVar.mo15425dC(); if (dC == null) { C1607gr.m4709W("A GMSG tried to close something that wasn't an overlay."); } else { dC.close(); } } }; /* renamed from: pV */ public static final C1374cd f2791pV = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { guVar.mo15438q("1".equals(map.get("custom_close"))); } }; /* renamed from: pW */ public static final C1374cd f2792pW = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { String str = map.get("u"); if (str == null) { C1607gr.m4709W("URL missing from httpTrack GMSG."); } else { new C1605gp(guVar.getContext(), guVar.mo15429dG().f3554wS, str).start(); } } }; /* renamed from: pX */ public static final C1374cd f2793pX = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { C1607gr.m4707U("Received log message: " + map.get("string")); } }; /* renamed from: pY */ public static final C1374cd f2794pY = new C1374cd() { /* renamed from: a */ public void mo14738a(C1610gu guVar, Map<String, String> map) { String str = map.get("tx"); String str2 = map.get("ty"); String str3 = map.get("td"); try { int parseInt = Integer.parseInt(str); int parseInt2 = Integer.parseInt(str2); int parseInt3 = Integer.parseInt(str3); C1788k dF = guVar.mo15428dF(); if (dF != null) { dF.mo15943C().mo15351a(parseInt, parseInt2, parseInt3); } } catch (NumberFormatException e) { C1607gr.m4709W("Could not parse touch parameters from gmsg."); } } }; /* renamed from: pZ */ public static final C1374cd f2795pZ = new C1380cj(); }
40.980296
178
0.479745
e3b434ed0a53ea75d69c6c4b732446dbbe3fd969
26,290
/* * Copyright 2016 Davide Maestroni * * 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.dm.jrt.android.method; import android.content.Context; import com.github.dm.jrt.android.channel.AndroidChannels; import com.github.dm.jrt.android.channel.ParcelableSelectable; import com.github.dm.jrt.android.core.JRoutineService; import com.github.dm.jrt.android.core.ServiceContext; import com.github.dm.jrt.android.core.config.ServiceConfigurable; import com.github.dm.jrt.android.core.config.ServiceConfiguration; import com.github.dm.jrt.android.core.config.ServiceConfiguration.Builder; import com.github.dm.jrt.android.core.invocation.ContextInvocation; import com.github.dm.jrt.android.object.ContextInvocationTarget; import com.github.dm.jrt.android.object.JRoutineServiceObject; import com.github.dm.jrt.core.JRoutineCore; import com.github.dm.jrt.core.builder.ChannelBuilder; import com.github.dm.jrt.core.channel.Channel; import com.github.dm.jrt.core.common.RoutineException; import com.github.dm.jrt.core.config.InvocationConfiguration; import com.github.dm.jrt.core.invocation.InvocationException; import com.github.dm.jrt.core.routine.InvocationMode; import com.github.dm.jrt.core.routine.Routine; import com.github.dm.jrt.core.util.ConstantConditions; import com.github.dm.jrt.core.util.Reflection; import com.github.dm.jrt.method.RoutineMethod; import com.github.dm.jrt.method.annotation.In; import com.github.dm.jrt.method.annotation.Out; import com.github.dm.jrt.object.config.ObjectConfigurable; import com.github.dm.jrt.object.config.ObjectConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static com.github.dm.jrt.android.core.invocation.TargetInvocationFactory.factoryOf; import static com.github.dm.jrt.core.util.Reflection.asArgs; import static com.github.dm.jrt.core.util.Reflection.boxingClass; import static com.github.dm.jrt.core.util.Reflection.boxingDefault; import static com.github.dm.jrt.core.util.Reflection.cloneArgs; import static com.github.dm.jrt.core.util.Reflection.findBestMatchingMethod; /** * This class provides an easy way to implement a routine running in a dedicated Android Service, * which can be combined in complex ways with other ones. * <h2>How to implement a routine</h2> * The class behaves like a {@link RoutineMethod} with a few differences. In order to run in a * Service, the implementing class must be static. Moreover, each constructor must have the Service * context as first argument and all the other arguments must be among the ones supported by the * {@link android.os.Parcel#writeValue(Object)} method. * <br> * In case a remote Service is employed (that is, a Service running in a different process), the * same restriction applies to the method parameters (other than input and output channels) and * to the input and output data. * <h2>How to access the Android Context</h2> * It is possible to get access to the Android Context (that is the Service instance) from inside * the routine by calling the {@code getContext()} method. Like, for instance: * <pre> * <code> * * public static class MyMethod extends ServiceRoutineMethod { * * public MyMethod(final ServiceContext context) { * super(context); * } * * void run(&#64;In final Channel&lt;?, String&gt; input, * &#64;Out final Channel&lt;String, ?&gt; output) { * final MyService service = (MyService) getContext(); * // do it * } * } * </code> * </pre> * <p> * Created by davide-maestroni on 08/18/2016. */ @SuppressWarnings("WeakerAccess") public class ServiceRoutineMethod extends RoutineMethod implements ServiceConfigurable<ServiceRoutineMethod> { private final Object[] mArgs; private final ServiceContext mContext; private final ThreadLocal<Channel<?, ?>> mLocalChannel = new ThreadLocal<Channel<?, ?>>(); private final ThreadLocal<Context> mLocalContext = new ThreadLocal<Context>(); private final ThreadLocal<Boolean> mLocalIgnore = new ThreadLocal<Boolean>(); private ServiceConfiguration mConfiguration = ServiceConfiguration.defaultConfiguration(); private Class<?> mReturnType; /** * Constructor. * * @param context the Service context. */ public ServiceRoutineMethod(@NotNull final ServiceContext context) { this(context, (Object[]) null); } /** * Constructor. * * @param context the Service context. * @param args the constructor arguments. */ public ServiceRoutineMethod(@NotNull final ServiceContext context, @Nullable final Object... args) { mContext = ConstantConditions.notNull("Service context", context); final Class<? extends RoutineMethod> type = getClass(); if (!Reflection.hasStaticScope(type)) { throw new IllegalStateException( "the method class must have a static scope: " + type.getName()); } final Object[] additionalArgs; final Object[] safeArgs = Reflection.asArgs(args); if (type.isAnonymousClass()) { if (safeArgs.length > 0) { additionalArgs = new Object[safeArgs.length + 1]; System.arraycopy(safeArgs, 0, additionalArgs, 1, safeArgs.length); additionalArgs[0] = safeArgs; } else { additionalArgs = safeArgs; } } else { additionalArgs = cloneArgs(safeArgs); } final Object[] constructorArgs = new Object[additionalArgs.length + 1]; System.arraycopy(additionalArgs, 0, constructorArgs, 1, additionalArgs.length); constructorArgs[0] = context; Reflection.findBestMatchingConstructor(type, constructorArgs); mArgs = additionalArgs; } /** * Builds a Service object routine method by wrapping the specified static method. * * @param context the Service context. * @param method the method. * @return the routine method instance. * @throws java.lang.IllegalArgumentException if the specified method is not static. */ @NotNull public static ObjectServiceRoutineMethod from(@NotNull final ServiceContext context, @NotNull final Method method) { if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException("the method is not static: " + method); } return from(context, ContextInvocationTarget.classOfType(method.getDeclaringClass()), method); } /** * Builds a Service object routine method by wrapping a method of the specified target. * * @param context the Service context. * @param target the invocation target. * @param method the method. * @return the routine method instance. * @throws java.lang.IllegalArgumentException if the specified method is not implemented by the * target instance. */ @NotNull public static ObjectServiceRoutineMethod from(@NotNull final ServiceContext context, @NotNull final ContextInvocationTarget<?> target, @NotNull final Method method) { if (!method.getDeclaringClass().isAssignableFrom(target.getTargetClass())) { throw new IllegalArgumentException( "the method is not applicable to the specified target class: " + target.getTargetClass()); } return new ObjectServiceRoutineMethod(context, target, method); } /** * Builds a Service object routine method by wrapping a method of the specified target. * * @param context the Service context. * @param target the invocation target. * @param name the method name. * @param parameterTypes the method parameter types. * @return the routine method instance. * @throws java.lang.NoSuchMethodException if no method with the specified signature is found. */ @NotNull public static ObjectServiceRoutineMethod from(@NotNull final ServiceContext context, @NotNull final ContextInvocationTarget<?> target, @NotNull final String name, @Nullable final Class<?>... parameterTypes) throws NoSuchMethodException { return from(context, target, target.getTargetClass().getMethod(name, parameterTypes)); } @NotNull @Override public ServiceRoutineMethod apply(@NotNull final InvocationConfiguration configuration) { return (ServiceRoutineMethod) super.apply(configuration); } @NotNull @Override @SuppressWarnings("unchecked") public InvocationConfiguration.Builder<? extends ServiceRoutineMethod> applyInvocationConfiguration() { return (InvocationConfiguration.Builder<? extends ServiceRoutineMethod>) super .applyInvocationConfiguration(); } /** * Calls the routine. * <br> * The output channel will produced the data returned by the method. In case the method does not * return any output, the channel will be anyway notified of invocation abortion and completion. * <p> * Note that the specific method will be selected based on the specified parameters. If no * matching method is found, the call will fail with an exception. * * @param params the parameters. * @param <OUT> the output data type. * @return the output channel instance. */ @NotNull @Override public <OUT> Channel<?, OUT> call(@Nullable final Object... params) { final Object[] safeParams = asArgs(params); return call(findBestMatchingMethod(getClass(), safeParams), InvocationMode.ASYNC, safeParams); } /** * Calls the routine in parallel mode. * <br> * The output channel will produced the data returned by the method. In case the method does not * return any output, the channel will be anyway notified of invocation abortion and completion. * <p> * Note that the specific method will be selected based on the specified parameters. If no * matching method is found, the call will fail with an exception. * * @param params the parameters. * @param <OUT> the output data type. * @return the output channel instance. * @see com.github.dm.jrt.core.routine.Routine Routine */ @NotNull @Override public <OUT> Channel<?, OUT> callParallel(@Nullable final Object... params) { final Object[] safeParams = asArgs(params); return call(findBestMatchingMethod(getClass(), safeParams), InvocationMode.PARALLEL, safeParams); } /** * Tells the routine to ignore the method return value, that is, it will not be passed to the * output channel. * * @param <OUT> the output data type. * @return the return value. */ @SuppressWarnings("unchecked") protected <OUT> OUT ignoreReturnValue() { mLocalIgnore.set(true); return (OUT) boxingDefault(mReturnType); } /** * Returns the input channel which is ready to produce data. If the method takes no input channel * as parameter, null will be returned. * <p> * Note this method will return null if called outside the routine method invocation or from a * different thread. * * @param <IN> the input data type. * @return the input channel producing data or null. */ @Override @SuppressWarnings("unchecked") protected <IN> Channel<?, IN> switchInput() { return (Channel<?, IN>) mLocalChannel.get(); } @NotNull @Override public ServiceRoutineMethod apply(@NotNull final ServiceConfiguration configuration) { mConfiguration = ConstantConditions.notNull("Service configuration", configuration); return this; } @NotNull @Override public Builder<? extends ServiceRoutineMethod> applyServiceConfiguration() { return new Builder<ServiceRoutineMethod>(this, mConfiguration); } /** * Returns the Android Context (that is, the Service instance). * <p> * Note this method will return null if called outside the routine method invocation or from a * different thread. * * @return the Context. */ protected Context getContext() { return mLocalContext.get(); } /** * Returns the Service configuration. * * @return the Service configuration. */ @NotNull protected ServiceConfiguration getServiceConfiguration() { return mConfiguration; } @NotNull @SuppressWarnings("unchecked") private <OUT> Channel<?, OUT> call(@NotNull final Method method, @NotNull final InvocationMode mode, @NotNull final Object[] params) { final ArrayList<Channel<?, ?>> inputChannels = new ArrayList<Channel<?, ?>>(); final ArrayList<Channel<?, ?>> outputChannels = new ArrayList<Channel<?, ?>>(); final Annotation[][] annotations = method.getParameterAnnotations(); for (int i = 0; i < params.length; ++i) { final Object param = params[i]; final Class<? extends Annotation> annotationType = getAnnotationType(param, annotations[i]); if (annotationType == In.class) { params[i] = InputChannelPlaceHolder.class; inputChannels.add((Channel<?, ?>) param); } else if (annotationType == Out.class) { params[i] = OutputChannelPlaceHolder.class; outputChannels.add((Channel<?, ?>) param); } } final ChannelBuilder channelBuilder = JRoutineCore.io(); final Channel<OUT, OUT> resultChannel = channelBuilder.buildChannel(); outputChannels.add(resultChannel); final Channel<?, ? extends ParcelableSelectable<Object>> inputChannel = (!inputChannels.isEmpty()) ? AndroidChannels.mergeParcelable(inputChannels).buildChannels() : channelBuilder.<ParcelableSelectable<Object>>of(); final Channel<ParcelableSelectable<Object>, ParcelableSelectable<Object>> outputChannel = mode.invoke(JRoutineService.on(mContext) .with(factoryOf(ServiceInvocation.class, getClass(), mArgs, params)) .apply(getConfiguration()) .apply(getServiceConfiguration())).pass(inputChannel).close(); final Map<Integer, Channel<?, Object>> channelMap = AndroidChannels.selectOutput(0, outputChannels.size(), outputChannel).buildChannels(); for (final Entry<Integer, Channel<?, Object>> entry : channelMap.entrySet()) { entry.getValue().bind((Channel<Object, Object>) outputChannels.get(entry.getKey())).close(); } return resultChannel; } private boolean isIgnoreReturnValue() { return (mLocalIgnore.get() != null); } private void resetIgnoreReturnValue() { mLocalIgnore.set(null); } private void setLocalContext(@Nullable final Context context) { mLocalContext.set(context); } private void setLocalInput(@Nullable final Channel<?, ?> inputChannel) { mLocalChannel.set(inputChannel); } private void setReturnType(@NotNull final Class<?> returnType) { mReturnType = returnType; } /** * Implementation of a Service routine method wrapping an object method. */ public static class ObjectServiceRoutineMethod extends ServiceRoutineMethod implements ObjectConfigurable<ObjectServiceRoutineMethod> { private final ServiceContext mContext; private final Method mMethod; private final ContextInvocationTarget<?> mTarget; private ObjectConfiguration mConfiguration = ObjectConfiguration.defaultConfiguration(); /** * Constructor. * * @param context the Service context. * @param target the invocation target. * @param method the method instance. */ private ObjectServiceRoutineMethod(@NotNull final ServiceContext context, @NotNull final ContextInvocationTarget<?> target, @NotNull final Method method) { super(context, target, method); mContext = context; mTarget = target; mMethod = method; } @NotNull @Override public ObjectServiceRoutineMethod apply(@NotNull final InvocationConfiguration configuration) { return (ObjectServiceRoutineMethod) super.apply(configuration); } @NotNull @Override @SuppressWarnings("unchecked") public InvocationConfiguration.Builder<? extends ObjectServiceRoutineMethod> applyInvocationConfiguration() { return (InvocationConfiguration.Builder<? extends ObjectServiceRoutineMethod>) super .applyInvocationConfiguration(); } @NotNull @Override public <OUT> Channel<?, OUT> call(@Nullable final Object... params) { return call(InvocationMode.ASYNC, params); } @NotNull @Override public <OUT> Channel<?, OUT> callParallel(@Nullable final Object... params) { return call(InvocationMode.PARALLEL, params); } @NotNull @Override public ObjectServiceRoutineMethod apply(@NotNull final ServiceConfiguration configuration) { return (ObjectServiceRoutineMethod) super.apply(configuration); } @NotNull @Override @SuppressWarnings("unchecked") public Builder<? extends ObjectServiceRoutineMethod> applyServiceConfiguration() { return (Builder<? extends ObjectServiceRoutineMethod>) super.applyServiceConfiguration(); } @NotNull @Override public ObjectServiceRoutineMethod apply(@NotNull final ObjectConfiguration configuration) { mConfiguration = ConstantConditions.notNull("object configuration", configuration); return this; } @NotNull @Override public ObjectConfiguration.Builder<? extends ObjectServiceRoutineMethod> applyObjectConfiguration() { return new ObjectConfiguration.Builder<ObjectServiceRoutineMethod>(this, mConfiguration); } @NotNull @SuppressWarnings("unchecked") private <OUT> Channel<?, OUT> call(@NotNull final InvocationMode mode, @Nullable final Object[] params) { final Object[] safeParams = asArgs(params); final Method method = mMethod; if (method.getParameterTypes().length != safeParams.length) { throw new IllegalArgumentException("wrong number of parameters: expected <" + method.getParameterTypes().length + "> but was <" + safeParams.length + ">"); } final Routine<Object, Object> routine = JRoutineServiceObject.on(mContext) .with(mTarget) .apply(getConfiguration()) .apply(getServiceConfiguration()) .apply(mConfiguration) .method(method); final Channel<Object, Object> channel = mode.invoke(routine).sorted(); for (final Object param : safeParams) { if (param instanceof Channel) { channel.pass((Channel<?, ?>) param); } else { channel.pass(param); } } return (Channel<?, OUT>) channel.close(); } } /** * Input channel placeholder class used to make the method parameters parcelable. */ private static class InputChannelPlaceHolder {} /** * Output channel placeholder class used to make the method parameters parcelable. */ private static class OutputChannelPlaceHolder {} /** * Context invocation implementation. */ private static class ServiceInvocation implements ContextInvocation<ParcelableSelectable<Object>, ParcelableSelectable<Object>> { private final Object[] mArgs; private final ArrayList<Channel<?, ?>> mInputChannels = new ArrayList<Channel<?, ?>>(); private final Method mMethod; private final Object[] mOrigParams; private final ArrayList<Channel<?, ?>> mOutputChannels = new ArrayList<Channel<?, ?>>(); private final boolean mReturnResults; private final Class<? extends ServiceRoutineMethod> mType; private Constructor<? extends ServiceRoutineMethod> mConstructor; private Object[] mConstructorArgs; private Context mContext; private ServiceRoutineMethod mInstance; private boolean mIsAborted; private boolean mIsBound; private boolean mIsComplete; private Object[] mParams; /** * Constructor. * * @param type the Service routine method type. * @param args the constructor arguments. * @param params the method parameters. */ private ServiceInvocation(@NotNull final Class<? extends ServiceRoutineMethod> type, @NotNull final Object[] args, @NotNull final Object[] params) { final ChannelBuilder channelBuilder = JRoutineCore.io(); for (int i = 0; i < params.length; ++i) { final Object param = params[i]; if (param == InputChannelPlaceHolder.class) { params[i] = channelBuilder.buildChannel(); } else if (param == OutputChannelPlaceHolder.class) { params[i] = channelBuilder.buildChannel(); } } mType = type; mArgs = args; mMethod = findBestMatchingMethod(type, params); mOrigParams = params; mReturnResults = (boxingClass(mMethod.getReturnType()) != Void.class); } @Override public void onAbort(@NotNull final RoutineException reason) throws Exception { mIsAborted = true; final List<Channel<?, ?>> inputChannels = mInputChannels; for (final Channel<?, ?> inputChannel : inputChannels) { inputChannel.abort(reason); } final ServiceRoutineMethod instance = mInstance; instance.setLocalInput((!inputChannels.isEmpty()) ? inputChannels.get(0) : null); try { if (!mIsComplete) { invokeMethod(); } } finally { instance.resetIgnoreReturnValue(); instance.setLocalInput(null); for (final Channel<?, ?> outputChannel : mOutputChannels) { outputChannel.abort(reason); } } } @Override public void onComplete(@NotNull final Channel<ParcelableSelectable<Object>, ?> result) throws Exception { bind(result); mIsComplete = true; if (!mIsAborted) { final List<Channel<?, ?>> inputChannels = mInputChannels; for (final Channel<?, ?> inputChannel : inputChannels) { inputChannel.close(); } final ServiceRoutineMethod instance = mInstance; instance.setLocalInput((!inputChannels.isEmpty()) ? inputChannels.get(0) : null); instance.resetIgnoreReturnValue(); final List<Channel<?, ?>> outputChannels = mOutputChannels; try { final Object methodResult = invokeMethod(); if (mReturnResults && !instance.isIgnoreReturnValue()) { result.pass(new ParcelableSelectable<Object>(methodResult, outputChannels.size())); } } finally { instance.resetIgnoreReturnValue(); instance.setLocalInput(null); } for (final Channel<?, ?> outputChannel : outputChannels) { outputChannel.close(); } } } @Override public void onInput(final ParcelableSelectable<Object> input, @NotNull final Channel<ParcelableSelectable<Object>, ?> result) throws Exception { bind(result); @SuppressWarnings("unchecked") final Channel<Object, Object> inputChannel = (Channel<Object, Object>) mInputChannels.get(input.index); inputChannel.pass(input.data); final ServiceRoutineMethod instance = mInstance; instance.setLocalInput(inputChannel); try { final Object methodResult = invokeMethod(); if (mReturnResults && !instance.isIgnoreReturnValue()) { result.pass(new ParcelableSelectable<Object>(methodResult, mOutputChannels.size())); } } finally { instance.resetIgnoreReturnValue(); instance.setLocalInput(null); } } @Override public void onRecycle(final boolean isReused) { mInputChannels.clear(); mOutputChannels.clear(); } @Override public void onRestart() throws Exception { mIsBound = false; mIsAborted = false; mIsComplete = false; final ServiceRoutineMethod instance = (mInstance = mConstructor.newInstance(mConstructorArgs)); instance.setReturnType(mMethod.getReturnType()); mParams = replaceChannels(mMethod, mOrigParams, mInputChannels, mOutputChannels); } @Override public void onContext(@NotNull final Context context) throws Exception { mContext = context; final Object[] additionalArgs = mArgs; final Object[] constructorArgs = (mConstructorArgs = new Object[additionalArgs.length + 1]); System.arraycopy(additionalArgs, 0, constructorArgs, 1, additionalArgs.length); constructorArgs[0] = ServiceContext.serviceFrom(context); mConstructor = Reflection.findBestMatchingConstructor(mType, constructorArgs); } private void bind(@NotNull final Channel<ParcelableSelectable<Object>, ?> result) { if (!mIsBound) { mIsBound = true; final List<Channel<?, ?>> outputChannels = mOutputChannels; if (!outputChannels.isEmpty()) { result.pass(AndroidChannels.mergeParcelable(outputChannels).buildChannels()); } } } @Nullable private Object invokeMethod() throws Exception { final ServiceRoutineMethod instance = mInstance; instance.setLocalContext(mContext); try { return mMethod.invoke(instance, mParams); } catch (final InvocationTargetException e) { throw InvocationException.wrapIfNeeded(e.getTargetException()); } finally { instance.setLocalContext(null); } } } }
36.412742
100
0.688132
9bc80c0ad8ad8a5e4891d7147c039ff04a78c08e
796
package cqu.edu.cn.ssosystem.controller; import cqu.edu.cn.ssosystem.global.DBConnection; import cqu.edu.cn.ssosystem.global.ResData; import cqu.edu.cn.ssosystem.model.Token; import cqu.edu.cn.ssosystem.model.User; public class TokenControllerTest { public static void main (String[] args) throws Exception { DBConnection mysqlConnect = new DBConnection(); Token myToken = new Token(mysqlConnect.getConn()); // 将用户数据库模型实例化 User myUser = new User(mysqlConnect.getConn());// 将token的数据库模型实例化 TokenController tokenControll = new TokenController(myUser, myToken); ResData tokenRes = tokenControll.checkToken("5A8F56141005CA2D13969003119qq", "qq"); System.out.println(tokenRes.isError()); System.out.println(tokenRes.getData()); } }
36.181818
91
0.729899
08889914cbce8e8590e81ccbf88413a07d744199
103
package com.csculb.interfaceDemo; public interface BaseRepository { void save(Savable entity); }
14.714286
33
0.76699
d4dbe8bfc7a22fc4c6ef00216be4bfb8b83a32c3
323
package lumien.randomthings.container; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; public class ContainerAnalogEmitter extends ContainerEmptyContainer { public ContainerAnalogEmitter(EntityPlayer player, World world, int x, int y, int z) { super(player, world, x, y, z); } }
21.533333
85
0.786378
1957bd9c31e95cc89f77f3137984a1566fb862eb
651
package com.juztoss.shapes; import com.juztoss.Game; /** * Created by Kirill on 5/16/2016. */ public class IShape extends AbstractShape { private boolean[][] mContent; public IShape(Game game) { super(game); } @Override void reset() { super.reset(); mContent = new boolean[4][1]; mContent[0][0] = true; mContent[1][0] = true; mContent[2][0] = true; mContent[3][0] = true; } @Override protected boolean[][] getContent() { return mContent; } @Override protected void setContent(boolean[][] content) { mContent = content; } }
18.6
52
0.562212
c8305fd6c6b8593ac3301c08cfa4e1797dd7bad7
18,328
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2014 The ZAP Development Team * * 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.zaproxy.zap.extension.multiFuzz; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.border.Border; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import org.owasp.jbrofuzz.core.Fuzzer; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.AbstractDialog; import org.parosproxy.paros.view.View; import org.zaproxy.zap.extension.httppanel.Message; /** * The main UI component for the choice of fuzzing options and targets for a specific message. * * @param <M> the target message type * @param <L> the associated {@link FuzzLocation} type * @param <P> the associated {@link Payload} type * @param <G> the associated {@link FuzzGap} type */ public abstract class FuzzDialog<M extends Message, L extends FuzzLocation<M>, P extends Payload, G extends FuzzGap<M, L, P>> extends AbstractDialog { private static final long serialVersionUID = 3855005636913607013L; protected ExtensionFuzz res; protected M fuzzableMessage; private JPanel background; private JSplitPane splitPane; private JLabel info; private JPanel searchBar; private JButton cancelButton = null; private JButton startButton = null; private JButton addComponentButton; private JButton editComponentButton; private JButton delComponentButton; private JTextArea searchField; private JCheckBox scriptEnabled; protected TargetModel<G> targetModel; protected JTable targetTable; private ArrayList<SubComponent> subs = new ArrayList<>(); private ArrayList<FuzzerListener<?, ArrayList<G>>> listeners = new ArrayList<>(); /** * Converts a JBroFuzzer into a simple FileFuzzer * @param jBroFuzzer The JBroFuzzer * @return the resulting @FileFuzzer */ public abstract FileFuzzer<P> convertToFileFuzzer(Fuzzer jBroFuzzer); /** * Generates and returns the {@link FuzzProcessFactory} for the generation of {@link FuzzProcess} instances * according to the users choice of options. * @return the {@link FuzzProcessFactory} */ public abstract FuzzProcessFactory getFuzzProcessFactory(); /** * Generates and returns the {@link PayloadFactory} for the generation of {@link Payload} instances * that are defined by the user. * @return the {@link PayloadFactory} */ protected abstract PayloadFactory<P> getPayloadFactory(); /** * Returns the target message of the current fuzzing procedure for which {@link Payload} are defined and other options are determined. * @return the target message */ public M getMessage() { return this.fuzzableMessage; } /** * To be overridden to include components that enable the user to choose options for the fuzzing process specific to the message type. * @param panel the panel the components are added to * @param currentRow row in the GridBagLayout they are inserted in * @return the next row in the GridBagLayout after the custom components */ protected abstract int addCustomComponents(JPanel panel, int currentRow); /** * To be overridden to provide an implementation of {@link FuzzComponent} to display the current message and fuzz targets in * @return the {@link FuzzComponent} */ protected abstract FuzzComponent<M, L, G> getMessageContent(); /** * The standard constructor. * @param ext the {@link ExtensionFuzz} resources can be loaded from * @param msg the target message. * @param subs a list of subcomponents to be displayed * @throws HeadlessException */ public FuzzDialog(ExtensionFuzz ext, M msg, ArrayList<SubComponent> subs) throws HeadlessException { super(View.getSingleton().getMainFrame(), true); this.setTitle(Constant.messages.getString("fuzz.title")); this.res = ext; fuzzableMessage = msg; this.subs = subs; initialize(); } /** * This method initializes the Dialog and its components */ protected void initialize() { this.setContentPane(getJPanel()); this.setSize(800, 400); } /** * This method initializes the main JPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (background == null) { background = new JPanel(); background.setLayout(new GridBagLayout()); int currentRow = 0; Font headLine = new Font(Font.SERIF, Font.BOLD, 20); JLabel headL = new JLabel(Constant.messages.getString("fuzz.title")); headL.setFont(headLine); GridBagConstraints h = Util.getGBC(0, currentRow, 2, 1.0, 0.0, java.awt.GridBagConstraints.HORIZONTAL); h.anchor = java.awt.GridBagConstraints.PAGE_START; background.add(headL, h); currentRow++; GridBagConstraints i = Util.getGBC(0, currentRow, 2, 1.0, 0.0, java.awt.GridBagConstraints.HORIZONTAL); i.anchor = java.awt.GridBagConstraints.PAGE_START; background.add(getInfo(), i); currentRow++; GridBagConstraints b = Util.getGBC(0, currentRow, 2, 1.0, 1.0, java.awt.GridBagConstraints.BOTH); b.anchor = java.awt.GridBagConstraints.CENTER; background.add(getJTabbed(), b); } return background; } private JSplitPane getJTabbed() { if (splitPane == null) { Font headLine = new Font(Font.SERIF, Font.BOLD, 16); splitPane = new JSplitPane(); JPanel left = new JPanel(); left.setLayout(new GridBagLayout()); int currentRow = 0; left.add( getMessageContent().messageView(), Util.getGBC(0, currentRow, 2, 1.0, 1.0, java.awt.GridBagConstraints.BOTH)); currentRow++; left.add( getSearchBar(), Util.getGBC(0, currentRow, 2, 1.0, 0.0, java.awt.GridBagConstraints.HORIZONTAL)); JPanel rbg = new JPanel(); JTabbedPane tabbed = new JTabbedPane(); JPanel targetDisplay = new JPanel(); JPanel general = new JPanel(); targetDisplay.setLayout(new GridBagLayout()); currentRow = 0; JLabel targetHead = new JLabel( Constant.messages.getString("fuzz.targetHead")); targetHead.setFont(headLine); targetDisplay.add(targetHead, Util.getGBC(0, currentRow, 6, 1)); currentRow++; targetDisplay.add( new JScrollPane(getTargetField()), Util.getGBC(0, currentRow, 4, 1.0, 1.0, java.awt.GridBagConstraints.BOTH)); currentRow++; targetDisplay.add(getAddComponentButton(), Util.getGBC(1, currentRow, 1, 0.0)); targetDisplay.add(getEditComponentButton(), Util.getGBC(2, currentRow, 1, 0.0)); targetDisplay.add(getDelComponentButton(), Util.getGBC(3, currentRow, 1, 0.0)); general.setLayout(new GridBagLayout()); currentRow = 0; JLabel messageOpts = new JLabel( Constant.messages.getString("fuzz.message.options")); messageOpts.setFont(headLine); general.add(messageOpts, Util.getGBC(0, currentRow, 6, 1)); currentRow++; general.add( new JLabel(Constant.messages .getString("fuzz.label.scriptEnabled")), Util.getGBC(0, currentRow, 2, 0.125)); general.add(getScriptEnabled(), Util.getGBC(2, currentRow, 4, 0.125)); currentRow++; currentRow = addCustomComponents(general, currentRow); for(SubComponent c : subs){ general.add(c.addOptions(), Util.getGBC(0, currentRow, 4, 0.125)); currentRow++; } tabbed.addTab(Constant.messages.getString("fuzz.tab.targets"), targetDisplay); tabbed.addTab(Constant.messages.getString("fuzz.tab.general"), general); rbg.setLayout(new GridBagLayout()); rbg.add(tabbed, Util.getGBC(0, 0, 3, 1.0, 1.0, java.awt.GridBagConstraints.BOTH)); rbg.add(getStartButton(), Util.getGBC(0, 1, 1, 0.0)); rbg.add(getCancelButton(), Util.getGBC(2, 1, 1, 0.0)); Dimension minimumSize = new Dimension(50, 50); left.setMinimumSize(minimumSize); rbg.setMinimumSize(minimumSize); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(left); splitPane.setRightComponent(rbg); splitPane.setDividerLocation(400); } return splitPane; } protected JTable getTargetField() { if (targetTable == null) { targetModel = new TargetModel(); targetTable = new JTable(targetModel); targetTable .setDefaultRenderer(Color.class, new ColorRenderer(true)); } return targetTable; } protected JLabel getInfo() { if (info == null) { info = new JLabel(Constant.messages.getString("fuzz.info.gen")); } return info; } // Left Panel private JPanel getSearchBar() { if (searchBar == null) { this.searchBar = new JPanel(); searchBar.setLayout(new GridBagLayout()); searchField = new JTextArea( Constant.messages.getString("fuzz.label.search")); searchField.setEditable(true); searchBar .add(searchField, Util.getGBC(0, 0, 4, 0.8, 1.0, java.awt.GridBagConstraints.BOTH)); JButton search = new JButton(); search.setAction(getSearchAction()); searchBar.add(search, Util.getGBC(5, 0, 1, 0.2)); } return searchBar; } // Right Panel public void addFuzzerListener(FuzzerListener<?, ArrayList<G>> listener) { listeners.add(listener); } public void removeFuzzerListener(FuzzerListener<?, ArrayList<G>> listener) { listeners.remove(listener); } public boolean getScripting() { return scriptEnabled.isSelected(); } protected boolean isCustomCategory(String cat) { return Constant.messages.getString("fuzz.category.custom").equals(cat); } protected boolean isJBroFuzzCategory(String cat) { return cat.startsWith(ExtensionFuzz.JBROFUZZ_CATEGORY_PREFIX); } protected JButton getAddComponentButton() { if (addComponentButton == null) { addComponentButton = new JButton(); addComponentButton.setAction(getAddFuzzAction()); getAddComponentButton().setText( Constant.messages.getString("fuzz.button.add.add")); } return addComponentButton; } protected JButton getEditComponentButton() { if (editComponentButton == null) { editComponentButton = new JButton(); editComponentButton.setAction(getEditFuzzAction()); editComponentButton.setText( Constant.messages.getString("fuzz.button.edit")); } return editComponentButton; } protected JButton getDelComponentButton() { if (delComponentButton == null) { delComponentButton = new JButton(); delComponentButton.setAction(getDelFuzzAction()); delComponentButton.setText( Constant.messages.getString("fuzz.button.del")); } return delComponentButton; } protected JButton getStartButton() { if (startButton == null) { startButton = new JButton(); startButton.setAction(getStartFuzzAction()); } return startButton; } protected JButton getCancelButton() { if (cancelButton == null) { cancelButton = new JButton(); cancelButton.setAction(getCancelFuzzAction()); } return cancelButton; } private JCheckBox getScriptEnabled() { if (scriptEnabled == null) { scriptEnabled = new JCheckBox(); scriptEnabled.setSelected(true); } return scriptEnabled; } protected Action getSearchAction() { return new SearchAction(); } protected AddFuzzAction getAddFuzzAction() { return new AddFuzzAction(); } protected EditFuzzAction getEditFuzzAction() { return new EditFuzzAction(); } protected DelFuzzAction getDelFuzzAction() { return new DelFuzzAction(); } protected StartFuzzAction getStartFuzzAction() { return new StartFuzzAction(); } protected CancelFuzzAction getCancelFuzzAction() { return new CancelFuzzAction(); } protected class StartFuzzAction extends AbstractAction { private static final long serialVersionUID = -961522394390805325L; public StartFuzzAction() { super(Constant.messages.getString("fuzz.button.start")); setEnabled(false); } @Override public void actionPerformed(ActionEvent e) { for (FuzzerListener<?, ArrayList<G>> f : listeners) { f.notifyFuzzerComplete(targetModel.getEntries()); } } } protected class CancelFuzzAction extends AbstractAction { private static final long serialVersionUID = -6716179197963523133L; public CancelFuzzAction() { super(Constant.messages.getString("fuzz.button.cancel")); } @Override public void actionPerformed(ActionEvent e) { setVisible(false); } } protected class DelFuzzAction extends AbstractAction { private static final long serialVersionUID = -961522394390805325L; public DelFuzzAction() { super(Constant.messages.getString("fuzz.button.del")); } @Override public void actionPerformed(ActionEvent e) { int[] sel = getTargetField().getSelectedRows(); for(int i = 0; i < sel.length; i++){ targetModel.removeEntry(sel[i] - i); } if (targetModel.getRowCount() == 0) { getStartButton().setEnabled(false); } getInfo().setText(Constant.messages.getString("fuzz.info.gen")); getMessageContent().highlight(targetModel.getEntries()); } } protected class EditFuzzAction extends AbstractAction { private static final long serialVersionUID = -961522394390805325L; public EditFuzzAction() { super(Constant.messages.getString("fuzz.button.edit")); } @Override public void actionPerformed(ActionEvent e) { } } protected class AddFuzzAction extends AbstractAction { private static final long serialVersionUID = -961522394390805325L; public AddFuzzAction() { super(Constant.messages.getString("fuzz.button.add.add")); } protected boolean isValidLocation(L l) { boolean valid = true; for (G g : targetModel.getEntries()) { valid &= !l.overlap(g.getLocation()); if(!valid){ break; } } return valid; } @Override public void actionPerformed(ActionEvent e) { getInfo().setText(Constant.messages.getString("fuzz.info.gen")); getMessageContent().highlight(targetModel.getEntries()); } } private class SearchAction extends AbstractAction { public SearchAction() { super(Constant.messages.getString("fuzz.search")); } @Override public void actionPerformed(ActionEvent arg0) { getMessageContent().search(searchField.getText()); } } public static class TargetModel<G extends FuzzGap<?,?,?>> extends AbstractTableModel { static final String[] columnNames = { Constant.messages.getString("fuzz.table.origHead"), Constant.messages.getString("fuzz.table.color") }; private ArrayList<G> targets = new ArrayList<>(); @Override public int getColumnCount() { return columnNames.length; } @Override public int getRowCount() { return targets.size(); } @Override public String getColumnName(int col) { return columnNames[col]; } @Override public Object getValueAt(int row, int col) { if (col == 0) { return targets.get(row).orig(); } else if (col == 1) { return Util.getColor(row + 1); } return null; } @Override public Class<?> getColumnClass(int c) { switch (c) { case 1: return Color.class; default: return String.class; } } @Override public boolean isCellEditable(int row, int col) { return false; } public void addEntries(ArrayList<G> t) { targets.addAll(t); fireTableRowsInserted(targets.size() - t.size(), targets.size() - 1); } public void addEntry(G t) { targets.add(t); fireTableRowsInserted(targets.size() - 1, targets.size() - 1); } public ArrayList<G> getEntries() { return targets; } public void removeEntry(int idx){ if (idx != -1) { targets.remove(idx); fireTableRowsDeleted(idx, idx); } } public void removeEntry(G t) { int idx = targets.indexOf(t); if (idx != -1) { targets.remove(idx); fireTableRowsDeleted(idx, idx); } } } public class ColorRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); // MUST do this for background to show up. } @Override public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Color newColor = (Color) color; setBackground(newColor); if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getBackground()); } setBorder(unselectedBorder); } } return this; } } }
30.045902
136
0.689655
852998698bd5bd00395727d233aa3e81b3ddaab1
6,504
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.model.internal.fixture; import org.gradle.api.Action; import org.gradle.internal.BiAction; import org.gradle.internal.TriAction; import org.gradle.model.internal.core.*; import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor; import org.gradle.model.internal.core.rule.describe.SimpleModelRuleDescriptor; import org.gradle.model.internal.type.ModelType; import java.util.Collections; import java.util.List; public class ModelActionBuilder<T> { private static final List<ModelReference<?>> NO_REFS = Collections.emptyList(); private ModelPath path; private ModelType<T> type; private ModelRuleDescriptor descriptor; private ModelActionBuilder(ModelPath path, ModelType<T> type, ModelRuleDescriptor descriptor) { this.path = path; this.type = type; this.descriptor = descriptor; } public static ModelActionBuilder<Object> of() { return new ModelActionBuilder<Object>(null, ModelType.UNTYPED, new SimpleModelRuleDescriptor("testrule")); } private <N> ModelActionBuilder<N> copy(ModelType<N> type) { return new ModelActionBuilder<N>(path, type, descriptor); } public ModelActionBuilder<T> path(String path) { return this.path(ModelPath.path(path)); } public ModelActionBuilder<T> path(ModelPath path) { this.path = path; return this; } public ModelActionBuilder<T> descriptor(String descriptor) { return descriptor(new SimpleModelRuleDescriptor(descriptor)); } public ModelActionBuilder<T> descriptor(ModelRuleDescriptor descriptor) { this.descriptor = descriptor; return this; } public <N> ModelActionBuilder<N> type(Class<N> type) { return type(ModelType.of(type)); } public <N> ModelActionBuilder<N> type(ModelType<N> type) { return copy(type); } public ModelAction action(final Action<? super T> action) { return build(NO_REFS, new TriAction<MutableModelNode, T, List<ModelView<?>>>() { @Override public void execute(MutableModelNode mutableModelNode, T t, List<ModelView<?>> inputs) { action.execute(t); } }); } public ModelAction node(final Action<? super MutableModelNode> action) { return toAction(action, path, type, descriptor); } public <I> ModelAction action(ModelPath modelPath, Class<I> inputType, BiAction<? super T, ? super I> action) { return action(modelPath, ModelType.of(inputType), action); } public <I> ModelAction action(String modelPath, Class<I> inputType, BiAction<? super T, ? super I> action) { return action(ModelPath.path(modelPath), ModelType.of(inputType), action); } public <I> ModelAction action(ModelPath modelPath, ModelType<I> inputType, BiAction<? super T, ? super I> action) { return action(modelPath, inputType, inputType.toString(), action); } public <I> ModelAction action(String modelPath, ModelType<I> inputType, BiAction<? super T, ? super I> action) { return action(modelPath, inputType, modelPath, action); } public <I> ModelAction action(final ModelPath modelPath, final ModelType<I> inputType, String referenceDescription, final BiAction<? super T, ? super I> action) { return action(ModelReference.of(modelPath, inputType, referenceDescription), action); } public <I> ModelAction action(final ModelReference<I> inputReference, final BiAction<? super T, ? super I> action) { return build(Collections.<ModelReference<?>>singletonList(inputReference), new TriAction<MutableModelNode, T, List<ModelView<?>>>() { @Override public void execute(MutableModelNode mutableModelNode, T t, List<ModelView<?>> inputs) { action.execute(t, ModelViews.assertType(inputs.get(0), inputReference.getType()).getInstance()); } }); } public <I> ModelAction action(final String modelPath, final ModelType<I> inputType, String referenceDescription, final BiAction<? super T, ? super I> action) { return action(ModelPath.path(modelPath), inputType, referenceDescription, action); } public <I> ModelAction action(final ModelType<I> inputType, final BiAction<? super T, ? super I> action) { return action((ModelPath) null, inputType, action); } public <I> ModelAction action(final Class<I> inputType, final BiAction<? super T, ? super I> action) { return action(ModelType.of(inputType), action); } private ModelAction build(List<ModelReference<?>> references, TriAction<? super MutableModelNode, ? super T, ? super List<ModelView<?>>> action) { return toAction(references, action, path, type, descriptor); } private static <T> ModelAction toAction(final List<ModelReference<?>> references, final TriAction<? super MutableModelNode, ? super T, ? super List<ModelView<?>>> action, final ModelPath path, final ModelType<T> type, final ModelRuleDescriptor descriptor) { return DirectNodeInputUsingModelAction.of(subject(path, type), descriptor, references, new TriAction<MutableModelNode, T, List<ModelView<?>>>() { @Override public void execute(MutableModelNode modelNode, T t, List<ModelView<?>> inputs) { action.execute(modelNode, t, inputs); } }); } private static <T> ModelAction toAction(Action<? super MutableModelNode> action, final ModelPath path, final ModelType<T> type, final ModelRuleDescriptor descriptor) { return DirectNodeNoInputsModelAction.of(subject(path, type), descriptor, action); } private static <T> ModelReference<T> subject(ModelPath path, ModelType<T> type) { return path != null ? ModelReference.of(path, type) : ModelReference.of(type).inScope(ModelPath.ROOT); } }
42.509804
261
0.697109
90819d9e7920ed503ba70361270eaea4ae86c501
426
package com.qr.model; import javax.websocket.Session; public class WebSocketClient { private String code; private Session session; public void setCode(String code) { this.code = code; } public Session getSession() { return session; } public String getCode() { return code; } public void setSession(Session session) { this.session = session; } }
15.214286
45
0.619718
16290cd7d85d544c2a2aededaa83646bbd770749
1,607
/* * Licensed to GIScience Research Group, Heidelberg University (GIScience) * * http://www.giscience.uni-hd.de * http://www.heigit.org * * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The GIScience 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 heigit.ors.locations; /** * This Class handles the error Codes as described in the error_codes.md * * @author OpenRouteServiceTeam * @author Julian Psotta, julian@openrouteservice.org */ public class LocationsErrorCodes { public static int INVALID_JSON_FORMAT = 4000; public static int MISSING_PARAMETER = 4001; public static int INVALID_PARAMETER_FORMAT = 4002; public static int INVALID_PARAMETER_VALUE = 4003; public static int PARAMETER_VALUE_EXCEEDS_MAXIMUM = 4004; public static int EXPORT_HANDLER_ERROR = 4006; public static int UNSUPPORTED_EXPORT_FORMAT = 4007; public static int EMPTY_ELEMENT = 4008; public static int UNKNOWN = 4099; }
40.175
80
0.749844
f48f6767b36cd996cf0691e58f8cbddc071bce77
269
package com.yapp.pet.domain.common; import lombok.Getter; @Getter public enum PetSizeType { LARGE("대형견"), MEDIUM("중형견"), SMALL("소형견"), ALL("상관없음"); private final String value; PetSizeType(String value){ this.value = value; } }
13.45
35
0.613383
d1dfd49c2edf97680f5b37834aae34f798c016d4
893
package com.example.leetcodedemo.array.medium; /** * 给定数组 A,我们可以对其进行煎饼翻转:我们选择一些正整数 k <= A.length,然后反转 A 的前 k 个元素的顺序。我们要执行零次或多次煎饼翻转(按顺序一次接一次地进行)以完成对数组 A 的排序。 * * 返回能使 A 排序的煎饼翻转操作所对应的 k 值序列。任何将数组排序且翻转次数在 10 * A.length 范围内的有效答案都将被判断为正确。 * *   * * 示例 1: * * 输入:[3,2,4,1] * 输出:[4,2,4,3] * 解释: * 我们执行 4 次煎饼翻转,k 值分别为 4,2,4,和 3。 * 初始状态 A = [3, 2, 4, 1] * 第一次翻转后 (k=4): A = [1, 4, 2, 3] * 第二次翻转后 (k=2): A = [4, 1, 2, 3] * 第三次翻转后 (k=4): A = [3, 2, 1, 4] * 第四次翻转后 (k=3): A = [1, 2, 3, 4],此时已完成排序。 * 示例 2: * * 输入:[1,2,3] * 输出:[] * 解释: * 输入已经排序,因此不需要翻转任何内容。 * 请注意,其他可能的答案,如[3,3],也将被接受。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/pancake-sorting * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ import java.util.List; /** * Created by Wcxdhr on 2019/9/26. */ public class PancakeSorting { public List<Integer> pancakeSort(int[] A) { return null; } }
19.844444
106
0.592385
5e02cead3c1781f66618d7bec40ae99d493172e4
6,102
package com.base.services.aws; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.DeleteObjectRequest; import com.amazonaws.services.s3.model.PutObjectRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Date; @Service public class AmazonClient { private static final Logger logger = LoggerFactory.getLogger(AmazonClient.class); private AmazonS3 s3client; @Value("${amazonProperties.endpointUrl}") private String endpointUrl; @Value("${amazon.s3.default-bucket}") private String bucketName; @Value("${amazon.aws.access-key-id}") private String accessKey; @Value("${amazon.aws.access-key-secret}") private String secretKey; @PostConstruct private void initializeAmazon() { BasicAWSCredentials creds = new BasicAWSCredentials(this.accessKey, this.secretKey); s3client = AmazonS3ClientBuilder.standard().withRegion("sa-east-1").withCredentials(new AWSStaticCredentialsProvider(creds)).build(); // ClientConfiguration clientConfig = new ClientConfiguration(); // clientConfig.setProtocol(Protocol.HTTP); // AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey); // this.s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.SA_EAST_1).build(); } private File convertMultiPartToFile(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; } private String generateFileName(MultipartFile multiPart) { return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_"); } private void uploadFileTos3bucket(String fileName, File file) { s3client.putObject(new PutObjectRequest(bucketName, fileName, file) .withCannedAcl(CannedAccessControlList.PublicRead)); } public String uploadBase64(String base64Data, Long userID) { try { byte[] imageByte = org.apache.commons.codec.binary.Base64.decodeBase64((base64Data.substring(base64Data.indexOf(",") + 1)).getBytes()); String fileName = ""; BufferedImage image = null; InputStream fis = new ByteArrayInputStream(imageByte); image = ImageIO.read(fis); fis.close(); File outputfile = new File("image.jpg"); ImageIO.write(image, "jpg", outputfile); //Resize da imagem // outputfile = imageRisize.resize(outputfile, true, 400); //Set metadata for object //ObjectMetadata metadata = new ObjectMetadata(); //metadata.setContentLength(bbI.length); //metadata.setContentType("image/jpeg"); //metadata.setCacheControl("public, max-age=31536000"); fileName = fileName + new Date().getTime() + "-" + "Profile-" + userID.toString(); // //s3client.putObject(bucketName, fileName, fis, metadata); // s3client.setObjectAcl(bucketName, fileName, CannedAccessControlList.PublicRead); uploadFileTos3bucket(fileName, outputfile); //Generate Url to image String fileUrl = endpointUrl + "/" + bucketName + "/" + fileName; return fileUrl; } catch (Exception e) { e.printStackTrace(); logger.error("Error", e); return null; } } public String uploadFile(MultipartFile multipartFile) { String fileUrl = null; String pathname = ""; try { File file = convertMultiPartToFile(multipartFile); String fileOrigeNamePath = file.getName(); String fileName = generateFileName(multipartFile); uploadFileTos3bucket(fileName, file); fileUrl = endpointUrl + "/" + bucketName + "/" + fileName; file.delete(); } catch (Exception e) { e.printStackTrace(); logger.error("Error", e); } return fileUrl; } public String uploadFileImage(MultipartFile multipartFile, boolean isThumb) { String fileUrl = null; String pathname = ""; try { File file = convertMultiPartToFile(multipartFile); String fileOrigeNamePath = file.getName(); String fileName = generateFileName(multipartFile); // recize da imagem // if (isThumb) { // file = imageRisize.resize(file, true, 400); // pathname = "thumb.jpg"; // } // else { // // file = imageRisize.resize(file, false, 1280); // pathname = "description.jpg"; // } uploadFileTos3bucket(fileName, file); fileUrl = endpointUrl + "/" + bucketName + "/" + fileName; file.delete(); Files.delete(Paths.get(fileOrigeNamePath)); } catch (Exception e) { e.printStackTrace(); logger.error("Error", e); } return fileUrl; } public String deleteFileFromS3Bucket(String fileUrl) { String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); s3client.deleteObject(new DeleteObjectRequest(bucketName + "/", fileName)); return "Successfully deleted"; } }
34.868571
160
0.646018
676416e88786ee98243ccb3c07ecb99404bc6248
262
package ru.job4j.menustructure; import java.util.List; /** * the interface for items with children. */ public interface IntChildren { /** * returns the children list. * @return the list with children. */ List<IntName> getChildren(); }
17.466667
41
0.656489
e797447b7e1cb6c8381d8c78b921d1f5f220a276
2,235
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory 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. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.update.md.v130beta6; import org.artifactory.fs.FolderInfo; import org.artifactory.update.md.MetadataConverterTest; import org.artifactory.util.ResourceUtils; import org.artifactory.util.XmlUtils; import org.jdom2.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.Test; /** * Tests the conversion of folder info metadata. * * @author Yossi Shaul */ @Test public class FolderAdditionalInfoNameConverterTest extends MetadataConverterTest { private static final Logger log = LoggerFactory.getLogger(FolderAdditionalInfoNameConverterTest.class); public void convertValidFolderInfo() throws Exception { String fileMetadata = "/metadata/v130beta6/artifactory-folder.xml"; Document doc = convertXml(fileMetadata, new FolderAdditionalInfoNameConverter()); String result = XmlUtils.outputString(doc); log.debug(result); // the result is intermediate so it might not be compatible with latest FolderInfo // but for now it is a good test to test the resulting FolderInfo FolderInfo folderInfo = (FolderInfo) xstream.fromXML(result); Assert.assertNotNull(folderInfo.getModifiedBy()); FolderInfo expected = (FolderInfo) xstream.fromXML( ResourceUtils.getResource("/metadata/v130beta6/artifactory-folder-expected.xml")); Assert.assertTrue(folderInfo.isIdentical(expected)); } }
39.210526
107
0.75302
dcffe5f4203447af4460608665c0fa1f3841c6e3
957
package io.blockv.example.feature.login.phone; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import io.blockv.example.R; import io.blockv.example.feature.BaseFragment; /** * The LoginPhoneFragment demonstrates logging a user into the blockv platform using a phone number * * @see LoginPhonePresenterImpl */ public class LoginPhoneFragment extends BaseFragment { LoginPhonePresenter presenter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_login_phone, container, false); LoginPhoneScreen screen = new LoginPhoneScreenImpl(view,this); presenter = new LoginPhonePresenterImpl(screen); screen.registerEvents(presenter); return view; } @Override public void onDestroyView() { presenter.onDestroy(); super.onDestroyView(); } }
28.147059
101
0.776385
ca06da8fa175c74c6bb0e9e45fc2669a46dca36f
4,259
package cn.com.nexwise.sdk.common; import java.util.concurrent.Callable; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import cn.com.nexwise.sdk.common.dto.ApiResult; import cn.com.nexwise.sdk.common.dto.TaskResult; import okhttp3.Request; import okhttp3.Response; public class ApiPollCallback implements Callable<ApiResult>,Delayed { private final SimpleLogger logger = new SimpleLogger(this.getClass()); protected long timeInterval = 5000L; protected long timeout = 3 * 60 * 1000L; protected long startTime = -1L; private Api api; private String url; private long count = 0; private boolean runFlag = false; private boolean completed = false; private ApiResult done(ApiResult res) { if(!this.isCompleted()) { this.setCompleted(true); logger.info("poll callback completed {}",System.currentTimeMillis()); }else { return null; } try { api.completion.complete(res); } catch (Throwable t) { res = new ApiResult(); res.setCode(ReturnCode.ERROR); res.setMsg(Constants.COMPLETE_EXECUTE_ERROR); api.completion.complete(res); } return res; } private synchronized boolean checkToRun() { if(runFlag || completed) { return false; } long cur = System.currentTimeMillis(); long nexttime = startTime + (this.count * this.timeInterval); boolean flag = cur >= nexttime; if(flag) { runFlag = true; this.count++; } return flag; } @Override public ApiResult call() throws Exception { if(!checkToRun()) { return null; } logger.info("poll callback run {}",System.currentTimeMillis()); try { return doCall(); }catch (Throwable e) { ApiResult res = new ApiResult(); res.setCode(ReturnCode.ERROR); res.setMsg(e.getMessage()); return done(res); }finally { synchronized (this) { runFlag = false; } } } private ApiResult doCall() { // 检查是否超时 if (getDelay() < 0L) { ApiResult res = new ApiResult(); res.setCode(ReturnCode.ERROR); res.setMsg(Constants.POLLING_TIMEOUT_ERROR); return done(res); } Request.Builder builder = (new Request.Builder()) .url(url); api.fillPollingApiHeaderParams(builder); Request req = builder.build(); try (Response response = ApiClient.http.newCall(req).execute()) { if (response.code() != 200) { return done(api.httpError(response.code(), response.body().string())); } else { TaskResult ret = (TaskResult) api.task.translateResult(response.body().string()); if(!ret.checkSuccess()) { throw new ApiException(String.format(" %s code: [%s], msg [%s]", Constants.POLLING_RETURN_ERROR,ret.getCode(),ret.getMsg())); } if(ret.checkCompleted()) { return done(ret); } } } catch (Throwable e) { ApiResult res = new ApiResult(); res.setCode(ReturnCode.ERROR); res.setMsg(e.getMessage()); return done(res); } return null; } public ApiPollCallback(Api api, String url, long timeInterval, long timeout) { this.api = api; this.url = url; this.timeInterval = timeInterval; this.timeout = timeout; this.startTime = System.currentTimeMillis(); } @Override public int compareTo(Delayed o) { if(getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) { return -1; }else if(getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) { return 1; } return 0; } @Override public synchronized long getDelay(TimeUnit unit) { return startTime + timeout - System.currentTimeMillis(); } public long getDelay() { return getDelay(TimeUnit.MILLISECONDS); } public void setStartTime(long startTime) { this.startTime = startTime; } public synchronized boolean isCompleted() { return completed; } public synchronized void setCompleted(boolean completed) { this.completed = completed; } }
25.502994
90
0.61869
1bd744293a8c36ada898638b56492577003202cd
1,040
package com.archyx.aureliumskills.skills.mining; import com.archyx.aureliumskills.AureliumSkills; import com.archyx.aureliumskills.ability.Ability; import com.archyx.aureliumskills.api.event.LootDropCause; import com.archyx.aureliumskills.data.PlayerData; import com.archyx.aureliumskills.loot.LootPool; import com.archyx.aureliumskills.loot.handler.BlockLootHandler; import com.archyx.aureliumskills.skills.Skills; import com.archyx.aureliumskills.source.Source; import org.bukkit.block.Block; public class MiningLootHandler extends BlockLootHandler { public MiningLootHandler(AureliumSkills plugin) { super(plugin, Skills.MINING, Ability.MINER); } @Override public Source getSource(Block block) { return MiningSource.getSource(block); } @Override public double getChance(LootPool pool, PlayerData playerData) { return getCommonChance(pool, playerData); } @Override public LootDropCause getCause(LootPool pool) { return LootDropCause.MINING_OTHER_LOOT; } }
30.588235
67
0.773077
5cbb5075b93b6af5b0a26705fc95e5cca998fe31
1,492
package io.skysail.server.app.storymapper.story.resources; import io.skysail.server.db.DbClassName; import io.skysail.server.queryfilter.Filter; import io.skysail.server.restlet.resources.ListServerResource; import io.skysail.api.links.Link; import java.util.List; import java.util.Map; import io.skysail.server.ResourceContextId; import io.skysail.server.app.storymapper.*; import io.skysail.server.app.storymapper.map.*; import io.skysail.server.app.storymapper.map.resources.*; import io.skysail.server.app.storymapper.story.*; import io.skysail.server.app.storymapper.story.resources.*; /** * generated from listResourceNonAggregate.stg */ public class StorysResourceGen extends ListServerResource<io.skysail.server.app.storymapper.story.Story> { private StoryMapperApplication app; public StorysResourceGen() { super(StoryResourceGen.class); addToContext(ResourceContextId.LINK_TITLE, "list Storys"); } @Override protected void doInit() { app = (StoryMapperApplication) getApplication(); } @Override public List<?> getEntity() { //return repository.find(new Filter(getRequest())); String sql = "SELECT from " + DbClassName.of(Story.class) + " WHERE #" + getAttribute("id") + " IN in('pages')"; return null;//((SpaceRepository)app.getRepository(Space.class)).execute(Story.class, sql); } public List<Link> getLinks() { return super.getLinks(PostStoryResourceGen.class); } }
31.083333
120
0.728552
843fc6ad40bbc45f5bd55d2bf8ec8515418bb8ad
1,715
package io.keinix.protoflow.data.source; import android.arch.lifecycle.LiveData; import android.os.AsyncTask; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import io.keinix.protoflow.data.Routine; import io.keinix.protoflow.data.source.local.RoutineDao; @Singleton public class RoutineRepository { private RoutineDao mRoutineDao; @Inject RoutineRepository(RoutineDao routineDao) { mRoutineDao = routineDao; } void insertRoutine(Routine routine) { new insertRoutineAsync(mRoutineDao).execute(routine); } void deleteRoutine(Routine routine) { new deleteRoutineAsyncTask(mRoutineDao).execute(routine); } LiveData<List<Routine>> getAllRoutines() { return mRoutineDao.getAllRoutines(); } //---------------AsyncTasks--------------- // INSERT ASYNC private static class insertRoutineAsync extends AsyncTask<Routine, Void, Void> { private RoutineDao asyncRoutineDao; public insertRoutineAsync(RoutineDao routineDao) { asyncRoutineDao = routineDao; } @Override protected Void doInBackground(Routine... routines) { asyncRoutineDao.insertRoutine(routines[0]); return null; } } //DELETE ASYNC private static class deleteRoutineAsyncTask extends AsyncTask<Routine, Void, Void> { private RoutineDao mAsyncDao; public deleteRoutineAsyncTask(RoutineDao asyncDao) { mAsyncDao = asyncDao; } @Override protected Void doInBackground(Routine... routine) { mAsyncDao.deleteRooutine(routine[0]); return null; } } }
24.5
88
0.66414
c2da127f2b8b81a74b859415e298656ee775e440
823
package com.learning.ads.design; import java.util.PriorityQueue; /** * https://www.geeksforgeeks.org/kth-largest-element-in-a-stream/ * * * @author Arun Rahul * */ public class KthLargestElementInStream { /** * Complexity: O(n) * * @param array * @param k * @return */ public int[] find(int[] array, int k) { int c = Integer.MIN_VALUE; int[] result = new int[array.length]; int resultCounter = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(k); for (int i = 0; i < array.length; i++) { if (i < k - 1) { pq.add(array[i]); result[resultCounter++] = -1; } else { int a = array[i]; if (a >= c) { if (!pq.isEmpty()) { pq.add(a); c = pq.poll(); } else { c = a; } } result[resultCounter++] = c; } } return result; } }
17.510638
65
0.550425
f17d7951d1d2ac5e6523092dc2ab664e49239862
1,030
package cz.muni.fi.pa165.mushrooms.service.config; import cz.muni.fi.pa165.mushrooms.facade.MushroomHunterFacade; import cz.muni.fi.pa165.mushrooms.service.MushroomHunterService; import cz.muni.fi.pa165.mushrooms.validation.PersistenceSampleApplicationContext; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. * * @author bkompis */ @Configuration @Import(PersistenceSampleApplicationContext.class) @ComponentScan(basePackageClasses = {MushroomHunterService.class, MushroomHunterFacade.class}) public class ServiceConfiguration { @Bean public Mapper dozer() { DozerBeanMapper dozer = new DozerBeanMapper(); return dozer; } }
35.517241
101
0.784466
66643116ed999efe29157d5562419257a242cceb
5,173
/* * $Header: * /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons * //httpclient/src/java/org/apache/commons/httpclient/util/DateParser.java,v * 1.11 2004/11/06 19:15:42 mbecke Exp $ $Revision: 480424 $ $Date: 2006-11-29 * 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * 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. * ==================================================================== * * This software consists of voluntary contributions made by many individuals on * behalf of the Apache Software Foundation. For more information on the Apache * Software Foundation, please see <http://www.apache.org/>. */ package com.microsoft.tfs.core.httpclient.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.TimeZone; /** * A utility class for parsing HTTP dates as used in cookies and other headers. * This class handles dates as defined by RFC 2616 section 3.3.1 as well as some * other common non-standard formats. * * @author Christopher Brown * @author Michael Becke * * @deprecated Use {@link com.microsoft.tfs.core.httpclient.util.DateUtil} */ @Deprecated public class DateParser { /** * Date format pattern used to parse HTTP date headers in RFC 1123 format. */ public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in RFC 1036 format. */ public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in ANSI C * <code>asctime()</code> format. */ public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; private static final Collection DEFAULT_PATTERNS = Arrays.asList(new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 }); /** * Parses a date value. The formats used for parsing the date value are * retrieved from the default http params. * * @param dateValue * the date value to parse * * @return the parsed date * * @throws DateParseException * if the value could not be parsed using any of the supported date * formats */ public static Date parseDate(final String dateValue) throws DateParseException { return parseDate(dateValue, null); } /** * Parses the date value using the given date formats. * * @param dateValue * the date value to parse * @param dateFormats * the date formats to use * * @return the parsed date * * @throws DateParseException * if none of the dataFormats could parse the dateValue */ public static Date parseDate(String dateValue, Collection dateFormats) throws DateParseException { if (dateValue == null) { throw new IllegalArgumentException("dateValue is null"); } if (dateFormats == null) { dateFormats = DEFAULT_PATTERNS; } // trim single quotes around date if present // see issue #5279 if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'")) { dateValue = dateValue.substring(1, dateValue.length() - 1); } SimpleDateFormat dateParser = null; final Iterator formatIter = dateFormats.iterator(); while (formatIter.hasNext()) { final String format = (String) formatIter.next(); if (dateParser == null) { dateParser = new SimpleDateFormat(format, Locale.US); dateParser.setTimeZone(TimeZone.getTimeZone("GMT")); } else { dateParser.applyPattern(format); } try { return dateParser.parse(dateValue); } catch (final ParseException pe) { // ignore this exception, we will try the next format } } // we were unable to parse the date throw new DateParseException("Unable to parse the date " + dateValue); } /** This class should not be instantiated. */ private DateParser() { } }
34.952703
102
0.639474
dda706259f967677a45674ac53d69bb23e63a32c
5,500
/* * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package vm.mlvm.meth.share.transform.v2; import vm.mlvm.meth.share.Argument; import vm.mlvm.meth.share.Arguments; public abstract class MHEnvelopeArgTFPair extends MHTFPair { private final String _tag; private final int _argNum; protected final Argument _envelopeArg; protected final Argument _envelopeLocatorArg; private final Argument _componentArg; public MHEnvelopeArgTFPair(MHCall outboundTarget, String tag, int argNum, Argument envelope, Argument envelopeLocator) { super(outboundTarget); _tag = tag; _argNum = argNum; envelopeLocator.setPreserved(true); envelopeLocator.setTag(tag + "_Locator"); _envelopeLocatorArg = envelopeLocator; Argument arg = outboundTarget.getArgs()[argNum]; _componentArg = arg; envelope.setTag(tag + "_Envelope"); envelope.setPreserved(true); _envelopeArg = envelope; } @Override public MHTF getOutboundTF() { try { MHMacroTF mTF = new MHMacroTF("envelope arg outbound"); mTF.addOutboundCall(outboundTarget); Argument[] outArgs = outboundTarget.getArgs(); mTF.addTransformation(new MHPermuteTF( mTF.addTransformation(new MHFoldTF( mTF.addTransformation(new MHPermuteTF(outboundTarget, MHPermuteTF.moveArgsInPermuteArray(MHPermuteTF.getIdentityPermuteArray(outArgs.length), 0, 1, _argNum) )), mTF.addTransformation(computeGetTF(_envelopeArg, _envelopeLocatorArg)) )), MHPermuteTF.moveArgsInPermuteArray(MHPermuteTF.getIdentityPermuteArray(outArgs.length + 1), _argNum, 2, 0) )); return mTF; } catch ( Exception e ) { throw (IllegalArgumentException) (new IllegalArgumentException("Exception when creating TF")).initCause(e); } } protected abstract MHTF computeGetTF(Argument envelopeArg2, Argument envelopeLocatorArg2); @Override public MHTF getInboundTF(MHCall target) { try { Argument[] outArgs = target.getArgs(); int[] arrayArgIdxs = Arguments.findTag(outArgs, _tag + "_Envelope"); if ( arrayArgIdxs.length != 1 ) throw new IllegalArgumentException("There should be only one argument tagged [" + _tag + "_Envelope], but there are " + arrayArgIdxs); int arrayArgIdx = arrayArgIdxs[0]; int[] idxArgIdxs = Arguments.findTag(outArgs, _tag + "_Locator"); if ( idxArgIdxs.length != 1 ) throw new IllegalArgumentException("There should be only one argument tagged [" + _tag + "_Locator], but there are " + idxArgIdxs); int idxArgIdx = idxArgIdxs[0]; MHMacroTF mTF = new MHMacroTF("envelope arg inbound"); mTF.addOutboundCall(target); int[] innerPermuteArray = MHPermuteTF.getIdentityPermuteArray(outArgs.length); if ( arrayArgIdx < idxArgIdx ) innerPermuteArray = MHPermuteTF.moveArgsInPermuteArray(MHPermuteTF.moveArgsInPermuteArray(innerPermuteArray, 0, 1, arrayArgIdx), 0, 1, idxArgIdx); else innerPermuteArray = MHPermuteTF.moveArgsInPermuteArray(MHPermuteTF.moveArgsInPermuteArray(innerPermuteArray, 0, 1, idxArgIdx), 0, 1, arrayArgIdx); mTF.addTransformation(new MHPermuteTF( mTF.addTransformation(new MHInsertTF( mTF.addTransformation(new MHFoldTF( mTF.addTransformation(new MHPermuteTF(target, innerPermuteArray)), mTF.addTransformation(computeSetTF(_envelopeArg, _envelopeLocatorArg, _componentArg)) )), 0, new Argument[] { _envelopeArg, _envelopeLocatorArg }, true )), MHPermuteTF.moveArgsInPermuteArray(MHPermuteTF.getIdentityPermuteArray(outArgs.length), arrayArgIdx, 1, 0) )); return mTF; } catch ( Exception e ) { throw (IllegalArgumentException) (new IllegalArgumentException("Exception when creating TF")).initCause(e); } } protected abstract MHTF computeSetTF(Argument envelopeArg2, Argument envelopeLocatorArg2, Argument componentArg2); }
44
162
0.654182
f4104f7b2a6f7bff44e7567c6ccc722943a8e503
2,432
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_CONTENT; import static seedu.address.logic.parser.CliSyntax.PREFIX_FROM; import static seedu.address.logic.parser.CliSyntax.PREFIX_SUBJECT; import java.util.stream.Stream; import org.simplejavamail.email.Email; import org.simplejavamail.email.EmailBuilder; import seedu.address.logic.commands.ComposeEmailListCommand; import seedu.address.logic.parser.exceptions.ParseException; //@@author EatOrBeEaten /** * Parses input arguments and creates a new ComposeEmailListCommand object */ public class ComposeEmailListCommandParser implements Parser<ComposeEmailListCommand> { /** * Parses the given {@code String} of arguments in the context of the ComposeEmailListCommand * and returns an ComposeEmailListCommand object for execution. * * @throws ParseException if the user input does not conform the expected format */ public ComposeEmailListCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_FROM, PREFIX_SUBJECT, PREFIX_CONTENT); if (!arePrefixesPresent(argMultimap, PREFIX_FROM, PREFIX_SUBJECT, PREFIX_CONTENT) || !argMultimap.getPreamble().isEmpty()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ComposeEmailListCommand.MESSAGE_USAGE)); } String from = ParserUtil.parseEmail(argMultimap.getValue(PREFIX_FROM).get()).toString(); String subject = ParserUtil.parseSubject(argMultimap.getValue(PREFIX_SUBJECT).get()).toString(); String content = ParserUtil.parseContent(argMultimap.getValue(PREFIX_CONTENT).get()).toString(); Email email = EmailBuilder.startingBlank() .from(from) .withSubject(subject) .withHTMLText(content) .buildEmail(); return new ComposeEmailListCommand(email); } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
40.533333
104
0.738898
83a778bebbf34d891e0a5ab0d73e7637275b7127
2,882
/* SPDX-License-Identifier: Apache-2.0 */ package org.odpi.openmetadata.accessservices.subjectarea.properties.classifications; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.OmasObject; import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.common.SystemAttributes; import java.io.Serializable; import java.util.Date; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * A Classification */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class Classification implements Serializable, OmasObject { protected static final long serialVersionUID = 1L; //system attributes private SystemAttributes systemAttributes = null; private Date effectiveFromTime = null; private Date effectiveToTime = null; private Map<String, String> additionalProperties; protected String classificationName = null; public Classification() {} /** * Get the core attributes * * @return core attributes */ public SystemAttributes getSystemAttributes() { return systemAttributes; } public void setSystemAttributes(SystemAttributes systemAttributes) { this.systemAttributes = systemAttributes; } /** * Return the date/time that this node should start to be used (null means it can be used from creationTime). * * @return Date the node becomes effective. */ public Date getEffectiveFromTime() { return effectiveFromTime; } public void setEffectiveFromTime(Date effectiveFromTime) { this.effectiveFromTime = effectiveFromTime; } /** * Return the date/time that this node should no longer be used. * * @return Date the node stops being effective. */ public Date getEffectiveToTime() { return effectiveToTime; } public void setEffectiveToTime(Date effectiveToTime) { this.effectiveToTime = effectiveToTime; } public String getClassificationName() { return this.classificationName; } /** * Get the additional properties - ones that are in addition to the standard types. * * @return additional properties */ public Map<String, String> getAdditionalProperties() { return additionalProperties; } public void setAdditionalProperties(Map<String, String> additionalProperties) { this.additionalProperties = additionalProperties; } }
31.67033
113
0.738376
1f1f26a5949c58acb5fc29f8fa216e1d52d36f93
946
package com.bluebee.smartsupply; import com.bluebee.smartsupply.config.AppConfig; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import javax.sql.DataSource; @SpringBootApplication @EnableAutoConfiguration(exclude={ DataSourceAutoConfiguration.class }) public class SmartsupplyApplication { public static void main(String[] args) { SpringApplication.run(SmartsupplyApplication.class, args); } }
32.62069
97
0.858351
bf671a061dee0fff183abd848985a9e343c7782d
4,872
package org.folio.finc.select; import io.restassured.RestAssured; import io.restassured.parsing.Parser; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.Timeout; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.ext.web.client.WebClient; import org.folio.finc.ApiTestSuite; import org.folio.finc.TenantUtil; import org.folio.postgres.testing.PostgresTesterContainer; import org.folio.rest.RestVerticle; import org.folio.rest.client.TenantClient; import org.folio.rest.jaxrs.model.Select; import org.folio.rest.jaxrs.model.TenantAttributes; import org.folio.rest.persist.PostgresClient; import org.folio.rest.tools.utils.NetworkUtils; import org.folio.rest.utils.Constants; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @RunWith(VertxUnitRunner.class) public class SelectMetadataSourcesHelperTest { private static final String TENANT_UBL = "ubl"; private static Vertx vertx; private static SelectMetadataSourcesHelper cut; @Rule public Timeout timeout = Timeout.seconds(10); @BeforeClass public static void setUp(TestContext context) throws InterruptedException, ExecutionException, TimeoutException { vertx = Vertx.vertx(); PostgresClient.setPostgresTester(new PostgresTesterContainer()); int port = NetworkUtils.nextFreePort(); RestAssured.reset(); RestAssured.baseURI = "http://localhost"; RestAssured.port = port; RestAssured.defaultParser = Parser.JSON; DeploymentOptions options = new DeploymentOptions().setConfig(new JsonObject().put("http.port", port)); startVerticle(options); prepareTenants(); cut = new SelectMetadataSourcesHelper(vertx, TENANT_UBL); } private static void startVerticle(DeploymentOptions options) throws InterruptedException, ExecutionException, TimeoutException { CompletableFuture<String> deploymentComplete = new CompletableFuture<>(); vertx.deployVerticle( RestVerticle.class.getName(), options, res -> { if (res.succeeded()) { deploymentComplete.complete(res.result()); } else { deploymentComplete.completeExceptionally(res.cause()); } }); deploymentComplete.get(30, TimeUnit.SECONDS); } private static void prepareTenants() { String url = RestAssured.baseURI + ":" + RestAssured.port; try { CompletableFuture fincFuture = new CompletableFuture(); CompletableFuture ublFuture = new CompletableFuture(); WebClient webClient = WebClient.create(vertx); TenantClient tenantClientFinc = new TenantClient(url, Constants.MODULE_TENANT, Constants.MODULE_TENANT, webClient); TenantClient tenantClientUbl = new TenantClient(url, TENANT_UBL, TENANT_UBL, webClient); tenantClientFinc.postTenant( new TenantAttributes().withModuleTo(ApiTestSuite.getModuleVersion()), fincFuture::complete); tenantClientUbl.postTenant( new TenantAttributes().withModuleTo(ApiTestSuite.getModuleVersion()), ublFuture::complete); fincFuture.get(30, TimeUnit.SECONDS); ublFuture.get(30, TimeUnit.SECONDS); } catch (Exception e) { assert false; } } @AfterClass public static void teardown() throws InterruptedException, ExecutionException, TimeoutException { RestAssured.reset(); CompletableFuture<String> undeploymentComplete = new CompletableFuture<>(); vertx.close( res -> { if (res.succeeded()) { undeploymentComplete.complete(null); } else { undeploymentComplete.completeExceptionally(res.cause()); } }); undeploymentComplete.get(20, TimeUnit.SECONDS); PostgresClient.stopPostgresTester(); } @Test public void testSuccessfulSelect(TestContext context) { Select select = new Select().withSelect(true); Map<String, String> header = new HashMap<>(); header.put("X-Okapi-Tenant", TENANT_UBL); header.put("content-type", "application/json"); header.put("accept", "application/json"); Async async = context.async(); cut.selectAllCollectionsOfMetadataSource( TenantUtil.getMetadataSource2().getId(), select, header, ar -> { if (ar.succeeded()) { async.complete(); } else { context.fail(); } }, vertx.getOrCreateContext()); } }
33.833333
99
0.712644
a9044aad0984af850e9ca02d11dde8fe21ad01db
3,687
package com.eitan.shopik.genderFilteringPages; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.eitan.shopik.CustomItemAnimator; import com.eitan.shopik.R; import com.eitan.shopik.adapters.RecyclerGridAdapter; import com.eitan.shopik.viewModels.GenderModel; import com.eitan.shopik.viewModels.OutletsModel; public class OutletsFragment extends Fragment { private RecyclerView recyclerView; private String gender; private GenderModel model; private OutletsModel outletsModel; private TextView header; private TextView count,total; private RecyclerView.LayoutManager mLayoutManager; private RecyclerGridAdapter recyclerGridAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); model = new ViewModelProvider(requireActivity()).get(GenderModel.class); outletsModel = new ViewModelProvider(requireActivity()).get(OutletsModel.class); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_e3, container,false); header = view.findViewById(R.id.best_sellers2); count = view.findViewById(R.id.items_count); total = view.findViewById(R.id.items_total); recyclerView = view.findViewById(R.id.grid_view); mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recyclerGridAdapter = new RecyclerGridAdapter(outletsModel.getOutlets().getValue(),"outlets"); recyclerView.setItemAnimator(new CustomItemAnimator()); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); gender = model.getGender().getValue(); String header_text = "Save on Outlet"; header.setText(header_text); model.getGender().observe(getViewLifecycleOwner(), s -> { if(!gender.equals(s)) { gender = s; outletsModel.clearAllOutlets(); recyclerGridAdapter.notifyDataSetChanged(); } }); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setAdapter(recyclerGridAdapter); outletsModel.getOutlets().observe(requireActivity(), shoppingItems -> { recyclerGridAdapter.setAllItems(shoppingItems); recyclerGridAdapter.notifyDataSetChanged(); }); outletsModel.getTotalItems().observe(requireActivity(), integer -> { String text = "/ " + integer; total.setText(text); }); outletsModel.getCurrentItem().observe(requireActivity(), integer ->{ count.setText(String.valueOf(integer)); recyclerGridAdapter.notifyDataSetChanged(); }); } @Override public void onDestroyView() { super.onDestroyView(); model.getGender().removeObservers(getViewLifecycleOwner()); outletsModel.getOutlets().removeObservers(getViewLifecycleOwner()); outletsModel.getTotalItems().removeObservers(getViewLifecycleOwner()); outletsModel.getCurrentItem().removeObservers(getViewLifecycleOwner()); } }
37.242424
102
0.715758
a2d9f0fa591864bfba5659b5c8eae13af73d2ee2
2,689
/* * Copyright 2013 SFB 632. * * 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 annis; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.corpus_tools.salt.common.SDocumentGraph; import org.corpus_tools.salt.common.SDominanceRelation; import org.corpus_tools.salt.common.SSpanningRelation; import org.corpus_tools.salt.common.STextualDS; import org.corpus_tools.salt.common.STextualRelation; import org.corpus_tools.salt.core.GraphTraverseHandler; import org.corpus_tools.salt.core.SGraph.GRAPH_TRAVERSE_TYPE; import org.corpus_tools.salt.core.SNode; import org.corpus_tools.salt.core.SRelation; /** * Traverses the Salt graph and gets the covered {@link STextualDS} for a list * of nodes. * @author Thomas Krause <krauseto@hu-berlin.de> */ public class CoveredTextsCalculator implements GraphTraverseHandler { private Set<STextualDS> texts; public CoveredTextsCalculator(SDocumentGraph graph, List<SNode> startNodes) { texts = new LinkedHashSet<STextualDS>(); if (startNodes.size() > 0) { graph.traverse(new ArrayList<SNode>(startNodes), GRAPH_TRAVERSE_TYPE.TOP_DOWN_DEPTH_FIRST, "CoveredTextsCalculator", (GraphTraverseHandler) this, true); } } @Override public void nodeReached(GRAPH_TRAVERSE_TYPE traversalType, String traversalId, SNode currNode, SRelation relation, SNode fromNode, long order) { if (currNode instanceof STextualDS) { texts.add((STextualDS) currNode); } } @Override public void nodeLeft(GRAPH_TRAVERSE_TYPE traversalType, String traversalId, SNode currNode, SRelation relation, SNode fromNode, long order) { } @Override public boolean checkConstraint(GRAPH_TRAVERSE_TYPE traversalType, String traversalId, SRelation relation, SNode currNode, long order) { if (relation == null || relation instanceof SDominanceRelation || relation instanceof SSpanningRelation || relation instanceof STextualRelation) { return true; } else { return false; } } public Set<STextualDS> getCoveredTexts() { return texts; } }
29.549451
80
0.742655
d24e92f0b659a34107d35539956320df0015c5e3
4,425
package com.dice.util; import android.util.Log; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableMap; import com.google.android.exoplayer2.endeavor.WebUtil; public class MockStreamSource { public static void logRNParam(int pos, String name, ReadableType type, Object param) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < pos; i++) { builder.append(" "); } builder.append(type).append(" : "); builder.append(name).append(" : "); boolean isMap = type == ReadableType.Map; boolean isArr = type == ReadableType.Array; if (!isMap && !isArr) { builder.append(param); } Log.d(WebUtil.DEBUG, builder.toString()); // Children int childPos = pos + 4; if (isMap) { ReadableMap parent = (ReadableMap) param; ReadableMapKeySetIterator iter = parent.keySetIterator(); while (iter.hasNextKey()) { String childName = iter.nextKey(); ReadableType childType = parent.getType(childName); logRNParam(childPos, childName, childType, castRNValue(childType, parent.getDynamic(childName))); } } else if (isArr) { ReadableArray parent = (ReadableArray) param; for (int i = 0; i < parent.size(); i++) { ReadableType childType = parent.getType(i); logRNParam(childPos, "", childType, castRNValue(childType, parent.getDynamic(i))); } } } private static Object castRNValue(ReadableType type, Dynamic param) { if (type == ReadableType.Null) { return null; } else if (type == ReadableType.Map) { return param.asMap(); } else if (type == ReadableType.Array) { return param.asArray(); } else if (type == ReadableType.String) { return param.asString(); } else if (type == ReadableType.Number) { return param.asDouble(); } else if (type == ReadableType.Boolean) { return param.asBoolean(); } return null; } public static ReadableMap getMockTvStream() { WritableMap src = Arguments.createMap(); WritableMap ima = Arguments.createMap(); int startDate = (int) (System.currentTimeMillis() / 1000); int endDate = startDate + 6000; WritableMap adTagParameters = Arguments.createMap(); adTagParameters.putString("an", "prendetv"); adTagParameters.putString("output", "xml_vast4"); adTagParameters.putString("description_url", "https://univision.diceplatform.com/live/182788/test-vll-drm--ssai-big-buck-bunny"); adTagParameters.putString("url", "https://univision.diceplatform.com/live/182788/test-vll-drm--ssai-big-buck-bunny"); adTagParameters.putString("vpa", "2"); adTagParameters.putString("iu", "/6881/prendetv/live/firetv/drmtest"); adTagParameters.putString("cust_params", "tags=secretosucl,deportes,serie&program_name=secretosucl&program_id=2481&first_category=deportes&vertical=sport&content_source=tudn.com&season=1&category=deportes&video_type=fullepisode&episode=20&rating=tv-14&mcp_id=4010550&language=es&appbundle=com.univision.prendetv&deep_link=0&subscriber=1&row="); ima.putString("assetKey", "OJjJsVn4QYuWjxDW3i5WKw"); ima.putMap("adTagParameters", adTagParameters); ima.putInt("startDate", startDate); ima.putInt("endDate", endDate); WritableMap aps = Arguments.createMap(); aps.putBoolean("testMode", false); src.putMap("ima", ima); src.putBoolean("isAsset", false); src.putDouble("mainVer", 0.0); src.putMap("aps", aps); src.putString("id", "182788"); src.putDouble("patchVer", 0.0); src.putBoolean("isNetwork", true); src.putString("channelName", "Test VLL DRM + SSAI - Big Buck Bunny"); src.putString("uri", "https://dai.google.com/linear/hls/event/OJjJsVn4QYuWjxDW3i5WKw/master.m3u8"); src.putString("type", "m3u8"); return src; } }
43.382353
352
0.63774
413cf336e22785bbb5ed6781707dc826eabe19b7
1,142
package cn.lemonit.tencent_cloud_im_server_sdk.service; import cn.lemonit.tencent_cloud_im_server_sdk.exceptions.ServiceException; import cn.lemonit.tencent_cloud_im_server_sdk.model.common.ApiResponse; import cn.lemonit.tencent_cloud_im_server_sdk.utils.RestTemplateUtil; import org.springframework.http.ResponseEntity; public class BaseService { protected <T extends ApiResponse> T post(String url, Class<T> responseBodyType, Object request) throws ServiceException { ResponseEntity<T> tResponseEntity = RestTemplateUtil.getInstance().postForEntity(url, request, responseBodyType); return processResponse(url,tResponseEntity ); } protected <T extends ApiResponse> T processResponse(String url, ResponseEntity<T> response) throws ServiceException { ApiResponse body =(ApiResponse) response.getBody(); if (body.getErrorCode().equals("0")) { return response.getBody(); } else { ApiResponse respBody = response.getBody(); throw new ServiceException(url, respBody.getActionStatus(), respBody.getErrorInfo(), respBody.getErrorCode()); } } }
43.923077
125
0.749562
034d8c650e58ae4c7e05c2c19a5be4ac782ddabf
2,256
package com.snowcattle.game.net.client.tcp; import com.snowcattle.game.common.config.GameServerConfig; import com.snowcattle.game.common.constant.GlobalConstants; import com.snowcattle.game.bootstrap.manager.LocalMananger; import com.snowcattle.game.service.config.GameServerConfigService; import com.snowcattle.game.service.net.tcp.handler.GameLoggingHandler; import com.snowcattle.game.service.message.decoder.NetProtoBufMessageTCPDecoder; import com.snowcattle.game.service.message.encoder.NetProtoBufMessageTCPEncoder; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.timeout.IdleStateHandler; /** * Created by jiangwenping on 17/2/8. */ public class GameClientChannleInitializer extends ChannelInitializer<NioSocketChannel> { @Override protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { ChannelPipeline channelPipLine = nioSocketChannel.pipeline(); int maxLength = Integer.MAX_VALUE; channelPipLine.addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0)); channelPipLine.addLast("encoder", new NetProtoBufMessageTCPEncoder()); channelPipLine.addLast("decoder", new NetProtoBufMessageTCPDecoder()); int readerIdleTimeSeconds = 0; int writerIdleTimeSeconds = 0; int allIdleTimeSeconds = GlobalConstants.Net.SESSION_HEART_ALL_TIMEOUT; GameServerConfigService gameServerConfigService = LocalMananger.getInstance().getLocalSpringServiceManager().getGameServerConfigService(); GameServerConfig gameServerConfig = gameServerConfigService.getGameServerConfig(); if(gameServerConfig.isDevelopModel()) { channelPipLine.addLast("logger", new GameLoggingHandler(LogLevel.DEBUG)); } channelPipLine.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)); // channelPipLine.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); channelPipLine.addLast("handler", new GameClientHandler()); } }
52.465116
146
0.791223
a9ca5a18b61276d358efcd60db1889aec50ff671
1,909
package org.evomaster.client.java.controller; import org.evomaster.client.java.controller.api.dto.ActionDto; import org.evomaster.client.java.controller.api.dto.UnitsInfoDto; import org.evomaster.client.java.controller.internal.SutController; import org.evomaster.client.java.instrumentation.*; import org.evomaster.client.java.instrumentation.staticstate.ExecutionTracer; import org.evomaster.client.java.instrumentation.staticstate.UnitsInfoRecorder; import java.util.Collection; import java.util.List; public abstract class EmbeddedSutController extends SutController { @Override public final void setupForGeneratedTest(){ /* We need to configure P6Spy for example, otherwise by default it will generate an annoying spy.log file */ String driverName = getDatabaseDriverName(); if(driverName != null) { InstrumentingAgent.initP6Spy(driverName); } } @Override public final boolean isInstrumentationActivated() { return InstrumentingAgent.isActive(); } @Override public final void newSearch(){ InstrumentationController.resetForNewSearch(); } @Override public final void newTestSpecificHandler(){ InstrumentationController.resetForNewTest(); } @Override public final List<TargetInfo> getTargetInfos(Collection<Integer> ids){ return InstrumentationController.getTargetInfos(ids); } @Override public final List<AdditionalInfo> getAdditionalInfoList(){ return InstrumentationController.getAdditionalInfoList(); } @Override public final void newActionSpecificHandler(ActionDto dto){ ExecutionTracer.setAction(new Action(dto.index, dto.inputVariables)); } @Override public final UnitsInfoDto getUnitsInfoDto(){ return getUnitsInfoDto(UnitsInfoRecorder.getInstance()); } }
30.301587
80
0.72813
75f1d28807cdd832370a1452fb038934d08cda93
1,619
package com.koolearn.android.kooreader.preferences; import android.content.Context; import com.koolearn.klibrary.core.options.ZLStringOption; import com.koolearn.klibrary.core.resources.ZLResource; import com.koolearn.klibrary.ui.android.view.AndroidFontUtil; import java.util.ArrayList; class FontPreference extends ZLStringListPreference implements ReloadablePreference { private final ZLStringOption myOption; private final boolean myIncludeDummyValue; private static String UNCHANGED = "inherit"; FontPreference(Context context, ZLResource resource, ZLStringOption option, boolean includeDummyValue) { super(context, resource); myOption = option; myIncludeDummyValue = includeDummyValue; reload(); } public void reload() { final ArrayList<String> fonts = new ArrayList<String>(); AndroidFontUtil.fillFamiliesList(fonts); if (myIncludeDummyValue) { fonts.add(0, UNCHANGED); } setList(fonts.toArray(new String[fonts.size()])); final String optionValue = myOption.getValue(); final String initialValue = optionValue.length() > 0 ? AndroidFontUtil.realFontFamilyName(optionValue) : UNCHANGED; for (String fontName : fonts) { if (initialValue.equals(fontName)) { setInitialValue(fontName); return; } } for (String fontName : fonts) { if (initialValue.equals(AndroidFontUtil.realFontFamilyName(fontName))) { setInitialValue(fontName); return; } } } @Override protected void onDialogClosed(boolean result) { super.onDialogClosed(result); final String value = getValue(); myOption.setValue(UNCHANGED.equals(value) ? "" : value); } }
28.403509
105
0.759111
e2dce8df0f511618c06be81e1b50e92d03c78d4c
5,085
package com.stripe.example.module; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.ListView; import com.stripe.android.model.Card; import com.stripe.android.view.CardInputWidget; import com.stripe.example.controller.AsyncTaskTokenController; import com.stripe.example.controller.ErrorDialogHandler; import com.stripe.example.controller.IntentServiceTokenController; import com.stripe.example.controller.ListViewController; import com.stripe.example.controller.ProgressDialogController; import com.stripe.example.controller.RxTokenController; /** * A dagger-free simple way to handle dependencies in the Example project. Most of this work would * ordinarily be done in a module class. */ public class DependencyHandler { private AsyncTaskTokenController mAsyncTaskController; private CardInputWidget mCardInputWidget; private Context mContext; private ErrorDialogHandler mErrorDialogHandler; private IntentServiceTokenController mIntentServiceTokenController; private ListViewController mListViewController; private RxTokenController mRxTokenController; private ProgressDialogController mProgresDialogController; public DependencyHandler( AppCompatActivity activity, CardInputWidget cardInputWidget, ListView outputListView) { mCardInputWidget = cardInputWidget; mContext = activity.getBaseContext(); mProgresDialogController = new ProgressDialogController(activity.getSupportFragmentManager()); mListViewController = new ListViewController(outputListView); mErrorDialogHandler = new ErrorDialogHandler(activity.getSupportFragmentManager()); } /** * Attach a listener that creates a token using the {@link android.os.AsyncTask}-based method. * Only gets attached once, unless you call {@link #clearReferences()}. * * @param button a button that, when clicked, gets a token. * @return a reference to the {@link AsyncTaskTokenController} */ @NonNull public AsyncTaskTokenController attachAsyncTaskTokenController(Button button) { if (mAsyncTaskController == null) { mAsyncTaskController = new AsyncTaskTokenController( button, mCardInputWidget, mContext, mErrorDialogHandler, mListViewController, mProgresDialogController); } return mAsyncTaskController; } /** * Attach a listener that creates a token using an {@link android.app.IntentService} and the * synchronous {@link com.stripe.android.Stripe#createTokenSynchronous(Card, String)} method. * * Only gets attached once, unless you call {@link #clearReferences()}. * * @param button a button that, when clicked, gets a token. * @return a reference to the {@link IntentServiceTokenController} */ @NonNull public IntentServiceTokenController attachIntentServiceTokenController( AppCompatActivity appCompatActivity, Button button) { if (mIntentServiceTokenController == null) { mIntentServiceTokenController = new IntentServiceTokenController( appCompatActivity, button, mCardInputWidget, mErrorDialogHandler, mListViewController, mProgresDialogController); } return mIntentServiceTokenController; } /** * Attach a listener that creates a token using a {@link rx.Subscription} and the * synchronous {@link com.stripe.android.Stripe#createTokenSynchronous(Card, String)} method. * * Only gets attached once, unless you call {@link #clearReferences()}. * * @param button a button that, when clicked, gets a token. * @return a reference to the {@link RxTokenController} */ @NonNull public RxTokenController attachRxTokenController(Button button) { if (mRxTokenController == null) { mRxTokenController = new RxTokenController( button, mCardInputWidget, mContext, mErrorDialogHandler, mListViewController, mProgresDialogController); } return mRxTokenController; } /** * Clear all the references so that we can start over again. */ public void clearReferences() { if (mAsyncTaskController != null) { mAsyncTaskController.detach(); } if (mRxTokenController != null) { mRxTokenController.detach(); } if (mIntentServiceTokenController != null) { mIntentServiceTokenController.detach(); } mAsyncTaskController = null; mRxTokenController = null; mIntentServiceTokenController = null; } }
36.321429
98
0.67237
e68d50673b36764a63fcb8795dcc0076d09bcca2
1,413
package com.dmg.fusion.config; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class SaleSystemConfig { private static SaleSystemConfig instance = null; private static final String CONFIG_LOCATION = System.getProperty("config.location"); private SaleSystemConfig() throws IOException { Properties prop = new Properties(); InputStream input = new FileInputStream(CONFIG_LOCATION); prop.load(input); this.providerIdentification = prop.getProperty("provider.identification"); this.applicationName = prop.getProperty("application.name"); this.softwareVersion = prop.getProperty("software.version"); this.certificationCode = prop.getProperty("certification.code"); } private String providerIdentification; private String applicationName; private String softwareVersion; private final String certificationCode; public String getProviderIdentification() { return providerIdentification; } public String getApplicationName() { return applicationName; } public String getSoftwareVersion() { return softwareVersion; } public String getCertificationCode() { return certificationCode; } public static SaleSystemConfig getInstance() throws IOException { if (SaleSystemConfig.instance == null) { SaleSystemConfig.instance = new SaleSystemConfig(); } return SaleSystemConfig.instance; } }
25.690909
85
0.785563
7380dddf6a66918a167d50587437510858d060a0
998
package com.xandersu.class082_leetcode.chapter_4; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author suxun * @date 2020/8/8 12:35 * @description */ public class $1_349_intersection_of_two_arrays_My { public static int[] intersection(int[] nums1, int[] nums2) { if (nums1 == null) { return nums2; } if (nums2 == null) { return nums1; } Set<Integer> resultSet = new HashSet<>(); for (int i = 0; i < nums1.length; i++) { int num = nums1[i]; for (int j = 0; j < nums2.length; j++) { if (num == nums2[j]) { resultSet.add(num); } } } int[] res = new int[resultSet.size()]; int index = 0; for (int num : resultSet) { res[index++] = num; } return res; } public static void main(String[] args) { } }
23.209302
64
0.504008
dec80bee67e761095ea1955d1a05e482dfbb76a5
928
package com.nmmoc7.polymercore.api.util; /** * 表示一个属性的Key * * @param <T> */ public class AttributeKey<T> { private final Class<T> valueClass; private final String attributeName; private AttributeKey(Class<T> valueClass, String attributeName) { this.valueClass = valueClass; this.attributeName = attributeName; } /** * 创建一个属性Key * * @param valueClass 属性的类型,仅用于变量类型转换 * @param name 属性实际存储的key,注意不要冲突 */ public static <T> AttributeKey<T> create(Class<T> valueClass, String name) { return new AttributeKey<>(valueClass, name); } public T cast(Object o) { return valueClass.cast(o); } public boolean isInstance(Object o) { return valueClass.isInstance(o); } public Class<T> getValueClass() { return valueClass; } public String getAttributeName() { return attributeName; } }
21.090909
80
0.626078
cc1ac3d4d4a259e511e71bb780fc7e0dc34d12c5
1,152
package br.com.zup.mercadolivre.email; import br.com.zup.mercadolivre.email.dto.SendEmailRequest; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.validation.Valid; @Service public class EmailService { final JavaMailSenderImpl emailSender; public EmailService(JavaMailSenderImpl emailSender) { this.emailSender = emailSender; } public void sendEmail(@Valid SendEmailRequest request) { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message); try { mimeMessageHelper.setTo(request.getRecipient()); mimeMessageHelper.setFrom(request.getFrom()); mimeMessageHelper.setSubject(request.getSubject()); mimeMessageHelper.setText(request.getMessage()); } catch (MessagingException e) { e.printStackTrace(); } emailSender.send(message); } }
32
77
0.731771
0fd4735f509268f64001666a1a91282be3d7c94d
544
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.notification.impl; import com.intellij.util.xmlb.annotations.Attribute; /** * @author Alexander Lobas */ @Deprecated public final class NotificationGroupBean { @Attribute("parentId") public String parentId; @Attribute("groupId") public String groupId; @Attribute("replaceTitle") public String replaceTitle; @Attribute("shortTitle") public String shortTitle; }
24.727273
140
0.757353