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 |
|---|---|---|---|---|---|
aa0f06694750f748d816deba590bf13f82ddd310 | 2,254 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.samza.operators.spec;
import org.apache.samza.operators.functions.SinkFunction;
import org.apache.samza.operators.functions.TimerFunction;
import org.apache.samza.operators.functions.WatermarkFunction;
/**
* The spec for an operator that outputs a stream to an arbitrary external system.
* <p>
* This is a terminal operator and does not allow further operator chaining.
*
* @param <M> the type of input message
*/
public class SinkOperatorSpec<M> extends OperatorSpec<M, Void> {
private final SinkFunction<M> sinkFn;
/**
* Constructs a {@link SinkOperatorSpec} with a user defined {@link SinkFunction}.
*
* @param sinkFn a user defined {@link SinkFunction} that will be called with the output message,
* the output {@link org.apache.samza.task.MessageCollector} and the
* {@link org.apache.samza.task.TaskCoordinator}.
* @param opId the unique ID of this {@link OperatorSpec} in the graph
*/
SinkOperatorSpec(SinkFunction<M> sinkFn, String opId) {
super(OpCode.SINK, opId);
this.sinkFn = sinkFn;
}
public SinkFunction<M> getSinkFn() {
return this.sinkFn;
}
@Override
public WatermarkFunction getWatermarkFn() {
return sinkFn instanceof WatermarkFunction ? (WatermarkFunction) sinkFn : null;
}
@Override
public TimerFunction getTimerFn() {
return sinkFn instanceof TimerFunction ? (TimerFunction) sinkFn : null;
}
}
| 35.21875 | 100 | 0.72937 |
83834c21d9c0acbf05921e676cb36d31c6ba78db | 1,316 | package org.broadinstitute.ddp.model.activity.instance.answer;
import java.io.Serializable;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import com.google.gson.annotations.SerializedName;
import org.jdbi.v3.core.mapper.reflect.ColumnName;
import org.jdbi.v3.core.mapper.reflect.JdbiConstructor;
public class FileInfo implements Serializable {
@NotBlank
@SerializedName("fileName")
private String fileName;
@Positive
@SerializedName("fileSize")
private long fileSize;
private transient long uploadId;
private transient String uploadGuid;
@JdbiConstructor
public FileInfo(@ColumnName("file_upload_id") long uploadId,
@ColumnName("file_upload_guid") String uploadGuid,
@ColumnName("file_name") String fileName,
@ColumnName("file_size") long fileSize) {
this.uploadId = uploadId;
this.uploadGuid = uploadGuid;
this.fileName = fileName;
this.fileSize = fileSize;
}
public long getUploadId() {
return uploadId;
}
public String getUploadGuid() {
return uploadGuid;
}
public String getFileName() {
return fileName;
}
public long getFileSize() {
return fileSize;
}
}
| 25.803922 | 70 | 0.680091 |
b439e55b7a59099b7f704248745addf10e880f7f | 452 | package com.pf.system.constants.enums;
import com.pf.base.BaseErrCode;
/**
* @ClassName : TableFieldTypeEnum
* @Description :
* @Author : wangjie
* @Date: 2021/10/19-17:38
*/
public enum TableFieldTypeEnum {
SELECTION( 0 ),
EXPAND( 1 ) ,
INDEX( 2 ) ,
NORMAL( 3 ),
;
private final int code;
TableFieldTypeEnum(int code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
| 15.586207 | 38 | 0.595133 |
3be3eb4d785321d52964290b254c354e147cde9c | 3,044 | package net.minecraft.core;
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
import java.util.Random;
public class BlockMinecartTrack extends Block {
protected BlockMinecartTrack(int i, int j) {
super(i, j, Material.circuits);
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F);
}
public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int i, int j, int k) {
return null;
}
public boolean allowsAttachment() {
return false;
}
public MovingObjectPosition collisionRayTrace(World world, int i, int j, int k, Vec3D vec3d, Vec3D vec3d1) {
setBlockBoundsBasedOnState(world, i, j, k);
return super.collisionRayTrace(world, i, j, k, vec3d, vec3d1);
}
public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, int i, int j, int k) {
int l = iblockaccess.getBlockMetadata(i, j, k);
if (l >= 2 && l <= 5) {
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F);
} else {
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F);
}
}
public int quantityDropped(Random random) {
return 1;
}
public boolean canPlaceBlockAt(World world, int i, int j, int k) {
return world.doesBlockAllowAttachment(i, j - 1, k);
}
public void onBlockAdded(World world, int i, int j, int k) {
if (!world.multiplayerWorld) {
world.setBlockMetadataWithNotify(i, j, k, 15);
func_4038_g(world, i, j, k);
}
}
public void onNeighborBlockChange(World world, int i, int j, int k, int l) {
if (world.multiplayerWorld) {
return;
}
int i1 = world.getBlockMetadata(i, j, k);
boolean flag = false;
if (!world.doesBlockAllowAttachment(i, j - 1, k)) {
flag = true;
}
if (i1 == 2 && !world.doesBlockAllowAttachment(i + 1, j, k)) {
flag = true;
}
if (i1 == 3 && !world.doesBlockAllowAttachment(i - 1, j, k)) {
flag = true;
}
if (i1 == 4 && !world.doesBlockAllowAttachment(i, j, k - 1)) {
flag = true;
}
if (i1 == 5 && !world.doesBlockAllowAttachment(i, j, k + 1)) {
flag = true;
}
if (flag) {
dropBlockAsItem(world, i, j, k, world.getBlockMetadata(i, j, k));
world.setBlockWithNotify(i, j, k, 0);
} else if (l > 0 && Block.blocksList[l].canProvidePower() && MinecartTrackLogic.func_600_a(new MinecartTrackLogic(this, world, i, j, k)) == 3) {
func_4038_g(world, i, j, k);
}
}
private void func_4038_g(World world, int i, int j, int k) {
if (world.multiplayerWorld) {
return;
} else {
(new MinecartTrackLogic(this, world, i, j, k)).func_596_a(world.isBlockIndirectlyGettingPowered(i, j, k));
return;
}
}
}
| 33.822222 | 152 | 0.57523 |
5ae2d7c891691e20fa109327206596c0a7c564c6 | 2,157 | package us.fjj.spring.learning.annotationdeclarativetransactionmanagement;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
private UserDao userDao;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void createUserTable() {
this.jdbcTemplate.execute("CREATE TABLE `user4` (`id` INTEGER PRIMARY KEY, `name` VARCHAR(50) DEFAULT NULL, `age` INTEGER DEFAULT NULL)");
}
@Override
public void saveUser(User user) {
try {
this.jdbcTemplate.update("INSERT INTO user4(name, age) VALUES (?,?)", user.getName(), user.getAge());
}catch (Exception e) {
System.out.println("error in creating record, rolling back");
throw e;
}
}
@Override
public List<User> listUser() {
List<User> users = this.jdbcTemplate.query("SELECT name, age FROM user4", new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
});
return users;
}
}
| 31.720588 | 146 | 0.668521 |
bf4a01e01e28933efd7be8d68be6703f8591d3b1 | 6,845 | /*
* Copyright (c) 2010-2017 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.web.page.admin.certification.dto;
import com.evolveum.midpoint.gui.api.util.ModelServiceLocator;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.schema.util.CertCampaignTypeUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang3.StringUtils;
import javax.xml.datatype.Duration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kate on 15.12.2015.
*/
public class StageDefinitionDto implements Serializable {
public final static String F_NUMBER = "number";
public final static String F_NAME = "name";
public final static String F_DESCRIPTION = "description";
public final static String F_DURATION = "duration";
public final static String F_NOTIFY_BEFORE_DEADLINE = "notifyBeforeDeadline";
public final static String F_NOTIFY_ONLY_WHEN_NO_DECISION = "notifyOnlyWhenNoDecision";
public final static String F_REVIEWER_SPECIFICATION = "reviewerSpecification";
public final static String F_REVIEWER_DTO = "reviewerDto";
public final static String F_OUTCOME_STRATEGY = "outcomeStrategy";
public final static String F_OUTCOME_IF_NO_REVIEWERS = "outcomeIfNoReviewers";
private int number;
private String name;
private String description;
private String duration;
private DeadlineRoundingType deadlineRounding;
private String notifyBeforeDeadline;
private boolean notifyOnlyWhenNoDecision;
private AccessCertificationReviewerDto reviewerDto;
private AccessCertificationCaseOutcomeStrategyType outcomeStrategy;
private AccessCertificationResponseType outcomeIfNoReviewers;
private List<AccessCertificationResponseType> stopReviewOnRaw;
private List<AccessCertificationResponseType> advanceToNextStageOnRaw;
private List<WorkItemTimedActionsType> timedActionsTypes;
public StageDefinitionDto(AccessCertificationStageDefinitionType stageDefObj, ModelServiceLocator modelServiceLocator) throws SchemaException {
if (stageDefObj != null) {
setNumber(stageDefObj.getNumber());
setName(stageDefObj.getName());
setDescription(stageDefObj.getDescription());
if (stageDefObj.getDuration() != null) {
setDuration(stageDefObj.getDuration().toString());
}
setDeadlineRounding(stageDefObj.getDeadlineRounding());
setNotifyBeforeDeadline(convertDurationListToString(stageDefObj.getNotifyBeforeDeadline()));
setNotifyOnlyWhenNoDecision(Boolean.TRUE.equals(stageDefObj.isNotifyOnlyWhenNoDecision()));
setReviewerDto(new AccessCertificationReviewerDto(stageDefObj.getReviewerSpecification(), modelServiceLocator));
setOutcomeStrategy(stageDefObj.getOutcomeStrategy());
setOutcomeIfNoReviewers(stageDefObj.getOutcomeIfNoReviewers());
setStopReviewOnRaw(new ArrayList<>(stageDefObj.getStopReviewOn()));
setAdvanceToNextStageOnRaw(new ArrayList<>(stageDefObj.getAdvanceToNextStageOn()));
setTimedActionsTypes(new ArrayList<>(stageDefObj.getTimedActions()));
} else {
setReviewerDto(new AccessCertificationReviewerDto(null, modelServiceLocator));
}
}
private String convertDurationListToString(List<Duration> list){
return StringUtils.join(list, ", ");
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public DeadlineRoundingType getDeadlineRounding() {
return deadlineRounding;
}
public void setDeadlineRounding(DeadlineRoundingType deadlineRounding) {
this.deadlineRounding = deadlineRounding;
}
public String getNotifyBeforeDeadline() {
return notifyBeforeDeadline;
}
public void setNotifyBeforeDeadline(String notifyBeforeDeadline) {
this.notifyBeforeDeadline = notifyBeforeDeadline;
}
public boolean isNotifyOnlyWhenNoDecision() {
return notifyOnlyWhenNoDecision;
}
public void setNotifyOnlyWhenNoDecision(boolean notifyOnlyWhenNoDecision) {
this.notifyOnlyWhenNoDecision = notifyOnlyWhenNoDecision;
}
public AccessCertificationReviewerDto getReviewerDto() {
return reviewerDto;
}
public void setReviewerDto(AccessCertificationReviewerDto reviewerDto) {
this.reviewerDto = reviewerDto;
}
public AccessCertificationCaseOutcomeStrategyType getOutcomeStrategy() {
return outcomeStrategy;
}
public void setOutcomeStrategy(AccessCertificationCaseOutcomeStrategyType outcomeStrategy) {
this.outcomeStrategy = outcomeStrategy;
}
public AccessCertificationResponseType getOutcomeIfNoReviewers() {
return outcomeIfNoReviewers;
}
public void setOutcomeIfNoReviewers(AccessCertificationResponseType outcomeIfNoReviewers) {
this.outcomeIfNoReviewers = outcomeIfNoReviewers;
}
public List<AccessCertificationResponseType> getStopReviewOn() {
if (stopReviewOnRaw.isEmpty() && advanceToNextStageOnRaw.isEmpty()) {
return null;
}
return CertCampaignTypeUtil.getOutcomesToStopOn(stopReviewOnRaw, advanceToNextStageOnRaw);
}
public List<AccessCertificationResponseType> getStopReviewOnRaw() {
return stopReviewOnRaw;
}
public void setStopReviewOnRaw(List<AccessCertificationResponseType> stopReviewOnRaw) {
this.stopReviewOnRaw = stopReviewOnRaw;
}
public List<AccessCertificationResponseType> getAdvanceToNextStageOnRaw() {
return advanceToNextStageOnRaw;
}
public void setAdvanceToNextStageOnRaw(List<AccessCertificationResponseType> advanceToNextStageOnRaw) {
this.advanceToNextStageOnRaw = advanceToNextStageOnRaw;
}
public List<WorkItemTimedActionsType> getTimedActionsTypes() {
return timedActionsTypes;
}
public void setTimedActionsTypes(List<WorkItemTimedActionsType> timedActionsTypes) {
this.timedActionsTypes = timedActionsTypes;
}
}
| 36.409574 | 147 | 0.740979 |
b7aa81475c56cf563611b612a41db68605590ba2 | 23,178 | package lattice;
/*
* Concept.java
*
*
* Copyright: 2013-2014 Karell Bertet, France
*
* License: http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html CeCILL-B license
*
* This file is part of java-lattices, free package. You can redistribute it and/or modify
* it under the terms of CeCILL-B license.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeSet;
import dgraph.Node;
import dgraph.DGraph;
import dgraph.DAGraph;
import dgraph.Edge;
/**
* This class gives a representation for a concept, i.e. a node of a concept lattice.
*
* A concept extends class {@link Node} by providing two comparable sets defined
* by {@link ComparableSet}, namely `setA` and `setB`, aiming at storing set of a concepts.
*
* This component can also be used to store a closed set by using only set `A`.
*
* This class implements class `Comparable` aiming at
* sorting concepts by providing the {@link #compareTo} method.
* Comparison between this component and those in parameter is realised by comparing set `A`.
*
* @todo Should not inherit from Node since content is not used
*
* 
*
* @uml Concept.png
* !include src/dgraph/Node.iuml
* !include src/lattice/Concept.iuml
* !include src/lattice/ComparableSet.iuml
*
* hide members
* show Concept members
* class Concept #LightCyan
* title Concept UML graph
*/
public class Concept extends Node {
/* ------------- FIELDS ------------------ */
/**
* This first set of comparable elements of the concept.
*/
private ComparableSet setA;
/**
* This second set of comparable elements of the concept.
*/
private ComparableSet setB;
/* ------------- CONSTRUCTORS ------------------ */
/**
* Constructs a new concept containing the specified comparables set as setA and setB.
*
* @param setA set of comparable used to initialise setA.
* @param setB set of comparable used to initialise setB.
*/
public Concept(TreeSet<Comparable> setA, TreeSet<Comparable> setB) {
this.setA = new ComparableSet(setA);
this.setB = new ComparableSet(setB);
}
/**
* Constructs a new concept with an empty set of comparableset as setA and set B if the two boolean are true.
* False booleans allow to construct a concept with only one of the two sets.
*
* @param setA field setA is empty if true, setA is null if false.
* @param setB field setB is empty if true, setB is null if false.
*/
public Concept(boolean setA, boolean setB) {
if (setA) {
this.setA = new ComparableSet();
} else {
this.setA = null;
}
if (setB) {
this.setB = new ComparableSet();
} else {
this.setB = null;
}
}
/**
* Constructs a new concept containing the specified comparables set as setA, and an empty set of comparableset as setB if the boolean is true.
* A false boolean allows to construct a concept with the only set A.
*
* @param setA set of comparable used to initialise setA.
* @param setB field setB is empty if true, setB is null if false.
*/
public Concept(TreeSet<Comparable> setA, boolean setB) {
this.setA = new ComparableSet(setA);
if (setB) {
this.setB = new ComparableSet();
} else {
this.setB = null;
}
}
/**
* Constructs a new concept containing the specified comparables set as setB, and an empty set of comparableset as setA if the boolean is true.
* A false boolean allows to construct concept with the only set B.
*
* @param setA field setA is empty if true, setA is null if false.
* @param setB set of comparable used to initialise setB.
*/
public Concept(boolean setA, TreeSet<Comparable> setB) {
this.setB = new ComparableSet(setB);
if (setA) {
this.setA = new ComparableSet();
} else {
this.setA = null;
}
}
/**
* Constructs this component as a copy of the specified ClosedSet.
*
* @param c the closed set to be copied
*/
public Concept(Concept c) {
if (c.hasSetA()) {
this.setA = new ComparableSet(c.getSetA());
} else {
this.setA = null;
}
if (c.hasSetB()) {
this.setB = new ComparableSet(c.getSetB());
} else {
this.setB = null;
}
}
/* --------------- ACCESSOR AND OVERLAPPING METHODS ------------ */
/**
* Returns a copy of this component.
*
* @return a copy of this component
*/
public Concept copy() {
if (this.hasSetA() && this.hasSetB()) {
TreeSet setA = (TreeSet) this.getSetA().clone();
TreeSet setB = (TreeSet) this.getSetB().clone();
return new Concept(setA, setB);
}
if (this.hasSetA() && !this.hasSetB()) {
TreeSet setA = (TreeSet) this.getSetA().clone();
return new Concept(setA, false);
} else {
if (this.hasSetB()) {
TreeSet setB = (TreeSet) this.getSetB().clone();
return new Concept(false, setB);
} else {
return new Concept(false, false);
}
}
}
/**
* Checks if the concept has an empty set B.
*
* @return true if and only if setB is not null
*/
public boolean hasSetB() {
return this.setB != null;
}
/**
* Checks if the concept has an empty set A.
*
* @return true if and only if setA is not null
*/
public boolean hasSetA() {
return this.setA != null;
}
/**
* Returns the set A of this component.
*
* @return the set A of this component
*/
public TreeSet<Comparable> getSetA() {
return this.setA;
}
/**
* Returns the set B of comparable of this component.
*
* @return the set B of this component.
*/
public TreeSet<Comparable> getSetB() {
return this.setB;
}
/**
* Checks if the set A contains the specified comparable.
*
* @param x comparable to find in setA.
*
* @return true if and only if setA contains x.
*/
public boolean containsInA(Comparable x) {
if (this.hasSetA()) {
return this.setA.contains(x);
} else {
return false;
}
}
/**
* Checks if the set B contains the specified comparable.
*
* @param x comparable to find in setB.
*
* @return true if and only if setB contains x.
*/
public boolean containsInB(Comparable x) {
if (this.hasSetB()) {
return this.setB.contains(x);
} else {
return false;
}
}
/**
* Checks if the set A contains the specified set of comparable.
*
* @param x set of comparable to find in setA.
*
* @return true if and only if setA contains all elemens of x.
*/
public boolean containsAllInA(TreeSet x) {
if (this.hasSetA()) {
return this.setA.containsAll(x);
} else {
return false;
}
}
/**
* Checks if the set B contains the specified set of comparable.
*
* @param x set of comparable to find in setB.
*
* @return true if and only if setB contains all elemens of x.
*/
public boolean containsAllInB(TreeSet x) {
if (this.hasSetB()) {
return this.setB.containsAll(x);
} else {
return false;
}
}
/**
* Replaces the set A of this component by the specified one.
*
* @param x set of comparable used to replace setB
*/
public void putSetB(ComparableSet x) {
if (this.hasSetB()) {
this.setB = x;
} else {
this.setB = new ComparableSet(x);
}
}
/**
* Replaces the set A of this component by the specified one.
*
* @param x set of comparable used to replace setA
*/
public void putSetA(ComparableSet x) {
if (this.hasSetA()) {
this.setA = x;
} else {
this.setA = new ComparableSet(x);
}
}
/**
* Adds a comparable to the set A.
*
* @param x comparable to add to setA
*
* @return true if and only if addition is successful.
*/
public boolean addToA(Comparable x) {
if (this.hasSetA()) {
return this.setA.add(x);
} else {
return false;
}
}
/**
* Adds a comparable to the set B.
*
* @param x comparable to add to setB
*
* @return true if and only if addition is successful.
*/
public boolean addToB(Comparable x) {
if (this.hasSetB()) {
return this.setB.add(x);
} else {
return false;
}
}
/**
* Adds the specified set of comparable to the set A.
*
* @param x set of comparable to add to setA
*
* @return true if and only if addition is successful.
*/
public boolean addAllToA(TreeSet x) {
if (this.hasSetA()) {
return this.setA.addAll(x);
} else {
return false;
}
}
/**
* Adds the specified set of comparable to the set B.
*
* @param x set of comparable to add to setB
*
* @return true if and only if addition is successful.
*/
public boolean addAllToB(TreeSet x) {
if (this.hasSetB()) {
return this.setB.addAll(x);
} else {
return false;
}
}
/**
* Remove a comparable from the set A.
*
* @param x comparable to remove from setA
*
* @return true if and only if removal is successful.
*/
public boolean removeFromA(Comparable x) {
if (this.hasSetA()) {
return this.setA.remove(x);
} else {
return false;
}
}
/**
* Remove a comparable from the set B.
*
* @param x comparable to remove from setB
*
* @return true if and only if removal is successful.
*/
public boolean removeFromB(Comparable x) {
if (this.hasSetB()) {
return this.setB.remove(x);
} else {
return false;
}
}
/**
* Remove a set of comparable from the set A.
*
* @param x set to remove from setA
*
* @return true if and only if removal is successful.
*/
public boolean removeAllFromA(TreeSet x) {
if (this.hasSetA()) {
return this.setA.removeAll(x);
} else {
return false;
}
}
/**
* Remove a set of comparable from the set B.
*
* @param x set to remove from setB
*
* @return true if and only if removal is successful.
*/
public boolean removeAllFromB(TreeSet x) {
if (this.hasSetB()) {
return this.setB.removeAll(x);
} else {
return false;
}
}
/* --------------- OVERLAPPING METHODS ------------ */
/**
* Returns the description of this component in a String without spaces.
*
* @return the description of this component in a String without spaces.
*/
public String toString() {
String s = "";
if (this.hasSetA()) {
s += this.setA;
}
if (this.hasSetA() && this.hasSetB()) {
s += "-";
}
if (this.hasSetB()) {
s += this.setB;
}
StringTokenizer st = new StringTokenizer(s);
s = "";
while (st.hasMoreTokens()) {
s += st.nextToken();
}
return s;
}
/**
* Returns the hash code of this component.
*
* @return hash code of this component
*/
public int hashCode() {
return super.hashCode();
}
/**
* Compares this component with the specified one.
*
* @param o object compared to this component.
*
* @return true if and only if o is equals to this component.
*/
public boolean equals(Object o) {
if (!(o instanceof Concept)) {
return false;
}
if (!this.hasSetB()) {
return this.setA.equals(((Concept) o).setA);
}
if (!this.hasSetA()) {
return this.setB.equals(((Concept) o).setB);
}
return this.setA.equals(((Concept) o).setA) && this.setB.equals(((Concept) o).setB);
}
/** Compares this component with the specified one sorted by the lectic order.
* @return a negative integer, zero, or a positive integer as this component is less than,
* equal to, or greater than the specified object.
*/
/*public int compareTo(Object o){
if (!(o instanceof lattice.Concept)) return -1;
Concept c = (Concept) o;
//System.out.println("compareTo : "+this+" "+o);
if (!this.hasSetB()) {
return this.setA.compareTo(c.setA);
}
if (!this.hasSetA()) {
return this.setB.compareTo(c.setB);
}
if (this.setA.compareTo(c.setA)!=0) {
return this.setB.compareTo(c.setB);
} else {
return this.setA.compareTo(c.setA);
}
}*/
/**
* Computes the immediate successors of this component with the LOA algorithm.
*
* @param init context from which successor of this component are computed.
*
* @return immediate successors of this component.
*/
public ArrayList<TreeSet<Comparable>> immediateSuccessorsLOA(Context init) {
ArrayList<TreeSet<Comparable>> succB = new ArrayList();
TreeSet<Comparable> attributes = (TreeSet<Comparable>) init.getSet().clone();
attributes.removeAll(this.getSetA());
boolean add;
for (Comparable x : attributes) {
add = true;
Iterator it = succB.iterator();
while (it.hasNext()) {
TreeSet tX = (TreeSet) it.next();
TreeSet<Comparable> bx = (TreeSet<Comparable>) this.getSetA().clone();
bx.add(x);
TreeSet<Comparable> bX = (TreeSet<Comparable>) this.getSetA().clone();
bX.addAll(tX);
TreeSet<Comparable> bXx = (TreeSet<Comparable>) bX.clone();
bXx.add(x);
int cBx = count(init, bx);
int cBX = count(init, bX);
int cBXx = count(init, bXx);
if (cBx == cBX) { // Try to group tests by pairs.
if (cBXx == cBx) {
it.remove(); // Update present potential successor.
TreeSet<Comparable> xX = new TreeSet();
xX.addAll(tX);
xX.add(x);
succB.add(xX);
add = false;
break;
}
}
if (cBx < cBX) {
if (cBXx == cBx) {
add = false;
break;
}
}
if (cBx > cBX) {
if (cBXx == cBX) {
it.remove();
}
}
}
if (add) {
TreeSet<Comparable> t = new TreeSet();
t.add(x);
succB.add(new TreeSet(t));
}
}
for (TreeSet t : succB) {
t.addAll(this.getSetA());
}
return succB;
}
/**
* Returns the number of observations corresponding to the set of attributes in the init context.
*
* @param init initial context from which attributes are count.
* @param attributes attributes from which observations are counted.
*
* @return number of observations corresponding to the set of attributes in init context.
*/
private int count(Context init, TreeSet<Comparable> attributes) {
return init.getExtentNb(attributes);
}
/**
* Returns the list of immediate successors of a given node of the lattice.
*
* This treatment is an adaptation of Bordat's theorem stating that there is a bijection
* between minimal strongly connected component of the precedence subgraph issued
* from the specified node, and its immediate successors.
*
* This treatment is performed in O(Cl|S|^3log g) where S is the initial set of elements,
* Cl is the closure computation complexity
* and g is the number of minimal generators of the lattice.
*
* This treatment is recursively invoked by method recursiveDiagramlattice. In this case, the dependance graph
* is initialized by method recursiveDiagramMethod, and updated by this method,
* with addition some news edges and/or new valuations on existing edges.
* When this treatment is not invoked by method recursiveDiagramLattice, then the dependance graph
* is initialized, but it may be not complete. It is the case for example for on-line generation of the
* concept lattice.
*
* cguerin - 2013-04-12 - transfer immedateSuccessors method from ConceptLattice to Concept
*
* @param init closure system used to compute immediate successors of this component.
*
* @return the list of immediate successors of this component.
*/
public ArrayList<TreeSet<Comparable>> immediateSuccessors(ClosureSystem init) {
// Initialization of the dependance graph when not initialized by method recursiveDiagramLattice
DGraph dependanceGraph = null;
dependanceGraph = new DGraph();
for (Comparable c : init.getSet()) {
dependanceGraph.addNode(new Node(c));
}
// computes newVal, the subset to be used to valuate every new dependance relation
// newVal = F\predecessors of F in the precedence graph of the closure system
// For a non reduced closure system, the precedence graph is not acyclic,
// and therefore strongly connected components have to be used.
ComparableSet f = new ComparableSet(this.getSetA());
long start = System.currentTimeMillis();
System.out.print("Precedence graph... ");
DGraph prec = init.precedenceGraph();
System.out.println(System.currentTimeMillis() - start + "ms");
start = System.currentTimeMillis();
System.out.print("Srongly connected component... ");
DAGraph acyclPrec = prec.getStronglyConnectedComponent();
System.out.println(System.currentTimeMillis() - start + "ms");
ComparableSet newVal = new ComparableSet();
newVal.addAll(f);
for (Object x : f) {
// computes nx, the strongly connected component containing x
Node nx = null;
for (Node cc : acyclPrec.getNodes()) {
TreeSet<Node> cC = (TreeSet<Node>) cc.getContent();
for (Node y : cC) {
if (x.equals(y.getContent())) {
nx = cc;
}
}
}
// computes the minorants of nx in the acyclic graph
TreeSet<Node> ccMinNx = acyclPrec.minorants(nx);
// removes from newVal every minorants of nx
for (Node cc : ccMinNx) {
TreeSet<Node> cC = (TreeSet<Node>) cc.getContent();
for (Node y : cC) {
newVal.remove(y.getContent());
}
}
}
// computes the node belonging in S\F
TreeSet<Node> n = new TreeSet<Node>();
for (Node in : dependanceGraph.getNodes()) {
if (!f.contains(in.getContent())) {
n.add(in);
}
}
System.out.print("Dependance... ");
start = System.currentTimeMillis();
// computes the dependance relation between nodes in S\F
// and valuated this relation by the subset of S\F
TreeSet<Edge> e = new TreeSet<Edge>();
for (Node from : n) {
for (Node to : n) {
if (!from.equals(to)) {
// check if from is in dependance relation with to
// i.e. "from" belongs to the closure of "F+to"
ComparableSet fPlusTo = new ComparableSet(f);
fPlusTo.add(to.getContent());
fPlusTo = new ComparableSet(init.closure(fPlusTo));
if (fPlusTo.contains(from.getContent())) {
// there is a dependance relation between from and to
// search for an existing edge between from and to
Edge ed = dependanceGraph.getEdge(from, to);
if (ed == null) {
ed = new Edge(from, to, new TreeSet<ComparableSet>());
dependanceGraph.addEdge(ed);
}
e.add(ed);
// check if F is a minimal set closed for dependance relation between from and to
((TreeSet<ComparableSet>) ed.getContent()).add(newVal);
TreeSet<ComparableSet> valEd = new TreeSet<ComparableSet>((TreeSet<ComparableSet>) ed.getContent());
for (ComparableSet x1 : valEd) {
if (x1.containsAll(newVal) && !newVal.containsAll(x1)) {
((TreeSet<ComparableSet>) ed.getContent()).remove(x1);
}
if (!x1.containsAll(newVal) && newVal.containsAll(x1)) {
((TreeSet<ComparableSet>) ed.getContent()).remove(newVal);
}
}
}
}
}
}
System.out.println(System.currentTimeMillis() - start + "ms");
System.out.print("Subgraph... ");
start = System.currentTimeMillis();
// computes the dependance subgraph of the closed set F as the reduction
// of the dependance graph composed of nodes in S\A and edges of the dependance relation
DGraph sub = dependanceGraph.getSubgraphByNodes(n);
DGraph delta = sub.getSubgraphByEdges(e);
// computes the sources of the CFC of the dependance subgraph
// that corresponds to successors of the closed set F
DAGraph cfc = delta.getStronglyConnectedComponent();
TreeSet<Node> sccmin = cfc.getSinks();
System.out.println(System.currentTimeMillis() - start + "ms");
ArrayList<TreeSet<Comparable>> immSucc = new ArrayList<TreeSet<Comparable>>();
for (Node n1 : sccmin) {
TreeSet s = new TreeSet(f);
TreeSet<Node> toadd = (TreeSet<Node>) n1.getContent();
for (Node n2 : toadd) {
s.add(n2.getContent());
}
immSucc.add(s);
}
return immSucc;
}
}
| 33.111429 | 147 | 0.550738 |
3a899b86d96ff4957acc04e8b7b2e9678d7d9bb9 | 1,596 | /**
* Copyright 2017 TerraMeta Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.quickstart.easy.widerows;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.plasma.sdo.PlasmaDataGraph;
import commonj.sdo.DataGraph;
import examples.quickstart.model.Card;
import examples.quickstart.model.Transaction;
import examples.quickstart.ExampleRunner;
public class ExampleTest {
private static final Log log = LogFactory.getLog(ExampleTest.class);
@Test
public void testExcmple() throws IOException {
DataGraph[] results = ExampleRunner.runExample();
for (DataGraph graph : results) {
log.info(((PlasmaDataGraph) graph).asXml());
Card card = (Card) graph.getRootObject();
for (Transaction trans : card.getTransaction()) {
assertTrue(trans.getDollars() >= ExampleRunner.MIN_DOLLARS);
assertTrue(trans.getDollars() <= ExampleRunner.MAX_DOLLARS);
}
}
}
}
| 33.25 | 75 | 0.740602 |
03bb089781ac8845cf3f9aefbfb68e45b982c557 | 1,081 | package com.nick.jvm.entry;
import java.io.*;
/**
* Created by KangShuai on 2017/7/14.
*/
public class DirEntry extends BaseEntry {
public DirEntry(String classPath) {
super(classPath);
}
@Override
public byte[] readClass() {
try {
byte[] bytes = new byte[1024];
FileInputStream fileReader = new FileInputStream(classPath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
int n;
try {
while ((n = fileReader.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, n);
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
for (byte b : byteArray) {
System.out.print(b + " ");
}
return byteArray;
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new byte[0];
}
}
| 27.717949 | 90 | 0.517114 |
ab1e0423fefe9c080b60ad11f709c309875b3b35 | 1,378 | /*
* Copyright (c) 2018 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liulishuo.okdownload.core.exception;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class PreAllocateExceptionTest {
private PreAllocateException exception;
private long freeSpace = 1;
private long requireSpace = 2;
@Before
public void setup() {
exception = new PreAllocateException(requireSpace, freeSpace);
}
@Test
public void construct() {
assertThat(exception.getMessage()).isEqualTo(
"There is Free space less than Require space: " + freeSpace + " < " + requireSpace);
assertThat(exception.getRequireSpace()).isEqualTo(requireSpace);
assertThat(exception.getFreeSpace()).isEqualTo(freeSpace);
}
} | 32.809524 | 100 | 0.717707 |
175f5d1fd18275e1631e413106cad531acea026c | 1,392 | package com.voisintech.tagmyclip.solr;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import com.voisintech.tagmyclip.model.TagSolr;
@Repository
public class TagServiceImpl implements TagService{
private static final Pattern IGNORED_CHARS_PATTERN = Pattern.compile("\\p{Punct}");
@Autowired
TagSolrRepository solrProductRepository;
@Override
public Page<TagSolr> findByName(String searchTerm, Pageable pageable) {
if (StringUtils.isBlank(searchTerm) || StringUtils.equals(searchTerm, "*")) {
return solrProductRepository.findAll(pageable);
}
return solrProductRepository.findByTagNameIn(splitSearchTermAndRemoveIgnoredCharacters(searchTerm), pageable);
}
private Collection<String> splitSearchTermAndRemoveIgnoredCharacters(String searchTerm) {
String[] searchTerms = StringUtils.split(searchTerm, " ");
List<String> result = new ArrayList<String>(searchTerms.length);
for (String term : searchTerms) {
if (StringUtils.isNotEmpty(term)) {
result.add(IGNORED_CHARS_PATTERN.matcher(term).replaceAll(" "));
}
}
return result;
}
}
| 31.636364 | 112 | 0.793103 |
b188b81446dc0b1115ef568894d0fa41b4c4b5e1 | 2,807 | /**
* Copyright 2009 Wilfred Springer
*
* 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 nl.flotsam.xeger;
import org.junit.Test;
import dk.brics.automaton.Automaton;
import dk.brics.automaton.RegExp;
import static org.junit.Assert.assertTrue;
public class XegerTest {
@Test
public void shouldGenerateTextCorrectly() {
String regex = "[ab]{4,6}c";
Xeger generator = new Xeger(regex);
for (int i = 0; i < 100; i++) {
String text = generator.generate();
assertTrue(text.matches(regex));
}
regex = ".*apache.*";
generator = new Xeger(regex);
for (int i = 0; i < 100; i++) {
String text = generator.generate(); //"aapachee";
// System.out.println(text);
assertTrue(text.matches(regex));
}
}
@Test
public void automatonTest() {
RegExp r = new RegExp("ab(c|d)*");
Automaton a = r.toAutomaton();
String s = "abcccdc";
// System.out.println("Match: " + a.run(s)); // prints: true
r = new RegExp(".*apache.*");
a = r.toAutomaton();
s = "apachec";
// System.out.println("Match: " + a.run(s)); // prints: true
}
@Test
public void shouldGenerateTextCorrectly2() {
String regex = ".*a";
Xeger generator = new Xeger(regex);
for (int i = 0; i < 100; i++) {
String text = generator.generate();
assertTrue(text.matches(regex));
}
}
@Test
public void shouldGenerateTextCorrectly3() {
String regex1 = ".*a";
String regex2 = "ba";
Xeger generator = new Xeger(regex1, regex2);
for (int i = 0; i < 100; i++) {
String text = generator.generate();
assertTrue(text.matches(regex1));
assertTrue(text.matches(regex2));
}
}
@Test
public void shouldGenerateTextCorrectly4() {
String regex1 = ".*apache.*";
String regex2 = ".*commons.*";
Xeger generator = new Xeger(regex1, regex2);
for (int i = 0; i < 1; i++) {
String text = generator.generate();
System.out.println(text);
assertTrue(text.matches(regex1));
assertTrue(text.matches(regex2));
}
}
} | 30.51087 | 75 | 0.582829 |
1791b82edaa3231ce2e18f295d5ea75b141a07df | 1,325 | package csdn.shimiso.eim.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* SQLite数据库管理类
*
* 主要负责数据库资源的初始化,开启,关闭,以及获得DatabaseHelper帮助类操作
*
* @author shimiso
*
*/
public class DBManager {
private int version = 1;
private String databaseName;
// 本地Context对象
private Context mContext = null;
private static DBManager dBManager = null;
/**
* 构造函数
*
* @param mContext
*/
private DBManager(Context mContext) {
super();
this.mContext = mContext;
}
public static DBManager getInstance(Context mContext, String databaseName) {
if (null == dBManager) {
dBManager = new DBManager(mContext);
}
dBManager.databaseName = databaseName;
return dBManager;
}
/**
* 关闭数据库 注意:当事务成功或者一次性操作完毕时候再关闭
*/
public void closeDatabase(SQLiteDatabase dataBase, Cursor cursor) {
if (null != dataBase) {
dataBase.close();
}
if (null != cursor) {
cursor.close();
}
}
/**
* 打开数据库 注:SQLiteDatabase资源一旦被关闭,该底层会重新产生一个新的SQLiteDatabase
*/
public SQLiteDatabase openDatabase() {
return getDatabaseHelper().getWritableDatabase();
}
/**
* 获取DataBaseHelper
*
* @return
*/
public DataBaseHelper getDatabaseHelper() {
return new DataBaseHelper(mContext, this.databaseName, null,
this.version);
}
}
| 18.150685 | 77 | 0.701132 |
5ff378fe699db5324a75d4ea947b2565916dabc2 | 1,269 | /*
* Copyright (C) 2005-present, 58.com. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wuba.wpaxos;
/**
* propose result
*/
public class ProposeResult {
// ret, 0 if success
private int result;
// return when propose success
private long instanceID = 0;
public ProposeResult(int result, long instanceID) {
super();
this.result = result;
this.instanceID = instanceID;
}
public ProposeResult(int result) {
super();
this.result = result;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public long getInstanceID() {
return instanceID;
}
public void setInstanceID(long instanceID) {
this.instanceID = instanceID;
}
}
| 23.5 | 75 | 0.710008 |
f6e1a99684b116de56f431c68808b3a5271ed801 | 3,280 | package com.ivorita.servlet;
import com.google.gson.Gson;
import com.ivorita.bean.GranaryInfo;
import com.ivorita.bean.InfoTotal;
import com.ivorita.util.JDBCUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 查询历史记录数据
*/
@WebServlet("/QueryHistory")
public class QueryHistory extends HttpServlet {
private List<GranaryInfo> granaryInfoList = new ArrayList<>();
private String json;
private Connection conn = null;
private PreparedStatement pStmt = null;
private ResultSet rs = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String start = req.getParameter("start");
String end = req.getParameter("end");
String sql = "select * from granary_info where time between" + " '" + start + "' " + "and DATE_ADD(" + " '" + end + "' " + ",INTERVAL 1 DAY)";
try {
//使用alibaba的druid连接池
conn = JDBCUtils.getConnection();
System.out.println("Query History : 连接数据库");
pStmt = conn.prepareStatement(sql);
rs = pStmt.executeQuery(sql);
if (rs != null) {
while (rs.next()) {
int id = rs.getInt("id");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = df.format(rs.getTimestamp("time"));
float temperature = rs.getFloat("temperature");
float humidity = rs.getFloat("humidity");
float carbon_dioxide = rs.getFloat("carbon_dioxide");
float illumination = rs.getFloat("illumination");
float gas = rs.getFloat("gas");
System.out.println("id: " + id + " time: " + timeStr + "temperature:" + temperature + " humidity: " + humidity + " carbon_dioxide:" + carbon_dioxide);
GranaryInfo granaryInfo = new GranaryInfo(id, timeStr, carbon_dioxide, temperature, humidity, illumination, gas);
granaryInfoList.add(granaryInfo);
InfoTotal nt = new InfoTotal(granaryInfoList.size(), granaryInfoList);
Gson gson = new Gson();
json = gson.toJson(nt);
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("error" + e.toString());
} finally {
JDBCUtils.close(rs, pStmt, conn);//归还连接
granaryInfoList.clear();
}
System.out.println(json);
PrintWriter pw = new PrintWriter(resp.getOutputStream());
pw.print(json);
pw.flush();
}
}
| 36.043956 | 173 | 0.623476 |
6177a6e03a72aa210ec8cc3f8cc9ec5a89c7eaad | 19,687 | /*
* MIT License
*
* Copyright (c) 2020 XenoAmess
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.xenoamess.cyan_potion.base.io.input.gamepad;
import com.github.strikerx3.jxinput.XInputAxes;
import com.github.strikerx3.jxinput.XInputButtons;
import com.github.strikerx3.jxinput.XInputComponents;
import com.xenoamess.cyan_potion.base.GameWindow;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* this class is used as data class, (struct)
* thus it will not be fully encapsulated.
*
* @author XenoAmess
* @version 0.162.3
* @see JXInputGamepadDevice
* @deprecated
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@EqualsAndHashCode(callSuper = true)
@ToString
@Deprecated
public class JXInputGamepadData extends AbstractGamepadData {
/**
* Constant <code>JXINPUT_KEY_A=0</code>
*/
public static final int JXINPUT_KEY_A = 0;
/**
* Constant <code>JXINPUT_KEY_B=1</code>
*/
public static final int JXINPUT_KEY_B = 1;
/**
* Constant <code>JXINPUT_KEY_X=2</code>
*/
public static final int JXINPUT_KEY_X = 2;
/**
* Constant <code>JXINPUT_KEY_Y=3</code>
*/
public static final int JXINPUT_KEY_Y = 3;
/**
* Constant <code>JXINPUT_KEY_BACK=4</code>
*/
public static final int JXINPUT_KEY_BACK = 4;
/**
* Constant <code>JXINPUT_KEY_START=5</code>
*/
public static final int JXINPUT_KEY_START = 5;
/**
* Constant <code>JXINPUT_KEY_LB=6</code>
*/
public static final int JXINPUT_KEY_LB = 6;
/**
* Constant <code>JXINPUT_KEY_RB=7</code>
*/
public static final int JXINPUT_KEY_RB = 7;
/**
* Constant <code>JXINPUT_KEY_L=8</code>
*/
public static final int JXINPUT_KEY_L = 8;
/**
* Constant <code>JXINPUT_KEY_R=9</code>
*/
public static final int JXINPUT_KEY_R = 9;
/**
* Constant <code>JXINPUT_KEY_UP=10</code>
*/
public static final int JXINPUT_KEY_UP = 10;
/**
* Constant <code>JXINPUT_KEY_DOWN=11</code>
*/
public static final int JXINPUT_KEY_DOWN = 11;
/**
* Constant <code>JXINPUT_KEY_LEFT=12</code>
*/
public static final int JXINPUT_KEY_LEFT = 12;
/**
* Constant <code>JXINPUT_KEY_RIGHT=13</code>
*/
public static final int JXINPUT_KEY_RIGHT = 13;
/**
* Constant <code>JXINPUT_KEY_GUIDE=14</code>
*/
public static final int JXINPUT_KEY_GUIDE = 14;
/**
* Constant <code>JXINPUT_KEY_UNKNOWN=15</code>
*/
public static final int JXINPUT_KEY_UNKNOWN = 15;
/**
* Constant <code>JXINPUT_KEY_LT=16</code>
*/
public static final int JXINPUT_KEY_LT = 16;
/**
* Constant <code>JXINPUT_KEY_RT=17</code>
*/
public static final int JXINPUT_KEY_RT = 17;
/**
* Constant <code>JXINPUT_KEY_LAST=17</code>
*/
public static final int JXINPUT_KEY_LAST = 17;
/**
* Constant <code>DPAD_CENTER=-1</code>
*/
public static final int DPAD_CENTER = -1;
/**
* Constant <code>DPAD_UP_LEFT=0</code>
*/
public static final int DPAD_UP_LEFT = 0;
/**
* Constant <code>DPAD_UP=1</code>
*/
public static final int DPAD_UP = 1;
/**
* Constant <code>DPAD_UP_RIGHT=2</code>
*/
public static final int DPAD_UP_RIGHT = 2;
/**
* Constant <code>DPAD_RIGHT=3</code>
*/
public static final int DPAD_RIGHT = 3;
/**
* Constant <code>DPAD_DOWN_RIGHT=4</code>
*/
public static final int DPAD_DOWN_RIGHT = 4;
/**
* Constant <code>DPAD_DOWN=5</code>
*/
public static final int DPAD_DOWN = 5;
/**
* Constant <code>DPAD_DOWN_LEFT=6</code>
*/
public static final int DPAD_DOWN_LEFT = 6;
/**
* Constant <code>DPAD_LEFT=7</code>
*/
public static final int DPAD_LEFT = 7;
public boolean a;
public boolean b;
public boolean x;
public boolean y;
public boolean back;
public boolean start;
public boolean lShoulder;
public boolean rShoulder;
public boolean lThumb;
public boolean rThumb;
public boolean up;
public boolean down;
public boolean left;
public boolean right;
public boolean guide;
public boolean unknown;
public int lxRaw, lyRaw;
public int rxRaw, ryRaw;
public int ltRaw, rtRaw;
public float lx, ly;
public float rx, ry;
public float lt, rt;
public int dpad;
/**
* Returns an integer representing the current direction of the D-Pad.
*
* @param up the up button state
* @param down the down button state
* @param left the left button state
* @param right the right button state
* @return one of the <code>DPAD_*</code> values of this class
*/
@SuppressWarnings("unused")
public static int dpadFromButtons(final boolean up, final boolean down,
final boolean left, final boolean right) {
boolean u = up;
boolean d = down;
boolean l = left;
boolean r = right;
// Fix invalid buttons (cancel up-down and left-right)
if (u && d) {
u = d = false;
}
if (l && r) {
l = r = false;
}
// Now we have 9 cases:
// left center right
// up DPAD_UP_LEFT DPAD_UP DPAD_UP_RIGHT
// center DPAD_LEFT DPAD_CENTER DPAD_RIGHT
// down DPAD_DOWN_LEFT DPAD_DOWN DPAD_DOWN_RIGHT
if (u) {
if (l) {
return DPAD_UP_LEFT;
}
if (r) {
return DPAD_UP_RIGHT;
}
return DPAD_UP;
}
if (d) {
if (l) {
return DPAD_DOWN_LEFT;
}
if (r) {
return DPAD_DOWN_RIGHT;
}
return DPAD_DOWN;
}
// vertical center
if (l) {
return DPAD_LEFT;
}
if (r) {
return DPAD_RIGHT;
}
return DPAD_CENTER;
}
/**
* {@inheritDoc}
*/
@Override
public void reset() {
this.a = this.b = this.x = this.y = false;
this.back = this.start = false;
this.lShoulder = this.rShoulder = false;
this.lThumb = this.rThumb = false;
this.up = this.down = this.left = this.right = false;
this.guide = this.unknown = false;
this.lxRaw = this.lyRaw = 0;
this.rxRaw = this.ryRaw = 0;
this.ltRaw = this.rtRaw = 0;
this.lx = this.ly = 0f;
this.rx = this.ry = 0f;
this.lt = this.rt = 0f;
this.dpad = DPAD_CENTER;
}
/**
* <p>copy.</p>
*
* @param buttons buttons
*/
protected void copy(final XInputButtons buttons) {
this.a = buttons.a;
this.b = buttons.b;
this.x = buttons.x;
this.y = buttons.y;
this.back = buttons.back;
this.start = buttons.start;
this.lShoulder = buttons.lShoulder;
this.rShoulder = buttons.rShoulder;
this.lThumb = buttons.lThumb;
this.rThumb = buttons.rThumb;
this.up = buttons.up;
this.down = buttons.down;
this.left = buttons.left;
this.right = buttons.right;
this.guide = buttons.guide;
this.unknown = buttons.unknown;
}
/**
* <p>copy.</p>
*
* @param axes axes
*/
protected void copy(final XInputAxes axes) {
this.lxRaw = axes.lxRaw;
this.lyRaw = axes.lyRaw;
this.rxRaw = axes.rxRaw;
this.ryRaw = axes.ryRaw;
this.ltRaw = axes.ltRaw;
this.rtRaw = axes.rtRaw;
this.lx = axes.lx;
this.ly = axes.ly;
this.rx = axes.rx;
this.ry = axes.ry;
this.lt = axes.lt;
this.rt = axes.rt;
this.dpad = axes.dpad;
}
/**
* <p>Constructor for JXInputGamepadData.</p>
*
* @param gamepadDevice gamepadDevice
*/
public JXInputGamepadData(AbstractGamepadDevice gamepadDevice) {
super(gamepadDevice);
}
/**
* {@inheritDoc}
*/
@Override
public void updateGamepadStatus(GameWindow gameWindow) {
XInputComponents components =
((JXInputGamepadDevice) this.getGamepadDevice()).getRawXInputDevice().getComponents();
XInputButtons buttons = components.getButtons();
XInputAxes axes = components.getAxes();
// axes.
long window = gameWindow.getWindow();
int action;
if (this.a != buttons.a) {
if (buttons.a) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_A, action,
this.getGamepadDevice()));
} else if (buttons.a) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_A, action,
this.getGamepadDevice()));
}
if (this.b != buttons.b) {
if (buttons.b) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_B, action,
this.getGamepadDevice()));
} else if (buttons.b) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_B, action,
this.getGamepadDevice()));
}
if (this.x != buttons.x) {
if (buttons.x) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_X, action,
this.getGamepadDevice()));
} else if (buttons.x) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_X, action,
this.getGamepadDevice()));
}
if (this.y != buttons.y) {
if (buttons.y) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_Y, action,
this.getGamepadDevice()));
} else if (buttons.y) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_Y, action,
this.getGamepadDevice()));
}
if (this.back != buttons.back) {
if (buttons.back) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_BACK, action,
this.getGamepadDevice()));
} else if (buttons.back) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_BACK, action,
this.getGamepadDevice()));
}
if (this.start != buttons.start) {
if (buttons.start) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_START, action,
this.getGamepadDevice()));
} else if (buttons.start) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_START, action,
this.getGamepadDevice()));
}
if (this.lShoulder != buttons.lShoulder) {
if (buttons.lShoulder) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_LB, action,
this.getGamepadDevice()));
} else if (buttons.lShoulder) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_LB, action,
this.getGamepadDevice()));
}
if (this.rShoulder != buttons.rShoulder) {
if (buttons.rShoulder) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_RB, action,
this.getGamepadDevice()));
} else if (buttons.rShoulder) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_RB, action,
this.getGamepadDevice()));
}
if (this.lThumb != buttons.lThumb) {
if (buttons.lThumb) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_L, action,
this.getGamepadDevice()));
} else if (buttons.lThumb) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_L, action,
this.getGamepadDevice()));
}
if (this.rThumb != buttons.rThumb) {
if (buttons.rThumb) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_R, action,
this.getGamepadDevice()));
} else if (buttons.rThumb) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_R, action,
this.getGamepadDevice()));
}
if (this.up != buttons.up) {
if (buttons.up) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_UP, action,
this.getGamepadDevice()));
} else if (buttons.up) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_UP, action,
this.getGamepadDevice()));
}
if (this.down != buttons.down) {
if (buttons.down) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_DOWN, action,
this.getGamepadDevice()));
} else if (buttons.down) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_DOWN, action,
this.getGamepadDevice()));
}
if (this.left != buttons.left) {
if (buttons.left) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_LEFT, action,
this.getGamepadDevice()));
} else if (buttons.left) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_LEFT, action,
this.getGamepadDevice()));
}
if (this.right != buttons.right) {
if (buttons.right) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_RIGHT, action,
this.getGamepadDevice()));
} else if (buttons.right) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_RIGHT, action,
this.getGamepadDevice()));
}
if (this.guide != buttons.guide) {
if (buttons.guide) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_GUIDE, action,
this.getGamepadDevice()));
} else if (buttons.guide) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_GUIDE, action,
this.getGamepadDevice()));
}
if (this.unknown != buttons.unknown) {
if (buttons.unknown) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_UNKNOWN, action,
this.getGamepadDevice()));
} else if (buttons.unknown) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_UNKNOWN, action,
this.getGamepadDevice()));
}
boolean ifLtNow = (this.lt > 0.5f);
boolean ifLtNext = (axes.lt > 0.5f);
if (ifLtNow != ifLtNext) {
if (ifLtNext) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_LT, action,
this.getGamepadDevice()));
} else if (ifLtNext) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_LT, action,
this.getGamepadDevice()));
}
boolean ifRtNow = (this.rt > 0.5f);
boolean ifRtNext = (axes.rt > 0.5f);
if (ifRtNow != ifRtNext) {
if (ifRtNext) {
action = 1;
} else {
action = 0;
}
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_RT, action,
this.getGamepadDevice()));
} else if (ifRtNext) {
action = 2;
gameWindow.getGameManager().eventListAdd(new GamepadButtonEvent(window, JXINPUT_KEY_RT, action,
this.getGamepadDevice()));
}
this.copy(buttons);
this.copy(axes);
}
}
| 32.702658 | 112 | 0.55849 |
5eb9fb41e8fc2d644a64af726de43824777bf7e9 | 3,566 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.codecentric.boot.admin.notify;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.web.client.RestTemplate;
import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent;
import de.codecentric.boot.admin.model.Application;
import de.codecentric.boot.admin.model.StatusInfo;
public class PagerdutyNotifierTest {
private PagerdutyNotifier notifier;
private RestTemplate restTemplate;
@Before
public void setUp() {
restTemplate = mock(RestTemplate.class);
notifier = new PagerdutyNotifier();
notifier.setServiceKey("--service--");
notifier.setClient("TestClient");
notifier.setClientUrl(URI.create("http://localhost"));
notifier.setRestTemplate(restTemplate);
}
@Test
public void test_onApplicationEvent_resolve() {
StatusInfo infoDown = StatusInfo.ofDown();
StatusInfo infoUp = StatusInfo.ofUp();
notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(),
infoDown, infoUp));
Map<String, Object> expected = new HashMap<String, Object>();
expected.put("service_key", "--service--");
expected.put("incident_key", "App/-id-");
expected.put("event_type", "resolve");
expected.put("description", "App/-id- is UP");
Map<String, Object> details = new HashMap<String, Object>();
details.put("from", infoDown);
details.put("to", infoUp);
expected.put("details", details);
verify(restTemplate).postForEntity(eq(PagerdutyNotifier.DEFAULT_URI), eq(expected),
eq(Void.class));
}
@Test
public void test_onApplicationEvent_trigger() {
StatusInfo infoDown = StatusInfo.ofDown();
StatusInfo infoUp = StatusInfo.ofUp();
notifier.notify(new ClientApplicationStatusChangedEvent(
Application.create("App").withId("-id-").withHealthUrl("http://health").build(),
infoUp, infoDown));
Map<String, Object> expected = new HashMap<String, Object>();
expected.put("service_key", "--service--");
expected.put("incident_key", "App/-id-");
expected.put("event_type", "trigger");
expected.put("description", "App/-id- is DOWN");
expected.put("client", "TestClient");
expected.put("client_url", URI.create("http://localhost"));
Map<String, Object> details = new HashMap<String, Object>();
details.put("from", infoUp);
details.put("to", infoDown);
expected.put("details", details);
Map<String, Object> context = new HashMap<String, Object>();
context.put("type", "link");
context.put("href", "http://health");
context.put("text", "Application health-endpoint");
expected.put("contexts", Arrays.asList(context));
verify(restTemplate).postForEntity(eq(PagerdutyNotifier.DEFAULT_URI), eq(expected),
eq(Void.class));
}
}
| 34.288462 | 85 | 0.732473 |
0a2d62d7ec9238aa16873a6073aa8aa5bd95dfac | 4,744 | package com.icebox.bombjammers.elements.character;
import java.io.File;
import com.icebox.bombjammers.loaders.BJAnimationLoader;
import com.icebox.bombjammers.loaders.BJPropertiesLoader;
import com.ragebox.bombframework.bwt.BTAnimatedImage;
import kuusisto.tinysound.Sound;
import kuusisto.tinysound.TinySound;
public class BJCharacterMoveDash extends BJCharacterMoveState {
private int accelerationTime;
private int decelerationTime;
private float modX;
private float modY;
private BTAnimatedImage animationDashN;
private BTAnimatedImage animationDashNE;
private BTAnimatedImage animationDashE;
private BTAnimatedImage animationDashSE;
private BTAnimatedImage animationDashS;
private BTAnimatedImage animationDashSW;
private BTAnimatedImage animationDashW;
private BTAnimatedImage animationDashNW;
private BTAnimatedImage currentAnimation;
private Sound dash;
private double volEffects = Double.valueOf(BJPropertiesLoader.getInstance().
getProperty(BJPropertiesLoader.VOLUME_EFFECTS))/100;
protected BJCharacterMoveDash(BJCharacter character,
BJCharacterMoveContext context) {
super(character, context);
BJAnimationLoader loader = BJAnimationLoader.getInstance();
animationDashN = loader.getAnimation("dash_n",
character.getFileRepertory()+"sprite_sheet.png");
animationDashNE = loader.getAnimation("dash_ne",
character.getFileRepertory()+"sprite_sheet.png");
animationDashE = loader.getAnimation("dash_e",
character.getFileRepertory()+"sprite_sheet.png");
animationDashSE = loader.getAnimation("dash_se",
character.getFileRepertory()+"sprite_sheet.png");
animationDashS = loader.getAnimation("dash_s",
character.getFileRepertory()+"sprite_sheet.png");
animationDashSW = loader.getAnimation("dash_sw",
character.getFileRepertory()+"sprite_sheet.png");
animationDashW = loader.getAnimation("dash_w",
character.getFileRepertory()+"sprite_sheet.png");
animationDashNW = loader.getAnimation("dash_nw",
character.getFileRepertory()+"sprite_sheet.png");
dash = TinySound.loadSound(new File("./res/sound/dash.wav"));
}
@Override
public void init() {
animationDashN.init();
animationDashNE.init();
animationDashE.init();
animationDashSE.init();
animationDashS.init();
animationDashSW.init();
animationDashW.init();
animationDashNW.init();
}
@Override
public void activate() {
animationDashN.reset();
animationDashNE.reset();
animationDashE.reset();
animationDashSE.reset();
animationDashS.reset();
animationDashSW.reset();
animationDashW.reset();
animationDashNW.reset();
accelerationTime = 40 * character.getWeight();
decelerationTime = 60 * character.getWeight();
modX = (float) (character.getSpeed() * 2.5);
modY = (float) (character.getSpeed() * 2.5);
dash.play(volEffects);
}
@Override
public void verifyAnimation(byte mask) {
if ((mask & BJCharacter.MOVE) != 0) {
if ((mask & BJCharacter.MOVE_UP) != 0) {
if ((mask & BJCharacter.MOVE_LEFT) != 0) {
currentAnimation = animationDashNW;
modX *= -1;
modY *= -1;
} else if ((mask & BJCharacter.MOVE_RIGHT) != 0) {
currentAnimation = animationDashNE;
modY *= -1;
} else if ((mask & BJCharacter.MOVE_DOWN) == 0) {
currentAnimation = animationDashN;
modX = 0;
modY *= -1;
}
} else if ((mask & BJCharacter.MOVE_DOWN) != 0) {
if ((mask & BJCharacter.MOVE_LEFT) != 0) {
currentAnimation = animationDashSW;
modX *= -1;
} else if ((mask & BJCharacter.MOVE_RIGHT) != 0) {
currentAnimation = animationDashSE;
} else if ((mask & BJCharacter.MOVE_UP) == 0) {
currentAnimation = animationDashS;
modX = 0;
}
} else if ((mask & BJCharacter.MOVE_LEFT) != 0) {
currentAnimation = animationDashW;
modX *= -1;
modY = 0;
} else if ((mask & BJCharacter.MOVE_RIGHT) != 0) {
currentAnimation = animationDashE;
modY = 0;
}
}
}
@Override
public void update(byte mask, int deltaTime) {
currentAnimation.update(deltaTime);
character.translateX(modX);
character.translateY(modY);
if (accelerationTime > 0) {
accelerationTime -= deltaTime;
if (accelerationTime <= 0) {
decelerationTime -= accelerationTime;
modX /= 5;
modY /= 5;
}
} else if (decelerationTime > 0) {
decelerationTime -= deltaTime;
} else if ((mask & BJCharacter.HAS_BOMB) != 0) {
context.changeContext(BJCharacterMoveContext.HAS_BOMB, mask);
} else if ((mask & BJCharacter.MOVE) != 0) {
context.changeContext(BJCharacterMoveContext.RUN, mask);
} else {
context.changeContext(BJCharacterMoveContext.STILL, mask);
}
}
@Override
public void render() {
currentAnimation.render();
}
}
| 28.926829 | 77 | 0.711847 |
ef58f3eab55645f13130b1717f677ab9f4d3d17b | 2,277 | package net.jackw.olep.common.store;
import net.jackw.olep.common.StoreKeyMissingException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public interface SharedKeyValueStore<K, V> {
int DEFAULT_BACKOFF_ATTEMPTS = 20;
/**
* Tests whether the specified key has a corresponding value in this store
*
* @param key The key to check
* @return true if there is a value in the table for the key, and false otherwise
*/
boolean containsKey(K key);
/**
* Get the value associated with the requested key
*
* @param key The key to retrieve the value of
* @return The value associated with that key, or null if there is no entry for that key
*/
@Nullable
V get(K key);
/**
* Get the value associated with the key, blocking until the value becomes available. Blocking time is limited, and
* if the key is still not present a {@link StoreKeyMissingException} will be thrown.
*
* @param key The key to retrieve the value of
* @param maxAttempts The number of times to retry, or 0 for unlimited
* @return The value associated with that key
*/
@Nonnull
default V getBlocking(K key, int maxAttempts) throws InterruptedException {
int attempts = 0;
V result;
do {
while (!containsKey(key)) {
if (maxAttempts > 0 && attempts >= maxAttempts) {
throw new StoreKeyMissingException(key);
}
Thread.sleep(50);
attempts++;
}
result = get(key);
} while (result == null);
return result;
}
/**
* Get the value associated with the key, blocking until the value becomes available. Blocking time is limited, and
* if the key is still not present a {@link StoreKeyMissingException} will be thrown.
*
* 20 attempts will be made (for a maximum blocking time of approximately 1 second) before the exception is thrown.
*
* @param key The key to retrieve the value of
* @return The value associated with that key
*/
@Nonnull
default V getBlocking(K key) throws InterruptedException {
return getBlocking(key, DEFAULT_BACKOFF_ATTEMPTS);
}
}
| 33.985075 | 119 | 0.640316 |
713c72b87d7e38fce1160447aa410467ac0f37ff | 870 | package com.veertu.plugin.anka;
import hudson.model.TaskListener;
/**
* Created by avia on 09/07/2016.
*/
public class AnkaTaskListenerLog implements AnkaLogger {
private final TaskListener taskListener;
private final String logPrefix;
public AnkaTaskListenerLog(TaskListener taskLister, String logPrefix) {
this.taskListener = taskLister;
this.logPrefix = logPrefix;
}
/* log methods from AnkaLogger */
public void logInfo(String message) {
taskListener.getLogger().println(logPrefix + message);
}
public void logWarning(String message) {
taskListener.error(logPrefix + message);
}
public void logError(String message) {
taskListener.error(logPrefix + message);
}
public void logFatalError(String message) {
taskListener.fatalError(logPrefix + message);
}
}
| 22.894737 | 75 | 0.693103 |
b4f1cfdcbbd2cf7114f257d01bd5876915b7c567 | 2,513 | /*
* This file was last modified at 2020.04.24 21:39 by Victor N. Skurikhin.
* This is free and unencumbered software released into the public domain.
* For more information, please refer to <http://unlicense.org>
* SortFields.java
* $Id: b4f1cfdcbbd2cf7114f257d01bd5876915b7c567 $
*/
package su.svn.showcase.utils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import su.svn.showcase.domain.Sort;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
public class SortFields {
private static final Logger LOGGER = LoggerFactory.getLogger(SortFields.class);
@Data
@ToString
@EqualsAndHashCode
public static class Cluster {
Map<String, Boolean> cluster = new LinkedHashMap<>();
}
private final String entityName;
private final Set<Cluster> clusters;
public SortFields(Class<?> aClass) {
this.entityName = aClass.getSimpleName();
this.clusters = Collections.unmodifiableSet(sortFields(aClass));
}
public boolean contains(Map<String, Boolean> sorting) {
Cluster cluster = new Cluster();
cluster.setCluster(sorting);
return clusters.contains(cluster);
}
@Override
public String toString() {
return "SortFields{" +
"entityName='" + entityName + '\'' +
", clusters=" + clusters +
'}';
}
private Set<Cluster> sortFields(Class<?> aClass) {
Set<Cluster> clusters = new LinkedHashSet<>();
Map<String, Field> mapFields = Arrays.stream(aClass.getDeclaredFields())
.filter(field -> field.isAnnotationPresent(Sort.class))
.collect(Collectors.toMap(Field::getName, f -> f));
for (String fieldName : mapFields.keySet()) {
Cluster cluster = new Cluster();
Field field = mapFields.get(fieldName);
cluster.getCluster().put(fieldName, ! getAnnotationSort(field).decrease());
for (String other : getAnnotationSort(field).cluster()) {
Field f = mapFields.get(other);
boolean ascending = f == null || ! getAnnotationSort(f).decrease();
cluster.getCluster().put(other, ascending);
}
clusters.add(cluster);
}
return clusters;
}
private Sort getAnnotationSort(Field field) {
return field.getAnnotation(Sort.class);
}
}
| 32.217949 | 87 | 0.64226 |
e7f6f1bce3cca5f1c634802fb3c035f38524f82e | 332 | package com.rhialtothemarvellous.newangelesrivalrandomizer;
public enum Unused implements CorpOrUnused {
UNUSED(R.string.unused);
private final int stringID;
Unused(int stringID) {
this.stringID = stringID;
}
@Override
public int getStringID() {
return this.stringID;
}
}
| 19.529412 | 59 | 0.656627 |
46ee77fd463fe8fdb77e1017d568e2c034ac71fc | 5,278 | package com.ascn.richlife.server.group;
import com.ascn.richlife.model.CardGroup;
import com.ascn.richlife.model.Game;
import com.ascn.richlife.model.Location;
import com.ascn.richlife.model.role.CurrentRole;
import com.ascn.richlife.model.role.RoleInfo;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
/**
* 游戏对战逻辑管理
*/
public class GameManager {
//游戏列表
private static Map<String, Game> gameMap = new ConcurrentHashMap<>();
/**
* 添加一个游戏
*
* @param game
*/
public static void addGame(Game game) {
gameMap.put(game.getRoomId(), game);
}
/**
* 获取指定的游戏
*
* @param roomId
*/
public static Game getGame(String roomId) {
return gameMap.get(roomId);
}
/**
* 删除一个游戏
*
* @param roomId
*/
public static void removeGame(String roomId) {
gameMap.remove(roomId);
}
/**
* 是否有该游戏
*
* @param roomId
* @return
*/
public static boolean containsKey(String roomId) {
return gameMap.containsKey(roomId);
}
/**
* 获取指定游戏的玩家初始化数据
*
* @param roomId
* @return
*/
public static Map<String, Boolean> getRoleInitData(String roomId) {
if (gameMap.containsKey(roomId)) {
return getGame(roomId).getRoleInitData();
}
throw new RuntimeException("没有该房间");
}
/**
* 获取指定角色的游戏数据
*
* @param roomId
* @param playerId
* @return
*/
public static RoleInfo getRoleInfo(String roomId, String playerId) {
return getGame(roomId).getRoleInfoData().get(playerId);
}
/**
* 获取游戏中所有的角色数据
*
* @param roomId
* @return
*/
public static Map<String, RoleInfo> getRoleInfoGroup(String roomId) {
return getGame(roomId).getRoleInfoData();
}
/**
* 获取角色顺序
*
* @param roomId
* @return
*/
public static Queue<CurrentRole> getRoleOrder(String roomId) {
return getGame(roomId).getRoleOrder();
}
/**
* 获取角色位置信息
*
* @param roomId
* @return
*/
public static Map<String, Location> getRoleLocationData(String roomId) {
return getGame(roomId).getRoleLocationData();
}
/**
* 获取角色掷骰子数
*
* @param roomId
* @return
*/
public static Map<String, Integer> getRoleRollDiceData(String roomId) {
return getGame(roomId).getRoleRollDiceNumber();
}
/**
* 获取卡组
*
* @param roomId
* @return
*/
public static CardGroup getCardGroup(String roomId) {
return getGame(roomId).getCardGroup();
}
/**
* 获取回合结束数据
*
* @param roomId
* @return
*/
public static Map<String, Boolean> getRoundEndData(String roomId) {
return getGame(roomId).getRoundEndData();
}
/**
* 更新角色回合结束数据
*
* @param roomId
* @param roundEndData
*/
public static void updateRoundEndData(String roomId, Map<String, Boolean> roundEndData) {
getGame(roomId).setRoundEndData(roundEndData);
}
/**
* 获取角色购买保险数据
*
* @param roomId
*/
public static Map<String, Boolean> getInsuranceData(String roomId) {
return getGame(roomId).getInsuranceData();
}
/**
* 获取发红包的数据
*
* @param roomId
* @return
*/
public static Map<String, Boolean> getSendRedEnvelopeData(String roomId) {
return getGame(roomId).getSendRedEnvelopeData();
}
/**
* 获取发红包的金额
*
* @param roomId
* @return
*/
public static Map<String, Integer> getSendRedEnvelopeMoney(String roomId) {
return getGame(roomId).getSendRedEnvelopeMoney();
}
/**
* 重置红包数据
*
* @param roomId
* @param sendRedEnvelopeData
*/
public static void updateSendRedEnvelopeData(String roomId, Map<String, Boolean> sendRedEnvelopeData) {
getGame(roomId).setSendRedEnvelopeData(sendRedEnvelopeData);
}
/**
* 重置当前角色
*
* @param roomId
* @param currentRole
*/
public static void updateCurrentRole(String roomId, String currentRole) {
getGame(roomId).setCurrentRole(currentRole);
}
/**
* 移除初始化断线的玩家
*
* @param roomId
* @param playerId
*/
public static void removeRoleInRoleInit(String roomId, String playerId) {
getRoleInitData(roomId).remove(playerId);
}
/**
* 移除掉线角色多人回合
*
* @param roomId
* @param playerId
*/
public static void removeRoleFromAllRoundEnd(String roomId, String playerId) {
getGame(roomId).getRoundEndData().remove(playerId);
}
/**
* 从当前发红包房间移除掉线玩家
*
* @param roomId
* @param playerId
*/
public static void removeRoleFromSendRedEnvelop(String roomId, String playerId) {
getGame(roomId).getSendRedEnvelopeData().remove(playerId);
}
/**
* 将掉线玩家重新添加到游戏中发红包、多人回合
*
* @param roomId
* @param playerId
*/
public static void putRoleInGame(String roomId, String playerId) {
getGame(roomId).getSendRedEnvelopeData().put(playerId, false);
getGame(roomId).getRoundEndData().put(playerId, false);
}
}
| 21.720165 | 107 | 0.598143 |
baed1d86d454c310f1396b2a769fd8b251cdda22 | 182 | package br.exemplo.heranca;
public class Cachorro extends Animal{
public Cachorro() {
//Sempre que for referencia a SUPER classe AMINAL, usa o SUPER
super(30,"Carne");
}
}
| 16.545455 | 64 | 0.714286 |
6fb472c91b68702142c7428c06ab99e870d98305 | 17,475 | /**
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.market.param;
import static com.opengamma.strata.collect.TestHelper.assertThrowsIllegalArg;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static org.testng.Assert.assertEquals;
import java.util.List;
import java.util.Optional;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.FxMatrix;
import com.opengamma.strata.basics.currency.FxRate;
import com.opengamma.strata.collect.array.DoubleMatrix;
import com.opengamma.strata.collect.tuple.Pair;
import com.opengamma.strata.data.MarketDataName;
import com.opengamma.strata.market.curve.CurveName;
/**
* Test {@link CrossGammaParameterSensitivities}.
*/
@Test
public class CrossGammaParameterSensitivitiesTest {
private static final double FACTOR1 = 3.14;
private static final DoubleMatrix MATRIX_USD1 = DoubleMatrix.of(2, 2, 100, 200, 300, 123);
private static final DoubleMatrix MATRIX_USD2 = DoubleMatrix.of(2, 2, 1000, 250, 321, 123);
private static final DoubleMatrix MATRIX_USD2_IN_EUR = DoubleMatrix.of(2, 2, 1000 / 1.6, 250 / 1.6, 321 / 1.6, 123 / 1.6);
private static final DoubleMatrix MATRIX_USD12 = DoubleMatrix.of(2, 4, 100, 200, 1000, 250, 300, 123, 321, 123);
private static final DoubleMatrix MATRIX_USD21 = DoubleMatrix.of(2, 4, 1000, 250, -500, -400, 321, 123, -200, -300);
private static final DoubleMatrix MATRIX_ZERO = DoubleMatrix.of(2, 2, 0, 0, 0, 0);
private static final DoubleMatrix TOTAL_USD = DoubleMatrix.of(2, 2, 1100, 450, 621, 246);
private static final DoubleMatrix MATRIX_EUR1 = DoubleMatrix.of(2, 2, 1000, 250, 321, 123);
private static final DoubleMatrix MATRIX_EUR1_IN_USD =
DoubleMatrix.of(2, 2, 1000 * 1.6, 250 * 1.6, 321 * 1.6, 123 * 1.6);
private static final Currency USD = Currency.USD;
private static final Currency EUR = Currency.EUR;
private static final FxRate FX_RATE = FxRate.of(EUR, USD, 1.6d);
private static final MarketDataName<?> NAME0 = CurveName.of("NAME-0");
private static final MarketDataName<?> NAME1 = CurveName.of("NAME-1");
private static final MarketDataName<?> NAME2 = CurveName.of("NAME-2");
private static final MarketDataName<?> NAME3 = CurveName.of("NAME-3");
private static final List<ParameterMetadata> METADATA0 = ParameterMetadata.listOfEmpty(2);
private static final List<ParameterMetadata> METADATA1 = ParameterMetadata.listOfEmpty(2);
private static final List<ParameterMetadata> METADATA2 = ParameterMetadata.listOfEmpty(2);
private static final List<ParameterMetadata> METADATA3 = ParameterMetadata.listOfEmpty(2);
private static final CrossGammaParameterSensitivity ENTRY_USD =
CrossGammaParameterSensitivity.of(NAME1, METADATA1, USD, MATRIX_USD1);
private static final CrossGammaParameterSensitivity ENTRY_USD2 =
CrossGammaParameterSensitivity.of(NAME1, METADATA1, USD, MATRIX_USD2);
private static final CrossGammaParameterSensitivity ENTRY_USD_TOTAL =
CrossGammaParameterSensitivity.of(NAME1, METADATA1, USD, TOTAL_USD);
private static final CrossGammaParameterSensitivity ENTRY_USD2_IN_EUR =
CrossGammaParameterSensitivity.of(NAME1, METADATA1, EUR, MATRIX_USD2_IN_EUR);
private static final CrossGammaParameterSensitivity ENTRY_EUR =
CrossGammaParameterSensitivity.of(NAME2, METADATA2, EUR, MATRIX_EUR1);
private static final CrossGammaParameterSensitivity ENTRY_EUR_IN_USD =
CrossGammaParameterSensitivity.of(NAME2, METADATA2, USD, MATRIX_EUR1_IN_USD);
private static final CrossGammaParameterSensitivity ENTRY_ZERO0 =
CrossGammaParameterSensitivity.of(NAME0, METADATA0, USD, MATRIX_ZERO);
private static final CrossGammaParameterSensitivity ENTRY_ZERO3 =
CrossGammaParameterSensitivity.of(NAME3, METADATA3, USD, MATRIX_ZERO);
private static final CrossGammaParameterSensitivity ENTRY_USD12 = CrossGammaParameterSensitivity.of(
NAME1, METADATA1, ImmutableList.of(Pair.of(NAME1, METADATA1), Pair.of(NAME2, METADATA2)), USD, MATRIX_USD12);
private static final CrossGammaParameterSensitivity ENTRY_USD21 = CrossGammaParameterSensitivity.of(
NAME2, METADATA2, ImmutableList.of(Pair.of(NAME1, METADATA1), Pair.of(NAME2, METADATA2)), USD, MATRIX_USD21);
private static final CrossGammaParameterSensitivities SENSI_1 = CrossGammaParameterSensitivities.of(ENTRY_USD);
private static final CrossGammaParameterSensitivities SENSI_2 =
CrossGammaParameterSensitivities.of(ImmutableList.of(ENTRY_USD2, ENTRY_EUR));
private static final CrossGammaParameterSensitivities SENSI_3 =
CrossGammaParameterSensitivities.of(ImmutableList.of(ENTRY_USD12, ENTRY_USD21));
private static final double TOLERENCE_CMP = 1.0E-8;
//-------------------------------------------------------------------------
public void test_empty() {
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.empty();
assertEquals(test.size(), 0);
assertEquals(test.getSensitivities().size(), 0);
}
public void test_of_single() {
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of(ENTRY_USD);
assertEquals(test.size(), 1);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD));
}
public void test_of_array_none() {
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of();
assertEquals(test.size(), 0);
}
public void test_of_list_none() {
ImmutableList<CrossGammaParameterSensitivity> list = ImmutableList.of();
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of(list);
assertEquals(test.size(), 0);
}
public void test_of_list_notNormalized() {
ImmutableList<CrossGammaParameterSensitivity> list = ImmutableList.of(ENTRY_USD, ENTRY_EUR);
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of(list);
assertEquals(test.size(), 2);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD, ENTRY_EUR));
}
public void test_of_list_normalized() {
ImmutableList<CrossGammaParameterSensitivity> list = ImmutableList.of(ENTRY_USD, ENTRY_USD2);
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of(list);
assertEquals(test.size(), 1);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD_TOTAL));
}
//-------------------------------------------------------------------------
public void test_getSensitivity() {
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of(ENTRY_USD);
assertEquals(test.getSensitivity(NAME1, USD), ENTRY_USD);
assertThrowsIllegalArg(() -> test.getSensitivity(NAME1, EUR));
assertThrowsIllegalArg(() -> test.getSensitivity(NAME0, USD));
assertThrowsIllegalArg(() -> test.getSensitivity(NAME0, EUR));
}
public void test_findSensitivity() {
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.of(ENTRY_USD);
assertEquals(test.findSensitivity(NAME1, USD), Optional.of(ENTRY_USD));
assertEquals(test.findSensitivity(NAME1, EUR), Optional.empty());
assertEquals(test.findSensitivity(NAME0, USD), Optional.empty());
assertEquals(test.findSensitivity(NAME0, EUR), Optional.empty());
}
//-------------------------------------------------------------------------
public void test_combinedWith_one_notNormalized() {
CrossGammaParameterSensitivities test = SENSI_1.combinedWith(ENTRY_EUR);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD, ENTRY_EUR));
}
public void test_combinedWith_one_normalized() {
CrossGammaParameterSensitivities test = SENSI_1.combinedWith(ENTRY_USD2);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD_TOTAL));
}
public void test_combinedWith_other() {
CrossGammaParameterSensitivities test = SENSI_1.combinedWith(SENSI_2);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD_TOTAL, ENTRY_EUR));
}
public void test_combinedWith_otherEmpty() {
CrossGammaParameterSensitivities test = SENSI_1.combinedWith(CrossGammaParameterSensitivities.empty());
assertEquals(test, SENSI_1);
}
public void test_combinedWith_empty() {
CrossGammaParameterSensitivities test = CrossGammaParameterSensitivities.empty().combinedWith(SENSI_1);
assertEquals(test, SENSI_1);
}
//-------------------------------------------------------------------------
public void test_convertedTo_singleCurrency() {
CrossGammaParameterSensitivities test = SENSI_1.convertedTo(USD, FxMatrix.empty());
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD));
}
public void test_convertedTo_multipleCurrency() {
CrossGammaParameterSensitivities test = SENSI_2.convertedTo(USD, FX_RATE);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD2, ENTRY_EUR_IN_USD));
}
public void test_convertedTo_multipleCurrency_mergeWhenSameName() {
CrossGammaParameterSensitivities test = SENSI_1.combinedWith(ENTRY_USD2_IN_EUR).convertedTo(USD, FX_RATE);
assertEquals(test.getSensitivities(), ImmutableList.of(ENTRY_USD_TOTAL));
}
//-------------------------------------------------------------------------
public void test_total_singleCurrency() {
assertEquals(SENSI_1.total(USD, FxMatrix.empty()).getAmount(), MATRIX_USD1.total(), 1e-8);
}
public void test_total_multipleCurrency() {
assertEquals(SENSI_2.total(USD, FX_RATE).getAmount(), MATRIX_USD2.total() + MATRIX_EUR1.total() * 1.6d, 1e-8);
}
public void test_totalMulti_singleCurrency() {
assertEquals(SENSI_1.total().size(), 1);
assertEquals(SENSI_1.total().getAmount(USD).getAmount(), MATRIX_USD1.total(), 1e-8);
}
public void test_totalMulti_multipleCurrency() {
assertEquals(SENSI_2.total().size(), 2);
assertEquals(SENSI_2.total().getAmount(USD).getAmount(), MATRIX_USD2.total(), 1e-8);
assertEquals(SENSI_2.total().getAmount(EUR).getAmount(), MATRIX_EUR1.total(), 1e-8);
}
public void test_diagonal() {
assertEquals(SENSI_2.diagonal().size(), 2);
assertEquals(SENSI_2.diagonal().getSensitivity(NAME1, USD), ENTRY_USD2.diagonal());
assertEquals(SENSI_2.diagonal().getSensitivity(NAME2, EUR), ENTRY_EUR.diagonal());
assertEquals(SENSI_3.diagonal().getSensitivity(NAME1, USD), ENTRY_USD12.diagonal());
assertEquals(SENSI_3.diagonal().getSensitivity(NAME2, USD), ENTRY_USD21.diagonal());
}
//-------------------------------------------------------------------------
public void test_multipliedBy() {
CrossGammaParameterSensitivities multiplied = SENSI_1.multipliedBy(FACTOR1);
DoubleMatrix test = multiplied.getSensitivities().get(0).getSensitivity();
for (int i = 0; i < MATRIX_USD1.columnCount(); i++) {
for (int j = 0; j < MATRIX_USD1.rowCount(); j++) {
assertEquals(test.get(i, j), MATRIX_USD1.get(i, j) * FACTOR1);
}
}
}
public void test_mapSensitivities() {
CrossGammaParameterSensitivities multiplied = SENSI_1.mapSensitivities(a -> 1 / a);
DoubleMatrix test = multiplied.getSensitivities().get(0).getSensitivity();
for (int i = 0; i < MATRIX_USD1.columnCount(); i++) {
for (int j = 0; j < MATRIX_USD1.rowCount(); j++) {
assertEquals(test.get(i, j), 1 / MATRIX_USD1.get(i, j));
}
}
}
public void test_multipliedBy_vs_combinedWith() {
CrossGammaParameterSensitivities multiplied = SENSI_2.multipliedBy(2d);
CrossGammaParameterSensitivities added = SENSI_2.combinedWith(SENSI_2);
assertEquals(multiplied, added);
}
public void test_getSensitivity_name() {
assertEquals(SENSI_3.getSensitivity(NAME1, NAME1, USD), ENTRY_USD);
assertEquals(SENSI_3.getSensitivity(NAME1, NAME2, USD),
CrossGammaParameterSensitivity.of(NAME1, METADATA1, NAME2, METADATA2, USD, MATRIX_USD2));
assertEquals(SENSI_3.getSensitivity(NAME2, NAME1, USD),
CrossGammaParameterSensitivity.of(NAME2, METADATA2, NAME1, METADATA1, USD, MATRIX_USD2));
assertEquals(SENSI_3.getSensitivity(NAME2, NAME2, USD),
CrossGammaParameterSensitivity.of(NAME2, METADATA2, NAME2, METADATA2, USD,
DoubleMatrix.of(2, 2, -500, -400, -200, -300)));
}
//-------------------------------------------------------------------------
public void test_equalWithTolerance() {
CrossGammaParameterSensitivities sensUsdTotal = CrossGammaParameterSensitivities.of(ENTRY_USD_TOTAL);
CrossGammaParameterSensitivities sensEur = CrossGammaParameterSensitivities.of(ENTRY_EUR);
CrossGammaParameterSensitivities sens1plus2 = SENSI_1.combinedWith(ENTRY_USD2);
CrossGammaParameterSensitivities sensZeroA = CrossGammaParameterSensitivities.of(ENTRY_ZERO3);
CrossGammaParameterSensitivities sensZeroB = CrossGammaParameterSensitivities.of(ENTRY_ZERO0);
CrossGammaParameterSensitivities sens1plus2plus0a = SENSI_1.combinedWith(ENTRY_USD2).combinedWith(ENTRY_ZERO0);
CrossGammaParameterSensitivities sens1plus2plus0b = SENSI_1.combinedWith(ENTRY_USD2).combinedWith(ENTRY_ZERO3);
CrossGammaParameterSensitivities sens1plus2plus0 = SENSI_1
.combinedWith(ENTRY_USD2).combinedWith(ENTRY_ZERO0).combinedWith(ENTRY_ZERO3);
CrossGammaParameterSensitivities sens2plus0 = SENSI_2.combinedWith(sensZeroA);
assertEquals(SENSI_1.equalWithTolerance(sensZeroA, TOLERENCE_CMP), false);
assertEquals(SENSI_1.equalWithTolerance(SENSI_1, TOLERENCE_CMP), true);
assertEquals(SENSI_1.equalWithTolerance(SENSI_2, TOLERENCE_CMP), false);
assertEquals(SENSI_1.equalWithTolerance(sensUsdTotal, TOLERENCE_CMP), false);
assertEquals(SENSI_1.equalWithTolerance(sensEur, TOLERENCE_CMP), false);
assertEquals(SENSI_1.equalWithTolerance(sens1plus2, TOLERENCE_CMP), false);
assertEquals(SENSI_1.equalWithTolerance(sens2plus0, TOLERENCE_CMP), false);
assertEquals(SENSI_2.equalWithTolerance(sensZeroA, TOLERENCE_CMP), false);
assertEquals(SENSI_2.equalWithTolerance(SENSI_1, TOLERENCE_CMP), false);
assertEquals(SENSI_2.equalWithTolerance(SENSI_2, TOLERENCE_CMP), true);
assertEquals(SENSI_2.equalWithTolerance(sensUsdTotal, TOLERENCE_CMP), false);
assertEquals(SENSI_2.equalWithTolerance(sensEur, TOLERENCE_CMP), false);
assertEquals(SENSI_2.equalWithTolerance(sens1plus2, TOLERENCE_CMP), false);
assertEquals(SENSI_2.equalWithTolerance(sens2plus0, TOLERENCE_CMP), true);
assertEquals(sensZeroA.equalWithTolerance(sensZeroA, TOLERENCE_CMP), true);
assertEquals(sensZeroA.equalWithTolerance(SENSI_1, TOLERENCE_CMP), false);
assertEquals(sensZeroA.equalWithTolerance(SENSI_2, TOLERENCE_CMP), false);
assertEquals(sensZeroA.equalWithTolerance(sensUsdTotal, TOLERENCE_CMP), false);
assertEquals(sensZeroA.equalWithTolerance(sensEur, TOLERENCE_CMP), false);
assertEquals(sensZeroA.equalWithTolerance(sens1plus2, TOLERENCE_CMP), false);
assertEquals(sensZeroA.equalWithTolerance(sens2plus0, TOLERENCE_CMP), false);
assertEquals(sensZeroA.equalWithTolerance(sensZeroB, TOLERENCE_CMP), true);
assertEquals(sensZeroB.equalWithTolerance(sensZeroB, TOLERENCE_CMP), true);
assertEquals(sensZeroB.equalWithTolerance(SENSI_1, TOLERENCE_CMP), false);
assertEquals(sensZeroB.equalWithTolerance(SENSI_2, TOLERENCE_CMP), false);
assertEquals(sensZeroB.equalWithTolerance(sensUsdTotal, TOLERENCE_CMP), false);
assertEquals(sensZeroB.equalWithTolerance(sensEur, TOLERENCE_CMP), false);
assertEquals(sensZeroB.equalWithTolerance(sens1plus2, TOLERENCE_CMP), false);
assertEquals(sensZeroB.equalWithTolerance(sens2plus0, TOLERENCE_CMP), false);
assertEquals(sensZeroB.equalWithTolerance(sensZeroA, TOLERENCE_CMP), true);
assertEquals(sens1plus2.equalWithTolerance(sens1plus2, TOLERENCE_CMP), true);
assertEquals(sens1plus2.equalWithTolerance(sens1plus2plus0a, TOLERENCE_CMP), true);
assertEquals(sens1plus2.equalWithTolerance(sens1plus2plus0b, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0a.equalWithTolerance(sens1plus2, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0a.equalWithTolerance(sens1plus2plus0, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0a.equalWithTolerance(sens1plus2plus0a, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0a.equalWithTolerance(sens1plus2plus0b, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0b.equalWithTolerance(sens1plus2, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0b.equalWithTolerance(sens1plus2plus0, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0b.equalWithTolerance(sens1plus2plus0a, TOLERENCE_CMP), true);
assertEquals(sens1plus2plus0b.equalWithTolerance(sens1plus2plus0b, TOLERENCE_CMP), true);
assertEquals(sens2plus0.equalWithTolerance(sens2plus0, TOLERENCE_CMP), true);
assertEquals(sensZeroA.equalWithTolerance(CrossGammaParameterSensitivities.empty(), TOLERENCE_CMP), true);
assertEquals(CrossGammaParameterSensitivities.empty().equalWithTolerance(sensZeroA, TOLERENCE_CMP), true);
}
//-------------------------------------------------------------------------
public void coverage() {
coverImmutableBean(CrossGammaParameterSensitivities.empty());
coverImmutableBean(SENSI_1);
coverBeanEquals(SENSI_1, SENSI_2);
}
}
| 54.780564 | 124 | 0.754335 |
9e610faab8cc88a92bbd561b19ab225ce4534a15 | 602 | package com.yosanai.spring.starter.samplefileparse.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public abstract class BaseRecord {
public static final String RECORD_TYPE_HEADER = "01";
public static final String RECORD_TYPE_TRAILER = "05";
public static final String RECORD_TYPE_DEPARTMENT_HEADER = "02";
public static final String RECORD_TYPE_DEPARTMENT_TRAILER = "04";
public static final String RECORD_TYPE_EMPLOYEE = "03";
String recordType;
public BaseRecord(String recordType) {
super();
this.recordType = recordType;
}
}
| 23.153846 | 66 | 0.785714 |
9f90c90c8d4787de70d2cee8b02706b1d7d2b611 | 1,245 | package com.htc.htcwalletsdk.Utils;
import android.content.Context;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
public class VolleyUtils {
static public final String TAG = "VolleyUtils";
static public final String urlContractServer = "https://api-htcexodus.htctouch.com/";
static public final String eth_erc_table = "eth/ercjson/list/";
/**
* Naming : contractTable
* Method : http GET
*
* ex : https://www.htcsense.exodus/contractTable?dataSet=20&version=0
*
* if http request got 200 ok, but JSON body is null, it means no need to update.
*/
static public void downloadData(Context context, JsonObjectRequest jsonObjectRequest) {
ZKMALog.d(TAG,"VolleyUtils.downloadData() +++");
Volley.newRequestQueue(context).add(jsonObjectRequest);
ZKMALog.d(TAG,"VolleyUtils.downloadData() ---");
}
}
| 31.923077 | 91 | 0.725301 |
09f6d6442ae4bf74b253ca278cb802d8116190db | 1,670 | package edu.nikon.simpleapi.api.catalog;
import edu.nikon.simpleapi.api.catalog.dto.CountryItemDto;
import edu.nikon.simpleapi.api.catalog.dto.DocTypeItemDto;
import edu.nikon.simpleapi.api.catalog.service.CountryService;
import edu.nikon.simpleapi.api.catalog.service.DocumentTypeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* Catalog api controller
*/
@RestController
@RequestMapping("/api")
public class CatalogController {
private final DocumentTypeService documentTypeService;
private final CountryService countryService;
@Autowired
public CatalogController(DocumentTypeService documentTypeService,
CountryService countryService) {
this.documentTypeService = documentTypeService;
this.countryService = countryService;
}
@ApiOperation(value = "Return documents", nickname = "documents", httpMethod = "GET")
@GetMapping(value = "/docs", produces = APPLICATION_JSON_VALUE)
public List<DocTypeItemDto> getDocs() {
return documentTypeService.findAll();
}
@ApiOperation(value = "Return counties", nickname = "countries", httpMethod = "GET")
@GetMapping(value = "/countries", produces = APPLICATION_JSON_VALUE)
public List<CountryItemDto> getCountries() {
return countryService.findAll();
}
}
| 36.304348 | 89 | 0.764671 |
0171a39cae2eb4880c573d1cae6ca444f1fb1819 | 318 | package ca.bc.gov.open.scss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ScssApplication {
public static void main(String[] args) {
SpringApplication.run(ScssApplication.class, args);
}
}
| 26.5 | 68 | 0.786164 |
1b4116fdba7a8d8721035c09e53670cb8700b071 | 635 | package hr.tvz.vatrogasci.views.about;
import java.util.Optional;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.RouteAlias;
@PageTitle("About")
@Route(value = "about")
@RouteAlias(value = "")
public class AboutView extends Div {
public AboutView() {
addClassName("about-view");
add(new Text("Content placeholder"));
Optional<String> sOpt = Optional.ofNullable("dans");
if(sOpt.isEmpty()) {
add(new Text("dsds"));
}
}
}
| 23.518519 | 60 | 0.669291 |
f252e19a4c6292a4f5486e186333b350454597af | 4,180 | /*
* Copyright 2000-2006 JetBrains s.r.o.
*
* 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 jetbrains.communicator.jabber.impl;
import com.intellij.openapi.util.io.FileUtil;
import jetbrains.communicator.core.impl.BaseTestCase;
import jetbrains.communicator.jabber.AccountInfo;
import jetbrains.communicator.mock.MockIDEFacade;
import java.io.File;
import java.util.Arrays;
import java.util.List;
/**
* @author Kir
*/
public class JabberFacadeTest extends BaseTestCase {
private JabberFacadeImpl myFacade;
private MockIDEFacade myIDEFacade;
@Override
protected void setUp() throws Exception {
super.setUp();
myIDEFacade = new MockIDEFacade(getClass());
myFacade = new JabberFacadeImpl(myIDEFacade);
myFacade.getMyAccount().setRememberPassword(true);
}
public void testGoogleTalk() {
try {
assertNull(myFacade.connect("maxkir1", "123123123", "talk.google.com", 5222, false));
assertTrue(myFacade.isConnectedAndAuthenticated());
assertNull(myFacade.connect("maxkir1@gmail.com", "123123123", "talk.google.com", 5222, false));
assertTrue(myFacade.isConnectedAndAuthenticated());
assertTrue(myFacade.getConnection().isSecureConnection());
assertEquals("Should not change", "maxkir1@gmail.com", myFacade.getMyAccount().getUsername());
} finally {
myFacade.disconnect();
}
}
public void testPersist_Settings() {
myFacade.getMyAccount().setUsername("user");
myFacade.getMyAccount().setPassword("\u043f\u0440\u0438\u0432\u0435\u0442 \u0442\u0435\u0431\u0435");
myFacade.getMyAccount().setServer("jabber.ru");
myFacade.getMyAccount().setPort(839);
myFacade.saveSettings();
JabberFacadeImpl loaded = new JabberFacadeImpl(myIDEFacade);
assertEquals("Should persist AccountInfo",
new AccountInfo("user", "\u043f\u0440\u0438\u0432\u0435\u0442 \u0442\u0435\u0431\u0435", "jabber.ru", 839).toString(),
loaded.getMyAccount().toString());
assertEquals("Password decoded incorrectly",
"\u043f\u0440\u0438\u0432\u0435\u0442 \u0442\u0435\u0431\u0435", loaded.getMyAccount().getPassword());
}
public void testNoPlainPassword() throws Exception {
myFacade.getMyAccount().setPassword("pwd822");
myFacade.saveSettings();
File file = new File(myIDEFacade.getConfigDir(), JabberFacadeImpl.FILE_NAME);
String fileText = FileUtil.loadFile(file);
assertEquals("toString Should not contain plain password: " + myFacade.getMyAccount().toString(), -1,
myFacade.getMyAccount().toString().indexOf("pwd822"));
assertEquals("Settings file should not contain plain password: " + fileText, -1, fileText.indexOf("pwd822"));
}
public void testDoNotRememberPassword() {
myFacade.getMyAccount().setPassword("pwd822");
myFacade.getMyAccount().setRememberPassword(false);
myFacade.saveSettings();
JabberFacadeImpl loaded = new JabberFacadeImpl(myIDEFacade);
assertEquals("Should not remember password", "", loaded.getMyAccount().getPassword());
}
public void testGetServers() {
List<String> list = Arrays.asList(myFacade.getServers());
assertTrue("List of servers should be taken from file:" + list, list.size() > 20);
assertTrue("List should contain jabber.org:" + list, list.contains("jabber.org"));
for (int i = 0; i < list.size(); i++) {
java.lang.String s = list.get(i);
assertNotNull("Nulls not allowed:" + i +" " + list, s);
}
}
public void testSkipConnect_WhenDisabled() {
myFacade.getMyAccount().setLoginAllowed(false);
myFacade.connect();
assertNull("Should not try to connect", myFacade.getConnection());
}
}
| 36.99115 | 126 | 0.71866 |
ade5366c5f9a8c39470cf579b5611dacc549cce1 | 663 | package com.github.davidmoten.security;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
final class Bytes {
private Bytes() {
// prevent instantiation
}
static byte[] from(InputStream is) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
int nRead;
byte[] buffer = new byte[1024];
while ((nRead = is.read(buffer)) != -1) {
bytes.write(buffer, 0, nRead);
}
return bytes.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 23.678571 | 70 | 0.570136 |
8863fdb0252594ce029e6b785a7aad65cfdccdd3 | 1,559 | package net.dzikoysk.netkit;
import net.dzikoysk.netkit.listener.LoadListener;
import org.apache.commons.lang.StringEscapeUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicLong;
public class NetkitPage {
private static final AtomicLong idAssigner = new AtomicLong();
private final long id;
private final Netkit netkit;
private final Collection<LoadListener> loadListeners;
public NetkitPage(Netkit netkit) {
this.id = idAssigner.getAndIncrement();
this.netkit = netkit;
this.loadListeners = new ArrayList<>(1);
}
public void loadURL(String url) {
netkit.executeScript("Netkit.loadURL(" + id + ",'" + url + "');");
}
public void loadContent(String content) {
netkit.executeScript("Netkit.loadContent(" + id + ", '" + StringEscapeUtils.escapeHtml(content) + "');");
}
public void addJavascriptInterface(String interfaceName, Object gateway) {
String temp = getId() + "-" + interfaceName;
netkit.addJavascriptInterface(temp, gateway);
netkit.executeScript("Netkit.setPageJavascriptInterface(" + temp + ", '" + interfaceName + "');");
}
public void executeScript(String script) {
netkit.executeScript(script);
}
public void addLoadListener(LoadListener listener) {
this.loadListeners.add(listener);
}
protected Collection<LoadListener> getLoadListeners() {
return loadListeners;
}
public long getId() {
return id;
}
}
| 28.345455 | 113 | 0.675433 |
345ed3b8ebb5a1dc403bd8afd6b9aeef82df6778 | 9,864 | package com.jakub.ajamarks.services.showdataservices;
import com.jakub.ajamarks.entities.Classroom;
import com.jakub.ajamarks.entities.Student;
import com.jakub.ajamarks.repositories.ClassroomRepository;
import com.jakub.ajamarks.services.showdataservices.ClassroomServiceImpl;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import java.util.*;
/**
* Created by ja on 23.01.17.
*/
public class ClassroomServiceImplTest {
private ClassroomServiceImpl classroomServiceImpl;
private Classroom classroom1;
private Classroom classroom2;
private List<Classroom> classroomList;
private Set<Student> studentSet;
@Before
public void testSetUp(){
Student student1 = new Student();
student1.setFirstName("Jakub");
student1.setLastName("Jakub2");
student1.setUserName("Jakub3");
Student student2 = new Student();
student2.setFirstName("Tomasz");
student2.setLastName("Tomasz2");
student2.setUserName("Tomasz3");
studentSet = new TreeSet<>();
Collections.addAll(studentSet, student1, student2);
classroom1 = new Classroom();
classroom1.setIdClassroom(1L);
classroom1.setClassroomNumber(1);
classroom1.setClassroomName("Pierwsza");
classroom1.setStudentsInClassroom(Collections.emptySet());
classroom2 = new Classroom();
classroom2.setIdClassroom(2L);
classroom2.setClassroomNumber(2);
classroom2.setClassroomName("Druga");
classroom2.setStudentsInClassroom(studentSet);
classroomList = new ArrayList<>();
Collections.addAll(classroomList, classroom1, classroom2);
classroomServiceImpl = new ClassroomServiceImpl();
classroomServiceImpl.classroomRepository = mock(ClassroomRepository.class);
}
@Test
public void saveClassroomTest(){
//given
when(classroomServiceImpl.classroomRepository.save(classroom1)).thenReturn(classroom1);
//when
classroomServiceImpl.saveClassroom(classroom1);
//then
verify(classroomServiceImpl.classroomRepository).save(classroom1);
}
@Test(expected = IllegalArgumentException.class)
public void saveClassroom_IllegalArgumentExceptionTest(){
//given
Classroom classroom3 = null;
//when
classroomServiceImpl.saveClassroom(classroom3);
//then
}
@Test
public void deleteTest(){
//given
doNothing().when(classroomServiceImpl.classroomRepository).delete(classroom1);
//when
classroomServiceImpl.delete(classroom1);
//then
verify(classroomServiceImpl.classroomRepository).delete(classroom1);
}
@Test(expected = IllegalArgumentException.class)
public void delete_IllegalArgumentExceptionTest(){
//given
Classroom classroom3 = null;
//when
classroomServiceImpl.delete(classroom3);
//then
}
@Test
public void updateClassroomTest(){
//given
when(classroomServiceImpl.classroomRepository.findOne(1L)).thenReturn(classroom1);
//when
classroomServiceImpl.updateClassroom(1L, classroom2);
//then
verify(classroomServiceImpl.classroomRepository).findOne(1L);
}
@Test(expected = NullPointerException.class)
public void updateClassroom_IllegalArgumentExceptionTest(){
//given
Classroom classroom3 = null;
//when
classroomServiceImpl.updateClassroom(1L, classroom3);
//then
}
@Test(expected = IllegalArgumentException.class)
public void updateClassroom_NullPointerExceptionTest(){
//given
Classroom classroom3 = new Classroom();
//when
classroomServiceImpl.updateClassroom(0L, classroom3);
//then
}
@Test
public void getAllByClassroomNameAscTest(){
//given
when(classroomServiceImpl.classroomRepository.findAllByOrderByClassroomNameAsc()).thenReturn(classroomList);
//when
List<Classroom> allByClassroomNameAsc = classroomServiceImpl.getAllByClassroomNameAsc();
//then
verify(classroomServiceImpl.classroomRepository).findAllByOrderByClassroomNameAsc();
}
@Test
public void getClassroomByIdTest(){
//given
long idClassroom = classroom1.getIdClassroom();
when(classroomServiceImpl.classroomRepository.findOne(idClassroom)).thenReturn(classroom1);
//when
classroomServiceImpl.getClassroomById(idClassroom);
//then
verify(classroomServiceImpl.classroomRepository).findOne(idClassroom);
}
@Test(expected = IllegalArgumentException.class)
public void getClassroomById_IllegalArgumentExceptionTest(){
//given
long idClassroom = 0;
//when
classroomServiceImpl.getClassroomById(idClassroom);
//then
}
@Test
public void getClassroomByNumberTest(){
//given
int classroomNumber = classroom1.getClassroomNumber();
when(classroomServiceImpl.classroomRepository.findByClassroomNumber(classroomNumber)).thenReturn(classroom1);
//when
classroomServiceImpl.getClassroomByNumber(classroomNumber);
//then
verify(classroomServiceImpl.classroomRepository).findByClassroomNumber(classroomNumber);
}
@Test(expected = IllegalArgumentException.class)
public void getClassroomByNumber_IllegalArgumentExceptionTest(){
//given
int classroomNumber = 0;
//when
classroomServiceImpl.getClassroomByNumber(classroomNumber);
//then
}
@Test
public void getClassroomByNameTest(){
//given
String classroomName = classroom1.getClassroomName();
when(classroomServiceImpl.classroomRepository.findByClassroomName(classroomName)).thenReturn(classroom1);
//when
classroomServiceImpl.getClassroomByName(classroomName);
//then
verify(classroomServiceImpl.classroomRepository).findByClassroomName(classroomName);
}
@Test(expected = IllegalArgumentException.class)
public void getClassroomByName_IllegalArgumentExceptionTest(){
//given
String classroomName = null;
//when
classroomServiceImpl.getClassroomByName(classroomName);
//then
}
@Test
public void getClassroomStudentsByClassroomNumberTest(){
//given
int classroomNumber = classroom2.getClassroomNumber();
when(classroomServiceImpl.classroomRepository.findByClassroomNumber(classroomNumber)).thenReturn(classroom2);
//when
classroomServiceImpl.getClassroomStudentsByClassroomNumber(classroomNumber);
//then
verify(classroomServiceImpl.classroomRepository).findByClassroomNumber(classroomNumber);
}
@Test
public void getClassroomStudentsByClassroomNumber_NoStudentsTest(){
//given
int classroomNumber = classroom1.getClassroomNumber();
when(classroomServiceImpl.classroomRepository.findByClassroomNumber(classroomNumber)).thenReturn(classroom1);
//when
Set<Student> classroomStudentsByClassroomNumber = classroomServiceImpl.getClassroomStudentsByClassroomNumber(classroomNumber);
//then
verify(classroomServiceImpl.classroomRepository).findByClassroomNumber(classroomNumber);
assertEquals(Collections.emptySet(), classroomStudentsByClassroomNumber);
}
@Test(expected = IllegalArgumentException.class)
public void getClassroomStudentsByClassroomNumber_IllegalArgumentExceptionTest(){
//given
int classroomNumber = 0;
//when
classroomServiceImpl.getClassroomStudentsByClassroomNumber(classroomNumber);
//then
}
@Test(expected = NullPointerException.class)
public void getClassroomStudentsByClassroomNumber_NullPointerExceptionTest(){
//given
int classroomNumber = 21;
//when
classroomServiceImpl.getClassroomStudentsByClassroomNumber(classroomNumber);
//then
}
@Test
public void getClassroomStudentsByClassroomNameTest(){
//given
String classroomName = classroom2.getClassroomName();
when(classroomServiceImpl.classroomRepository.findByClassroomName(classroomName)).thenReturn(classroom2);
//when
classroomServiceImpl.getClassroomStudentsByClassroomName(classroomName);
//then
verify(classroomServiceImpl.classroomRepository).findByClassroomName(classroomName);
}
@Test
public void getClassroomStudentsByClassroomName_NoStudentsTest(){
//given
String classroomName = classroom1.getClassroomName();
when(classroomServiceImpl.classroomRepository.findByClassroomName(classroomName)).thenReturn(classroom1);
//when
Set<Student> classroomStudentsByClassroomName = classroomServiceImpl.getClassroomStudentsByClassroomName(classroomName);
//then
verify(classroomServiceImpl.classroomRepository).findByClassroomName(classroomName);
assertEquals(Collections.emptySet(), classroomStudentsByClassroomName);
}
@Test(expected = IllegalArgumentException.class)
public void getClassroomStudentsByClassroomName_IllegalArgumentExceptionTest(){
//given
String classroomName = null;
//when
classroomServiceImpl.getClassroomStudentsByClassroomName(classroomName);
//then
}
@Test(expected = NullPointerException.class)
public void getClassroomStudentsByClassroomName_NullPointerExceptionTest(){
//given
String classroomName = "no name";
//when
classroomServiceImpl.getClassroomStudentsByClassroomName(classroomName);
//then
}
}
| 34.25 | 134 | 0.710361 |
b888333dc953ac6b5024717df4bb865440127d70 | 5,182 | /*
* Copyright (C) 2016-present Albie Liang. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package cc.suitalk.arbitrarygen.template;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.File;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import cc.suitalk.arbitrarygen.template.base.BasePyroWorker;
import cc.suitalk.arbitrarygen.utils.FileOperation;
import cc.suitalk.arbitrarygen.utils.Log;
import cc.suitalk.arbitrarygen.utils.TemplateUtils;
import cc.suitalk.arbitrarygen.utils.Util;
/**
*
* @author AlbieLiang
*
*/
public class PyroGenTask extends BasePyroWorker {
private static final String TAG = "AG.PyroGenTask";
private List<String> mSupportSuffixList;
public PyroGenTask(TemplateConfig cfg) {
super(cfg);
mSupportSuffixList = new LinkedList<>();
}
public PyroGenTask(TemplateConfig cfg, List<String> supportSuffixList) {
this(cfg);
addSupportSuffixList(supportSuffixList);
}
@SuppressWarnings("unchecked")
@Override
public String genCode(ScriptEngine engine, JSONObject jsonObj, TaskInfo info) {
String pkg = jsonObj.optString("@package", "");
String delegate = jsonObj.optString("@delegate", "");
String rawTags = jsonObj.optString("@tag", "");
String rootTag = jsonObj.optString("@delegateTag", null);
JSONObject delegateJson = new JSONObject();
delegateJson.put("@package", pkg);
delegateJson.put("@name", delegate);
String[] tags = null;
if (!Util.isNullOrNil(rawTags)) {
tags = rawTags.split(",");
} else {
Set<String> list = new HashSet<>();
for (String key : (Set<String>) jsonObj.keySet()) {
if (key != null && !key.startsWith("@")) {
list.add(key);
}
}
if (!list.isEmpty()) {
tags = new String[list.size()];
int i = 0;
for (String tag : list) {
tags[i++] = tag;
}
}
}
if (tags != null) {
for (int i = 0; i < tags.length; i++) {
String tagName = tags[i];
Object tagObj = jsonObj.get(tagName);
if (tagObj == null) {
Log.w(TAG, "the JSON object do not exist with tag : %s", tagName);
continue;
}
JSONArray list = new JSONArray();
try {
String template = TemplateManager.getImpl().get(tagName);
if (Util.isNullOrNil(template)) {
Log.w(TAG, "the template do not exist with tag : %s", tagName);
continue;
}
Log.i(TAG, "start gen code, tagName : %s.", tagName);
if (tagObj instanceof JSONArray) {
JSONArray arr = (JSONArray) tagObj;
for (int j = 0, len = arr.size(); j < len; j++) {
JSONObject obj = arr.getJSONObject(j);
obj.put("@package", pkg);
if (!Util.isNullOrNil(template)) {
genCode(engine, template, info.script, info.destPath, obj);
}
list.add(obj);
}
} else {
JSONObject json = (JSONObject) tagObj;
json.put("@package", pkg);
if (!Util.isNullOrNil(template)) {
genCode(engine, template, info.script, info.destPath, json);
}
list.add(json);
}
} catch (ScriptException e) {
Log.e(TAG, "gen code error : %s", e);
}
delegateJson.put(getValidateTag(tagName), list);
}
}
while (!Util.isNullOrNil(delegate)) {
String template = TemplateManager.getImpl().get(rootTag);
if (Util.isNullOrNil(template)) {
Log.w(TAG, "the template do not exist with tag : %s", rootTag);
break;
}
try {
genCode(engine, template, info.script, info.destPath, delegateJson);
} catch (ScriptException e) {
Log.e(TAG, "gen code error : %s", e);
}
break;
}
return null;
}
@Override
public List<String> getSupportSuffixList() {
return mSupportSuffixList;
}
public void addSupportSuffixList(List<String> suffixList) {
mSupportSuffixList.addAll(suffixList);
}
private String getValidateTag(String tag) {
if (Util.isNullOrNil(tag)) {
return tag;
}
return tag.replaceAll("-", "_");
}
private void genCode(ScriptEngine engine, String template, String script, String destPath, JSONObject obj) throws ScriptException {
String jsonStr = obj.toString().replace("@", "_");
String s = script + "\nparseTemplate(\"" + TemplateUtils.escape(template) + "\"," + jsonStr + ");";
String dest = destPath + "/" + obj.getString("@package").replace('.', '/');
String path = dest + "/" + obj.getString("@name") + ".java";
File destFolder = new File(dest);
if (!destFolder.exists()) {
destFolder.mkdirs();
}
FileOperation.write(path, TemplateUtils.format(TemplateUtils.unescape((String) engine.eval(s))));
}
}
| 29.443182 | 132 | 0.66345 |
56b4eae78ac0cab5d865550d24e1fa051aca1742 | 9,993 | /***********************************************************************************************************************
* 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.nephele.instance;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Set;
import eu.stratosphere.nephele.deployment.TaskDeploymentDescriptor;
import eu.stratosphere.nephele.execution.librarycache.LibraryCacheManager;
import eu.stratosphere.nephele.execution.librarycache.LibraryCacheProfileRequest;
import eu.stratosphere.nephele.execution.librarycache.LibraryCacheProfileResponse;
import eu.stratosphere.nephele.execution.librarycache.LibraryCacheUpdate;
import eu.stratosphere.nephele.executiongraph.ExecutionVertexID;
import eu.stratosphere.nephele.taskmanager.TaskKillResult;
import eu.stratosphere.runtime.io.channels.ChannelID;
import eu.stratosphere.nephele.ipc.RPC;
import eu.stratosphere.nephele.jobgraph.JobID;
import eu.stratosphere.nephele.net.NetUtils;
import eu.stratosphere.nephele.protocols.TaskOperationProtocol;
import eu.stratosphere.nephele.taskmanager.TaskCancelResult;
import eu.stratosphere.nephele.taskmanager.TaskSubmissionResult;
import eu.stratosphere.nephele.topology.NetworkNode;
import eu.stratosphere.nephele.topology.NetworkTopology;
/**
* An abstract instance represents a resource a {@link eu.stratosphere.nephele.taskmanager.TaskManager} runs on.
*
*/
public abstract class AbstractInstance extends NetworkNode {
/**
* The type of the instance.
*/
private final InstanceType instanceType;
/**
* The connection info identifying the instance.
*/
private final InstanceConnectionInfo instanceConnectionInfo;
/**
* The hardware description as reported by the instance itself.
*/
private final HardwareDescription hardwareDescription;
/**
* Stores the RPC stub object for the instance's task manager.
*/
private TaskOperationProtocol taskManager = null;
/**
* Constructs an abstract instance object.
*
* @param instanceType
* the type of the instance
* @param instanceConnectionInfo
* the connection info identifying the instance
* @param parentNode
* the parent node in the network topology
* @param networkTopology
* the network topology this node is a part of
* @param hardwareDescription
* the hardware description provided by the instance itself
*/
public AbstractInstance(final InstanceType instanceType, final InstanceConnectionInfo instanceConnectionInfo,
final NetworkNode parentNode, final NetworkTopology networkTopology,
final HardwareDescription hardwareDescription) {
super((instanceConnectionInfo == null) ? null : instanceConnectionInfo.toString(), parentNode, networkTopology);
this.instanceType = instanceType;
this.instanceConnectionInfo = instanceConnectionInfo;
this.hardwareDescription = hardwareDescription;
}
/**
* Creates or returns the RPC stub object for the instance's task manager.
*
* @return the RPC stub object for the instance's task manager
* @throws IOException
* thrown if the RPC stub object for the task manager cannot be created
*/
private TaskOperationProtocol getTaskManagerProxy() throws IOException {
if (this.taskManager == null) {
this.taskManager = RPC.getProxy(TaskOperationProtocol.class,
new InetSocketAddress(getInstanceConnectionInfo().address(),
getInstanceConnectionInfo().ipcPort()), NetUtils.getSocketFactory());
}
return this.taskManager;
}
/**
* Destroys and removes the RPC stub object for this instance's task manager.
*/
private void destroyTaskManagerProxy() {
if (this.taskManager != null) {
RPC.stopProxy(this.taskManager);
this.taskManager = null;
}
}
/**
* Returns the type of the instance.
*
* @return the type of the instance
*/
public final InstanceType getType() {
return this.instanceType;
}
/**
* Returns the instance's connection information object.
*
* @return the instance's connection information object
*/
public final InstanceConnectionInfo getInstanceConnectionInfo() {
return this.instanceConnectionInfo;
}
/**
* Returns the instance's hardware description as reported by the instance itself.
*
* @return the instance's hardware description
*/
public HardwareDescription getHardwareDescription() {
return this.hardwareDescription;
}
/**
* Checks if all the libraries required to run the job with the given
* job ID are available on this instance. Any libary that is missing
* is transferred to the instance as a result of this call.
*
* @param jobID
* the ID of the job whose libraries are to be checked for
* @throws IOException
* thrown if an error occurs while checking for the libraries
*/
public synchronized void checkLibraryAvailability(final JobID jobID) throws IOException {
// Now distribute the required libraries for the job
String[] requiredLibraries = LibraryCacheManager.getRequiredJarFiles(jobID);
if (requiredLibraries == null) {
throw new IOException("No entry of required libraries for job " + jobID);
}
LibraryCacheProfileRequest request = new LibraryCacheProfileRequest();
request.setRequiredLibraries(requiredLibraries);
// Send the request
LibraryCacheProfileResponse response = null;
response = getTaskManagerProxy().getLibraryCacheProfile(request);
// Check response and transfer libraries if necessary
for (int k = 0; k < requiredLibraries.length; k++) {
if (!response.isCached(k)) {
LibraryCacheUpdate update = new LibraryCacheUpdate(requiredLibraries[k]);
getTaskManagerProxy().updateLibraryCache(update);
}
}
}
/**
* Submits a list of tasks to the instance's {@link eu.stratosphere.nephele.taskmanager.TaskManager}.
*
* @param tasks
* the list of tasks to be submitted
* @return the result of the submission attempt
* @throws IOException
* thrown if an error occurs while transmitting the task
*/
public synchronized List<TaskSubmissionResult> submitTasks(final List<TaskDeploymentDescriptor> tasks)
throws IOException {
return getTaskManagerProxy().submitTasks(tasks);
}
/**
* Cancels the task identified by the given ID at the instance's
* {@link eu.stratosphere.nephele.taskmanager.TaskManager}.
*
* @param id
* the ID identifying the task to be canceled
* @throws IOException
* thrown if an error occurs while transmitting the request or receiving the response
* @return the result of the cancel attempt
*/
public synchronized TaskCancelResult cancelTask(final ExecutionVertexID id) throws IOException {
return getTaskManagerProxy().cancelTask(id);
}
/**
* Kills the task identified by the given ID at the instance's
* {@link eu.stratosphere.nephele.taskmanager.TaskManager}.
*
* @param id
* the ID identifying the task to be killed
* @throws IOException
* thrown if an error occurs while transmitting the request or receiving the response
* @return the result of the kill attempt
*/
public synchronized TaskKillResult killTask(final ExecutionVertexID id) throws IOException {
return getTaskManagerProxy().killTask(id);
}
@Override
public boolean equals(final Object obj) {
// Fall back since dummy instances do not have a instanceConnectionInfo
if (this.instanceConnectionInfo == null) {
return super.equals(obj);
}
if (!(obj instanceof AbstractInstance)) {
return false;
}
final AbstractInstance abstractInstance = (AbstractInstance) obj;
return this.instanceConnectionInfo.equals(abstractInstance.getInstanceConnectionInfo());
}
@Override
public int hashCode() {
// Fall back since dummy instances do not have a instanceConnectionInfo
if (this.instanceConnectionInfo == null) {
return super.hashCode();
}
return this.instanceConnectionInfo.hashCode();
}
/**
* Triggers the remote task manager to print out the current utilization of its read and write buffers to its logs.
*
* @throws IOException
* thrown if an error occurs while transmitting the request
*/
public synchronized void logBufferUtilization() throws IOException {
getTaskManagerProxy().logBufferUtilization();
}
/**
* Kills the task manager running on this instance. This method is mainly intended to test and debug Nephele's fault
* tolerance mechanisms.
*
* @throws IOException
* thrown if an error occurs while transmitting the request
*/
public synchronized void killTaskManager() throws IOException {
getTaskManagerProxy().killTaskManager();
}
/**
* Invalidates the entries identified by the given channel IDs from the remote task manager's receiver lookup cache.
*
* @param channelIDs
* the channel IDs identifying the cache entries to invalidate
* @throws IOException
* thrown if an error occurs during this remote procedure call
*/
public synchronized void invalidateLookupCacheEntries(final Set<ChannelID> channelIDs) throws IOException {
getTaskManagerProxy().invalidateLookupCacheEntries(channelIDs);
}
/**
* Destroys all RPC stub objects attached to this instance.
*/
public synchronized void destroyProxies() {
destroyTaskManagerProxy();
}
}
| 33.533557 | 120 | 0.734314 |
cb3c8bfc8efcf69c754191a7d2a048ec81f4b78a | 193 | package com.github.mmurak.scalemaker.functions;
public class KI extends Function {
public double calculateFunction(double value) {
return 1.0 - Math.log10(Math.pow(value, 1.0 / 3.0));
}
}
| 24.125 | 54 | 0.735751 |
1bd47eafe50372bedd809e1166547d4189201c1d | 572 | public class ChessboardPoint {
private int x;
private int y;
public ChessboardPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String toString() {
return String.format("(%d,%d)", x, y);
}
public ChessboardPoint offset(int dx, int dy) {
int a = x + dx;
int b = y + dy;
if (a < 0 || a > 7 || b < 0 || b > 7) {
return null;
} else return new ChessboardPoint(a, b);
}
} | 19.724138 | 51 | 0.475524 |
6eee12e73e81a2dc6e80d2e213170b802b883187 | 583 | package org.testobject.rest.api.resource.v2;
import org.testobject.rest.api.model.TestSuiteReport;
import javax.ws.rs.*;
@Produces({"application/json"})
@Consumes({"application/json"})
@Path("v2/batchReports")
public interface TestSuiteReportResourceV2 {
@GET
@Produces({"application/json"})
@Consumes({"application/json"})
@Path("{testSuiteReport}")
TestSuiteReport getReport(@PathParam("testSuiteReport") long batchReport, @HeaderParam("Accept") String mediatype, String apiKey);
String getXMLReport(@PathParam("testSuiteReport") long batchReport, String apiKey);
}
| 27.761905 | 131 | 0.765009 |
77ee68141ee02e21216b246d32efa79c3e2a2647 | 2,471 | package scanner;
import domain.ScanResult;
import util.CollectionUtil;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;
public class IPScanner {
private final static Logger logger = Logger.getLogger(IPScanner.class.getName());
private final static int PORTS_PER_THREAD = 20;
public List<Integer> scanIP(final String ip, final int[] ports) {
final List<Future<List<ScanResult>>> scanResults = getOpenPorts(ip, ports);
final List<Integer> openPorts = new ArrayList<>();
for (Future<List<ScanResult>> future : scanResults) {
try {
final List<ScanResult> partialScanResults = future.get();
for (ScanResult scanResult : partialScanResults) {
if (scanResult.isOpen()) {
openPorts.add(scanResult.getPort());
}
}
} catch (InterruptedException | ExecutionException e) {
logger.warning(e.getMessage());
}
}
return openPorts;
}
private List<Future<List<ScanResult>>> getOpenPorts(final String ip, final int[] ports) {
final ExecutorService executorService = Executors.newFixedThreadPool(PORTS_PER_THREAD);
final int[][] partialPorts = CollectionUtil.divideArray(ports, PORTS_PER_THREAD);
final List<Future<List<ScanResult>>> openPorts = new ArrayList<>();
Arrays
.stream(partialPorts)
.forEach(partialPort -> openPorts
.add(executorService.submit(() -> getOpenPortsSync(ip, partialPort))));
executorService.shutdown();
return openPorts;
}
List<ScanResult> getOpenPortsSync(final String ip, final int ports[]) {
final List<ScanResult> scanResults = new ArrayList<>();
for (int port : ports) {
final ScanResult scanResult = new ScanResult(port, false);
scanResult.setOpen(connect(new Socket(), ip, port));
scanResults.add(scanResult);
}
return scanResults;
}
boolean connect(final Socket socket, final String ip, final int port) {
try {
socket.connect(new InetSocketAddress(ip, port), 200);
socket.close();
return true;
} catch (final IOException e) {
logger.info("Port: " + port + " is closed.");
return false;
}
}
}
| 32.946667 | 91 | 0.696074 |
dca77f5fecbd44374d13f342a7b3672a86c59471 | 7,253 | /*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.kurento.jsonrpc.client;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.kurento.jsonrpc.JsonRpcHandler;
import org.kurento.jsonrpc.JsonUtils;
import org.kurento.jsonrpc.internal.JsonRpcHandlerManager;
import org.kurento.jsonrpc.internal.JsonRpcRequestSenderHelper;
import org.kurento.jsonrpc.internal.client.ClientSession;
import org.kurento.jsonrpc.internal.client.TransactionImpl;
import org.kurento.jsonrpc.internal.client.TransactionImpl.ResponseSender;
import org.kurento.jsonrpc.message.Message;
import org.kurento.jsonrpc.message.Request;
import org.kurento.jsonrpc.message.Response;
import org.kurento.jsonrpc.message.ResponseError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class JsonRpcClientLocal extends JsonRpcClient {
private static Logger log = LoggerFactory.getLogger(JsonRpcClientLocal.class);
private JsonRpcHandler<? extends Object> remoteHandler;
private final JsonRpcHandlerManager remoteHandlerManager = new JsonRpcHandlerManager();
public <F> JsonRpcClientLocal(JsonRpcHandler<? extends Object> handler) {
this.remoteHandler = handler;
this.remoteHandlerManager.setJsonRpcHandler(remoteHandler);
session = new ClientSession("XXX", null, this);
rsHelper = new JsonRpcRequestSenderHelper() {
@Override
public <P, R> Response<R> internalSendRequest(Request<P> request, Class<R> resultClass)
throws IOException {
return localSendRequest(request, resultClass);
}
@Override
protected void internalSendRequest(Request<? extends Object> request,
Class<JsonElement> resultClass, Continuation<Response<JsonElement>> continuation) {
Response<JsonElement> result = localSendRequest(request, resultClass);
if (result != null) {
continuation.onSuccess(result);
}
}
};
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <R, P> Response<R> localSendRequest(Request<P> request, Class<R> resultClass) {
// Simulate sending json string for net
String jsonRequest = request.toString();
log.debug("--> {}", jsonRequest);
Request<JsonObject> newRequest = JsonUtils.fromJsonRequest(jsonRequest, JsonObject.class);
final Response<JsonObject>[] response = new Response[1];
ClientSession clientSession = new ClientSession(session.getSessionId(), null,
new JsonRpcRequestSenderHelper() {
@Override
protected void internalSendRequest(Request<? extends Object> request,
Class<JsonElement> clazz, final Continuation<Response<JsonElement>> continuation) {
handlerManager.handleRequest(session, (Request<JsonElement>) request,
new ResponseSender() {
@Override
public void sendResponse(Message message) throws IOException {
continuation.onSuccess((Response<JsonElement>) message);
}
@Override
public void sendPingResponse(Message message) throws IOException {
sendResponse(message);
}
});
}
@Override
protected <P2, R2> Response<R2> internalSendRequest(Request<P2> request,
Class<R2> resultClass) throws IOException {
final Object[] response = new Object[1];
final CountDownLatch responseLatch = new CountDownLatch(1);
handlerManager.handleRequest(session, (Request<JsonElement>) request,
new ResponseSender() {
@Override
public void sendResponse(Message message) throws IOException {
response[0] = message;
responseLatch.countDown();
}
@Override
public void sendPingResponse(Message message) throws IOException {
sendResponse(message);
}
});
Response<R2> response2 = (Response<R2>) response[0];
try {
responseLatch.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.debug("<-- {}", response2);
Object result = response2.getResult();
if (result == null || resultClass.isAssignableFrom(result.getClass())) {
return response2;
} else if (resultClass == JsonElement.class) {
response2.setResult((R2) JsonUtils.toJsonElement(result));
return response2;
} else {
throw new ClassCastException("Class " + result + " cannot be converted to "
+ resultClass);
}
}
});
TransactionImpl t = new TransactionImpl(clientSession, newRequest, new ResponseSender() {
@Override
public void sendResponse(Message message) throws IOException {
response[0] = (Response<JsonObject>) message;
}
@Override
public void sendPingResponse(Message message) throws IOException {
sendResponse(message);
}
});
try {
remoteHandler.handleRequest(t, (Request) request);
} catch (Exception e) {
ResponseError error = ResponseError.newFromException(e);
return new Response<>(request.getId(), error);
}
if (response[0] != null) {
// Simulate receiving json string from net
Response<R> responseObj = (Response<R>) response[0];
if (responseObj.getId() == null) {
responseObj.setId(request.getId());
}
String jsonResponse = responseObj.toString();
// log.debug("< {}", jsonResponse);
Response<R> newResponse = JsonUtils.fromJsonResponse(jsonResponse, resultClass);
newResponse.setId(request.getId());
return newResponse;
}
return new Response<>(request.getId());
}
@Override
public void close() throws IOException {
handlerManager.afterConnectionClosed(session, "Client close");
super.close();
}
@Override
public void setServerRequestHandler(org.kurento.jsonrpc.JsonRpcHandler<?> handler) {
super.setServerRequestHandler(handler);
handlerManager.afterConnectionEstablished(session);
remoteHandlerManager.afterConnectionEstablished(session);
}
@Override
public void connect() throws IOException {
}
@Override
public void setRequestTimeout(long requesTimeout) {
log.warn("setRequestTimeout(...) method will be ignored");
}
}
| 33.423963 | 94 | 0.665656 |
a1d89ab55e10c5c483a229eea4469febd4e65cc9 | 4,706 | package org.adligo.tests4j_tests.system.shared.report.summary;
import org.adligo.tests4j.models.shared.results.PhaseStateMutant;
import org.adligo.tests4j.shared.asserts.reference.AllowedReferences;
import org.adligo.tests4j.shared.en.Tests4J_EnglishConstants;
import org.adligo.tests4j.shared.i18n.I_Tests4J_ReportMessages;
import org.adligo.tests4j.shared.output.I_Tests4J_Log;
import org.adligo.tests4j.system.shared.report.summary.TestsProgressDisplay;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_4mockito.MockMethod;
import org.adligo.tests4j_tests.base_trials.I_CountType;
import org.adligo.tests4j_tests.base_trials.SourceFileCountingTrial;
import org.adligo.tests4j_tests.references_groups.Tests4J_Summary_GwtReferenceGroup;
@SourceFileScope (sourceClass=TestsProgressDisplay.class)
@AllowedReferences (groups=Tests4J_Summary_GwtReferenceGroup.class)
public class TestsProgressDisplayTrial extends SourceFileCountingTrial {
private I_Tests4J_Log logMock_;
private MockMethod<Void> logRecord_;
private MockMethod<Void> logLineRecord_;
private MockMethod<Void> onThrowableRecord_;
private TestsProgressDisplay reporter_;
@Override
public void beforeTests() {
logMock_ = mock(I_Tests4J_Log.class);
logRecord_ = new MockMethod<Void>();
doAnswer(logRecord_).when(logMock_).log(any());
logLineRecord_ = new MockMethod<Void>();
doAnswer(logLineRecord_).when(logMock_).logLine(anyVararg());
onThrowableRecord_ = new MockMethod<Void>();
doAnswer(onThrowableRecord_).when(logMock_).onThrowable(any());
when(logMock_.lineSeparator()).thenReturn("lineSeperator");
reporter_ = new TestsProgressDisplay(Tests4J_EnglishConstants.ENGLISH);
}
@SuppressWarnings("boxing")
@Test
public void testProgressReportLogOff() {
PhaseStateMutant info = new PhaseStateMutant();
info.setProcessName("tests");
info.setPercentDone(100.0);
info.setHasFinishedAll(true);
reporter_.onProgress(logMock_, info);
assertEquals(0, logRecord_.count());
assertEquals(0, onThrowableRecord_.count());
}
@SuppressWarnings("boxing")
@Test
public void testProgressReportPartDone() {
when(logMock_.isLogEnabled(any())).thenReturn(true);
PhaseStateMutant info = new PhaseStateMutant();
info.setProcessName("tests");
info.setPercentDone(17.343);
reporter_.onProgress(logMock_, info);
assertEquals(1, logLineRecord_.count());
Object [] args = logLineRecord_.getArgs(0);
I_Tests4J_ReportMessages messages = Tests4J_EnglishConstants.ENGLISH.getReportMessages();
assertEquals("Tests4J: ", args[0]);
assertEquals("tests", args[1]);
assertEquals(" ", args[2]);
assertEquals("17.34" + messages.getPctComplete(), args[3]);
assertEquals(4, args.length);
assertEquals(0, logRecord_.count());
assertEquals(0, onThrowableRecord_.count());
}
@SuppressWarnings("boxing")
@Test
public void testProgressReportDone() {
when(logMock_.isLogEnabled(any())).thenReturn(true);
PhaseStateMutant info = new PhaseStateMutant();
info.setProcessName("tests");
info.setPercentDone(100.0);
info.setHasFinishedAll(true);
reporter_.onProgress(logMock_, info);
assertEquals(1, logLineRecord_.count());
Object [] args = logLineRecord_.getArgs(0);
assertEquals(4, args.length);
I_Tests4J_ReportMessages messages = Tests4J_EnglishConstants.ENGLISH.getReportMessages();
assertEquals("Tests4J: ", args[0]);
assertEquals("tests", args[1]);
assertEquals(" ", args[2]);
assertEquals(messages.getDoneEOS(), args[3]);
assertEquals(4, args.length);
assertEquals(0, logRecord_.count());
assertEquals(0, onThrowableRecord_.count());
}
@Override
public int getTests(I_CountType type) {
return super.getTests(type, 3, true);
}
@Override
public int getAsserts(I_CountType type) {
int thisAsserts = 19;
//code coverage and circular dependencies +
//custom afterTrialTests
//+ see above
int thisAfterAsserts = 3;
if (type.isFromMetaWithCoverage()) {
return super.getAsserts(type, thisAsserts + thisAfterAsserts);
} else {
return super.getAsserts(type, thisAsserts);
}
}
@Override
public int getUniqueAsserts(I_CountType type) {
int thisUniqueAsserts = 15;
//code coverage and circular dependencies +
//custom afterTrialTests
//+ see above
int thisAfterUniqueAsserts = 3;
if (type.isFromMetaWithCoverage()) {
//code coverage and circular dependencies +
//custom afterTrialTests
return super.getUniqueAsserts(type, thisUniqueAsserts + thisAfterUniqueAsserts);
} else {
return super.getUniqueAsserts(type, thisUniqueAsserts);
}
}
}
| 33.614286 | 91 | 0.760943 |
ba463d75e63df722bc55f8f2d3b8e03a2456bd2b | 1,606 | package com.fasterxml.jackson.databind.filter;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
/**
* Unit tests for ensuring that entries accessible via "any filter"
* can also be filtered with JSON Filter functionality.
*/
public class TestAnyGetterFiltering extends BaseMapTest
{
@JsonFilter("anyFilter")
public static class AnyBean
{
private Map<String, String> properties = new HashMap<String, String>();
{
properties.put("a", "1");
properties.put("b", "2");
}
@JsonAnyGetter
public Map<String, String> anyProperties()
{
return properties;
}
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
// should also work for @JsonAnyGetter, as per [JACKSON-516]
public void testAnyGetterFiltering() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
FilterProvider prov = new SimpleFilterProvider().addFilter("anyFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("b"));
assertEquals("{\"b\":\"2\"}", mapper.writer(prov).writeValueAsString(new AnyBean()));
}
}
| 30.884615 | 93 | 0.627646 |
35b65a1026939baa0a28c6085caa11d15a4531ce | 534 | package io.dkgj.modules.sys.dao;
import io.dkgj.modules.sys.entity.LogloanEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Mark
* @email sunlightcs@gmail.com
* @date 2019-03-27 10:12:15
*/
@Mapper
public interface LogloanDao extends BaseMapper<LogloanEntity> {
Map<String, Object> selectSum(Map<String, Object> params);
List<LogloanEntity> selectLogloanlList(Map<String, Object> params);
}
| 22.25 | 71 | 0.750936 |
8676e9421a4aa925b7491684f93cee5ff5a54111 | 421 | package fun.play.dubbo;
import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;
@Service
public class OneServiceImpl implements OneService{
public String doSth(){
return "Hello,client";
}
@Override
public String timeOut() {
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
return e.getMessage();
}
return "ok";
}
}
| 17.541667 | 50 | 0.703088 |
d64e298088a63a28b7e0fa3513cb81bab06fe38e | 1,021 | package com.mimecast.robin;
import java.util.ArrayList;
import java.util.List;
/**
* Main runnable.
*/
public final class MainMock extends Main {
/**
* Logs list.
*/
private List<String> logs;
/**
* Main runnable.
*
* @param argv List of String.
*/
public static List<String> main(List<String> argv) {
MainMock main = new MainMock(argv.toArray(new String[0]));
return main.getLogs();
}
/**
* Constructs a new Main instance.
*
* @param args String array.
*/
private MainMock(String[] args) {
super(args);
}
/**
* Logging wrapper.
*
* @param string String.
*/
@Override
public void log(String string) {
super.log(string);
if (logs == null) {
logs = new ArrayList<>();
}
logs.add(string);
}
/**
* Gets logs.
*
* @return List of String.
*/
private List<String> getLogs() {
return logs;
}
}
| 17.603448 | 66 | 0.520078 |
e363239ee6daa3a66928f3b0296216e9f5c76e63 | 7,387 | /*
* ******************************************************************************
* * Copyright (c) 2021 Deeplearning4j Contributors
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.datavec.api.transform.transform.integer;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.datavec.api.transform.metadata.ColumnMetaData;
import org.datavec.api.transform.metadata.IntegerMetaData;
import org.datavec.api.transform.schema.Schema;
import org.datavec.api.transform.transform.BaseTransform;
import org.datavec.api.writable.IntWritable;
import org.datavec.api.writable.Writable;
import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties;
import org.nd4j.shade.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Convert an integer column to a set of one-hot columns.
*
*
* @author Alex Black
*/
@Data
@EqualsAndHashCode(exclude = {"columnIdx"}, callSuper = false)
@JsonIgnoreProperties({"inputSchema", "columnIdx", "stateNames", "statesMap"})
public class IntegerToOneHotTransform extends BaseTransform {
private String columnName;
private int minValue;
private int maxValue;
private int columnIdx = -1;
public IntegerToOneHotTransform(@JsonProperty("columnName") String columnName,
@JsonProperty("minValue") int minValue, @JsonProperty("maxValue") int maxValue) {
this.columnName = columnName;
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public void setInputSchema(Schema inputSchema) {
super.setInputSchema(inputSchema);
columnIdx = inputSchema.getIndexOfColumn(columnName);
ColumnMetaData meta = inputSchema.getMetaData(columnName);
if (!(meta instanceof IntegerMetaData))
throw new IllegalStateException("Cannot convert column \"" + columnName
+ "\" from integer to one-hot: column is not integer (is: " + meta.getColumnType() + ")");
}
@Override
public String toString() {
return "CategoricalToOneHotTransform(columnName=\"" + columnName + "\")";
}
@Override
public Schema transform(Schema schema) {
List<String> origNames = schema.getColumnNames();
List<ColumnMetaData> origMeta = schema.getColumnMetaData();
int i = 0;
Iterator<String> namesIter = origNames.iterator();
Iterator<ColumnMetaData> typesIter = origMeta.iterator();
List<ColumnMetaData> newMeta = new ArrayList<>(schema.numColumns());
while (namesIter.hasNext()) {
String s = namesIter.next();
ColumnMetaData t = typesIter.next();
if (i++ == columnIdx) {
//Convert this to one-hot:
for (int x = minValue; x <= maxValue; x++) {
String newName = s + "[" + x + "]";
newMeta.add(new IntegerMetaData(newName, 0, 1));
}
} else {
newMeta.add(t);
}
}
return schema.newSchema(newMeta);
}
@Override
public List<Writable> map(List<Writable> writables) {
if (writables.size() != inputSchema.numColumns()) {
throw new IllegalStateException("Cannot execute transform: input writables list length (" + writables.size()
+ ") does not " + "match expected number of elements (schema: " + inputSchema.numColumns()
+ "). Transform = " + toString());
}
int idx = getColumnIdx();
int n = maxValue - minValue + 1;
List<Writable> out = new ArrayList<>(writables.size() + n);
int i = 0;
for (Writable w : writables) {
if (i++ == idx) {
int currValue = w.toInt();
if (currValue < minValue || currValue > maxValue) {
throw new IllegalStateException("Invalid value: integer value (" + currValue + ") is outside of "
+ "valid range: must be between " + minValue + " and " + maxValue + " inclusive");
}
for (int j = minValue; j <= maxValue; j++) {
if (j == currValue) {
out.add(new IntWritable(1));
} else {
out.add(new IntWritable(0));
}
}
} else {
//No change to this column
out.add(w);
}
}
return out;
}
/**
* Transform an object
* in to another object
*
* @param input the record to transform
* @return the transformed writable
*/
@Override
public Object map(Object input) {
int currValue = ((Number) input).intValue();
if (currValue < minValue || currValue > maxValue) {
throw new IllegalStateException("Invalid value: integer value (" + currValue + ") is outside of "
+ "valid range: must be between " + minValue + " and " + maxValue + " inclusive");
}
List<Integer> oneHot = new ArrayList<>();
for (int j = minValue; j <= maxValue; j++) {
if (j == currValue) {
oneHot.add(1);
} else {
oneHot.add(0);
}
}
return oneHot;
}
/**
* Transform a sequence
*
* @param sequence
*/
@Override
public Object mapSequence(Object sequence) {
List<?> values = (List<?>) sequence;
List<List<Integer>> ret = new ArrayList<>();
for (Object obj : values) {
ret.add((List<Integer>) map(obj));
}
return ret;
}
/**
* The output column name
* after the operation has been applied
*
* @return the output column name
*/
@Override
public String outputColumnName() {
throw new UnsupportedOperationException("Output column name will be more than 1");
}
/**
* The output column names
* This will often be the same as the input
*
* @return the output column names
*/
@Override
public String[] outputColumnNames() {
List<String> l = transform(inputSchema).getColumnNames();
return l.toArray(new String[l.size()]);
}
/**
* Returns column names
* this op is meant to run on
*
* @return
*/
@Override
public String[] columnNames() {
return new String[] {columnName};
}
/**
* Returns a singular column name
* this op is meant to run on
*
* @return
*/
@Override
public String columnName() {
return columnName;
}
}
| 32.399123 | 120 | 0.569514 |
b06a94ff68c51fe9f5a7174f55dfc62afaf8c1ef | 3,304 | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// 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.dataprep.api.service.command.aggregation;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.talend.dataprep.command.GenericCommand;
import org.talend.dataprep.exception.TDPException;
import org.talend.dataprep.exception.error.CommonErrorCodes;
import org.talend.dataprep.transformation.aggregation.api.AggregationParameters;
import java.io.InputStream;
import static org.talend.dataprep.command.Defaults.pipeStream;
/**
* Aggregate command. Take the content of the dataset or preparation before sending it to the transformation service.
*/
@Component
@Scope(org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE)
public class Aggregate extends GenericCommand<InputStream> {
/** This class' logger. */
private static final Logger LOG = LoggerFactory.getLogger(Aggregate.class);
/**
* Default constructor.
* @param parameters aggregation parameters.
*/
public Aggregate(final AggregationParameters parameters) {
super(GenericCommand.TRANSFORM_GROUP);
execute(() -> onExecute(parameters));
on(HttpStatus.OK).then(pipeStream());
}
/**
* Call the transformation service with the export parameters in json the request body.
*
* @param parameters the aggregate parameters.
* @return the http request to execute.
*/
private HttpRequestBase onExecute(AggregationParameters parameters) {
// must work on either a dataset or a preparation, if both parameters are set, an error is thrown
if (StringUtils.isNotBlank(parameters.getDatasetId())
&& StringUtils.isNotBlank(parameters.getPreparationId())) {
LOG.error("Cannot aggregate on both dataset id & preparation id : {}", parameters);
throw new TDPException(CommonErrorCodes.BAD_AGGREGATION_PARAMETERS);
}
String uri = transformationServiceUrl + "/aggregate"; //$NON-NLS-1$
HttpPost aggregateCall = new HttpPost(uri);
try {
String paramsAsJson = objectMapper.writer().writeValueAsString(parameters);
aggregateCall.setEntity(new StringEntity(paramsAsJson, ContentType.APPLICATION_JSON));
} catch (JsonProcessingException e) {
throw new TDPException(CommonErrorCodes.UNABLE_TO_AGGREGATE, e);
}
return aggregateCall;
}
}
| 39.333333 | 117 | 0.703995 |
ebd7a26c2210b681cc1612437679ecd77129e2f4 | 12,164 | /*
* COPYRIGHT AND LICENSE
*
* Copyright 2014 The Regents of the University of California All Rights Reserved
*
* Permission to copy, modify and distribute any part of this CRBS Workflow
* Service for educational, research and non-profit purposes, without fee, and
* without a written agreement is hereby granted, provided that the above
* copyright notice, this paragraph and the following three paragraphs appear
* in all copies.
*
* Those desiring to incorporate this CRBS Workflow Service into commercial
* products or use for commercial purposes should contact the Technology
* Transfer Office, University of California, San Diego, 9500 Gilman Drive,
* Mail Code 0910, La Jolla, CA 92093-0910, Ph: (858) 534-5815,
* FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
* LOST PROFITS, ARISING OUT OF THE USE OF THIS CRBS Workflow Service, EVEN IF
* THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE CRBS Workflow Service PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE
* UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE UNIVERSITY OF CALIFORNIA MAKES
* NO REPRESENTATIONS AND EXTENDS NO WARRANTIES OF ANY KIND, EITHER IMPLIED OR
* EXPRESS, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT THE USE OF
* THE CRBS Workflow Service WILL NOT INFRINGE ANY PATENT, TRADEMARK OR OTHER
* RIGHTS.
*/
package edu.ucsd.crbs.cws.log;
import edu.ucsd.crbs.cws.auth.User;
import edu.ucsd.crbs.cws.workflow.Job;
import edu.ucsd.crbs.cws.workflow.Workflow;
import edu.ucsd.crbs.cws.workflow.WorkspaceFile;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
/**
* Creates Event objects and sets appropriate fields to denote different
* types of Events
*
* @author Christopher Churas <churas@ncmir.ucsd.edu>
*/
public class EventBuilderImpl implements EventBuilder {
/**
* HttpServletRequest Header Parameter showing what tool the requestor used
* to make the web request
*/
public static final String USER_AGENT_HEADER = "User-Agent";
/**
* HttpServletRequest Header Parameter to get host that responded to request
*/
public static final String HOST_HEADER = "Host";
/**
* GAE engine HttpServletRequest Header Parameter name to get city
* where request originated
*/
public static final String CITY_HEADER = "X-AppEngine-City";
/**
* GAE engine HttpServletRequest Header Parameter name to get region (in U.S. its the state)
* where request originated
*/
public static final String REGION_HEADER = "X-AppEngine-Region";
/**
* GAE engine HttpServletRequest Header Parameter name to get country
* where request originated
*/
public static final String COUNTRY_HEADER = "X-AppEngine-Country";
/**
* GAE engine HttpServletRequest Header Parameter name to get latitude and longitude of the city
* where request originated
*/
public static final String CITY_LAT_LONG_HEADER = "X-AppEngine-CityLatLong";
/**
* Logger
*/
private static final Logger _log
= Logger.getLogger(EventBuilderImpl.class.getName());
/**
* @param val
* @return returns string "null" if <b>val</b> is null otherwise returns <b>val</b>
*/
private String nullSafeString(final String val){
if (val == null){
return "null";
}
return val;
}
private String nullSafeDateString(final Date date){
if (date == null){
return "null";
}
return date.toString();
}
/**
* Creates a new Event by parsing parameters out of HttpServletRequest and User
* objects passed in.
* @param request
* @param user
* @return New Event with location data and if possible user information set, note Id is NOT set
*/
@Override
public Event createEvent(HttpServletRequest request, User user) {
Event event = new Event();
if (user != null){
event.setIpAddress(user.getIpAddress());
event.setUserId(user.getId());
}
else {
_log.warning("User object is null");
}
if (request != null){
event.setUserAgent(request.getHeader(USER_AGENT_HEADER));
event.setHost(request.getHeader(HOST_HEADER));
event.setCity(request.getHeader(CITY_HEADER));
event.setRegion(request.getHeader(REGION_HEADER));
event.setCountry(request.getHeader(COUNTRY_HEADER));
event.setCityLatLong(request.getHeader(CITY_LAT_LONG_HEADER));
}
return event;
}
/**
* Logs Job creation event
* @param event
* @param job
* @return
*/
@Override
public Event setAsCreateJobEvent(Event event, Job job) {
if (anyOfTheseObjectsNull(event,job) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setJobId(job.getId());
event.setEventType(Event.CREATE_JOB_EVENT_TYPE);
event.setDate(job.getCreateDate());
return event;
}
@Override
public Event setAsCreateWorkflowEvent(Event event, Workflow workflow) {
if (anyOfTheseObjectsNull(event,workflow) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setWorkflowId(workflow.getId());
event.setEventType(Event.CREATE_WORKFLOW_EVENT_TYPE);
event.setDate(workflow.getCreateDate());
return event;
}
@Override
public Event setAsCreateWorkspaceFileEvent(Event event, WorkspaceFile workspaceFile) {
if (anyOfTheseObjectsNull(event,workspaceFile) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setWorkspaceFileId(workspaceFile.getId());
event.setEventType(Event.CREATE_WORKSPACEFILE_EVENT_TYPE);
event.setDate(workspaceFile.getCreateDate());
return event;
}
@Override
public Event setAsFailedCreateJobEvent(Event event, Job job) {
if (anyOfTheseObjectsNull(event,job) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setEventType(Event.FAILED_CREATE_JOB_EVENT_TYPE);
event.setDate(new Date());
String errorSummary = job.getSummaryOfErrors();
if (errorSummary != null){
event.setMessage(job.getSummaryOfErrors());
}
return event;
}
@Override
public Event setAsCreateUserEvent(Event event, User user) {
if (anyOfTheseObjectsNull(event,user) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setEventType(Event.CREATE_USER_EVENT_TYPE);
event.setDate(user.getCreateDate());
event.setCreatedUserId(user.getId());
event.setMessage("perms("+user.getPermissions()+")");
return event;
}
/**
* Checks if any of the Objects passed in is null. If yes true is returned
* @param objects Objects to check
* @return true if no objects are passed in or if objects are null or if one or more objects is null
*/
private boolean anyOfTheseObjectsNull(Object...objects){
if (objects == null){
return true;
}
if (objects.length < 1){
return true;
}
for (Object o : objects){
if (o == null){
return true;
}
}
return false;
}
@Override
public Event setAsLogicalDeleteWorkflowEvent(Event event, Workflow workflow) {
if (anyOfTheseObjectsNull(event,workflow) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setWorkflowId(workflow.getId());
event.setEventType(Event.LOGICAL_DELETE_WORKFLOW_EVENT_TYPE);
event.setDate(new Date());
return event;
}
@Override
public Event setAsDeleteWorkflowEvent(Event event, Workflow workflow) {
if (anyOfTheseObjectsNull(event,workflow) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setWorkflowId(workflow.getId());
event.setEventType(Event.DELETE_WORKFLOW_EVENT_TYPE);
event.setDate(new Date());
StringBuilder sb = new StringBuilder();
sb.append("Name=");
sb.append(nullSafeString(workflow.getName()));
sb.append(",Version=");
sb.append(Integer.toString(workflow.getVersion()));
sb.append(",CreateDate=");
sb.append(nullSafeDateString(workflow.getCreateDate()));
event.setMessage(sb.toString());
return event;
}
@Override
public Event setAsLogicalDeleteWorkspaceFileEvent(Event event, WorkspaceFile wsf) {
if (anyOfTheseObjectsNull(event,wsf) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setWorkspaceFileId(wsf.getId());
event.setEventType(Event.LOGICAL_DELETE_WORKSPACEFILE_EVENT_TYPE);
event.setDate(new Date());
return event;
}
@Override
public Event setAsDeleteWorkspaceFileEvent(Event event, WorkspaceFile wsf) {
if (anyOfTheseObjectsNull(event,wsf) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setWorkspaceFileId(wsf.getId());
event.setEventType(Event.DELETE_WORKSPACEFILE_EVENT_TYPE);
event.setDate(new Date());
StringBuilder sb = new StringBuilder();
sb.append("Name=");
sb.append(nullSafeString(wsf.getName()));
sb.append(",CreateDate=");
sb.append(nullSafeDateString(wsf.getCreateDate()));
sb.append(",Path=");
sb.append(nullSafeString(wsf.getPath()));
event.setMessage(sb.toString());
return event;
}
@Override
public Event setAsDeleteJobEvent(Event event, Job job) {
if (this.anyOfTheseObjectsNull(event,job) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setJobId(job.getId());
event.setEventType(Event.DELETE_JOB_EVENT_TYPE);
event.setDate(new Date());
StringBuilder sb = new StringBuilder();
sb.append("Name=");
sb.append(nullSafeString(job.getName()));
sb.append(",CreateDate=");
sb.append(nullSafeDateString(job.getCreateDate()));
event.setMessage(sb.toString());
return event;
}
@Override
public Event setAsLogicalDeleteJobEvent(Event event, Job job) {
if (this.anyOfTheseObjectsNull(event,job) == true){
_log.log(Level.WARNING,"One or more parameters passed in is null. Unable to log event.");
return null;
}
event.setJobId(job.getId());
event.setEventType(Event.LOGICAL_DELETE_JOB_EVENT_TYPE);
event.setDate(new Date());
return event;
}
}
| 34.458924 | 104 | 0.637701 |
42cc86c128f5ffb362f2fb356f9e0c15ea751c5f | 9,299 | /***
Copyright 2013-2015 Tushar Dudani
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.tushar.cmspen;
import net.pocketmagic.android.eventinjector.Events;
import net.pocketmagic.android.eventinjector.Events.InputDevice;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
int id = -1;
boolean compatible = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(pref.getInt("id", id) == -1)
{
try {
compatible = new CheckComp().execute().get();
} catch (Exception e) {
e.printStackTrace();
}
if(compatible)
{
SharedPreferences.Editor editor = pref.edit();
editor.putInt("id", id);
editor.commit();
}
else
{
AlertDialog.Builder builderdonate = new AlertDialog.Builder(this);
builderdonate.setTitle("CM S Pen Add-on");
builderdonate.setMessage("Sorry your device is not compatible with this Application. Please email me for further assistance.");
builderdonate.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builderdonate.setCancelable(false);
builderdonate.show();
}
}
final int pvalues[] = {100,250,500,750,1000,1250,1500,1750,2000,2250,2500,2750,3000,3250,3500,3750,4000};
final TextView polltext = (TextView) findViewById(R.id.pollingvalue);
final TextView soffpolltext = (TextView) findViewById(R.id.soffpollingvalue);
ToggleButton startStop = (ToggleButton) findViewById(R.id.onOfftoggle);
final ToggleButton soffchk = (ToggleButton) findViewById(R.id.soffpollingtoggle);
final SeekBar pvalue = (SeekBar) findViewById(R.id.polling);
final SeekBar soffpvalue = (SeekBar) findViewById(R.id.soffpolling);
if(pref.getBoolean("enabled", false))
{
startStop.setChecked(true);
}
else
{
soffchk.setEnabled(false);
pvalue.setEnabled(false);
soffpvalue.setEnabled(false);
}
if(pref.getBoolean("soffchk", false))
{
soffchk.setChecked(true);
}
else
{
soffpvalue.setEnabled(false);
}
if(pref.getInt("pollingchoice", -1) == -1)
{
SharedPreferences.Editor editor = pref.edit();
editor.putInt("pollingchoice", 4);
editor.commit();
}
if(pref.getInt("soffpolling", -1) == -1)
{
SharedPreferences.Editor editor = pref.edit();
editor.putInt("soffpolling", 8);
editor.commit();
}
pvalue.setProgress(pref.getInt("pollingchoice", 0));
polltext.setText("Polling Value: " + String.valueOf(pvalues[pref.getInt("pollingchoice", 0)]));
soffpvalue.setProgress(pref.getInt("soffpolling", 0));
soffpolltext.setText("Screen-off Polling Value: " + String.valueOf(pvalues[pref.getInt("soffpolling", 0)]));
startStop.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
if(isChecked)
{
StartEventMonitor(MainActivity.this);
Toast.makeText(MainActivity.this, "Event monitor started.", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("enabled", true);
editor.commit();
soffchk.setEnabled(true);
pvalue.setEnabled(true);
soffpvalue.setEnabled(true);
}
else
{
Toast.makeText(MainActivity.this, "Event monitor stopped.", Toast.LENGTH_SHORT).show();
StopEventMonitor(MainActivity.this);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("enabled", false);
editor.commit();
soffchk.setEnabled(false);
pvalue.setEnabled(false);
soffpvalue.setEnabled(false);
}
}
});
soffchk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
if(isChecked)
{
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("soffchk", true);
editor.commit();
soffpvalue.setEnabled(true);
StopEventMonitor(MainActivity.this);
StartEventMonitor(MainActivity.this);
}
else
{
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("soffchk", false);
editor.commit();
soffpvalue.setEnabled(false);
StopEventMonitor(MainActivity.this);
StartEventMonitor(MainActivity.this);
}
}
});
pvalue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
polltext.setText("Polling Value: " + String.valueOf(pvalues[arg1]));
SharedPreferences.Editor editor = pref.edit();
editor.putInt("pollingchoice", arg1);
editor.commit();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this, "Please disable and enable the detection to apply.", Toast.LENGTH_SHORT).show();
}
});
soffpvalue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
soffpolltext.setText("Screen-off Polling Value: " + String.valueOf(pvalues[arg1]));
SharedPreferences.Editor editor = pref.edit();
editor.putInt("soffpolling", arg1);
editor.commit();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this, "Please disable and enable the detection to apply.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
}
public static void StopEventMonitor(Context ctx) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
if(pref.getBoolean("soffchk", false))
ctx.stopService(new Intent(ctx,SPenDetection.class));
else
ctx.stopService(new Intent(ctx,BackgroundService.class));
}
public static void StartEventMonitor(Context ctx) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
if(pref.getBoolean("soffchk", false))
ctx.startService(new Intent(ctx,SPenDetection.class));
else
ctx.startService(new Intent(ctx,BackgroundService.class));
}
class CheckComp extends AsyncTask<Void, Void, Boolean> {
ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute()
{
mDialog.setMessage(" Checking Compatibility");
mDialog.setProgressStyle(ProgressDialog.THEME_HOLO_DARK);
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
Events events = new Events();
events.Init();
Boolean temp = false;
for (InputDevice idev:events.m_Devs) {
{
try
{
if(idev.Open(true))
if(idev.getName().contains("sec_e-pen") == true)
{
temp = true;
id = events.m_Devs.indexOf(idev);
break;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
return temp;
}
@Override
protected void onPostExecute(Boolean v) {
mDialog.dismiss();
}
}
}
| 35.903475 | 137 | 0.64394 |
6704b12e3c27b035d18b3f3897605172bdc05835 | 809 | /*
* 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 uts.isd.model;
import java.util.Date;
/**
*
* @author willi
*/
public class UniversalAccessLog {
private Date loggedin;
private Date loggedout;
public Date getLoggedin() {
return loggedin;
}
public void setLoggedout(Date loggedout) {
this.loggedout = loggedout;
}
public Date getLoggedout() {
return loggedout;
}
public void setLoggedin(Date loggedin) {
this.loggedin = loggedin;
}
public UniversalAccessLog(Date loggedin, Date loggedout) {
this.loggedin = loggedin;
this.loggedout = loggedout;
}
}
| 19.731707 | 79 | 0.648949 |
cbdfc69c246709470f47c025102f27d071b65862 | 1,830 | /*
* Copyright 2018-2021 Crown Copyright
*
* 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 uk.gov.gchq.palisade.service.data.service.authorisation;
import uk.gov.gchq.palisade.service.data.exception.ForbiddenException;
import uk.gov.gchq.palisade.service.data.model.AuthorisedDataRequest;
import uk.gov.gchq.palisade.service.data.model.DataRequest;
import java.util.concurrent.CompletableFuture;
/**
* The only function that the service controls outside of pluggable extensions is the authorisation
* of a data-request and gathering of rules that apply to this data access.
* These rules have been persisted by the Attribute-Masking Service and must be recalled here by some
* means.
*/
public interface AuthorisationService {
/**
* Request the trusted details about a client's request from persistence (what policies to apply, user details, etc).
*
* @param request the client's request for a leaf resource and their unique request token
* @return rules apply when accessing the data, returned as a {@link AuthorisedDataRequest} to pass to the
* data-reader and null if there is no data
* @throws ForbiddenException if there is no authorised data for the request
*/
CompletableFuture<AuthorisedDataRequest> authoriseRequest(final DataRequest request);
}
| 41.590909 | 121 | 0.761749 |
01f571166614ac0bb32380fb9f749cf13fa360ef | 1,455 | package dk.osaa.psaw.job;
import lombok.Value;
/**
* The constraints to obey when traversing, aka moving without the laser on.
*/
@Value
public class TraverseSettings {
boolean accurate;
boolean speedUnlimited;
boolean exitSpeedMandatory;
double maxSpeed;
/**
* Move as quickly as possible, but hit the target point accurately without optimization
*/
static final public TraverseSettings ACCURATE = new TraverseSettings(true, true, false, 0);
/**
* Move as quickly as possible, but don't generate a move if too little distance is covered
*/
static final public TraverseSettings FAST = new TraverseSettings(false, true, false, 0);
/**
* Creates constraints that sets a max speed for the move and allow the move to be optimized out if it's too short.
*
* @param maxSpeed The speed limit in mm/s
* @return The constraints constructed
*/
static public TraverseSettings atMaxSpeed(double maxSpeed) {
return new TraverseSettings(false, false, false, maxSpeed);
}
/**
* Creates constraints that sets a speed for the move that must be archived and allow the move to be optimized out if it's too short.
*
* @param maxSpeed The speed limit in mm/s
* @return The constraints constructed
*/
static public TraverseSettings hitExitSpeed(double maxSpeed) {
return new TraverseSettings(false, false, true, maxSpeed);
}
}
| 32.333333 | 137 | 0.694158 |
66dfade782e60b6750fb16627b0bc63d44128b0f | 458 | /*CopyrightHere*/
package repast.simphony.freezedry.wizard;
import repast.simphony.freezedry.FreezeDryedDataSource;
import repast.simphony.util.wizard.WizardOption;
public interface FreezeDryWizardOption extends WizardOption {
DataSourceBuilder createDataSourceBuilder(FreezeDryedDataSource oldDataSource);
ControllerActionBuilder<? extends FreezerControllerAction> createAction(
FreezeDryWizardModel model, DataSourceBuilder builder);
}
| 35.230769 | 81 | 0.838428 |
1fdcf8adbb5f6b10ef34874fe6bed9668e50a879 | 3,269 | package seedu.address.logic.parser.commands.inventory;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_QUANTITY;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import seedu.address.logic.commands.inventory.InventoryFindCommand;
import seedu.address.logic.parser.ArgumentMultimap;
import seedu.address.logic.parser.ArgumentTokenizer;
import seedu.address.logic.parser.ParserUtil;
import seedu.address.logic.parser.commands.Parser;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.ingredient.Ingredient;
import seedu.address.model.ingredient.IngredientNameContainsWordsPredicate;
import seedu.address.model.ingredient.IngredientQuantityLessThanEqualsPredicate;
public class InventoryFindCommandParser implements Parser<InventoryFindCommand> {
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns a FindCommand object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public InventoryFindCommand parse(String userInput) throws ParseException {
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(userInput, PREFIX_NAME, PREFIX_QUANTITY);
boolean namePresent = ParserUtil.arePrefixesPresent(argMultimap, PREFIX_NAME);
boolean quantityPresent = ParserUtil.arePrefixesPresent(argMultimap, PREFIX_QUANTITY);
if (!namePresent && !quantityPresent) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
InventoryFindCommand.MESSAGE_USAGE));
}
List<Predicate<Ingredient>> predicates = getPredicates(argMultimap);
return new InventoryFindCommand(predicates);
}
private List<Predicate<Ingredient>> getPredicates(ArgumentMultimap argMultimap) throws ParseException {
List<Predicate<Ingredient>> predicates = new ArrayList<>();
Optional<String> nameArgs = argMultimap.getValue(PREFIX_NAME);
Optional<String> quantityArg = argMultimap.getValue(PREFIX_QUANTITY);
if (nameArgs.isPresent()) {
List<String> keywords;
try {
keywords = ParserUtil.parseKeywords(nameArgs.get());
} catch (ParseException pe) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
InventoryFindCommand.MESSAGE_USAGE), pe);
}
predicates.add(new IngredientNameContainsWordsPredicate(keywords));
}
if (quantityArg.isPresent()) {
int quantity;
try {
quantity = ParserUtil.parseNonNegativeInt(quantityArg.get());
} catch (ParseException pe) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
InventoryFindCommand.MESSAGE_USAGE), pe);
}
predicates.add(new IngredientQuantityLessThanEqualsPredicate(quantity));
}
return predicates;
}
}
| 42.454545 | 107 | 0.720404 |
651c4cd35f2de45219d30326cf6dc9507e3fa377 | 3,239 | package com.dianping.cat.consumer.matrix.model.entity;
import static com.dianping.cat.consumer.matrix.model.Constants.ATTR_NAME;
import static com.dianping.cat.consumer.matrix.model.Constants.ENTITY_MATRIX;
import java.util.LinkedHashMap;
import java.util.Map;
import com.dianping.cat.consumer.matrix.model.BaseEntity;
import com.dianping.cat.consumer.matrix.model.IVisitor;
public class Matrix extends BaseEntity<Matrix> {
private String m_type;
private String m_name;
private int m_count;
private long m_totalTime;
private String m_url;
private Map<String, Ratio> m_ratios = new LinkedHashMap<String, Ratio>();
public Matrix() {
}
public Matrix(String name) {
m_name = name;
}
@Override
public void accept(IVisitor visitor) {
visitor.visitMatrix(this);
}
public Matrix addRatio(Ratio ratio) {
m_ratios.put(ratio.getType(), ratio);
return this;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Matrix) {
Matrix _o = (Matrix) obj;
if (!equals(getName(), _o.getName())) {
return false;
}
return true;
}
return false;
}
public Ratio findRatio(String type) {
return m_ratios.get(type);
}
public Ratio findOrCreateRatio(String type) {
Ratio ratio = m_ratios.get(type);
if (ratio == null) {
synchronized (m_ratios) {
ratio = m_ratios.get(type);
if (ratio == null) {
ratio = new Ratio(type);
m_ratios.put(type, ratio);
}
}
}
return ratio;
}
public int getCount() {
return m_count;
}
public String getName() {
return m_name;
}
public Map<String, Ratio> getRatios() {
return m_ratios;
}
public long getTotalTime() {
return m_totalTime;
}
public String getType() {
return m_type;
}
public String getUrl() {
return m_url;
}
@Override
public int hashCode() {
int hash = 0;
hash = hash * 31 + (m_name == null ? 0 : m_name.hashCode());
return hash;
}
public Matrix incCount() {
m_count++;
return this;
}
public Matrix incCount(int count) {
m_count += count;
return this;
}
@Override
public void mergeAttributes(Matrix other) {
assertAttributeEquals(other, ENTITY_MATRIX, ATTR_NAME, m_name, other.getName());
if (other.getType() != null) {
m_type = other.getType();
}
m_count = other.getCount();
m_totalTime = other.getTotalTime();
if (other.getUrl() != null) {
m_url = other.getUrl();
}
}
public Ratio removeRatio(String type) {
return m_ratios.remove(type);
}
public Matrix setCount(int count) {
m_count = count;
return this;
}
public Matrix setName(String name) {
m_name = name;
return this;
}
public Matrix setTotalTime(long totalTime) {
m_totalTime = totalTime;
return this;
}
public Matrix setType(String type) {
m_type = type;
return this;
}
public Matrix setUrl(String url) {
m_url = url;
return this;
}
}
| 19.279762 | 86 | 0.600494 |
75056ace5606ad7527bd61e99f1dcb4b32845591 | 355 | /**
* generated by Xtext 2.16.0
*/
package in.handyman.validation;
import in.handyman.validation.AbstractDslValidator;
/**
* This class contains custom validation rules.
*
* See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#validation
*/
@SuppressWarnings("all")
public class DslValidator extends AbstractDslValidator {
}
| 22.1875 | 87 | 0.769014 |
3b4fab564ebb07e45526b047585ac4818ee04ad8 | 10,247 | /*
* $Id$
*
* $Log$
* Revision 1.1 2008/04/04 18:21:04 cvs
* Added legacy code to repository
*
* Revision 1.6 2008/02/10 20:17:33 mmaloney
* dev
*
* Revision 1.2 2008/02/01 15:20:40 cvs
* modified files for internationalization
*
* Revision 1.5 2006/05/11 18:26:42 mmaloney
* dev
*
* Revision 1.4 2004/12/21 14:46:04 mjmaloney
* Added javadocs
*
* Revision 1.3 2004/04/20 20:08:18 mjmaloney
* Working reference list editor, required several mods to SQL code.
*
* Revision 1.2 2004/04/12 21:30:32 mjmaloney
* dev
*
*/
package decodes.rledit;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ResourceBundle;
import decodes.db.*;
import ilex.util.*;
/**
DTEDialog is a pop-up in which the user edits a single data-type-equivalence
entry. It's used when the user hits the Add or Edit button. on the DTE panel.
*/
public class DTEDialog extends JDialog
{
private static ResourceBundle genericLabels =
RefListEditor.getGenericLabels();
private static ResourceBundle labels = RefListEditor.getLabels();
private JPanel panel1 = new JPanel();
private BorderLayout borderLayout1 = new BorderLayout();
private JPanel jPanel1 = new JPanel();
private FlowLayout flowLayout1 = new FlowLayout();
private JLabel jLabel1 = new JLabel();
private JPanel jPanel2 = new JPanel();
private JButton okButton = new JButton();
private FlowLayout flowLayout2 = new FlowLayout();
private JButton cancelButton = new JButton();
private JPanel jPanel3 = new JPanel();
private JLabel stdLabel[] = new JLabel[5];
private JTextField dtField[] = new JTextField[5];
private GridBagLayout gridBagLayout1 = new GridBagLayout();
private boolean _wasChanged = false;
private int numstds = 0;
private DTEquivTableModel myModel = null;
private String origCodes[];
private int rowNum = -1;
/**
* Constructor.
* @param frame the owner
* @param title the dialog title
* @param modal true if modal
*/
public DTEDialog(Frame frame, String title, boolean modal)
{
super(frame, title, modal);
stdLabel[0] = new JLabel();
stdLabel[1] = new JLabel();
stdLabel[2] = new JLabel();
stdLabel[3] = new JLabel();
stdLabel[4] = new JLabel();
dtField[0] = new JTextField();
dtField[1] = new JTextField();
dtField[2] = new JTextField();
dtField[3] = new JTextField();
dtField[4] = new JTextField();
try {
jbInit();
pack();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* Constructor.
* @param parent the owner
*/
public DTEDialog(Frame parent)
{
this(parent, "", true);
}
/**
* No args constructor for JBuilder.
*/
public DTEDialog()
{
this(null, "", true);
}
/**
* Fills the dialog according to the values found in the specified row
* of the model.
* @param model the model
* @param row the selected row
*/
public void fillValues(DTEquivTableModel model, int row)
{
myModel = model;
rowNum = row;
numstds = myModel.getColumnCount();
if (numstds > stdLabel.length)
numstds = stdLabel.length;
int i = 0;
origCodes = new String[numstds];
for(; i<numstds; i++)
{
stdLabel[i].setText(myModel.getColumnName(i) + ":");
stdLabel[i].setVisible(true);
dtField[i].setVisible(true);
if (row != -1)
dtField[i].setText(origCodes[i] = (String)myModel.getValueAt(row, i));
else
dtField[i].setText(origCodes[i] = "");
}
for(; i<stdLabel.length; i++)
{
stdLabel[i].setVisible(false);
dtField[i].setVisible(false);
}
}
private void jbInit() throws Exception
{
panel1.setLayout(borderLayout1);
this.setModal(true);
this.setTitle(labels.getString("DTEDialog.dataTypeEquiv"));
jPanel1.setLayout(flowLayout1);
flowLayout1.setVgap(10);
jLabel1.setText(labels.getString("DTEDialog.dataTypesEquiv"));
// okButton.setMinimumSize(new Dimension(80, 23));
// okButton.setPreferredSize(new Dimension(80, 23));
okButton.setText(genericLabels.getString("OK"));
okButton.addActionListener(new DTEDialog_okButton_actionAdapter(this));
jPanel2.setLayout(flowLayout2);
flowLayout2.setHgap(20);
flowLayout2.setVgap(10);
// cancelButton.setMinimumSize(new Dimension(80, 23));
// cancelButton.setPreferredSize(new Dimension(80, 23));
cancelButton.setText(genericLabels.getString("cancel"));
cancelButton.addActionListener(new DTEDialog_cancelButton_actionAdapter(this));
jPanel3.setLayout(gridBagLayout1);
stdLabel[0].setText(labels.getString("DTEDialog.standardOne"));
stdLabel[1].setText(labels.getString("DTEDialog.standardTwo"));
stdLabel[2].setText(labels.getString("DTEDialog.standardThree"));
stdLabel[3].setText(labels.getString("DTEDialog.standardFour"));
stdLabel[4].setText(labels.getString("DTEDialog.standardFive"));
dtField[0].setMinimumSize(new Dimension(100, 20));
dtField[0].setPreferredSize(new Dimension(100, 20));
dtField[0].setText("");
dtField[1].setText("");
dtField[2].setText("");
dtField[3].setText("");
dtField[4].setText("");
getContentPane().add(panel1);
panel1.add(jPanel1, BorderLayout.NORTH);
jPanel1.add(jLabel1, null);
panel1.add(jPanel2, BorderLayout.SOUTH);
jPanel2.add(okButton, null);
jPanel2.add(cancelButton, null);
panel1.add(jPanel3, BorderLayout.CENTER);
jPanel3.add(stdLabel[0], new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(10, 15, 5, 3), 0, 0));
jPanel3.add(stdLabel[1], new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 15, 5, 3), 0, 0));
jPanel3.add(stdLabel[2], new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 15, 5, 3), 0, 0));
jPanel3.add(stdLabel[3], new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 15, 5, 3), 0, 0));
jPanel3.add(stdLabel[4], new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0
,GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 15, 5, 3), 0, 0));
jPanel3.add(dtField[0], new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(10, 0, 5, 100), 0, 0));
jPanel3.add(dtField[1], new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 100), 0, 0));
jPanel3.add(dtField[2], new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 100), 0, 0));
jPanel3.add(dtField[3], new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 100), 0, 0));
jPanel3.add(dtField[4], new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 10, 100), 0, 0));
}
/**
* Called when OK button is pressed.
* @param e ignored.
*/
void okButton_actionPerformed(ActionEvent e)
{
DataType dataTypes[] = new DataType[numstds];
for(int i=0; i<numstds; i++) dataTypes[i] = null;
// At least 2 dt's must be defined.
// ALL DTs in this dialog must be either unchanged or new.
// No clashes allowed.
int numDefined = 0;
DataTypeSet dts = Database.getDb().dataTypeSet;
for(int i=0; i<numstds; i++)
{
String code = dtField[i].getText().trim();
if (code.length() > 0)
{
numDefined++;
String std = myModel.getColumnName(i);
// Make sure this std/code isn't already in another equivalence
// ring!
if (myModel.exists(std, code, rowNum))
{
showError(LoadResourceBundle.sprintf(
labels.getString("DTEDialog.dataTypeExistsErr"),
std,code));
return;
}
// This will create the data type record if necessary.
dataTypes[i] = DataType.getDataType(std, code);
}
}
/*
If user changes a code, might have to de-assert the old equivalence.
*/
for(int i=0; i<numstds; i++)
{
String std = myModel.getColumnName(i);
String orig = origCodes[i];
String now = dtField[i].getText().trim();
if (orig.length() > 0) // There was a DT in this column before?
{
if (!now.equals(orig))
{
// It was either modified or blanked.
// Remove old data type.
DataType odt = dts.get(std, orig);
if (odt != null)
{
Logger.instance().debug3(
"De-asserting equivalence of " + odt.toString());
odt.deAssertEquivalence();
}
}
}
}
if (numDefined == 0)
return; // do nothing.
else if (numDefined == 1)
{
showError(labels.getString("DTEDialog.assertEquvErr"));
return;
}
// Now assert the equivalencies.
DataType lastDT = null;
for(DataType dt : dataTypes)
{
if (dt != null)
{
if (lastDT != null)
{
Logger.instance().debug3(
"Asserting equivalence of " + dt.toString() + " and "
+ lastDT.toString());
lastDT.assertEquivalence(dt);
}
lastDT = dt;
}
}
_wasChanged = true;
closeDlg();
}
/**
* Called when Cancel button is pressed.
* @param e ignored.
*/
void cancelButton_actionPerformed(ActionEvent e)
{
_wasChanged = false;
closeDlg();
}
/**
* @return true if data in the dialog was changed.
*/
public boolean wasChanged() { return _wasChanged; }
/** Closes the dialog. */
void closeDlg()
{
setVisible(false);
dispose();
}
/**
Convenience method to display an error in a JOptionPane.
@param msg the error message.
*/
private void showError(String msg)
{
System.err.println(msg);
JOptionPane.showMessageDialog(this,
AsciiUtil.wrapString(msg, 60), "Error!", JOptionPane.ERROR_MESSAGE);
}
}
class DTEDialog_okButton_actionAdapter implements java.awt.event.ActionListener {
DTEDialog adaptee;
DTEDialog_okButton_actionAdapter(DTEDialog adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.okButton_actionPerformed(e);
}
}
class DTEDialog_cancelButton_actionAdapter implements java.awt.event.ActionListener {
DTEDialog adaptee;
DTEDialog_cancelButton_actionAdapter(DTEDialog adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.cancelButton_actionPerformed(e);
}
}
| 29.193732 | 102 | 0.6842 |
ee2eaeb50e4f230326daf61a65813f86b6f7f529 | 118 | package mineCord.world;
public abstract class ChunkGenerator
{
protected abstract void generate(Chunk chunk);
} | 19.666667 | 48 | 0.779661 |
a7856b7755ca8b317573ea74ef03357bb619adc4 | 824 | package test.pivotal.pal.trackerapi;
import io.pivotal.pal.tracker.PalTrackerApplication;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@SpringBootTest(classes = PalTrackerApplication.class, webEnvironment = RANDOM_PORT)
public class WelcomeApiTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello from test");
}
}
| 34.333333 | 94 | 0.793689 |
94690d59b8c23be4fad11755cdad09c42a27e847 | 5,828 | package ui;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.mxgraph.swing.mxGraphComponent;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JScrollBar;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JScrollPane;
@SuppressWarnings("serial")
public class View extends JFrame implements Observer {
private JPanel contentPane;
private JButton btnImportarGrafo;
private JButton btnOrdenacaoTopologica;
private JButton btnDijkstra;
private JButton btnMST;
private JButton btnProximo;
private JButton btnUltimo;
private JTextField textField_NodoInicial;
private JTextField textField_NodoFinal;
private javax.swing.filechooser.FileFilter filter;
private JLabel lblNodoInicial;
private JLabel lblNodoFinal;
private JButton btnExecutar;
private mxGraphComponent comp;
/**
* Create the frame.
*/
public View() {
filter = new javax.swing.filechooser.FileFilter() {
@Override
public boolean accept(File arg0) {
if (arg0.getName().endsWith(".csv"))
return true;
return false;
}
@Override
public String getDescription() {
return "Arquivo texto CSV formatado com separador ';'";
}
};
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 672, 478);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnImportarGrafo = new JButton("Importar Grafo");
btnImportarGrafo.setBackground(new Color(204, 204, 204));
btnImportarGrafo.setBounds(10, 11, 124, 23);
contentPane.add(btnImportarGrafo);
btnOrdenacaoTopologica = new JButton("Orden. Topológica");
btnOrdenacaoTopologica.setBackground(new Color(204, 204, 204));
btnOrdenacaoTopologica.setBounds(312, 11, 160, 23);
contentPane.add(btnOrdenacaoTopologica);
btnDijkstra = new JButton("Dijkstra");
btnDijkstra.setBackground(new Color(204, 204, 204));
btnDijkstra.setBounds(482, 11, 86, 23);
contentPane.add(btnDijkstra);
btnMST = new JButton("MST");
btnMST.setBackground(new Color(204, 204, 204));
btnMST.setBounds(578, 11, 68, 23);
contentPane.add(btnMST);
btnProximo = new JButton("Próximo");
btnProximo.setBackground(new Color(204, 204, 204));
btnProximo.setBounds(10, 405, 89, 23);
contentPane.add(btnProximo);
btnUltimo = new JButton("Último");
btnUltimo.setBackground(new Color(204, 204, 204));
btnUltimo.setBounds(109, 405, 89, 23);
contentPane.add(btnUltimo);
lblNodoInicial = new JLabel("Nodo inicial:");
lblNodoInicial.setBounds(464, 73, 78, 14);
contentPane.add(lblNodoInicial);
lblNodoFinal = new JLabel("Nodo final:");
lblNodoFinal.setBounds(464, 101, 78, 14);
contentPane.add(lblNodoFinal);
textField_NodoInicial = new JTextField();
textField_NodoInicial.setBounds(560, 70, 86, 20);
contentPane.add(textField_NodoInicial);
textField_NodoInicial.setColumns(10);
textField_NodoFinal = new JTextField();
textField_NodoFinal.setBounds(560, 98, 86, 20);
contentPane.add(textField_NodoFinal);
textField_NodoFinal.setColumns(10);
btnExecutar = new JButton("Executar");
btnExecutar.setBackground(new Color(51, 102, 255));
btnExecutar.setBounds(496, 123, 89, 23);
contentPane.add(btnExecutar);
this.exibirBotoes_Algoritimos(false);
this.exibirBotoes_ProximoUltimo(false);
this.exibirComponentes_Dijkstra(false);
}
public void associaController_btnImportarGrafo(ActionListener c) {
btnImportarGrafo.addActionListener(c);
}
public void associaController_btnOrdenacaoTopologica(ActionListener c) {
btnOrdenacaoTopologica.addActionListener(c);
}
public void associaController_btnDijkstra(ActionListener c) {
btnDijkstra.addActionListener(c);
}
public void associaController_btnMST(ActionListener c) {
btnMST.addActionListener(c);
}
public void associaController_btnProximo(ActionListener c) {
btnProximo.addActionListener(c);
}
public void associaController_btnFinal(ActionListener c) {
btnUltimo.addActionListener(c);
}
public void associaController_btnExecutar(ActionListener c) {
btnExecutar.addActionListener(c);
}
public File fileChooserDialog() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);
fileChooser.setDialogTitle("Abra um arquivo texto em forma de grafo");
fileChooser.showOpenDialog(this);
return fileChooser.getSelectedFile();
}
public void exibirBotoes_ProximoUltimo(boolean b) {
this.btnProximo.setVisible(b);
this.btnUltimo.setVisible(b);
}
public void exibirBotoes_Algoritimos(boolean b) {
this.btnDijkstra.setVisible(b);
this.btnMST.setVisible(b);
this.btnOrdenacaoTopologica.setVisible(b);
}
public void exibirComponentes_Dijkstra(boolean b) {
this.lblNodoFinal.setVisible(b);
this.lblNodoInicial.setVisible(b);
this.textField_NodoFinal.setVisible(b);
this.textField_NodoInicial.setVisible(b);
this.btnExecutar.setVisible(b);
}
public String getText_NodeInicial() {
return this.textField_NodoInicial.getText();
}
public String getText_NodeFinal() {
return this.textField_NodoFinal.getText();
}
public void updateComponent(mxGraphComponent comp) {
if (this.comp != null)
contentPane.remove(this.comp);
comp.setBounds(20, 65, 400, 300);
comp.setVisible(true);
this.comp = comp;
contentPane.add(this.comp);
}
@Override
public void update(Observable arg0, Object arg1) {
Model model = (Model) arg0;
this.updateComponent(model.getGrafoComponent());
contentPane.updateUI();
}
}
| 27.752381 | 73 | 0.756692 |
37d0d22ae2e210c1b98e061de702679a323f2bd4 | 1,122 | package org.aicoder.bizdelegate;
import java.util.List;
import org.archcorner.chartreuse.dal.dao.LedgerDAO;
import org.archcorner.chartreuse.pojo.Ledger;
public class LedgerBusinessDelegate{
private LedgerDAO ledgerDAO ;
public int getHighestId()
{
ledgerDAO = new LedgerDAO();
int id=ledgerDAO.getHighestId();
return id;
}
public void insertLedger(Ledger ledger)
{
ledgerDAO = new LedgerDAO();
ledgerDAO.insertLedger(ledger);
}
public void updateLedger(Ledger ledger)
{
ledgerDAO = new LedgerDAO();
ledgerDAO.updateLedger(ledger);
}
public void deleteLedger(Ledger ledger)
{
ledgerDAO = new LedgerDAO();
ledgerDAO.deleteLedger(ledger);
}
public Ledger getLedgerById(int ledgerId)
{
ledgerDAO = new LedgerDAO();
Ledger ledger= ledgerDAO.getLedgerById(ledgerId);
return ledger;
}
public Ledger getLedger(String ledgerName)
{
ledgerDAO = new LedgerDAO();
Ledger ledger= ledgerDAO.getLedger(ledgerName);
return ledger;
}
public List<Ledger> getAll( )
{
ledgerDAO = new LedgerDAO();
List<Ledger> ledgers = ledgerDAO.getLedgers( );
return ledgers;
}
}
| 19.016949 | 51 | 0.73262 |
3270960983ce6b1bd1d43e93b4d3537a875cac39 | 9,840 | // Copyright (c) 2014-2019 K Team. All Rights Reserved.
package org.kframework.krun;
import com.beust.jcommander.DynamicParameter;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.ParametersDelegate;
import com.google.inject.Inject;
import org.apache.commons.lang3.tuple.Pair;
import org.kframework.main.GlobalOptions;
import org.kframework.rewriter.SearchType;
import org.kframework.unparser.OutputModes;
import org.kframework.unparser.PrintOptions;
import org.kframework.utils.OS;
import org.kframework.utils.errorsystem.KEMException;
import org.kframework.utils.file.FileUtil;
import org.kframework.utils.inject.RequestScoped;
import org.kframework.utils.options.BackendOptions;
import org.kframework.utils.options.BaseEnumConverter;
import org.kframework.utils.options.DefinitionLoadingOptions;
import org.kframework.utils.options.OnOffConverter;
import org.kframework.utils.options.SMTOptions;
import org.kframework.utils.options.StringListConverter;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestScoped
public final class KRunOptions {
@ParametersDelegate
public transient GlobalOptions global = new GlobalOptions();
@ParametersDelegate
public ConfigurationCreationOptions configurationCreation = new ConfigurationCreationOptions();
@ParametersDelegate
public BackendOptions backend = new BackendOptions();
public static final class ConfigurationCreationOptions {
public ConfigurationCreationOptions() {}
//TODO(dwightguth): remove in Guice 4.0
@Inject
public ConfigurationCreationOptions(Void v) {}
@Parameter(description="<file>")
private List<String> parameters;
public String pgm() {
if (parameters == null || parameters.size() == 0) {
return null;
}
if (parameters.size() > 1) {
throw KEMException.criticalError("You can only specify $PGM on the command line itself");
}
return parameters.get(0);
}
@ParametersDelegate
public DefinitionLoadingOptions definitionLoading = new DefinitionLoadingOptions();
@Parameter(names={"--parser"}, description="Command used to parse programs. Default is \"kast\"")
public String parser;
public String parser(String mainModuleName, FileUtil files) {
String kastBinary = getKast(files);
if (parser == null) {
if (term()) {
return kastBinary + " -m " + mainModuleName;
} else {
return kastBinary;
}
} else {
return parser;
}
}
@DynamicParameter(names={"--config-parser", "-p"}, description="Command used to parse " +
"configuration variables. Default is \"kast --parser ground -e\". See description of " +
"--parser. For example, -pPGM=\"kast\" specifies that the configuration variable $PGM " +
"should be parsed with the command \"kast\".")
private Map<String, String> configVarParsers = new HashMap<>();
@DynamicParameter(names={"--config-var", "-c"}, description="Specify values for variables in the configuration. " +
"For example `-cVAR=value`. " +
"To read value from file, combine this option with `-p`. For example, if value is already parsed: " +
"`-pVAR=cat -cVAR=file`. " +
"If it is not parsed: `-pVAR=\"kast -s SORT\" -cVAR=file`. See `kast --help` for more details.")
private Map<String, String> configVars = new HashMap<>();
public Map<String, Pair<String, String>> configVars(String mainModuleName, FileUtil files) {
String kastBinary = getKast(files);
Map<String, Pair<String, String>> result = new HashMap<>();
for (Map.Entry<String, String> entry : configVars.entrySet()) {
String cfgParser = kastBinary + " -m " + mainModuleName + " -e";
if (configVarParsers.get(entry.getKey()) != null) {
cfgParser = configVarParsers.get(entry.getKey());
}
result.put(entry.getKey(), Pair.of(entry.getValue(), cfgParser));
}
if (!term() && pgm() != null) {
if (configVars.containsKey("PGM")) {
throw KEMException.criticalError("Cannot specify both -cPGM and a program to parse.");
}
result.put("PGM", Pair.of(pgm(), parser(mainModuleName, files)));
}
if (configVars.containsKey("STDIN") || configVars.containsKey("IO")) {
throw KEMException.criticalError("Cannot specify -cSTDIN or -cIO which are reserved for the builtin K-IO module.");
}
return result;
}
@Parameter(names="--term", description="Input argument will be parsed with the specified parser and used as the sole input to krun.")
private boolean term = false;
public boolean term() {
if (term && configVars.size() > 0) {
throw KEMException.criticalError("You cannot specify both the term and the configuration variables.");
}
if (term && pgm() == null) {
throw KEMException.criticalError("You must specify something to parse with the --term option.");
}
return term;
}
}
private static String getKast(FileUtil files) {
String binary = "kast";
return files.resolveKBase("bin/" + binary).getAbsolutePath();
}
@Parameter(names="--io", description="Use real IO when running the definition. Defaults to true.", arity=1,
converter=OnOffConverter.class)
private Boolean io;
public boolean io() {
if (io != null && io == true && search()) {
throw KEMException.criticalError("You cannot specify both --io on and --search");
}
if (search()) {
return false;
}
if (io == null) {
return true;
}
return io;
}
@ParametersDelegate
public PrintOptions print = new PrintOptions();
@Parameter(names="--search", description="In conjunction with it you can specify 3 options that are optional: pattern (the pattern used for search), bound (the number of desired solutions) and depth (the maximum depth of the search).")
public boolean search = false;
@Parameter(names="--search-final", description="Same as --search but only return final states, even if --depth is provided.")
private boolean searchFinal = false;
@Parameter(names="--search-all", description="Same as --search but return all matching states, even if --depth is not provided.")
private boolean searchAll = false;
@Parameter(names="--search-one-step", description="Same as --search but search only one transition step.")
private boolean searchOneStep = false;
@Parameter(names="--search-one-or-more-steps", description="Same as --search-all but exclude initial state, even if it matches.")
private boolean searchOneOrMoreSteps = false;
public boolean search() {
return search || searchFinal || searchAll || searchOneStep || searchOneOrMoreSteps;
}
public SearchType searchType() {
if (search) {
if (searchFinal || searchAll || searchOneStep || searchOneOrMoreSteps) {
throw KEMException.criticalError("You can specify only one type of search.");
}
if (depth != null) {
return SearchType.STAR;
}
return SearchType.FINAL;
} else if (searchFinal) {
if (searchAll || searchOneStep || searchOneOrMoreSteps) {
throw KEMException.criticalError("You can specify only one type of search.");
}
return SearchType.FINAL;
} else if (searchAll) {
if (searchOneStep || searchOneOrMoreSteps) {
throw KEMException.criticalError("You can specify only one type of search.");
}
return SearchType.STAR;
} else if (searchOneStep) {
if (searchOneOrMoreSteps) {
throw KEMException.criticalError("You can specify only one type of search.");
}
return SearchType.ONE;
} else if (searchOneOrMoreSteps) {
return SearchType.PLUS;
} else {
return null;
}
}
@Parameter(names="--pattern", description="Specify a term and/or side condition that the result of execution or search must match in order to succeed. Return the resulting matches as a list of substitutions. In conjunction with it you can specify other 2 options that are optional: bound (the number of desired solutions) and depth (the maximum depth of the search).")
public String pattern;
@Parameter(names="--bound", description="The number of desired solutions for search.")
public Integer bound;
@Parameter(names="--depth", description="The maximum number of computational steps to execute or search the definition for.")
public Integer depth;
@Parameter(names="--statistics", description="Print rewrite engine statistics.", arity=1,
converter=OnOffConverter.class)
public boolean statistics = false;
@Parameter(names="--debugger", description="Run an execution in debug mode.")
public boolean debugger = false;
@ParametersDelegate
public SMTOptions smt = new SMTOptions();
@Parameter(names="--profile", description="Run krun multiple times to gather better performance metrics.")
public int profile = 1;
}
| 42.969432 | 372 | 0.63811 |
6f0999999b10440365b8dce7f8dc46d61e505b3b | 713 | package org.artur.masterdetail.data;
import java.util.List;
import java.util.Optional;
public abstract class CrudEndpointWithService<T, ID> implements CrudEndpoint<T, ID> {
protected abstract CrudService<T, ID> getService();
@Override
public List<T> list(int offset, int limit) {
return getService().list(offset, limit);
}
@Override
public Optional<T> get(ID id) {
return getService().get(id);
}
@Override
public T update(T entity) {
return getService().update(entity);
}
@Override
public void delete(ID id) {
getService().delete(id);
}
@Override
public int count() {
return getService().count();
}
} | 20.371429 | 85 | 0.629734 |
9419a09b4b52cb1afaec7d00f7c2f08966fbf1a6 | 1,832 | /*
* Copyright 2017 Prasenjit Purohit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.prasenjit.crypto.impl;
import org.junit.Test;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by prase on 13-06-2017.
*/
public class PBEEncryptorTest {
@Test
public void process() throws Exception {
String data = "My precious data";
PBEEncryptor encryptor = new PBEEncryptor("password".toCharArray());
String encrypt = encryptor.encrypt(data);
String decrypt = encryptor.decrypt(encrypt);
assertEquals(data, decrypt);
}
@Test
public void wrap() throws Exception {
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
PBEEncryptor encryptor = new PBEEncryptor("password".toCharArray());
String encrypt = encryptor.wrapKey(secretKey);
Key decrypted = encryptor.unwrapKey(encrypt, "AES", Cipher.SECRET_KEY);
assertEquals(decrypted.getAlgorithm(), secretKey.getAlgorithm());
assertTrue(Arrays.equals(decrypted.getEncoded(), secretKey.getEncoded()));
}
} | 32.140351 | 82 | 0.706332 |
ac3f26716f5b74eb15656e9337315cbb2998f6ff | 926 | /*
*
* * Copyright 2020 PPI AG (Hamburg, Germany)
* * This program is made available under the terms of the MIT License.
*
*/
package de.ppi.deepsampler.examples.helloworld;
import javax.inject.Inject;
/**
* An example for a Service that would give access to person related data.
* This Service is used to create an indirection between {@link GreetingService} and {@link PersonDaoImpl} to simulate
* a bigger compound and to demonstrate how DeepSampler is able to stub iobjects that are not directly accessible
* by the object that is under test.
*/
public class PersonService {
@Inject
private PersonDao personDao;
/**
* Loads a person using the personId and retrieves the name of the person.
* @param personId The id of the person
* @return The name of the person
*/
public String getName(int personId) {
return personDao.loadPerson(personId).getName();
}
}
| 28.060606 | 118 | 0.709503 |
1157acf095b994dfae3563ca7f88315783efc4e7 | 1,025 | package thingverse.common.config;
import com.thingverse.common.env.health.EnvironmentHealthListener;
import com.thingverse.common.env.health.EnvironmentHealthListenerImpl;
import com.thingverse.common.log.DeferredLogActivator;
import com.thingverse.common.log.DeferredLogActivatorImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(ThingverseBaseProperties.class)
public class ThingverseCommonAutoConfiguration {
@Bean
DeferredLogActivator deferredLogActivator(ApplicationContext context) {
return new DeferredLogActivatorImpl(context);
}
@Bean
EnvironmentHealthListener environmentHealthListener(ApplicationContext context, ThingverseBaseProperties properties) {
return new EnvironmentHealthListenerImpl(context, properties);
}
}
| 39.423077 | 122 | 0.843902 |
c0eade7c09e03473488fb7eb41ed94c79ac3b32d | 1,668 | package hsoft;
import com.hsoft.codingtest.DataProvider;
import com.hsoft.codingtest.DataProviderFactory;
import com.hsoft.codingtest.PricingDataListener;
import com.hsoft.codingtest.impl.TestDataProvider;
import hsoft.services.DataListenerService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;
import static org.mockito.Mockito.doAnswer;
@ExtendWith(MockitoExtension.class)
@SuppressWarnings("unchecked")
public class FairValueTest {
@Spy
private DataProvider provider = DataProviderFactory.getDataProvider();
@InjectMocks
private DataListenerService handler = new DataListenerService();
private final String ISIN_TEST = "ISIN_TEST";
@Test
void shouldUpdateFairValue() {
doAnswer((Answer<Object>) a -> {
Field field = TestDataProvider.class.getDeclaredField("pricingDataListeners");
field.setAccessible(true);
List<PricingDataListener> listeners = (List<PricingDataListener>) field.get(provider);
listeners.get(0).fairValueChanged(ISIN_TEST, 66D);
return null;
}).when(provider).listen();
handler.listen();
// Verify fairValue data
Assertions.assertTrue(handler.getFairValues().containsKey(ISIN_TEST));
Assertions.assertEquals(0, BigDecimal.valueOf(66).compareTo(handler.getFairValues().get(ISIN_TEST)));
}
} | 32.705882 | 109 | 0.747002 |
8954b02d033fcba76630758ac350bb01bbef114f | 395 | public class S0504Base7 {
public String convertToBase7(int num) {
if (num < 0) {
return "-" + convertToBase7(-num);
}
StringBuilder res = new StringBuilder();
while (num >= 7) {
res.insert(0, String.valueOf(num%7));
num = num/7;
}
res.insert(0, String.valueOf(num));
return res.toString();
}
}
| 24.6875 | 49 | 0.506329 |
4946cb865311602617b755699a29d721bacea6ad | 1,247 | package sample;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class ErrorsController {
@FXML
private Text errortext;
@FXML
private Button okbutton;
public void display(String message) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("errors.fxml"));
Parent child3 = loader.load();
Stage stage = new Stage();
stage.setTitle("Error");
stage.setScene(new Scene(child3));
stage.initModality(Modality.APPLICATION_MODAL);
ErrorsController errorsController = loader.getController();
errorsController.errortext.setText(message);
errorsController.okbutton.setOnAction(actionEvent -> stage.close());
stage.getIcons().add(new Image(getClass().getResourceAsStream("software-license.png")));
stage.setResizable(false);
stage.showAndWait();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
| 31.974359 | 100 | 0.659182 |
234051894427ea1a0b4e8ce2c4ce8584118ad30b | 3,522 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ambari.logsearch.conf;
import org.apache.ambari.logsearch.config.api.LogSearchPropertyDescription;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import static org.apache.ambari.logsearch.common.LogSearchConstants.LOGSEARCH_PROPERTIES_FILE;
@Configuration
public class SolrServiceLogPropsConfig extends SolrConnectionPropsConfig {
@Value("${logsearch.solr.service.logs.collection:hadoop_logs}")
@LogSearchPropertyDescription(
name = "logsearch.solr.service.logs",
description = "Name of Log Search service log collection.",
examples = {"hadoop_logs"},
defaultValue = "hadoop_logs",
sources = {LOGSEARCH_PROPERTIES_FILE}
)
private String collection;
@Value("${logsearch.solr.service.logs.config.name:hadoop_logs}")
@LogSearchPropertyDescription(
name = "logsearch.solr.service.logs.config.name",
description = "Solr configuration name of the service log collection.",
examples = {"hadoop_logs"},
defaultValue = "hadoop_logs",
sources = {LOGSEARCH_PROPERTIES_FILE}
)
private String configName;
@Value("${logsearch.solr.service.logs.numshards:1}")
@LogSearchPropertyDescription(
name = "logsearch.solr.service.logs.numshards",
description = "Number of Solr shards for service log collection (bootstrapping).",
examples = {"2"},
defaultValue = "1",
sources = {LOGSEARCH_PROPERTIES_FILE}
)
private Integer numberOfShards;
@Value("${logsearch.solr.service.logs.replication.factor:1}")
@LogSearchPropertyDescription(
name = "logsearch.solr.service.logs.replication.factor",
description = "Solr replication factor for service log collection (bootstrapping).",
examples = {"2"},
defaultValue = "1",
sources = {LOGSEARCH_PROPERTIES_FILE}
)
private Integer replicationFactor;
@Override
public String getCollection() {
return collection;
}
@Override
public void setCollection(String collection) {
this.collection = collection;
}
@Override
public String getConfigName() {
return configName;
}
@Override
public void setConfigName(String configName) {
this.configName = configName;
}
@Override
public Integer getNumberOfShards() {
return numberOfShards;
}
@Override
public void setNumberOfShards(Integer numberOfShards) {
this.numberOfShards = numberOfShards;
}
@Override
public Integer getReplicationFactor() {
return replicationFactor;
}
@Override
public void setReplicationFactor(Integer replicationFactor) {
this.replicationFactor = replicationFactor;
}
@Override
public String getLogType() {
return "service";
}
}
| 30.626087 | 94 | 0.74276 |
fe757a62b881eb3d42fa79c712118206277ffa2e | 1,519 | package b.l.a.c.f.e;
import android.os.Parcel;
import android.os.Parcelable;
import b.l.a.c.b.a;
import java.util.ArrayList;
public final class zj implements Parcelable.Creator<yj> {
public final Object createFromParcel(Parcel parcel) {
int C0 = a.C0(parcel);
boolean z = false;
boolean z2 = false;
String str = null;
String str2 = null;
ql qlVar = null;
ArrayList<String> arrayList = null;
while (parcel.dataPosition() < C0) {
int readInt = parcel.readInt();
switch (65535 & readInt) {
case 2:
str = a.L(parcel, readInt);
break;
case 3:
z = a.n0(parcel, readInt);
break;
case 4:
str2 = a.L(parcel, readInt);
break;
case 5:
z2 = a.n0(parcel, readInt);
break;
case 6:
qlVar = (ql) a.K(parcel, readInt, ql.CREATOR);
break;
case 7:
arrayList = a.M(parcel, readInt);
break;
default:
a.z0(parcel, readInt);
break;
}
}
a.S(parcel, C0);
return new yj(str, z, str2, z2, qlVar, arrayList);
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i2) {
return new yj[i2];
}
}
| 29.784314 | 73 | 0.445688 |
93e295f74dfa02173631ade68be09c82370da277 | 12,928 | package com.telekom.m2m.cot.restsdk.measurement;
import com.telekom.m2m.cot.restsdk.CloudOfThingsPlatform;
import com.telekom.m2m.cot.restsdk.inventory.ManagedObject;
import com.telekom.m2m.cot.restsdk.util.ExtensibleObject;
import com.telekom.m2m.cot.restsdk.util.Filter;
import com.telekom.m2m.cot.restsdk.util.SampleTemperatureSensor;
import com.telekom.m2m.cot.restsdk.util.TestHelper;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Date;
/**
* Created by Patrick Steinert on 14.10.16.
*
* @author Patrick Steinert
*/
public class MeasurementApiCollectionIT {
private CloudOfThingsPlatform cotPlat = new CloudOfThingsPlatform(TestHelper.TEST_HOST, TestHelper.TEST_USERNAME, TestHelper.TEST_PASSWORD);
private ManagedObject testManagedObject;
private MeasurementApi measurementApi;
@BeforeMethod
public void setUp() {
testManagedObject = TestHelper.createRandomManagedObjectInPlatform(cotPlat, "fake_name");
measurementApi = cotPlat.getMeasurementApi();
}
@AfterMethod
public void tearDown() {
measurementApi.deleteMeasurements(Filter.build().bySource(testManagedObject.getId()));
TestHelper.deleteManagedObjectInPlatform(cotPlat, testManagedObject);
}
@Test
public void testMultipleMeasurements() throws Exception {
final Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date());
testMeasurement.setType("mytype");
measurementApi.createMeasurement(testMeasurement);
MeasurementCollection measurementCollection = measurementApi.getMeasurements(5);
Measurement[] measurements = measurementCollection.getMeasurements();
Assert.assertTrue(measurements.length > 0);
Measurement measurement = measurements[0];
Assert.assertTrue(measurement.getId() != null);
Assert.assertTrue(measurement.getId().length() > 0);
Assert.assertTrue(measurement.getTime() != null);
Assert.assertTrue(measurement.getTime().compareTo(new Date()) < 0);
Assert.assertTrue(measurement.getType() != null);
Assert.assertTrue(measurement.getType().length() > 0);
}
@Test
public void testMultipleMeasurementsWithPaging() throws Exception {
for (int i = 0; i < 6; i++) {
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date(new Date().getTime() - (i * 5000)));
testMeasurement.setType("mytype-" + i);
measurementApi.createMeasurement(testMeasurement);
}
MeasurementCollection measurementCollection = measurementApi.getMeasurements(Filter.build().bySource(testManagedObject.getId()), 5);
Measurement[] measurements = measurementCollection.getMeasurements();
Assert.assertEquals(measurements.length, 5);
Assert.assertTrue(measurementCollection.hasNext());
Assert.assertFalse(measurementCollection.hasPrevious());
measurementCollection.next();
measurements = measurementCollection.getMeasurements();
Assert.assertEquals(measurements.length, 1);
Assert.assertFalse(measurementCollection.hasNext());
Assert.assertTrue(measurementCollection.hasPrevious());
measurementCollection.previous();
measurements = measurementCollection.getMeasurements();
Assert.assertEquals(measurements.length, 5);
Assert.assertTrue(measurementCollection.hasNext());
Assert.assertFalse(measurementCollection.hasPrevious());
measurementCollection.setPageSize(10);
measurements = measurementCollection.getMeasurements();
Assert.assertEquals(measurements.length, 6);
Assert.assertFalse(measurementCollection.hasNext());
Assert.assertFalse(measurementCollection.hasPrevious());
}
@Test
public void testDeleteMultipleMeasurementsBySource() throws Exception {
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date());
testMeasurement.setType("mytype");
measurementApi.createMeasurement(testMeasurement);
//measurements = measurementApi.getMeasurementsBySource(testManagedObject.getId());
MeasurementCollection measurements = measurementApi.getMeasurements(Filter.build().bySource(testManagedObject.getId()), 5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 1);
measurementApi.deleteMeasurements(Filter.build().bySource(testManagedObject.getId()));
measurements = measurementApi.getMeasurements(Filter.build().bySource(testManagedObject.getId()), 5);
ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 0);
}
@Test
public void testMultipleMeasurementsBySource() throws Exception {
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date());
testMeasurement.setType("mytype");
measurementApi.createMeasurement(testMeasurement);
ManagedObject testManagedObject2 = TestHelper.createRandomManagedObjectInPlatform(cotPlat, "fake_name");
Measurement testMeasurement2 = new Measurement();
testMeasurement2.setSource(testManagedObject2);
testMeasurement2.setTime(new Date());
testMeasurement2.setType("mytype");
measurementApi.createMeasurement(testMeasurement2);
MeasurementCollection measurements = measurementApi.getMeasurements(5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertTrue(ms.length > 0);
boolean allMeasurementsFromSource = true;
for (Measurement m : ms) {
ExtensibleObject source = (ExtensibleObject) m.get("source");
if (!source.get("id").equals(testManagedObject.getId())) {
allMeasurementsFromSource = false;
}
}
Assert.assertFalse(allMeasurementsFromSource);
measurements = measurementApi.getMeasurements(Filter.build().bySource(testManagedObject.getId()), 5);
ms = measurements.getMeasurements();
Assert.assertTrue(ms.length > 0);
for (Measurement m : ms) {
ExtensibleObject source = (ExtensibleObject) m.get("source");
Assert.assertEquals(source.get("id"), testManagedObject.getId());
}
// cleanup
measurementApi.deleteMeasurements(Filter.build().bySource(testManagedObject2.getId()));
TestHelper.deleteManagedObjectInPlatform(cotPlat, testManagedObject2);
}
@Test
public void testMultipleMeasurementsByType() throws Exception {
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date());
testMeasurement.setType("mysuperspecialtype");
measurementApi.createMeasurement(testMeasurement);
Measurement testMeasurement2 = new Measurement();
testMeasurement2.setSource(testManagedObject);
testMeasurement2.setTime(new Date());
testMeasurement2.setType("mytype");
measurementApi.createMeasurement(testMeasurement2);
MeasurementCollection measurements = measurementApi.getMeasurements(5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertTrue(ms.length > 0);
boolean allMeasurementsFromSameType = true;
for (Measurement m : ms) {
if (!m.getType().equals(testManagedObject.getType())) {
allMeasurementsFromSameType = false;
}
}
Assert.assertFalse(allMeasurementsFromSameType);
measurements = measurementApi.getMeasurements(Filter.build().byType(testMeasurement.getType()), 5);
ms = measurements.getMeasurements();
Assert.assertTrue(ms.length > 0);
for (Measurement m : ms) {
Assert.assertEquals(m.getType(), testMeasurement.getType());
}
}
@Test
public void testMultipleMeasurementsByDate() throws Exception {
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date(new Date().getTime() - (1000 * 60)));
testMeasurement.setType("mysuperspecialtype");
measurementApi.createMeasurement(testMeasurement);
Date yesterday = new Date(new Date().getTime() - (1000 * 60 * 60 * 24));
MeasurementCollection measurements = measurementApi.getMeasurements(Filter.build().byDate(yesterday, new Date()), 5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertTrue(ms.length > 0);
Date beforeYesterday = new Date(new Date().getTime() - (1000 * 60 * 60 * 24) - 10);
measurements = measurementApi.getMeasurements(Filter.build().byDate(beforeYesterday, yesterday), 5);
ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 0);
}
@Test
public void testMultipleMeasurementsByDateAndBySource() throws Exception {
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date(new Date().getTime() - (1000 * 60)));
testMeasurement.setType("mysuperspecialtype");
measurementApi.createMeasurement(testMeasurement);
Date yesterday = new Date(new Date().getTime() - (1000 * 60 * 60 * 24));
MeasurementCollection measurements = measurementApi.getMeasurements(
Filter.build()
.byDate(yesterday, new Date())
.bySource(testManagedObject.getId()), 5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 1);
Date beforeYesterday = new Date(new Date().getTime() - (1000 * 60 * 60 * 24) - 10);
measurements = measurementApi.getMeasurements(
Filter.build()
.byDate(beforeYesterday, yesterday)
.bySource(testManagedObject.getId()), 5);
ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 0);
}
@Test
public void testMultipleMeasurementsByTypeAndBySource() throws Exception {
SampleTemperatureSensor sts = new SampleTemperatureSensor();
sts.setTemperature(100);
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date(new Date().getTime() - (1000 * 60)));
testMeasurement.setType("mysuperspecialtype");
testMeasurement.set(sts);
measurementApi.createMeasurement(testMeasurement);
MeasurementCollection measurements = measurementApi.getMeasurements(
Filter.build()
.byType("mysuperspecialtype")
.bySource(testManagedObject.getId()), 5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 1);
measurements = measurementApi.getMeasurements(
Filter.build()
.byType("NOT_USED")
.bySource(testManagedObject.getId()), 5);
ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 0);
}
@Test
public void testMultipleMeasurementsByFragmentTypeAndBySource() throws Exception {
SampleTemperatureSensor sts = new SampleTemperatureSensor();
sts.setTemperature(100);
Measurement testMeasurement = new Measurement();
testMeasurement.setSource(testManagedObject);
testMeasurement.setTime(new Date(new Date().getTime() - (1000 * 60)));
testMeasurement.setType("mysuperspecialtype");
testMeasurement.set(sts);
measurementApi.createMeasurement(testMeasurement);
MeasurementCollection measurements = measurementApi.getMeasurements(
Filter.build()
.byFragmentType("com_telekom_m2m_cot_restsdk_util_SampleTemperatureSensor")
.bySource(testManagedObject.getId()), 5);
Measurement[] ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 1);
measurements = measurementApi.getMeasurements(
Filter.build()
.byFragmentType("com_telekom_m2m_cot_restsdk_util_SampleTemperatureSensor_not")
.bySource(testManagedObject.getId()), 5);
ms = measurements.getMeasurements();
Assert.assertEquals(ms.length, 0);
}
}
| 40.654088 | 144 | 0.68487 |
4f5c71265abd362fe73be355fd5bd33c9d0bc181 | 1,772 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myfileutil;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Scanner;
/**
*
* @author msaad
*/
public class myFileHandler {
public String myReadFileUtf8(String fileName){
String str = null;
try {
File fileDir = new File(fileName);
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return str;
}
public String readEntilerFile(String fn) throws FileNotFoundException{
String content = new Scanner(new File(fn), "UTF-8").useDelimiter("\\A").next();
return content;
}
public void writeFileUTF(String sring, String fn) throws UnsupportedEncodingException, FileNotFoundException, IOException{
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fn), "UTF-8"));
try {
out.write(sring);
} finally {
out.close();
}
}
}
| 23.626667 | 126 | 0.645598 |
3e71fb17b3af02ea3a315f0e64fe0db73637e6a1 | 3,351 | /**
* The MIT License (MIT)
*
* Copyright (c) 2016 Thiago Souza <thiago@scrap.sh>
*
* 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 sh.scrap.scrapper.functions;
import org.reactivestreams.Subscription;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sh.scrap.scrapper.DataScrapperFunction;
import sh.scrap.scrapper.DataScrapperFunctionFactory;
import sh.scrap.scrapper.DataScrapperFunctionLibrary;
import sh.scrap.scrapper.annotation.Name;
import java.util.Iterator;
import java.util.Map;
@Name("to-iterable")
public class ToIterableFunctionFactory implements DataScrapperFunctionFactory<Void> {
@Override @SuppressWarnings("unchecked")
public DataScrapperFunction create(String name, DataScrapperFunctionLibrary library,
Void mainArgument, Map<String, Object> annotations) {
return context -> subscription -> subscription.onSubscribe(new Subscription() {
@Override
public void request(long n) {
Object data = context.data();
if (data.getClass().isArray())
data = toIterable((Object[]) data);
else if (data instanceof NodeList)
data = toIterable((NodeList) data);
else if (!(data instanceof Iterable))
data = toIterable(new Object[] { data });
subscription.onNext(context.withData(data));
subscription.onComplete();
}
@Override public void cancel() {}
});
}
private Iterable<Object> toIterable(Object[] array) {
return () -> new Iterator<Object>() {
int index = 0;
@Override
public boolean hasNext() {
return index < array.length;
}
@Override
public Object next() {
return array[index++];
}
};
}
private Iterable<Node> toIterable(NodeList list) {
return () -> new Iterator<Node>() {
int index = 0;
@Override
public boolean hasNext() {
return index < list.getLength();
}
@Override
public Node next() {
return list.item(index++);
}
};
}
}
| 36.423913 | 92 | 0.632945 |
bab12217195fbc4639f4d12810eaa3a1c2aeb9fc | 287 | package godofjava.inheritance;
public class Dog extends Animal {
String dogVariable;
public void move() {
System.out.println("Method Dog move overriding");
}
public void eatFood() {
System.out.println("Method Dog eatFood overriding");
}
}
| 23.916667 | 61 | 0.637631 |
556d155cdbdc7528a17bdd4b6837e00f543d8b74 | 22,515 | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.git;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.copybara.exception.ValidationException.checkCondition;
import static com.google.copybara.git.github.util.GitHubUtil.asGithubUrl;
import static com.google.copybara.git.github.util.GitHubUtil.asHeadRef;
import static com.google.copybara.git.github.util.GitHubUtil.asMergeRef;
import static com.google.copybara.git.github.util.GitHubUtil.getProjectNameFromUrl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.copybara.BaselinesWithoutLabelVisitor;
import com.google.copybara.Change;
import com.google.copybara.Endpoint;
import com.google.copybara.GeneralOptions;
import com.google.copybara.Origin;
import com.google.copybara.authoring.Authoring;
import com.google.copybara.checks.Checker;
import com.google.copybara.exception.CannotResolveRevisionException;
import com.google.copybara.exception.EmptyChangeException;
import com.google.copybara.exception.RepoException;
import com.google.copybara.exception.ValidationException;
import com.google.copybara.git.GitOrigin.ReaderImpl;
import com.google.copybara.git.GitOrigin.SubmoduleStrategy;
import com.google.copybara.git.GitRepository.GitLogEntry;
import com.google.copybara.git.github.api.AuthorAssociation;
import com.google.copybara.git.github.api.GitHubApi;
import com.google.copybara.git.github.api.Issue;
import com.google.copybara.git.github.api.Issue.Label;
import com.google.copybara.git.github.api.PullRequest;
import com.google.copybara.git.github.api.Review;
import com.google.copybara.git.github.api.User;
import com.google.copybara.git.github.util.GitHubUtil;
import com.google.copybara.git.github.util.GitHubUtil.GitHubPrUrl;
import com.google.copybara.profiler.Profiler.ProfilerTask;
import com.google.copybara.transform.patch.PatchTransformation;
import com.google.copybara.util.Glob;
import com.google.copybara.util.console.Console;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/**
* A class for reading GitHub Pull Requests
*/
public class GitHubPROrigin implements Origin<GitRevision> {
static final int RETRY_COUNT = 3;
public static final String GITHUB_PR_NUMBER_LABEL = "GITHUB_PR_NUMBER";
public static final String GITHUB_BASE_BRANCH = "GITHUB_BASE_BRANCH";
public static final String GITHUB_BASE_BRANCH_SHA1 = "GITHUB_BASE_BRANCH_SHA1";
public static final String GITHUB_PR_TITLE = "GITHUB_PR_TITLE";
public static final String GITHUB_PR_URL = "GITHUB_PR_URL";
public static final String GITHUB_PR_BODY = "GITHUB_PR_BODY";
public static final String GITHUB_PR_USER = "GITHUB_PR_USER";
public static final String GITHUB_PR_ASSIGNEE = "GITHUB_PR_ASSIGNEE";
public static final String GITHUB_PR_REVIEWER_APPROVER = "GITHUB_PR_REVIEWER_APPROVER";
public static final String GITHUB_PR_REVIEWER_OTHER = "GITHUB_PR_REVIEWER_OTHER";
public static final String GITHUB_PR_REQUESTED_REVIEWER = "GITHUB_PR_REQUESTED_REVIEWER";
private static final String LOCAL_PR_HEAD_REF = "refs/PR_HEAD";
public static final String GITHUB_PR_HEAD_SHA = "GITHUB_PR_HEAD_SHA";
private static final String LOCAL_PR_MERGE_REF = "refs/PR_MERGE";
private static final String LOCAL_PR_BASE_BRANCH = "refs/PR_BASE_BRANCH";
private final String url;
private final boolean useMerge;
private final GeneralOptions generalOptions;
private final GitOptions gitOptions;
private final GitOriginOptions gitOriginOptions;
private final GitHubOptions gitHubOptions;
private final Set<String> requiredLabels;
private final Set<String> retryableLabels;
private final SubmoduleStrategy submoduleStrategy;
private final Console console;
private final boolean baselineFromBranch;
private final Boolean firstParent;
private final StateFilter requiredState;
@Nullable private final ReviewState reviewState;
private final ImmutableSet<AuthorAssociation> reviewApprovers;
@Nullable private final Checker endpointChecker;
@Nullable private final PatchTransformation patchTransformation;
@Nullable private final String branch;
private final boolean describeVersion;
GitHubPROrigin(String url, boolean useMerge, GeneralOptions generalOptions,
GitOptions gitOptions, GitOriginOptions gitOriginOptions, GitHubOptions gitHubOptions,
Set<String> requiredLabels, Set<String> retryableLabels, SubmoduleStrategy submoduleStrategy,
boolean baselineFromBranch, Boolean firstParent, StateFilter requiredState,
@Nullable ReviewState reviewState, ImmutableSet<AuthorAssociation> reviewApprovers,
@Nullable Checker endpointChecker,
@Nullable PatchTransformation patchTransformation,
@Nullable String branch,
boolean describeVersion) {
this.url = checkNotNull(url);
this.useMerge = useMerge;
this.generalOptions = checkNotNull(generalOptions);
this.gitOptions = checkNotNull(gitOptions);
this.gitOriginOptions = checkNotNull(gitOriginOptions);
this.gitHubOptions = gitHubOptions;
this.requiredLabels = checkNotNull(requiredLabels);
this.retryableLabels = checkNotNull(retryableLabels);
this.submoduleStrategy = checkNotNull(submoduleStrategy);
console = generalOptions.console();
this.baselineFromBranch = baselineFromBranch;
this.firstParent = firstParent;
this.requiredState = checkNotNull(requiredState);
this.reviewState = reviewState;
this.reviewApprovers = checkNotNull(reviewApprovers);
this.endpointChecker = endpointChecker;
this.patchTransformation = patchTransformation;
this.branch = branch;
this.describeVersion = describeVersion;
}
@Override
public GitRevision resolve(String reference) throws RepoException, ValidationException {
checkCondition(reference != null, ""
+ "A pull request reference is expected as argument in the command line."
+ " Invoke copybara as:\n"
+ " copybara copy.bara.sky workflow_name 12345");
console.progress("GitHub PR Origin: Resolving reference " + reference);
// A whole https pull request url
Optional<GitHubPrUrl> githubPrUrl = GitHubUtil.maybeParseGithubPrUrl(reference);
String configProjectName = getProjectNameFromUrl(url);
if (githubPrUrl.isPresent()) {
checkCondition(
githubPrUrl.get().getProject().equals(configProjectName),
"Project name should be '%s' but it is '%s' instead", configProjectName,
githubPrUrl.get().getProject());
return getRevisionForPR(configProjectName, githubPrUrl.get().getPrNumber());
}
// A Pull request number
if (CharMatcher.digit().matchesAllOf(reference)) {
return getRevisionForPR(getProjectNameFromUrl(url), Integer.parseInt(reference));
}
// refs/pull/12345/head
Optional<Integer> prNumber = GitHubUtil.maybeParseGithubPrFromHeadRef(reference);
if (prNumber.isPresent()) {
return getRevisionForPR(configProjectName, prNumber.get());
}
String sha1Part = Splitter.on(" ").split(reference).iterator().next();
Matcher matcher = GitRevision.COMPLETE_SHA1_PATTERN.matcher(sha1Part);
// The only valid use case for this is to resolve previous ref. Because we fetch the head of
// the base branch when resolving the PR, it should exist at this point. If it doesn't then it
// is a non-valid reference.
// Note that this might not work if the PR is for a different branch than the imported to
// the destination. But in this case we cannot do that much apart from --force.
if (matcher.matches()) {
return new GitRevision(getRepository(), getRepository().parseRef(sha1Part));
}
throw new CannotResolveRevisionException(
String.format("'%s' is not a valid reference for a GitHub Pull Request. Valid formats:"
+ "'https://github.com/project/pull/1234', 'refs/pull/1234/head' or '1234'",
reference));
}
@Override
@Nullable
public String showDiff(GitRevision revisionFrom, GitRevision revisionTo) throws RepoException {
return getRepository().showDiff(
checkNotNull(revisionFrom, "revisionFrom should not be null").getSha1(),
checkNotNull(revisionTo, "revisionTo should not be null").getSha1());
}
private GitRevision getRevisionForPR(String project, int prNumber)
throws RepoException, ValidationException {
GitHubApi api = gitHubOptions.newGitHubApi(project);
if (!requiredLabels.isEmpty()) {
int retryCount = 0;
Set<String> requiredButNotPresent;
do {
Issue issue;
try (ProfilerTask ignore = generalOptions.profiler().start("github_api_get_issue")) {
issue = api.getIssue(project, prNumber);
}
requiredButNotPresent = Sets.newHashSet(requiredLabels);
requiredButNotPresent.removeAll(Collections2.transform(issue.getLabels(), Label::getName));
// If we got all the labels we want or none of the ones we didn't get are retryable, return.
if (requiredButNotPresent.isEmpty()
|| Collections.disjoint(requiredButNotPresent, retryableLabels)) {
break;
}
Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
retryCount++;
} while (retryCount < RETRY_COUNT);
if (!requiredButNotPresent.isEmpty()) {
throw new EmptyChangeException(String.format(
"Cannot migrate http://github.com/%s/pull/%d because it is missing the following"
+ " labels: %s",
project,
prNumber,
requiredButNotPresent));
}
}
ImmutableListMultimap.Builder<String, String> labels = ImmutableListMultimap.builder();
PullRequest prData;
try (ProfilerTask ignore = generalOptions.profiler().start("github_api_get_pr")) {
prData = api.getPullRequest(project, prNumber);
}
if (branch != null && !Objects.equals(prData.getBase().getRef(), branch)) {
throw new EmptyChangeException(String.format(
"Cannot migrate http://github.com/%s/pull/%d because its base branch is '%s', but"
+ " the workflow is configured to only migrate changes for branch '%s'",
project,
prNumber,
prData.getBase().getRef(),
branch));
}
if (reviewState != null) {
ImmutableList<Review> reviews = api.getReviews(project, prNumber);
if (!reviewState.shouldMigrate(reviews, reviewApprovers, prData.getHead().getSha())) {
throw new EmptyChangeException(String.format(
"Cannot migrate http://github.com/%s/pull/%d because it is missing the required"
+ " approvals (origin is configured as %s)",
project, prNumber, reviewState));
}
Set<String> approvers = new HashSet<>();
Set<String> others = new HashSet<>();
for (Review review : reviews) {
if (reviewApprovers.contains(review.getAuthorAssociation())) {
approvers.add(review.getUser().getLogin());
} else {
others.add(review.getUser().getLogin());
}
}
labels.putAll(GITHUB_PR_REVIEWER_APPROVER, approvers);
labels.putAll(GITHUB_PR_REVIEWER_OTHER, others);
}
if (requiredState == StateFilter.OPEN && !prData.isOpen()) {
throw new EmptyChangeException(String.format("Pull Request %d is not open", prNumber));
}
if (requiredState == StateFilter.CLOSED && prData.isOpen()) {
throw new EmptyChangeException(String.format("Pull Request %d is open", prNumber));
}
// Fetch also the baseline branch. It is almost free and doing a roundtrip later would hurt
// latency.
console.progressFmt("Fetching Pull Request %d and branch '%s'",
prNumber, prData.getBase().getRef());
try(ProfilerTask ignore = generalOptions.profiler().start("fetch")) {
ImmutableList.Builder<String> refSpecBuilder = ImmutableList.<String>builder()
.add(String.format("%s:%s", asHeadRef(prNumber), LOCAL_PR_HEAD_REF))
// Prefix the branch name with 'refs/heads/' since some implementations of
// GitRepository need the whole reference name.
.add(String.format("refs/heads/%s:" + LOCAL_PR_BASE_BRANCH, prData.getBase().getRef()));
if (useMerge) {
refSpecBuilder.add(String.format("%s:%s", asMergeRef(prNumber), LOCAL_PR_MERGE_REF));
}
ImmutableList<String> refspec = refSpecBuilder.build();
getRepository().fetch(asGithubUrl(project),/*prune=*/false,/*force=*/true, refspec);
} catch (CannotResolveRevisionException e) {
if (useMerge) {
throw new CannotResolveRevisionException(
String.format("Cannot find a merge reference for Pull Request %d."
+ " It might have a conflict with head.", prNumber), e);
} else {
throw new CannotResolveRevisionException(
String.format("Cannot find Pull Request %d.", prNumber), e);
}
}
String refForMigration = useMerge ? LOCAL_PR_MERGE_REF : LOCAL_PR_HEAD_REF;
GitRevision gitRevision = getRepository().resolveReference(refForMigration);
String headPrSha1 = getRepository().resolveReference(LOCAL_PR_HEAD_REF).getSha1();
String integrateLabel = new GitHubPRIntegrateLabel(getRepository(), generalOptions,
project, prNumber,
prData.getHead().getLabel(),
// The integrate SHA has to be HEAD of the PR not the merge ref, even if use_merge = True
headPrSha1)
.toString();
labels.putAll(GITHUB_PR_REQUESTED_REVIEWER, prData.getRequestedReviewers().stream()
.map(User::getLogin)
.collect(ImmutableList.toImmutableList()));
labels.put(GITHUB_PR_NUMBER_LABEL, Integer.toString(prNumber));
labels.put(GitModule.DEFAULT_INTEGRATE_LABEL, integrateLabel);
labels.put(GITHUB_BASE_BRANCH, prData.getBase().getRef());
labels.put(GITHUB_PR_HEAD_SHA, headPrSha1);
String mergeBase = getRepository().mergeBase(refForMigration, LOCAL_PR_BASE_BRANCH);
labels.put(GITHUB_BASE_BRANCH_SHA1, mergeBase);
labels.put(GITHUB_PR_TITLE, prData.getTitle());
labels.put(GITHUB_PR_BODY, prData.getBody());
labels.put(GITHUB_PR_URL, prData.getHtmlUrl());
labels.put(GITHUB_PR_USER, prData.getUser().getLogin());
labels.putAll(GITHUB_PR_ASSIGNEE, prData.getAssignees().stream()
.map(User::getLogin)
.collect(Collectors.toList()));
GitRevision result = new GitRevision(
getRepository(),
gitRevision.getSha1(),
// TODO(malcon): Decide the format to use here:
/*reviewReference=*/null,
useMerge ? asMergeRef(prNumber) : asHeadRef(prNumber),
labels.build(),
url);
return describeVersion ? getRepository().addDescribeVersion(result) : result;
}
@VisibleForTesting
public GitRepository getRepository() throws RepoException {
return gitOptions.cachedBareRepoForUrl(url);
}
@Override
public Reader<GitRevision> newReader(Glob originFiles, Authoring authoring)
throws ValidationException {
return new ReaderImpl(url, originFiles, authoring, gitOptions, gitOriginOptions,
generalOptions, /*includeBranchCommitLogs=*/false, submoduleStrategy, firstParent,
patchTransformation, describeVersion) {
/**
* Disable rebase since this is controlled by useMerge field.
*/
@Override
protected void maybeRebase(GitRepository repo, GitRevision ref, Path workdir)
throws RepoException, CannotResolveRevisionException {
}
@Override
public Optional<Baseline<GitRevision>> findBaseline(GitRevision startRevision, String label)
throws RepoException, ValidationException {
if (!baselineFromBranch) {
return super.findBaseline(startRevision, label);
}
return findBaselinesWithoutLabel(startRevision, /*limit=*/1).stream()
.map(e -> new Baseline<>(e.getSha1(), e))
.findFirst();
}
@Override
public ImmutableList<GitRevision> findBaselinesWithoutLabel(GitRevision startRevision,
int limit)
throws RepoException, ValidationException {
String baseline = Iterables.getLast(
startRevision.associatedLabels().get(GITHUB_BASE_BRANCH_SHA1), null);
checkNotNull(baseline, "%s label should be present in %s",
GITHUB_BASE_BRANCH_SHA1, startRevision);
GitRevision baselineRev = getRepository().resolveReference(baseline);
// Don't skip the first change as it is already the baseline
BaselinesWithoutLabelVisitor<GitRevision> visitor =
new BaselinesWithoutLabelVisitor<>(originFiles, limit, /*skipFirst=*/ false);
visitChanges(baselineRev, visitor);
return visitor.getResult();
}
@Override
public Endpoint getFeedbackEndPoint(Console console) throws ValidationException {
gitHubOptions.validateEndpointChecker(endpointChecker);
return new GitHubEndPoint(gitHubOptions.newGitHubApiSupplier(url, endpointChecker), url,
console);
}
/**
* Deal with the case of useMerge. We have a new commit (the merge) and first-parent from that
* commit doesn't work for this case.
*/
@Override
public ChangesResponse<GitRevision> changes(@Nullable GitRevision fromRef,
GitRevision toRef) throws RepoException {
if (!useMerge) {
return super.changes(fromRef, toRef);
}
GitLogEntry merge = Iterables.getOnlyElement(getRepository()
.log(toRef.getSha1())
.withLimit(1)
.run());
// Fast-forward merge
if (merge.getParents().size() == 1) {
return super.changes(fromRef, toRef);
}
// HEAD of the Pull Request
GitRevision gitRevision = merge.getParents().get(1);
ChangesResponse<GitRevision> prChanges = super.changes(fromRef, gitRevision);
// Merge might have an effect, but we are not interested on it if the PR doesn't touch
// origin_files
if (prChanges.isEmpty()){
return prChanges;
}
try {
return ChangesResponse.forChanges(
ImmutableList.<Change<GitRevision>>builder()
.addAll(prChanges.getChanges())
.add(change(merge.getCommit()))
.build());
} catch (EmptyChangeException e) {
throw new RepoException("Error getting the merge commit information: " + merge, e);
}
}
};
}
@Override
public String getLabelName() {
return GitRepository.GIT_ORIGIN_REV_ID;
}
@Override
public String getType() {
return "git.github_pr_origin";
}
@VisibleForTesting
public ReviewState getReviewState() {
return reviewState;
}
@VisibleForTesting
public Set<String> getRequiredLabels() {
return requiredLabels;
}
@Override
public ImmutableSetMultimap<String, String> describe(Glob originFiles) {
ImmutableSetMultimap.Builder<String, String> builder =
new ImmutableSetMultimap.Builder<String, String>()
.put("type", getType())
.put("url", url);
if (reviewState != null) {
builder.put("review_state", reviewState.name());
builder.putAll("review_approvers",
reviewApprovers.stream().map(Enum::name).collect(ImmutableList.toImmutableList()));
}
return builder.build();
}
/**
* Only migrate PR in one of the following states:
*/
enum StateFilter {
OPEN,
CLOSED,
ALL
}
@VisibleForTesting
public enum ReviewState {
/**
* Requires that the current head commit has at least one valid approval
*/
HEAD_COMMIT_APPROVED {
@Override
boolean shouldMigrate(ImmutableList<Review> reviews, String sha) {
return reviews.stream()
.filter(e -> e.getCommitId().equals(sha))
.anyMatch(Review::isApproved);
}
},
/**
* Any valid approval, even for old commits is good.
*/
ANY_COMMIT_APPROVED {
@Override
boolean shouldMigrate(ImmutableList<Review> reviews, String sha) {
return reviews.stream().anyMatch(Review::isApproved);
}
},
/**
* There are reviewers in the change that have commented, asked for changes or approved
*/
HAS_REVIEWERS {
@Override
boolean shouldMigrate(ImmutableList<Review> reviews, String sha) {
return !reviews.isEmpty();
}
},
/**
* Import the change regardless of the the review state. It will populate the appropriate
* labels if found
*/
ANY {
@Override
boolean shouldMigrate(ImmutableList<Review> reviews, String sha) {
return true;
}
};
boolean shouldMigrate(ImmutableList<Review> reviews,
ImmutableSet<AuthorAssociation> approvers, String sha) {
return shouldMigrate(reviews.stream()
// Only take into acccount reviews by valid approverTypes
.filter(e -> approvers.contains(e.getAuthorAssociation()))
.collect(ImmutableList.toImmutableList()),
sha);
}
abstract boolean shouldMigrate(ImmutableList<Review> reviews, String sha);
}
}
| 41.849442 | 100 | 0.708594 |
eb1e4d8d9789777043c68a1222203a4b6539b4e1 | 3,060 | package com.maoface.ueditor.config;
import com.maoface.ueditor.consts.Constants;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author zhuxuchao
* @date 2020-04-15 16:01
*/
@ConfigurationProperties(prefix = "ueditor.config.upload-image-config")
public class UploadImageProperties {
/**
* 执行上传图片的action名称
*/
private String imageActionName = Constants.Action.UPLOAD_IMAGE;
/**
* 提交的图片表单名称
*/
private String imageFieldName = "upfile";
/**
* 上传大小限制,单位B,默认2MB,注意修改服务器的大小限制
*/
private int imageMaxSize = 10240000;
/**
* 上传保存路径,可以自定义保存路径和文件名格式
*/
private String imagePathFormat = "/ueditor/upload/image/{yyyy}{mm}{dd}{hh}{ii}{ss}{rand:6}";
/**
* 图片访问路径前缀
*/
private String imageUrlPrefix = "";
/**
* 图片压缩最长边限制
*/
private int imageCompressBorder = 1600;
/**
* 是否压缩图片
*/
private boolean imageCompressEnable = true;
/**
* 插入的图片浮动方式
*/
private String imageInsertAlign = "none";
/**
* 上传图片格式限制
*/
private Set<String> imageAllowFiles = new HashSet<>(Arrays.asList(".png", ".jpg", ".jpeg", ".gif", ".bmp"));
public String getImageActionName() {
return imageActionName;
}
public void setImageActionName(String imageActionName) {
this.imageActionName = imageActionName;
}
public String getImageFieldName() {
return imageFieldName;
}
public void setImageFieldName(String imageFieldName) {
this.imageFieldName = imageFieldName;
}
public int getImageMaxSize() {
return imageMaxSize;
}
public void setImageMaxSize(int imageMaxSize) {
this.imageMaxSize = imageMaxSize;
}
public String getImagePathFormat() {
return imagePathFormat;
}
public void setImagePathFormat(String imagePathFormat) {
this.imagePathFormat = imagePathFormat;
}
public String getImageUrlPrefix() {
return imageUrlPrefix;
}
public void setImageUrlPrefix(String imageUrlPrefix) {
this.imageUrlPrefix = imageUrlPrefix;
}
public int getImageCompressBorder() {
return imageCompressBorder;
}
public void setImageCompressBorder(int imageCompressBorder) {
this.imageCompressBorder = imageCompressBorder;
}
public boolean isImageCompressEnable() {
return imageCompressEnable;
}
public void setImageCompressEnable(boolean imageCompressEnable) {
this.imageCompressEnable = imageCompressEnable;
}
public String getImageInsertAlign() {
return imageInsertAlign;
}
public void setImageInsertAlign(String imageInsertAlign) {
this.imageInsertAlign = imageInsertAlign;
}
public Set<String> getImageAllowFiles() {
return imageAllowFiles;
}
public void setImageAllowFiles(Set<String> imageAllowFiles) {
this.imageAllowFiles = imageAllowFiles;
}
}
| 24.48 | 112 | 0.664706 |
00dd653719fb3776c3d9110748fc6575250c3a19 | 156 | /**
* Package for task: 3.1. Максимум из двух чисел.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 0.1
*/
package ru.job4j.max;
| 17.333333 | 49 | 0.666667 |
9af7b9d8e751cd199f73b04670cb83cc3f149edb | 2,650 | package org.qiunet.flash.handler.bootstrap;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.qiunet.flash.handler.bootstrap.hook.MyHook;
import org.qiunet.flash.handler.common.message.MessageContent;
import org.qiunet.flash.handler.context.header.ProtocolHeaderType;
import org.qiunet.flash.handler.context.session.DSession;
import org.qiunet.flash.handler.netty.client.param.TcpClientParams;
import org.qiunet.flash.handler.netty.client.tcp.NettyTcpClient;
import org.qiunet.flash.handler.netty.client.tcp.TcpClientConnector;
import org.qiunet.flash.handler.netty.client.trigger.IPersistConnResponseTrigger;
import org.qiunet.flash.handler.netty.server.BootstrapServer;
import org.qiunet.flash.handler.netty.server.hook.Hook;
import org.qiunet.flash.handler.netty.server.param.TcpBootstrapParams;
import org.qiunet.flash.handler.startup.context.StartupContext;
import org.qiunet.utils.scanner.ClassScanner;
import java.util.concurrent.locks.LockSupport;
/**
* Created by qiunet.
* 17/11/25
*/
public abstract class TcpBootStrap implements IPersistConnResponseTrigger {
protected static final String host = "localhost";
protected static final int port = 8888;
protected static final Hook hook = new MyHook();
protected TcpClientConnector tcpClientConnector;
private static Thread currThread;
@BeforeClass
public static void init() throws Exception {
ClassScanner.getInstance().scanner();
currThread = Thread.currentThread();
Thread thread = new Thread(() -> {
TcpBootstrapParams tcpParams = TcpBootstrapParams.custom()
.setProtocolHeaderType(ProtocolHeaderType.server)
.setStartupContext(new StartupContext())
.setEncryption(true)
.setPort(port)
.build();
BootstrapServer server = BootstrapServer.createBootstrap(hook).tcpListener(tcpParams);
LockSupport.unpark(currThread);
server.await();
});
thread.start();
LockSupport.park();
}
@Before
public void connect(){
currThread = Thread.currentThread();
NettyTcpClient tcpClient = NettyTcpClient.create(TcpClientParams.DEFAULT_PARAMS, this);
tcpClientConnector = tcpClient.connect(host, port);
}
@After
public void closeConnect(){
currThread = Thread.currentThread();
LockSupport.park();
}
@Override
public void response(DSession session, MessageContent data) {
this.responseTcpMessage(session, data);
LockSupport.unpark(currThread);
}
protected abstract void responseTcpMessage(DSession session, MessageContent data);
@AfterClass
public static void shutdown() {
BootstrapServer.sendHookMsg(hook.getHookPort(), hook.getShutdownMsg());
}
}
| 33.125 | 89 | 0.789811 |
9dd413d1f846a12a51096afa5c3283296a613ab6 | 7,019 | package pokecube.legends.conditions;
import java.util.ArrayList;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import pokecube.core.database.Database;
import pokecube.core.database.PokedexEntry;
import pokecube.core.database.stats.CaptureStats;
import pokecube.core.database.stats.ISpecialCaptureCondition;
import pokecube.core.database.stats.ISpecialSpawnCondition;
import pokecube.core.handlers.PokecubePlayerDataHandler;
import pokecube.core.handlers.events.SpawnHandler;
import pokecube.core.interfaces.IPokemob;
import pokecube.core.utils.PokeType;
import pokecube.core.utils.Tools;
import pokecube.legends.PokecubeLegends;
import thut.api.maths.Vector3;
public abstract class Condition implements ISpecialCaptureCondition, ISpecialSpawnCondition
{
protected static boolean isBlock(final World world, final ArrayList<Vector3> blocks, final Block toTest)
{
for (final Vector3 v : blocks)
if (v.getBlock(world) != toTest) return false;
return true;
}
/**
* @param world
* @param blocks
* @param material
* @param bool
* if true, looks for matches, if false looks for anything that
* doesn't match.
* @return
*/
protected static boolean isMaterial(final World world, final ArrayList<Vector3> blocks, final Material material,
final boolean bool)
{
final boolean ret = true;
if (bool)
{
for (final Vector3 v : blocks)
if (v.getBlockMaterial(world) != material) return false;
}
else for (final Vector3 v : blocks)
if (v.getBlockMaterial(world) == material) return false;
return ret;
}
public abstract PokedexEntry getEntry();
@Override
public boolean canCapture(final Entity trainer)
{
if (trainer == null) return false;
if (CaptureStats.getTotalNumberOfPokemobCaughtBy(trainer.getUniqueID(), this.getEntry()) > 0) return false;
if (trainer instanceof ServerPlayerEntity && PokecubePlayerDataHandler.getCustomDataTag(
(ServerPlayerEntity) trainer).getBoolean("capt:" + this.getEntry().getTrimmedName())) return false;
return true;
}
@Override
public void onSpawn(final IPokemob mob)
{
}
@Override
public boolean canSpawn(final Entity trainer)
{
if (trainer == null) return false;
if (CaptureStats.getTotalNumberOfPokemobCaughtBy(trainer.getUniqueID(), this.getEntry()) > 0) return true;
// Also check if can capture, if not, no point in being able to spawn.
if (trainer instanceof ServerPlayerEntity && PokecubePlayerDataHandler.getCustomDataTag(
(ServerPlayerEntity) trainer).getBoolean("capt:" + this.getEntry().getTrimmedName())) return false;
if (trainer instanceof ServerPlayerEntity)
{
final boolean prevSpawn = PokecubePlayerDataHandler.getCustomDataTag((ServerPlayerEntity) trainer)
.getBoolean("spwn:" + this.getEntry().getTrimmedName());
if (!prevSpawn) return true;
final MinecraftServer server = trainer.getServer();
final long spwnDied = PokecubePlayerDataHandler.getCustomDataTag((ServerPlayerEntity) trainer).getLong(
"spwn_ded:" + this.getEntry().getTrimmedName());
if (spwnDied > 0) return spwnDied + PokecubeLegends.config.respawnLegendDelay < server.getWorld(
DimensionType.OVERWORLD).getGameTime();
return false;
}
return true;
}
@Override
public boolean canSpawn(final Entity trainer, final Vector3 location, final boolean message)
{
if (!this.canSpawn(trainer)) return false;
if (SpawnHandler.canSpawn(this.getEntry().getSpawnData(), location, trainer.getEntityWorld(), false))
{
final boolean here = Tools.countPokemon(location, trainer.getEntityWorld(), 32, this.getEntry()) > 0;
return !here;
}
if (message) this.sendNoHere(trainer);
return false;
}
public void sendNoTrust(final Entity trainer)
{
final String message = "msg.notrust.info";
final ITextComponent component = new TranslationTextComponent(message, new TranslationTextComponent(this
.getEntry().getUnlocalizedName()));
trainer.sendMessage(component);
}
public void sendNoHere(final Entity trainer)
{
final String message = "msg.nohere.info";
final ITextComponent component = new TranslationTextComponent(message, new TranslationTextComponent(this
.getEntry().getUnlocalizedName()));
trainer.sendMessage(component);
}
// Basic Legend
public void sendLegend(final Entity trainer, String type, final int numA, final int numB)
{
final String message = "msg.infolegend.info";
type = PokeType.getTranslatedName(PokeType.getType(type));
trainer.sendMessage(new TranslationTextComponent(message, type, numA + 1, numB));
}
// Duo Type Legend
public void sendLegendDuo(final Entity trainer, String type, String kill, final int numA, final int numB,
final int killa, final int killb)
{
final String message = "msg.infolegendduo.info";
type = PokeType.getTranslatedName(PokeType.getType(type));
kill = PokeType.getTranslatedName(PokeType.getType(kill));
trainer.sendMessage(new TranslationTextComponent(message, type, kill, numA + 1, numB, killa + 1, killb));
}
// Catch specific Legend
public void sendLegendExtra(final Entity trainer, final String names)
{
final String message = "msg.infolegendextra.info";
final String[] split = names.split(", ");
ITextComponent namemes = null;
for (final String s : split)
{
PokedexEntry entry = Database.getEntry(s);
if (entry == null) entry = Database.missingno;
if (namemes == null) namemes = new TranslationTextComponent(entry.getUnlocalizedName());
else namemes = namemes.appendText(", ").appendSibling(new TranslationTextComponent(entry
.getUnlocalizedName()));
}
trainer.sendMessage(new TranslationTextComponent(message, namemes));
}
public void sendAngered(final Entity trainer)
{
final String message = "msg.angeredlegend.json";
final ITextComponent component = new TranslationTextComponent(message, new TranslationTextComponent(this
.getEntry().getUnlocalizedName()));
trainer.sendMessage(component);
}
}
| 40.80814 | 116 | 0.679442 |
4d791906fe8e2a3ea6912cf827c829c6a2987482 | 11,058 | package org.openpaas.paasta.portal.api.service;
import org.cloudfoundry.uaa.clients.*;
import org.cloudfoundry.uaa.tokens.GrantType;
import org.openpaas.paasta.portal.api.common.Common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Service
public class ClientServiceV2 extends Common {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientServiceV2.class);
public ListClientsResponse getClientList() throws Exception {
return uaaAdminClient(connectionContext(), adminUserName, adminPassword, uaaAdminClientId, uaaAdminClientSecret).clients().list(ListClientsRequest.builder().build()).block();
}
/**
* 클라이언트 정보 조회
*
* @param clientId clientId
* @return GetClientResponse
* @throws Exception the exception
*/
public GetClientResponse getClient(String clientId) throws Exception {
return uaaAdminClient(connectionContext(), adminUserName, adminPassword, uaaAdminClientId, uaaAdminClientSecret).clients().get(GetClientRequest.builder().clientId(clientId).build()).block();
}
/**
* 클라이언트 등록
* cloudFoundryClient
*
* @param param
* @return CreateClientResponse
* @throws Exception the exception
*/
public CreateClientResponse registerClient(Map<String, Object> param) throws Exception {
ClientServiceV2.ClientOption clientOption = new ClientServiceV2.ClientOption();
clientOption = clientOption.setClientOptionByMap(param);
return uaaAdminClient(connectionContext(), adminUserName, adminPassword, uaaAdminClientId, uaaAdminClientSecret).clients().create(CreateClientRequest.builder().clientId(clientOption.clientId).clientSecret(clientOption.clientSecret).name(clientOption.name).scopes(clientOption.scopes).authorities(clientOption.authorities).resourceIds(clientOption.resourceIds).authorizedGrantTypes(clientOption.authorizedGrantTypes).redirectUriPatterns(clientOption.redirectUriPatterns).autoApproves(clientOption.autoApproves).tokenSalt(clientOption.tokenSalt).allowedProviders(clientOption.allowedProviders).accessTokenValidity(clientOption.accessTokenValidity).refreshTokenValidity(clientOption.refreshTokenValidity).build()).block();
}
/**
* 클라이언트 수정
*
* @param param
* @return Map map
* @throws Exception the exception
*/
public UpdateClientResponse updateClient(Map<String, Object> param) throws Exception {
ClientServiceV2.ClientOption clientOption = new ClientServiceV2.ClientOption();
clientOption = clientOption.setClientOptionByMap(param);
//LOGGER.info(clientOption.toString());
//Secret, Token Validity 는 생성 이후 수정 불가
return uaaAdminClient(connectionContext(), adminUserName, adminPassword, uaaAdminClientId, uaaAdminClientSecret).clients().update(UpdateClientRequest.builder().clientId(clientOption.clientId)
.name(clientOption.name).scopes(clientOption.scopes).authorities(clientOption.authorities).resourceIds(clientOption.resourceIds).authorizedGrantTypes(clientOption.authorizedGrantTypes).redirectUriPatterns(clientOption.redirectUriPatterns).autoApproves(clientOption.autoApproves).tokenSalt(clientOption.tokenSalt).allowedProviders(clientOption.allowedProviders)
.build()).block();
}
/**
* 클라이언트 삭제
*
* @param clientId
* @return Map map
* @throws Exception the exception
*/
public DeleteClientResponse deleteClient(String clientId) throws Exception {
return uaaAdminClient(connectionContext(), adminUserName, adminPassword, uaaAdminClientId, uaaAdminClientSecret).clients().delete(DeleteClientRequest.builder().clientId(clientId).build()).block();
}
/**
* ClientOption Inner Class
* 생성/수정시 사용되는 Option 객체를 생성하기 위한 Inner Class
*
* @author CISS
* @version 1.0
* @since 2018.6.7 최초작성
*/
static private class ClientOption {
private List<GrantType> authorizedGrantTypes;
private List<String> authorities;
private List<String> scopes;
private List<String> resourceIds;
private String name;
private String clientId;
private String clientSecret;
private List<String> redirectUriPatterns;
private List<String> autoApproves;
private String tokenSalt;
private List<String> allowedProviders;
private long accessTokenValidity;
private long refreshTokenValidity;
/**
* 클라리언트 옵션 Set
* Map 으로 받은 Option 을 CreateClientRequest Argument 에 맞게 파싱처리
*
* @return Map map
* @see //docs.cloudfoundry.org/api/uaa/version/4.12.0/#create-6
*/
public ClientOption setClientOptionByMap(Map<String, Object> param) {
this.authorizedGrantTypes = new ArrayList<>();
this.authorities = new ArrayList<>();
this.scopes = new ArrayList<>();
this.resourceIds = new ArrayList<>();
this.name = "";
this.clientId = "";
this.clientSecret = "";
this.redirectUriPatterns = new ArrayList<>();
this.autoApproves = new ArrayList<>();
this.tokenSalt = "";
this.allowedProviders = new ArrayList<>();
this.accessTokenValidity = 0;
this.refreshTokenValidity = 0;
for (Map.Entry<String,Object> entry : param.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println(key+"="+value);
}
//Iterator<String> keys = param.keySet().iterator();
//while (keys.hasNext()) {
for (Map.Entry<String,Object> entry : param.entrySet()) {
//String key = keys.next();
//Object value = param.get(key);
String key = entry.getKey();
Object value = entry.getValue();
LOGGER.info( "key : " + key + ", value : " + value);
// ID
if (key.equals("client_id")) {
clientId = (String) value;
}
// Secret
if (key.equals("client_secret")) {
clientSecret = (String) value;
}
//authorizedGrantTypes
if (key.equals("authorized_grant_types")) {
if (value.getClass().equals(ArrayList.class)) {
for (Object obj : (ArrayList) value) {
switch ((String) obj) {
case "client_credentials":
authorizedGrantTypes.add(GrantType.CLIENT_CREDENTIALS);
continue;
case "authorization_code":
authorizedGrantTypes.add(GrantType.AUTHORIZATION_CODE);
continue;
case "implicit":
authorizedGrantTypes.add(GrantType.IMPLICIT);
continue;
case "password":
authorizedGrantTypes.add(GrantType.PASSWORD);
continue;
case "refresh_token":
authorizedGrantTypes.add(GrantType.REFRESH_TOKEN);
continue;
default:
continue;
}
}
}
}
// List Item proc
if (key.equals("authorities") || key.equals("scope") || key.equals("resource_ids") || key.equals("redirect_uri") || key.equals("autoapprove") || key.equals("allowedproviders ") || key.equals("name")) {
if (value.getClass().equals(ArrayList.class)) {
for (Object obj : (ArrayList) value) {
switch (key) {
case "authorities": // authorities
authorities.add((String) obj);
continue;
case "scope": // scope
scopes.add((String) obj);
continue;
case "resource_ids": // resourceIds
resourceIds.add((String) obj);
continue;
case "redirect_uri": // redirectUriPatterns
redirectUriPatterns.add((String) obj);
continue;
case "autoapprove": // autoApproves
autoApproves.add((String) obj);
continue;
case "allowedproviders": // allowedProviders
allowedProviders.add((String) obj);
continue;
// 아래부터는 단건이지만 Front에서 List로 전달하고 있음
case "name": // name
name = (String) obj;
break;
case "token_salt": // tokenSalt
tokenSalt = (String) obj;
break;
case "access_token_validity": // accessTokenValidity(unit: seconds)
accessTokenValidity = Long.parseLong((String) obj);
break;
case "refresh_token_validity": // refreshTokenValidity(unit: seconds)
refreshTokenValidity = Long.parseLong((String) obj);
break;
default:
continue;
}
}
}
}
}
return this;
}
@Override
public String toString() {
return "ClientOption{" + "authorizedGrantTypes=" + authorizedGrantTypes + ", authorities=" + authorities + ", scopes=" + scopes + ", resourceIds=" + resourceIds + ", name=" + name + ", clientId=" + clientId + ", clientSecret=" + clientSecret + ", redirectUriPatterns=" + redirectUriPatterns + ", autoApproves=" + autoApproves + ", tokenSalt=" + tokenSalt + ", allowedProviders=" + allowedProviders + ", accessTokenValidity=" + accessTokenValidity + ", refreshTokenValidity=" + refreshTokenValidity + "}";
}
}
}
| 46.075 | 727 | 0.552089 |
9dea33a311db623d1cb06a39d044bb6fb4255883 | 1,148 | package com.cjh.eshop.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import com.cjh.eshop.dao.IProvinceDao;
import com.cjh.eshop.dao.common.BaseDao;
import com.cjh.eshop.model.Province;
@Repository
public class ProvinceDao extends BaseDao<Province, Integer> implements IProvinceDao {
@Resource(name = "sqlSessionTemplate")
private SqlSessionTemplate sqlSession;
final String MAPPER = ASD + "provinceMapper.";
@Override
public Province getById(Integer id) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Province> getAll() {
return sqlSession.selectList(MAPPER + "selectAll");
}
@Override
public Integer save(Province entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public void update(Province entity) {
// TODO Auto-generated method stub
}
@Override
public void deleteById(Integer id) {
// TODO Auto-generated method stub
}
}
| 22.509804 | 85 | 0.684669 |
8f8540c0f97a13c039eb65ab6f089bacd2e7831c | 3,246 | /*L
* Copyright SAIC, Ellumen and RSNA (CTP)
*
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
*/
package gov.nih.nci.nbia.dao;
import gov.nih.nci.nbia.dto.CustomSeriesDTO;
import gov.nih.nci.nbia.dto.CustomSeriesListAttributeDTO;
import gov.nih.nci.nbia.dto.CustomSeriesListDTO;
import gov.nih.nci.nbia.dto.QcCustomSeriesListDTO;
import gov.nih.nci.nbia.util.SiteData;
import java.util.List;
import org.springframework.dao.DataAccessException;
/**
* handle all database transactions for the custom series list
*
* @author lethai
*
*/
public interface CustomSeriesListDAO {
/**
* query database table to check for existence of name
*
* @param name
*/
public boolean isDuplicateName(String name) throws DataAccessException;
/**
* find series that belongs to public group
* @param seriesUids
* @param authorizedPublicSites
*/
public List<CustomSeriesDTO> findSeriesForPublicCollection(List<String> seriesUids,
List<SiteData> authorizedPublicSites) throws DataAccessException;
/**
* find all series that contains all the seriesuids and user has permission
* to see
*
* @param seriesUids
* @param authorizedSites
* @param authorizedSeriesSecurityGroups
*/
public List<CustomSeriesDTO> findSeriesBySeriesInstanceUids(List<String> seriesUids,
List<SiteData> authorizedSites,
List<String> authorizedSeriesSecurityGroups) throws DataAccessException;
/**
* Find all shared list by a given list of series instance uids
* @param seriesUids
*/
public List<QcCustomSeriesListDTO> findSharedListBySeriesInstanceUids(List<String> seriesUids) throws DataAccessException;
//public String findEmailByUserName(String uName)throws DataAccessException;
public String findEmailByUserName(String uName);
/**
* update database with data in the dto
*
*/
public long update(CustomSeriesListDTO editList, String userName, Boolean updatedSeries) throws DataAccessException;
public void updateUsageCount(int id) throws DataAccessException;
/**
* insert a new record for the custom series list
*
* @param customList
*/
public long insert(CustomSeriesListDTO customList, String username) throws DataAccessException;
/**
* find all the shared list for a given user
* @param username
*/
public List<CustomSeriesListDTO> findCustomSeriesListByUser(String username) throws DataAccessException;
public CustomSeriesListDTO findCustomSeriesListByName(String name) throws DataAccessException;
public List<CustomSeriesListDTO> findCustomSeriesListByNameLikeSearch(String name) throws DataAccessException;
public List<CustomSeriesListAttributeDTO> findCustomSeriesListAttribute(
Integer customSeriesListPkId) throws DataAccessException;
/**
* delete from database with data in the dto
*
*/
public long delete(CustomSeriesListDTO editList) throws DataAccessException;
/**
*
* @return
* @throws DataAccessException
*/
public List<String> getSharedListUserNames() throws DataAccessException;
} | 30.622642 | 127 | 0.741836 |
8c5bff91f60eb9277726b12640143e6de6cfffaf | 2,081 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.docker.command;
import org.apache.karaf.docker.ImageSearch;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.support.table.ShellTable;
@Command(scope = "docker", name = "search", description = "Search the Docker Hub for images")
@Service
public class SearchCommand extends DockerCommandSupport {
@Argument(index = 0, name = "term", description = "Search term", required = true, multiValued = false)
String term;
@Override
public Object execute() throws Exception {
ShellTable table = new ShellTable();
table.column("Name");
table.column("Description");
table.column("Automated");
table.column("Official");
table.column("Star Count");
for (ImageSearch search : getDockerService().search(term, url)) {
table.addRow().addContent(
search.getName(),
search.getDescription(),
search.isAutomated(),
search.isOfficial(),
search.getStarCount()
);
}
table.print(System.out);
return null;
}
}
| 38.537037 | 106 | 0.67852 |
d141c731d7cec9edb1a3b12ac685f62958685b4d | 10,943 | package co.edu.uniandes.csw.fiestas.test.logic;
import co.edu.uniandes.csw.fiestas.ejb.ContratoLogic;
import co.edu.uniandes.csw.fiestas.entities.ContratoEntity;
import co.edu.uniandes.csw.fiestas.entities.EventoEntity;
import co.edu.uniandes.csw.fiestas.entities.HorarioEntity;
import co.edu.uniandes.csw.fiestas.entities.ProductoEntity;
import co.edu.uniandes.csw.fiestas.entities.ProveedorEntity;
import co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.fiestas.persistence.ContratoPersistence;
import java.util.*;
import javax.inject.Inject;
import javax.persistence.*;
import javax.transaction.UserTransaction;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.*;
import org.junit.runner.RunWith;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
/**
*
* @author mc.gonzalez15
*/
@RunWith(Arquillian.class)
public class ContratoLogicTest {
public ContratoLogicTest() {
}
private final PodamFactory factory = new PodamFactoryImpl();
@Inject
private ContratoLogic contratoLogic;
@PersistenceContext
private EntityManager em;
@Inject
private UserTransaction utx;
private List<ContratoEntity> data = new ArrayList<>();
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addPackage(ContratoEntity.class.getPackage())
.addPackage(ContratoLogic.class.getPackage())
.addPackage(ContratoPersistence.class.getPackage())
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml")
.addAsManifestResource("META-INF/beans.xml", "beans.xml");
}
/**
* Configuración inicial de la prueba.
*/
@Before
public void configTest() {
try {
utx.begin();
clearData();
insertData();
utx.commit();
} catch (Exception e) {
e.printStackTrace();
try {
utx.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
/**
* Limpia las tablas que están implicadas en la prueba.
*/
private void clearData() {
em.createQuery("delete from ContratoEntity").executeUpdate();
}
/**
* Inserta los datos iniciales para el correcto funcionamiento de las
* pruebas.
*/
private void insertData() {
for (int i = 0; i < 3; i++) {
ContratoEntity contrato = factory.manufacturePojo(ContratoEntity.class);
EventoEntity evento = factory.manufacturePojo(EventoEntity.class);
ProveedorEntity proveedor = factory.manufacturePojo(ProveedorEntity.class);
HorarioEntity horario = factory.manufacturePojo(HorarioEntity.class);
contrato.setEvento(evento);
contrato.setProveedor(proveedor);
contrato.setHorario(horario);
ArrayList<ProductoEntity> productos = new ArrayList<>();
for (int l = 0; l < 10; l++) {
ProductoEntity producto = factory.manufacturePojo(ProductoEntity.class);
productos.add(producto);
em.persist(producto);
}
contrato.setProductos(productos);
em.persist(contrato);
em.persist(evento);
em.persist(horario);
em.persist(proveedor);
data.add(contrato);
System.out.println("Si se añaden elementos a la lista.");
}
}
/**
* Prueba para crear un Contrato
*
* @throws co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException
*/
@Test
public void createContratoTest() throws BusinessLogicException {
ContratoEntity newEntity = factory.manufacturePojo(ContratoEntity.class);
HorarioEntity horario = factory.manufacturePojo(HorarioEntity.class);
horario.setHoraInicio(new Date(2018, 5, 20, 20, 15, 0));
horario.setHoraFin(new Date(2018, 5, 20, 20, 22, 0));
newEntity.setValor(2);
ContratoEntity newEntity2 = factory.manufacturePojo(ContratoEntity.class);
HorarioEntity horario2 = factory.manufacturePojo(HorarioEntity.class);
//Caso 1: Normal
try {
ContratoEntity result = contratoLogic.createContrato(newEntity);
ContratoEntity entidad = em.find(ContratoEntity.class, result.getId());
Assert.assertEquals(newEntity.getId(), entidad.getId());
Assert.assertEquals(newEntity.getValor(), entidad.getValor());
Assert.assertEquals(newEntity.getTyc(), entidad.getTyc());
Assert.assertEquals(newEntity.getProveedor(), entidad.getProveedor());
Assert.assertEquals(newEntity.getEvento(), entidad.getEvento());
Assert.assertEquals(newEntity.getProductos(), entidad.getProductos());
} catch (Exception e) {
Assert.fail("No debería lanzar excepcion " + e.getMessage());
}
//Caso 2: Los términos y condiciones están vacíos.
try {
horario2.setHoraInicio(new Date(2018, 5, 20, 20, 15, 0));
horario2.setHoraFin(new Date(2018, 5, 20, 20, 22, 0));
newEntity2.setTyc("");
ContratoEntity result = contratoLogic.createContrato(newEntity2);
Assert.fail("No debería llegar aquí");
} catch (Exception e) {
//Debería llegar aquí
}
//Caso 3: El valor es negativo
try {
newEntity2.setValor(-1);
ContratoEntity result = contratoLogic.createContrato(newEntity2);
Assert.fail("No debería llegar aquí");
} catch (Exception e) {
//Debería llegar aquí
}
//Caso 4: El contrato con id ya existe.
try {
ContratoEntity result = contratoLogic.createContrato(newEntity);
Assert.fail("No debería llegar aquí");
} catch (Exception e) {
//Debería llegar aquí
}
}
/**
* Prueba para consultar la lista de contratos
*/
@Test
public void getContratosTest() {
List<ContratoEntity> lista = contratoLogic.getContratos();
Assert.assertEquals(data.size(), lista.size());
for (ContratoEntity entity : lista) {
boolean encontrado = false;
for (ContratoEntity contratoEntity : data) {
if (entity.getId().equals(contratoEntity.getId())) {
encontrado = true;
break;
}
}
Assert.assertTrue(encontrado);
}
}
/**
* Prueba para eliminar un contrato
*/
@Test
public void deleteContrato() {
ContratoEntity entity = data.get(0);
contratoLogic.deleteContrato(entity.getId());
ContratoEntity deleted = em.find(ContratoEntity.class, entity.getId());
org.junit.Assert.assertNull(deleted);
}
/**
* Prueba para actualizar un contrato
*/
@Test
public void updateContratoTest() {
ContratoEntity entity = data.get(0);
ContratoEntity newEntity = factory.manufacturePojo(ContratoEntity.class);
newEntity.setId(entity.getId());
contratoLogic.updateContrato(newEntity);
ContratoEntity resp = em.find(ContratoEntity.class, entity.getId());
Assert.assertEquals(newEntity.getId(), resp.getId());
Assert.assertEquals(newEntity.getValor(), resp.getValor());
Assert.assertEquals(newEntity.getTyc(), resp.getTyc());
Assert.assertEquals(newEntity.getProveedor(), resp.getProveedor());
Assert.assertEquals(newEntity.getEvento(), resp.getEvento());
Assert.assertEquals(newEntity.getProductos(), resp.getProductos());
}
/**
* Prueba para la lista de productos
*/
@Test
public void listProductosTest() {
ContratoEntity entity = data.get(0);
List<ProductoEntity> productos = contratoLogic.listProductos(entity.getId());
for (int i = 0; i < productos.size(); i++) {
if (!productos.contains(entity.getProductos().get(i))) {
Assert.fail("Deberían contener los mismos productos.");
}
}
}
/**
* Prueba para obtener un producto
*/
@Test
public void getProductoTest() {
ContratoEntity entity = data.get(0);
ProductoEntity p = entity.getProductos().get(0);
ProductoEntity producto = contratoLogic.getProducto(entity.getId(), p.getId());
Assert.assertEquals(p, producto);
}
/**
* Prueba para agregar un producto
*/
@Test
public void addProductoTest() {
ContratoEntity entity = data.get(0);
ProductoEntity p = data.get(1).getProductos().get(0);
ProductoEntity producto = contratoLogic.addProducto(entity.getId(), p.getId());
if(!producto.equals(p))
{
Assert.fail();
}
}
/**
* Prueba para reemplazar los productos
*/
@Test
public void replaceProductosTest() {
ContratoEntity entity = data.get(0);
ArrayList<ProductoEntity> productosNuevos = new ArrayList<>();
for(int i = 0; i<10; i++)
{
productosNuevos.add(factory.manufacturePojo(ProductoEntity.class));
}
List<ProductoEntity> productos = contratoLogic.replaceProductos(entity.getId(), productosNuevos);
if(!productos.containsAll(productosNuevos))
{
Assert.fail();
}
}
/**
* Prueba para remover un producto
*/
@Test
public void removeProductoTest() {
ContratoEntity entity = data.get(0);
ProductoEntity p = entity.getProductos().get(0);
contratoLogic.removeProducto(entity.getId() , p.getId());
if(entity.getProductos().contains(p))
{
Assert.fail();
}
}
/**
* Prueba para reemplazar un horario
*/
@Test
public void replaceHorarioTest() {
ContratoEntity entity = data.get(0);
HorarioEntity nuevo = factory.manufacturePojo(HorarioEntity.class);
HorarioEntity hor = contratoLogic.replaceHorario(entity.getId(), nuevo);
Assert.assertEquals(nuevo, hor);
}
}
| 31.445402 | 106 | 0.598556 |
b1bef381dbd0d996a89a7a57abf2aa688740497a | 18,332 | package com.zy.coolbicycle.ui.activity.user;
import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.IDNA;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.kongzue.dialog.interfaces.OnInputDialogButtonClickListener;
import com.kongzue.dialog.interfaces.OnMenuItemClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.BottomMenu;
import com.kongzue.dialog.v3.InputDialog;
import com.kongzue.dialog.v3.TipDialog;
import com.yang.easyhttp.EasyHttpClient;
import com.yang.easyhttp.callback.EasyCallback;
import com.yang.easyhttp.callback.EasyStringCallback;
import com.yang.easyhttp.request.EasyRequestParams;
import com.zy.coolbicycle.R;
import com.zy.coolbicycle.application.MyApplication;
import com.zy.coolbicycle.ui.activity.main.MainActivity;
import com.zy.coolbicycle.ui.fragment.user.UserFragment;
import com.zy.coolbicycle.widget.CircleImageView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.zy.coolbicycle.ui.fragment.user.UserFragment.dip2px;
/**
* 应用模块:
* 类描述:
* Created by 卢文钏 on 2020/4/9
*/
public class UserDetailActivity extends AppCompatActivity {
@BindView(R.id.iv_detail_avatar)
CircleImageView ivDetailAvatar; //头像
@BindView(R.id.tv_user_detail_nick_name)
TextView tvNickName; //昵称
@BindView(R.id.tv_user_detail_account)
TextView tvUserAccount; //账号
@BindView(R.id.tv_user_detail_email)
TextView tvUserEmail; //邮箱
@BindView(R.id.tv_join_time)
TextView tvJoinTime; //注册时间
private MyApplication mApplication;
private static final int TAKE_PHOTO_PERMISSION_REQUEST_CODE = 0; // 拍照的权限处理返回码
private static final int WRITE_SDCARD_PERMISSION_REQUEST_CODE = 1; // 读储存卡内容的权限处理返回码
private static final int TAKE_PHOTO_REQUEST_CODE = 3; // 拍照返回的 requestCode
private static final int CHOICE_FROM_ALBUM_REQUEST_CODE = 4; // 相册选取返回的 requestCode
private static final int CROP_PHOTO_REQUEST_CODE = 5; // 裁剪图片返回的 requestCode
private Uri photoUri = null;
private Uri photoOutputUri = null; // 图片最终的输出文件的 Uri
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_user_detail);
ButterKnife.bind(this);
/*
* 先判断用户以前有没有对我们的应用程序允许过读写内存卡内容的权限,
* 用户处理的结果在 onRequestPermissionResult 中进行处理
*/
if (ContextCompat.checkSelfPermission(UserDetailActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// 申请读写内存卡内容的权限
ActivityCompat.requestPermissions(UserDetailActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_SDCARD_PERMISSION_REQUEST_CODE);
}
getLoginInfo();
initData();
showActionBar();
}
@OnClick({R.id.tv_user_detail_account, R.id.tv_join_time})
public void Unchangeable(View view) {
TipDialog.show(UserDetailActivity.this, "无法修改", TipDialog.TYPE.WARNING)
.setTipTime(1000)
.setTheme(DialogSettings.THEME.LIGHT);
}
/**
* 点击更换头像
*
* @param view
*/
@OnClick(R.id.iv_detail_avatar)
public void ivDetailAvatarOnClick(View view) {
List<String> datas = new ArrayList<>();
datas.add("拍照");
datas.add("从手机相册选择");
BottomMenu.build(UserDetailActivity.this)
.setCancelButtonText("取消")
.setTheme(DialogSettings.THEME.LIGHT)
.setStyle(DialogSettings.STYLE.STYLE_KONGZUE)
.setMenuTextList(datas)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public void onClick(String text, int index) {
switch (index) {
case 0:
if (ContextCompat.checkSelfPermission(UserDetailActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
//下面是对调用相机拍照权限进行申请
ActivityCompat.requestPermissions(UserDetailActivity.this,
new String[]{Manifest.permission.CAMERA,}, TAKE_PHOTO_PERMISSION_REQUEST_CODE);
} else {
openCamera(); // 打开相机
}
break;
case 1:
openGallery(); // 打开相册
break;
}
}
}).show();
}
/**
* 打开相机
*/
private void openCamera() {
/**
* 设置拍照得到的照片的储存目录,因为我们访问应用的缓存路径并不需要读写内存卡的申请权限,
* 因此,这里为了方便,将拍照得到的照片存在这个缓存目录中
*/
File file = new File(getExternalCacheDir(), String.valueOf(System.currentTimeMillis()) + ".jpg");
System.out.println(file);
try {
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
photoUri = FileProvider.getUriForFile(this, "com.zy.coolbicycle.provider", file);
} else {
photoUri = Uri.fromFile(file); // Android 7.0 以前使用原来的方法来获取文件的 Uri
}
// 打开系统相机的 Action,等同于:"android.media.action.IMAGE_CAPTURE"
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 设置拍照所得照片的输出目录
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST_CODE);
}
/**
* 打开相册
*/
private void openGallery() {
// 打开系统图库的 Action,等同于: "android.intent.action.GET_CONTENT"
Intent choiceFromAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
// 设置数据类型为图片类型
choiceFromAlbumIntent.setType("image/*");
startActivityForResult(choiceFromAlbumIntent, CHOICE_FROM_ALBUM_REQUEST_CODE);
}
/**
* 裁剪图片
*/
private void cropPhoto(Uri inputUri) {
// 调用系统裁剪图片的 Action
Intent cropPhotoIntent = new Intent("com.android.camera.action.CROP");
// 设置数据Uri 和类型
cropPhotoIntent.setDataAndType(inputUri, "image/*");
// 授权应用读取 Uri,这一步要有,不然裁剪程序会崩溃
cropPhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// 设置图片的最终输出目录
cropPhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
photoOutputUri = Uri.parse("file:////sdcard/upload_head.jpg"));
startActivityForResult(cropPhotoIntent, CROP_PHOTO_REQUEST_CODE);
}
/**
* 动态获取权限
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
// 调用相机拍照:
case TAKE_PHOTO_PERMISSION_REQUEST_CODE:
// 如果用户授予权限,那么打开相机拍照
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_SHORT).show();
}
break;
// 打开相册选取:
case WRITE_SDCARD_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(this, "读写内存卡内容权限被拒绝", Toast.LENGTH_SHORT).show();
}
break;
}
}
/**
* 判断用户选择头像的方式
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case TAKE_PHOTO_REQUEST_CODE:
cropPhoto(photoUri);
break;
case CHOICE_FROM_ALBUM_REQUEST_CODE:
cropPhoto(data.getData());
break;
case CROP_PHOTO_REQUEST_CODE:
File file = new File(photoOutputUri.getPath());
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(photoOutputUri.getPath());
ivDetailAvatar.setImageBitmap(bitmap);
upLoadFile(file, mApplication.getLoginUser().getU_account());
// file.delete(); // 选取完后删除照片
} else {
Toast.makeText(this, "找不到照片", Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* 上传头像
*
* @param file 头像文件
* @param currentUser 当前用户
*/
private void upLoadFile(File file, String currentUser) {
System.out.println("文件名:" + file.getName() + ",文件绝对路径:" + file.getAbsolutePath());
RequestBody fileBody2 = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("account", currentUser)
.addFormDataPart("image", file.getName(), fileBody2)
.build();
Request request = new Request.Builder()
.url(UserDetailActivity.this.getApplication().getString(R.string.server_address) + "/load/upload.php")
.post(requestBody)
.build();
final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
OkHttpClient okHttpClient = httpBuilder
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
final String newHeadUrl = response.body().string();//获取服务器返回的新头像的地址
mApplication.getLoginUser().setU_head(newHeadUrl);//设置新头像
System.out.println(newHeadUrl);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response);
}
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e);
}
});
}
/**
* 点击更改昵称
*
* @param view
*/
@OnClick(R.id.tv_user_detail_nick_name)
public void tvUserNickNameOnClick(View view) {
InputDialog.show(UserDetailActivity.this, "设置昵称", "设置一个好听的昵称吧", "确定", "取消")
.setTheme(DialogSettings.THEME.LIGHT)
.setStyle(DialogSettings.STYLE.STYLE_KONGZUE)
.setOnOkButtonClickListener(new OnInputDialogButtonClickListener() {
@Override
public boolean onClick(BaseDialog baseDialog, View v, String inputStr) {
//向服务器发送请求
EasyRequestParams params = new EasyRequestParams();
params.put("account", mApplication.getLoginUser().getU_account());
params.put("nickname", inputStr);
EasyHttpClient.post(UserDetailActivity.this.getApplication().getString(R.string.server_address) + "/load/nickname.php",
params, new EasyStringCallback() {
@Override
public void onSuccess(String content) {
mApplication.getLoginUser().setU_nickname(content);
tvNickName.setText(content);
}
@Override
public void onFailure(Throwable error, String content) {
}
});
return false;
}
})
.setOnCancelButtonClickListener(new OnInputDialogButtonClickListener() {
@Override
public boolean onClick(BaseDialog baseDialog, View v, String inputStr) {
baseDialog.doDismiss();
return false;
}
});
}
/**
* 点击更换邮箱
*
* @param view
*/
@OnClick(R.id.tv_user_detail_email)
public void tvUserEmailOnClick(View view) {
InputDialog.show(UserDetailActivity.this, "设置邮箱", "请输入您的邮箱", "确定", "取消")
.setTheme(DialogSettings.THEME.LIGHT)
.setStyle(DialogSettings.STYLE.STYLE_KONGZUE)
.setOnOkButtonClickListener(new OnInputDialogButtonClickListener() {
@Override
public boolean onClick(BaseDialog baseDialog, View v, String inputStr) {
//向服务器请求
EasyRequestParams params = new EasyRequestParams();
params.put("account", mApplication.getLoginUser().getU_account());
params.put("email", inputStr);
EasyHttpClient.post(UserDetailActivity.this.getApplication().getString(R.string.server_address) + "/load/email.php",
params, new EasyStringCallback() {
@Override
public void onSuccess(String content) {
mApplication.getLoginUser().setU_email(content);
tvUserEmail.setText(content);
}
@Override
public void onFailure(Throwable error, String content) {
Toast.makeText(UserDetailActivity.this, "连接服务器失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
}
});
return false;
}
})
.setOnCancelButtonClickListener(new OnInputDialogButtonClickListener() {
@Override
public boolean onClick(BaseDialog baseDialog, View v, String inputStr) {
baseDialog.doDismiss();
return false;
}
});
}
public void getLoginInfo() {
mApplication = (MyApplication) getApplication();
}
private void initData() {
Glide.with(this) //设置context
.load(mApplication.getLoginUser().getU_head()) //图片url地址
.override(dip2px(this, 62), dip2px(this, 62))//固定大小
.centerCrop()//图片适应
.into(ivDetailAvatar);//图片显示的imageview
tvNickName.setText(mApplication.getLoginUser().getU_nickname());
tvUserAccount.setText(mApplication.getLoginUser().getU_account());
tvUserEmail.setText(mApplication.getLoginUser().getU_email());
tvJoinTime.setText(mApplication.getLoginUser().getU_ride_time());//这是骑行年龄
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:// 点击返回图标事件
startActivity(new Intent(UserDetailActivity.this, MainActivity.class));
this.finish();
default:
return super.onOptionsItemSelected(item);
}
}
/**
* 显示顶部导航栏
*/
public void showActionBar() {
//顶部导航
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("个人资料");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
}
}
| 39.08742 | 144 | 0.570532 |
4bacd538c4c57e4bfa3b3aefcac9380d0bb4fa4e | 401 | package me.lisirrx.fastR.serialization;
import java.io.Serializable;
/**
* @author lihan lisirrx@gmail.com
* @date 2019/5/19
*/
class TestData implements Serializable {
String inner;
public TestData(String inner) {
this.inner = inner;
}
public String getInner() {
return inner;
}
public void setInner(String inner) {
this.inner = inner;
}
} | 16.708333 | 40 | 0.633416 |
2211ec71763bd241d2d413afe4b7fe3ff70b7e49 | 4,230 | package com.orasi.utils.dataHelpers.personFactory.seeds;
import java.util.Random;
public class LastNames {
private static String[] names = {
"adams",
"alexander",
"allen",
"alvarez",
"anderson",
"andrews",
"armstrong",
"arnold",
"austin",
"bailey",
"baker",
"banks",
"barnes",
"barnett",
"barrett",
"bates",
"beck",
"bell",
"bennett",
"berry",
"bishop",
"black",
"bowman",
"boyd",
"bradley",
"brewer",
"brooks",
"brown",
"bryant",
"burke",
"burns",
"burton",
"butler",
"byrd",
"caldwell",
"campbell",
"carlson",
"carpenter",
"carr",
"carroll",
"carter",
"castillo",
"castro",
"chambers",
"chapman",
"chavez",
"clark",
"cole",
"coleman",
"collins",
"cook",
"cooper",
"cox",
"craig",
"crawford",
"cruz",
"cunningham",
"curtis",
"daniels",
"davidson",
"davis",
"day",
"dean",
"diaz",
"dixon",
"douglas",
"duncan",
"dunn",
"edwards",
"elliott",
"ellis",
"evans",
"ferguson",
"fernandez",
"fields",
"fisher",
"fleming",
"fletcher",
"flores",
"ford",
"foster",
"fowler",
"fox",
"franklin",
"frazier",
"freeman",
"fuller",
"garcia",
"gardner",
"garrett",
"garza",
"george",
"gibson",
"gilbert",
"gomez",
"gonzales",
"gonzalez",
"gordon",
"graham",
"grant",
"graves",
"gray",
"green",
"gregory",
"griffin",
"gutierrez",
"hale",
"hall",
"hamilton",
"hansen",
"hanson",
"harper",
"harris",
"harrison",
"hart",
"harvey",
"hawkins",
"hayes",
"henderson",
"henry",
"hernandez",
"herrera",
"hicks",
"hill",
"hoffman",
"holland",
"holmes",
"holt",
"hopkins",
"horton",
"howard",
"howell",
"hudson",
"hughes",
"hunt",
"hunter",
"jackson",
"jacobs",
"james",
"jenkins",
"jennings",
"jensen",
"jimenez",
"johnson",
"johnston",
"jones",
"jordan",
"kelley",
"kelly",
"kennedy",
"kim",
"king",
"knight",
"kuhn",
"lambert",
"lane",
"larson",
"lawrence",
"lawson",
"lee",
"lewis",
"little",
"long",
"lopez",
"lowe",
"lucas",
"lynch",
"marshall",
"martin",
"martinez",
"mason",
"matthews",
"may",
"mccoy",
"mcdonalid",
"mckinney",
"medina",
"mendoza",
"meyer",
"miles",
"miller",
"mills",
"mitchell",
"mitchelle",
"montgomery",
"moore",
"morales",
"moreno",
"morgan",
"morris",
"morrison",
"murphy",
"murray",
"myers",
"neal",
"nelson",
"newman",
"nguyen",
"nichols",
"obrien",
"oliver",
"olson",
"ortiz",
"owens",
"palmer",
"parker",
"patterson",
"payne",
"pearson",
"pena",
"perez",
"perkins",
"perry",
"peters",
"peterson",
"phillips",
"pierce",
"porter",
"powell",
"price",
"ramirez",
"ramos",
"ray",
"reed",
"reid",
"reyes",
"reynolds",
"rhodes",
"rice",
"richards",
"richardson",
"riley",
"rivera",
"roberts",
"robertson",
"robinson",
"rodriguez",
"rodriquez",
"rogers",
"romero",
"rose",
"ross",
"ruiz",
"russell",
"ryan",
"sanchez",
"sanders",
"schmidt",
"scott",
"shaw",
"shelton",
"silva",
"simmmons",
"simmons",
"simpson",
"sims",
"smith",
"snyder",
"soto",
"spencer",
"stanley",
"stephens",
"stevens",
"steward",
"stewart",
"stone",
"sullivan",
"sutton",
"taylor",
"terry",
"thomas",
"thompson",
"torres",
"tucker",
"turner",
"vargas",
"vasquez",
"wade",
"wagner",
"walker",
"wallace",
"walters",
"ward",
"warren",
"washington",
"watkins",
"watson",
"watts",
"weaver",
"webb",
"welch",
"wells",
"west",
"wheeler",
"white",
"williams",
"williamson",
"willis",
"wilson",
"wood",
"woods",
"wright",
"young"
};
public static String getLastName(){
Random r = new Random();
return names[r.nextInt(names.length)];
}
}
| 13.343849 | 56 | 0.479433 |
a542203d1b04d1943bbada1fb0379ac3c1fa6c6c | 2,044 | /******************************************************************************
* Project Doppelgänger *
* *
* Copyright (c) 2020. Elex. All Rights Reserved. *
* https://www.elex-project.com/ *
******************************************************************************/
package com.elex_project.doppelganger;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
public final class CallableStatement extends BaseCallableStatementWrapper {
public CallableStatement(final java.sql.CallableStatement statement) {
super(statement);
}
public @NotNull CompletableFuture<Integer> executeUpdate(final @NotNull ExecutorService executorService) {
final CompletableFuture<Integer> future = new CompletableFuture<>();
executorService.execute(() -> {
try {
future.complete(executeUpdate());
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}
public @NotNull CompletableFuture<Boolean> execute(final @NotNull ExecutorService executorService) {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
executorService.execute(() -> {
try {
future.complete(execute());
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}
public @NotNull CompletableFuture<ResultSet> executeQuery(final @NotNull ExecutorService executorService) {
final CompletableFuture<ResultSet> future = new CompletableFuture<>();
executorService.execute(() -> {
try {
future.complete(executeQuery());
} catch (SQLException e) {
future.completeExceptionally(e);
}
});
return future;
}
@Override
public ResultSet executeQuery() throws SQLException {
return new ResultSet(super.executeQuery());
}
}
| 32.967742 | 108 | 0.608121 |
e5813d369979c8ff7dc138b2f0e4ed4aa23440a9 | 7,306 | package com.study.riseof.contactBookAndWeather.contactBook.model;
public class Contact {
private final String EMPTY_STRING = "";
private int id;
private final String firstName;
private final String firstNameInitialLetter;
private final String secondName;
private final String secondNameInitialLetter;
private final String patronymic;
private final String patronymicInitialLetter;
private final String lastName;
private final String lastNameInitialLetter;
private final String mobilePhone;
private final String homePhone;
private final String personalWebsite;
private final String eMail;
private final String flat;
private final String house;
private final String street;
private final String city;
private final String state;
private final String country;
private final String postCode;
public Contact() {
this.firstName = EMPTY_STRING;
this.firstNameInitialLetter = EMPTY_STRING;
this.secondName = EMPTY_STRING;
this.secondNameInitialLetter = EMPTY_STRING;
this.patronymic = EMPTY_STRING;
this.patronymicInitialLetter = EMPTY_STRING;
this.lastName = EMPTY_STRING;
this.lastNameInitialLetter = EMPTY_STRING;
this.mobilePhone = EMPTY_STRING;
this.homePhone = EMPTY_STRING;
this.personalWebsite = EMPTY_STRING;
this.eMail = EMPTY_STRING;
this.flat = EMPTY_STRING;
this.house = EMPTY_STRING;
this.street = EMPTY_STRING;
this.city = EMPTY_STRING;
this.state = EMPTY_STRING;
this.country = EMPTY_STRING;
this.postCode = EMPTY_STRING;
}
public Contact(String firstName,
String firstNameInitialLetter,
String secondName,
String secondNameInitialLetter,
String patronymic,
String patronymicInitialLetter,
String lastName,
String lastNameInitialLetter,
String mobilePhone,
String homePhone,
String personalWebsite,
String eMail,
String flat,
String house,
String street,
String city,
String state,
String country,
String postCode) {
this.firstName = firstName;
this.firstNameInitialLetter = firstNameInitialLetter;
this.secondName = secondName;
this.secondNameInitialLetter = secondNameInitialLetter;
this.patronymic = patronymic;
this.patronymicInitialLetter = patronymicInitialLetter;
this.lastName = lastName;
this.lastNameInitialLetter = lastNameInitialLetter;
this.mobilePhone = mobilePhone;
this.homePhone = homePhone;
this.personalWebsite = personalWebsite;
this.eMail = eMail;
this.flat = flat;
this.house = house;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.postCode = postCode;
}
public Contact(int id,
String firstName,
String firstNameInitialLetter,
String secondName,
String secondNameInitialLetter,
String patronymic,
String patronymicInitialLetter,
String lastName,
String lastNameInitialLetter,
String mobilePhone,
String homePhone,
String personalWebsite,
String eMail,
String flat,
String house,
String street,
String city,
String state,
String country,
String postCode) {
this.id = id;
this.firstName = firstName;
this.firstNameInitialLetter = firstNameInitialLetter;
this.secondName = secondName;
this.secondNameInitialLetter = secondNameInitialLetter;
this.patronymic = patronymic;
this.patronymicInitialLetter = patronymicInitialLetter;
this.lastName = lastName;
this.lastNameInitialLetter = lastNameInitialLetter;
this.mobilePhone = mobilePhone;
this.homePhone = homePhone;
this.personalWebsite = personalWebsite;
this.eMail = eMail;
this.flat = flat;
this.house = house;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.postCode = postCode;
}
public Contact(RandomContact randomContact) {
this.firstName = randomContact.getFirstName();
this.firstNameInitialLetter = randomContact.getFirstNameInitialLetter();
this.secondName = randomContact.getSecondName();
this.secondNameInitialLetter = randomContact.getSecondNameInitialLetter();
this.patronymic = randomContact.getPatronymic();
this.patronymicInitialLetter = randomContact.getPatronymicInitialLetter();
this.lastName = randomContact.getLastName();
this.lastNameInitialLetter = randomContact.getLastNameInitialLetter();
this.mobilePhone = randomContact.getMobilePhone();
this.homePhone = randomContact.getHomePhone();
this.personalWebsite = randomContact.getPersonalWebsite();
this.eMail = randomContact.getEMail();
this.flat = randomContact.getFlat();
this.house = randomContact.getHouse();
this.street = randomContact.getStreet();
this.city = randomContact.getCity();
this.state = randomContact.getState();
this.country = randomContact.getCountry();
this.postCode = randomContact.getPostCode();
}
public int getId() {
return id;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
public String getEMail() {
return eMail;
}
public String getFirstName() {
return firstName;
}
public String getFlat() {
return flat;
}
public String getHomePhone() {
return homePhone;
}
public String getHouse() {
return house;
}
public String getLastName() {
return lastName;
}
public String getMobilePhone() {
return mobilePhone;
}
public String getPatronymic() {
return patronymic;
}
public String getPersonalWebsite() {
return personalWebsite;
}
public String getPostCode() {
return postCode;
}
public String getSecondName() {
return secondName;
}
public String getState() {
return state;
}
public String getStreet() {
return street;
}
public String getFirstNameInitialLetter() {
return firstNameInitialLetter;
}
public String getSecondNameInitialLetter() {
return secondNameInitialLetter;
}
public String getPatronymicInitialLetter() {
return patronymicInitialLetter;
}
public String getLastNameInitialLetter() {
return lastNameInitialLetter;
}
}
| 31.356223 | 82 | 0.615385 |
f3b2dfdd0a9c39b672fc1ed3fc570a6eef0dd5e5 | 668 | package com.shura.im.client.handle;
import com.shura.im.client.listener.CustomMsgHandleListener;
/**
* @Author: Garvey
* @Created: 2021/10/24
* @Description: 消息回调 Bean
*/
public class MsgHandleCaller {
/**
* 回调接口
*/
private CustomMsgHandleListener msgHandleListener ;
public MsgHandleCaller(CustomMsgHandleListener msgHandleListener) {
this.msgHandleListener = msgHandleListener;
}
public CustomMsgHandleListener getMsgHandleListener() {
return msgHandleListener;
}
public void setMsgHandleListener(CustomMsgHandleListener msgHandleListener) {
this.msgHandleListener = msgHandleListener;
}
}
| 23.034483 | 81 | 0.724551 |
21f1ef5d4984c76fc316cb72644d2eeb07fe3252 | 793 | package de.danoeh.antennapod.core.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CollectionTestUtil {
public static <T> List<? extends T> concat(T item, List<? extends T> list) {
List<T> res = new ArrayList<>(list);
res.add(0, item);
return res;
}
public static <T> List<? extends T> concat(List<? extends T> list, T item) {
List<T> res = new ArrayList<>(list);
res.add(item);
return res;
}
public static <T> List<? extends T> concat(List<? extends T> list1, List<? extends T> list2) {
List<T> res = new ArrayList<>(list1);
res.addAll(list2);
return res;
}
public static <T> List<T> list(T... a) {
return Arrays.asList(a);
}
}
| 25.580645 | 98 | 0.592686 |
8c1cdddebc4c1594778016f74c68b6ccb86a2006 | 16,049 | /*
* Copyright 2017 ~ 2050 the original author or authors <Wanglsir@gmail.com, 983708408@qq.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.dopaas.lcdp.codegen.engine.specs;
import static com.wl4g.component.common.collection.CollectionUtils2.disDupCollection;
import static com.wl4g.component.common.collection.CollectionUtils2.safeList;
import static com.wl4g.component.common.lang.Assert2.hasTextOf;
import static com.wl4g.component.common.lang.Assert2.notEmptyOf;
import static com.wl4g.component.common.reflect.ReflectionUtils2.doWithLocalFields;
import static com.wl4g.component.common.reflect.ReflectionUtils2.getField;
import static com.wl4g.component.common.reflect.ReflectionUtils2.makeAccessible;
import static com.wl4g.dopaas.lcdp.codegen.engine.specs.BaseSpecs.CommentExtractor.ofExtractor;
import static java.lang.String.format;
import static java.lang.String.valueOf;
import static java.util.Locale.US;
import static java.util.Objects.isNull;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.replaceEach;
import static org.apache.commons.lang3.StringUtils.replacePattern;
import static org.apache.commons.lang3.StringUtils.trim;
import static org.apache.commons.lang3.SystemUtils.LINE_SEPARATOR;
//import org.apdplat.word.WordSegmenter;
//import org.apdplat.word.segmentation.Word;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.google.common.collect.Lists;
import com.wl4g.component.common.bean.ConfigOption;
import com.wl4g.component.common.collection.CollectionUtils2;
import com.wl4g.component.common.id.SnowflakeIdGenerator;
import com.wl4g.component.common.lang.StringUtils2;
import com.wl4g.dopaas.common.bean.lcdp.GenTableColumn;
import com.wl4g.dopaas.common.bean.lcdp.extra.ExtraOptionDefinition.GenExtraOption;
import com.wl4g.dopaas.common.bean.lcdp.extra.TableExtraOptionDefinition.GenTableExtraOption;
import com.wl4g.dopaas.lcdp.codegen.utils.BuiltinColumnDefinition;
/**
* Generic base specification utility.
*
* @author Wangl.sir <wanglsir@gmail.com, 983708408@qq.com>
* @version v1.0 2020-09-16
* @since
*/
public class BaseSpecs {
// --- Naming. ---
/**
* Gets the string that converts the first letter to uppercase.</br>
* Refer to freeMarker: ""?cap_first
*/
public static String capf(@Nullable String str) {
if (isBlank(str)) {
return str;
}
char[] cs = str.toCharArray();
if (97 <= cs[0] && cs[0] <= 122) {
cs[0] -= 32;
}
return valueOf(cs);
}
/**
* Gets the string that converts the first letter to lowercase.</br>
* Refer to freeMarker: ""?uncap_first
*/
public static String uncapf(@Nullable String str) {
if (isBlank(str)) {
return str;
}
char[] cs = str.toCharArray();
if (65 <= cs[0] && cs[0] <= 90) {
cs[0] += 32;
}
return valueOf(cs);
}
/**
* Gets the string that converts the all letter to upper case
*/
public static String uCase(@Nullable String str) {
if (isBlank(str)) {
return str;
}
return str.toUpperCase(US);
}
/**
* Gets the string that converts the all letter to lower case
*/
public static String lCase(@Nullable String str) {
if (isBlank(str)) {
return str;
}
return str.toLowerCase(US);
}
/**
* Generate next ID.
*
* @return
*/
public static long genNextId() {
return SnowflakeIdGenerator.getDefault().nextId();
}
// --- Comments. ---
/**
* Clean up and normalize comment strings, such as replacing line breaks,
* double quotes, and so on. </br>
* </br>
*
* for example (unix):
*
* <pre>
* {@link cleanComment("abcdefgh123456", null, null)} => abcdefgh123456
* {@link cleanComment("abcd\refgh123456", null, null)} => abcd efgh123456
* {@link cleanComment("abcd\nefgh123456", null, null)} => abcd efgh123456
* {@link cleanComment("abcd\r\nefgh123456", null, null)} => abcd efgh123456
* {@link cleanComment("abcd\r\nefgh"jack"123456", null, null)} => abcd efgh'jack'123456
* </pre>
*
* @param str
* @return
*/
public static String cleanComment(@Nullable String str) {
return cleanComment(str, null, null);
}
/**
* Clean up and normalize comment strings, such as replacing line breaks,
* double quotes, and so on. </br>
* </br>
*
* for example (unix):
*
* <pre>
* {@link cleanComment("abcdefgh123456", null, null)} => abcdefgh123456
* {@link cleanComment("abcd\refgh123456", null, null)} => abcd efgh123456
* {@link cleanComment("abcd\nefgh123456", null, null)} => abcd efgh123456
* {@link cleanComment("abcd\r\nefgh123456", null, null)} => abcd efgh123456
* {@link cleanComment("abcd\r\nefgh"jack"123456", null, null)} => abcd efgh'jack'123456
* </pre>
*
* @param str
* @param lineReplacement
* @param doubleQuotesReplacement
* @return
*/
public static String cleanComment(@Nullable String str, @Nullable String lineReplacement,
@Nullable String doubleQuotesReplacement) {
if (isBlank(str)) {
return str;
}
lineReplacement = isBlank(lineReplacement) ? " " : lineReplacement;
doubleQuotesReplacement = isBlank(doubleQuotesReplacement) ? "'" : doubleQuotesReplacement;
// Escape line separators.
// Match and replace Windows newline character first: '\r\n'
str = replacePattern(str, "\r\n|\n|\r", lineReplacement);
// Escape double quotes.
return replacePattern(str, "\"", doubleQuotesReplacement);
}
/**
* It is useful to minimize and optimize the compression of comment strings,
* such as for menu and list header display. </br>
* </br>
*
* @param str
* @param extractor
* @return
*/
public static String extractComment(@Nullable String str, @NotBlank String extractor) {
return extractComment(str, ofExtractor(hasTextOf(extractor, "extractor")));
}
/**
* It is useful to minimize and optimize the compression of comment strings,
* such as for menu and list header display. </br>
* </br>
*
* @param str
* @param extractor
* @return
*/
public static String extractComment(@Nullable String str, @NotNull CommentExtractor extractor) {
if (isBlank(str)) {
return str;
}
return cleanComment(extractor.getHandler().extract(str));
}
/**
* Convert content to multiline comments format, and return without any
* action if the original content conforms to the format of multiline
* comments.
*
* @param sourceContent
* @return
* @see {@link com.wl4g.dopaas.lcdp.codegen.engine.specs.BaseSpecsTests#wrapCommentCase()}
*/
public static String wrapMultiComment(@Nullable String sourceContent) {
if (isBlank(sourceContent)) { // Optional
return EMPTY;
}
// Nothing do
if (sourceContent.contains("/*") && sourceContent.contains("*/")) {
return sourceContent;
}
StringBuffer newCopyright = new StringBuffer("/*");
try (BufferedReader bfr = new BufferedReader(new StringReader(sourceContent));) {
String line = null;
while (!isNull(line = bfr.readLine())) {
newCopyright.append(LINE_SEPARATOR);
newCopyright.append(" * ");
newCopyright.append(line);
}
newCopyright.append(LINE_SEPARATOR);
newCopyright.append(" */");
} catch (IOException e) {
throw new IllegalStateException(e);
}
return newCopyright.toString();
}
/**
* Convert content to single comments format, and return without any action
* if the original content conforms to the format of single comments.
*
* @param sourceContent
* @param markHead
* @return
* @see {@link com.wl4g.dopaas.lcdp.codegen.engine.specs.BaseSpecsTests#wrapCommentCase()}
*/
public static String wrapSingleComment(@Nullable String sourceContent, @NotBlank String markHead) {
hasTextOf(markHead, "markHead");
if (isBlank(sourceContent)) { // Optional
return EMPTY;
}
// Nothing do
if (trim(sourceContent).startsWith(markHead)) {
return sourceContent;
}
StringBuffer newCopyright = new StringBuffer(markHead);
try (BufferedReader bfr = new BufferedReader(new StringReader(sourceContent));) {
String line = null;
while (!isNull(line = bfr.readLine())) {
newCopyright.append(LINE_SEPARATOR);
newCopyright.append(markHead);
newCopyright.append(" ");
newCopyright.append(line);
}
newCopyright.append(LINE_SEPARATOR);
newCopyright.append(markHead);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return newCopyright.toString();
}
// --- Functions. ---
/**
* Check if the state is true.
*
* @param assertion
* @return
*/
public static boolean isTrue(@Nullable String value) {
return isTrue(value, false);
}
/**
* Check if the state is true.
*
* @param assertion
* @param defaultValue
* @return
*/
public static boolean isTrue(@Nullable String value, boolean defaultValue) {
return StringUtils2.isTrue(value, defaultValue);
}
/**
* Check whether the specified extension configuration item exists. see:
* {@link GenExtraOption} or {@link GenTableExtraOption}
*
* @param configuredOptions
* @param name
* @param value
* @return
*/
public static boolean isConf(@Nullable List<? extends ConfigOption> configuredOptions, @NotBlank String name,
@NotBlank String value) {
hasTextOf(name, "configKey");
hasTextOf(value, "configValue");
// Extra config optional
if (CollectionUtils2.isEmpty(configuredOptions)) {
return false;
}
// Verify name and value contains in options.
for (ConfigOption opt : configuredOptions) {
if (equalsIgnoreCase(opt.getName(), name) && equalsIgnoreCase(opt.getSelectedValue(), value)) {
return true;
}
}
return false;
}
/**
* Check whether the specified extension configuration item exists. see:
* {@link GenExtraOption} or {@link GenTableExtraOption}
*
* @param configuredOptions
* @param name
* @param values
* @return
*/
public static boolean isConfAnd(@Nullable List<? extends ConfigOption> configuredOptions, @NotBlank String name,
@NotEmpty String... values) {
notEmptyOf(values, "configValues");
for (String value : values) {
if (!isConf(configuredOptions, name, value)) {
return false;
}
}
return true;
}
/**
* Check whether the specified extension configuration item exists. see:
* {@link GenExtraOption} or {@link GenTableExtraOption}
*
* @param configuredOptions
* @param name
* @param values
* @return
*/
public static boolean isConfOr(@Nullable List<? extends ConfigOption> configuredOptions, @NotBlank String name,
@NotEmpty String... values) {
notEmptyOf(values, "configValues");
for (String value : values) {
if (isConf(configuredOptions, name, value)) {
return true;
}
}
return false;
}
/**
* Filter out the columns displayed on the front page of
* {@link GenTableColumn}.
*
* @param <T>
* @param columns
* @param condition
* @return
*/
public static List<GenTableColumn> filterColumns(@Nullable List<GenTableColumn> columns) {
return filterColumns(columns, BuiltinColumnDefinition.COLUMN_NAME_VALUES);
}
/**
* Filter out the columns displayed on the front page of
* {@link GenTableColumn}.
*
* @param <T>
* @param columns
* @param condition
* @return
*/
public static List<GenTableColumn> filterColumns(@Nullable List<GenTableColumn> columns,
@Nullable List<String> withoutColumnNames) {
List<String> conditions = safeList(withoutColumnNames);
return safeList(columns).stream()
.filter(e -> !conditions.contains(e.getAttrName()) && !conditions.contains(e.getColumnName())).collect(toList());
}
/**
* Remove duplicate collection elements.
*
* @param list
* @return
*/
public static List<Object> distinctList(List<Object> list) {
return Lists.newArrayList(disDupCollection(list).toArray(new Object[0]));
}
/**
* Transform {@link GenTableColumn} attributes.
*
* @param columns
* @param fieldName
* @return
*/
public static List<Object> transformColumns(@Nullable List<GenTableColumn> columns, @NotBlank String fieldName) {
hasTextOf(fieldName, "fieldName");
List<Object> transformed = new ArrayList<>(isNull(columns) ? 0 : columns.size());
safeList(columns).forEach(c -> {
doWithLocalFields(GenTableColumn.class, f -> {
if (f.getName().equals(fieldName)) {
makeAccessible(f);
transformed.add(getField(f, c));
}
});
});
return transformed;
}
/**
* Check if there is a matches value of the field of {@link List}.
*
* @param values
* @param matchValue
* @return
*/
public static boolean hasFieldValue(@Nullable List<Object> values, @NotBlank String matchValue) {
hasTextOf(matchValue, "matchValue");
return safeList(values).stream().filter(v -> !isNull(v) && v.equals(matchValue)).findFirst().isPresent();
}
/**
* Useful comment extractor.
*
* @author Wangl.sir <wanglsir@gmail.com, 983708408@qq.com>
* @version 2020-10-07
* @sine v1.0.0
* @see
*/
public static enum CommentExtractor {
/**
* <pre>
* case1: 统计类型(1.计划完成 2.实际完成) => words[统计, 类型, 1, 计划, 2]
* </pre>
*/
// wordSeg(str -> {
// // Chinese word segmentation keyword extraction.
// List<Word> words = safeList(WordSegmenter.seg(str));
// if (words.isEmpty()) {
// return str;
// }
// StringBuffer comment = new StringBuffer();
// for (int i = 0; i < words.size(); i++) {
// Word word = words.get(i);
// if (comment.length() <= 4) {
// comment.append(word.getText());
// } else {
// break;
// }
// }
// return comment.toString().replace("表", EMPTY);
// }),
/**
* <pre>
* case1: 用户表 => 用户
* case2: 用户类型(1:普通用户,2:vip客户) => 用户
* </pre>
*/
simple(str -> {
String extracted = str.substring(0, Math.min(str.length(), 5));
return replaceEach(extracted, new String[] { ",", ",", "。", "(", ")", "(", ")", "表" },
new String[] { EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY });
});
private final ExtractHandler handler;
private CommentExtractor(ExtractHandler handler) {
this.handler = handler;
}
public ExtractHandler getHandler() {
return handler;
}
/**
* Parse comment extractor of name
*
* @param extractorName
* @return
*/
public static final CommentExtractor ofExtractor(String extractorName) {
for (CommentExtractor ext : values()) {
if (equalsIgnoreCase(ext.name(), extractorName)) {
return ext;
}
}
throw new IllegalArgumentException(format("No such comment extractor of %s", extractorName));
}
/**
* {@link ExtractHandler}
*/
static interface ExtractHandler {
String extract(@Nullable String str);
}
}
} | 29.556169 | 118 | 0.671818 |
053540f969431bb1a9e2d7373e5b9f9954b949ab | 303 | package tk.snapz.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SnapzApplication {
public static void main(String[] args) {
SpringApplication.run(SnapzApplication.class, args);
}
}
| 21.642857 | 68 | 0.815182 |
27ab697e461eb74dad2193f17da615de3a023c97 | 353 | package de.gw.auto.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import de.gw.auto.domain.Auto;
import de.gw.auto.domain.Benutzer;
public interface AutoRepository extends JpaRepository<Auto, Integer> {
public Auto findByKfz(String kfz);
public List<Auto> findByUsers(List<Benutzer> benutzers);
}
| 25.214286 | 70 | 0.8017 |
b55973d9cff8067e1f136a354636d48bd61c0903 | 11,210 | package org.seckill.service.impl;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.seckill.api.constant.SeckillStatusConstant;
import org.seckill.api.dto.Exposer;
import org.seckill.api.dto.SeckillExecution;
import org.seckill.api.dto.SeckillInfo;
import org.seckill.api.enums.SeckillStatEnum;
import org.seckill.api.exception.RepeatKillException;
import org.seckill.api.exception.SeckillCloseException;
import org.seckill.api.exception.SeckillException;
import org.seckill.api.service.SeckillService;
import org.seckill.dao.GoodsMapper;
import org.seckill.dao.RedisDao;
import org.seckill.dao.SeckillMapper;
import org.seckill.dao.SuccessKilledMapper;
import org.seckill.dao.ext.ExtSeckillMapper;
import org.seckill.entity.*;
import org.seckill.service.common.trade.alipay.AlipayRunner;
import org.seckill.service.inner.SeckillExecutor;
import org.seckill.service.mq.MqTask;
import org.seckill.service.util.PropertiesUtil;
import org.seckill.service.util.ZookeeperLockUtil;
import org.seckill.util.common.util.DateUtil;
import org.seckill.util.common.util.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
/**
* 秒杀接口实现类
*
* @author heng
* @date 2016/7/16
*/
@Service
@Slf4j
public class SeckillServiceImpl extends AbstractServiceImpl<SeckillMapper, SeckillExample, Seckill> implements SeckillService, SeckillExecutor, InitializingBean {
@Autowired
private AlipayRunner alipayRunner;
@Autowired
private ExtSeckillMapper extSeckillMapper;
@Autowired
private SuccessKilledMapper successKilledMapper;
@Autowired
private RedisDao redisDao;
@Autowired
private GoodsMapper goodsMapper;
@Resource(name = "taskExecutor")
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
private MqTask mqTask;
@Autowired
private PropertiesUtil propertiesUtil;
@Autowired
private ZookeeperLockUtil zookeeperLockUtil;
private RedissonClient redissonClient;
public void setAlipayRunner(AlipayRunner alipayRunner) {
this.alipayRunner = alipayRunner;
}
public void setExtSeckillMapper(ExtSeckillMapper extSeckillMapper) {
this.extSeckillMapper = extSeckillMapper;
}
public void setSuccessKilledMapper(SuccessKilledMapper successKilledMapper) {
this.successKilledMapper = successKilledMapper;
}
public void setRedisDao(RedisDao redisDao) {
this.redisDao = redisDao;
}
public void setGoodsMapper(GoodsMapper goodsMapper) {
this.goodsMapper = goodsMapper;
}
@Override
public PageInfo getSeckillList(int pageNum, int pageSize) {
return selectByPage(new SeckillExample(), pageNum, pageSize);
}
@Override
public SeckillInfo getById(long seckillId) {
Seckill seckill = extSeckillMapper.selectByPrimaryKey(seckillId);
SeckillInfo seckillInfo = new SeckillInfo();
BeanUtils.copyProperties(seckill, seckillInfo);
Goods goods = goodsMapper.selectByPrimaryKey(seckill.getGoodsId());
seckillInfo.setGoodsName(goods.getName());
return seckillInfo;
}
@Override
public Exposer exportSeckillUrl(long seckillId) {
//从redis中获取缓存秒杀信息
Seckill seckill = redisDao.getSeckill(seckillId);
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
Date nowTime = new Date();
if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
}
String md5 = MD5Util.getMD5(seckillId);
return new Exposer(true, md5, seckillId);
}
@Transactional
@Override
public SeckillExecution executeSeckill(long seckillId, String userPhone, String md5) {
if (md5 == null || !md5.equals(MD5Util.getMD5(seckillId))) {
throw new SeckillException("seckill data rewrite");
}
Date nowTime = DateUtil.getNowTime();
try {
int updateCount = extSeckillMapper.reduceNumber(seckillId, nowTime);
if (updateCount <= 0) {
throw new SeckillCloseException("seckill is closed");
} else {
SuccessKilled successKilled = new SuccessKilled();
successKilled.setSeckillId(seckillId);
successKilled.setUserPhone(userPhone);
int insertCount = successKilledMapper.insertSelective(successKilled);
String QRfilePath = alipayRunner.trade_precreate(seckillId);
if (insertCount <= 0) {
throw new RepeatKillException("seckill repeated");
} else {
SuccessKilledKey key = new SuccessKilledKey();
key.setSeckillId(seckillId);
key.setUserPhone(userPhone);
return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, successKilledMapper.selectByPrimaryKey(key), QRfilePath);
}
}
} catch (SeckillCloseException e1) {
log.info(e1.getMessage(), e1);
throw e1;
} catch (RepeatKillException e2) {
log.info(e2.getMessage(), e2);
throw e2;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new SeckillException("seckill inner error:" + e.getMessage());
}
}
@Override
public int addSeckill(Seckill seckill) {
return extSeckillMapper.insert(seckill);
}
@Override
public int deleteSeckill(Long seckillId) {
return extSeckillMapper.deleteByPrimaryKey(seckillId);
}
@Override
public int updateSeckill(Seckill seckill) {
return extSeckillMapper.updateByPrimaryKeySelective(seckill);
}
@Override
public Seckill selectById(Long seckillId) {
return extSeckillMapper.selectByPrimaryKey(seckillId);
}
@Override
public int deleteSuccessKillRecord(long seckillId) {
SuccessKilledExample example = new SuccessKilledExample();
example.createCriteria().andSeckillIdEqualTo(seckillId);
return successKilledMapper.deleteByExample(example);
}
@Override
public void executeWithSynchronized(Long seckillId, int executeTime) {
CountDownLatch countDownLatch = new CountDownLatch(executeTime);
for (int i = 0; i < executeTime; i++) {
int userId = i;
taskExecutor.execute(() -> {
synchronized (this) {
Seckill seckill = extSeckillMapper.selectByPrimaryKey(seckillId);
if (seckill.getNumber() > 0) {
extSeckillMapper.reduceNumber(seckillId, new Date());
SuccessKilled record = new SuccessKilled();
record.setSeckillId(seckillId);
record.setUserPhone(String.valueOf(userId));
record.setStatus((byte) 1);
record.setCreateTime(new Date());
successKilledMapper.insert(record);
} else {
mqTask.sendSeckillSuccessTopic(seckillId, "秒杀场景一(sychronized同步锁实现)");
if (log.isDebugEnabled()) {
log.debug("库存不足,无法继续秒杀!");
}
}
}
countDownLatch.countDown();
});
}
// 等待线程执行完毕,阻塞当前进程
try {
countDownLatch.await();
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
}
@Override
public void executeWithProcedure(Long seckillId, int executeTime, int userPhone) {
dealSeckill(seckillId, String.valueOf(userPhone), "秒杀场景五(存储过程实现)");
}
@Override
public void executeWithRedisson(Long seckillId, int executeTime, int userPhone) {
RLock lock = redissonClient.getLock(seckillId + "");
lock.lock();
try {
dealSeckill(seckillId, String.valueOf(userPhone), "秒杀场景二(redis分布式锁实现)");
} finally {
lock.unlock();
}
}
/**
* 获取秒杀成功笔数
*
* @param seckillId 秒杀活动id
* @return
*/
@Override
public long getSuccessKillCount(Long seckillId) {
SuccessKilledExample example = new SuccessKilledExample();
example.createCriteria().andSeckillIdEqualTo(seckillId);
long count = successKilledMapper.countByExample(example);
return count;
}
@Override
public void executeWithZookeeperLock(Long seckillId, int executeTime, int userPhone) {
zookeeperLockUtil.lock(seckillId);
try {
dealSeckill(seckillId, String.valueOf(userPhone), "秒杀场景七(zookeeper分布式锁)");
} finally {
zookeeperLockUtil.releaseLock(seckillId);
}
}
@Override
public void dealSeckill(long seckillId, String userPhone, String note) {
Seckill seckill = extSeckillMapper.selectByPrimaryKey(seckillId);
log.info("当前库存:{}", seckill.getNumber());
if (seckill.getNumber() > 0) {
extSeckillMapper.reduceNumber(seckillId, new Date());
SuccessKilled record = new SuccessKilled();
record.setSeckillId(seckillId);
record.setUserPhone(userPhone);
record.setStatus((byte) 1);
record.setCreateTime(new Date());
try {
InetAddress localHost = InetAddress.getLocalHost();
record.setServerIp(localHost.getHostAddress() + ":" + localHost.getHostName());
} catch (UnknownHostException e) {
log.warn("请求被未知IP处理!", e);
}
successKilledMapper.insert(record);
} else {
if (!SeckillStatusConstant.END.equals(seckill.getStatus())) {
mqTask.sendSeckillSuccessTopic(seckillId, note);
Seckill sendTopicResult = new Seckill();
sendTopicResult.setSeckillId(seckillId);
sendTopicResult.setStatus(SeckillStatusConstant.END);
extSeckillMapper.updateByPrimaryKeySelective(sendTopicResult);
}
if (log.isDebugEnabled()) {
log.debug("库存不足,无法继续秒杀!");
}
}
}
@Override
public void afterPropertiesSet() {
Config config = new Config();
config.useSingleServer().setAddress(propertiesUtil.getProperty("cache_ip_address"));
redissonClient = Redisson.create(config);
}
}
| 36.754098 | 162 | 0.654951 |
4b9bacbafa88eb17d4a982c583393049ac49868f | 1,629 | package com.supenta.flitchio.demo.powerup.util;
/**
* Smoothing engine based on a circular buffer.
* It computes the average over the last half second in an efficient manner.
*
* @author Radu Hambasan <radu.hambasan@tobyrich.com>
* @date 07 Jul 2014
*/
public class SmoothingEngine {
private static final int MICROS_IN_SEC = 1000000;
// Average over half a second
private static final int BUFFER_SIZE = (MICROS_IN_SEC / Const.SENSOR_DELAY) / 2;
private final float[][] buffer = new float[BUFFER_SIZE][3];
private int currElement = -1;
private float sum0 = 0;
private float sum1 = 0;
private float sum2 = 0;
/**
* @param input an array of 3 elements (smoothed individually)
* @return an array of 3 smoothed values corresponding to the input values
*/
public float[] smooth(float[] input) {
if (input.length != 3) {
throw new IllegalArgumentException("smooth only works on an array of 3 elements");
}
++currElement;
currElement %= BUFFER_SIZE;
float old0 = buffer[currElement][0];
float old1 = buffer[currElement][1];
float old2 = buffer[currElement][2];
sum0 = sum0 - old0 + input[0];
sum1 = sum1 - old1 + input[1];
sum2 = sum2 - old2 + input[2];
buffer[currElement][0] = input[0];
buffer[currElement][1] = input[1];
buffer[currElement][2] = input[2];
float[] result = new float[3];
result[0] = sum0 / BUFFER_SIZE;
result[1] = sum1 / BUFFER_SIZE;
result[2] = sum2 / BUFFER_SIZE;
return result;
}
}
| 29.618182 | 94 | 0.62124 |
1b1aa5c63e9cd9d0770132145a4ee18d31fc3243 | 589 | package android.hardware;
import com.koushikdutta.monojavabridge.MonoBridge;
import com.koushikdutta.monojavabridge.MonoProxy;
public class Camera_OnZoomChangeListenerDelegateWrapper extends com.koushikdutta.monojavabridge.MonoProxyBase implements MonoProxy, android.hardware.Camera.OnZoomChangeListener
{
static
{
MonoBridge.link(Camera_OnZoomChangeListenerDelegateWrapper.class, "onZoomChange", "(IZLandroid/hardware/Camera;)V", "System.Int32,System.Boolean,android.hardware.Camera");
}
public native void onZoomChange(int arg0,boolean arg1,android.hardware.Camera arg2);
}
| 31 | 176 | 0.837012 |
88ef5442e01f3c9ec39a168a9c8892043634e8eb | 495 | package tr.com.obss.jss.jss_final_project.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.*;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
private EnumRole name;
}
| 21.521739 | 59 | 0.753535 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.