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 |
|---|---|---|---|---|---|
c2fe72fea97ef3f37235b9d2632b63e44b571571 | 1,231 | package io.jenkins.plugins.tuleap_api.client.internals.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.jenkins.plugins.tuleap_api.client.GitFileContent;
public class GitFileContentEntity implements GitFileContent {
private final String encoding;
private final Integer size;
private final String name;
private final String path;
private final String content;
public GitFileContentEntity(
@JsonProperty("encoding") String encoding,
@JsonProperty("size") Integer size,
@JsonProperty("name") String name,
@JsonProperty("path") String path,
@JsonProperty("content") String content
) {
this.encoding = encoding;
this.size = size;
this.name = name;
this.content = content;
this.path = path;
}
@Override
public String getEncoding() {
return this.encoding;
}
@Override
public Integer getSize() {
return this.size;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getPath() {
return this.path;
}
@Override
public String getContent() {
return this.content;
}
}
| 22.796296 | 64 | 0.644192 |
7f11cd87426673ce3e12948589d945ae218741ba | 309 | package com.zw.api2.swaggerEntity;
import lombok.Data;
/***
@Author gfw
@Date 2019/2/15 19:19
@Description 从业人员查询分页
@version 1.0
**/
@Data
public class SwaggerProfessionalsQuery {
private Long page;
private Long limit;
private String simpleQueryParam;
private String groupName;
}
| 14.045455 | 40 | 0.708738 |
f0330edfd58e3af3bcf40ea13ba93703c448efd7 | 3,609 | import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.io.IOException;
class LwPolyLine extends DxfSection {
GeneralPath path;
LwPolyLine() {
this.path = new GeneralPath();
this.s = this.path;
}
public void parse(DxfReader paramDxfReader, DxfDocument paramDxfDocument)
throws IOException {
DxfItem localDxfItem = paramDxfReader.goToCode(90);
int j = Integer.parseInt(localDxfItem.value);
int k = 0;
double d1 = 0.0D;
Point2D.Double localDouble1 = new Point2D.Double();
int m = 0;
while (k < j) {
localDxfItem = paramDxfReader.readItem();
if (10 == localDxfItem.code) {
localDouble1.x = Float.parseFloat(localDxfItem.value);
}
if (20 == localDxfItem.code) {
localDouble1.y = java.lang.Double
.parseDouble(localDxfItem.value);
m = 1;
}
if (42 == localDxfItem.code) {
d1 = Float.parseFloat(localDxfItem.value);
}
if (m != 0) {
if (0 < k) {
if (d1 != 0.0D) {
Point2D.Double localDouble2 = new Point2D.Double(
this.path.getCurrentPoint().getX(), this.path
.getCurrentPoint().getY());
double d2;
double d3;
if ((1.0D > d1) && (-1.0D < d1)) {
d2 = Math.abs(2.0D * Math.atan(d1));
d3 = localDouble2.distance(localDouble1) / 2.0D;
double d4 = d3 * Math.tan(d2);
Point2D.Double localObject = new Point2D.Double();
if (0.0D < d1)
((Point2D.Double) localObject).setLocation(d3,
-d4);
else {
((Point2D.Double) localObject).setLocation(d3,
d4);
}
AffineTransform localAffineTransform2 = new AffineTransform();
localAffineTransform2.rotate(Utils
.getDirectionAngle(localDouble2,
localDouble1));
localAffineTransform2.transform(
(Point2D) localObject,
(Point2D) localObject);
localObject.x += localDouble2.x;
localObject.y += localDouble2.y;
double d5 = d3 / Math.sin(d2);
Arc2D.Double localDouble4 = new Arc2D.Double();
localDouble4.setArcByTangent(localDouble2,
(Point2D) localObject, localDouble1, d5);
this.path.append(localDouble4, true);
} else {
d2 = -180.0D;
if (0.0D > d1) {
d2 = 180.0D;
}
d3 = localDouble2.distance(localDouble1) / 2.0D;
Arc2D.Double localDouble3 = new Arc2D.Double(0.0D,
-d3, 2.0D * d3, 2.0D * d3, 180.0D, d2, 0);
AffineTransform localAffineTransform1 = new AffineTransform();
localAffineTransform1.rotate(Utils
.getDirectionAngle(localDouble2,
localDouble1));
Shape localObject = localAffineTransform1
.createTransformedShape(localDouble3);
localAffineTransform1 = new AffineTransform();
localAffineTransform1.translate(localDouble2.x,
localDouble2.y);
this.path
.append(localAffineTransform1
.createTransformedShape((Shape) localObject),
true);
}
} else {
this.path.lineTo((float) localDouble1.x,
(float) localDouble1.y);
}
} else {
this.path.moveTo((float) localDouble1.x,
(float) localDouble1.y);
}
m = 0;
d1 = 0.0D;
k++;
}
}
paramDxfDocument.entities.add(this.s);
}
}
/*
* Location: C:\Users\kurt\Desktop\Cleartrack\ClearTrack.jar Qualified Name:
* LwPolyLine JD-Core Version: 0.6.2
*/ | 29.104839 | 77 | 0.601552 |
69ced80c76053315f5452986bb120adcae4bdbfb | 5,461 | package cellsociety.model;
import cellsociety.Errors.ErrorFactory;
import cellsociety.controller.Grid;
import cellsociety.model.neighbors.CellSocietyNeighbors;
import cellsociety.ruleStructure.CellSocietyRules;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.Consumer;
/**
* This is the central abstract model class for the CellSociety game. It uses reflection to
* determine which game is being played, and loads the relevant model class for that game. This
* class takes a cell and determines its next state by using the Rules and ruleStructure packages.
* The model always has the most up to date data about a cell's current and next states.
*/
public abstract class CellSocietyModel {
private static final String GAME_ERROR = "GameError";
private final Map<String, String> myParametersMap;
private final ErrorFactory myErrorFactory;
private CellSocietyRules myRules;
private CellSocietyNeighbors myNeighbors;
private ResourceBundle statesBundle;
/**
* This is the constructor for the abstract CellSocietyModel. It sets up the relevant parameters
* needed for the game by using the parameters hash map. This map has information about the type
* of game that is being played, the types of neighbors we want for the game, and any relevant
* parameters that may be needed for specific games. This constructor uses reflection to
* initialize the relevant rules and neighbor classes based on the game type and values within the
* parameters map. It also initializes the error factory and resource bundles for the model.
*
* @param myType: The game string with the right game class that needs to be loaded using
* reflection
* @param parameters: A map that contains all of the relevant parameters for a given game as read
* from the .sim file in the controller.
*/
public CellSocietyModel(String myType, Map<String, String> parameters) {
myParametersMap = parameters;
myErrorFactory = new ErrorFactory();
try {
Object[] paramValuesSub = {myType, myParametersMap};
myRules = (CellSocietyRules) Class.forName(
String.format("cellsociety.ruleStructure.%sRules", myType))
.getConstructor(String.class, Map.class).newInstance(paramValuesSub);
myNeighbors = (CellSocietyNeighbors) Class.forName(
String.format("cellsociety.model.neighbors.%s", myParametersMap.get("Neighbors")))
.getConstructor().newInstance();
String modelResourceBundleBase = "cellsociety.model.resources.";
statesBundle = ResourceBundle.getBundle(
String.format("%s%sStates", modelResourceBundleBase, myType));
} catch (Exception e) {
myErrorFactory.updateError(GAME_ERROR);
}
}
protected Map<String, String> getMyParameters() {
return myParametersMap;
}
protected CellSocietyNeighbors getMyNeighbors() {
return myNeighbors;
}
protected CellSocietyRules getMyRules() {
if (myRules.getMyErrorFactory().errorExists()) {
myErrorFactory.updateError(myRules.getMyErrorFactory().getErrorKey());
}
return myRules;
}
protected ResourceBundle getStatesBundle() {
return statesBundle;
}
/**
* This is an abstract method that is implemented differently in each game specific model class.
* It takes in the current cell, and runs all of the relevant game rules on it to determine what
* the cell's next state should be based on its surrounding cells.
*
* @param myCell: the current cell being considered in the state-changing process
* @param row: the row number of the current cell
* @param col: the column number of the current cell
* @param myGrid: the grid of all the cells, we use the current cell's row and column to determine
* its neighbors from this grid.
*/
public abstract void setNextState(Cells myCell, int row, int col, Grid myGrid);
protected int quantityOfCellsOfGivenStateInCluster(int state, List<Cells> myRelevantCluster) {
int runningCountOfState = 0;
try {
for (Cells eachCell : myRelevantCluster) {
if (eachCell.getCurrentState() == state) {
runningCountOfState++;
}
}
} catch (Exception e) {
myErrorFactory.updateError(GAME_ERROR);
}
return runningCountOfState;
}
protected int getNextState(Cells myCell) {
return myCell.getMyNextState();
}
protected void consumerGenerateNextState(int currentState, Consumer<Integer> consumer) {
try {
consumer.accept(currentState);
} catch (NullPointerException e) {
myErrorFactory.updateError(GAME_ERROR);
}
}
/**
* This method returns the CellSocietyModel class's instance of ErrorFactory, which holds
* information as to whether or not an error exists, and if it does exist - what the error is. It
* is used by the controller to keep track of any errors that show up while determining cell
* states.
*
* @return myErrorFactory: the error information for the CellSocietyModel class
*/
public ErrorFactory getMyErrorFactory() {
return myErrorFactory;
}
protected List<Cells> neighborGenerator(int row, int col, Grid myGrid) {
return getMyNeighbors().generateNeighbors(row, col, myGrid);
}
protected Integer bundleToInteger(String myString) {
return Integer.parseInt(getStatesBundle().getString(myString));
}
}
| 38.457746 | 100 | 0.724226 |
3c3c8ca7d129e69469366f013f9d9a16d536f191 | 1,852 | public class Test<V> {
// no javadoc
public void ok0(){ }
/* no javadoc */
public void ok1(){ }
/**
* no tags
*/
public void ok2(){ }
/**
* @param p1 correctly spelled
*/
public void ok3(int p1){ }
/**
* @param <T> type parameter
*/
public <T> T ok4(){ return null; }
/**
* @param <T> several type
* @param <V> parameters
*/
public <T,V> T ok5(V p){ return null; }
/**
* @param <T> several type
* @param <V> parameters
* @param p mixed with normal parameters
*/
public <T,V> T ok6(V p){ return null; }
/**
* weird parameter name
* @param <V>
* @param V
*/
private <V> void ok7(V V){ V = null; }
/**
* not a param
* param something
*/
protected void ok8(){ }
/**
* param param
* @param param
*/
protected void ok9(int...param){ }
/**
* @param prameter typo
*/
public void problem1(int parameter){ }
/**
* @param Parameter capitalization
*/
public void problem2(int parameter){ }
/**
* @param parameter unmatched
*/
public void problem3(){ }
/**
* @param someOtherParameter matched
* @param parameter unmatched
*/
public void problem4(int someOtherParameter){ }
/**
* @param <V> unmatched type parameter
*/
private <T> T problem5(){ return null; }
/**
* @param <V> matched type parameter
* @param <P> unmatched type parameter
* @param n unmatched normal parameter
*/
private <T,V> T problem6(V p){ return null; }
/**
* param with immediate newline
* @param
*/
protected void problem7(){ }
/**
* param without a value (followed by blanks)
* @param
*/
protected void problem8(){ }
class SomeClass {
/**
* @param i exists
* @param k does not
*/
SomeClass(int i, int j) {}
}
}
| 16.990826 | 49 | 0.547516 |
c84cfd1702a70acc930c05ea4dd2b29fc6f5d453 | 752 | package org.haobtc.wallet.adapter;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import org.haobtc.wallet.R;
import java.util.List;
public class UnbackupKeyAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
public UnbackupKeyAdapter(@Nullable List<String> data) {
super(R.layout.un_backup_item, data);
}
@Override
protected void convert(BaseViewHolder helper, String item) {
String keyName = mContext.getString(R.string.now_wallet) + item + mContext.getString(R.string.no_backup);
helper.setText(R.id.test_un_backup_name, keyName);
helper.addOnClickListener(R.id.test_go_to_backup);
}
}
| 31.333333 | 113 | 0.756649 |
5b4423a79b38a9ca041b4a2586ffcc20a45ca44f | 3,721 | /*
* 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 br.com.golfx.loja;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
/**
*
* @author walmir.silva
*/
public class LoginApp extends Application {
private AnchorPane pane;
private TextField txLogin;
private PasswordField txSenha;
private Button btEntrar;
private Button btSair;
private static Stage stage;
@Override
public void start(Stage stage) throws Exception {
initComponents();
initListeners();
Scene scene = new Scene(pane);
scene.getStylesheets().add(getClass().getResource("css/login.css").toExternalForm());
stage.setScene(scene);
stage.setResizable(false);
stage.setTitle("Login - GolFX");
stage.show();
initLayout();
LoginApp.stage = stage;
}
private void initComponents() {
pane = new AnchorPane();
pane.setPrefSize(400, 300);
pane.getStyleClass().add("pane");
// pane.setStyle("-fx-background-color: linear-gradient("
// + "from 0% 0% to 100% 100%, blue 0%, silver 100%);");
txLogin = new TextField();
txLogin.setPromptText("Digite aqui seu login");
txSenha = new PasswordField();
txSenha.setPromptText("Digite aqui sua senha");
btEntrar = new Button("Entrar");
btEntrar.getStyleClass().add("btEntrar");
btSair = new Button("Sair");
btSair.getStyleClass().add("btSair");
pane.getChildren().addAll(txLogin, txSenha, btEntrar, btSair);
}
private void initLayout() {
txLogin.setLayoutX((pane.getWidth() - txLogin.getWidth()) / 2);
txLogin.setLayoutY(50);
txSenha.setLayoutX((pane.getWidth() - txSenha.getWidth()) / 2);
txSenha.setLayoutY(100);
btSair.setLayoutX((pane.getWidth() - btSair.getWidth()) / 2);
btEntrar.setLayoutY(150);
btEntrar.setLayoutX((pane.getWidth() - btEntrar.getWidth()) / 2);
btSair.setLayoutY(200);
}
private void initListeners() {
btEntrar.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
logar();
}
});
btSair.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
fecharAplicacao();
}
});
}
private void logar() {
if (txLogin.getText().equals("admin") &&
txSenha.getText().equals("12345")) {
try {
new VitrineApp().start(new Stage());
LoginApp.getStage().close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Login e/ou senha inválidos", "Erro", JOptionPane.ERROR_MESSAGE);
}
}
private void fecharAplicacao() {
System.exit(0);
}
public static Stage getStage() {
return stage;
}
public static void main(String ... args) {
launch(args);
}
}
| 28.623077 | 113 | 0.583445 |
cad83e7fa8d98cbb04c0b8043373a7526bcd79c2 | 14,936 | package factorization.beauty;
import factorization.api.*;
import factorization.api.datahelpers.DataHelper;
import factorization.api.datahelpers.Share;
import factorization.api.wind.IWindmill;
import factorization.api.wind.WindModel;
import factorization.common.FactoryType;
import factorization.fzds.DeltaChunk;
import factorization.fzds.TransferLib;
import factorization.fzds.interfaces.DeltaCapability;
import factorization.fzds.interfaces.DimensionSliceEntityBase;
import factorization.fzds.interfaces.IDCController;
import factorization.fzds.interfaces.IDimensionSlice;
import factorization.fzds.interfaces.transform.Pure;
import factorization.fzds.interfaces.transform.TransformData;
import factorization.net.StandardMessageType;
import factorization.shared.BlockClass;
import factorization.shared.Core;
import factorization.shared.EntityReference;
import factorization.shared.TileEntityCommon;
import factorization.util.FzUtil;
import factorization.util.NumUtil;
import factorization.util.PlayerUtil;
import factorization.util.SpaceUtil;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFence;
import net.minecraft.block.BlockLog;
import net.minecraft.block.BlockWall;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.*;
import net.minecraft.world.World;
import java.io.IOException;
public class TileEntityWindMill extends TileEntityCommon implements IRotationalEnergySource, IDCController, IWindmill, IMeterInfo, ITickable {
EnumFacing sailDirection = EnumFacing.UP;
boolean dirty = true;
double power_per_tick, power_this_tick, target_velocity, velocity;
double wind_strength = 0, efficiency = 0;
double radius = 0;
final EntityReference<DimensionSliceEntityBase> idcRef = new EntityReference<DimensionSliceEntityBase>().whenFound(new IDCController.AutoControl(this));
@Override
public void setWorldObj(World w) {
super.setWorldObj(w);
idcRef.setWorld(w);
WindModel.activeModel.registerWindmillTileEntity(this);
if (radius > 0) {
WindModel.activeModel.registerWindmillTileEntity(this);
}
}
@Override
public BlockClass getBlockClass() {
return BlockClass.Machine;
}
@Override
public FactoryType getFactoryType() {
return FactoryType.WIND_MILL_GEN;
}
@Override
public boolean canConnect(EnumFacing direction) {
return direction == this.sailDirection.getOpposite();
}
@Override
public double availableEnergy(EnumFacing direction) {
if (direction != sailDirection.getOpposite()) return 0;
return power_this_tick;
}
@Override
public double takeEnergy(EnumFacing direction, double maxPower) {
if (direction != sailDirection.getOpposite()) return 0;
if (maxPower > power_this_tick) {
maxPower = power_this_tick;
}
power_this_tick -= maxPower;
return maxPower;
}
@Override
public double getVelocity(EnumFacing direction) {
if (direction != sailDirection.getOpposite()) return 0;
return velocity;
}
@Override
protected boolean removedByPlayer(EntityPlayer player, boolean willHarvest) {
if (!willHarvest) return super.removedByPlayer(player, willHarvest);
if (PlayerUtil.isPlayerCreative(player) && player.isSneaking()) {
IDimensionSlice idc = idcRef.getEntity();
if (idc != null) idc.killIDS();
return super.removedByPlayer(player, willHarvest);
}
if (idcRef.trackedAndAlive()) return false;
return super.removedByPlayer(player, willHarvest);
}
@Override
public void onPlacedBy(EntityPlayer player, ItemStack is, EnumFacing side, float hitX, float hitY, float hitZ) {
super.onPlacedBy(player, is, side, hitX, hitY, hitZ);
sailDirection = side;
}
@Override
public boolean isTileEntityInvalid() {
return this.isInvalid();
}
@Override
public boolean placeBlock(IDimensionSlice idc, EntityPlayer player, Coord at) {
dirty = true;
return false;
}
@Override
public boolean breakBlock(IDimensionSlice idc, EntityPlayer player, Coord at, EnumFacing sideHit) {
dirty = true;
return false;
}
@Override public boolean hitBlock(IDimensionSlice idc, EntityPlayer player, Coord at, EnumFacing sideHit) { return false; }
@Override public boolean useBlock(IDimensionSlice idc, EntityPlayer player, Coord at, EnumFacing sideHit) { return false; }
@Override public void idcDied(IDimensionSlice idc) { }
@Override public void beforeUpdate(IDimensionSlice idc) { }
@Override public void afterUpdate(IDimensionSlice idc) { }
@Override public boolean onAttacked(IDimensionSlice idc, DamageSource damageSource, float damage) { return false; }
@Override public CollisionAction collidedWithWorld(World realWorld, AxisAlignedBB realBox, World shadowWorld, AxisAlignedBB shadowBox) { return CollisionAction.STOP_BEFORE; }
@Override
public void putData(DataHelper data) throws IOException {
sailDirection = data.as(Share.VISIBLE, "sailDirection").putEnum(sailDirection);
dirty = data.as(Share.PRIVATE, "dirty").putBoolean(dirty);
data.as(Share.VISIBLE, "idcRef").putIDS(idcRef);
power_per_tick = data.as(Share.VISIBLE, "powerPerTick").putDouble(power_per_tick);
power_this_tick = data.as(Share.VISIBLE, "powerThisTick").putDouble(power_this_tick);
target_velocity = data.as(Share.VISIBLE, "targetVelocity").putDouble(target_velocity);
velocity = data.as(Share.VISIBLE, "velocity").putDouble(velocity);
wind_strength = data.as(Share.PRIVATE, "wind_strength").putDouble(wind_strength);
efficiency = data.as(Share.PRIVATE, "efficiency").putDouble(efficiency);
radius = data.as(Share.PRIVATE, "radius").putDouble(radius);
}
@Override
public void representYoSelf() {
super.representYoSelf();
channel_id = DeltaChunk.getHammerRegistry().makeChannelFor(Core.modId, "fluidMill", channel_id, -1, "waterwheels & windmills");
}
static int channel_id = 100;
static final int MAX_OUT = 2;
static final int MAX_IN = 2;
static final int MAX_RADIUS = 6;
boolean working = false;
@Override
public void onNeighborTileChanged(int tilex, int tiley, int tilez) {
neighborChanged(null);
}
@Override
public void neighborChanged(Block neighbor) {
if (working) return;
if (idcRef.trackedAndAlive()) {
updateRedstoneState();
}
working = true;
try {
trySpawnMill();
} finally {
working = false;
}
}
@Override
public boolean handleMessageFromServer(Enum messageType, ByteBuf input) throws IOException {
if (super.handleMessageFromServer(messageType, input)) {
return true;
}
if (messageType == StandardMessageType.SetSpeed) {
velocity = input.readDouble();
}
return false;
}
void sendVelocity() {
broadcastMessage(null, StandardMessageType.SetSpeed, velocity);
}
private boolean trySpawnMill() {
Coord fenceLocation = new Coord(this);
fenceLocation.adjust(sailDirection);
if (!isFenceish(fenceLocation)) return false;
DeltaCoord idcSize = new DeltaCoord(MAX_RADIUS * 2, MAX_OUT + MAX_IN, MAX_RADIUS * 2);
DeltaCoord offset = new DeltaCoord(MAX_RADIUS, MAX_OUT, MAX_RADIUS);
IDimensionSlice idc = DeltaChunk.allocateSlice(worldObj, channel_id, idcSize);
idc.permit(DeltaCapability.BLOCK_PLACE,
DeltaCapability.BLOCK_MINE,
DeltaCapability.INTERACT,
DeltaCapability.ROTATE,
DeltaCapability.DIE_WHEN_EMPTY,
DeltaCapability.REMOVE_ALL_ENTITIES);
idc.forbid(DeltaCapability.COLLIDE_WITH_WORLD,
DeltaCapability.COLLIDE,
DeltaCapability.VIOLENT_COLLISIONS,
DeltaCapability.DRAG);
TransformData<Pure> transform = idc.getTransform();
transform.setOffset(offset.toVector().addVector(0.5, 0.5, 0.5));
final EnumFacing normal = sailDirection.getOpposite();
Coord at = new Coord(this).add(sailDirection);
idc.getTransform().setPos(at.toMiddleVector());
if (normal.getDirectionVec().getY() == 0) {
Vec3 up = SpaceUtil.fromDirection(EnumFacing.UP);
Vec3 vnorm = SpaceUtil.fromDirection(normal);
Vec3 axis = up.crossProduct(vnorm);
Quaternion rot = Quaternion.getRotationQuaternionRadians(-Math.PI / 2, axis);
transform.setRot(rot);
transform.addPos(0, 0.5, 0);
} else {
double a = .5;
transform.addPos(SpaceUtil.scale(SpaceUtil.fromDirection(sailDirection), a));
if (normal.getDirectionVec().getY() == 1) {
transform.addPos(0, 1, 0);
}
}
TransferLib.move(fenceLocation, idc.getCenter(), false /* We'll do it this way to synchronize them */, true);
fenceLocation.setAir();
idcRef.spawnAndTrack(idc.getEntity());
updateWindStrength(true);
idc.setPartName("Windmill");
updateRedstoneState();
return true;
}
private boolean isFenceish(Coord fenceLocation) {
final Block block = fenceLocation.getBlock();
if (block instanceof BlockFence) return true;
if (block instanceof BlockWall) return true;
if (block instanceof BlockLog) return true;
if (block.getMaterial() == Material.iron) {
BlockPos pos = fenceLocation.toBlockPos();
if (block.isBeaconBase(worldObj, pos, pos)) {
return true;
}
}
return false;
}
@Override
public void update() {
if (worldObj.isRemote) return;
if (!idcRef.entityFound()) {
if (velocity != 0) {
velocity = 0;
sendVelocity();
}
idcRef.getEntity();
return;
}
updateWindStrength(false);
power_this_tick = power_per_tick;
if (velocity != target_velocity) {
double error = target_velocity > velocity ? (velocity / target_velocity) : 1;
velocity = (velocity * 5 + target_velocity) / 6;
power_this_tick *= error;
if (error > 0.9999) {
velocity = target_velocity;
}
IDimensionSlice idc = idcRef.getEntity();
if (idc != null) {
idc.getVel().setRot(Quaternion.getRotationQuaternionRadians(velocity, sailDirection));
}
sendVelocity();
}
if (!dirty) {
if (worldObj.getTotalWorldTime() % 1200 == 0) {
dirty = true;
}
return;
}
if (worldObj.getTotalWorldTime() % 40 != 0) return;
calculate();
}
static double MAX_SPEED = IRotationalEnergySource.MAX_SPEED / 4; // Maximum velocity (doesn't change power output)
static double V_SCALE = 0.05; // Scales down velocity (also doesn't change power output)
static double WIND_POWER_SCALE = 1.0 / 10.0; // Boosts the power output (and does not influence velocity)
void calculate() {
IDimensionSlice idc = idcRef.getEntity();
if (idc == null) return;
dirty = false;
int score = 0;
int asymetry = 0;
Coord center = idc.getCenter();
center.y -= MAX_IN;
int ys = MAX_IN + MAX_OUT;
double max_score = 1;
double new_radius = 0;
while (ys-- > 0) {
Symmetry symmetry = new Symmetry(center, MAX_RADIUS, EnumFacing.UP);
symmetry.calculate();
score += symmetry.score;
asymetry += symmetry.asymetry;
center.y++;
max_score = symmetry.max_score;
new_radius = Math.max(symmetry.measured_radius, new_radius);
}
max_score = MAX_RADIUS * 4 * 3;
if (radius != new_radius) {
if (radius != 0) {
WindModel.activeModel.deregisterWindmillTileEntity(this);
}
radius = new_radius;
if (radius != 0) {
WindModel.activeModel.registerWindmillTileEntity(this);
}
}
score -= 5; // Don't turn if it's just a shaft or whatever
double sum = score - asymetry * 20;
if (sum < 0) {
efficiency = 0;
return;
}
if (sum > max_score) {
sum = max_score;
}
efficiency = sum / (max_score / 8);
efficiency = NumUtil.clip(efficiency, 0, 1);
updatePowerPerTick();
}
void updatePowerPerTick() {
power_per_tick = efficiency * wind_strength;
if (power_this_tick < 0) power_this_tick = 0;
target_velocity = power_per_tick * V_SCALE;
if (target_velocity > MAX_SPEED) {
target_velocity = MAX_SPEED;
}
power_per_tick *= WIND_POWER_SCALE;
}
@Override
public int getWindmillRadius() {
return MAX_RADIUS;
}
@Override
public EnumFacing getDirection() {
return sailDirection;
}
void updateWindStrength(boolean force) {
if (!force && worldObj.getTotalWorldTime() % 200 != 0) return;
if (getCoord().isWeaklyPowered()) {
wind_strength = 0;
updatePowerPerTick();
return;
}
Vec3 wind = WindModel.activeModel.getWindPower(worldObj, pos, this);
// TODO: Dot product or something to reverse the velocity
wind_strength = wind.lengthVector();
updatePowerPerTick();
}
@Override
public String getInfo() {
if (!idcRef.trackedAndAlive()) {
return "No windmill";
}
String speed;
if (velocity == 0) {
speed = "stopped";
} else {
double spr = 1 / (Math.toDegrees(velocity) * 20 / 360);
if (spr > 60) {
speed = (int) spr + " SPR";
} else {
speed = FzUtil.toRpm(velocity);
}
}
return "Efficiency: " + (int) (efficiency * 100) + "%" +
"\nWind: " + wind_strength +
"\nSpeed: " + speed;
}
private static final byte UNSET = 0, POWERED = 1, UNPOWERED = 2;
private byte redstone_mode = UNSET;
private void updateRedstoneState() {
byte next = getCoord().isWeaklyPowered() ? POWERED : UNPOWERED;
if (next == redstone_mode) return;
redstone_mode = next;
updateWindStrength(true);
}
}
| 36.879012 | 178 | 0.636784 |
408234f2e7412d31a39a266fefc98a578fdd3df5 | 2,025 | package com.example.Adapter;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bean.HotSearchBean;
import com.example.mycloudmusic.R;
import java.util.List;
public class HotSearchAdapter extends RecyclerView.Adapter<HotSearchAdapter.ViewHolder> {
private List<HotSearchBean> mDatas;
static class ViewHolder extends RecyclerView.ViewHolder{
View itemView;
TextView searchWord;
public ViewHolder(View v){
super(v);
itemView = v;
searchWord = (TextView) v.findViewById(R.id.hot_search_textview);
}
}
public HotSearchAdapter(List<HotSearchBean> list){
mDatas = list;
}
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.hot_search_item,parent,false);
final ViewHolder holder = new ViewHolder(v);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
HotSearchBean item = mDatas.get(position);
//在子布局中获取父布局就这样写
EditText input = (EditText) ((View)((View) parent.getParent()).getParent())
.findViewById(R.id.searchInput);
input.setText(item.getSearchWord());
input.setSelection(item.getSearchWord().length());
}
});
return holder;
}
public void onBindViewHolder(ViewHolder holder, int position){
HotSearchBean item = mDatas.get(position);
holder.searchWord.setText(item.getSearchWord());
}
@Override
public int getItemCount() {
return mDatas.size();
}
}
| 33.75 | 93 | 0.655802 |
84c958522b32478d2ba498e78909e3f3cdcbf0ed | 2,887 | /*******************************************************************************
* Copyright 2017 Alessio Arleo
*
* 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.graphray;
import java.io.IOException;
import org.apache.giraph.bsp.CentralizedServiceWorker;
import org.apache.giraph.comm.WorkerClientRequestProcessor;
import org.apache.giraph.graph.AbstractComputation;
import org.apache.giraph.graph.GraphState;
import org.apache.giraph.graph.Vertex;
import org.apache.giraph.worker.WorkerGlobalCommUsage;
import org.apache.hadoop.io.Writable;
import org.apache.log4j.Logger;
import com.graphray.common.edgetypes.PathfinderEdgeType;
import com.graphray.common.vertextypes.PathfinderVertexID;
import com.graphray.common.vertextypes.PathfinderVertexType;
import com.graphray.masters.GraphRayMasterCompute;
/**
* @author spark
*
*/
public class GraphRayComputation<I extends Writable, M extends Writable> extends AbstractComputation<PathfinderVertexID, PathfinderVertexType, PathfinderEdgeType, I, M> {
protected static Logger log = Logger.getLogger(GraphRayComputation.class);
protected boolean isLogEnabled = false;
/* (non-Javadoc)
* @see org.apache.giraph.graph.AbstractComputation#compute(org.apache.giraph.graph.Vertex, java.lang.Iterable)
*/
@Override
public void compute(Vertex<PathfinderVertexID, PathfinderVertexType, PathfinderEdgeType> vertex, Iterable<I> messages)
throws IOException {
if(isLogEnabled)
log.info("im " + vertex.getId());
}
/* (non-Javadoc)
* @see org.apache.giraph.graph.AbstractComputation#initialize(org.apache.giraph.graph.GraphState, org.apache.giraph.comm.WorkerClientRequestProcessor, org.apache.giraph.bsp.CentralizedServiceWorker, org.apache.giraph.worker.WorkerGlobalCommUsage)
*/
@Override
public void initialize(GraphState graphState,
WorkerClientRequestProcessor<PathfinderVertexID, PathfinderVertexType, PathfinderEdgeType> workerClientRequestProcessor,
CentralizedServiceWorker<PathfinderVertexID, PathfinderVertexType, PathfinderEdgeType> serviceWorker,
WorkerGlobalCommUsage workerGlobalCommUsage) {
super.initialize(graphState, workerClientRequestProcessor, serviceWorker, workerGlobalCommUsage);
isLogEnabled = getConf().getBoolean(GraphRayMasterCompute.enableLogOption, false);
}
}
| 41.84058 | 248 | 0.759266 |
4df82a67b0b59fef70e715fee4a5cbba6726310b | 238 | package org.glasswall.solutions.model;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class RebuildFileRequestBody {
private String InputGetUrl, outputPutUrl;
private ContentManagementFlags contentManagementFlags;
}
| 19.833333 | 55 | 0.836134 |
e472fcf9988ad87ea19d8c1ba8a8522a4146e135 | 1,560 | import com.intellij.ui.components.BrowserLink;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBTextField;
import com.intellij.util.ui.FormBuilder;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* Supports creating and managing a {@link JPanel} for the Settings Dialog.
*/
public class AppSettingsComponent {
private final JPanel myMainPanel;
private final JBTextField glvrdKeyText = new JBTextField();
private final JButton glvrdAPILink = new BrowserLink("glvrd.ru", "https://glvrd.ru/api/");
private final JButton bitcoinLabel = new BrowserLink("bc1qejh37h2epmkrs0vmrv480fc27e0z4arkncevcp");
public AppSettingsComponent() {
myMainPanel = FormBuilder.createFormBuilder()
.addLabeledComponent(new JBLabel("Приобрести ключ"), glvrdAPILink, 1, false)
.addLabeledComponent(new JBLabel("Введите ключ для активации"), glvrdKeyText, 1, false)
.addComponentFillVertically(new JPanel(), 0)
.addSeparator(0)
.addLabeledComponent(new JBLabel("🍺 Поддержи разработку! Отправь BTC на этот кошелек: "), bitcoinLabel)
.getPanel();
}
public JPanel getPanel() {
return myMainPanel;
}
public JComponent getPreferredFocusedComponent() {
return glvrdKeyText;
}
@NotNull
public String getHTTPAPIText() {
return glvrdKeyText.getText();
}
public void setHTTPAPIText(@NotNull String newText) {
glvrdKeyText.setText(newText);
}
} | 35.454545 | 119 | 0.695513 |
4bd97b754b11cba0dd75aaa4499ddd5fe5c50e0d | 6,414 | package GUI.Tabs;
import GUI.Commands.CommandExecutable;
import GUI.Commands.CommandLine;
import GUI.Commands.Language;
import GUI.Commands.LanguageChangeable;
import GUI.GUI.GUIDisplay;
import GUI.GUI.GUIdata;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Consumer;
/*
* Class that contains tabs with information to display to user
* Author: Louis Jensen, Ryan Culhane
*/
public class TabExplorer extends TabPane implements CommandExecutable, LanguageChangeable {
private static final String VARIABLES = "Variables";
private static final String METHODS = "Methods";
private static final String COMMANDS = "CommandHistory";
private static final Double QUARTER = 1.0 / 4;
private static final Double HALF = 1.0 / 2;
private Consumer<String> myCommandAccess;
private SLogoTab myVariables;
private SLogoTab myCommands;
private SLogoTab myMethods;
private GUIdata myDataTracker;
private CommandLine myTextBox;
private Language myLanguage;
private ResourceBundle myFilePaths;
private static final String METHODS_TITLE = "Variables";
private static final String METHODS_CONTENT = "Parameters Separated by Commas:";
private static final String VARIABLES_TITLE = "Variable Editor";
private static final String VARIABLES_CONTENT = "Enter new value:";
/*
* Default Constructor for TabExplorer calls TabPane constructor
*/
public TabExplorer(){
super();
setPrefSize(GUIDisplay.SCENE_WIDTH * QUARTER, GUIDisplay.SCENE_HEIGHT * HALF);
}
/**
* Constructor for TabExplorer calls TabPane constructor and establishes instance variables
* @param dataTracker Passes data between TabExplorer and GUIDisplay
* @param language Current language for user
* @param textBox Box in which user enters commands
*/
public TabExplorer(GUIdata dataTracker, Language language, CommandLine textBox){
super();
myLanguage = language;
myDataTracker = dataTracker;
myTextBox = textBox;
myFilePaths = ResourceBundle.getBundle("FilePaths");
initializeTabs();
setPrefSize(GUIDisplay.SCENE_WIDTH * QUARTER, GUIDisplay.SCENE_HEIGHT * HALF);
}
private void initializeTabs() {
myVariables = makeInteractiveTab(VARIABLES, myDataTracker, VARIABLES_TITLE, VARIABLES_CONTENT);
myMethods = makeInteractiveTab(METHODS, myDataTracker, METHODS_TITLE, METHODS_CONTENT);
myCommands = makeTab(COMMANDS, myDataTracker, myTextBox);
getTabs().addAll(myVariables, myMethods, myCommands);
}
/**
* TabExplorer is always resizeable
* @return true
*/
@Override
public boolean isResizable(){
return true;
}
/**
* Resizes TabExplorer
* @param width new width to set
* @param height new height to set
*/
@Override
public void resize(double width, double height){
super.setWidth(width);
super.setHeight(height);
}
/**
* Gives the class the ability to run commands by passing a consumer that takes a String and passes
* the command to the parser to be run through the backend and have its effects displayed on the front end as
* well as stored in the backend
* @param commandAccess a consumer that feeds the command to the parser to run the command through the backend.
*/
@Override
public void giveAbilityToRunCommands(Consumer<String> commandAccess) {
myCommandAccess = commandAccess;
}
/**
* Method that calls the accept method on the consumer that was passed in the giveAbilityToRunCommands method
* @param command the command to be run
*/
@Override
public void runCommand(String command) {
myCommandAccess.accept(command);
}
/**
* Change the language dependent features of the class to accommodate the new language
* @param newLanguage new language that the program is being changed to
*/
@Override
public void setLanguage(Language newLanguage) {
myLanguage = newLanguage;
myVariables.setText(myLanguage.getTranslatedWord(VARIABLES));
myCommands.setText(myLanguage.getTranslatedWord(COMMANDS));
myMethods.setText(myLanguage.getTranslatedWord(METHODS));
}
private SLogoTab makeInteractiveTab(String tabType, GUIdata dataTracker, String title, String content) {
SLogoTab tab;
try {
Class tabClass = Class.forName(myFilePaths.getString(tabType));
Constructor constructor = tabClass.getConstructor(String.class, GUIdata.class, String.class, String.class);
tab = (SLogoTabInteractive) constructor.newInstance(myLanguage.getTranslatedWord(tabType), dataTracker, title, content);
} catch (Exception e) {
tab = new SLogoTab();
}
tab.getContent().setOnMouseClicked(event -> {
runCommand(dataTracker.getMyCommandToRun());
});
return tab;
}
private SLogoTab makeTab(String tabType, GUIdata data, TextArea commandLine){
SLogoTab tab = new SLogoTab(myLanguage.getTranslatedWord(tabType), data);
tab.getContent().setOnMouseClicked(event -> {
commandLine.setText(data.getMyTextToUpdate());
});
return tab;
}
/**
* Adds a command to the history when user clicks run
* @param command Command to add to history
*/
public void addToCommandHistory(String command){
myCommands.addContents(command);
}
/**
* Clears command history so it is empty
*/
public void clearCommandHistory() {
myCommands.clearContents();
}
/**
* Adds a variable and value to the variables tab
* @param name Name of variable
* @param val Value of variable
*/
public void addVariable(String name, Double val) {
myVariables.addContents(name + " " + val);
}
/**
* Adds a user defined command to the methods tab
* @param name Name of user defined command
* @param myVars variables necessary to run user defined command
*/
public void addUserDefinedCommand(String name, List<String> myVars) {
myMethods.addContents(name + ": " + String.join(" ", myVars));
}
}
| 35.832402 | 132 | 0.690988 |
3359499542cc4f95c81ca3d08ead68b175677bd9 | 230 | package JBrain;
public class Data_Cartridge {
double[] Data;
double[] Expected_Output;
public Data_Cartridge(double[] row_values, double[] result_values) {
this.Data=row_values;
this.Expected_Output=result_values;
}
}
| 17.692308 | 69 | 0.756522 |
3db8fad119d6eeb31ba2b5b1ec5d2e33cb6a2f40 | 1,140 | package fr.calamus.common.mail.model;
import fr.calamus.common.model.EntityMapWithIntId;
import java.util.Map;
public class DestinataireMap extends EntityMapWithIntId implements IDestinataireMap {
public DestinataireMap() {
super("id,nom,mail","Id,Nom,E-mail");
}
public DestinataireMap(Map<String, ? extends Object> dbMap) {
super(dbMap,"id,nom,mail","Id,Nom,E-mail");
}
public DestinataireMap(Map<String, ? extends Object> dbMap, String cols, String labels) {
super(dbMap,cols, labels);
}
public DestinataireMap(String cols, String labels) {
super(cols, labels);
}
public DestinataireMap(Integer id, String nom, String mail) {
super("id,nom,mail","Id,Nom,E-mail");
setId(id);
setNom(nom);
setMail(mail);
}
@Override
public String getNom() {
return (String) get("nom");
}
@Override
public void setNom(String nom) {
put("nom", nom);
}
@Override
public String getMail() {
return (String) get("mail");
}
@Override
public void setMail(String mail) {
put("mail", mail);
}
@Override
public String getValeurAffichable(String key) {
return get(key)==null?"":get(key).toString();
}
}
| 20 | 90 | 0.697368 |
3fe0016221c24d74b273d4bf54f8800ea1ce616f | 271 | package test;
import javax.persistence.Embeddable;
import javax.persistence.OneToMany;
import java.util.Set;
@Embeddable
public class Country {
public String code;
public String name;
public int thing = 0;
@OneToMany
public Set<Person> residents;
}
| 18.066667 | 36 | 0.734317 |
aaaac1c0a85375f1e39cd51d1ff7efbda3f8e033 | 1,836 | /*
* Copyright 2018 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.common.logging;
import java.util.function.Supplier;
import org.apache.kafka.connect.data.SchemaAndValue;
import org.slf4j.Logger;
final class StructuredLoggerImpl implements StructuredLogger {
private static final String LOG_MSG = "{}";
private final Logger inner;
StructuredLoggerImpl(final Logger inner) {
this.inner = inner;
}
public String getName() {
return inner.getName();
}
public void error(final Supplier<SchemaAndValue> msgSupplier) {
if (!inner.isErrorEnabled()) {
return;
}
error(msgSupplier.get());
}
public void error(final SchemaAndValue msg) {
inner.error(LOG_MSG, new SerializableSchemaAndValue(msg));
}
public void info(final Supplier<SchemaAndValue> msgSupplier) {
if (!inner.isInfoEnabled()) {
return;
}
info(msgSupplier.get());
}
public void info(final SchemaAndValue msg) {
inner.info(LOG_MSG, new SerializableSchemaAndValue(msg));
}
public void debug(final Supplier<SchemaAndValue> msgSupplier) {
if (!inner.isDebugEnabled()) {
return;
}
debug(msgSupplier.get());
}
public void debug(final SchemaAndValue msg) {
inner.debug(LOG_MSG, new SerializableSchemaAndValue(msg));
}
}
| 26.608696 | 75 | 0.715686 |
705d6dada003ec4f110367e1d36a1d72a55ebf39 | 7,105 | package HealthMonitorMng.service.impl.background;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hibernate.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import HealthMonitorMng.hbm.base.background.DetectObject;
import HealthMonitorMng.hbm.base.background.BasicData.Area;
import HealthMonitorMng.hbm.base.background.BasicData.BasicData;
import HealthMonitorMng.hbm.base.background.BasicData.City;
import HealthMonitorMng.hbm.base.background.BasicData.Province;
import HealthMonitorMng.model.DataGrid;
import HealthMonitorMng.model.DataGridJson;
import HealthMonitorMng.model.Location;
import HealthMonitorMng.service.background.BasicDataServiceI;
import HealthMonitorMng.service.impl.BaseServiceImpl;
/**
* @ClassName: BasicDataServiceImpl
* @Description: 基础数据维护服务类
* @author WuHoushuang
* @date 2015年2月4日 下午8:02:41
*/
@Transactional
@Service("basicDataService")
public class BasicDataServiceImpl extends BaseServiceImpl implements BasicDataServiceI{
/*
* 实现基础数据维护的添加
* <p>Title: addBasicData</p>
* <p>Description: </p>
* @param basicData 基础数据类
* @return 刚添加的基础数据类
* @see onesun.service.background.BasicDataServiceI#addBasicData(onesun.hbm.base.background.BasicData.BasicData)
*/
@Override
public BasicData addBasicData(BasicData basicData) {
basicData.setDataId(UUID.randomUUID().toString());
BasicData basic=new BasicData();
BeanUtils.copyProperties(basicData, basic);
super.getBaseDao().save(basic);
List<String> nameList=new ArrayList<String>();
nameList.add(basicData.getDetectObject());
String hql="From DetectObject where detectName=?";
DetectObject detect=(DetectObject) super.getBaseDao().get(hql, nameList);
if(detect==null){
DetectObject detectObject=new DetectObject();
detectObject.setDataId(UUID.randomUUID().toString());
detectObject.setDetectName(basicData.getDetectObject());
super.getBaseDao().save(detectObject);
}
return basicData;
}
@Override
public DataGridJson datagrid(DataGrid dg, BasicData basicData) {
DataGridJson j = new DataGridJson();
String hql = " from BasicData t where 1=1 ";
List<Object> values = new ArrayList<Object>();
String totalHql = " select count(*) " + hql;
j.setTotal(super.getBaseDao().count(totalHql, values));// 设置总记录数
if (dg.getSort() != null) {// 设置排序
hql += " order by " + dg.getSort() + " " + dg.getOrder();
} else {
hql += " order by code desc ";
}
List<BasicData> ol = super.getBaseDao().find(hql, dg.getPage(), dg.getRows(), values);// 查询分页
List<BasicData> nl = new ArrayList<BasicData>();
if (ol != null && ol.size() > 0) {// 转换模型
for (BasicData o : ol) {
BasicData basic = new BasicData();
BeanUtils.copyProperties(o,basic);
nl.add(basic);
}
}
j.setRows(nl);// 设置返回的行
return j;
}
@Override
public BasicData edit(BasicData basicData) {
BasicData bd=(BasicData) super.getBaseDao().get(BasicData.class, basicData.getDataId());
BeanUtils.copyProperties(basicData, bd);//转换模型
return basicData;
}
@Override
public void delete(String ids) {
for(String id: ids.split(",")){
if(id!=null&&!"".equals(id)){
BasicData bd=(BasicData) super.getBaseDao().load(BasicData.class, id);
super.getBaseDao().delete(bd);
}
}
}
@Override
public List<DetectObject> getDetectName() {
String hql="From DetectObject";
Query query=super.getBaseDao().createQuery(hql);
List<DetectObject> detectObjects=query.list();
return detectObjects;
}
@Override
public List<Province> getProvinces() {
String hql="From Province";
Query query=super.getBaseDao().createQuery(hql);
List<Province> provinces=query.list();
return provinces;
}
@Override
public List<City> getCities(String provinceid) {
String hql="From City where provinceid=?";
List<String> proList=new ArrayList<String>();
proList.add(provinceid);
List<City> cities=super.getBaseDao().find(hql, proList);
return cities;
}
@Override
public List<Area> getAreas(String cityid) {
String hql="From Area where cityid=?";
List<String> cityList=new ArrayList<String>();
cityList.add(cityid);
List<Area> areas=super.getBaseDao().find(hql, cityList);
return areas;
}
@Override
public Province getProvince(String provinceid) {
System.out.println(provinceid);
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(provinceid);
Province province=null;
if(isNum.matches()){
String hql="From Province where provinceid=?";
List<String> list=new ArrayList<String>();
list.add(provinceid);
province=(Province) super.getBaseDao().get(hql, list);
}else{
String hql="From Province where province=?";
List<String> list=new ArrayList<String>();
list.add(provinceid);
province=(Province) super.getBaseDao().get(hql, list);
}
return province;
}
@Override
public City getCity(String cityid) {
System.out.println(cityid);
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(cityid);
City city=null;
if(isNum.matches()){
String hql="From City where cityid=?";
List<String> list=new ArrayList<String>();
list.add(cityid);
city=(City) super.getBaseDao().get(hql, list);
}else{
String hql="From City where city=?";
List<String> list=new ArrayList<String>();
list.add(cityid);
city=(City) super.getBaseDao().get(hql, list);
}
if("市".equals(city.getCity())||"市辖区".equals(city.getCity())||"县".equals(city.getCity())
||"香港特别行政区".equals(city.getCity())||"澳门特别行政区".equals(city.getCity())){
city.setCity("");
}
return city;
}
@Override
public Area getArea(String areaid) {
Pattern p=Pattern.compile("[0-9]*");
Matcher m=p.matcher(areaid);
Area area=null;
if(m.matches()){
String hql="From Area where areaid=?";
List<String> list=new ArrayList<String>();
list.add(areaid);
area=(Area) super.getBaseDao().get(hql, list);
}else{
String hql="From Area where area=?";
List<String> list=new ArrayList<String>();
list.add(areaid);
area=(Area) super.getBaseDao().get(hql, list);
}
if("香港特别行政区".equals(area.getArea())||"澳门特别行政区".equals(area.getArea())){
area.setArea("");
}
return area;
}
@Override
public BasicData getData(String rowId) {
String hql="From BasicData where dataId=?";
List<String> list=new ArrayList<String>();
list.add(rowId);
BasicData basicData=(BasicData) super.getBaseDao().get(hql, list);
return basicData;
}
}
| 33.356808 | 114 | 0.665306 |
f147845dce4170f2b5d81f0f1fd3048cf81f7d8a | 2,461 | /**
* Copyright 2014 Brian Sensale
*
* 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.sensale.qp.quickbooks;
import static org.junit.Assert.*;
import org.junit.Test;
public class IIFHeadersTest {
IIFHeaders headers = new IIFHeaders();
@Test
public void testIsEndTransaction() {
assertTrue(headers.isEndTransactionHeader("!ENDTRNS"));
assertFalse(headers.isEndTransactionHeader("foo"));
assertFalse(headers.isEndTransactionHeader(""));
assertFalse(headers.isEndTransactionHeader(null));
}
@Test
public void testIsStartTransaction() {
assertTrue(headers.isTransactionHeader("!TRNS\tDATE\tACCNT\tNAME\tCLASS\tAMOUNT\tMEMO"));
assertFalse(headers.isTransactionHeader("!TRNS\tACCNT\tDATE\tNAME\tCLASS\tAMOUNT\tMEMO"));
assertFalse(headers.isTransactionHeader(null));
assertFalse(headers.isTransactionHeader(""));
assertFalse(headers.isTransactionHeader("foo"));
}
@Test
public void testIsSplit() {
assertTrue(headers.isSplitInputHeader("!SPL\tDATE\tACCNT\tNAME\tAMOUNT\tMEMO"));
assertFalse(headers.isSplitInputHeader("!SPL\tACCNT\tDATE\tNAME\tAMOUNT\tMEMO"));
assertFalse(headers.isSplitInputHeader(null));
assertFalse(headers.isSplitInputHeader(""));
assertFalse(headers.isSplitInputHeader("foo"));
}
@Test
public void getTransactionHeader() {
assertEquals(
"!TRNS\tDATE\tACCNT\tNAME\tCLASS\tAMOUNT\tMEMO\t",
headers.getTransactionHeader());
}
@Test
public void getSplitHeader() {
assertEquals(
"!SPL\tDATE\tACCNT\tNAME\tCLASS\tAMOUNT\tMEMO\t",
headers.getSplitHeader());
}
@Test
public void getEndTransactionHeader() {
assertEquals("!ENDTRNS", headers.getEndTransactionHeader());
}
}
| 34.661972 | 99 | 0.670053 |
1198533685ccab579e0dda6ca2ba18033c79217e | 374 | package com.bartosektom.letsplayfolks.repository;
import com.bartosektom.letsplayfolks.entity.ChallengeState;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ChallengeStateRepository extends CrudRepository<ChallengeState, Integer> {
ChallengeState findByState(String state);
}
| 31.166667 | 91 | 0.855615 |
1f375e599003aaa75ccbdef90ae728e4301adadf | 1,855 | package uk.gov.companieshouse.api.accounts.model.rest.profitloss;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Range;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ProfitOrLossBeforeTax {
private static final int MAX_RANGE = 99999999;
private static final int ZERO = 0;
private static final int MIN_RANGE = -99999999;
@Range(min = ZERO, max = MAX_RANGE, message = "value.outside.range")
@JsonProperty("interest_payable_and_similar_charges")
private Long interestPayableAndSimilarCharges;
@Range(min = ZERO, max = MAX_RANGE, message = "value.outside.range")
@JsonProperty("interest_receivable_and_similar_income")
private Long interestReceivableAndSimilarIncome;
@Range(min = MIN_RANGE, max = MAX_RANGE, message = "value.outside.range")
@JsonProperty("total_profit_or_loss_before_tax")
private Long totalProfitOrLossBeforeTax;
public Long getInterestPayableAndSimilarCharges() {
return interestPayableAndSimilarCharges;
}
public void setInterestPayableAndSimilarCharges(Long interestPayableAndSimilarCharges) {
this.interestPayableAndSimilarCharges = interestPayableAndSimilarCharges;
}
public Long getInterestReceivableAndSimilarIncome() {
return interestReceivableAndSimilarIncome;
}
public void setInterestReceivableAndSimilarIncome(Long interestReceivableAndSimilarIncome) {
this.interestReceivableAndSimilarIncome = interestReceivableAndSimilarIncome;
}
public Long getTotalProfitOrLossBeforeTax() {
return totalProfitOrLossBeforeTax;
}
public void setTotalProfitOrLossBeforeTax(Long totalProfitOrLossBeforeTax) {
this.totalProfitOrLossBeforeTax = totalProfitOrLossBeforeTax;
}
}
| 37.1 | 96 | 0.781671 |
4d89a0ce92b0e897712330d14c01039c86d3b1e5 | 227 | package com.day02;
public class Homework07 {
public static void main(String[] args) {
boolean a = false;
boolean b = true;
System.out.println(a&&b);
System.out.println(a||b);
System.out.println(a||b&&a||b);
}
}
| 17.461538 | 41 | 0.647577 |
b0dd62adb5f9798d37255a72640b90aac5e7064b | 33,093 | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config.materials.mercurial;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.SecretParam;
import com.thoughtworks.go.config.materials.Filter;
import com.thoughtworks.go.config.materials.PasswordAwareMaterial;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.config.materials.git.GitMaterial;
import com.thoughtworks.go.domain.MaterialInstance;
import com.thoughtworks.go.domain.MaterialRevision;
import com.thoughtworks.go.domain.materials.*;
import com.thoughtworks.go.domain.materials.mercurial.HgCommand;
import com.thoughtworks.go.domain.materials.mercurial.HgVersion;
import com.thoughtworks.go.domain.materials.mercurial.StringRevision;
import com.thoughtworks.go.helper.HgTestRepo;
import com.thoughtworks.go.helper.MaterialsMother;
import com.thoughtworks.go.helper.TestRepo;
import com.thoughtworks.go.util.JsonValue;
import com.thoughtworks.go.util.ReflectionUtil;
import com.thoughtworks.go.util.command.*;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static com.thoughtworks.go.helper.MaterialConfigsMother.hg;
import static com.thoughtworks.go.util.JsonUtils.from;
import static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
@EnableRuleMigrationSupport
public class HgMaterialTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private static final HgVersion LINUX_HG_094 = HgVersion.parse("Mercurial Distributed SCM (version 0.9.4)\n");
private static final HgVersion WINDOWS_HG_OFFICIAL_102 = HgVersion.parse("Mercurial Distributed SCM (version 1.0.2+20080813)\n");
private static final String WINDOWS_HG_TORTOISE = "Mercurial Distributed SCM (version 626cb86a6523+tortoisehg)";
private static final String REVISION_0 = "b61d12de515d82d3a377ae3aae6e8abe516a2651";
private static final String REVISION_1 = "35ff2159f303ecf986b3650fc4299a6ffe5a14e1";
private static final String REVISION_2 = "ca3ebb67f527c0ad7ed26b789056823d8b9af23f";
@Nested
class PasswordAware {
private HgMaterial material;
@BeforeEach
void setUp() {
material = new HgMaterial("some-url", null);
}
@Test
void shouldBePasswordAwareMaterial() {
assertThat(material).isInstanceOf(PasswordAwareMaterial.class);
}
@Test
void shouldUpdatePasswordFromConfig() {
assertThat(material.getPassword()).isNull();
material.updateFromConfig(hg("some-url", "bob", "badger"));
assertThat(material.getPassword()).isEqualTo("badger");
}
}
@Nested
class SlowOldTestWhichUsesHgCheckout {
private HgMaterial hgMaterial;
private HgTestRepo hgTestRepo;
private File workingFolder;
private InMemoryStreamConsumer outputStreamConsumer;
@BeforeEach
void setUp() throws Exception {
temporaryFolder.create();
hgTestRepo = new HgTestRepo("hgTestRepo1", temporaryFolder);
hgMaterial = MaterialsMother.hgMaterial(hgTestRepo.projectRepositoryUrl());
workingFolder = temporaryFolder.newFolder("workingFolder");
outputStreamConsumer = inMemoryConsumer();
}
@AfterEach
void teardown() {
temporaryFolder.delete();
FileUtils.deleteQuietly(workingFolder);
TestRepo.internalTearDown();
}
@Test
void shouldRefreshWorkingFolderWhenRepositoryChanged() throws Exception {
new HgCommand(null, workingFolder, "default", hgTestRepo.url().originalArgument(), null).clone(inMemoryConsumer(), hgTestRepo.url());
File testFile = createNewFileInWorkingFolder();
HgTestRepo hgTestRepo2 = new HgTestRepo("hgTestRepo2", temporaryFolder);
hgMaterial = MaterialsMother.hgMaterial(hgTestRepo2.projectRepositoryUrl());
hgMaterial.latestModification(workingFolder, new TestSubprocessExecutionContext());
String workingUrl = new HgCommand(null, workingFolder, "default", hgTestRepo.url().originalArgument(), null).workingRepositoryUrl().outputAsString();
assertThat(workingUrl).isEqualTo(hgTestRepo2.projectRepositoryUrl());
assertThat(testFile.exists()).isFalse();
}
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldNotRefreshWorkingFolderWhenFileProtocolIsUsedOnLinux() throws Exception {
final UrlArgument repoUrl = hgTestRepo.url();
new HgCommand(null, workingFolder, "default", repoUrl.originalArgument(), null).clone(inMemoryConsumer(), repoUrl);
File testFile = createNewFileInWorkingFolder();
hgMaterial = MaterialsMother.hgMaterial("file://" + hgTestRepo.projectRepositoryUrl());
updateMaterial(hgMaterial, new StringRevision("0"));
String workingUrl = new HgCommand(null, workingFolder, "default", repoUrl.originalArgument(), null).workingRepositoryUrl().outputAsString();
assertThat(workingUrl).isEqualTo(hgTestRepo.projectRepositoryUrl());
assertThat(testFile.exists()).isTrue();
}
@Test
void shouldGetModifications() {
List<Modification> mods = hgMaterial.modificationsSince(workingFolder, new StringRevision(REVISION_0), new TestSubprocessExecutionContext());
assertThat(mods.size()).isEqualTo(2);
Modification modification = mods.get(0);
assertThat(modification.getRevision()).isEqualTo(REVISION_2);
assertThat(modification.getModifiedFiles().size()).isEqualTo(1);
}
@Test
void shouldNotAppendDestinationDirectoryWhileFetchingModifications() {
hgMaterial.setFolder("dest");
hgMaterial.modificationsSince(workingFolder, new StringRevision(REVISION_0), new TestSubprocessExecutionContext());
assertThat(new File(workingFolder, "dest").exists()).isFalse();
}
@Test
void shouldGetModificationsBasedOnRevision() {
List<Modification> modificationsSince = hgMaterial.modificationsSince(workingFolder,
new StringRevision(REVISION_0), new TestSubprocessExecutionContext());
assertThat(modificationsSince.get(0).getRevision()).isEqualTo(REVISION_2);
assertThat(modificationsSince.get(1).getRevision()).isEqualTo(REVISION_1);
assertThat(modificationsSince.size()).isEqualTo(2);
}
@Test
void shouldReturnLatestRevisionIfNoModificationsDetected() {
List<Modification> modification = hgMaterial.modificationsSince(workingFolder,
new StringRevision(REVISION_2), new TestSubprocessExecutionContext());
assertThat(modification.isEmpty()).isTrue();
}
@Test
void shouldUpdateToSpecificRevision() {
updateMaterial(hgMaterial, new StringRevision("0"));
File end2endFolder = new File(workingFolder, "end2end");
assertThat(end2endFolder.listFiles().length).isEqualTo(3);
assertThat(outputStreamConsumer.getStdOut()).isNotEqualTo("");
updateMaterial(hgMaterial, new StringRevision("1"));
assertThat(end2endFolder.listFiles().length).isEqualTo(4);
}
@Test
void shouldUpdateToDestinationFolder() {
hgMaterial.setFolder("dest");
updateMaterial(hgMaterial, new StringRevision("0"));
File end2endFolder = new File(workingFolder, "dest/end2end");
assertThat(end2endFolder.exists()).isTrue();
}
@Test
void shouldLogRepoInfoToConsoleOutWithoutFolder() {
updateMaterial(hgMaterial, new StringRevision("0"));
assertThat(outputStreamConsumer.getStdOut()).contains(format("Start updating %s at revision %s from %s", "files", "0",
hgMaterial.getUrl()));
}
@Test
void shouldDeleteWorkingFolderWhenItIsNotAnHgRepository() throws Exception {
File testFile = createNewFileInWorkingFolder();
hgMaterial.latestModification(workingFolder, new TestSubprocessExecutionContext());
assertThat(testFile.exists()).isFalse();
}
@Test
void shouldThrowExceptionWithUsefulInfoIfFailedToFindModifications() {
final String url = "/tmp/notExistDir";
hgMaterial = MaterialsMother.hgMaterial(url);
try {
hgMaterial.latestModification(workingFolder, new TestSubprocessExecutionContext());
fail("Should have thrown an exception when failed to clone from an invalid url");
} catch (Exception e) {
assertThat(e.getMessage()).contains("abort: repository " + url + " not found!");
}
}
private File createNewFileInWorkingFolder() throws IOException {
if (!workingFolder.exists()) {
workingFolder.mkdirs();
}
File testFile = new File(workingFolder, "not_in_hg_repository.txt");
testFile.createNewFile();
return testFile;
}
@Test
void shouldReturnFalseWhenVersionIsNotRecgonized() {
assertThatCode(() -> hgMaterial.isVersionOneDotZeroOrHigher(WINDOWS_HG_TORTOISE))
.isInstanceOf(Exception.class);
}
@Test
void shouldCheckConnection() {
ValidationBean validation = hgMaterial.checkConnection(new TestSubprocessExecutionContext());
assertThat(validation.isValid()).isTrue();
String notExistUrl = "http://notExisthost/hg";
hgMaterial = MaterialsMother.hgMaterial(notExistUrl);
validation = hgMaterial.checkConnection(new TestSubprocessExecutionContext());
assertThat(validation.isValid()).isFalse();
}
@Test
void shouldReturnInvalidBeanWithRootCauseAsLowerVersionInstalled() {
ValidationBean validationBean = hgMaterial.handleException(new Exception(), LINUX_HG_094);
assertThat(validationBean.isValid()).isFalse();
assertThat(validationBean.getError()).contains("Please install Mercurial Version 1.0 or above");
}
@Test
void shouldReturnInvalidBeanWithRootCauseAsRepositoryURLIsNotFound() {
ValidationBean validationBean = hgMaterial.handleException(new Exception(), WINDOWS_HG_OFFICIAL_102);
assertThat(validationBean.isValid()).isFalse();
assertThat(validationBean.getError()).contains("not found!");
}
@Test
void shouldBeAbleToConvertToJson() {
Map<String, Object> json = new LinkedHashMap<>();
hgMaterial.toJson(json, new StringRevision("123"));
JsonValue jsonValue = from(json);
assertThat(jsonValue.getString("scmType")).isEqualTo("Mercurial");
assertThat(new File(jsonValue.getString("location"))).isEqualTo(new File(hgTestRepo.projectRepositoryUrl()));
assertThat(jsonValue.getString("action")).isEqualTo("Modified");
}
// #3103
@Test
void shouldParseComplexCommitMessage() throws Exception {
String comment = "changeset: 8139:b1a0b0bbb4d1\n"
+ "branch: trunk\n"
+ "user: QYD\n"
+ "date: Tue Jun 30 14:56:37 2009 +0800\n"
+ "summary: add story #3001 - 'Pipelines should use the latest version of ...";
hgTestRepo.commitAndPushFile("SomeDocumentation.txt", comment);
List<Modification> modification = hgMaterial.latestModification(workingFolder, new TestSubprocessExecutionContext());
assertThat(modification.size()).isEqualTo(1);
assertThat(modification.get(0).getComment()).isEqualTo(comment);
}
@Test
void shouldGenerateSqlCriteriaMapInSpecificOrder() {
Map<String, Object> map = hgMaterial.getSqlCriteria();
assertThat(map.size()).isEqualTo(2);
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
assertThat(iter.next().getKey()).isEqualTo("type");
assertThat(iter.next().getKey()).isEqualTo("url");
}
private void updateMaterial(HgMaterial hgMaterial, StringRevision revision) {
hgMaterial.updateTo(outputStreamConsumer, workingFolder, new RevisionContext(revision), new TestSubprocessExecutionContext());
}
}
@Test
void checkConnectionShouldUseUrlForCommandLine() {
final HgMaterial material = spy(new HgMaterial("http://example.com", ""));
material.setUserName("bob");
material.setPassword("password");
material.checkConnection(new TestSubprocessExecutionContext());
verify(material, atLeastOnce()).urlForCommandLine();
}
@Test
void shouldNotRefreshWorkingDirectoryIfDefaultRemoteUrlDoesNotContainPasswordButMaterialUrlDoes() throws Exception {
final HgMaterial material = new HgMaterial("http://user:pwd@domain:9999/path", null);
final HgCommand hgCommand = mock(HgCommand.class);
final ConsoleResult consoleResult = mock(ConsoleResult.class);
when(consoleResult.outputAsString()).thenReturn("http://user@domain:9999/path");
when(hgCommand.workingRepositoryUrl()).thenReturn(consoleResult);
assertThat((Boolean) ReflectionUtil.invoke(material, "isRepositoryChanged", hgCommand)).isFalse();
}
@Test
void shouldRefreshWorkingDirectoryIfUsernameInDefaultRemoteUrlIsDifferentFromOneInMaterialUrl() throws Exception {
final HgMaterial material = new HgMaterial("http://some_new_user:pwd@domain:9999/path", null);
final HgCommand hgCommand = mock(HgCommand.class);
final ConsoleResult consoleResult = mock(ConsoleResult.class);
when(consoleResult.outputAsString()).thenReturn("http://user:pwd@domain:9999/path");
when(hgCommand.workingRepositoryUrl()).thenReturn(consoleResult);
assertThat((Boolean) ReflectionUtil.invoke(material, "isRepositoryChanged", hgCommand)).isTrue();
}
@Test
void shouldBeEqualWhenUrlSameForHgMaterial() {
final Material material = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
final Material anotherMaterial = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
assertThat(material.equals(anotherMaterial)).isTrue();
assertThat(anotherMaterial.equals(material)).isTrue();
}
@Test
void shouldNotBeEqualWhenUrlDifferent() {
final Material material1 = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
final Material material2 = MaterialsMother.hgMaterials("url2", "hgdir").get(0);
assertThat(material1.equals(material2)).isFalse();
assertThat(material2.equals(material1)).isFalse();
}
@Test
void shouldNotBeEqualWhenTypeDifferent() {
final Material material = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
final Material svnMaterial = MaterialsMother.defaultSvnMaterialsWithUrl("url1").get(0);
assertThat(material.equals(svnMaterial)).isFalse();
assertThat(svnMaterial.equals(material)).isFalse();
}
@Test
void shouldBeEqual() {
final Material hgMaterial1 = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
final Material hgMaterial2 = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
assertThat(hgMaterial1.equals(hgMaterial2)).isTrue();
assertThat(hgMaterial1.hashCode()).isEqualTo(hgMaterial2.hashCode());
}
@Test
void shouldRemoveTheForwardSlashAndApplyThePattern() {
Material material = MaterialsMother.hgMaterial();
assertThat(material.matches("a.doc", "/a.doc")).isTrue();
assertThat(material.matches("/a.doc", "a.doc")).isFalse();
}
@Test
void shouldApplyThePatternDirectly() {
Material material = MaterialsMother.hgMaterial();
assertThat(material.matches("a.doc", "a.doc")).isTrue();
}
/**
* An hg abbreviated hash is 12 chars. See the hg documentation.
* %h: short-form changeset hash (12 bytes of hexadecimal)
*/
@Test
void shouldtruncateHashTo12charsforAShortRevision() {
Material hgMaterial = new HgMaterial("file:///foo", null);
assertThat(hgMaterial.getShortRevision("dc3d7e656831d1b203d8b7a63c4de82e26604e52")).isEqualTo("dc3d7e656831");
assertThat(hgMaterial.getShortRevision("dc3d7e65683")).isEqualTo("dc3d7e65683");
assertThat(hgMaterial.getShortRevision("dc3d7e6568312")).isEqualTo("dc3d7e656831");
assertThat(hgMaterial.getShortRevision("24")).isEqualTo("24");
assertThat(hgMaterial.getShortRevision(null)).isNull();
}
@Test
void shouldNotDisplayPasswordInToString() {
HgMaterial hgMaterial = new HgMaterial("https://user:loser@foo.bar/baz?quux=bang", null);
assertThat(hgMaterial.toString()).doesNotContain("loser");
}
@Test
void shouldGetLongDescriptionForMaterial() {
HgMaterial material = new HgMaterial("http://url/", "folder");
assertThat(material.getLongDescription()).isEqualTo("URL: http://url/");
}
@Test
void shouldFindTheBranchName() {
HgMaterial material = new HgMaterial("http://url/##foo", "folder");
assertThat(material.getBranch()).isEqualTo("foo");
}
@Test
void shouldSetDefaultAsBranchNameIfBranchNameIsNotSpecifiedInUrl() {
HgMaterial material = new HgMaterial("http://url/", "folder");
assertThat(material.getBranch()).isEqualTo("default");
}
@Test
void shouldMaskThePasswordInDisplayName() {
HgMaterial material = new HgMaterial("http://user:pwd@url##branch", "folder");
assertThat(material.getDisplayName()).isEqualTo("http://user:******@url##branch");
}
@Test
void shouldGetAttributesWithSecureFields() {
HgMaterial material = new HgMaterial("http://username:password@hgrepo.com", null);
Map<String, Object> attributes = material.getAttributes(true);
assertThat(attributes.get("type")).isEqualTo("mercurial");
Map<String, Object> configuration = (Map<String, Object>) attributes.get("mercurial-configuration");
assertThat(configuration.get("url")).isEqualTo("http://username:password@hgrepo.com");
}
@Test
void shouldGetAttributesWithoutSecureFields() {
HgMaterial material = new HgMaterial("http://username:password@hgrepo.com", null);
Map<String, Object> attributes = material.getAttributes(false);
assertThat(attributes.get("type")).isEqualTo("mercurial");
Map<String, Object> configuration = (Map<String, Object>) attributes.get("mercurial-configuration");
assertThat(configuration.get("url")).isEqualTo("http://username:******@hgrepo.com");
}
@Nested
class Equals {
@Test
void shouldBeEqualIfObjectsHaveSameUrlAndBranch() {
final HgMaterial material_1 = new HgMaterial("http://example.com", "master");
material_1.setUserName("bob");
material_1.setBranch("feature");
final HgMaterial material_2 = new HgMaterial("http://example.com", "master");
material_2.setUserName("bob");
material_2.setBranch("feature");
assertThat(material_1.equals(material_2)).isTrue();
}
}
@Nested
class Fingerprint {
@Test
void shouldGenerateFingerprintForGivenMaterialUrl() {
HgMaterial hgMaterial = new HgMaterial("https://bob:pass@github.com/gocd#feature", "dest");
assertThat(hgMaterial.getFingerprint()).isEqualTo("d84d91f37da0367a9bd89fff0d48638f5c1bf993d637735ec26f13c21c23da19");
}
@Test
void shouldConsiderBranchWhileGeneratingFingerprint_IfBranchSpecifiedAsAnAttribute() {
HgMaterial hgMaterial = new HgMaterial("https://bob:pass@github.com/gocd", "dest");
hgMaterial.setBranch("feature");
assertThat(hgMaterial.getFingerprint()).isEqualTo("db13278ed2b804fc5664361103bcea3d7f5106879683085caed4311aa4d2f888");
}
@Test
void branchInUrlShouldGenerateFingerprintWhichIsOtherFromBranchInAttribute() {
HgMaterial hgMaterialWithBranchInUrl = new HgMaterial("https://github.com/gocd##feature", "dest");
HgMaterial hgMaterialWithBranchAsAttribute = new HgMaterial("https://github.com/gocd", "dest");
hgMaterialWithBranchAsAttribute.setBranch("feature");
assertThat(hgMaterialWithBranchInUrl.getFingerprint())
.isNotEqualTo(hgMaterialWithBranchAsAttribute.getFingerprint());
}
@Nested
class fingerPrintComparisionBetweenHgMaterialAndHgMaterialConfig {
@Test
void fingerprintGeneratedByHgMaterialAndHgMaterialConfigShouldBeSame() {
HgMaterial hgMaterial = new HgMaterial("https://github.com/gocd#feature", "dest");
assertThat(hgMaterial.getFingerprint()).isEqualTo(hgMaterial.config().getFingerprint());
}
@Test
void fingerprintGeneratedByHgMaterialAndHgMaterialConfigShouldBeSameWhenBranchProvidedAsAttribute() {
HgMaterial hgMaterial = new HgMaterial("https://github.com/gocd", "dest");
hgMaterial.setBranch("feature");
assertThat(hgMaterial.getFingerprint()).isEqualTo(hgMaterial.config().getFingerprint());
}
}
}
@Nested
class getBranch {
@Test
void shouldBeTheBranchAttributeIfSpecified() {
HgMaterial hgMaterial = new HgMaterial("https://github.com/gocd", "dest");
hgMaterial.setBranch("feature");
assertThat(hgMaterial.getBranch()).isEqualTo("feature");
}
@Test
void shouldBeBranchFromUrlIfBranchNotSpecifedAsAttribute() {
HgMaterial hgMaterial = new HgMaterial("https://github.com/gocd#from_url", "dest");
assertThat(hgMaterial.getBranch()).isEqualTo("from_url");
}
@Test
void shouldBeDefaultBranchIfBranchNotSpecified() {
HgMaterial hgMaterial = new HgMaterial("https://github.com/gocd", "dest");
assertThat(hgMaterial.getBranch()).isEqualTo("default");
}
}
@Nested
class ConfigToMaterial {
@Test
void shouldBuildFromConfigObject() {
final HgMaterialConfig materialConfig = hg(new HgUrlArgument("http://example.com"), "bob", "pass",
"feature", true, Filter.create("igrnored"), false, "destination",
new CaseInsensitiveString("example"));
final HgMaterial hgMaterial = new HgMaterial(materialConfig);
assertThat(hgMaterial.getUrl()).isEqualTo(materialConfig.getUrl());
assertThat(hgMaterial.getUserName()).isEqualTo(materialConfig.getUserName());
assertThat(hgMaterial.getPassword()).isEqualTo(materialConfig.getPassword());
assertThat(hgMaterial.getBranch()).isEqualTo(materialConfig.getBranch());
assertThat(hgMaterial.getAutoUpdate()).isEqualTo(materialConfig.getAutoUpdate());
assertThat(hgMaterial.getInvertFilter()).isEqualTo(materialConfig.getInvertFilter());
assertThat(hgMaterial.getFolder()).isEqualTo(materialConfig.getFolder());
assertThat(hgMaterial.getName()).isEqualTo(materialConfig.getName());
assertThat(hgMaterial.getFingerprint()).isEqualTo(materialConfig.getFingerprint());
}
}
@Nested
class MaterialToConfig {
@Test
void shouldBuildConfigFromMaterialObject() {
final HgMaterial hgMaterial = new HgMaterial("http://example.com", "destination");
hgMaterial.setUserName("bob");
hgMaterial.setPassword("pass");
hgMaterial.setBranch("feature");
hgMaterial.setAutoUpdate(true);
hgMaterial.setName(new CaseInsensitiveString("example"));
hgMaterial.setInvertFilter(true);
hgMaterial.setFolder("destination");
hgMaterial.setFilter(Filter.create("whitelist"));
final HgMaterialConfig materialConfig = (HgMaterialConfig) hgMaterial.config();
assertThat(hgMaterial.getUrl()).isEqualTo(materialConfig.getUrl());
assertThat(hgMaterial.getUserName()).isEqualTo(materialConfig.getUserName());
assertThat(hgMaterial.getPassword()).isEqualTo(materialConfig.getPassword());
assertThat(hgMaterial.getBranch()).isEqualTo(materialConfig.getBranch());
assertThat(hgMaterial.getAutoUpdate()).isEqualTo(materialConfig.getAutoUpdate());
assertThat(hgMaterial.getInvertFilter()).isEqualTo(materialConfig.getInvertFilter());
assertThat(hgMaterial.getFolder()).isEqualTo(materialConfig.getFolder());
assertThat(hgMaterial.getName()).isEqualTo(materialConfig.getName());
assertThat(hgMaterial.getFingerprint()).isEqualTo(materialConfig.getFingerprint());
}
}
@Nested
class urlForCommandLine {
@Test
void shouldBeSameAsTheConfiguredUrlForTheMaterial() {
final HgMaterial hgMaterial = new HgMaterial("http://bob:pass@exampele.com", "destination");
assertThat(hgMaterial.urlForCommandLine()).isEqualTo("http://bob:pass@exampele.com");
}
@Test
void shouldIncludeUserInfoIfProvidedAsUsernameAndPasswordAttributes() {
final HgMaterial hgMaterial = new HgMaterial("http://exampele.com", "destination");
hgMaterial.setUserName("bob");
hgMaterial.setPassword("pass");
assertThat(hgMaterial.urlForCommandLine()).isEqualTo("http://bob:pass@exampele.com");
}
@Test
void shouldIncludeUserNameIfProvidedAsUsernameAttributes() {
final HgMaterial hgMaterial = new HgMaterial("http://exampele.com", "destination");
hgMaterial.setUserName("bob");
assertThat(hgMaterial.urlForCommandLine()).isEqualTo("http://bob@exampele.com");
}
@Test
void shouldIncludePasswordIfProvidedAsPasswordAttribute() {
final HgMaterial hgMaterial = new HgMaterial("http://exampele.com", "destination");
hgMaterial.setPassword("pass");
assertThat(hgMaterial.urlForCommandLine()).isEqualTo("http://:pass@exampele.com");
}
@Test
void shouldEncodeUserInfoIfProvidedAsUsernamePasswordAttributes() {
final HgMaterial hgMaterial = new HgMaterial("http://exampele.com", "destination");
hgMaterial.setUserName("bob@example.com");
hgMaterial.setPassword("p@ssw:rd");
assertThat(hgMaterial.urlForCommandLine()).isEqualTo("http://bob%40example.com:p%40ssw:rd@exampele.com");
}
@Test
void shouldHaveResolvedUserInfoIfSecretParamsIsPresent() {
final HgMaterial gitMaterial = new HgMaterial("http://exampele.com", "destination");
gitMaterial.setUserName("bob@example.com");
String password = "{{SECRET:[test][id]}}";
gitMaterial.setPassword(password);
SecretParam secretParam = gitMaterial.getSecretParams().get(0);
secretParam.setValue("p@ssw:rd");
assertThat(gitMaterial.urlForCommandLine()).isEqualTo("http://bob%40example.com:p%40ssw:rd@exampele.com");
}
}
@Nested
class createMaterialInstance {
@Test
void shouldCreateMaterialInstanceObject() {
final HgMaterial hgMaterial = new HgMaterial("http://exampele.com#feature", "destination");
hgMaterial.setUserName("bob");
MaterialInstance materialInstance = hgMaterial.createMaterialInstance();
assertThat(materialInstance.getUrl()).isEqualTo(hgMaterial.getUrl());
assertThat(materialInstance.getUsername()).isEqualTo(hgMaterial.getUserName());
assertThat(materialInstance.getBranch()).isNull();
}
@Test
void shouldCreateMaterialInstanceObjectWithBranchProvidedAttributeInMaterial() {
final HgMaterial hgMaterial = new HgMaterial("http://exampele.com", "destination");
hgMaterial.setUserName("bob");
hgMaterial.setBranch("branch-as-attribute");
MaterialInstance materialInstance = hgMaterial.createMaterialInstance();
assertThat(materialInstance.getUrl()).isEqualTo(hgMaterial.getUrl());
assertThat(materialInstance.getUsername()).isEqualTo(hgMaterial.getUserName());
assertThat(materialInstance.getBranch()).isEqualTo("branch-as-attribute");
}
}
@Nested
class secrets {
@Test
void shouldReplaceUrlForCommandLineWithUrlForDisplay_whenCredntialsAreProvidedInUrl() {
HgMaterial hgMaterial = new HgMaterial("https://bob:pass@example.com", "destinations");
String info = hgMaterial.secrets().get(0).replaceSecretInfo("https://bob:pass@example.com");
assertThat(info).isEqualTo(hgMaterial.getUriForDisplay());
}
@Test
void shouldReplaceUrlForCommandLineWithUrlForDisplay_whenCredentialsAreProvidedAsAttributes() {
HgMaterial hgMaterial = new HgMaterial("https://example.com", "destinations");
hgMaterial.setUserName("bob");
hgMaterial.setPassword("pass");
String info = hgMaterial.secrets().get(0).replaceSecretInfo("https://bob:pass@example.com");
assertThat(info).isEqualTo(hgMaterial.getUriForDisplay());
}
}
@Test
void populateEnvContextShouldSetMaterialEnvVars() {
HgMaterial material = new HgMaterial("https://user:password@github.com/bob/my-project", "folder");
material.setBranch("branchName");
EnvironmentVariableContext ctx = new EnvironmentVariableContext();
final ArrayList<Modification> modifications = new ArrayList<>();
modifications.add(new Modification("user2", "comment2", "email2", new Date(), "24"));
modifications.add(new Modification("user1", "comment1", "email1", new Date(), "23"));
MaterialRevision materialRevision = new MaterialRevision(material, modifications);
assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL)).isNull();
assertThat(ctx.getProperty(GitMaterial.GO_MATERIAL_BRANCH)).isNull();
material.populateEnvironmentContext(ctx, materialRevision, new File("."));
String propertySuffix = material.getMaterialNameForEnvironmentVariable();
assertThat(ctx.getProperty(format("%s_%s", ScmMaterial.GO_MATERIAL_URL, propertySuffix))).isEqualTo("https://github.com/bob/my-project");
assertThat(ctx.getProperty(format("%s_%s", GitMaterial.GO_MATERIAL_BRANCH, propertySuffix))).isEqualTo("branchName");
}
@Test
void shouldPopulateBranchWithDefaultIfNotSet() {
HgMaterial material = new HgMaterial("https://user:password@github.com/bob/my-project", "folder");
EnvironmentVariableContext ctx = new EnvironmentVariableContext();
final ArrayList<Modification> modifications = new ArrayList<>();
modifications.add(new Modification("user1", "comment1", "email1", new Date(), "23"));
MaterialRevision materialRevision = new MaterialRevision(material, modifications);
material.populateEnvironmentContext(ctx, materialRevision, new File("."));
String propertySuffix = material.getMaterialNameForEnvironmentVariable();
assertThat(ctx.getProperty(format("%s_%s", GitMaterial.GO_MATERIAL_BRANCH, propertySuffix))).isEqualTo("default");
}
}
| 45.395062 | 161 | 0.680476 |
f8304d4b3871790e4892b4a70bda3cc6fbe761bd | 1,147 |
package com.codepath.apps.simpletweets.models.gson.singletweet;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.parceler.Generated;
@Generated("org.jsonschema2pojo")
public class Small {
@SerializedName("w")
@Expose
private Long w;
@SerializedName("h")
@Expose
private Long h;
@SerializedName("resize")
@Expose
private String resize;
/**
*
* @return
* The w
*/
public Long getW() {
return w;
}
/**
*
* @param w
* The w
*/
public void setW(Long w) {
this.w = w;
}
/**
*
* @return
* The h
*/
public Long getH() {
return h;
}
/**
*
* @param h
* The h
*/
public void setH(Long h) {
this.h = h;
}
/**
*
* @return
* The resize
*/
public String getResize() {
return resize;
}
/**
*
* @param resize
* The resize
*/
public void setResize(String resize) {
this.resize = resize;
}
}
| 14.896104 | 63 | 0.489974 |
8ccf9dd560a256b97d58da5551c648d1cdb82a08 | 123 | package com.example.invoke.common;
public enum DataSourceKey {
DB_MASTER,
DB_SLAVE1,
DB_SLAVE2,
DB_OTHER
} | 15.375 | 34 | 0.707317 |
2f49179c6d20a437e9cb3df67a8c6e48b7ecb030 | 1,098 | package com.beowulfe.hap.impl.characteristics.valve;
import com.beowulfe.hap.HomekitCharacteristicChangeCallback;
import com.beowulfe.hap.accessories.ValveWithTimer;
import com.beowulfe.hap.characteristics.EventableCharacteristic;
import com.beowulfe.hap.characteristics.IntegerCharacteristic;
import java.util.concurrent.CompletableFuture;
public class SetDurationCharacteristic extends IntegerCharacteristic
implements EventableCharacteristic {
private final ValveWithTimer valve;
public SetDurationCharacteristic(ValveWithTimer valve) {
super("000000D3-0000-1000-8000-0026BB765291", true, true, null, 0, 3600, "seconds");
this.valve = valve;
}
@Override
public void subscribe(HomekitCharacteristicChangeCallback callback) {
valve.subscribeSetDuration(callback);
}
@Override
public void unsubscribe() {
valve.unsubscribeSetDuration();
}
@Override
protected void setValue(Integer value) throws Exception {
valve.setSetDuration(value);
}
@Override
protected CompletableFuture<Integer> getValue() {
return valve.getSetDuration();
}
}
| 28.894737 | 88 | 0.788707 |
01a130079de2adea3117cb1a5d5351ae3ec73123 | 2,045 | /*
* Copyright 2010-2020 Australian Signals Directorate
*
* 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 au.gov.asd.tac.constellation.views.conversationview;
import au.gov.asd.tac.constellation.graph.GraphReadMethods;
import au.gov.asd.tac.constellation.utilities.temporal.TimeZoneUtilities;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.util.List;
/**
* The DefaultConversationBackgroundProvider updates the background color behind
* the bubbles to alternating colors so that bubbles that occur on the same day
* are the same color.
*
* @author sirius
*/
public class DefaultConversationBackgroundProvider implements ConversationBackgroundProvider {
@Override
public void updateMessageBackgrounds(GraphReadMethods graph, List<ConversationMessage> messages) {
//Background bg = new Background(new BackgroundFill(Color.RED, null, null));
String[] colors = new String[]{"transparent", "rgb(60, 60, 60)"};
int currentColor = 1;
int currentDay = -1;
for (ConversationMessage message : messages) {
// Get the unique day since the epcoh of the date-time in UTC.
final int day = (int) ZonedDateTime.of(message.getDatetime().getDate().toLocalDateTime(), TimeZoneUtilities.UTC).getLong(ChronoField.EPOCH_DAY);
if (day != currentDay) {
currentColor ^= 1;
currentDay = day;
}
message.setBackgroundColor(colors[currentColor]);
}
}
}
| 37.87037 | 156 | 0.714425 |
183a916d6d914c1027ffe9b9e309a268e598a23b | 481 | package org.cyberborean.rdfbeans.impl;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
public class Constants {
public static final IRI BINDINGCLASS_PROPERTY = SimpleValueFactory.getInstance().createIRI(
"http://viceversatech.com/rdfbeans/2.0/bindingClass");
public static final IRI BINDINGIFACE_PROPERTY = SimpleValueFactory.getInstance().createIRI(
"http://viceversatech.com/rdfbeans/2.0/bindingIface");
}
| 32.066667 | 93 | 0.773389 |
42a1691bf2c13b318c29204d11ecb4bdcd3b109e | 3,535 |
package com.vzome.core.zomic;
import com.vzome.core.math.symmetry.Axis;
import com.vzome.core.math.symmetry.Direction;
import com.vzome.core.math.symmetry.DirectionNaming;
import com.vzome.core.math.symmetry.IcosahedralSymmetry;
import com.vzome.core.math.symmetry.NamingConvention;
import com.vzome.core.math.symmetry.Permutation;
import com.vzome.core.math.symmetry.Symmetry;
/**
* @author Scott Vorthmann
*
*/
public class ZomicNamingConvention extends NamingConvention
{
public static final int SHORT = 3;
public static final int MEDIUM = 4;
public static final int LONG = 5;
public ZomicNamingConvention( IcosahedralSymmetry symm )
{
Direction dir = symm .getDirection( "red" );
DirectionNaming redNames = new ZomodDirectionNaming( dir, new int[]{ 0, 1, 2, 15, 17, 46 } );
addDirectionNaming( redNames );
dir = symm .getDirection( "yellow" );
DirectionNaming yellowNames = new ZomodDirectionNaming( dir, new int[]{ 6, 9, 12, 0, 3, 1, 14, 5, 24, 17 } );
addDirectionNaming( yellowNames );
dir = symm .getDirection( "blue" );
addDirectionNaming( new ZomodDirectionNaming( dir, new int[]{ 9, 12, 0, 3, 6, 1, 14, 18, 26, 52, 58, 4, 7, 2, 5 } ) );
dir = symm .getDirection( "olive" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "maroon" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "lavender" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "rose" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "navy" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "turquoise" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "coral" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "sulfur" );
addDirectionNaming( new DirectionNaming( dir, dir .getName() ) );
dir = symm .getDirection( "green" );
addDirectionNaming( new GreenDirectionNaming( dir, redNames, yellowNames ) );
dir = symm .getDirection( "orange" );
addDirectionNaming( new GreenDirectionNaming( dir, redNames, yellowNames ) );
dir = symm .getDirection( "purple" );
addDirectionNaming( new GreenDirectionNaming( dir, redNames, yellowNames ) {
@Override
public String getName( Axis axis )
{
int orn = axis .getOrientation();
Axis redNeighbor = mRedNames .getDirection() .getAxis( axis .getSense(), orn );
String redName = mRedNames .getName( redNeighbor );
// rotate twice since purple RY is opposite green RY
Permutation rot = redNeighbor .getRotationPermutation();
orn = rot .mapIndex( rot .mapIndex( orn ) );
if ( axis.getSense() == Symmetry .MINUS )
orn = rot .mapIndex( orn );
Axis yellowNeighbor = mYellowNames .getDirection() .getAxis( axis .getSense(), orn );
String yellowName = mYellowNames .getName( yellowNeighbor ) .substring( 1 ); // remove the sign
// System .out .println( SIGN[ axis.getSense() ] + axis .getOrientation() + " is purple " + redName + yellowName );
return redName + yellowName;
}
} );
dir = symm .getDirection( "black" );
addDirectionNaming( new BlackDirectionNaming( dir, redNames, yellowNames ) );
}
}
| 43.109756 | 121 | 0.665347 |
92724a268b64cead47113121271d7ca026a6e5fe | 1,179 | package com.globallypaid.example.customer;
import com.globallypaid.exception.GloballyPaidException;
import com.globallypaid.http.Config;
import com.globallypaid.service.Customer;
import java.io.IOException;
import java.util.List;
public class CustomersRetrieve {
public static void main(String[] args) throws IOException, GloballyPaidException {
new Customer(
Config.builder()
.publishableApiKey(System.getenv("PUBLISHABLE_API_KEY"))
.appId(System.getenv("APP_ID"))
.sharedSecret(System.getenv("SHARED_SECRET"))
.sandbox(System.getenv("USE_SANDBOX"))
.build());
try {
List<Customer> customers = Customer.builder().build().list();
System.out.println("Retrieved customers: " + customers);
customers.forEach(
c -> System.out.println("Customer: " + c.getFirstName() + " " + c.getLastName()));
} catch (GloballyPaidException e) {
System.out.println(
"Customer retrieve ---> Code: "
+ e.getCode()
+ "\nMsg: "
+ e.getMessage()
+ "\nApi error: "
+ e.getGloballyPaidError());
}
}
}
| 32.75 | 92 | 0.620865 |
b66009860de98d103df77f3974b2412bba400ba8 | 1,109 | package org.fastcatsearch.ir.group.value;
import java.util.List;
import org.fastcatsearch.ir.group.GroupFunctionType;
import org.fastcatsearch.ir.group.GroupingValue;
public class FloatGroupingValue extends GroupingValue<Float> {
public FloatGroupingValue(GroupFunctionType type) {
super(type);
}
public FloatGroupingValue(Float i, GroupFunctionType type) {
super(i, type);
}
@Override
public void add(Float i) {
if (value == null) {
value = i;
} else {
value = value + i;
}
}
@Override
public void increment() {
if(value == null) {
value = 0f;
}
value++;
}
@Override
public int compareTo(GroupingValue<Float> o) {
float cmp = value - o.get();
return cmp == 0f ? 0 : (cmp < 0 ? -1 : 1);
}
public static FloatGroupingValue[] createList(int groupKeySize, GroupFunctionType type) {
FloatGroupingValue[] list = new FloatGroupingValue[groupKeySize];
for (int i = 0; i < groupKeySize; i++) {
list[i] = new FloatGroupingValue(type);
}
return list;
}
@Override
public boolean isEmpty() {
return value == null;
}
}
| 20.537037 | 90 | 0.662759 |
ea97f0fb3fe13979daf4c42fe95d23eeb2005cb4 | 2,695 | /*
* Copyright (c) 2018 CA. All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.ca.apim.gateway.cagatewayconfig.bundle.loader;
import com.ca.apim.gateway.cagatewayconfig.beans.Bundle;
import com.ca.apim.gateway.cagatewayconfig.beans.ScheduledTask;
import com.ca.apim.gateway.cagatewayconfig.util.entity.EntityTypes;
import org.w3c.dom.Element;
import javax.inject.Singleton;
import java.util.Map;
import static com.ca.apim.gateway.cagatewayconfig.util.gateway.BuilderUtils.mapPropertiesElements;
import static com.ca.apim.gateway.cagatewayconfig.util.gateway.BundleElementNames.*;
import static com.ca.apim.gateway.cagatewayconfig.util.xml.DocumentUtils.*;
import static org.apache.commons.lang3.BooleanUtils.toBoolean;
@Singleton
public class ScheduledTaskLoader implements BundleEntityLoader {
@Override
public void load(Bundle bundle, Element element) {
final Element scheduledTask = getSingleChildElement(getSingleChildElement(element, RESOURCE), SCHEDULED_TASK);
final String policyId = getSingleChildElementAttribute(scheduledTask, POLICY_REFERENCE, ATTRIBUTE_ID);
final String name = getSingleChildElementTextContent(scheduledTask, NAME);
final boolean isOneNode = toBoolean(getSingleChildElementTextContent(scheduledTask, ONE_NODE));
final String jobType = getSingleChildElementTextContent(scheduledTask, JOB_TYPE);
final String jobStatus = getSingleChildElementTextContent(scheduledTask, JOB_STATUS);
final String executionDate = getSingleChildElementTextContent(scheduledTask, EXECUTION_DATE);
final String cronExpression = getSingleChildElementTextContent(scheduledTask, CRON_EXPRESSION);
final boolean shouldExecuteOnCreate = toBoolean(getSingleChildElementTextContent(scheduledTask, EXECUTE_ON_CREATE));
final Map<String, Object> properties = mapPropertiesElements(getSingleChildElement(scheduledTask, PROPERTIES, true), PROPERTIES);
ScheduledTask task = new ScheduledTask();
task.setId(scheduledTask.getAttribute(ATTRIBUTE_ID));
task.setPolicy(policyId);
task.setName(name);
task.setOneNode(isOneNode);
task.setJobType(jobType);
task.setJobStatus(jobStatus);
task.setExecutionDate(executionDate);
task.setCronExpression(cronExpression);
task.setShouldExecuteOnCreate(shouldExecuteOnCreate);
task.setProperties(properties);
bundle.getScheduledTasks().put(name, task);
}
@Override
public String getEntityType() {
return EntityTypes.SCHEDULED_TASK_TYPE;
}
}
| 46.465517 | 137 | 0.773655 |
9171af4fd1503dba10ddf692c3605c32e2515c32 | 8,690 | package org.xdef.transform.xsd.xd2schema.factory.facet;
import org.apache.ws.commons.schema.XmlSchemaEnumerationFacet;
import org.apache.ws.commons.schema.XmlSchemaFacet;
import org.apache.ws.commons.schema.XmlSchemaFractionDigitsFacet;
import org.apache.ws.commons.schema.XmlSchemaLengthFacet;
import org.apache.ws.commons.schema.XmlSchemaMaxExclusiveFacet;
import org.apache.ws.commons.schema.XmlSchemaMaxInclusiveFacet;
import org.apache.ws.commons.schema.XmlSchemaMaxLengthFacet;
import org.apache.ws.commons.schema.XmlSchemaMinExclusiveFacet;
import org.apache.ws.commons.schema.XmlSchemaMinInclusiveFacet;
import org.apache.ws.commons.schema.XmlSchemaMinLengthFacet;
import org.apache.ws.commons.schema.XmlSchemaPatternFacet;
import org.apache.ws.commons.schema.XmlSchemaTotalDigitsFacet;
import org.apache.ws.commons.schema.XmlSchemaWhiteSpaceFacet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xdef.XDNamedValue;
import org.xdef.transform.xsd.msg.XSD;
import org.xdef.transform.xsd.xd2schema.model.impl.XsdAdapterCtx;
import java.util.ArrayList;
import java.util.List;
import static org.xdef.transform.xsd.util.LoggingUtil.logHeader;
import static org.xdef.transform.xsd.xd2schema.def.AlgPhase.TRANSFORMATION;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XD_FACET_FORMAT;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XD_INTERNAL_FACET_OUTFORMAT;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_ENUMERATION;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_FRACTION_DIGITS;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_LENGTH;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_MAX_EXCLUSIVE;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_MAX_INCLUSIVE;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_MAX_LENGTH;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_MIN_EXCLUSIVE;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_MIN_INCLUSIVE;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_MIN_LENGTH;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_PATTERN;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_TOTAL_DIGITS;
import static org.xdef.transform.xsd.xd2schema.def.Xd2XsdDefinitions.XSD_FACET_WHITESPACE;
/**
* Base class for transformation of facets
*/
public abstract class AbstractXsdFacetFactory implements IXsdFacetFactory {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
/**
* XML Schema adapter context
*/
protected XsdAdapterCtx adapterCtx;
/**
* X-definition value type
*/
protected ValueType valueType;
@Override
public void setAdapterCtx(XsdAdapterCtx adapterCtx) {
this.adapterCtx = adapterCtx;
}
@Override
public List<XmlSchemaFacet> build(final XDNamedValue[] params) {
LOG.debug("{}Building facets ...", logHeader(TRANSFORMATION));
List<XmlSchemaFacet> facets = new ArrayList<>();
if (params != null && params.length > 0) {
for (XDNamedValue param : params) {
build(facets, param);
}
} else {
LOG.debug("{}No basic facets will be built - no input params",
logHeader(TRANSFORMATION));
}
LOG.debug("{}Building extra facets ...", logHeader(TRANSFORMATION));
extraFacets(facets);
return facets;
}
@Override
public XmlSchemaMinExclusiveFacet minExclusive(XDNamedValue param) {
throw new UnsupportedOperationException("minExclusive");
}
@Override
public XmlSchemaMinInclusiveFacet minInclusive(XDNamedValue param) {
throw new UnsupportedOperationException("minInclusive");
}
@Override
public XmlSchemaMaxExclusiveFacet maxExclusive(XDNamedValue param) {
throw new UnsupportedOperationException("maxExclusive");
}
@Override
public XmlSchemaMaxInclusiveFacet maxInclusive(XDNamedValue param) {
throw new UnsupportedOperationException("maxInclusive");
}
@Override
public XmlSchemaMinLengthFacet minLength(XDNamedValue param) {
throw new UnsupportedOperationException("minLength");
}
@Override
public XmlSchemaMaxLengthFacet maxLength(XDNamedValue param) {
throw new UnsupportedOperationException("maxLength");
}
@Override
public XmlSchemaLengthFacet length(XDNamedValue param) {
throw new UnsupportedOperationException("length");
}
@Override
public List<XmlSchemaPatternFacet> pattern(XDNamedValue param) {
throw new UnsupportedOperationException("pattern");
}
@Override
public XmlSchemaPatternFacet pattern(String value) {
LOG.debug("{}Pattern. value='{}'", logHeader(TRANSFORMATION), value);
XmlSchemaPatternFacet facet = new XmlSchemaPatternFacet();
facet.setValue(value);
return facet;
}
@Override
public List<XmlSchemaEnumerationFacet> enumeration(XDNamedValue param) {
throw new UnsupportedOperationException("enumeration");
}
@Override
public XmlSchemaFractionDigitsFacet fractionDigits(XDNamedValue param) {
throw new UnsupportedOperationException("fractionDigits");
}
@Override
public XmlSchemaTotalDigitsFacet totalDigits(XDNamedValue param) {
throw new UnsupportedOperationException("totalDigits");
}
@Override
public XmlSchemaWhiteSpaceFacet whitespace(XDNamedValue param) {
throw new UnsupportedOperationException("whitespace");
}
@Override
public boolean customFacet(List<XmlSchemaFacet> facets, XDNamedValue param) {
return false;
}
@Override
public void extraFacets(final List<XmlSchemaFacet> facets) {
}
@Override
public void setValueType(final ValueType valueType) {
this.valueType = valueType;
}
/**
* Creates facet from given X-Definition parameter
* @param facets list of facets, where newly created facet will be inserted
* @param param X-Definition parameter
*/
protected void build(final List<XmlSchemaFacet> facets, final XDNamedValue param) {
LOG.debug("{}Creating Facet. typeName='{}'",
logHeader(TRANSFORMATION), param.getName());
XmlSchemaFacet facet = null;
if (XSD_FACET_ENUMERATION.equals(param.getName())) {
facets.addAll(enumeration(param));
} else if (XSD_FACET_MAX_EXCLUSIVE.equals(param.getName())) {
facet = maxExclusive(param);
} else if (XSD_FACET_MAX_INCLUSIVE.equals(param.getName())) {
facet = maxInclusive(param);
} else if (XSD_FACET_MIN_EXCLUSIVE.equals(param.getName())) {
facet = minExclusive(param);
} else if (XSD_FACET_MIN_INCLUSIVE.equals(param.getName())) {
facet = minInclusive(param);
} else if (XSD_FACET_LENGTH.equals(param.getName())) {
facet = length(param);
} else if (XSD_FACET_MAX_LENGTH.equals(param.getName())) {
facet = maxLength(param);
} else if (XSD_FACET_MIN_LENGTH.equals(param.getName())) {
facet = minLength(param);
} else if (XSD_FACET_FRACTION_DIGITS.equals(param.getName())) {
facet = fractionDigits(param);
} else if (XSD_FACET_PATTERN.equals(param.getName()) || XD_FACET_FORMAT.equals(param.getName())) {
facets.addAll(pattern(param));
} else if (XSD_FACET_TOTAL_DIGITS.equals(param.getName())) {
facet = totalDigits(param);
} else if (XSD_FACET_WHITESPACE.equals(param.getName())) {
facet = whitespace(param);
} else if (isInternalFacet(param)) {
// Do nothing
} else if (!customFacet(facets, param)) {
adapterCtx.getReportWriter().warning(XSD.XSD032, param.getName());
LOG.warn("{}Unsupported restriction parameter. parameterName='{}'",
logHeader(TRANSFORMATION), param.getName());
}
if (facet != null) {
facets.add(facet);
}
}
/**
* Check if given X-Definition parameter is internal and should not be transformed
* @param param X-Definition parameter
* @return true, if given parameter is internal
*/
private boolean isInternalFacet(XDNamedValue param) {
return XD_INTERNAL_FACET_OUTFORMAT.equals(param.getName());
}
}
| 39.144144 | 106 | 0.716801 |
669a01db87bb20a4e28a856077f9f978d7695670 | 2,745 | package com.zmsoft.framework.persistent.system.S903020UserRole;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.zmsoft.framework.beans.common.RESTResultBean;
import org.zmsoft.framework.beans.page.PageModel;
import org.zmsoft.framework.support.MyControllerSupport;
/**
* 系统用户关联角色信息接口
* @version 0.1.1
* @since 0.1.1
*/
@CrossOrigin
@RestController
@RequestMapping(value = "/api/1.0/base/s903020userrole", method = { RequestMethod.POST})
public class S903020UserRoleController extends MyControllerSupport { //MyTokenCommonSupport
@Resource
protected S903020UserRoleBusinesslogic bizS903020UserRole;
//private MyModelAndViewSupport model = super.getModelAndView("S903020_user_role");
//一览(分页查询)
@RequestMapping(value = "/list", method = RequestMethod.POST)
public RESTResultBean<S903020UserRoleDBO> doList(S903020UserRoleDBO param, PageModel<S903020UserRoleDBO> pageModel) throws Exception {
// 输出参数日志
logger.debug("param=====>>>>" + param.toString());
// 设定查询参数
pageModel.setFormParamBean(param);
// 开启记录数统计
//pageModel.setResultCountFlag(true);
// 分页查询
return bizS903020UserRole.doList(pageModel);
}
//信息详情
@RequestMapping(value = "/info", method = RequestMethod.POST)
public RESTResultBean<S903020UserRoleDBO> doInfo(S903020UserRoleDBO param) throws Exception {
// 输出参数日志
logger.debug("param=====>>>>" + param.toString());
// 数据查询
return bizS903020UserRole.doInfo(param);
}
//信息插入
@RequestMapping(value = "/append", method = RequestMethod.POST)
public RESTResultBean<String> doAppend(S903020UserRoleDBO param) throws Exception {
// 输出参数日志
logger.debug("param=====>>>>" + param.toString());
// 信息插入
return bizS903020UserRole.doAppend(param);
}
//信息编辑
@RequestMapping(value = "/modify", method = RequestMethod.POST)
public RESTResultBean<String> doModify(S903020UserRoleDBO param) throws Exception {
// 输出参数日志
logger.debug("param=====>>>>" + param.toString());
// 信息插入
return bizS903020UserRole.doModify(param);
}
//信息删除
@RequestMapping(value = "/discard", method = RequestMethod.POST)
public RESTResultBean<String> doDiscard(S903020UserRoleDBO param) throws Exception {
// 输出参数日志
logger.debug("param=====>>>>" + param.toString());
// 信息插入
return bizS903020UserRole.doDiscard(param);
}
}
| 36.118421 | 138 | 0.695446 |
50d618a5c91354a8039b60413a1111a97c5b5976 | 3,119 | /*
* 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;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.web.component.TabbedPanel;
import com.evolveum.midpoint.web.page.admin.certification.dto.StageDefinitionDto;
/**
* @author lazyman
*/
public class StageEditorPanel extends BasePanel<StageDefinitionDto> {
private static final String ID_NAME_LABEL = "nameLabel";
private static final String ID_NAME = "name";
public StageEditorPanel(String id, IModel<StageDefinitionDto> model) {
super(id, model);
initPanelLayout();
}
private void initPanelLayout() {
AjaxLink<Void> name = new AjaxLink<Void>(ID_NAME) {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
nameClickPerformed(target);
}
};
Label nameLabel = new Label(ID_NAME_LABEL, getModel().getObject().getName() == null || getModel().getObject().getName().trim().equals("") ?
"Stage definition #" + getModel().getObject().getNumber()
: getModel().getObject().getName());
name.add(nameLabel);
add(name);
}
private void nameClickPerformed(AjaxRequestTarget target) {
TabbedPanel tabbedPanel = this.findParent(TabbedPanel.class);
IModel<List<ITab>> tabsModel = tabbedPanel.getTabs();
List<ITab> tabsList = tabsModel.getObject();
PropertyModel<String> tabNameModel;
if (getModel().getObject().getName() == null || getModel().getObject().getName().trim().equals("")){
tabNameModel = new PropertyModel<>(getModel(), StageDefinitionDto.F_NUMBER);
} else {
tabNameModel = new PropertyModel<>(getModel(), StageDefinitionDto.F_NAME);
}
for (ITab tab : tabsList){
if (tab.getTitle().getObject().equals(tabNameModel.getObject())){
int i = tabsList.indexOf(tab);
tabbedPanel.setSelectedTab(i);
target.add(tabbedPanel);
return;
}
}
tabsList.add(new AbstractTab(tabNameModel) {
@Override
public WebMarkupContainer getPanel(String panelId) {
return new DefinitionStagePanel(panelId, getModel());
}
});
tabbedPanel.setSelectedTab(tabsList.size() - 1);
target.add(tabbedPanel);
}
}
| 35.443182 | 147 | 0.661109 |
47fd7e3296fb00c8c335d0f5c7ad4a3341bb01fc | 4,366 | package com.aladdin.house.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aladdin.house.HouseContants;
import com.aladdin.house.HouseLayoutResult;
import com.aladdin.house.entity.HouseInfo;
import com.aladdin.house.mapper.HouseInfoMapper;
import com.aladdin.house.service.HouseLayoutService;
import com.aladdin.utils.BooleanUtils;
import tk.mybatis.mapper.entity.Example;
@Service
public class HouseLayoutServiceImpl implements HouseLayoutService {
@Autowired
private HouseInfoMapper houseInfoMapper;
@Override
public HouseInfo findHouseById(Integer houseId) {
HouseInfo house = new HouseInfo();
house.setId(houseId);
house.setIsDel(1);
return houseInfoMapper.selectOne(house);
}
@Override
public int deleteMyHouse(Integer houseId, String userId) {
Example example = new Example(HouseInfo.class);
if (houseId != null) {
example.createCriteria().andEqualTo("id", houseId);
}
if (userId != null && !"".equals(userId)) {
example.createCriteria().andEqualTo("designerId", userId);
}
HouseInfo house = new HouseInfo();
house.setIsDel(0);
return houseInfoMapper.updateByExampleSelective(house,example);
}
@Override
public int saveHouse(HouseInfo house) {
if(house==null||house.getDesignerId()==null){
return 0;
}
house.setCreateTime(new Date());
house.setState(HouseContants.verify_ok);//审核通过
house.setStatus(HouseContants.status_own);
return houseInfoMapper.insertSelective(house);
}
@Override
public int updateHouse(HouseInfo house) {
if(house==null||BooleanUtils.isEmpty(house.getId()))
return 0;
return houseInfoMapper.updateByPrimaryKeySelective(house);
}
/*@Override
public HouseLayoutResult find(String keyword,Integer pageNo,
Integer pageSize, float[] areas, String userid,Integer state,Integer status,String timeSort) {
Integer start_index = (pageNo - 1) * pageSize;
Integer count=houseInfoMapper.findHouseInfoCount(keyword, areas, userid, state, status);
List<HouseInfo> list=new ArrayList<HouseInfo>();
if(count==null){
count=0;
}
if(count!=0){
list = houseInfoMapper.findHouseInfos(keyword,start_index,pageSize, areas, userid,state,status,timeSort);
}
HouseLayoutResult result = new HouseLayoutResult(keyword, count, list, pageNo,areas,state);
return result;
}*/
@Override
public HouseLayoutResult find(Map<String, Object> parms) {
Integer count=houseInfoMapper.findHouseInfoCount(parms);
List<HouseInfo> list=new ArrayList<HouseInfo>();
if(count==null){
count = 0;
}
if(count!=0){
list = houseInfoMapper.findHouseInfos(parms);
}
Integer pageNo = 1;
if(parms.get("pageNo")!=null){
pageNo = Integer.parseInt(parms.get("pageNo").toString());
}
float[] areas = new float[]{0,1000};
if(parms.get("areas")!=null){
areas = (float[])parms.get("areas");
}
Integer state = 1;
if(parms.get("state")!=null&&!parms.get("state").equals("")){
state = Integer.parseInt(parms.get("state")+"");
}
HouseLayoutResult result = new HouseLayoutResult(
parms.get("keyword")+"",
count, list,
pageNo,
areas,
state);
return result;
}
@Override
public Map<String, Object> selectCountByDesignerId(String designerId) {
// TODO Auto-generated method stub
HouseInfo info=new HouseInfo();
info.setDesignerId(designerId);
//info.setState(HouseContants.verify_init);
Integer totalCount=houseInfoMapper.selectCount(info);
info.setState(HouseContants.verify_ok);
Integer verifyOkCount=houseInfoMapper.selectCount(info);
info.setState(HouseContants.verify_no);
Integer verifyNoCount=houseInfoMapper.selectCount(info);
Map<String, Object> resMap=new HashMap<String,Object>();
resMap.put("totalCount", totalCount);
resMap.put("verifyOkCount", verifyOkCount);
resMap.put("verifyNocount", verifyNoCount);
return resMap;
}
@Override
public int selectTotalCountByDesignerId(String designerId,Integer state) {
// TODO Auto-generated method stub
HouseInfo info=new HouseInfo();
info.setDesignerId(designerId);
if(state!=null && state != -1){
info.setState(state);
}
Integer totalCount=houseInfoMapper.selectCount(info);
return totalCount;
}
}
| 28.913907 | 109 | 0.740953 |
743e9b1297aa5d0d77f74aa684a8ece7ef8a512a | 2,875 | /*
* Copyright (C) 2018-2019 D3X Systems - 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.d3x.morpheus.csv;
import java.util.function.Consumer;
import com.d3x.morpheus.util.text.Formats;
import com.d3x.morpheus.util.text.printer.Printer;
/**
* Interface to a component that can emit the contents of a DataFrame to CSV format
*
* <p><strong>This is open source software released under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 License</a></strong></p>
*
* @author Xavier Witdouck
*/
public interface CsvSink<R,C> {
/**
* Writes the data frame out to CSV
*/
void apply();
/**
* Writes the data frame out to CSV
* @param configurator the options configurator
*/
void apply(Consumer<Options<R,C>> configurator);
/**
* The options for the CsvSink
* @param <R> the row key type
*/
@lombok.Data()
class Options<R,C> {
/** The title row row header column */
private String title;
/** The text to print for a null value */
private String nullText;
/** The formats used to render data types */
private Formats formats;
/** The separator for row values */
private String separator;
/** True to include a column with row keys */
private boolean includeRowHeader;
/** True to include a row with column keys */
private boolean includeColumnHeader;
/** The printer used to render row keys */
private Printer<R> rowKeyPrinter;
/** The printer used to render column keys */
private Printer<C> colKeyPrinter;
/**
* Constructor
*/
public Options() {
this.separator = ",";
this.title = "DataFrame";
this.formats = new Formats();
this.includeRowHeader = true;
this.includeColumnHeader = true;
}
/**
* Sets the formats to use for output to CSV
* @param configure the formats to apply
*/
public void withFormats(Consumer<Formats> configure) {
if (formats != null) {
configure.accept(formats);
} else {
this.formats = new Formats();
configure.accept(formats);
}
}
}
}
| 29.947917 | 150 | 0.613565 |
242aaced710d8ad514acfd57461700bf6bfdab02 | 2,050 | package net.kurobako.gesturefx.sample;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Supplier;
import javafx.application.HostServices;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.VBox;
public class SamplerController implements Initializable {
private static final String URI = "https://github.com/tom91136/gesturefx";
static class SampleEntry {
final String name;
final Supplier<? extends Sample> sampleFactory;
SampleEntry(String name, Supplier<? extends Sample> sampleFactory) {
this.name = name;
this.sampleFactory = sampleFactory;
}
}
interface Sample {
Node mkRoot();
}
@FXML private VBox root;
@FXML private Hyperlink link;
@FXML private TabPane tabs;
HostServices hostServices;
@Override
public void initialize(URL location, ResourceBundle resources) {
List<SampleEntry> samples = Arrays.asList(
new SampleEntry("Lena(ImageView)", LenaSample::new),
new SampleEntry("FXML(ImageView)", FXMLSample::new),
new SampleEntry("ViewportRect(ImageView)", ViewportRectSample::new),
new SampleEntry("Arbitrary Node(SubScene)", ArbitraryNodeSample::new),
new SampleEntry("WebView(Transformable)", WebViewSample::new),
new SampleEntry("Swing(ImageView)", SwingSample::new)
);
samples.forEach(s -> tabs.getTabs().add(new Tab(s.name, s.sampleFactory.get().mkRoot())));
link.setOnAction(e -> {
// for cases where java was started in something like i3wm
if (hostServices == null) {
TextInputDialog dialog = new TextInputDialog(URI);
dialog.setTitle("HostService missing");
dialog.setHeaderText("Unable to open URL due to missing HostService");
dialog.setContentText("URL");
dialog.showAndWait();
} else hostServices.showDocument(URI);
});
}
}
| 28.082192 | 92 | 0.745854 |
aba6e1bff989358f9253b22ab8cf12ef3ae8ee33 | 759 | //,temp,sample_5711.java,2,12,temp,sample_4239.java,2,17
//,3
public class xxx {
public void dummy_method(){
Map<byte[], String> results = table.coprocessorService(TestRpcServiceProtos.TestProtobufRpcProto.class, ROWS[0], ROWS[ROWS.length - 1], new Batch.Call<TestRpcServiceProtos.TestProtobufRpcProto, String>() {
public String call(TestRpcServiceProtos.TestProtobufRpcProto instance) throws IOException {
CoprocessorRpcUtils.BlockingRpcCallback<TestProtos.EchoResponseProto> callback = new CoprocessorRpcUtils.BlockingRpcCallback<>();
instance.echo(controller, request, callback);
TestProtos.EchoResponseProto response = callback.get();
return null;
}
}
);
for (Map.Entry<byte[], String> e : results.entrySet()) {
log.info("got value for region");
}
}
}; | 36.142857 | 205 | 0.785244 |
314878479ee2627677f7e9dce18b975ca682ec57 | 3,326 | /**
* This code is part of MTQC.
*
* Copyright (c) 2020 Javier Pellejero, Luis Aguirre.
*
* This code is licensed under the MIT License. You may obtain a copy
* of this license in the LICENSE file in the root directory of this source tree
* or at https://github.com/javpelle/TFGInformatica/blob/master/LICENSE.
*/
package view.tools;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import model.testresult.TestResult;
/**
* Table used to display results obtained from a single test.
*
* @author Javier & Luis
*
*/
public class ResultTable extends JPanel {
private static final long serialVersionUID = 1L;
private ArrayList<TestResult> results;
private TextField[][] labels;
private TextField[][] resume;
private TextField[] cols;
/**
* Constructor for the class.
*
* @param results Obtained result for a test.
*/
public ResultTable(ArrayList<TestResult> results) {
setLayout(new BorderLayout());
this.results = results;
cols = new TextField[3];
labels = new TextField[results.size()][3];
JPanel center = new JPanel();
center.setLayout(new GridLayout(results.size() + 1, 3));
centerPanel(center);
northPanel();
}
/**
* Creates north panel.
*/
private void northPanel() {
JPanel north = new JPanel();
north.setBorder(BorderFactory.createTitledBorder("Resume"));
north.setLayout(new GridLayout(2, 4));
resume = new TextField[2][4];
resume[0][0] = new TextField("Live Mutants #");
resume[0][1] = new TextField("Killed Mutants #");
resume[0][2] = new TextField("Total Mutants #");
resume[0][3] = new TextField("Mutant Score %");
resume[1][0] = new TextField("");
resume[1][1] = new TextField("");
resume[1][2] = new TextField("");
resume[1][3] = new TextField("");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
north.add(resume[i][j]);
}
}
add(north, BorderLayout.NORTH);
}
/**
* Creates center panel.
*
* @param center JPanel for the center of the view.
*/
private void centerPanel(JPanel center) {
cols[0] = new TextField("Name");
cols[1] = new TextField("Result");
cols[2] = new TextField("Killed");
center.add(cols[0]);
center.add(cols[1]);
center.add(cols[2]);
for (int i = 0; i < results.size(); i++) {
labels[i][0] = new TextField(results.get(i).getName());
labels[i][1] = new TextField(results.get(i).toString());
labels[i][2] = new TextField("");
center.add(labels[i][0]);
center.add(labels[i][1]);
center.add(labels[i][2]);
}
add(new JScrollPane(center), BorderLayout.CENTER);
}
/**
* Updates on the muntant kills.
*
* @param kills List of booleans which indicates which mutant dies.
*/
public void updateKills(ArrayList<Boolean> kills) {
int yes = 0;
int no = 0;
for (int i = 0; i < kills.size(); i++) {
if (kills.get(i)) {
labels[i + 1][2].setText("Yes");
yes += 1;
} else {
labels[i + 1][2].setText("No");
no += 1;
}
}
resume[1][0].setText(String.valueOf(no));
resume[1][1].setText(String.valueOf(yes));
resume[1][2].setText(String.valueOf(kills.size()));
resume[1][3].setText(String.valueOf((double) Math.round(yes * 1000.0 / kills.size()) / 10.0) + "%");
}
}
| 26.396825 | 102 | 0.646422 |
3796232d38f7963ec88d6145f499cd45060eafbe | 514 | package com.qraffa.easyrentboot.service;
import com.qraffa.easyrentboot.dao.TestTableDao;
import com.qraffa.easyrentboot.model.entity.TestTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TestTableService {
@Autowired
private TestTableDao testTableDao;
public List<TestTable> queryAll(){
return testTableDao.queryAll();
}
}
| 24.47619 | 62 | 0.793774 |
a9142783a7f82a59655c67042005dccea4777e17 | 791 | package site.zido.coffee.extra.security;
import org.springframework.data.redis.core.StringRedisTemplate;
/**
* 可以直接注入使用
* <p>
* 注意不同的业务(例如对接网易与对接其他第三方接口),
* 在注入bean的时候,记得使用命名bean或者可以直接继承实现,注入下一层的bean
*
* @author zido
*/
public class StringRedisTemplateSecurity extends AbstractSecurity {
private String nonceKey;
private StringRedisTemplate template;
public StringRedisTemplateSecurity(String token, String nonceKey, StringRedisTemplate template) {
super(token);
this.nonceKey = nonceKey;
this.template = template;
}
@Override
protected void clearNonce() {
template.delete(nonceKey);
}
@Override
protected boolean addNonce(String nonce) {
return 1 == template.opsForSet().add(nonceKey, nonce);
}
}
| 23.264706 | 101 | 0.7067 |
54ef9e47f47529103cdf438df69199c8bcecd1a0 | 2,269 | package com.openxu.cview.xmstock20201030.bean;
import java.util.List;
/**
* autour : xiami
* date : 2020/11/13 14:59
* className : HotDetailData
* version : 1.0
* description : 概念走势
*/
public class HotDetailData {
private String concept_id; //529683333575
private String concept_name;
private String intro;
private String pub_time;
private List<HotDetailNew> news;
//实时行情走势图,每个元素字段分别是:时间、现价、均价 、跌涨浮["0930",1639.83,1625.58,"0.10"]
private List<List<Object>> real_trend_line;
private HotDetailHotInfo hot_info; //实时行情数据
//概念走势图, 每个元素表示:时间、概念、热度 [20200803,"1582.08","30.00"],
private List<List<Object>> trend_line;
private List<DetailStock> stock_list;
public String getConcept_id() {
return concept_id;
}
public void setConcept_id(String concept_id) {
this.concept_id = concept_id;
}
public String getConcept_name() {
return concept_name;
}
public void setConcept_name(String concept_name) {
this.concept_name = concept_name;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getPub_time() {
return pub_time;
}
public void setPub_time(String pub_time) {
this.pub_time = pub_time;
}
public List<HotDetailNew> getNews() {
return news;
}
public void setNews(List<HotDetailNew> news) {
this.news = news;
}
public List<List<Object>> getReal_trend_line() {
return real_trend_line;
}
public void setReal_trend_line(List<List<Object>> real_trend_line) {
this.real_trend_line = real_trend_line;
}
public HotDetailHotInfo getHot_info() {
return hot_info;
}
public void setHot_info(HotDetailHotInfo hot_info) {
this.hot_info = hot_info;
}
public List<List<Object>> getTrend_line() {
return trend_line;
}
public void setTrend_line(List<List<Object>> trend_line) {
this.trend_line = trend_line;
}
public List<DetailStock> getStock_list() {
return stock_list;
}
public void setStock_list(List<DetailStock> stock_list) {
this.stock_list = stock_list;
}
}
| 23.153061 | 72 | 0.649625 |
a89f88e6566d829dda12922506ce67e5df37d462 | 3,645 | /*
* Copyright (c) 2021. Ou Yubin
* 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 cn.shanghai.oyb.compileflow.editor.commands;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.xml.XmlTag;
import cn.shanghai.oyb.flow.core.editor.commands.AbstractGraphEditCommand;
import cn.shanghai.oyb.flow.core.editor.editpart.TGraphEditPart;
import cn.shanghai.oyb.flow.core.editor.models.cells.BaseCell;
import cn.shanghai.oyb.flow.core.internal.TAdaptable;
import cn.shanghai.oyb.flow.core.models.XmlTagModelElement;
import cn.shanghai.oyb.compileflow.model.constants.CompileFlowXmlTagConstants;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import static cn.shanghai.oyb.compileflow.model.constants.CompileFlowXmlTagConstants.ID_ATTR_NAME;
import static cn.shanghai.oyb.compileflow.model.constants.CompileFlowXmlTagConstants.TO_ATTR_NAME;
/**
* 流程节点连接添加
*
* @author ouyubin
*/
public class CompileFlowConnectionAddCommand extends AbstractGraphEditCommand {
static private final Logger LOG = Logger.getInstance(CompileFlowConnectionAddCommand.class);
static private final String TRANSITION_NAME = "transition";
private BaseCell source;
private BaseCell target;
public CompileFlowConnectionAddCommand(TAdaptable adapter, String commandName) {
super(adapter,commandName);
}
public BaseCell getSource() {
return source;
}
public void setSource(BaseCell source) {
this.source = source;
}
public BaseCell getTarget() {
return target;
}
public void setTarget(BaseCell target) {
this.target = target;
}
@Override
public void execute() {
TGraphEditPart sourceEditPart = source.getMyEditPart();
XmlTagModelElement sourceXmlTagElement = ((XmlTagModelElement) sourceEditPart.getModel());
XmlTag sourceXmlTag = sourceXmlTagElement.getXmlTag();
LOG.info("获取到的起点标签" + sourceXmlTag.getName());
TGraphEditPart targetEditPart = target.getMyEditPart();
XmlTagModelElement targetXmlTagElement = ((XmlTagModelElement) targetEditPart.getModel());
XmlTag targetXmlTag = targetXmlTagElement.getXmlTag();
LOG.info("获取到的终点标签" + targetXmlTag.getName());
String transitionName = TRANSITION_NAME;
for (int i = 1; findTransitionTag(sourceXmlTag, transitionName); i++) {
transitionName = TRANSITION_NAME + i;
}
XmlTag transitionXmlTag = sourceXmlTag.createChildTag(CompileFlowXmlTagConstants.TRANSITION_TAG_NAME, null, null, false);
transitionXmlTag.setAttribute(TO_ATTR_NAME, targetXmlTag.getAttributeValue(ID_ATTR_NAME));
sourceXmlTag.addSubTag(transitionXmlTag, false);
sourceXmlTagElement.addSourceWire();
targetXmlTagElement.addTargetWire();
}
private boolean findTransitionTag(XmlTag parentXmlTag, String transitionName) {
return Arrays.stream(parentXmlTag.findSubTags(CompileFlowXmlTagConstants.TRANSITION_TAG_NAME)).filter(xmlTag -> StringUtils.equals(xmlTag.getAttributeValue(ID_ATTR_NAME), transitionName)).count() > 0;
}
}
| 36.45 | 208 | 0.74952 |
a52870b4083fcbe4f8d4cff3a35af89cf9d7e0c0 | 1,089 | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.sql.ast.expression;
import com.google.common.collect.ImmutableList;
import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.opensearch.sql.ast.AbstractNodeVisitor;
import org.opensearch.sql.ast.Node;
/**
* AST node that represents WHEN clause.
*/
@EqualsAndHashCode(callSuper = false)
@Getter
@RequiredArgsConstructor
@ToString
public class When extends UnresolvedExpression {
/**
* WHEN condition, either a search condition or compare value if case value present.
*/
private final UnresolvedExpression condition;
/**
* Result to return if condition matched.
*/
private final UnresolvedExpression result;
@Override
public List<? extends Node> getChild() {
return ImmutableList.of(condition, result);
}
@Override
public <T, C> T accept(AbstractNodeVisitor<T, C> nodeVisitor, C context) {
return nodeVisitor.visitWhen(this, context);
}
}
| 22.6875 | 86 | 0.754821 |
cf906a24b20bf50de48a3ccf06585da1bb3d8d93 | 2,241 | /**
*/
package CIM.IEC61970.Informative.MarketOperations;
import CIM.IEC61970.Core.IdentifiedObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Meter</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.Meter#getRegisteredResource <em>Registered Resource</em>}</li>
* </ul>
*
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getMeter()
* @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='This is generic logical meter object.'"
* annotation="http://langdale.com.au/2005/UML Profile\040documentation='This is generic logical meter object.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='This is generic logical meter object.' Profile\040documentation='This is generic logical meter object.'"
* @generated
*/
public interface Meter extends IdentifiedObject {
/**
* Returns the value of the '<em><b>Registered Resource</b></em>' reference.
* It is bidirectional and its opposite is '{@link CIM.IEC61970.Informative.MarketOperations.RegisteredResource#getMeters <em>Meters</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Registered Resource</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Registered Resource</em>' reference.
* @see #setRegisteredResource(RegisteredResource)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getMeter_RegisteredResource()
* @see CIM.IEC61970.Informative.MarketOperations.RegisteredResource#getMeters
* @model opposite="Meters"
* @generated
*/
RegisteredResource getRegisteredResource();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.Meter#getRegisteredResource <em>Registered Resource</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Registered Resource</em>' reference.
* @see #getRegisteredResource()
* @generated
*/
void setRegisteredResource(RegisteredResource value);
} // Meter
| 40.745455 | 182 | 0.716644 |
7a87eb4a12b9163196ed8b89c1e51610549aaf36 | 594 | package test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import com.nt.beans.StudentService;
public class ClientApp {
public static void main(String[] args) {
// Activate BF
XmlBeanFactory factory=new XmlBeanFactory(new FileSystemResource("src/com/nt/cfgs/applicationContext.xml"));
// get ServiceBean obj
StudentService service=(StudentService)factory.getBean("service");
//Call B.method
System.out.println("Result="+service.generateResult(132,"raja",90,36,45));
}//main
}//class
| 29.7 | 111 | 0.745791 |
61a811dee5865320f4f5e719bda879cd42423152 | 4,147 | /**
* Copyright Pravega 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 io.pravega.controller.util;
import io.pravega.common.Exceptions;
import io.pravega.common.Timer;
import io.pravega.common.concurrent.Futures;
import io.pravega.common.util.Retry;
import io.pravega.controller.retryable.RetryableException;
import io.pravega.controller.store.checkpoint.CheckpointStoreException;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class RetryHelper {
public static final Predicate<Throwable> RETRYABLE_PREDICATE = e -> {
Throwable t = Exceptions.unwrap(e);
return RetryableException.isRetryable(t) || (t instanceof CheckpointStoreException &&
((CheckpointStoreException) t).getType().equals(CheckpointStoreException.Type.Connectivity)) ||
t instanceof IOException;
};
public static final Predicate<Throwable> UNCONDITIONAL_PREDICATE = e -> true;
public static <U> U withRetries(Supplier<U> supplier, Predicate<Throwable> predicate, int numOfTries) {
return Retry.withExpBackoff(100, 2, numOfTries, 1000)
.retryWhen(predicate)
.run(supplier::get);
}
public static <U> CompletableFuture<U> withRetriesAsync(Supplier<CompletableFuture<U>> futureSupplier, Predicate<Throwable> predicate, int numOfTries,
ScheduledExecutorService executor) {
return Retry
.withExpBackoff(100, 2, numOfTries, 10000)
.retryWhen(predicate)
.runAsync(futureSupplier, executor);
}
public static <U> CompletableFuture<U> withIndefiniteRetriesAsync(Supplier<CompletableFuture<U>> futureSupplier,
Consumer<Throwable> exceptionConsumer,
ScheduledExecutorService executor) {
return Retry
.indefinitelyWithExpBackoff(100, 2, 10000, exceptionConsumer)
.runAsync(futureSupplier, executor);
}
public static CompletableFuture<Void> loopWithDelay(Supplier<Boolean> condition, Supplier<CompletableFuture<Void>> loopBody, long delay,
ScheduledExecutorService executor) {
return Futures.loop(condition, () -> Futures.delayedFuture(loopBody, delay, executor), executor);
}
public static CompletableFuture<Void> loopWithTimeout(Supplier<Boolean> condition, Supplier<CompletableFuture<Void>> loopBody,
long initialDelayMillis, long maxDelayMillis, long timeoutMillis, ScheduledExecutorService executor) {
Timer timer = new Timer();
AtomicInteger i = new AtomicInteger(0);
return Futures.loop(() -> {
boolean continueLoop = condition.get();
if (continueLoop && timer.getElapsedMillis() > timeoutMillis) {
throw new CompletionException(new TimeoutException());
}
return continueLoop;
}, () -> Futures.delayedFuture(
loopBody, Math.min(maxDelayMillis, initialDelayMillis * (int) Math.pow(2, i.getAndIncrement())), executor), executor);
}
}
| 47.666667 | 158 | 0.670605 |
7867d969944d08045d25ab7deea9fb9f9280a0fe | 578 | package com.sly.demo.cloud.business;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| 28.9 | 76 | 0.849481 |
71c4c4d3b7a94a856a66a0b8ccac4b31e60244f1 | 5,290 | package com.github.mikephil.charting.stockChart.charts;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.stockChart.dataManage.KLineDataManage;
import com.github.mikephil.charting.stockChart.markerView.KRightMarkerView;
import com.github.mikephil.charting.stockChart.markerView.LeftMarkerView;
import com.github.mikephil.charting.stockChart.renderer.MyCombinedChartRenderer;
import com.github.mikephil.charting.utils.CommonUtil;
/**
* Created by ly on 2016/9/12.
*/
public class CandleCombinedChart extends CombinedChart {
private LeftMarkerView myMarkerViewLeft;
private KRightMarkerView myMarkerViewRight;
public KLineDataManage kLineData;
public CandleCombinedChart(Context context) {
super(context);
}
public CandleCombinedChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CandleCombinedChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void initRenderer() {
mRenderer = new MyCombinedChartRenderer(this, mAnimator, mViewPortHandler);
}
public void setMarker(LeftMarkerView markerLeft, KRightMarkerView markerRight, KLineDataManage kLineData) {
this.myMarkerViewLeft = markerLeft;
this.myMarkerViewRight = markerRight;
this.kLineData = kLineData;
}
//暂时无用
public void setHighlightValue(Highlight h) {
if (mData == null) {
mIndicesToHighlight = null;
} else {
mIndicesToHighlight = new Highlight[]{h};
}
invalidate();
}
@Override
protected void drawMarkers(Canvas canvas) {
// if there is no marker view or drawing marker is disabled
if (!isDrawMarkersEnabled() || !valuesToHighlight()) {
return;
}
for (int i = 0; i < mIndicesToHighlight.length; i++) {
Highlight highlight = mIndicesToHighlight[i];
IDataSet set = mData.getDataSetByIndex(highlight.getDataSetIndex());
Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]);
int entryIndex = set.getEntryIndex(e);
// make sure entry not null
if (e == null || entryIndex > set.getEntryCount() * mAnimator.getPhaseX()) {
continue;
}
float[] pos = getMarkerPosition(highlight);
// check bounds
if (!mViewPortHandler.isInBounds(pos[0], pos[1])) {
continue;
}
if (pos[0] >= CommonUtil.getWindowWidth(getContext()) / 2) {
float yValForXIndex1 = (float) kLineData.getKLineDatas().get((int) mIndicesToHighlight[i].getX()).getClose();
myMarkerViewLeft.setData(yValForXIndex1);
myMarkerViewLeft.refreshContent(e, mIndicesToHighlight[i]);
myMarkerViewLeft.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
myMarkerViewLeft.layout(0, 0, myMarkerViewLeft.getMeasuredWidth(), myMarkerViewLeft.getMeasuredHeight());
if (getAxisLeft().getLabelPosition() == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
myMarkerViewLeft.draw(canvas, mViewPortHandler.contentLeft() - myMarkerViewLeft.getWidth() / 2, pos[1] + myMarkerViewLeft.getHeight() / 2);//+ CommonUtil.dip2px(getContext(),20) - myMarkerViewLeft.getHeight() / 2
} else {
myMarkerViewLeft.draw(canvas, mViewPortHandler.contentLeft() + myMarkerViewLeft.getWidth() / 2, pos[1] + myMarkerViewLeft.getHeight() / 2);//+ CommonUtil.dip2px(getContext(),20) - myMarkerViewLeft.getHeight() / 2
}
} else {
float yValForXIndex2 = (float) kLineData.getKLineDatas().get((int) mIndicesToHighlight[i].getX()).getClose();
myMarkerViewRight.setData(yValForXIndex2);
myMarkerViewRight.refreshContent(e, mIndicesToHighlight[i]);
myMarkerViewRight.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
myMarkerViewRight.layout(0, 0, myMarkerViewRight.getMeasuredWidth(), myMarkerViewRight.getMeasuredHeight());// - myMarkerViewRight.getHeight() / 2
if (getAxisRight().getLabelPosition() == YAxis.YAxisLabelPosition.OUTSIDE_CHART) {
myMarkerViewRight.draw(canvas, mViewPortHandler.contentRight() + myMarkerViewRight.getWidth() / 2, pos[1] + myMarkerViewLeft.getHeight() / 2);// - CommonUtil.dip2px(getContext(),20)
} else {
myMarkerViewRight.draw(canvas, mViewPortHandler.contentRight() - myMarkerViewRight.getWidth() / 2, pos[1] + myMarkerViewLeft.getHeight() / 2);// - CommonUtil.dip2px(getContext(),20)
}
}
}
}
}
| 46.403509 | 234 | 0.675236 |
863e843ef6ca03c97e52cba6159aa15c406847ce | 4,495 | package application.eocbox.com.demo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import app.eocbox.com.volley.toolbox.CircleNetworkImageView;
import app.eocbox.com.volley.toolbox.GsonRequest;
import app.eocbox.com.volley.toolbox.NetworkImageView;
import app.eocbox.com.volley.toolbox.VolleySingleton;
import app.eocbox.com.volley.toolbox.gsonclass.GsonTumblr;
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
Context context;
String errorUrl = "http://";
String testImageUrl = "http://i.imgur.com/ZzcDHhn.png";
String testGsonUrl = "https://api.tumblr.com/v2/blog/scipsy.tumblr.com/info?api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4";
//views
NetworkImageView errorNIV;
NetworkImageView demoNIV;
CircleNetworkImageView demoCNIV;
EditText demoEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
errorNIV = (NetworkImageView) findViewById(R.id.error_niv);
demoNIV = (NetworkImageView) findViewById(R.id.demo_niv);
demoCNIV = (CircleNetworkImageView) findViewById(R.id.demo_cniv);
demoEditText = (EditText) findViewById(R.id.gson_demo_et);
// when the url is not valid or the internet is not available
errorNIV.setErrorImageResId(R.drawable.dummy);
errorNIV.setDefaultImageResId(R.drawable.dummy);
errorNIV.setImageUrl(errorUrl, VolleySingleton.getInstance(context).getImageLoader());
// get the image from testImageUrl and show it with NetworkImageView
demoNIV.setErrorImageResId(R.drawable.dummy);
demoNIV.setDefaultImageResId(R.drawable.dummy);
demoNIV.setImageUrl(testImageUrl, VolleySingleton.getInstance(context).getImageLoader());
// get the image from testImageUrl and show it with CircleNetworkImageView
demoCNIV.setErrorImageResId(R.drawable.dummy);
demoCNIV.setDefaultImageResId(R.drawable.dummy);
demoCNIV.setImageUrl(testImageUrl, VolleySingleton.getInstance(context).getImageLoader());
// get the json oject from internet and use GSON to save it
GsonRequest<GsonTumblr> getTumblrReuest = new GsonRequest<GsonTumblr>(
Request.Method.GET, testGsonUrl, GsonTumblr.class,
createGetReqSuccessListener(),
createReqErrorListener());
getTumblrReuest.setRetryPolicy(new DefaultRetryPolicy(7000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getTumblrReuest.setTag("getTumblrReuest");
VolleySingleton.getInstance(context).getRequestQueue().add(getTumblrReuest);
}
private Response.Listener<GsonTumblr> createGetReqSuccessListener(
) {
return new Response.Listener<GsonTumblr>() {
@Override
public void onResponse(GsonTumblr response) {
Log.d(TAG, "Success response :" + response.toString());
demoEditText.setText(response.toString());
}
};
}
private Response.ErrorListener createReqErrorListener() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "error response :" + error);
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 37.773109 | 140 | 0.702558 |
e2e365a1dc3e2076921c46b502ecad9b7ba218b0 | 4,702 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.jedis;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.util.logging.ClientLogger;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Fluent credential builder for instantiating a {@link AzureJedisClient}.
*
* @see AzureJedisClient
*/
public class AzureJedisClientBuilder {
private String cacheHostName;
private Integer port;
private String username;
private String password;
private TokenCredential tokenCredential;
private RetryOptions retryOptions;
private final ClientLogger clientLogger = new ClientLogger(AzureJedisClientBuilder.class);
/**
* Creates an instance of {@link AzureJedisClientBuilder}
*/
public AzureJedisClientBuilder() {
}
/**
* Sets the Azure Redis Cache Host name to connect to.
* @param cacheHostName the cache host name.
* @return An updated instance of this builder.
*/
public AzureJedisClientBuilder cacheHostName(String cacheHostName) {
this.cacheHostName = cacheHostName;
return this;
}
/**
* Sets the port to connect to.
* @param port the port
* @return An updated instance of this builder.
*/
public AzureJedisClientBuilder port(Integer port) {
this.port = port;
return this;
}
/**
* Configure the credential to be used for authentication. if a password is configured via
* {@link AzureJedisClientBuilder#password(String)} then the credential is not required.
*
* @param tokenCredential the token credential
* @return An updated instance of this builder.
*/
public AzureJedisClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* The username to be used for authentication.
*
* @param username the username
* @return An updated instance of this builder.
*/
public AzureJedisClientBuilder username(String username) {
this.username = username;
return this;
}
/**
* The password to be used for authentication. If a @{@link TokenCredential} is provided via
* {@link AzureJedisClientBuilder#credential(TokenCredential)} then password is not required.
*
* @param password the password to be used for authentication
* @return An updated instance of this builder.
*/
public AzureJedisClientBuilder password(String password) {
this.password = password;
return this;
}
/**
* Configure the retry options.
*
* @param retryOptions the configuration to be used when retrying requests.
* @return An updated instance of this builder.
*/
public AzureJedisClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Build an instance of the {@link AzureJedisClient}
*
* @return An instance of {@link AzureJedisClient}
*/
public Jedis build() {
validate(this.getClass().getSimpleName(), new HashMap<String, Object>() {
{
this.put("cacheHostName", cacheHostName);
this.put("port", port);
this.put("username", username);
}
});
if (this.password != null && this.tokenCredential != null) {
throw this.clientLogger.logExceptionAsError(new IllegalArgumentException("Both Token Credential and Password are provided in AzureJedisClientBuilder. Only one of them should be provided."));
} else {
return tokenCredential != null ?
new AzureJedisClient(cacheHostName, port, username, tokenCredential, retryOptions) :
new AzureJedisClient(cacheHostName, port, username, password, retryOptions);
}
}
static void validate(String className, Map<String, Object> parameters) {
ClientLogger logger = new ClientLogger(className);
List<String> missing = new ArrayList<>();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
if (entry.getValue() == null) {
missing.add(entry.getKey());
}
}
if (missing.size() > 0) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("Must provide non-null values for "
+ String.join(", ", missing) + " properties in " + className));
}
}
}
| 33.347518 | 202 | 0.655678 |
42fb04b7b1b0a83e1fa691bb091a57bd46c66500 | 1,751 | package com.sap.cloud.lm.sl.cf.process.steps;
import java.util.List;
import org.activiti.engine.delegate.DelegateExecution;
import org.cloudfoundry.client.lib.domain.CloudApplication;
import com.sap.activiti.common.ExecutionStatus;
import com.sap.cloud.lm.sl.cf.client.lib.domain.CloudApplicationExtended;
import com.sap.cloud.lm.sl.cf.process.message.Messages;
public abstract class SetAppsUrisStep extends AbstractProcessStep {
@Override
protected ExecutionStatus executeStepInternal(DelegateExecution context) {
getStepLogger().logActivitiTask();
getStepLogger().info(getStartProgressMessage());
List<CloudApplicationExtended> apps = StepsUtil.getAppsToDeploy(context);
for (CloudApplicationExtended app : apps) {
assignUris(app);
}
StepsUtil.setAppsToDeploy(context, apps);
setAdditionalContextVariables(context);
getStepLogger().debug(getEndProgressMessage());
return ExecutionStatus.SUCCESS;
}
private void reportAssignedUris(CloudApplication app) {
for (String uri : app.getUris()) {
getStepLogger().info(Messages.ASSIGNING_URI, uri, app.getName());
}
}
private void assignUris(CloudApplicationExtended app) {
List<String> newUris = getNewUris(app);
if (newUris != null && !newUris.isEmpty()) {
app.setUris(newUris);
reportAssignedUris(app);
}
}
protected abstract List<String> getNewUris(CloudApplicationExtended app);
protected abstract void setAdditionalContextVariables(DelegateExecution context);
protected abstract String getStartProgressMessage();
protected abstract String getEndProgressMessage();
}
| 31.836364 | 85 | 0.711022 |
991ad12c7eeb869293f6479be1ce068eaa8a9cfe | 895 | package com.yourtion.leetcode.daily.m07.d18;
/**
* 97. 交错字符串
*
* @author Yourtion
* @link https://leetcode-cn.com/problems/interleaving-string/
*/
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int n = s1.length(), m = s2.length(), t = s3.length();
if (n + m != t) {
return false;
}
boolean[][] f = new boolean[n + 1][m + 1];
f[0][0] = true;
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
int p = i + j - 1;
if (i > 0) {
f[i][j] = f[i][j] || (f[i - 1][j] && s1.charAt(i - 1) == s3.charAt(p));
}
if (j > 0) {
f[i][j] = f[i][j] || (f[i][j - 1] && s2.charAt(j - 1) == s3.charAt(p));
}
}
}
return f[n][m];
}
}
| 28.870968 | 91 | 0.394413 |
09fa6dee45630181a2412960f525cbda8fc84526 | 2,552 | package com.ctrip.platform.dal.dao.client;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ctrip.platform.dal.common.enums.DatabaseCategory;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigure;
import com.ctrip.platform.dal.dao.configure.DataSourceConfigureLocator;
public class DbMeta {
private static Pattern hostRegxPattern = null;
private DataSourceConfigureLocator configureLocator = DataSourceConfigureLocator.getInstance();
private String databaseName;
private DatabaseCategory dbCategory;
private String dataBaseKeyName;
private String userName;
private String url;
private String host;
static {
String regEx = "(?<=://)[\\w\\-_]+(\\.[\\w\\-_]+)+(?=[,|:|;])";
hostRegxPattern = Pattern.compile(regEx);
}
private DbMeta(Connection conn, String realDbName, DatabaseCategory dbCategory) throws SQLException {
dataBaseKeyName = realDbName;
this.dbCategory = dbCategory;
try {
DatabaseMetaData meta = conn.getMetaData();
databaseName = conn.getCatalog();
url = meta.getURL();
host = parseHostFromDBURL(url);
DataSourceConfigure configure = configureLocator.getDataSourceConfigure(realDbName);
if (configure != null) {
userName = configure.getUserName();
}
} catch (Throwable e) {
}
}
public void populate(LogEntry entry) {
entry.setDatabaseName(databaseName);
entry.setServerAddress(host);
entry.setDbUrl(url);
entry.setUserName(userName);
entry.setDataBaseKeyName(dataBaseKeyName);
}
public static DbMeta createIfAbsent(String realDbName, DatabaseCategory dbCategory, Connection conn)
throws SQLException {
return new DbMeta(conn, realDbName, dbCategory);
}
public String getDatabaseName() {
return databaseName;
}
public String getDataBaseKeyName() {
return dataBaseKeyName;
}
public DatabaseCategory getDatabaseCategory() {
return dbCategory;
}
private String parseHostFromDBURL(String url) {
Matcher m = hostRegxPattern.matcher(url);
String host = "NA";
while (m.find()) {
host = m.group();
break;
}
return host;
}
}
| 30.746988 | 106 | 0.637931 |
80d212f2711c9de8b9e4e614e127dffc4d7fa712 | 993 | package org.packt.swarm.petstore.catalog;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.datasources.DatasourcesFraction;
public class Main {
public static void main(String[] args) throws Exception {
DatasourcesFraction datasourcesFraction = new DatasourcesFraction()
//1
.jdbcDriver("h2", (d) -> {
d.driverClassName("org.h2.Driver");
d.xaDatasourceClass("org.h2.jdbcx.JdbcDataSource");
d.driverModuleName("com.h2database.h2");
})
//2
.dataSource("CatalogDS", (ds) -> {
ds.driverName("h2");
ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
ds.userName("sa");
ds.password("sa");
});
Swarm swarm = new Swarm();
swarm.fraction(datasourcesFraction);
swarm.start().deploy();
}
} | 35.464286 | 98 | 0.540785 |
e8d9cfce4178c342f928b85f86b4d866784c6533 | 223 | package com.sisllc.mathformulas.ci.ch02;
/**
*
*
* @author javaugi
* @version $LastChangedRevision $LastChangedDate Last Modified Author:
* $LastChangedBy
*/
public class Q22IntWrapper {
public int value = 0;
}
| 15.928571 | 71 | 0.70852 |
365a48cadf22a314439f33190cd433abc7b88196 | 8,939 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.FormatHolder;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmSession;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
/**
* Reads from a {@link SampleQueue} and attaches {@link DrmSession} references to the {@link Format
* Formats} of encrypted regions.
*/
public final class DecryptableSampleQueueReader {
private final SampleQueue upstream;
private final DrmSessionManager<?> sessionManager;
private final FormatHolder formatHolder;
private final boolean playClearSamplesWithoutKeys;
private @MonotonicNonNull Format currentFormat;
@Nullable private DrmSession<?> currentSession;
/**
* Creates a sample queue reader.
*
* @param upstream The {@link SampleQueue} from which the created reader will read samples.
* @param sessionManager The {@link DrmSessionManager} that will provide {@link DrmSession
* DrmSessions} for the encrypted regions.
*/
public DecryptableSampleQueueReader(SampleQueue upstream, DrmSessionManager<?> sessionManager) {
this.upstream = upstream;
this.sessionManager = sessionManager;
formatHolder = new FormatHolder();
playClearSamplesWithoutKeys =
(sessionManager.getFlags() & DrmSessionManager.FLAG_PLAY_CLEAR_SAMPLES_WITHOUT_KEYS) != 0;
}
/** Releases any resources acquired by this reader. */
public void release() {
if (currentSession != null) {
currentSession.releaseReference();
currentSession = null;
}
}
/**
* Throws an error that's preventing data from being read. Does nothing if no such error exists.
*
* @throws IOException The underlying error.
*/
public void maybeThrowError() throws IOException {
// TODO: Avoid throwing if the DRM error is not preventing a read operation.
if (currentSession != null && currentSession.getState() == DrmSession.STATE_ERROR) {
throw Assertions.checkNotNull(currentSession.getError());
}
}
/**
* Reads from the upstream {@link SampleQueue}, populating {@link FormatHolder#drmSession} if the
* current {@link Format#drmInitData} is not null.
*
* <p>This reader guarantees that any read results are usable by clients. An encrypted sample will
* only be returned along with a {@link FormatHolder#drmSession} that has available keys.
*
* @param outputFormatHolder A {@link FormatHolder} to populate in the case of reading a format.
* {@link FormatHolder#drmSession} will be populated if the read format's {@link
* Format#drmInitData} is not null.
* @param buffer A {@link DecoderInputBuffer} to populate in the case of reading a sample or the
* end of the stream. If the end of the stream has been reached, the {@link
* C#BUFFER_FLAG_END_OF_STREAM} flag will be set on the buffer. If a {@link
* DecoderInputBuffer#isFlagsOnly() flags-only} buffer is passed, only the buffer flags may be
* populated by this method and the read position of the queue will not change.
* @param formatRequired Whether the caller requires that the format of the stream be read even if
* it's not changing. A sample will never be read if set to true, however it is still possible
* for the end of stream or nothing to be read.
* @param loadingFinished True if an empty queue should be considered the end of the stream.
* @param decodeOnlyUntilUs If a buffer is read, the {@link C#BUFFER_FLAG_DECODE_ONLY} flag will
* be set if the buffer's timestamp is less than this value.
* @return The result, which can be {@link C#RESULT_NOTHING_READ}, {@link C#RESULT_FORMAT_READ} or
* {@link C#RESULT_BUFFER_READ}.
*/
@SuppressWarnings("ReferenceEquality")
public int read(
FormatHolder outputFormatHolder,
DecoderInputBuffer buffer,
boolean formatRequired,
boolean loadingFinished,
long decodeOnlyUntilUs) {
boolean readFlagFormatRequired = false;
boolean readFlagAllowOnlyClearBuffers = false;
boolean onlyPropagateFormatChanges = false;
if (currentFormat == null || formatRequired) {
readFlagFormatRequired = true;
} else if (sessionManager != DrmSessionManager.DUMMY
&& currentFormat.drmInitData != null
&& Assertions.checkNotNull(currentSession).getState()
!= DrmSession.STATE_OPENED_WITH_KEYS) {
if (playClearSamplesWithoutKeys) {
// Content is encrypted and keys are not available, but clear samples are ok for reading.
readFlagAllowOnlyClearBuffers = true;
} else {
// We must not read any samples, but we may still read a format or the end of stream.
// However, because the formatRequired argument is false, we should not propagate a read
// format unless it is different than the current format.
onlyPropagateFormatChanges = true;
readFlagFormatRequired = true;
}
}
int result =
upstream.read(
formatHolder,
buffer,
readFlagFormatRequired,
readFlagAllowOnlyClearBuffers,
loadingFinished,
decodeOnlyUntilUs);
if (result == C.RESULT_FORMAT_READ) {
if (onlyPropagateFormatChanges && currentFormat == formatHolder.format) {
return C.RESULT_NOTHING_READ;
}
onFormat(Assertions.checkNotNull(formatHolder.format), outputFormatHolder);
}
return result;
}
/**
* Updates the current format and manages any necessary DRM resources.
*
* @param format The format read from upstream.
* @param outputFormatHolder The output {@link FormatHolder}.
*/
private void onFormat(Format format, FormatHolder outputFormatHolder) {
outputFormatHolder.format = format;
DrmInitData oldDrmInitData = currentFormat != null ? currentFormat.drmInitData : null;
currentFormat = format;
if (sessionManager == DrmSessionManager.DUMMY) {
// Avoid attempting to acquire a session using the dummy DRM session manager. It's likely that
// the media source creation has not yet been migrated and the renderer can acquire the
// session for the read DRM init data.
// TODO: Remove once renderers are migrated [Internal ref: b/122519809].
return;
}
outputFormatHolder.includesDrmSession = true;
outputFormatHolder.drmSession = currentSession;
if (Util.areEqual(oldDrmInitData, format.drmInitData)) {
// Nothing to do.
return;
}
// Ensure we acquire the new session before releasing the previous one in case the same session
// can be used for both DrmInitData.
DrmSession<?> previousSession = currentSession;
DrmInitData drmInitData = currentFormat.drmInitData;
if (drmInitData != null) {
currentSession =
sessionManager.acquireSession(Assertions.checkNotNull(Looper.myLooper()), drmInitData);
} else {
currentSession = null;
}
outputFormatHolder.drmSession = currentSession;
if (previousSession != null) {
previousSession.releaseReference();
}
}
/** Returns whether there is data available for reading. */
public boolean isReady(boolean loadingFinished) {
@SampleQueue.PeekResult int nextInQueue = upstream.peekNext();
if (nextInQueue == SampleQueue.PEEK_RESULT_NOTHING) {
return loadingFinished;
} else if (nextInQueue == SampleQueue.PEEK_RESULT_FORMAT) {
return true;
} else if (nextInQueue == SampleQueue.PEEK_RESULT_BUFFER_CLEAR) {
return currentSession == null || playClearSamplesWithoutKeys;
} else if (nextInQueue == SampleQueue.PEEK_RESULT_BUFFER_ENCRYPTED) {
return sessionManager == DrmSessionManager.DUMMY
|| Assertions.checkNotNull(currentSession).getState()
== DrmSession.STATE_OPENED_WITH_KEYS;
} else {
throw new IllegalStateException();
}
}
}
| 42.770335 | 100 | 0.719208 |
57d9ac7ff69335eecefddbb6669fe47751cbe899 | 32,168 | /*
* 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 DataProcessing;
import DB.DAC.DACSentence;
import DB.DAC.DACSentenceConcept;
import DB.DAC.DACDefConceptPattern;
import Form.InformationExctration;
import Stanford.StandfordBuckwalter;
import Utility.CapturedConceptStructure;
import Utility.Globals;
import Utility.OntologyInterface;
import Utility.ReasonerInterface;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
/**
*
* @author Mohammad Fasha
*/
public class ConceptExtractor {
DACSentenceConcept DACSentenceConcept;
DACSentence DACSentence;
DACDefConceptPattern DACDefConceptPattern;
private final OntologyInterface OntologyInterface;
private static ReasonerInterface ReasonerInterface;
//these two arrays are class level, they apply for all sentences
List<CapturedConceptStructure> AgentsBuffer = new ArrayList();
List<CapturedConceptStructure> ObjectsBuffer = new ArrayList();
public ConceptExtractor(OntologyInterface paraOntologyInterface) throws ClassNotFoundException, SQLException, OWLOntologyCreationException, Exception {
DACSentence = new DACSentence();
DACSentenceConcept = new DACSentenceConcept();
DACDefConceptPattern = new DACDefConceptPattern();
OntologyInterface = paraOntologyInterface;
ReasonerInterface = new ReasonerInterface(OntologyInterface.OntologyFile);
//class level arrays or memory buffers to resolve subject dropping and attached pronouns scenarios
AgentsBuffer = new ArrayList();
ObjectsBuffer = new ArrayList();
}
//this is the previous algorithm that we used first, it is pure sequential, the subject prodrop and objects pronouns won't be caught
public List<CapturedConceptStructure> ExtractAllConcepts(String paraSentenceText, String paraSentenceExpandedPOS, int paraLineNumber) throws SQLException {
try {
//Get all POS patterns which are defined in database
ResultSet conceptPatternRS = DACDefConceptPattern.GetAllRows();
return ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, conceptPatternRS, paraLineNumber);
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
return null;
}
}
public List<CapturedConceptStructure> ExtractAllFromSentenceByOrder(String paraSentenceText, String paraSentenceExpandedPOS, int paraLineNumber) throws SQLException {
try {
//this algorithm extracts all concepts in a given sentence
//it concentrates on events and agents first, it handles the agent pro-drop
//if an event is in the sentence and there is no agent for the sentence then
//we take the last character that matches the annotation signature
List<CapturedConceptStructure> eventsArray = new ArrayList();
List<CapturedConceptStructure> eventAgentArray = new ArrayList();
List<CapturedConceptStructure> eventObjectArray = new ArrayList();
List<CapturedConceptStructure> otherConceptsArray = new ArrayList();
List<CapturedConceptStructure> allConceptsArray = new ArrayList();
//this array is used to replace suffix objects with their designated objects
List<CapturedConceptStructure> eventsWithAttachedObjectsCCSArray = new ArrayList();
//1- get agents in sentence
ResultSet rs = DACDefConceptPattern.GetPatternsByConceptId(Globals.RegexPattern_Agent);
AgentsBuffer.addAll(ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber));
//2- get all nouns in the sentence
rs = DACDefConceptPattern.GetPatternsByConceptId(Globals.RegexPattern_Nouns);
ObjectsBuffer.addAll(ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber));
//3- get attached objects pronouns (SFX_OBJ) in the sentence, this specific array
//is more of linguistic that conceptual like the others
rs = DACDefConceptPattern.GetPatternsByConceptId(Globals.RegexPattern_SFXOBJ);
eventsWithAttachedObjectsCCSArray = ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber);
//********************************************************************************************
//get events in sentence
rs = DACDefConceptPattern.GetPatternsByConceptId(Globals.RegexPattern_Event);
eventsArray = ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber);
//get eventAgents relations in sentence
rs = DACDefConceptPattern.GetPatternsByConceptId(Globals.RegexPattern_ISTheAgentOfEvent);
eventAgentArray = ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber);
//get eventObjects relations in sentence
rs = DACDefConceptPattern.GetPatternsByConceptId(Globals.RegexPattern_ISTheObjectOfEvent);
eventObjectArray = ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber);
rs = DACDefConceptPattern.GetPatternsOfRemainingConcepts();;
otherConceptsArray = ExtractConceptsByPatternsList(paraSentenceText, paraSentenceExpandedPOS, rs, paraLineNumber);
//use ontology to restrict to concrete objects
//PruneArray(NounsArray, Globals.ConceptConcrete);
ResolveSubjectDropping(eventsArray, eventAgentArray, true);
ResolveObjectPronouns(eventsWithAttachedObjectsCCSArray, eventObjectArray, true);
allConceptsArray.addAll(AgentsBuffer);
allConceptsArray.addAll(eventsArray);
allConceptsArray.addAll(eventAgentArray);
allConceptsArray.addAll(eventObjectArray);
allConceptsArray.addAll(otherConceptsArray);
return allConceptsArray;
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
System.out.println(ex.toString());
return null;
}
}
private void ResolveSubjectDropping(List<CapturedConceptStructure> paraEventsArray, List<CapturedConceptStructure> paraEventAgentArray, boolean paraValidateSemantics) {
try {
//S U B J E C T D R O P
//Iterate all events and check if an agent was found
//if not found, then get the last agent from AgentsArray
for (CapturedConceptStructure event : paraEventsArray) {
boolean agentFound = false;
//Iterate over all extracted EventAgent relations
//and see if we have a relation for the event under examination
for (CapturedConceptStructure eventAgent : paraEventAgentArray) {
if (event.ArgumentOneTokenId == eventAgent.ArgumentTwoTokenId) {
agentFound = true;
break;
}
}
//If no agent was found for the event i.e. a pro drop relation
//then get the first matching character from the array
if (!agentFound) {
CapturedConceptStructure matchingAgent = null;
matchingAgent = FindMatchingAgentByPOS(event.ArgumentOneExpandedPOS, event.ArgumentOneClass, paraValidateSemantics);
if (matchingAgent != null) {
CapturedConceptStructure ccs = new CapturedConceptStructure();
ccs.ArgumentOneClass = matchingAgent.ArgumentOneClass;
ccs.ArgumentOneValue = matchingAgent.ArgumentOneValue;
ccs.ArgumentOneValueStemmed = matchingAgent.ArgumentOneValueStemmed;
ccs.ArgumentOneValueBuckwalter = matchingAgent.ArgumentOneValueBuckwalter;
ccs.ArgumentOneExpandedPOS = matchingAgent.ArgumentOneExpandedPOS;
//the token id where the drop subject (character) was referenced
ccs.ArgumentOneTokenId = matchingAgent.ArgumentOneTokenId;
//although we are filling argument two of the new relation
//we are referencing argument one of event concept structure since
//event is a unary relation, we didn'n find the binary relation thats
//why we are building it
ccs.ArgumentTwoClass = event.ArgumentOneClass;
ccs.ArgumentTwoValue = event.ArgumentOneValue;
ccs.ArgumentTwoValueStemmed = event.ArgumentOneValueStemmed;
ccs.ArgumentTwoValueBuckwalter = event.ArgumentOneValueBuckwalter;
ccs.ArgumentTwoExpandedPOS = event.ArgumentOneExpandedPOS;
ccs.LineNumber = event.LineNumber;
ccs.ArgumentTwoTokenId = event.ArgumentOneTokenId;
ccs.PatternId = "Subject drop";
ccs.ConceptIdValidated = matchingAgent.ConceptIdValidated;
ccs.ConceptId = Globals.RegexPattern_ISTheAgentOfEvent;
paraEventAgentArray.add(ccs);
}
}
}
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
}
}
private void ResolveObjectPronouns(List<CapturedConceptStructure> paraEventsWithAttachedObjectsCCSArray,
List<CapturedConceptStructure> paraEventObjectArray,
boolean paraValidateSemantics) {
try {
//O B J E C T P R O N O U N S
for (CapturedConceptStructure object : paraEventsWithAttachedObjectsCCSArray) {
String eventSuffix = object.ArgumentOneExpandedPOS.substring(object.ArgumentOneExpandedPOS.indexOf(Globals.RegexPattern_SFXOBJ), object.ArgumentOneExpandedPOS.length() - 2);//2 to skip both »>
CapturedConceptStructure matchingObject = null;
matchingObject = FindMatchingObjectByPOS(eventSuffix, object.ArgumentOneClass, paraValidateSemantics);
if (matchingObject != null) {
{
CapturedConceptStructure ccs = new CapturedConceptStructure();
ccs.ArgumentOneClass = matchingObject.ArgumentOneClass;
ccs.ArgumentOneExpandedPOS = matchingObject.ArgumentOneExpandedPOS;
ccs.ArgumentOneTokenId = matchingObject.ArgumentOneTokenId;
ccs.ArgumentOneValue = matchingObject.ArgumentOneValue;
ccs.ArgumentOneValueBuckwalter = matchingObject.ArgumentOneValueBuckwalter;
ccs.ArgumentOneValueStemmed = matchingObject.ArgumentOneValueStemmed;
ccs.ArgumentTwoClass = object.ArgumentOneClass;
ccs.ArgumentTwoExpandedPOS = object.ArgumentOneExpandedPOS;
ccs.ArgumentTwoTokenId = object.ArgumentOneTokenId;
ccs.ArgumentTwoValue = object.ArgumentOneValue;
ccs.ArgumentTwoValueBuckwalter = object.ArgumentOneValueBuckwalter;
ccs.ArgumentTwoValueStemmed = object.ArgumentOneValueStemmed;
ccs.LineNumber = object.LineNumber;
ccs.ConceptId = Globals.RegexPattern_ISTheObjectOfEvent;
ccs.ConceptIdValidated = matchingObject.ConceptIdValidated;
ccs.PatternId = "Object Pronoun";
paraEventObjectArray.add(ccs);
}
}
}
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
}
}
private CapturedConceptStructure FindMatchingAgentByPOS(String paraSignature, String paraEventType, boolean paraValidateSemantics) {
try {
//First, filter the signature of the Agent we are examining
//because the verb might be inflected with gender 1 and a it also might include a prefix of gender 2
//therefore, the Agent will be resolved to an incorrect agent
int startIndex = paraSignature.indexOf("VB");
startIndex = paraSignature.indexOf(Globals.RegularExpressionReadyTSegmentConcatinationChar, startIndex);
int endIndex = paraSignature.indexOf(Globals.RegularExpressionReadySegmentCloseBracket, startIndex);
paraSignature = paraSignature.substring(startIndex + 1, endIndex);
CapturedConceptStructure matchingAgent = null;
CapturedConceptStructure firstMatchingAgent = null;
for (int i = AgentsBuffer.size() - 1; i >= 0; i--) {
//we need the exact start location, nouns and proper nouns might have prefixes,
//therefore, we move to the last segment by looking for the last » character
//then from there we move to the first underscore to skip the name tag and extract
//the other modifiers e.g. SNG_MSC, PLRL_FEM...etc.
startIndex = AgentsBuffer.get(i).ArgumentOneExpandedPOS.indexOf("NN");
startIndex = AgentsBuffer.get(i).ArgumentOneExpandedPOS.indexOf(Globals.RegularExpressionReadyTSegmentConcatinationChar, startIndex);
endIndex = AgentsBuffer.get(i).ArgumentOneExpandedPOS.indexOf(Globals.RegularExpressionReadySegmentCloseBracket, startIndex);
String characterSignature = AgentsBuffer.get(i).ArgumentOneExpandedPOS.substring(startIndex + 1, endIndex);
//if the events POS signature contains the character POS signature
if (paraSignature.contains(characterSignature)) {
matchingAgent = new CapturedConceptStructure(AgentsBuffer.get(i));
if (firstMatchingAgent == null) {
firstMatchingAgent = new CapturedConceptStructure(AgentsBuffer.get(i));
}
if (paraValidateSemantics) {
System.out.println("Subject dropping: " + matchingAgent.ArgumentOneClass
+ ": " + matchingAgent.ArgumentOneValue
+ " " + Globals.RegexPattern_ISTheAgentOfEvent + " "
+ paraEventType);
if (!matchingAgent.ArgumentOneClass.contentEquals("Thing") && !paraEventType.contentEquals("Thing")) {
if (ValidSemanticRelation(matchingAgent.ArgumentOneClass, Globals.RegexPattern_ISTheAgentOfEvent, paraEventType)) {
matchingAgent.ConceptIdValidated = "Validated Agent";
i = 0;// to exit the for loop
}
}
}
}
}
if (matchingAgent != null) {
if (matchingAgent.ConceptIdValidated == "Validated Agent") {
return matchingAgent;
} else {
return firstMatchingAgent;
}
} else {
return null;
}
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.getMessage());
System.out.println(ex.toString());
return null;
}
}
private CapturedConceptStructure FindMatchingObjectByPOS(String paraSuffix, String paraEventType, boolean paraValidateSemantics) {
try {
//The start location is different than Agents array above, simply pass 8 characters to
//skip the SFX_OBJ_ characters and directly get the gender and number POS
int startIndex, endIndex;
paraSuffix = paraSuffix.substring(8, paraSuffix.length());
CapturedConceptStructure matchingObject = null;
CapturedConceptStructure firstMatchingObject = null;
for (int i = ObjectsBuffer.size() - 1; i >= 0; i--) {
//we need the exact start location, nouns and proper nouns might have prefixes,
//therefore, we move to the last segment by looking for the last » character
//then from there we move to the first underscore to skip the name tag and extract
//the other modifiers e.g. SNG_MSC, PLRL_FEM...etc.
startIndex = ObjectsBuffer.get(i).ArgumentOneExpandedPOS.indexOf("NN");
startIndex = ObjectsBuffer.get(i).ArgumentOneExpandedPOS.indexOf(Globals.RegularExpressionReadyTSegmentConcatinationChar, startIndex);
endIndex = ObjectsBuffer.get(i).ArgumentOneExpandedPOS.indexOf(Globals.RegularExpressionReadySegmentCloseBracket, startIndex);
String objectSignature = ObjectsBuffer.get(i).ArgumentOneExpandedPOS.substring(startIndex + 1, endIndex);
//if the events POS signature contains the character POS signature
if (objectSignature.contains(paraSuffix)) {
matchingObject = new CapturedConceptStructure(ObjectsBuffer.get(i));
if (firstMatchingObject == null) {
firstMatchingObject = new CapturedConceptStructure(ObjectsBuffer.get(i));
}
if (paraValidateSemantics) {
System.out.println("Objects pronouns: " + matchingObject.ArgumentOneClass
+ ": " + matchingObject.ArgumentOneValue
+ " " + Globals.RegexPattern_ISTheObjectOfEvent + " "
+ paraEventType);
if (!matchingObject.ArgumentOneClass.contentEquals("Thing") && !paraEventType.contentEquals("Thing")) {
if (ValidSemanticRelation(matchingObject.ArgumentOneClass, Globals.RegexPattern_ISTheObjectOfEvent, paraEventType)) {
matchingObject.ConceptIdValidated = "Validated Object";
i = 0;// to exit the for loop
}
}
}
}
}
if (matchingObject != null) {
if (matchingObject.ConceptIdValidated == "Validated Object") {
return matchingObject;
} else {
return firstMatchingObject;
}
} else {
return null;
}
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
return null;
}
}
private List<CapturedConceptStructure> ExtractConceptsByPatternsList(String paraSentenceText, String paraSentenceExpandedPOS, ResultSet paraPatternsRS, int paraLineNumber) throws SQLException {
try {
//the theme of this procedure is to run the passed pos version of text over all the defined regular expression pattern
//all these rules are design to capture a unary pattern or a binary pattern, not more not less
//therefore, all these patterns are defined with regular expression groups i.e. ( ), while each and every group
//have to be defined with the order seperator i.e. # which is followed either by 1 or 2 i.e. (VB#1)
//we select a seperator that is not used as a special character by regular expression engine i.e. #
//this parameter is defined in the Utility.Global class
//Initialize the concepts ArrayList
List<CapturedConceptStructure> conceptsArray = new ArrayList<>();
//Strip out digits and colons, we need to do this so that we can exract the correct
//word later and attach it in the designated concept slot (without its index number)
String textOnly = Utility.Globals.StripDigitsAndColons(paraSentenceText);
StandfordBuckwalter stanfordBuckwalter = new StandfordBuckwalter();
ShereenKhojaStemmer.ArabicStemmer aStemmer = new ShereenKhojaStemmer.ArabicStemmer();
//Tokenize sentence, create an array representation for sentence tokens
//for arabic, space character i.e. ascii 32 is suitable for splitting words
//we shall use this array to extract the designated item by its index so that
//we can insert it into the designated concept slot
String[] textTokenArray = textOnly.split(" ");
String[] expandedPOSTokenArray = paraSentenceExpandedPOS.split(" ");
paraPatternsRS.beforeFirst();
while (paraPatternsRS.next()) {
String patternRule = paraPatternsRS.getString("pos_pattern");
//Remove position markers, the 1 2 numbering of arguments
String patternRuleFiltered = Utility.Globals.StripDigitsAndHashSign(patternRule);
//Compile the regular expression to extract the pattern (the pattern without word order)
Pattern p = Pattern.compile(patternRuleFiltered);
//paraSentenceExpandedPOS is already fildtered by B2A2 as RE ready
Matcher m = p.matcher(paraSentenceExpandedPOS);
while (m.find()) {
CapturedConceptStructure cms = new CapturedConceptStructure();
cms.ConceptId = paraPatternsRS.getString("concept_id");
cms.PatternId = String.valueOf(paraPatternsRS.getInt("id"));
cms.LineNumber = paraLineNumber;
//check if this pattern has one arguement or two arguements
if (m.groupCount() == 1) {
int tokenIndex;
//m.end not m.start, to count all the open brackets untill the end of pattern match
//using the m.start created inconsitencies
tokenIndex = GetTokenIndexInMatchedText(paraSentenceExpandedPOS, m.end(1));
cms.ArgumentOneTokenId = tokenIndex;
cms.ArgumentOneValue = textTokenArray[tokenIndex - 1];
//this is the original expanded POS value of the concept
cms.ArgumentOneExpandedPOS = expandedPOSTokenArray[tokenIndex - 1];
cms.ParentClass = paraPatternsRS.getString("parent_class");
cms.ArgumentOneValueBuckwalter = stanfordBuckwalter.ArabicToBuckwalter(cms.ArgumentOneValue);
cms.ArgumentOneValueStemmed = aStemmer.StemWord(cms.ArgumentOneValue);
//Try to get the accurate class name from the supporting ontolgy
//if no value is found in the annotation, just use the original value
//that was set in the def_concept table
cms.ArgumentOneClass = OntologyInterface.getClassNameByAnnotationValue(cms.ArgumentOneValue);
if (cms.ArgumentOneClass == null) {
cms.ArgumentOneClass = paraPatternsRS.getString("argument_1_class");
}
} else if (m.groupCount() == 2) {//this patterm has two arguements
//in our patterns i.e. DL motivated, we only have either one group or two groups
//therefore, if deteremined which group is related to arguement one, then automatically
//the other group will be for arguement two
//m.end() determines the index of the group ending position
int argumentOneIndex;
int argumentTwoIndex;
if (GetArguementOneGroupOrderInPatternRule(patternRule, 1) == 1) {
argumentOneIndex = GetTokenIndexInMatchedText(paraSentenceExpandedPOS, m.end(1));
argumentTwoIndex = GetTokenIndexInMatchedText(paraSentenceExpandedPOS, m.end(2));
} else {
argumentOneIndex = GetTokenIndexInMatchedText(paraSentenceExpandedPOS, m.end(2));
argumentTwoIndex = GetTokenIndexInMatchedText(paraSentenceExpandedPOS, m.end(1));
}
cms.ArgumentOneTokenId = argumentOneIndex;
cms.ArgumentOneValue = textTokenArray[argumentOneIndex - 1];
cms.ArgumentOneExpandedPOS = expandedPOSTokenArray[argumentOneIndex - 1];
cms.ArgumentOneValueBuckwalter = stanfordBuckwalter.ArabicToBuckwalter(cms.ArgumentOneValue);
cms.ArgumentOneValueStemmed = aStemmer.StemWord(cms.ArgumentOneValue);
//Try to get the accurate class name from the supporting ontolgy
//if no value is found in the annotation, just use the original value
//that was set in the def_concept table
cms.ArgumentOneClass = OntologyInterface.getClassNameByAnnotationValue(cms.ArgumentOneValue);
if (cms.ArgumentOneClass == null) {
cms.ArgumentOneClass = paraPatternsRS.getString("argument_1_class");
}
cms.ArgumentTwoTokenId = argumentTwoIndex;
cms.ArgumentTwoValue = textTokenArray[argumentTwoIndex - 1];
cms.ArgumentTwoExpandedPOS = expandedPOSTokenArray[argumentTwoIndex - 1];
cms.ArgumentTwoValueBuckwalter = stanfordBuckwalter.ArabicToBuckwalter(cms.ArgumentTwoValue);
cms.ArgumentTwoValueStemmed = aStemmer.StemWord(cms.ArgumentTwoValue);
//Try to get the accurate class name from the supporting ontolgy
//if no value is found in the annotation, just use the original value
//that was set in the def_concept table
cms.ArgumentTwoClass = OntologyInterface.getClassNameByAnnotationValue(cms.ArgumentTwoValue);
if (cms.ArgumentTwoClass == null) {
cms.ArgumentTwoClass = paraPatternsRS.getString("argument_2_class");
}
}
conceptsArray.add(cms);
}
}
return conceptsArray;
} catch (Exception ex) {
System.out.println(ex.toString());
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
return null;
}
}
private int GetTokenIndexInMatchedText(String paraText, int paraEnd) {
try {
//the idea of this algorithm is to iterate the text string i.e. pos version of the string
//and count the token open and close brackets, if we meet an open bracket we increase c1 counter
//by 1, if we meet a close bracket, we decrement c1 counter by 1, once c1 becomes 0 after a
//substraction, we know that we have passed over a full token, so we can increase c2 by 1
//we continue moving until we reach the match start point, therefore we would have counted all
//the tokens during our way
int c1 = 0;
int c2 = 0;
//@@@@System.out.println("Static counter is ::: " + ++Globals.static_counter);
for (int i = 0; i < paraEnd; i++) {
if (paraText.charAt(i) == Utility.Globals.RegularExpressionReadyTokenOpenBracket) {
c1 += 1;
} else if (paraText.charAt(i) == Utility.Globals.RegularExpressionReadyTokenCloseBracket) {
c1 -= 1;
//if we met a closing bracked, and c1 became 0 i.e. all opens are close, then
//we know that we have passed through a complete token, so increment c2
if (c1 == 0) {
c2 += 1;
}
}
}
//once we finish and reach the paraStart index, we have to check c1
//if it is larger than zero, this means that we entered a new token
//but we couldn't finish it as the start of capture doesn't cover all
//the closing brakcets, nevertheless, we should increment c2 by one to
//take this new token into consideration
if (c1 >= 1) {
c2 += 1;
}
return c2;
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
System.out.println(ex.toString());
return 0;
}
}
private int GetArguementOneGroupOrderInPatternRule(String paraPatternRule, int paraGroupId) {
try {
//the idea of this algorithm is to move forward a Group Id number of times while
//passing through ItemOrderSeperator i.e #
//once we reach the required number of times, we extract the designated order number
int indexOfTokenOrder = -1;
for (int i = 1; i <= paraGroupId; i++) {
indexOfTokenOrder = paraPatternRule.indexOf(Utility.Globals.ItemOrderSeperator, indexOfTokenOrder);
indexOfTokenOrder = indexOfTokenOrder + 1;//move forward to point on item
}
if (indexOfTokenOrder != -1) {
return Integer.valueOf(paraPatternRule.substring(indexOfTokenOrder, indexOfTokenOrder + 1));
} else {
return -1;
}
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
return 0;
}
}
private void PruneArray(List<CapturedConceptStructure> paraArray, String paraParentClass) {
try {
// paraArray.stream().forEach((ccs
// -> {
// String childClass = OntologyInterface.getClassNameByAnnotationValue(ccs.ArgumentOneValue);
// if (!ReasonerInterface.ISSuperClassOf(paraParentClass, childClass)) {
// paraArray.remove(ccs);
// }
// }));
} catch (Exception ex) {
Logger.getLogger(ConceptExtractor.class.getName()).log(Level.SEVERE, null, ex.toString());
}
}
private boolean ValidSemanticRelation(String paraArgumentOneClass, String paraRelationID, String paraArgumentTwoClass) {
return ReasonerInterface.HasInstances(paraArgumentOneClass + " and " + paraRelationID + " some " + paraArgumentTwoClass);
}
}
| 56.237762 | 221 | 0.612596 |
a922883d6feb6798544d07e7200c4ff3a4ac0e87 | 902 | package com.oblivioussp.spartanweaponry.api.trait;
import java.util.List;
import com.oblivioussp.spartanweaponry.api.SpartanWeaponryAPI;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
public class SweepWeaponTrait extends WeaponTraitWithMagnitude
{
public SweepWeaponTrait(String propType, String propModId, int propLevel, float propMagnitude)
{
super(propType, propModId, propLevel, propMagnitude, TraitQuality.POSITIVE);
}
@Override
protected void addTooltipDescription(ItemStack stack, List<ITextComponent> tooltip)
{
if(magnitude == 1.0f)
tooltip.add(new TranslationTextComponent(String.format("tooltip.%s.trait.%s.fixed.desc", SpartanWeaponryAPI.MOD_ID, this.type), magnitude).mergeStyle(WeaponTrait.DESCRIPTION_COLOUR));
else
super.addTooltipDescription(stack, tooltip);
}
}
| 32.214286 | 186 | 0.810421 |
d9f57d196e99ec7c400f9cb7ab3102cc34965351 | 980 | package com.surirobot.process;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import com.surirobot.interfaces.IProcessVocal;
import com.surirobot.interfaces.services.IService;
import com.surirobot.services.vokaturi.EmotionVokaturi;
/**
*
* @author jussieu
*
* Permet de traiter le flux audio reçu.
*
*/
public class ProcessVocal implements IProcessVocal {
private static final Logger logger = LogManager.getLogger();
/**
* Méthode qui traite le fichier vocal reçu.
* si le flux == {@link <code>null</code>} ou vide: la méthode retourne un json vide.
* sinon : elle passe les donnée à l'API.
*/
@Override
public String process(String data) {
logger.info("ProcessVocal : start process");
if(data == null) return "{}";
if(data.equals("")) return "{}";
IService<JSONObject, String, String> vokaturi = new EmotionVokaturi();
return vokaturi.getEmotions(data).toString();
}
}
| 25.128205 | 86 | 0.722449 |
ab08da6f23072382f896d88b638a0a1b0eae6527 | 2,672 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* 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.dmdirc.addons.ui_swing.components.statusbar;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.border.EtchedBorder;
/**
* An {@link EtchedBorder} that leaves a gap in the bottom where the status bar popup window is.
*/
public class GappedEtchedBorder extends EtchedBorder {
/** Java serialisation version ID. */
private static final long serialVersionUID = 1;
/** Parent popup window. */
private final transient StatusbarPopupWindow outer;
/**
* Creates a new etched border leaving a gap where the specified window is.
*
* @param outer Window to leave a gap for
*/
protected GappedEtchedBorder(final StatusbarPopupWindow outer) {
this.outer = outer;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x,
final int y, final int width, final int height) {
g.translate(x, y);
g.setColor(etchType == LOWERED ? getShadowColor(c)
: getHighlightColor(c));
g.drawLine(0, 0, width - 1, 0);
g.drawLine(0, height - 1, outer.getParentPanel().getLocationOnScreen().x - outer.
getLocationOnScreen().x, height - 1);
g.drawLine(outer.getParentPanel().getWidth() + outer.getParentPanel()
.getLocationOnScreen().x - outer.getLocationOnScreen().x - 2,
height - 1, width - 1, height - 1);
g.drawLine(0, 0, 0, height - 1);
g.drawLine(width - 1, 0, width - 1, height - 1);
g.translate(-x, -y);
}
}
| 43.096774 | 119 | 0.693862 |
188929d19e069e6064e549478d1b0df341765c99 | 6,505 | /**
*
*/
package me.learn.personal.month4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Title 1152 :
*
* We are given some website visits: the user with name username[i] visited the
* website website[i] at time timestamp[i].
*
* A 3-sequence is a list of websites of length 3 sorted in ascending order by
* the time of their visits. (The websites in a 3-sequence are not necessarily
* distinct.)
*
* Find the 3-sequence visited by the largest number of users. If there is more
* than one solution, return the lexicographically smallest such 3-sequence.
*
*
*
* Example 1:
*
* Input: username =
* ["joe","joe","joe","james","james","james","james","mary","mary","mary"],
* timestamp = [1,2,3,4,5,6,7,8,9,10], website =
* ["home","about","career","home","cart","maps","home","home","about","career"]
* Output: ["home","about","career"] Explanation: The tuples in this example
* are: ["joe", 1, "home"] ["joe", 2, "about"] ["joe", 3, "career"] ["james", 4,
* "home"] ["james", 5, "cart"] ["james", 6, "maps"] ["james", 7, "home"]
* ["mary", 8, "home"] ["mary", 9, "about"] ["mary", 10, "career"] The
* 3-sequence ("home", "about", "career") was visited at least once by 2 users.
* The 3-sequence ("home", "cart", "maps") was visited at least once by 1 user.
* The 3-sequence ("home", "cart", "home") was visited at least once by 1 user.
* The 3-sequence ("home", "maps", "home") was visited at least once by 1 user.
* The 3-sequence ("cart", "maps", "home") was visited at least once by 1 user.
*
* @author bramanarayan
* @date Aug 22, 2020
*/
public class AnalyzeUserWebsiteVisitPattern {
/**
* @param args
*/
public static void main(String[] args) {
AnalyzeUserWebsiteVisitPattern solution = new AnalyzeUserWebsiteVisitPattern();
/*
* String[] users = new String[]
* {"joe","joe","joe","james","james","james","james","mary","mary","mary"};
* String[] pages = new String[]
* {"home","about","career","home","cart","maps","home","home","about","career"}
* ; int[] time = new int[] {1,2,3,4,5,6,7,8,9,10};
*/
String[] users = new String[] { "u1", "u1", "u1", "u2", "u2", "u2" };
String[] pages = new String[] { "a", "b", "c", "a", "b", "a" };
int[] time = new int[] { 1, 2, 3, 4, 5, 6 };
/**
* ["u1","u1","u1","u2","u2","u2"] [1,2,3,4,5,6] ["a","b","c","a","b","a"]
*/
solution.mostVisitedPattern(users, time, pages);
}
class Visit {
String userName;
int timestamp;
String website;
Visit(String u, int t, String w) {
userName = u;
timestamp = t;
website = w;
}
Visit() {
}
}
// Entry point
public List<String> mostVisitedPattern(String[] username, int[] timestamp, String[] website) {
// Convert all the entry as visit object to ease of understand
List<Visit> visitList = new ArrayList<>();
for (int i = 0; i < username.length; i++) {
visitList.add(new Visit(username[i], timestamp[i], website[i]));
}
// Sort all the visit entries using their timestamp -> ADOPT IT !!!!
Comparator<Visit> cmp = (v1, v2) -> {
return v1.timestamp - v2.timestamp;
};
Collections.sort(visitList, cmp);
// Collect list of websites for each user
Map<String, List<String>> userWebSitesMap = new HashMap<>();
for (Visit v : visitList) {
userWebSitesMap.putIfAbsent(v.userName, new ArrayList<>());
userWebSitesMap.get(v.userName).add(v.website);
}
Map<List<String>, Integer> seqUserFreMap = new HashMap<>();
// Now get all the values of all the users
for (List<String> websitesList : userWebSitesMap.values()) {
if (websitesList.size() < 3)
continue; // no need to consider less than 3 entries of web site visited by user
// if its more than or equal to 3.
Set<List<String>> sequencesSet = generate3Seq(websitesList);
// Now update the frequency of the sequence ( increment by 1 for 1 user)
for (List<String> seq : sequencesSet) {
seqUserFreMap.putIfAbsent(seq, 0);
seqUserFreMap.put(seq, seqUserFreMap.get(seq) + 1);
}
}
List<String> res = new ArrayList<>();
int MAX = 0;
for (Map.Entry<List<String>, Integer> entry : seqUserFreMap.entrySet()) {
if (entry.getValue() > MAX) {
MAX = entry.getValue();
res = entry.getKey();
} else if (entry.getValue() == MAX) {
// for lexicographic sort requirement
if (entry.getKey().toString().compareTo(res.toString()) < 0) {
res = entry.getKey();
}
}
}
return res;
}
// It will not return duplicate seq for each user that why we are using Set
private Set<List<String>> generate3Seq(List<String> websitesList) {
Set<List<String>> setOfListSeq = new HashSet<>();
for (int i = 0; i < websitesList.size(); i++) {
for (int j = i + 1; j < websitesList.size(); j++) {
for (int k = j + 1; k < websitesList.size(); k++) {
List<String> list = new ArrayList<>();
list.add(websitesList.get(i));
list.add(websitesList.get(j));
list.add(websitesList.get(k));
setOfListSeq.add(list);
}
}
}
return setOfListSeq;
}
// MY sol
public List<String> mostVisitedPatternMy(String[] username, int[] timestamp, String[] website) {
// user -> pages visited
Map<String, List<String>> map = new HashMap<>();
// pattern 3 tuple -> count
TreeMap<String, Integer> count = new TreeMap<>();
int n = username.length;
for (int i = 0; i < n; i++) {
String user = username[i];
String page = website[i];
int time = timestamp[i];
map.computeIfAbsent(user, x -> new ArrayList<String>()).add(page);
if (map.get(user).size() >= 3) {
String pattern = get3Tuple(map.get(user));
count.put(pattern, count.getOrDefault(pattern, 0) + 1);
}
}
int max = Collections.max(count.values());
List<String> resultSet = count.entrySet().stream().filter(e -> e.getValue() == max).map(e -> e.getKey())
.collect(Collectors.toList());
Collections.sort(resultSet);
String maxPattern = resultSet.get(0);
String[] websites = maxPattern.split("#");
List<String> result = new ArrayList<String>();
result.add(websites[0]);
result.add(websites[1]);
result.add(websites[2]);
return result;
}
private String get3Tuple(List<String> list) {
int n = list.size();
return String.format("%s#%s#%s", list.get(n - 3), list.get(n - 2), list.get(n - 1));
}
}
| 30.97619 | 106 | 0.630438 |
eb7123cb5b50d7999af5ff6e82e451cadf352f2a | 1,890 | package com.fntj.app.activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.fntj.app.R;
import com.fntj.app.util.StatusBarUtils;
import com.fntj.lib.zxing.CaptureFragment;
/**
* Fragment扫码
* @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
*/
public class CaptureFragmentActivity extends AppCompatActivity {
public static final String KEY_TITLE = "key_title";
public static final String KEY_IS_QR_CODE = "key_code";
public static final String KEY_IS_CONTINUOUS = "key_continuous_scan";
public static final int REQUEST_CODE_SCAN = 0X01;
public static final int REQUEST_CODE_PHOTO = 0X02;
public static final int RC_CAMERA = 0X01;
public static final int RC_READ_PHOTO = 0X02;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_activity);
Toolbar toolbar = findViewById(R.id.toolbar);
StatusBarUtils.immersiveStatusBar(this,toolbar,0.2f);
TextView tvTitle = findViewById(R.id.tvTitle);
tvTitle.setText(getIntent().getStringExtra(KEY_TITLE));
replaceFragment(CaptureFragment.newInstance());
}
public void replaceFragment(Fragment fragment){
replaceFragment( R.id.fragmentContent,fragment);
}
public void replaceFragment(@IdRes int id, Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(id, fragment).commit();
}
public void onClick(View v){
switch (v.getId()){
case R.id.ivLeft:
onBackPressed();
break;
}
}
}
| 30.983607 | 86 | 0.718519 |
4a810184005a1bd01b107dcb4ca7dfe7b1763f63 | 2,354 | /**
* Copyright © 2008-2019, Province of British Columbia
*
* 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 ca.bc.gov.ols.rowreader;
import java.util.Iterator;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
public class DatastaxResultSetRowReader implements RowReader {
protected ResultSet rs;
protected Iterator<Row> iterator;
protected Row curRow;
public DatastaxResultSetRowReader(ResultSet rs) {
this.rs = rs;
iterator = rs.iterator();
}
@Override
public boolean next() {
if(iterator.hasNext()) {
curRow = iterator.next();
return true;
} else {
return false;
}
}
@Override
public Object getObject(String column) {
return curRow.getObject(column);
}
@Override
public int getInt(String column) {
return curRow.getInt(column);
}
@Override
public Integer getInteger(String column) {
return (Integer)curRow.getObject(column);
}
@Override
public double getDouble(String column) {
return curRow.getDouble(column);
}
@Override
public String getString(String column) {
return curRow.getString(column);
}
@Override
public java.time.LocalDate getDate(String column) {
return curRow.getLocalDate(column);
}
@Override
public Point getPoint() {
throw new UnsupportedOperationException("DatastacresultSetRowReader does not support getPoint()");
}
@Override
public Point getPoint(String column) {
throw new UnsupportedOperationException("DatastacresultSetRowReader does not support getPoint(column)");
}
@Override
public LineString getLineString() {
throw new UnsupportedOperationException("DatastacresultSetRowReader does not support getLineString()");
}
@Override
public void close() {
}
} | 24.520833 | 106 | 0.742991 |
977e269a0bb6633a3fe229c62c3145d19faf734f | 6,485 | package org.kumoricon.site.attendee;
import com.vaadin.event.ShortcutAction;
import com.vaadin.navigator.View;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
import org.kumoricon.BaseGridView;
import org.kumoricon.model.attendee.Attendee;
import org.kumoricon.model.attendee.AttendeeHistory;
import org.kumoricon.site.attendee.search.AttendeeSearchPresenter;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public abstract class CheckInView extends BaseGridView implements View {
public static final String VIEW_NAME = "order";
public static final String REQUIRED_RIGHT = "pre_reg_check_in";
private TextArea attendeeInfo = new TextArea("Attendee");
private Button btnCheckIn = new Button("Continue");
private Button btnEdit = new Button("Edit");
private Button btnCancel = new Button("Cancel");
private CheckBox informationVerified = new CheckBox("Information Verified");
private CheckBox parentalConsentFormReceived = new CheckBox("Parental Consent Form Received");
protected Attendee attendee;
protected Integer orderId;
protected AttendeeSearchPresenter handler;
public CheckInView(AttendeeSearchPresenter handler) {
this.handler = handler;
}
@PostConstruct
public void init() {
setRows(4);
setColumns(5);
setRowExpandRatio(3, 10.0f);
setColumnExpandRatio(0, 10.0f);
setColumnExpandRatio(3, 2.0f);
setColumnExpandRatio(4, 10.0f);
attendeeInfo.setEnabled(false);
attendeeInfo.setWidth("500px");
attendeeInfo.setHeight("500px");
addComponent(attendeeInfo, 1, 0, 1, 2);
addComponent(informationVerified, 2, 0);
addComponent(parentalConsentFormReceived, 2, 1);
btnCheckIn.addClickListener((Button.ClickListener) clickEvent -> btnCheckInClicked());
btnEdit.addClickListener((Button.ClickListener) clickEvent -> btnEditClicked());
btnCancel.addClickListener(c -> close());
btnCheckIn.setClickShortcut(ShortcutAction.KeyCode.ENTER);
btnCheckIn.addStyleName(ValoTheme.BUTTON_PRIMARY);
btnCheckIn.setEnabled(false);
addComponent(btnCheckIn, 3, 0);
addComponent(btnEdit, 3, 1);
addComponent(btnCancel, 3, 2);
informationVerified.addValueChangeListener(e -> enableButtons());
parentalConsentFormReceived.addValueChangeListener(e -> enableButtons());
}
private void enableButtons() {
if (attendeeIsIncomplete(attendee)) {
btnCheckIn.setEnabled(false);
return;
}
if (informationVerified.getValue()) {
if (attendee.isMinor()) {
if (parentalConsentFormReceived.getValue()) {
btnCheckIn.setEnabled(true);
} else {
btnCheckIn.setEnabled(false);
}
} else {
btnCheckIn.setEnabled(true);
}
} else {
btnCheckIn.setEnabled(false);
}
}
protected void btnCheckInClicked() {
handler.checkInAttendee(this, attendee);
close();
}
protected void btnEditClicked() {
throw new RuntimeException("Override btnEditClicked() in view");
}
@Override
public String getRequiredRight() {
return REQUIRED_RIGHT;
}
public void showAttendee(Attendee attendee) {
if (!attendee.getCheckedIn()) {
this.attendee = attendee;
attendeeInfo.setValue(dumpAttendeeToString(attendee));
parentalConsentFormReceived.setEnabled(attendee.isMinor());
} else {
notify("Error: Attendee already checked in");
close();
}
}
/**
* Instead of showing attendee information, show a warning message and disable all the controls.
* @param message Error message
*/
public void showErrorMessage(String message) {
attendeeInfo.setValue(message);
parentalConsentFormReceived.setEnabled(false);
informationVerified.setEnabled(false);
btnCheckIn.setEnabled(false);
btnEdit.setEnabled(false);
}
protected String dumpAttendeeToString(Attendee attendee) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("Name: %s %s\n", attendee.getFirstName(), attendee.getLastName()));
if (!attendee.getNameIsLegalName()) {
sb.append(String.format("Legal Name: %s %s\n\n", attendee.getLegalFirstName(), attendee.getLegalLastName()));
}
sb.append(String.format("Birthdate: %s (%s years old)\n", attendee.getBirthDate().format(DateTimeFormatter.ofPattern("M/d/yyyy")), attendee.getAge()));
sb.append(String.format("Emergency Contact: \n\t%s \n\t%s\n", attendee.getEmergencyContactFullName(), attendee.getEmergencyContactPhone()));
if (attendee.isMinor()) {
sb.append(String.format("Parent Contact: \n\t%s \n\t%s\n", attendee.getParentFullName(), attendee.getParentPhone()));
}
if (attendeeIsIncomplete(attendee)) {
sb.append("\n** MISSING EMERGENCY CONTACT OR BIRTHDATE **");
}
sb.append("\nNotes:\n");
for (AttendeeHistory history : attendee.getHistory()) {
if (history.getUser() != null && history.getUser().getUsername() != null) {
sb.append(history.getUser().getUsername() + ": ");
}
sb.append(history.getMessage() + "\n");
}
return sb.toString();
}
private static boolean attendeeIsIncomplete(Attendee attendee) {
// Make sure emergency contact and birthdate exist. TODO: handle missing information more
// gracefully. Right now 1/1/1900 is kind of a "magic number" in that it was included
// in the import data as a default.
if (attendee.getEmergencyContactFullName().trim().isEmpty() ||
attendee.getEmergencyContactPhone().trim().isEmpty() ||
attendee.getBirthDate().equals(LocalDate.of(1900, 1, 1))) {
return true;
} else {
return false;
}
}
public boolean parentalConsentFormReceived() {
return parentalConsentFormReceived.getValue();
}
public boolean informationVerified() {
return informationVerified.getValue();
}
}
| 36.22905 | 159 | 0.6532 |
8262e4a257bb6d9d139e5ec3cc49b14af3a3e730 | 14,089 | /**
* 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.cloudata.core.tabletserver;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import org.cloudata.core.client.Cell;
import org.cloudata.core.client.CellFilter;
import org.cloudata.core.client.Row;
import org.cloudata.core.client.RowFilter;
import org.cloudata.core.client.CellFilter.CellPage;
import org.cloudata.core.common.conf.CloudataConf;
import org.cloudata.core.tablet.ColumnValue;
import org.cloudata.core.tablet.RowColumnValues;
import org.cloudata.core.tablet.TabletInfo;
import org.cloudata.core.tabletserver.DiskSSTable;
import org.cloudata.core.tabletserver.MemorySSTable;
import org.cloudata.core.tabletserver.RecordSearcher;
import org.cloudata.core.tabletserver.ServerSideMultiColumnScanner;
import org.cloudata.core.tabletserver.TabletScanner;
import junit.framework.TestCase;
/**
* @author jindolk
*
*/
public abstract class TestRecordSearcher extends TestCase {
public static boolean PRINT = false;
protected CloudataConf conf = new CloudataConf();
protected DecimalFormat df = new DecimalFormat("0000000000");
protected int NUM_ROWS = 100;
protected int NUM_CELL1 = 3;
protected int NUM_CELL2 = 20;
protected int TIMESTAMP1 = 10;
protected int TIMESTAMP2 = 100;
protected TabletInfo tabletInfo = new TabletInfo("T_TEST", "T_TEST_1234", Row.Key.MIN_KEY, Row.Key.MAX_KEY);
protected MemorySSTable memorySSTable;
protected DiskSSTable diskSSTable;
protected abstract MemorySSTable makeMemorySSTable() throws IOException;
protected abstract DiskSSTable makeDiskSSTable() throws IOException;
public TestRecordSearcher(String name) {
super(name);
conf.set("cloudata.filesystem", "local");
}
public void setUp() throws IOException {
memorySSTable = makeMemorySSTable();
diskSSTable = makeDiskSSTable();
}
protected int getNumCells(int rowId) {
return (rowId % 2 == 0 ? NUM_CELL1 : NUM_CELL2);
}
public void testFilter() throws IOException {
System.out.println("===================================== testRowFilter =====================================");
RecordSearcher searcher = new RecordSearcher(memorySSTable, diskSSTable, 3);
//1. get with row key
for(int i = 0; i < NUM_ROWS; i++) {
Row.Key rowKey = new Row.Key(df.format(i));
ColumnValue[] columnValues = searcher.search(rowKey, "Col1");
assertNotNull(columnValues);
assertTrue(columnValues.length > 0);
Row row = RowColumnValues.makeRow(
new RowColumnValues[]{new RowColumnValues("Col1", rowKey, columnValues)});
assertEquals(rowKey, row.getKey());
List<Cell> cells = row.getCellList("Col1");
assertEquals(getNumCells(i), cells.size());
columnValues = searcher.search(rowKey, "Col2");
assertNotNull(columnValues);
assertEquals(1, columnValues.length);
}
//2. get with cell key
for(int i = 0; i < NUM_ROWS; i++) {
Row.Key rowKey = new Row.Key(df.format(i));
int numCells = getNumCells(i);
for(int j = 0; j < numCells; j++) {
Cell.Key cellKey = new Cell.Key(df.format(j));
ColumnValue columnValue = searcher.search(rowKey, "Col1", cellKey);
assertNotNull(columnValue);
assertEquals(rowKey, columnValue.getRowKey());
assertEquals(cellKey, columnValue.getCellKey());
}
ColumnValue columnValue = searcher.search(rowKey, "Col2", Cell.Key.EMPTY_KEY);
assertNotNull(columnValue);
assertEquals(rowKey, columnValue.getRowKey());
assertEquals(Cell.Key.EMPTY_KEY, columnValue.getCellKey());
}
//3. get with CellFilter(timestamp)
for(int i = 0; i < NUM_ROWS; i++) {
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)));
CellFilter cellFilter1 = new CellFilter("Col1");
cellFilter1.setTimestamp(TIMESTAMP1, TIMESTAMP1 + 2);
rowFilter.addCellFilter(cellFilter1);
RowColumnValues[] values = searcher.search(rowFilter);
if(i % 2 == 1) {
assertNull(values);
continue;
}
assertNotNull(values);
Row row = RowColumnValues.makeRow(values);
List<Cell> cells = row.getCellList("Col1");
assertEquals(2, cells.size());
}
//4. get with CellFilter(numOfVersions)
for(int i = 0; i < NUM_ROWS; i++) {
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)));
CellFilter cellFilter1 = new CellFilter("Col1");
cellFilter1.setNumOfVersions(2);
rowFilter.addCellFilter(cellFilter1);
RowColumnValues[] values = searcher.search(rowFilter);
assertNotNull(values);
Row row = RowColumnValues.makeRow(values);
List<Cell> cells = row.getCellList("Col1");
assertEquals(getNumCells(i), cells.size());
for(Cell eachCell: cells) {
List<Cell.Value> cellValues = eachCell.getValues();
assertEquals(2, cellValues.size());
}
}
//5. get with CellFilter(cellPaging)
int pageSize = 5;
for(int i = 0; i < NUM_ROWS; i++) {
int readCell = 0;
int startKeyIndex = 2;
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)));
CellFilter cellFilter1 = new CellFilter("Col1", new Cell.Key(df.format(startKeyIndex)), new Cell.Key(df.format(15)));
cellFilter1.setCellPage(new CellPage(pageSize));
rowFilter.addCellFilter(cellFilter1);
RowColumnValues[] values = null;
int page = 1;
while( (values = searcher.search(rowFilter)) != null ) {
assertNotNull(values);
Row row = RowColumnValues.makeRow(values);
int expectedCells = 0;
if(i % 2 == 0) {
expectedCells = 1;
} else {
if(page == 3) {
expectedCells = 4;
} else {
expectedCells = pageSize;
}
}
List<Cell> cells = row.getCellList("Col1");
assertEquals(expectedCells, cells.size());
int index = 0;
for(Cell eachCell: cells) {
assertEquals(new Cell.Key(df.format(startKeyIndex + (page - 1) * pageSize + index)), eachCell.getKey());
readCell++;
index++;
}
page++;
cellFilter1.setCellPage(row.getNextCellPage("Col1", pageSize));
}
assertEquals(page - 1, i % 2 == 0 ? 1: 3);
assertEquals(readCell, i % 2 == 0 ? 1: 14);
}
//6. get with CellFilter(startCellKey, endCellKey)
int startCellIndex = 1;
int endCellIndex = 9;
for(int i = 0; i < NUM_ROWS; i++) {
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)));
CellFilter cellFilter1 = new CellFilter("Col1", new Cell.Key(df.format(startCellIndex)),new Cell.Key(df.format(endCellIndex)));
CellFilter cellFilter2 = new CellFilter("Col2", new Cell.Key(df.format(startCellIndex)),new Cell.Key(df.format(endCellIndex)));
rowFilter.addCellFilter(cellFilter1);
rowFilter.addCellFilter(cellFilter2);
RowColumnValues[] values = searcher.search(rowFilter);
assertNotNull(values);
int expectedCells = (i % 2 == 0 ? 2 : 9);
Row row = RowColumnValues.makeRow(values);
List<Cell> cells = row.getCellList("Col1");
assertEquals(i + " row" , expectedCells, cells.size());
for(int j = 0; j < expectedCells; j++) {
Cell cell = cells.get(j);
assertEquals(df.format(startCellIndex + j), cell.getKey().toString());
}
cells = row.getCellList("Col2");
assertNull(cells);
}
startCellIndex = 5;
endCellIndex = 9;
for(int i = 0; i < NUM_ROWS; i++) {
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)));
CellFilter cellFilter1 = new CellFilter("Col1", new Cell.Key(df.format(startCellIndex)),new Cell.Key(df.format(endCellIndex)));
CellFilter cellFilter2 = new CellFilter("Col2", new Cell.Key(df.format(startCellIndex)),new Cell.Key(df.format(endCellIndex)));
rowFilter.addCellFilter(cellFilter1);
rowFilter.addCellFilter(cellFilter2);
RowColumnValues[] values = searcher.search(rowFilter);
if(i % 2 == 0) {
assertNull(values);
continue;
}
assertNotNull(values);
int expectedCells = 5;
Row row = RowColumnValues.makeRow(values);
List<Cell> cells = row.getCellList("Col1");
assertEquals(i + " row" , expectedCells, cells.size());
for(int j = 0; j < expectedCells; j++) {
Cell cell = cells.get(j);
assertEquals(df.format(startCellIndex + j), cell.getKey().toString());
}
cells = row.getCellList("Col2");
assertNull(cells);
}
//7. get with CellFilter(startCellKey, endCellKey, numOfVersion)
startCellIndex = 1;
endCellIndex = 9;
for(int i = 0; i < NUM_ROWS; i++) {
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)));
CellFilter cellFilter1 = new CellFilter("Col1", new Cell.Key(df.format(startCellIndex)),new Cell.Key(df.format(endCellIndex)));
cellFilter1.setNumOfVersions(2);
rowFilter.addCellFilter(cellFilter1);
RowColumnValues[] values = searcher.search(rowFilter);
assertNotNull(values);
int expectedCells = (i % 2 == 0 ? 2 : 9);
Row row = RowColumnValues.makeRow(values);
List<Cell> cells = row.getCellList("Col1");
assertEquals(i + " row" , expectedCells, cells.size());
for(int j = 0; j < expectedCells; j++) {
Cell cell = cells.get(j);
assertEquals(df.format(startCellIndex + j), cell.getKey().toString());
List<Cell.Value> cellValues = cell.getValues();
assertNotNull(cellValues);
assertEquals(2, cellValues.size());
int index = 1;
for(Cell.Value cellValue: cellValues) {
assertEquals(df.format(i) + "_" + df.format(startCellIndex + j) + "_Cell1DataV" + index, cellValue.getValueAsString());
index--;
}
}
}
//8. get with CellFilter(timestamp)
for(int i = 0; i < NUM_ROWS; i++) {
RowFilter rowFilter = new RowFilter(new Row.Key(df.format(i)), new Row.Key(df.format(i)),
RowFilter.OP_EQ);
CellFilter cellFilter = new CellFilter("Col2");
cellFilter.setTimestamp(Long.MIN_VALUE, Long.MAX_VALUE);
rowFilter.addCellFilter(cellFilter);
RowColumnValues[] values = searcher.search(rowFilter);
assertNotNull(values);
Row row = RowColumnValues.makeRow(values);
List<Cell> cells = row.getCellList("Col2");
assertNotNull(cells);
assertEquals(1, cells.size());
}
}
public void testScanner() throws IOException {
System.out.println("===================================== testScanner =====================================");
//1. Scan all data
RowFilter rowFilter = new RowFilter(Row.Key.MIN_KEY, Row.Key.MAX_KEY);
CellFilter cellFilter = new CellFilter("Col1");
rowFilter.addCellFilter(cellFilter);
TabletScanner tabletScanner = new TabletScanner("test", conf, tabletInfo,
rowFilter.getStartRowKey(), rowFilter.getEndRowKey(), "Col1", memorySSTable, diskSSTable,
cellFilter, 3, false);
ServerSideMultiColumnScanner scanner = new ServerSideMultiColumnScanner(null, rowFilter, new TabletScanner[]{tabletScanner});
RowColumnValues[] rowColumnValue = null;
int rowCount = 0;
while((rowColumnValue = scanner.nextRow()) != null) {
Row row = RowColumnValues.makeRow(rowColumnValue);
assertEquals(new Row.Key(df.format(rowCount)), row.getKey());
List<Cell> cells = row.getCellList("Col1");
assertNotNull(cells);
assertEquals(getNumCells(rowCount), cells.size());
rowCount++;
}
scanner.close();
assertEquals(rowCount, NUM_ROWS);
//2. Range Scan
rowFilter = new RowFilter(new Row.Key(df.format(10)), new Row.Key(df.format(30)));
cellFilter = new CellFilter("Col1");
rowFilter.addCellFilter(cellFilter);
tabletScanner = new TabletScanner("test", conf, tabletInfo,
rowFilter.getStartRowKey(), rowFilter.getEndRowKey(), "Col1", memorySSTable, diskSSTable,
cellFilter, 3, false);
scanner = new ServerSideMultiColumnScanner(null, rowFilter, new TabletScanner[]{tabletScanner});
rowColumnValue = null;
rowCount = 0;
int rowIndex = 10;
while((rowColumnValue = scanner.nextRow()) != null) {
Row row = RowColumnValues.makeRow(rowColumnValue);
assertEquals(new Row.Key(df.format(rowIndex)), row.getKey());
List<Cell> cells = row.getCellList("Col1");
assertNotNull(cells);
assertEquals(getNumCells(rowCount), cells.size());
rowCount++;
rowIndex++;
}
scanner.close();
assertEquals(rowCount, 21);
}
}
| 37.570667 | 134 | 0.626304 |
9a242b0466e03f153ab8d76bffba5f02c351ffb1 | 9,366 | /*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at http://www.netbeans.org/cddl.html
* or http://www.netbeans.org/cddl.txt.
*
* When distributing Covered Code, include this CDDL Header Notice in each file
* and include the License file at http://www.netbeans.org/cddl.txt.
* If applicable, add the following below the CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.modules.erlang.project.ui;
import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.Icon;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.queries.VisibilityQuery;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.ChangeableDataFilter;
import org.openide.loaders.DataFilter;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;
import org.openide.nodes.FilterNode;
import org.openide.nodes.Node;
import org.openide.nodes.NodeNotFoundException;
import org.openide.nodes.NodeOp;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import org.openide.util.lookup.Lookups;
import org.openide.util.lookup.ProxyLookup;
// XXX need unit test
/**
* (Copied from Java Project Source (org.netbeans.spi.gsfpath.project.support.ui)
* Displays a package root in a tree.
* @see "#42151"
* @author Jesse Glick
*/
public final class TreeRootNode extends FilterNode implements PropertyChangeListener {
private static final DataFilter VISIBILITY_QUERY_FILTER = new VisibilityQueryDataFilter();
private final SourceGroup g;
public TreeRootNode(SourceGroup g) {
this(DataFolder.findFolder(g.getRootFolder()), g);
}
private TreeRootNode(DataFolder folder, SourceGroup g) {
this (new FilterNode (folder.getNodeDelegate(), folder.createNodeChildren(VISIBILITY_QUERY_FILTER)),g);
}
private TreeRootNode (Node originalNode, SourceGroup g) {
super(originalNode, new PackageFilterChildren(originalNode),
new ProxyLookup(
originalNode.getLookup(),
Lookups.singleton(new PathFinder(g))
// no need for explicit search info
));
this.g = g;
g.addPropertyChangeListener(WeakListeners.propertyChange(this, g));
}
static Image PACKAGE_BADGE = Utilities.loadImage( "org/netbeans/modules/erlang/project/ui/packageBadge.gif" ); // NOI18N
/** Copied from PackageRootNode with modifications. */
private Image computeIcon(boolean opened, int type) {
Icon icon = g.getIcon(opened);
if (icon == null) {
Image image = opened ? super.getOpenedIcon(type) : super.getIcon(type);
return Utilities.mergeImages(image, /*PackageRootNode.*/PACKAGE_BADGE, 7, 7);
} else {
return Utilities.icon2Image(icon);
}
}
public Image getIcon(int type) {
return computeIcon(false, type);
}
public Image getOpenedIcon(int type) {
return computeIcon(true, type);
}
public String getName() {
return g.getName();
}
public String getDisplayName() {
return g.getDisplayName();
}
public boolean canRename() {
return false;
}
public boolean canDestroy() {
return false;
}
public boolean canCut() {
return false;
}
public void propertyChange(PropertyChangeEvent ev) {
// XXX handle SourceGroup.rootFolder change too
fireNameChange(null, null);
fireDisplayNameChange(null, null);
fireIconChange();
fireOpenedIconChange();
}
/** Copied from PhysicalView and PackageRootNode. */
public static final class PathFinder {
private final SourceGroup g;
PathFinder(SourceGroup g) {
this.g = g;
}
public Node findPath(Node rootNode, Object o) {
FileObject fo;
if (o instanceof FileObject) {
fo = (FileObject) o;
} else if (o instanceof DataObject) {
fo = ((DataObject) o).getPrimaryFile();
} else {
return null;
}
FileObject groupRoot = g.getRootFolder();
if (FileUtil.isParentOf(groupRoot, fo) /* && group.contains(fo) */) {
FileObject folder = fo.isFolder() ? fo : fo.getParent();
String relPath = FileUtil.getRelativePath(groupRoot, folder);
List<String> path = new ArrayList<String>();
StringTokenizer strtok = new StringTokenizer(relPath, "/"); // NOI18N
while (strtok.hasMoreTokens()) {
String token = strtok.nextToken();
path.add(token);
}
try {
Node folderNode = folder.equals(groupRoot) ? rootNode : NodeOp.findPath(rootNode, Collections.enumeration(path));
if (fo.isFolder()) {
return folderNode;
} else {
Node[] childs = folderNode.getChildren().getNodes(true);
for (int i = 0; i < childs.length; i++) {
DataObject dobj = childs[i].getLookup().lookup(DataObject.class);
if (dobj != null && dobj.getPrimaryFile().getNameExt().equals(fo.getNameExt())) {
return childs[i];
}
}
}
} catch (NodeNotFoundException e) {
e.printStackTrace();
}
} else if (groupRoot.equals(fo)) {
return rootNode;
}
return null;
}
}
/** Copied from PhysicalView. */
private static final class VisibilityQueryDataFilter implements ChangeListener, ChangeableDataFilter {
private static final long serialVersionUID = 1L; // in case a DataFolder.ClonedFilterHandle saves me
private final EventListenerList ell = new EventListenerList();
public VisibilityQueryDataFilter() {
VisibilityQuery.getDefault().addChangeListener(this);
}
public boolean acceptDataObject(DataObject obj) {
FileObject fo = obj.getPrimaryFile();
return VisibilityQuery.getDefault().isVisible(fo);
}
public void stateChanged(ChangeEvent e) {
Object[] listeners = ell.getListenerList();
ChangeEvent event = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (event == null) {
event = new ChangeEvent(this);
}
((ChangeListener) listeners[i+1]).stateChanged(event);
}
}
}
public void addChangeListener(ChangeListener listener) {
ell.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener) {
ell.remove(ChangeListener.class, listener);
}
}
private static final class PackageFilterChildren extends FilterNode.Children {
public PackageFilterChildren (final Node originalNode) {
super (originalNode);
}
@Override
protected Node copyNode(final Node originalNode) {
DataObject dobj = originalNode.getLookup().lookup(DataObject.class);
return (dobj instanceof DataFolder) ? new PackageFilterNode (originalNode) : super.copyNode(originalNode);
}
}
private static final class PackageFilterNode extends FilterNode {
public PackageFilterNode (final Node origNode) {
super (origNode, new PackageFilterChildren (origNode));
}
@Override
public void setName (final String name) {
if (Utilities.isJavaIdentifier (name)) {
super.setName (name);
}
else {
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message (
NbBundle.getMessage(TreeRootNode.class,"MSG_InvalidPackageName"), NotifyDescriptor.INFORMATION_MESSAGE));
}
}
}
}
| 36.162162 | 134 | 0.61467 |
bd609842560a9fc72acbf29872e8b28c3985b145 | 887 | package com.sata.dfs.pureBackTracing.combinations;
import java.util.ArrayList;
import java.util.List;
/**
* LC 77
*/
public class Combinations {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
helper(res, tmp, 1, n, k);
return res;
}
private void helper(List<List<Integer>> res,
List<Integer> tmp,
int cur, int n,
int k) {
if(tmp.size() == k) { //number 是当前层数
res.add(new ArrayList<>(tmp));
return;
}
for(int i = cur; i <= n - (k - tmp.size()) + 1; i++) { //这里做了剪枝, i至少从n - (k - tmp.size()) + 1开始,避免元素个数不够
tmp.add(i);
helper(res, tmp, i + 1, n, k);
tmp.remove(tmp.size() - 1);
}
}
}
| 27.71875 | 112 | 0.485908 |
07829a496f409b97ed0773a9ce907cf30f0b01c9 | 9,866 | /*
* The MIT License
*
* Copyright (c) 2017 Quality First Software GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.qftest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import net.sf.json.JSONObject;
import static java.util.Collections.emptyList;
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value="UUF_UNUSED_FIELD",
justification="Need unused transient values for backward compatibility"
)
public class QFTestConfigBuilder extends Builder implements QFTestParamProvider
{
/* deprecated members */
private static final long serialVersionUID = 8305941021849820496L;
private transient boolean customReportTempDirectory;
private transient boolean specificQFTestVersion;
private transient boolean suitesEmpty;
private transient boolean daemonSelected;
private transient String daemonhost;
private transient String daemonport;
/* >> SAME LOGIC AS IN QFTESTSTEP >> */
/**
* CTOR
*
* @param suitefield Contains name of testsuites and their command line arguments
*/
@DataBoundConstructor
public QFTestConfigBuilder(List<Suites> suitefield) {
if (suitefield != null) {
this.suitefield = new ArrayList<Suites>(suitefield);
} else {
this.suitefield = Collections.<Suites>emptyList();
}
}
private final List<Suites> suitefield;
public List<Suites> getSuitefield() {
return suitefield;
}
@CheckForNull
private String customPath;
public @CheckForNull
String getCustomPath() {
return customPath;
}
@DataBoundSetter
public void setCustomPath(String customPath) {
if (customPath != null) {
this.customPath = customPath.isEmpty() ? null : customPath;
}
}
@CheckForNull
private String customReports;
public @Nonnull
String getReportDirectory() {
return (customReports != null ? customReports : DefaultValues.reportDir);
}
@DataBoundSetter
public void setReportDirectory(String customReports) {
if (customReports == null || customReports.isEmpty() || customReports.equals(DefaultValues.reportDir)) {
this.customReports = null;
} else {
this.customReports = customReports;
}
}
private String customReportArgs = "";
@Override
public String getReportGenArgs() {
return customReportArgs;
}
@DataBoundSetter
public void setReportGenArgs(String extraArgs) {
customReportArgs = extraArgs;
}
private Result onTestWarning;
private Result onTestError;
private Result onTestException;
private Result onTestFailure;
public String getOnTestWarning() {
return (onTestWarning != null ? onTestWarning : DefaultValues.testWarning).toString();
}
public String getOnTestError() {
return (onTestError != null ? onTestError : DefaultValues.testError).toString();
}
public String getOnTestException() {
return (onTestException != null ? onTestException : DefaultValues.testException).toString();
}
public String getOnTestFailure() {
return (onTestFailure != null ? onTestFailure : DefaultValues.testFailure).toString();
}
@DataBoundSetter
public void setOnTestWarning(String onTestWarning) {
if (!onTestWarning.equals(DefaultValues.testWarning.toString())) {
this.onTestWarning = Result.fromString(onTestWarning);
}
}
@DataBoundSetter
public void setOnTestError(String onTestError) {
if (!onTestError.equals(DefaultValues.testError.toString())) {
this.onTestError = Result.fromString(onTestError);
}
}
@DataBoundSetter
public void setOnTestException(String onTestException) {
if (!onTestException.equals(DefaultValues.testException.toString())) {
this.onTestException = Result.fromString(onTestException);
}
}
@DataBoundSetter
public void setOnTestFailure(String onTestFailure) {
if (!onTestFailure.equals(DefaultValues.testFailure.toString())) {
this.onTestFailure = Result.fromString(onTestFailure);
}
}
/* << SAME LOGIC AS IN QFTESTSTEP << */
/** Called by XStream when deserializing object
*/
protected Object readResolve() {
this.setCustomPath(customPath);
this.setReportDirectory(customReports);
return this;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, java.io.IOException, InterruptedException {
FilePath workspace = build.getWorkspace();
assert(workspace != null);
QFTestExecutor.Imp.run(build, workspace, launcher, listener, build.getEnvironment(listener), this);
return true;
}
/**
* Implementation of descriptor
*/
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
@CheckForNull
private String qfPath;
@CheckForNull
private String qfPathUnix;
public DescriptorImpl() {
load();
//ensure qfPath is either null or non-empty string
qfPath = this.getQfPath();
qfPathUnix = this.getQfPathUnix();
}
/*
* (non-Javadoc)
*
* @see hudson.tasks.BuildStepDescriptor#isApplicable(java.lang.Class)
*/
@Override
@SuppressWarnings("rawtypes")
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project
// types
return true;
}
/*
* (non-Javadoc)
*
* @see hudson.model.Descriptor#getDisplayName()
*/
@Override
public String getDisplayName() {
return "Run QF-Test";
}
/*
* (non-Javadoc)
*
* @see
* hudson.model.Descriptor#configure(org.kohsuke.stapler.StaplerRequest,
* net.sf.json.JSONObject)
*/
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
qfPath = formData.getString("qfPath");
qfPathUnix = formData.getString("qfPathUnix");
save();
return super.configure(req, formData);
}
/**
* Returns the defined QF-Test installation path (Windows) in the global
* setting.
*
* @return path to QF-Test installation (Windows)
*/
public String getQfPath() {
if (qfPath != null && !qfPath.isEmpty()) {
return qfPath;
} else {
return null;
}
}
/**
* Returns the defined QF-Test installation path (Unix) in the global
* setting.
*
* @return path to QF-Test installation (Unix)
*/
public String getQfPathUnix() {
if (qfPathUnix != null && !qfPathUnix.isEmpty()) {
return qfPathUnix;
} else {
return null;
}
}
//TODO: change this
public FormValidation doCheckDirectory(@QueryParameter String value) {
if (value.contains(":") || value.contains("*")
|| value.contains("?") || value.contains("<")
|| value.contains("|") || value.contains(">")) {
return FormValidation.error("Path contains forbidden characters");
}
return FormValidation.ok();
}
static public ListBoxModel fillOnTestResult(Result preSelect) {
ListBoxModel items = new ListBoxModel();
Stream.of(Result.SUCCESS, Result.UNSTABLE, Result.FAILURE, Result.ABORTED, Result.NOT_BUILT)
.forEach(res -> {
items.add(res.toString());
if (preSelect == res) { //mark this as selection
items.get(items.size()-1).selected = true;
}
});
return items;
}
public ListBoxModel doFillOnTestWarningItems(@QueryParameter("onTestWarning") String preset) {
return fillOnTestResult(preset.isEmpty()? DefaultValues.testWarning : Result.fromString(preset));
}
public ListBoxModel doFillOnTestErrorItems(@QueryParameter("onTestError") String preset) {
return fillOnTestResult(preset.isEmpty() ? DefaultValues.testError : Result.fromString(preset));
}
public ListBoxModel doFillOnTestExceptionItems(@QueryParameter("onTestException") String preset) {
return fillOnTestResult(preset.isEmpty() ? DefaultValues.testException : Result.fromString(preset));
}
public ListBoxModel doFillOnTestFailureItems(@QueryParameter("onTestFailure") String preset) {
return fillOnTestResult(preset.isEmpty() ? DefaultValues.testFailure : Result.fromString(preset));
}
}
// Descriptor is needed to access global variables
/*
* (non-Javadoc)
*
* @see hudson.tasks.Builder#getDescriptor()
*/
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
}
| 27.870056 | 151 | 0.735252 |
99f07ed76e83a30bf7c1af203e7e7010a84bbba7 | 261 | package com.credit.analysis.exeption;
import java.util.Optional;
public class Errors {
private String errorMessage;
public Errors(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
}
| 16.3125 | 37 | 0.762452 |
71eed6c0357fc51d56c2bf628944497264124dc7 | 1,799 | /*
* Copyright 2012 jts
*
* 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 ru.jts.data.holder.dyedata;
import ru.jts.annotations.data.array.IntArray;
import ru.jts.annotations.data.value.IntValue;
import ru.jts.annotations.data.value.StringValue;
/**
* @author : Camelion
* @date : 27.08.12 1:37
*/
public class DyeData {
@StringValue
public String dye_name; // Название, есть в itemdata.txt
@IntValue
public int dye_id; // ID
@IntValue
public int dye_item_id; // Item ID
@IntValue
public int dye_level; //
@IntValue
public int str; // STR
@IntValue
public int con; // CON
@IntValue
public int dex; // DEX
@IntValue(name = "int")
public int _int; // INT
@IntValue
public int men; // MEN
@IntValue
public int wit; // WIT
@IntValue
public int need_count; // Необходимое кол-во таких предметов для нанесения тату
@IntValue
public int wear_fee; // Вероятно, цена нанесения
@IntValue
public int cancel_count; // Количество предметов, возвращаемое при снятии тату
@IntValue
public int cancel_fee; // Цена снятия тату
@IntArray
public int[] wear_class; // Список классов, которым доступна эта тату
}
| 29.016129 | 84 | 0.670928 |
e5495ee7a0afad1fd416aa9445e272f92923d67b | 568 | package com.example.GreenNest.response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
public class ResponseHandle {
public static ResponseEntity<Object> response(String message, HttpStatus status, Object responseObj){
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", message);
map.put("status", status.value());
map.put("data", responseObj);
return new ResponseEntity<Object>(map, status);
}
}
| 29.894737 | 105 | 0.713028 |
16e4b406cc741956666b74708fe9c9e16dbfc0cf | 319 | package com.mstruzek.ccbyte.cpool;
import com.mstruzek.ccbyte.annotation.Discriminator;
@Discriminator(byteValue = 8)
public class CONSTANT_String extends CONSTANT_Tag {
public short string_index;
@Override
public String resolveAsString(ConstPool constPool) {
return constPool.resolve(string_index);
}
}
| 22.785714 | 54 | 0.793103 |
457cff31c80b0df2b40cfcc80eb5d93da3d22ab0 | 175 | package main.util.codetester;
public class Languages {
//Just to get pass by reference via SuperClass
public static String s;
public Languages(String s){
this.s=s;
}
}
| 17.5 | 47 | 0.737143 |
03cf447fe0d6d98a96714f01a3ad4226771114e0 | 1,315 | package net.minecraft.world.phys.shapes;
import it.unimi.dsi.fastutil.doubles.DoubleList;
import net.minecraft.core.EnumDirection;
public class VoxelShapeSlice extends VoxelShape {
private final VoxelShape b;
private final EnumDirection.EnumAxis c;
private static final DoubleList d = new VoxelShapeCubePoint(1);
public VoxelShapeSlice(VoxelShape voxelshape, EnumDirection.EnumAxis enumdirection_enumaxis, int i) {
super(a(voxelshape.a, enumdirection_enumaxis, i));
this.b = voxelshape;
this.c = enumdirection_enumaxis;
}
private static VoxelShapeDiscrete a(VoxelShapeDiscrete voxelshapediscrete, EnumDirection.EnumAxis enumdirection_enumaxis, int i) {
return new VoxelShapeDiscreteSlice(voxelshapediscrete, enumdirection_enumaxis.a(i, 0, 0), enumdirection_enumaxis.a(0, i, 0), enumdirection_enumaxis.a(0, 0, i), enumdirection_enumaxis.a(i + 1, voxelshapediscrete.a, voxelshapediscrete.a), enumdirection_enumaxis.a(voxelshapediscrete.b, i + 1, voxelshapediscrete.b), enumdirection_enumaxis.a(voxelshapediscrete.c, voxelshapediscrete.c, i + 1));
}
@Override
protected DoubleList a(EnumDirection.EnumAxis enumdirection_enumaxis) {
return enumdirection_enumaxis == this.c ? VoxelShapeSlice.d : this.b.a(enumdirection_enumaxis);
}
}
| 48.703704 | 399 | 0.769582 |
a73a5cb5ca2bea02d3f231b51b2e35dfbd537683 | 2,184 | package org.aflabs.kafka.consumer.notifier.processor;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.ir.ObjectNode;
import org.aflabs.kafka.consumer.notifier.notification.Email;
import org.aflabs.kafka.consumer.notifier.notification.Notification;
import org.aflabs.kafka.consumer.notifier.notification.NotificationFactory;
import org.aflabs.kafka.consumer.notifier.notification.Telegram;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
public class Processor implements Runnable {
private static final String SUBJECT = "New alarm received for host ";
private static final String CONTENT = "Information about host: ";
private static Logger log = LoggerFactory.getLogger(Processor.class);
private ConsumerRecords<String,String> consumerRecords;
Notification test = NotificationFactory.getNotification("email");
public Processor(ConsumerRecords<String,String> consumerRecords)
{
this.consumerRecords = consumerRecords;
}
@Override
public void run() {
ConsumerRecord<String,String> consumerRecord;
Iterator<ConsumerRecord<String, String>> iterator = consumerRecords.iterator();
while(iterator.hasNext())
{
consumerRecord = iterator.next();
log.info("Process message: Key -> {} Message -> {}",consumerRecord.key(),consumerRecord.value());
if(consumerRecord.value() == null)
continue;
NotificationFactory.getNotification("email").send(consumerRecord.key(),consumerRecord.value());
NotificationFactory.getNotification("telegram").send(consumerRecord.key(),consumerRecord.value());
//Email.sendEmail(SUBJECT+consumerRecord.key(),CONTENT+consumerRecord.value());
}
}
public ConsumerRecords<String, String> getConsumerRecords() {
return consumerRecords;
}
public void setConsumerRecords(ConsumerRecords<String, String> consumerRecords) {
this.consumerRecords = consumerRecords;
}
}
| 35.803279 | 110 | 0.732601 |
547736c04ed4da3af992f298fdbce5b75a77e700 | 3,272 | package p005cm.aptoide.p006pt.install;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import org.jacoco.agent.p025rt.internal_8ff85ea.Offline;
import p005cm.aptoide.p006pt.AptoideApplication;
import p005cm.aptoide.p006pt.crashreports.CrashReport;
import p005cm.aptoide.p006pt.root.RootAvailabilityManager;
import p026rx.C0117M;
import p026rx.p027b.C0128a;
import p026rx.p027b.C0129b;
import p026rx.schedulers.Schedulers;
/* renamed from: cm.aptoide.pt.install.CheckRootOnBoot */
public class CheckRootOnBoot extends BroadcastReceiver {
private static transient /* synthetic */ boolean[] $jacocoData = null;
private static final String HTC_BOOT_COMPLETED = "android.intent.action.QUICKBOOT_POWERON";
private CrashReport crashReport;
private static /* synthetic */ boolean[] $jacocoInit() {
boolean[] zArr = $jacocoData;
if (zArr != null) {
return zArr;
}
boolean[] probes = Offline.getProbes(-4232464843239016205L, "cm/aptoide/pt/install/CheckRootOnBoot", 17);
$jacocoData = probes;
return probes;
}
public CheckRootOnBoot() {
$jacocoInit()[0] = true;
}
public void onReceive(Context context, Intent intent) {
boolean[] $jacocoInit = $jacocoInit();
this.crashReport = CrashReport.getInstance();
$jacocoInit[1] = true;
if (intent == null) {
$jacocoInit[2] = true;
} else {
String action = intent.getAction();
$jacocoInit[3] = true;
if (action.equals("android.intent.action.BOOT_COMPLETED")) {
$jacocoInit[4] = true;
} else {
String action2 = intent.getAction();
$jacocoInit[5] = true;
if (action2.equals("android.intent.action.REBOOT")) {
$jacocoInit[6] = true;
} else {
String action3 = intent.getAction();
$jacocoInit[7] = true;
if (!action3.equals(HTC_BOOT_COMPLETED)) {
$jacocoInit[8] = true;
} else {
$jacocoInit[9] = true;
}
}
}
RootAvailabilityManager rootAvailabilityManager = ((AptoideApplication) context.getApplicationContext()).getRootAvailabilityManager();
$jacocoInit[10] = true;
C0117M updateRootAvailability = rootAvailabilityManager.updateRootAvailability();
$jacocoInit[11] = true;
C0117M b = updateRootAvailability.mo3593b(Schedulers.computation());
C4030b bVar = C4030b.f7529a;
C4027a aVar = new C4027a(this);
$jacocoInit[12] = true;
b.mo3588a((C0128a) bVar, (C0129b<? super Throwable>) aVar);
$jacocoInit[13] = true;
}
$jacocoInit[14] = true;
}
/* renamed from: a */
static /* synthetic */ void m8533a() {
$jacocoInit()[16] = true;
}
/* renamed from: a */
public /* synthetic */ void mo14974a(Throwable throwable) {
boolean[] $jacocoInit = $jacocoInit();
this.crashReport.log(throwable);
$jacocoInit[15] = true;
}
}
| 37.609195 | 146 | 0.599633 |
cbbe6e6b9e79bfd47c94a721495ae4605abc8b17 | 6,516 | /*
* Copyright 2016 Tsuyoshi Murakami
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tmurakami.dexopener;
import android.app.Instrumentation;
import android.content.Context;
import androidx.annotation.NonNull;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.github.tmurakami.dexopener.Constants.MY_PACKAGE_PREFIX;
/**
* This is a utility that provides the ability to mock your final classes. To use this, first add an
* AndroidJUnitRunner subclass into your app's <strong>androidTest</strong> directory.
*
* <pre><code>
* // Specify your root package as `package` statement.
* // The final classes you can mock are only in the package and its subpackages.
* package your.root.pkg;
*
* public class YourAndroidJUnitRunner extends AndroidJUnitRunner {
* @Override
* public Application newApplication(ClassLoader cl, String className, Context context)
* throws ClassNotFoundException, IllegalAccessException, InstantiationException {
* DexOpener.install(this); // Call me first!
* return super.newApplication(cl, className, context);
* }
* }
* </code></pre>
* <p>
* Then specify your AndroidJUnitRunner as the default test instrumentation runner in your app's
* build.gradle.
*
* <pre><code>
* android {
* defaultConfig {
* minSdkVersion 16 // 16 or higher
* testInstrumentationRunner 'your.root.pkg.YourAndroidJUnitRunner'
* }
* }
* </code></pre>
*/
public final class DexOpener {
private static final String[] REFUSED_PACKAGES = {
MY_PACKAGE_PREFIX,
// Android
"android.",
"androidx.",
"com.android.",
"com.google.android.",
"com.sun.",
"dalvik.",
"java.",
"javax.",
"libcore.",
"org.apache.commons.logging.",
"org.apache.harmony.",
"org.apache.http.",
"org.ccil.cowan.tagsoup.",
"org.json.",
"org.kxml2.io.",
"org.w3c.dom.",
"org.xml.sax.",
"org.xmlpull.v1.",
"sun.",
// JUnit 4
"junit.",
"org.hamcrest.",
"org.junit.",
};
private static final Executor EXECUTOR;
static {
final AtomicInteger count = new AtomicInteger();
int availableProcessors = Runtime.getRuntime().availableProcessors();
int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
EXECUTOR = Executors.newFixedThreadPool(
nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
}
private DexOpener() {
throw new AssertionError("Do not instantiate");
}
/**
* Provides the ability to mock your final classes.
*
* @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
* subclass
* @throws IllegalStateException if this method is called twice or is called in an
* inappropriate location
* @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
* to a special package such as 'android'
* @apiNote This method must be called first on the
* {@link Instrumentation#newApplication(ClassLoader, String, Context)
* newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
* subclass.
*/
public static void install(@NonNull Instrumentation instrumentation) {
Context context = instrumentation.getTargetContext();
if (context == null) {
String instrumentationName = instrumentation.getClass().getSimpleName();
throw new IllegalStateException(
"The " + instrumentationName + " instance has not yet been initialized");
}
Context app = context.getApplicationContext();
if (app != null) {
throw new IllegalStateException(
"The " + app.getClass().getSimpleName() + " instance has already been created");
}
ClassLoader loader = context.getClassLoader();
for (ClassLoader l = loader; l != null; l = l.getParent()) {
if (l instanceof ClassInjector) {
throw new IllegalStateException("Already installed");
}
}
DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
}
private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
String className = rootClass.getName();
int lastDotPos = className.lastIndexOf('.');
String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
if (isSupportedPackage(packageName)) {
Logger logger = Loggers.get();
if (logger.isLoggable(Level.FINEST)) {
logger.finest("The final classes under " + packageName + " will be opened");
}
return new DexNameFilter(packageName, rootClass);
}
throw new UnsupportedOperationException(
"Install to an Instrumentation instance the package of which is " + packageName);
}
private static boolean isSupportedPackage(String packageName) {
if (packageName == null || packageName.indexOf('.') == -1) {
return false;
}
for (String pkg : REFUSED_PACKAGES) {
if (packageName.startsWith(pkg)) {
return false;
}
}
return true;
}
}
| 37.883721 | 100 | 0.627532 |
89904f0c408967e77d0e8eff3479c8a7955b5236 | 2,954 | package net.daw.bean.implementation;
import com.google.gson.annotations.Expose;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.daw.bean.publicinterface.GenericBean;
import net.daw.helper.statics.EncodingUtilHelper;
public class UsuarioBean implements GenericBean{
@Expose
private Integer id;
@Expose
private String login = "";
@Expose
private String password = "";
@Expose
private String descripcion = "";
public UsuarioBean() {
this.id = 0;
}
public UsuarioBean(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toJson(Boolean expand) {
String strJson = "{";
strJson += "id:" + id + ",";
strJson += "login:" + EncodingUtilHelper.quotate(login) + ",";
strJson += "password:" + EncodingUtilHelper.quotate(password) + ",";
strJson += "descripcion:" + EncodingUtilHelper.quotate(descripcion) + ",";
strJson += "}";
return strJson;
}
public String getColumns() {
String strColumns = "";
strColumns += "id,";
strColumns += "login,";
strColumns += "password,";
strColumns += "descripcion";
return strColumns;
}
@Override
public String getValues() {
String strColumns = "";
strColumns += EncodingUtilHelper.quotate(login)+ ",";
strColumns += EncodingUtilHelper.quotate(password) + ",";
strColumns += EncodingUtilHelper.quotate(descripcion) + ",";
strColumns += descripcion;
return strColumns;
}
@Override
public String toPairs() {
String strPairs = "";
strPairs += "id=" + id + ",";
strPairs += "login=" + EncodingUtilHelper.quotate(login) + ",";
strPairs += "password=" + EncodingUtilHelper.quotate(password) + ",";
strPairs += "descripcion=" + EncodingUtilHelper.quotate(descripcion);
return strPairs;
}
@Override
public UsuarioBean fill(ResultSet oResultSet, Connection pooledConnection, Integer expand) throws SQLException, Exception {
this.setId(oResultSet.getInt("id"));
this.setLogin(oResultSet.getString("login"));
this.setPassword(oResultSet.getString("password"));
this.setDescripcion(oResultSet.getString("descripcion"));
return this;
}
}
| 25.465517 | 127 | 0.609682 |
da018449f44075c39f96731df716dfd1bc9ef470 | 10,681 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Callable
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|ExecutorService
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Executors
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileSystem
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|LocatedFileStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|RemoteIterator
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|DistributedFileSystem
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|FileMetadataExprType
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|MetaException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|conf
operator|.
name|MetastoreConf
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|utils
operator|.
name|HdfsUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|Lists
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|util
operator|.
name|concurrent
operator|.
name|ThreadFactoryBuilder
import|;
end_import
begin_class
specifier|public
class|class
name|FileMetadataManager
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|FileMetadataManager
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
specifier|final
name|RawStore
name|tlms
decl_stmt|;
specifier|private
specifier|final
name|ExecutorService
name|threadPool
decl_stmt|;
specifier|private
specifier|final
name|Configuration
name|conf
decl_stmt|;
specifier|private
specifier|final
class|class
name|CacheUpdateRequest
implements|implements
name|Callable
argument_list|<
name|Void
argument_list|>
block|{
name|FileMetadataExprType
name|type
decl_stmt|;
name|String
name|location
decl_stmt|;
specifier|public
name|CacheUpdateRequest
parameter_list|(
name|FileMetadataExprType
name|type
parameter_list|,
name|String
name|location
parameter_list|)
block|{
name|this
operator|.
name|type
operator|=
name|type
expr_stmt|;
name|this
operator|.
name|location
operator|=
name|location
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|Void
name|call
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|cacheMetadata
argument_list|(
name|type
argument_list|,
name|location
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|InterruptedException
name|ex
parameter_list|)
block|{
name|Thread
operator|.
name|currentThread
argument_list|()
operator|.
name|interrupt
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
comment|// Nobody can see this exception on the threadpool; just log it.
name|LOG
operator|.
name|error
argument_list|(
literal|"Failed to cache file metadata in background for "
operator|+
name|type
operator|+
literal|", "
operator|+
name|location
argument_list|,
name|ex
argument_list|)
expr_stmt|;
block|}
return|return
literal|null
return|;
block|}
block|}
specifier|public
name|FileMetadataManager
parameter_list|(
name|RawStore
name|tlms
parameter_list|,
name|Configuration
name|conf
parameter_list|)
block|{
name|this
operator|.
name|tlms
operator|=
name|tlms
expr_stmt|;
name|this
operator|.
name|conf
operator|=
name|conf
expr_stmt|;
name|int
name|numThreads
init|=
name|MetastoreConf
operator|.
name|getIntVar
argument_list|(
name|conf
argument_list|,
name|MetastoreConf
operator|.
name|ConfVars
operator|.
name|FILE_METADATA_THREADS
argument_list|)
decl_stmt|;
name|this
operator|.
name|threadPool
operator|=
name|Executors
operator|.
name|newFixedThreadPool
argument_list|(
name|numThreads
argument_list|,
operator|new
name|ThreadFactoryBuilder
argument_list|()
operator|.
name|setNameFormat
argument_list|(
literal|"File-Metadata-%d"
argument_list|)
operator|.
name|setDaemon
argument_list|(
literal|true
argument_list|)
operator|.
name|build
argument_list|()
argument_list|)
expr_stmt|;
block|}
specifier|public
name|void
name|queueCacheMetadata
parameter_list|(
name|String
name|location
parameter_list|,
name|FileMetadataExprType
name|type
parameter_list|)
block|{
name|threadPool
operator|.
name|submit
argument_list|(
operator|new
name|CacheUpdateRequest
argument_list|(
name|type
argument_list|,
name|location
argument_list|)
argument_list|)
expr_stmt|;
block|}
specifier|private
name|void
name|cacheMetadata
parameter_list|(
name|FileMetadataExprType
name|type
parameter_list|,
name|String
name|location
parameter_list|)
throws|throws
name|MetaException
throws|,
name|IOException
throws|,
name|InterruptedException
block|{
name|Path
name|path
init|=
operator|new
name|Path
argument_list|(
name|location
argument_list|)
decl_stmt|;
name|FileSystem
name|fs
init|=
name|path
operator|.
name|getFileSystem
argument_list|(
name|conf
argument_list|)
decl_stmt|;
name|List
argument_list|<
name|Path
argument_list|>
name|files
decl_stmt|;
if|if
condition|(
operator|!
name|fs
operator|.
name|isDirectory
argument_list|(
name|path
argument_list|)
condition|)
block|{
name|files
operator|=
name|Lists
operator|.
name|newArrayList
argument_list|(
name|path
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|files
operator|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
expr_stmt|;
name|RemoteIterator
argument_list|<
name|LocatedFileStatus
argument_list|>
name|iter
init|=
name|fs
operator|.
name|listFiles
argument_list|(
name|path
argument_list|,
literal|true
argument_list|)
decl_stmt|;
while|while
condition|(
name|iter
operator|.
name|hasNext
argument_list|()
condition|)
block|{
comment|// TODO: use fileId right from the list after HDFS-7878; or get dfs client and do it
name|LocatedFileStatus
name|lfs
init|=
name|iter
operator|.
name|next
argument_list|()
decl_stmt|;
if|if
condition|(
name|lfs
operator|.
name|isDirectory
argument_list|()
condition|)
continue|continue;
name|files
operator|.
name|add
argument_list|(
name|lfs
operator|.
name|getPath
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
for|for
control|(
name|Path
name|file
range|:
name|files
control|)
block|{
name|long
name|fileId
decl_stmt|;
comment|// TODO: use the other HdfsUtils here
if|if
condition|(
operator|!
operator|(
name|fs
operator|instanceof
name|DistributedFileSystem
operator|)
condition|)
return|return;
try|try
block|{
name|fileId
operator|=
name|HdfsUtils
operator|.
name|getFileId
argument_list|(
name|fs
argument_list|,
name|Path
operator|.
name|getPathWithoutSchemeAndAuthority
argument_list|(
name|file
argument_list|)
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|UnsupportedOperationException
name|ex
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Cannot cache file metadata for "
operator|+
name|location
operator|+
literal|"; "
operator|+
name|fs
operator|.
name|getClass
argument_list|()
operator|.
name|getCanonicalName
argument_list|()
operator|+
literal|" does not support fileId"
argument_list|)
expr_stmt|;
return|return;
block|}
name|LOG
operator|.
name|info
argument_list|(
literal|"Caching file metadata for "
operator|+
name|file
operator|+
literal|" (file ID "
operator|+
name|fileId
operator|+
literal|")"
argument_list|)
expr_stmt|;
name|file
operator|=
name|HdfsUtils
operator|.
name|getFileIdPath
argument_list|(
name|fs
argument_list|,
name|file
argument_list|,
name|fileId
argument_list|)
expr_stmt|;
name|tlms
operator|.
name|getFileMetadataHandler
argument_list|(
name|type
argument_list|)
operator|.
name|cacheFileMetadata
argument_list|(
name|fileId
argument_list|,
name|fs
argument_list|,
name|file
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 13.907552 | 813 | 0.801329 |
15f8a59946da5a18e872ccd03d54d04c79ec6831 | 848 | package com.dotcms.rest.validation.constraints;
import com.dotcms.repackage.javax.validation.Constraint;
import com.dotcms.repackage.javax.validation.Payload;
import com.dotcms.rest.validation.FireOnValidator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
validatedBy = {FireOnValidator.class}
)
public @interface FireOn {
String message() default "{javax.validation.constraints.FireOn.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| 31.407407 | 125 | 0.791274 |
54d33b061a03d369d7b696448e2ed0716aa1c721 | 3,327 | package com.google.android.gms.ads;
import android.content.Context;
import com.google.android.gms.ads.internal.client.AdSizeParcel;
import com.google.android.gms.ads.internal.client.zzl;
import com.google.android.gms.nearby.messages.Strategy;
public final class AdSize {
public static final int AUTO_HEIGHT = -2;
public static final AdSize BANNER = new AdSize(320, 50, "320x50_mb");
public static final AdSize FLUID = new AdSize(-3, -4, "fluid");
public static final AdSize FULL_BANNER = new AdSize(468, 60, "468x60_as");
public static final int FULL_WIDTH = -1;
public static final AdSize LARGE_BANNER = new AdSize(320, 100, "320x100_as");
public static final AdSize LEADERBOARD = new AdSize(728, 90, "728x90_as");
public static final AdSize MEDIUM_RECTANGLE = new AdSize(Strategy.TTL_SECONDS_DEFAULT, 250, "300x250_as");
public static final AdSize SMART_BANNER = new AdSize(-1, -2, "smart_banner");
public static final AdSize WIDE_SKYSCRAPER = new AdSize(160, 600, "160x600_as");
private final int zzov;
private final int zzow;
private final String zzox;
public AdSize(int width, int height) {
this(width, height, (width == -1 ? "FULL" : String.valueOf(width)) + "x" + (height == -2 ? "AUTO" : String.valueOf(height)) + "_as");
}
AdSize(int width, int height, String formatString) {
if (width < 0 && width != -1 && width != -3) {
throw new IllegalArgumentException("Invalid width for AdSize: " + width);
} else if (height >= 0 || height == -2 || height == -4) {
this.zzov = width;
this.zzow = height;
this.zzox = formatString;
} else {
throw new IllegalArgumentException("Invalid height for AdSize: " + height);
}
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof AdSize)) {
return false;
}
AdSize adSize = (AdSize) other;
return this.zzov == adSize.zzov && this.zzow == adSize.zzow && this.zzox.equals(adSize.zzox);
}
public int getHeight() {
return this.zzow;
}
public int getHeightInPixels(Context context) {
switch (this.zzow) {
case -4:
case -3:
return -1;
case -2:
return AdSizeParcel.zzb(context.getResources().getDisplayMetrics());
default:
return zzl.zzcN().zzb(context, this.zzow);
}
}
public int getWidth() {
return this.zzov;
}
public int getWidthInPixels(Context context) {
switch (this.zzov) {
case -4:
case -3:
return -1;
case -1:
return AdSizeParcel.zza(context.getResources().getDisplayMetrics());
default:
return zzl.zzcN().zzb(context, this.zzov);
}
}
public int hashCode() {
return this.zzox.hashCode();
}
public boolean isAutoHeight() {
return this.zzow == -2;
}
public boolean isFluid() {
return this.zzov == -3 && this.zzow == -4;
}
public boolean isFullWidth() {
return this.zzov == -1;
}
public String toString() {
return this.zzox;
}
}
| 32.617647 | 141 | 0.590021 |
1ceae9f5796a7cba5bc6c96998394bd83a12e8ae | 1,571 | package org.niko.timertracker.workdayslistactivity.ClickListener;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import androidx.appcompat.widget.AppCompatButton;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.niko.timertracker.workdayslistactivity.Persistence.FirebaseService;
import org.niko.workdayslistactivity.timertracker.R;
public class AddWorkIntervalClickListener implements View.OnClickListener {
private Long workdayId;
private Context context;
private boolean isStartTime;
public AddWorkIntervalClickListener(Long workdayId, boolean isStartTime, Context context) {
this.workdayId = workdayId;
this.context = context;
this.isStartTime = isStartTime;
}
@Override
public void onClick(View v) {
Intent intent = new Intent("add.workInterval.listAdapter_243985sadnfoiu2");
intent.putExtra("workdayId", this.workdayId);
intent.putExtra("isStartTime", this.isStartTime);
AppCompatButton appCompatButton = v.findViewById(R.id.addWorkIntervalButton);
if (FirebaseService.isIsWorkIntervalRunning()) {
appCompatButton.setBackgroundResource(R.drawable.ic_playicon);
FirebaseService.setIsWorkIntervalRunning(false);
}
else {
appCompatButton.setBackgroundResource(R.drawable.ic_stopicon);
FirebaseService.setIsWorkIntervalRunning(true);
}
LocalBroadcastManager.getInstance(this.context).sendBroadcast(intent);
}
}
| 35.704545 | 95 | 0.749204 |
648e07561f8a04af17196c23b85c0e1fc0ab2038 | 2,097 | package com.epam.spring.web.mvc.rentcarservice.api;
import com.epam.spring.web.mvc.rentcarservice.controller.model.CarModel;
import com.epam.spring.web.mvc.rentcarservice.dto.CarDto;
import io.swagger.annotations.Api;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@Api(tags = "Car management API")
@RequestMapping("/api/v1/cars")
public interface CarApi {
@ResponseStatus(HttpStatus.OK)
@GetMapping
List<CarModel> getAvailableCars();
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/{carNumber}")
CarModel getCar(@PathVariable String carNumber);
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
CarModel createCar(@Valid @RequestBody CarDto carDto);
@ResponseStatus(HttpStatus.OK)
@PutMapping(value = "/{carNumber}")
CarModel updateCar(@PathVariable String carNumber, @RequestBody CarDto carDto);
@DeleteMapping(value = "/{carNumber}")
ResponseEntity<Void> deleteCar(@PathVariable String carNumber);
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/filter/brand={brand}")
List<CarModel> findCarsByBrand(@PathVariable String brand,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size);
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/filter/car_class={carClass}")
List<CarModel> findCarsByCarClass(@PathVariable String carClass,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size);
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/sort/price")
List<CarModel> sortCarsByPrice(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size);
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/sort/name")
List<CarModel> sortCarsByName();
}
| 37.446429 | 83 | 0.679542 |
8b420a2817037388e05b53f5114c7ee5ade725b8 | 1,218 | /*
* Id: EventDetailsDto.java 03-Mar-2022 2:56:20 pm SubhajoyLaskar
* Copyright (©) 2022 Subhajoy Laskar
* https://www.linkedin.com/in/subhajoylaskar
*/
package com.xyz.apps.ticketeer.eventvenue.api.external.contract;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* The event details dto.
*
* @author Subhajoy Laskar
* @version 1.0
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventDetailsDto {
/** The event id. */
private Long eventId;
/** The name. */
private String name;
/** The description. */
private String description;
/** The event type. */
private String eventType;
/** The language. */
private String language;
/** The duration. */
private Long durationInMinutes;
/** The release date. */
private String releaseDate;
/** The genre. */
private String genre;
/** The movie director name. */
private String movieDirectorName;
/** The movie cast names. */
private List<String> movieCastNames;
/** The country name. */
private String countryName;
}
| 19.333333 | 64 | 0.674877 |
f52de282eb9bac118b70da416bc62f72a682fe8a | 1,053 | package com.jz.xd.mapper;
import com.jz.xd.model.TbRUGetanotherBackLog;
import com.jz.xd.model.TbRUGetanotherBackLogExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TbRUGetanotherBackLogMapper {
int countByExample(TbRUGetanotherBackLogExample example);
int deleteByExample(TbRUGetanotherBackLogExample example);
int deleteByPrimaryKey(Integer id);
int insert(TbRUGetanotherBackLog record);
int insertSelective(TbRUGetanotherBackLog record);
List<TbRUGetanotherBackLog> selectByExample(TbRUGetanotherBackLogExample example);
TbRUGetanotherBackLog selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") TbRUGetanotherBackLog record, @Param("example") TbRUGetanotherBackLogExample example);
int updateByExample(@Param("record") TbRUGetanotherBackLog record, @Param("example") TbRUGetanotherBackLogExample example);
int updateByPrimaryKeySelective(TbRUGetanotherBackLog record);
int updateByPrimaryKey(TbRUGetanotherBackLog record);
} | 35.1 | 136 | 0.817664 |
742442b8f38f99fd50a0ff12ff3ac8051291748a | 4,577 | package de.kreth.clubhelperbackend.config;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class ClubhelperAuthenticationProvider
implements
AuthenticationProvider,
UserDetailsService {
private final Logger log = LoggerFactory
.getLogger(ClubhelperAuthenticationProvider.class);
private final DataSource dataSource;
public ClubhelperAuthenticationProvider(DataSource dataSource)
throws SQLException {
this.dataSource = dataSource;
}
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
log.debug("Searching Login for name=\"" + name + "\"");
try {
List<GrantedAuthority> grantedAuths = getRoles(name, password);
if (grantedAuths.isEmpty()) {
log.warn("No valid login group found for \"" + name + "\"");
return null;
} else {
Authentication auth = new UsernamePasswordAuthenticationToken(
name, password, grantedAuths);
log.info("Login groups found for \"" + name + "\": "
+ grantedAuths);
return auth;
}
} catch (SQLException e) {
log.error("Sql error on authentication", e);
throw new AuthenticationCredentialsNotFoundException(
"Sql error on authentication", e);
}
}
private List<GrantedAuthority> getRoles(String name, String password)
throws SQLException {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
try (Connection connection = dataSource.getConnection()) {
PreparedStatement stmGroups = connection.prepareStatement(
"select groupDef.name groupname from person \n"
+ " left join persongroup on persongroup.person_id = person.id\n"
+ " left join groupDef on persongroup.group_id = groupDef.id\n"
+ " where person.username = ? and person.password = ?");
stmGroups.setString(1, name);
stmGroups.setString(2, password);
ResultSet rs = stmGroups.executeQuery();
while (rs.next()) {
grantedAuths.add(createAuthority(rs.getString("groupname")));
}
}
return grantedAuths;
}
private GrantedAuthority createAuthority(String roleName) {
return new SimpleGrantedAuthority("ROLE_" + roleName.toUpperCase());
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
log.debug("getting Userdetails for username " + username);
PreparedStatement stmUser = null;
try (Connection connection = dataSource.getConnection()) {
stmUser = connection.prepareStatement(
"select person.password password, groupDef.name groupname from person \n"
+ " left join persongroup on persongroup.person_id = person.id\n"
+ " left join groupDef on persongroup.group_id = groupDef.id\n"
+ " where person.username = ?");
stmUser.setString(1, username);
ResultSet rs = stmUser.executeQuery();
List<GrantedAuthority> grantedAuths = new ArrayList<>();
String password = null;
while (rs.next()) {
grantedAuths.add(createAuthority(rs.getString("groupname")));
password = rs.getString("password");
}
if (password == null) {
throw new UsernameNotFoundException(
"No user found matching " + username);
} else {
return new User(username, password, grantedAuths);
}
} catch (SQLException e) {
throw new UsernameNotFoundException("error executing " + stmUser,
e);
}
}
}
| 32.692857 | 94 | 0.753113 |
2084439f709a8a036ffd9aa6117c40cd305cdb4a | 1,451 | package net.xkor.ahlib;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public abstract class BaseAHFragment extends Fragment {
private BaseUiObjectHelper helper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getHelper().onCreate(savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getHelper().onSaveInstanceState(outState);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return getHelper().onCreateView(inflater, container);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getHelper().onViewCreated(view);
}
@Override
public void onDestroyView() {
super.onDestroyView();
getHelper().onDestroyView();
}
protected BaseUiObjectHelper getHelper() {
if (helper == null) {
helper = createHelper();
}
return helper;
}
protected BaseUiObjectHelper createHelper() {
return new BaseUiObjectHelper(this);
}
}
| 26.87037 | 123 | 0.698139 |
0b430b40cf588d792dde4448952bf1212c36da51 | 5,656 | /*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: trust@f4-i.fh-hannover.de
* Website: http://trust.f4.hs-hannover.de/
*
* This file is part of ifmapj, version 2.3.2, implemented by the Trust@HsH
* research group at the Hochschule Hannover.
* %%
* Copyright (C) 2010 - 2016 Trust@HsH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package de.hshannover.f4.trust.ifmapj.identifier;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import javax.xml.parsers.DocumentBuilder;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import util.DomHelpers;
import de.hshannover.f4.trust.ifmapj.exception.MarshalException;
import de.hshannover.f4.trust.ifmapj.exception.UnmarshalException;
public class DeviceHandlerTest {
private static DocumentBuilder sDocBuilder = DomHelpers.newDocumentBuilder();
private static DeviceHandler sDevHandler = new DeviceHandler();
@Test(expected = MarshalException.class)
public void testToElementWithNullName() throws MarshalException {
Document doc = sDocBuilder.newDocument();
Device dev = Identifiers.createDev(null);
Element res = sDevHandler.toElement(dev, doc);
assertNotNull(res);
}
@Test(expected = MarshalException.class)
public void testToElementWithEmptyName() throws MarshalException {
Document doc = sDocBuilder.newDocument();
Device dev = Identifiers.createDev("");
Element res = sDevHandler.toElement(dev, doc);
assertNotNull(res);
}
@Test
public void testToElementWithName() throws MarshalException {
Document doc = sDocBuilder.newDocument();
Device dev = Identifiers.createDev("DEV100");
Element xmlName = null;
Element res = sDevHandler.toElement(dev, doc);
assertNotNull(res);
assertEquals("device", res.getLocalName());
assertNull(res.getPrefix());
assertNull(res.getNamespaceURI());
assertEquals(1, res.getChildNodes().getLength());
xmlName = (Element) res.getFirstChild();
assertNotNull(xmlName);
assertEquals("name", xmlName.getLocalName());
assertEquals("DEV100", xmlName.getTextContent());
assertNull(res.getAttributeNode("administrative-domain"));
assertEquals(1, res.getChildNodes().getLength());
assertEquals(0, res.getAttributes().getLength());
assertEquals(1, xmlName.getChildNodes().getLength());
assertEquals(0, xmlName.getAttributes().getLength());
assertEquals(Node.TEXT_NODE, xmlName.getFirstChild().getNodeType());
}
@Test
public void testFromElementWithName() throws UnmarshalException {
Document doc = sDocBuilder.newDocument();
Element xmlDev = doc.createElementNS(null, "device");
Element xmlName = doc.createElementNS(null, "name");
xmlDev.appendChild(xmlName);
xmlName.setTextContent("DEV100");
Device dev = sDevHandler.fromElement(xmlDev);
assertNotNull(dev);
assertNotNull(dev.getName());
assertEquals("DEV100", dev.getName());
}
@Test(expected = UnmarshalException.class)
public void testFromElementWithNoName() throws UnmarshalException {
Document doc = sDocBuilder.newDocument();
Element xmlDev = doc.createElementNS(null, "device");
Device dev = sDevHandler.fromElement(xmlDev);
assertNull(dev);
}
@Test(expected = UnmarshalException.class)
public void testFromElementWithEmptyName() throws UnmarshalException {
Document doc = sDocBuilder.newDocument();
Element xmlDev = doc.createElementNS(null, "device");
Element xmlName = doc.createElementNS(null, "name");
xmlName.setTextContent("");
xmlDev.appendChild(xmlName);
Device dev = sDevHandler.fromElement(xmlDev);
assertNull(dev);
}
@Test(expected = UnmarshalException.class)
public void testFromElementWithBadElement() throws UnmarshalException {
Document doc = sDocBuilder.newDocument();
Element xmlDev = doc.createElementNS(null, "device");
Element xmlName = doc.createElementNS(null, "bad_name_element");
xmlDev.appendChild(xmlName);
Device dev = sDevHandler.fromElement(xmlDev);
assertNull(dev);
}
@Test
public void testNotResponsible() throws UnmarshalException {
Document doc = sDocBuilder.newDocument();
Element xmlAr = doc.createElementNS(null, "ip-address");
Device dev = sDevHandler.fromElement(xmlAr);
assertNull(dev);
}
@Test(expected = MarshalException.class)
public void testToElementWrongIdentifierType() throws UnmarshalException, MarshalException {
Document doc = sDocBuilder.newDocument();
Element ret = sDevHandler.toElement(Identifiers.createAr("ABC"), doc);
assertNull(ret);
}
}
| 34.699387 | 93 | 0.710396 |
27f8707a6b27fbe6f960ce346103f00a09a6d348 | 643 | package me.sixteen_.insane.command.commands;
import me.sixteen_.insane.command.Command;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
/**
* @author 16_
*/
@Environment(value = EnvType.CLIENT)
public class Config extends Command {
public Config() {
super(Config.class.getSimpleName());
}
@Override
public String syntax() {
return String.format(".%s <load|save>", getName());
}
@Override
public void run(String... param) {
if (param[1].equals("load")) {
getInsane().getConfig().load();
} else if (param[1].equals("save")) {
getInsane().getConfig().save();
}
}
} | 21.433333 | 54 | 0.650078 |
a83c9ad571a15cbdc7431c0619ba488100ab495b | 686 | package org.zalando.zmon.security;
import org.springframework.social.connect.Connection;
/**
*
* @author jbellmann
*
*/
public abstract class AbstractSignupCondition<T> implements SignupCondition<T> {
private Class<T> clazz;
public AbstractSignupCondition(Class<T> clazz) {
this.clazz = clazz;
}
public boolean matches(Connection<?> connection) {
return matches(getApi(connection));
}
public abstract boolean matches(T api);
@Override
public boolean supportsConnection(Connection<?> connection) {
return clazz.isAssignableFrom(connection.getApi().getClass());
}
protected T getApi(Connection<?> connection) {
return clazz.cast(connection.getApi());
}
}
| 20.176471 | 80 | 0.74344 |
b6d9eccc4e8c17a49e2155048a3336700ba42385 | 13,566 | /*******************************************************************************
* Copyright (c) 2020
* AG Embedded Systems, University of Münster
* SESE Software and Embedded Systems Engineering, TU Berlin
*
* Authors:
* Paula Herber
* Sabine Glesner
* Timm Liebrenz
*
* 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 simulink2dl.dlmodel.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.List;
import simulink2dl.dlmodel.DLModel;
import simulink2dl.dlmodel.DLModelDefaultStructure;
import simulink2dl.dlmodel.elements.Constant;
import simulink2dl.dlmodel.elements.Variable;
import simulink2dl.dlmodel.hybridprogram.ContinuousEvolution;
import simulink2dl.dlmodel.hybridprogram.DebugString;
import simulink2dl.dlmodel.hybridprogram.DiscreteAssignment;
import simulink2dl.dlmodel.hybridprogram.HybridProgram;
import simulink2dl.dlmodel.hybridprogram.HybridProgramCollection;
import simulink2dl.dlmodel.hybridprogram.NondeterministicAssignment;
import simulink2dl.dlmodel.hybridprogram.NondeterministicChoice;
import simulink2dl.dlmodel.hybridprogram.NondeterministicRepetition;
import simulink2dl.dlmodel.hybridprogram.TestFormula;
import simulink2dl.dlmodel.operator.Operator;
import simulink2dl.dlmodel.operator.formula.Formula;
import simulink2dl.dlmodel.term.Term;
/**
* Parser for plain text kyx files.
*
* @author nick
*
*/
public class KYXParser {
/**
* List that contains all functions of the system, which do not change their
* value
*/
private List<Constant> constants = new LinkedList<Constant>();
/**
* List that contains all variables of the system
*/
private List<Variable> variables = new LinkedList<Variable>();
/**
* Problem that contains the system behavior
*/
private Operator problem;
private DLModelDefaultStructure defStruct;
private DLModel dlmodel;
private FormulaParser formulaParser;
/**
* Creates new parser from an uncompressed kyx file.
*
* @param kyxFile
*/
public KYXParser(FileReader kyxFile) {
StringBuilder strb = new StringBuilder();
try (BufferedReader br = new BufferedReader(kyxFile)) {
String line = br.readLine();
while (line != null) {
// remove comments, cut leading/trailing whitespace
line = line.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)", "");
line = line.trim();
if (!line.isEmpty()) {
strb.append(line);
}
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
for (String section : strb.toString().split("End.")) {
String[] lines = section.split("\\.");
switch (lines[0]) {
case "Functions":
for (int i = 1; i < lines.length; i++) {
this.constants.add(AtomicTermParser.parseToConstant(lines[i]));
}
break;
case "ProgramVariables":
for (int i = 1; i < lines.length; i++) {
this.variables.add(AtomicTermParser.parseToVariable(lines[i]));
}
break;
case "Problem":
this.formulaParser = new FormulaParser(this);
this.parseProblem(section.replaceFirst("Problem.", "").replaceAll(" ", ""));
break;
default:
System.out.println("[ERR] Unexpected case found, while trying to evaluate sections. \n " + lines[0]);
break;
}
}
}
private Operator parseProblem(String problemString) {
String[] problem = problemString.split("->\\[");
if (problem.length == 2) { // DLModelDefaultStructure
// initial condition -> [behavior]true
this.defStruct = new DLModelDefaultStructure();
this.defStruct.setConstants(this.constants);
this.defStruct.setVariables(this.variables);
Formula initCondFormula = this.formulaParser.parse(problem[0]);
this.defStruct.addInitialCondition(initCondFormula);
int closingBracket = problem[1].lastIndexOf(']');
String programInsideBox = problem[1].substring(0, closingBracket);
// String postCondition = problem[1].substring(closingBracket + 1);
// Formula postConditionFormula = this.formulaParser.parse(postCondition);
// TODO is postCondition ever used?
NondeterministicRepetition loop = parseNondeterministicRepetition(programInsideBox);
this.defStruct.addBehavior(loop.getInnerProgram());
this.defStruct.getLoop().setInvariant(loop.getInvariant());
} else { // DLModel
// TODO
// this.dlmodel = new DLModel();
}
return null;
}
private NondeterministicRepetition parseNondeterministicRepetition(String repetitionString) {
int i = repetitionString.lastIndexOf("*@invariant");
if (i > 0) {
assert closingBracket(repetitionString, 0) == i - 1;
String wrappedRepitition = repetitionString.substring(0, i);
HybridProgram repitition = this.parseInnerProgram(unwrap(wrappedRepitition));
String wrappedInvariant = repetitionString.substring(i + "*@invariant".length());
Formula invariantForm = this.formulaParser.parse(wrappedInvariant);
return new NondeterministicRepetition(repitition, invariantForm);
}
int end = closingBracket(repetitionString, 0);
assert (repetitionString.charAt(end + 1) == '*' && repetitionString.length() == end + 1);
return (NondeterministicRepetition) this.parseInnerProgram(repetitionString);
}
private HybridProgram parseInnerProgram(String programString) {
// anchors
if (!programString.startsWith("{")) {
return this.parseNonNestedProgram(programString);
}
int end = closingBracket(programString, 0);
if (end + 1 == programString.length()) {
// call parseInnerProgram on unwrapped content, if corresponding '}' is
// the last character
return this.parseInnerProgram(unwrap(programString));
}
if (programString.charAt(end + 1) == '*' && programString.length() == end + 1) {
return new NondeterministicRepetition(new DebugString(unwrap(programString)));
}
// recursion
HybridProgramCollection coll = new HybridProgramCollection();
int start = 0;
while (end != -1) {
String subProgStr = programString.substring(start + 1, end);
coll.addElement(this.parseInnerProgram(subProgStr));
if (end + 1 < programString.length()) {
start = end + 1;
end = closingBracket(programString, start);
} else {
end = -1;
}
}
return coll;
}
private HybridProgram parseNonNestedProgram(String str) {
assert str.indexOf('{') == -1;
assert str.indexOf('}') == -1;
// HybridProgram simple = this.parseNonNestedProgram(str.substring(0,
// start));
// HybridProgram complex = this.parseInnerProgram(str.substring(start));
// return new HybridProgramCollection(simple, complex);
if (str.contains("++")) {
return this.parseNonNestedNondeterministicChoice(str);
}
return this.parseNonNestedSequence(str);
}
private HybridProgram parseNonNestedNondeterministicChoice(String prog) {
NondeterministicChoice chzr = new NondeterministicChoice();
for (String str : prog.split("\\+\\+")) {
chzr.addChoice(this.parseNonNestedSequence(str));
}
return chzr;
}
private HybridProgram parseNonNestedSequence(String program) {
String[] splits = program.split(";");
if (splits.length == 1) {
return this.parsePrimitive(splits[0]);
}
HybridProgramCollection coll = new HybridProgramCollection();
for (String str : splits) {
coll.addElement(this.parsePrimitive(str));
}
return coll;
}
private HybridProgram parsePrimitive(String program) {
if (program.contains(":=")) {
return this.parsePrimitiveAssignment(program);
}
if (program.startsWith("?")) {
return this.parsePrimitiveTestFormula(program);
}
return this.parsePrimitiveEvolution(program);
}
private static String unwrap(String str) {
return unwrap(str, 0);
}
/**
* Starts from the curly opening bracket at the given position, finds the
* corresponding closing bracket and returns everything inbetween.
*
* @param str
* @param start
* @return
*/
private static String unwrap(String str, int start) {
int end = closingBracket(str, start);
if (end == -1) {
return "";
}
return str.substring(start + 1, end);
}
/**
* Starts from the curly opening bracket at the given position, finds the
* corresponding closing bracket and returns its position.
*
* @param str
* @param start
* @return
*/
static int closingBracket(String str, int start) {
if (str.length() < 2 || str.length() <= start) {
System.out.println("[ERR] Malformed string: " + str + "\n Finding } at " + start + " impossible!");
return Integer.MIN_VALUE;
}
if (str.charAt(start) != '{') {
return -1;
}
int braceStatus = 1;
for (int i = start + 1; i < str.length(); i++) {
if (str.charAt(i) == '{') {
braceStatus++;
} else if (str.charAt(i) == '}') {
braceStatus--;
}
if (braceStatus == 0) {
return i;
}
}
System.out.println("[ERR] String: " + str + "\n Contains an opening, but no closing bracket!");
return Integer.MIN_VALUE;
}
/**
* Parses a string representation of a assignment (nondeterministic as well as
* discrete). Take note: No additional checks or transformations are applied.
* (primitive statement 1|2)
*
* @param assignment
* @return
*/
private HybridProgram parsePrimitiveAssignment(String assignment) {
String[] varTerm = assignment.split(":=");
assert varTerm.length == 2;
String valStr = varTerm[1].replaceFirst(";", "");
if (valStr.equals("*")) {
return new NondeterministicAssignment(this.getVariableByName(varTerm[0]));
}
return new DiscreteAssignment(this.getVariableByName(varTerm[0]), this.formulaParser.parseTerm(valStr));
}
/**
* Parses a string representation of a continuous evolution. Take note: No
* additional checks or transformations are applied. (primitive statement 3)
*
* @param prog
* @return
*/
private ContinuousEvolution parsePrimitiveEvolution(String prog) {
String[] evoDom = prog.split("&", 2);
ContinuousEvolution evo = new ContinuousEvolution(this.formulaParser.parse(evoDom[1]));
for (String singleEvo : evoDom[0].split(",")) {
String[] varVal = singleEvo.split("'=");
Variable var = getVariableByName(varVal[0]);
Term val = getTermByName(varVal[1]);
if (val == null) {
evo.addSingleEvolution(var, this.formulaParser.parseTerm(varVal[1]));
} else {
evo.addSingleEvolution(var, val);
}
}
return evo;
}
/**
* Parses a string representation of a test formula. Take note: No additional
* checks or transformations are applied. (primitive statement 4)
*
* @param formula
* @return
*/
private HybridProgram parsePrimitiveTestFormula(String formula) {
if (formula.startsWith("?")) {
formula = formula.replaceFirst("\\?", "");
}
return new TestFormula(this.formulaParser.parse(formula));
}
@SuppressWarnings("unused")
private HybridProgram parseIfStatement(String ifstate) {
return null; // TODO implement
}
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("G:\\keymaerax\\09-ping-pong.kyx");
} catch (Exception e) {
e.printStackTrace();
}
KYXParser parser = new KYXParser(fr);
if (parser.defStruct != null) {
System.out.println("[MAIN] out:\n" + parser.defStruct.createOutputString(true, true));
}
if (parser.dlmodel != null) {
System.out.println("[MAIN] out:\n" + parser.dlmodel.createOutputString(true, true));
}
}
/**
* @return the constants
*/
public List<Constant> getConstants() {
return constants;
}
/**
* @return the variables
*/
public List<Variable> getVariables() {
return variables;
}
/**
* @return the problem
*/
public Operator getProblem() {
return problem;
}
/**
* Returns the constant with the given name or null if no such constant exists.
*
* @param toSearch
*/
Constant getConstantByName(String toSearch) {
for (Constant constant : constants) {
if (constant.getName().equals(toSearch)) {
return constant;
}
}
return null;
}
/**
* Returns the variable with the given name or null if no such variable exists.
*
* @param toSearch
*/
Variable getVariableByName(String toSearch) {
for (Variable variable : variables) {
if (variable.getName().equals(toSearch)) {
return variable;
}
}
return null;
}
/**
* Returns a constant with the given name, a variable with the given name or
* null, iff neither exit.
*
* @param toSearch
* @return
*/
Term getTermByName(String toSearch) {
Constant con = getConstantByName(toSearch);
if (con == null) {
return getVariableByName(toSearch);
}
return con;
}
}
| 30.41704 | 106 | 0.694752 |
27ec3649c1958583f6592128830ad0944eba6d7c | 210 | package exame1_14_15.scoreService;
/**
* Created by Ruben Gomes on 19/07/2015.
*/
public class Team {
final String clubName;
public Team(String clubName){
this.clubName = clubName;
}
}
| 15 | 40 | 0.657143 |
cfb95c5fdc950c0c5ea75d1e5bef3ee73ee9624a | 15,958 | /**
*
*/
package dz.minagri.stat.services;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.vaadin.ui.renderers.LocalDateRenderer;
import dz.minagri.stat.enumeration.Availability;
import dz.minagri.stat.enumeration.Gender;
import dz.minagri.stat.enumeration.TypeCommune;
import dz.minagri.stat.enumeration.TypeDepartement;
import dz.minagri.stat.enumeration.TypeExploitation;
import dz.minagri.stat.enumeration.TypePersonne;
import dz.minagri.stat.model.Account;
import dz.minagri.stat.model.Adresse;
import dz.minagri.stat.model.CarteFellah;
import dz.minagri.stat.model.Category;
import dz.minagri.stat.model.Commune;
import dz.minagri.stat.model.Departement;
import dz.minagri.stat.model.EspeceCultivee;
import dz.minagri.stat.model.Exploitant;
import dz.minagri.stat.model.Exploitant.ExploitantStatus;
import dz.minagri.stat.model.Exploitation;
import dz.minagri.stat.model.Personne;
import dz.minagri.stat.model.Product;
import dz.minagri.stat.model.Role;
import dz.minagri.stat.model.Wilaya;
import dz.minagri.stat.model.Zone;
import dz.minagri.stat.repositories.AccountRepository;
import dz.minagri.stat.repositories.AdresseRepository;
import dz.minagri.stat.repositories.CarteFellahRepository;
import dz.minagri.stat.repositories.CategoryRepository;
import dz.minagri.stat.repositories.CommuneRepository;
import dz.minagri.stat.repositories.DepartementRepository;
import dz.minagri.stat.repositories.EspeceCultiveeRepository;
import dz.minagri.stat.repositories.ExploitantRepository;
import dz.minagri.stat.repositories.ExploitationRepository;
import dz.minagri.stat.repositories.ProductRepository;
import dz.minagri.stat.repositories.WilayaRepository;
import dz.minagri.stat.repositories.ZoneRepository;
/**
* @author bellal djamel
*
*/
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class MockDataGenerator {
@Autowired
private ProductRepository productRespoitory;
@Autowired
private AdresseRepository adRepo;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private WilayaRepository wRepo;
@Autowired
private EspeceCultiveeRepository espculRepo;
@Autowired
private CommuneRepository cRepo;
@Autowired
private ZoneRepository zRepo;
// @Autowired
// private AdresseRepository aRepo;
@Autowired
private CarteFellahRepository caRepo;
@Autowired
private ExploitantRepository expRepo;
@Autowired
private ExploitationRepository exptRepo;
@Autowired
private DepartementRepository depRepo;
@Autowired
private AccountRepository acRepo;
private static final Random random = new Random(1);
private static final String categoryNames[] = new String[] {
"Children's books", "Best sellers", "Romance", "Mystery",
"Thriller", "Sci-fi", "Non-fiction", "Cookbooks" };
private static String[] word1 = new String[] { "The art of", "Mastering",
"The secrets of", "Avoiding", "For fun and profit: ",
"How to fail at", "10 important facts about",
"The ultimate guide to", "Book of", "Surviving", "Encyclopedia of",
"Very much", "Learning the basics of", "The cheap way to",
"Being awesome at", "The life changer:", "The Vaadin way:",
"Becoming one with", "Beginners guide to",
"The complete visual guide to", "The mother of all references:" };
private static String[] exword1 = new String[] { "Zahya", "Dawya",
"hadjla:" };
private static String[] exword2 = new String[] { "DYARELRAHMA", "dehlyse",
"chorfa", "OKBA", "BARAKA: ",
"hydaya:" };
private static String[] ldword1 = new String[] { "KOYATTE", "OUED",
"HADBATE","BIR" };
private static String[] ldword2 = new String[] { "eddira", "elma",
"elwaha", "elkhire", "essaba " };
private static String[] ndword1 = new String[] { "Trek", "Youcef",
"Adel","Faress" };
private static String[] ndword2 = new String[] { "Ben Sadek", "Sadek",
"Ben Saaid","Saaid" };
private static String[] word2 = new String[] { "gardening",
"living a healthy life", "designing tree houses", "home security",
"intergalaxy travel", "meditation", "ice hockey",
"children's education", "computer programming", "Vaadin TreeTable",
"winter bathing", "playing the cello", "dummies", "rubber bands",
"feeling down", "debugging", "running barefoot",
"speaking to a big audience", "creating software", "giant needles",
"elephants", "keeping your wife happy" };
private static final String mll[] = new String[] {
" Zaouya Benouaar", "Mnahla", "Zaouya-Ouled-Moussa", "Sahra",
"Essareg", "zerzara", "Elkodya", "Zommitta" };
private static final String cames[] = new String[] {"Biskra","Oumache","Branis","Chetma", "Ouled Djellal","Ras El Miaad" ,"Besbes" ,"Sidi Khaled",
"Doucen","Ech Chaïba","Sidi Okba","M'Chouneche","El Haouch","Aïn Naga","Zeribet El Oued","El Feidh" ,"El Kantara" ,
"Aïn Zaatout","El Outaya" ,"Djemorah" ,"Tolga","Lioua","Lichana", "Ourlal","M'Lili","Foughala","Bordj Ben Azzouz", "El Mizaraa","Bouchagroune"
,"Mekhadma", "El Ghrous", "El Hadjeb","Khenguet Sidi Nadji"};
private static final String comAl[] = new String[] {"Alger-Centre","Sidi M'Hamed","El Madania","Belouizdad","Bab El Oued","Bologhine","Casbah",
"Oued Koriche","Bir Mourad Raïs","El Biar","Bouzareah","Birkhadem","El Harrach","Baraki","Oued Smar","Bachdjerrah","Hussein Dey","Kouba"
,"Bourouba","Dar El Beïda","Bab Ezzouar","Ben Aknoun","Dely Ibrahim","El Hammamet","Raïs Hamidou","Djasr Kasentina","El Mouradia","Hydra"
,"Mohammadia","Bordj El Kiffan","El Magharia","Beni Messous","Les Eucalyptus","Birtouta","Tessala El Merdja","Ouled Chebel","Sidi Moussa"
,"Aïn Taya","Bordj El Bahri","El Marsa","H'Raoua","Rouïba","Reghaïa","Aïn Benian","Staoueli","Zeralda","Mahelma","Rahmania","Souidania"
,"Cheraga","Ouled Fayet","El Achour","Draria","Douera","Baba Hassen","Khraicia","Saoula"};
private static final String supwil[] = new String[] {"439700","4795","25057","6783", "12192","3268" ,"20986" ,"162200"
,"1575","4439","556185","14227","9061","20673","3568","1190","66415" ,"2577","6504" ,"6764" ,"4026","9096","1439"
,"4101", "2187","8866" ,"2175","18718", "5941","211980","2121", "78870", "285000","4115","1356","3339","159000"
,"3152", "54573","9811","4541", "1605", "9373","4891","29950", "2379", "86105","4870"};
private static final String cwil[] = new String[] {"ADRAR","CHLEF","LAGHOUAT","OUM EL BOUAGHI", "BATNA","BEJAIA" ,"BISKRA" ,"BECHAR",
"BLIDA","BOUIRA","TAMANRASSET","TEBESSA","TLEMCEN","TIARET","TIZI OUZOU","ALGER","DJELFA" ,"JIJEL",
"SETIF","SAIDA" ,"SKIKDA" ,"SIDI BEL ABBES","ANNABA","GUELMA", "CONSTANTINE","MEDEA","MOSTAGANEM","M’SILA", "MASCARA","OUARGLA"
,"ORAN", "EL BAYADH", "ILLIZI", "BORDJ BOU ARRERIDJ","BOUMERDES","EL TARF","TINDOUF","TISSEMSILT", "EL OUED","KHENCHELA"
,"SOUK AHRAS", "TIPAZA", "MILA","AIN DEFLA","NAAMA", "AIN TEMOUCHENT", "GHARDAIA","RELIZANE"};
private static final String espcul[] = new String[] {"BLEDURE","BLETENDRE","ORGE","AVOINE","TRITICALE","MAIS","SORGHO","FEVESFEVEROLLE"
,"POIS","LENTILLE","POISCHICHE","HARICOT","GESSESGUERFALLA","TREFLE","PDT-MULTIPLICATION","VESCE","LUSERNE","TOMATES-INDUSTR"
,"TABAC","ARACHIDE","MENTHE","PDT-CONSOMMATION","PATATE-DOUCE","CARROTE","TOMATE-PLCHAMP","TOMATE-SERRES","OIGNON","MELON",
"MELON-D'EAU","CANTALOUP","PASTEQUE","ARTICHAUT","PIMENT","POIVRON","CONCOMBRE","COURGETTE","AUBERGINE","CHOUXVERT","CHOUXFLEUR"
,"NAVET","AIL","PETITSPOIS","FENOUIL","SALAD","BETRAVE","FRAISE","CELERIE","CITROULLE","PERCILE","EPINARD"};
@PostConstruct
private void init() {
List<Category> categories = createCategories();
createProducts(categories);
createZones();
createVege();
createFellah();
createExpts();
createAgent();
createAccount();
}
/**
*
*/
private void createAgent() {
List<Personne> personnes = new ArrayList<Personne>();
dz.minagri.stat.model.MoyenContact c = new dz.minagri.stat.model.MoyenContact();
c.setFax("0234568l");
c.setTelephone("045678");
c.setGsm("04567");
c.setEmail("bouchra@hotmail.fr");
Adresse add1 = new Adresse();
add1.setCommune(cRepo.findByNameLike("Biskra"));
add1.setCodePostal((long) 701);
add1.setNumero("11");
add1.setRue("beta");
adRepo.save(add1);
Adresse add = new Adresse();
add.setCommune(cRepo.findByNameLike("Biskra"));
add.setCodePostal((long) 701);
add.setNumero("1");
add.setRue("alfa");
Departement dsa = new Departement();
dsa.setAddress(add);
dsa.setNom("DSA-"+"Biskra");
dsa.setMoyenContact(c);
dsa.setTypeDepartement(TypeDepartement.DSA);
dsa.setPersonnes(personnes);
for(int i=0; i<ndword1.length; i++ ) {
Personne per = new Personne();
per.setFirstName(ndword1[i]);
per.setLastName(ndword2[i]);
per.setTypePersonne(TypePersonne.values()[random
.nextInt(TypePersonne.values().length)]);
personnes.add(per);
}
dsa.setPersonnes(personnes);
depRepo.save(dsa);
}
public void createAccount() {
List<Role> lR1 = new ArrayList<Role>();
List<Role> lR = new ArrayList<Role>();
Role r = new Role("ROLE_ADMIN", "Salah Admin");
// r.setOrdinal(1);
lR.add(r);
Account ac =new Account();
// ac.setReferenceId("001");
ac.setUsername("salah");
ac.setPassword("password");
ac.setCreatedBy("ADMIN");
ac.setCreatedAt(LocalDate.of(2010, 12, 22));
ac.setFirstName("Cisalah");
ac.setLastName("Bensalah");
ac.setEnabled(true);
ac.setNonExpired(true);
ac.setNonLocked(true);
ac.setCredentialNonExpired(true);
ac.setRoles(lR);
acRepo.save(ac);
Role r1 = new Role();
r1.setAuthority("ROLE_USER");
r1.setDescription("Salam User");
// r1.setOrdinal(2);
lR1.add(r1);
Account ac1 =new Account();
// ac1.setReferenceId("002");
ac1.setUsername("salam");
ac1.setPassword("password");
ac1.setCreatedBy("ADMIN");
ac1.setCreatedAt(LocalDate.of(2010, 11, 22));
ac1.setFirstName("Cisalam");
ac1.setLastName("Bensalam");
ac1.setEnabled(true);
ac1.setNonExpired(true);
ac1.setNonLocked(true);
ac1.setCredentialNonExpired(true);
ac1.setRoles(lR1);
acRepo.save(ac1);
}
/**
*
*/
private void createFellah() {
// Adresse ad1 = new Adresse();
// Commune co =new Commune();
// ad1.setCodePostal((long) 7330);
// ad1.setNumero("4");
// ad1.setRue("Elkodya");
// co = cRepo.findByNameLike("M'Lili");
// ad1.setCommune(co);
//
// aRepo.save(ad1);
CarteFellah cafel = new CarteFellah();
cafel.setNumS12("1111111111");
cafel.setZone(zRepo.findByNameLike("Elkodya"));
cafel.setRegistrationDate(LocalDate.now());
caRepo.save(cafel);
Exploitant expl = new Exploitant();
// expl.setAdress(ad1);
// expl.setCarteFellah(caRepo.findByNumS12Like("1111111111"));
// expl.setAdress(aRepo.findByRueAndNumeroLike("Elkodya", "4"));
expl.setFirstname("testonemane");
expl.setLastname("testlastname");
expl.setNationalNumber("222222222222");
expl.setExploitantStatus(ExploitantStatus.FELLAH);
expl.setGender(Gender.MR);
expl.setRegistrationDate(LocalDate.of(2010, 11, 22));
expRepo.save(expl);
}
/**
*
*/
private void createVege() {
for(int i=0; i<espcul.length; i++ ) {
EspeceCultivee var = new EspeceCultivee();
if(null==espculRepo.findOneByName(espcul[i])) {
var.setName(espcul[i]);
espculRepo.save(var);
}
}
}
/**
*
*/
private void createZones() {
for(int i=0; i<cwil.length; i++ ) {
Wilaya wil = new Wilaya();
if(null==wRepo.findOneBynomWilaya(cwil[i])) {
Long code = (long) (100*i+100);
wil.setCodeWilaya(code);
wil.setTotarea(Integer.parseInt(supwil[i]));
wil.setNomWilaya(cwil[i]);
wRepo.save(wil);
}
}
List<Commune> coms = new ArrayList<>();
Wilaya bis =wRepo.findOneBynomWilaya("BISKRA");
for(int i=0; i<cames.length; i++ ) {
Long code = (long) (700+i+1);
Commune com = new Commune();
com.setCodeCommune(code);
com.setWilaya(bis);
com.setTypeCommune(TypeCommune.COMMUNAL);
com.setName(cames[i]);
if(null==cRepo.findByNameLike(cames[i])) {
coms.add(com);
}
}
if(null!=coms) {
bis.setCommunes(coms);
wRepo.save(bis);
}
List<Zone> zones =new ArrayList<>();
Commune commlil = cRepo.findByNameLike("M'Lili");
for(int i =0;i<mll.length;i++) {
Zone zn =new Zone();
zn.setName(mll[i]);
zn.setCommune(commlil);
zones.add(zn);
if(null==zRepo.findOneByName(mll[i])) {
zones.add(zn);
}
}
if(null!=zones) {
commlil.getZones().addAll(zones);
cRepo.save(commlil);
}
List<Commune> comsal = new ArrayList<>();
Wilaya alg = wRepo.findOneBynomWilaya("ALGER");
for(int i=0; i<comAl.length; i++ ) {
Long code = (long) (1600+i+1);
Commune com = new Commune();
com.setCodeCommune(code);
com.setWilaya(alg);
com.setTypeCommune(TypeCommune.COMMUNAL);
com.setName(comAl[i]);
if(null==cRepo.findByNameLike(comAl[i])) {
comsal.add(com);
}
System.out.println(alg+" alg");
System.out.println(code+" code");
}
if(null!=comsal) {
alg.setCommunes(comsal);
wRepo.save(alg);
}
}
private List<Category> createCategories() {
List<Category> categories = new ArrayList<>();
for (String name : categoryNames) {
Category c = createCategory(name);
categories.add(c);
}
return categories;
}
private void createProducts(List<Category> categories) {
List<Product> products = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Product p = createProduct(categories);
products.add(p);
}
}
private Category createCategory(String name) {
Category category = new Category();
category.setName(name);
return categoryRepository.save(category);
}
private Product createProduct(List<Category> categories) {
Product product = new Product();
product.setProductName(generateName());
product.setPrice(new BigDecimal((random.nextInt(250) + 50) / 10.0));
product.setAvailability(Availability.values()[random
.nextInt(Availability.values().length)]);
if (product.getAvailability() == Availability.AVAILABLE) {
product.setStockCount(random.nextInt(523));
}
product.setCategory(getCategory(categories, 1, 2));
return productRespoitory.save(product);
}
private void createExpts() {
for (int i = 0; i < 10; i++) {
Exploitation p = createExploitation();
}
}
private Exploitation createExploitation() {
Exploitation exp = new Exploitation();
exp.setNom(generateExpName());
exp.setLieuDit(generateLieudit());
exp.setTypeExploitation(TypeExploitation.values()[random
.nextInt(TypeExploitation.values().length)]);
exp.setdLat(random.nextDouble()+34.8058);
exp.setdLon(random.nextDouble()+6.70698);
exp.setZone(zRepo.findOneByName("Sahra"));
return exptRepo.save(exp);
}
private Set<Category> getCategory(List<Category> categories, int min,
int max) {
int nr = random.nextInt(max) + min;
HashSet<Category> productCategories = new HashSet<>();
for (int i = 0; i < nr; i++) {
productCategories
.add(categories.get(random.nextInt(categories.size())));
}
return productCategories;
}
private String generateName() {
return word1[random.nextInt(word1.length)] + " "
+ word2[random.nextInt(word2.length)];
}
private String generateExpName() {
return exword1[random.nextInt(exword1.length)] + " "
+ exword2[random.nextInt(exword2.length)];
}
private String generateLieudit() {
return ldword1[random.nextInt(ldword1.length)] + " "
+ ldword2[random.nextInt(ldword2.length)];
}
}
| 33.039337 | 147 | 0.690249 |
cf4219101a747c58b6fb1fd3c078330428e228eb | 1,376 | package ru.job4j.loop;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test of Paint
*
* @author Andrey Sumin
* @since 17.02.2018
*/
public class PaintTest {
@Test
public void testPaintWithHeightFive() {
String line = System.lineSeparator();
Paint screen = new Paint();
String result = screen.paint(5);
String expected = ""
+ " ^ " + line
+ " ^^^ " + line
+ " ^^^^^ " + line
+ " ^^^^^^^ " + line
+ "^^^^^^^^^" + line;
assertThat(result, is(expected));
}
@Test
public void testPaintWithHeightEight() {
String line = System.lineSeparator();
Paint screen = new Paint();
String result = screen.paint(8);
String expected = ""
+ " ^ " + line
+ " ^^^ " + line
+ " ^^^^^ " + line
+ " ^^^^^^^ " + line
+ " ^^^^^^^^^ " + line
+ " ^^^^^^^^^^^ " + line
+ " ^^^^^^^^^^^^^ " + line
+ "^^^^^^^^^^^^^^^" + line;
assertThat(result, is(expected));
}
}
| 29.913043 | 51 | 0.374273 |
103faea513aa25ff79063e240c16b4b5cf33eb29 | 715 | package tkohdk.lib.calcstr.core;
import java.util.Iterator;
import java.util.regex.Matcher;
/**
* Created by takeoh on 2018/03/07.
*/
public class MatcherIterator implements Iterator<String> {
Matcher matcher = null;
int group_index = 1;
/**
* 正規表現パターンの照合結果(Matcherオブジェクト)用イテレータ
* @param matcher
*/
public MatcherIterator(Matcher matcher){
this.init(matcher, this.group_index);
}
private void init(Matcher matcher, int group_index){
this.matcher = matcher;
this.group_index = group_index;
}
public String next(){
return matcher.group(this.group_index);
}
public boolean hasNext(){
return matcher.find();
}
}
| 21.029412 | 58 | 0.65035 |
332bace3e2008f626c74b8d1f79c103d755fc258 | 4,065 | /**
* 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.camel.component.redis;
import java.util.Map;
import org.apache.camel.Processor;
public final class ListsRedisProcessorsCreator extends AbstractRedisProcessorCreator {
Map<Command, Processor> getProcessors(RedisClient redisClient, ExchangeConverter exchangeConverter) {
bind(Command.BLPOP, wrap(exchange -> redisClient.blpop(exchangeConverter.getKey(exchange),
exchangeConverter.getTimeout(exchange))));
bind(Command.BRPOP, wrap(exchange -> redisClient.brpop(exchangeConverter.getKey(exchange),
exchangeConverter.getTimeout(exchange))));
bind(Command.BRPOPLPUSH, wrap(exchange -> redisClient.brpoplpush(exchangeConverter.getKey(exchange),
exchangeConverter.getDestination(exchange),
exchangeConverter.getTimeout(exchange))));
bind(Command.LINDEX, wrap(exchange -> redisClient.lindex(exchangeConverter.getKey(exchange),
exchangeConverter.getIndex(exchange))));
bind(Command.LINSERT, wrap(exchange -> redisClient.linsert(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange),
exchangeConverter.getPivot(exchange),
exchangeConverter.getPosition(exchange))));
bind(Command.LLEN, wrap(exchange -> redisClient.llen(exchangeConverter.getKey(exchange))));
bind(Command.LPOP, wrap(exchange -> redisClient.lpop(exchangeConverter.getKey(exchange))));
bind(Command.LPUSH, wrap(exchange -> redisClient.lpush(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange))));
//nieuwe actie
bind(Command.LPUSHX, wrap(exchange -> redisClient.lpushx(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange))));
bind(Command.LRANGE, wrap(exchange -> redisClient.lrange(exchangeConverter.getKey(exchange),
exchangeConverter.getStart(exchange),
exchangeConverter.getEnd(exchange))));
bind(Command.LREM, wrap(exchange -> redisClient.lrem(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange),
exchangeConverter.getCount(exchange))));
bind(Command.LSET, exchange -> redisClient.lset(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange),
exchangeConverter.getIndex(exchange)));
bind(Command.LTRIM, exchange -> redisClient.ltrim(exchangeConverter.getKey(exchange),
exchangeConverter.getStart(exchange),
exchangeConverter.getEnd(exchange)));
bind(Command.RPOP, wrap(exchange ->
redisClient.rpop(exchangeConverter.getKey(exchange))));
bind(Command.RPOPLPUSH, wrap(exchange -> redisClient.rpoplpush(exchangeConverter.getKey(exchange),
exchangeConverter.getDestination(exchange))));
bind(Command.RPUSH, wrap(exchange -> redisClient.rpush(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange))));
bind(Command.RPUSHX, wrap(exchange -> redisClient.rpushx(exchangeConverter.getKey(exchange),
exchangeConverter.getValue(exchange))));
return result;
}
}
| 57.253521 | 108 | 0.707257 |
92a013baa47acf04db06313b7494c486982d6606 | 1,362 | //**********************************************************
// FILE: NAME : intcoll5client.java
// DESCRIPTION : This is a client of class Intcoll5.
//**********************************************************
import java.util.*;
public class Intcoll5client
{
public static final int SENTINEL = 0;
public static void main(String[] args)
{
int value; Scanner keyboard=new Scanner(System.in);
Intcoll5 P=new Intcoll5(), N=new Intcoll5(), L= new Intcoll5();
System.out.println("Enter an integer to be inserted or 0 to quit:");
value=keyboard.nextInt();
while(value != SENTINEL)
{
if (value > 0) {P.insert(value); L.insert(value);}
else {N.insert(-value); L.omit(-value);}
System.out.println("Enter next integer to be inserted or 0 to quit:");
value=keyboard.nextInt();
}
System.out.println("\nThe values in collection P are:");
P.print();
System.out.println("\nThe values in collection N are:");
N.print();
System.out.println("\nThe values in collection L are:");
L.print();
if (P.equals(N)) System.out.println("\nP and N are equal.");
else System.out.println("\nP and N are NOT equal.");
Intcoll5 A=new Intcoll5(); A.copy(L);
System.out.println("\nThe values in the copy of L are:\n");
A.print();
}
} | 35.842105 | 79 | 0.560206 |
66d78904eaa3a3ea650685d0263deb24c6bfa0fe | 351 | package au.com.aitcollaboration.chessgame.model.pieces.movement;
import au.com.aitcollaboration.chessgame.model.game.structure.Board;
import au.com.aitcollaboration.chessgame.model.pieces.Piece;
import au.com.aitcollaboration.chessgame.model.moves.PieceMoves;
public interface MovingBehaviour {
PieceMoves getMoves(Board board, Piece piece);
}
| 31.909091 | 68 | 0.82906 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.