text stringlengths 10 2.72M |
|---|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
/**
* Extension of {@link java.io.InputStream} that allows for optimized
* implementations of message digesting.
*
* @author Craig Andrews
* @since 4.2
*/
abstract class UpdateMessageDigestInputStream extends InputStream {
/**
* Update the message digest with the rest of the bytes in this stream.
* <p>Using this method is more optimized since it avoids creating new
* byte arrays for each call.
* @param messageDigest the message digest to update
* @throws IOException when propagated from {@link #read()}
*/
public void updateMessageDigest(MessageDigest messageDigest) throws IOException {
int data;
while ((data = read()) != -1) {
messageDigest.update((byte) data);
}
}
/**
* Update the message digest with the next len bytes in this stream.
* <p>Using this method is more optimized since it avoids creating new
* byte arrays for each call.
* @param messageDigest the message digest to update
* @param len how many bytes to read from this stream and use to update the message digest
* @throws IOException when propagated from {@link #read()}
*/
public void updateMessageDigest(MessageDigest messageDigest, int len) throws IOException {
int data;
int bytesRead = 0;
while (bytesRead < len && (data = read()) != -1) {
messageDigest.update((byte) data);
bytesRead++;
}
}
}
|
package com.troycardozo.myPlugin;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.troycardozo.myPlugin.Utils.OtherF;
import com.troycardozo.myPlugin.Utils.RandomCollection;
import com.troycardozo.myPlugin.config.YmlConfig;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import net.md_5.bungee.api.ChatColor;
public class Ore {
final App plugin;
final public String prefix = "[Ore] ";
// Config variables:
public String selectedEntity;
public String defaultBlock;
public String regenDuration;
public Integer rangeDistance;
public String configName;
public Boolean togglePlacedBlocksConfig = true;
public HashMap<String, List<Integer>> allEntitiesMinMax = new HashMap<String, List<Integer>>(); // x & z min max for
// all entities
public HashMap<String, String> spawnedList = new HashMap<String, String>(); // spawned ores map
public HashMap<String, Integer> rangeCoords = new HashMap<String, Integer>(); // range coords
private RandomCollection<String> oreCollection = new RandomCollection<String>(); // percentage ore picker
public Ore(App instance) {
plugin = instance;
getEntityList();
setAllMinMaxEntities();
}
public void displayEntityList(Player player) {
player.sendMessage(plugin.ore.prefix + "======================================");
for (String entity : getEntityList()) {
if (entity.equals(plugin.ore.selectedEntity)) {
player.sendMessage(plugin.ore.prefix + ChatColor.GOLD + "Entity: " + entity + " <Selected>");
} else {
player.sendMessage(plugin.ore.prefix + "Entity: " + entity);
}
}
player.sendMessage(
plugin.ore.prefix + "============= Entity List: [" + getEntityList().size() + "] =============");
}
public void loadConfigs() {
// loads all configs in a hashmap, which can be used anytime.
plugin.oreGenConfigs.clear();
File[] files = plugin.getDataFolder().listFiles();
for (File file : files) {
if (file.isFile()) {
if (file.getName().contains("oreGenConfig")) {
String entityName = file.getName().split("-oreGenConfig")[0];
plugin.oreGenConfigs.put(entityName, new YmlConfig(plugin, file.getName()));
plugin.oreGenConfigs.get(entityName).set("general.name", entityName);
} else {
// this will only run on first load of if someone deletes all the oreGenConfigs.
plugin.oreGenConfigs.put("default", new YmlConfig(plugin, "default" + plugin.configFileName));
plugin.oreGenConfigs.get("default").set("general.name", "default");
}
}
}
}
public void addEntitytoList(String entity) {
saveConfig("entity-list." + entity + ".coords", new HashMap<String, String>());
}
public void entityConfigMatch(Player player) {
if (player.isOp()) {
if (!(selectedEntity.equals(configName))) {
loadConfigVariables(selectedEntity, false);
}
}
}
public void loadConfigVariables(String entity, Boolean onLoad) {
plugin.oreGenConfig = plugin.oreGenConfigs.get(entity);
togglePlacedBlocksConfig = true;
getConfigName();
getSelectedEntity();
loadSpawnedOres();
loadOreCollection();
validateDefaultBlock();
getRegenDuration();
getRangeCoords();
if (onLoad) {
repairSpawnedOres();
}
}
public <T> void saveConfig(String path, T val) {
plugin.getConfig().set(path, val);
plugin.saveConfig();
}
public List<String> getEntityList() {
return new ArrayList<String>(
plugin.getConfig().getConfigurationSection("entity-list").getValues(false).keySet());
}
public void setAllMinMaxEntities() {
allEntitiesMinMax.clear();
for (String entity : getEntityList()) {
Integer[] xzMinMax = { plugin.getConfig().getInt("entity-list." + entity + ".coords.min.x"),
plugin.getConfig().getInt("entity-list." + entity + ".coords.max.x"),
plugin.getConfig().getInt("entity-list." + entity + ".coords.min.z"),
plugin.getConfig().getInt("entity-list." + entity + ".coords.max.z") };
List<Integer> myList = Arrays.asList(xzMinMax);
allEntitiesMinMax.put(entity, myList);
}
}
public Integer getEntityMinMax(List<Integer> minmaxList, char coord, String minOrMax) {
char x = 'x';
char z = 'z';
Integer index = -1;
if (coord == x && minOrMax.equals("min")) {
index = 0;
} else if (coord == x && minOrMax.equals("max")) {
index = 1;
} else if (coord == z && minOrMax.equals("min")) {
index = 2;
} else if (coord == z && minOrMax.equals("max")) {
index = 3;
}
return minmaxList.get(index);
}
private void getConfigName() {
configName = plugin.oreGenConfig.getConfig().getString("general.name");
}
private void getSelectedEntity() {
selectedEntity = plugin.getConfig().getString("selected-entity");
}
public void setSelectedEntity(String entity) {
selectedEntity = entity;
saveConfig("selected-entity", entity);
}
private void setRangeDistance(Integer length) {
rangeDistance = length;
saveConfig("entity-list." + selectedEntity + ".coords.distance", length);
}
private void getRegenDuration() {
regenDuration = plugin.oreGenConfig.getConfig().getString("general.regen-duration");
}
public void setRegenDuration(String name) {
regenDuration = name;
plugin.oreGenConfig.set("general.regen-duration", name);
}
public void outLineCoords(final Player player, Integer length, String eventType, Boolean save) {
Location entLoc = null;
if (eventType.equals("set")) {
entLoc = player.getLocation();
} else if (eventType.equals("show") || eventType.equals("hide")) {
if (plugin.getConfig().isSet("entity-list." + selectedEntity + ".coords.middle")) {
String savedLoc = plugin.getConfig().getString("entity-list." + selectedEntity + ".coords.middle");
entLoc = OtherF.deserializeLocation(plugin, savedLoc);
}
}
if (entLoc != null) {
Location corner1 = new Location(entLoc.getWorld(), entLoc.getBlockX() + length, entLoc.getBlockY() + 1,
entLoc.getBlockZ() - length);
Location corner2 = new Location(entLoc.getWorld(), entLoc.getBlockX() - length, entLoc.getBlockY() + 1,
entLoc.getBlockZ() + length);
int minX = Math.min(corner1.getBlockX(), corner2.getBlockX());
int maxX = Math.max(corner1.getBlockX(), corner2.getBlockX());
int minZ = Math.min(corner1.getBlockZ(), corner2.getBlockZ());
int maxZ = Math.max(corner1.getBlockZ(), corner2.getBlockZ());
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
if ((x == minX || x == maxX) || (z == minZ || z == maxZ)) {
final Block b = corner1.getWorld().getBlockAt(x, entLoc.getBlockY(), z);
if (eventType.equals("set")) {
player.sendBlockChange(b.getLocation(), Material.SEA_LANTERN.createBlockData()); // show
// outline
new BukkitRunnable() {
@Override
public void run() {
b.getState().update(); // undo to old block
}
}.runTaskLater(plugin, (20 * 5)); // seconds change the block to noprmal.
} else if (eventType.equals("show")) {
player.sendBlockChange(b.getLocation(), Material.SEA_LANTERN.createBlockData()); // show
// outline
} else if (eventType.equals("hide")) {
b.getState().update(); // undo to old block
}
}
}
}
if (eventType.equals("set")) {
saveConfig("entity-list." + selectedEntity + ".coords.middle",
OtherF.serializeLocation(entLoc.getBlock()));
setRangeDistance(length);
setRangeCoords(minX, maxX, minZ, maxZ);
}
}
}
// toggles highlights all the blocks that are placed.
public void highlightAllSpawnedBlocks(Boolean highlight, Player player) {
for (String blockLoc : plugin.ore.spawnedList.values()) {
Location loc = OtherF.deserializeLocation(plugin, blockLoc);
Block block = loc.getBlock();
if (highlight) {
player.sendBlockChange(loc, Material.SEA_LANTERN.createBlockData()); // show outline
togglePlacedBlocksConfig = false;
} else {
block.getState().update();
togglePlacedBlocksConfig = true;
}
}
}
private void getRangeCoords() {
rangeCoords.clear();
rangeDistance = plugin.getConfig().getInt("entity-list." + selectedEntity + ".coords.distance");
rangeCoords.put("x-min", plugin.getConfig().getInt("entity-list." + selectedEntity + ".coords.min.x"));
rangeCoords.put("x-max", plugin.getConfig().getInt("entity-list." + selectedEntity + ".coords.max.x"));
rangeCoords.put("z-min", plugin.getConfig().getInt("entity-list." + selectedEntity + ".coords.min.z"));
rangeCoords.put("z-max", plugin.getConfig().getInt("entity-list." + selectedEntity + ".coords.max.z"));
}
private void setRangeCoords(int minX, int maxX, int minZ, int maxZ) {
rangeCoords.clear();
saveConfig("entity-list." + selectedEntity + ".coords.min.x", minX);
saveConfig("entity-list." + selectedEntity + ".coords.max.x", maxX);
saveConfig("entity-list." + selectedEntity + ".coords.min.z", minZ);
saveConfig("entity-list." + selectedEntity + ".coords.max.z", maxZ);
rangeCoords.put("x-min", minX);
rangeCoords.put("x-max", maxX);
rangeCoords.put("z-min", minZ);
rangeCoords.put("z-max", maxZ);
}
private void getDefaultBlock() {
defaultBlock = plugin.oreGenConfig.getConfig().getString("general.default-block");
}
public void setDefaultBlock(String name) {
defaultBlock = name;
plugin.oreGenConfig.set("general.default-block", name);
}
public void getOreList(Player player) {
Map<String, Object> oreList = getYamlMap("ore-spawn");
player.sendMessage(prefix + "============= Ore List Size: [" + oreList.size() + "] =============");
for (Map.Entry<String, Object> oreTypes : oreList.entrySet()) {
String oreNames = oreTypes.getKey();
Double oreValues = Double.parseDouble(oreTypes.getValue().toString());
player.sendMessage(prefix + "Ore: " + oreNames + " ||==|| Spawn Rate: " + oreValues + "%");
}
player.sendMessage(prefix + "======================================");
}
// on plugin load, get default block and then validate if block is right.
private void validateDefaultBlock() {
getDefaultBlock();
if (!OtherF.isMaterial(defaultBlock)) {
setDefaultBlock("STONE");
}
}
public Boolean isBlockMined(String blockLOC, String setDefaultBlock) {
Location loc = OtherF.deserializeLocation(plugin, blockLOC);
Block myCustomblock = loc.getBlock();
String blockType = myCustomblock.getType().toString();
return setDefaultBlock.equals(blockType);
}
public void removeBlockIG(String blockDetails) {
Location loc = OtherF.deserializeLocation(plugin, blockDetails);
Block myCustomblock = loc.getBlock();
myCustomblock.setType(Material.AIR);
}
// get the block details associated to this block id.
public String getSpawnedBlockDetails(String blockID) {
return plugin.oreGenConfig.getConfig().getString("spawned-ores." + blockID);
}
public void removeBlock(String blockID) {
removeBlockIG(getSpawnedBlockDetails(blockID));
plugin.oreGenConfig.set("spawned-ores." + blockID, null); // remove block from the config
loadSpawnedOres(); // reload spawned list after removing.
}
// loads all the ore names and percentages from yaml into Map
public void loadOreCollection() {
oreCollection.clear();
Map<String, Object> oreList = getYamlMap("ore-spawn");
for (Map.Entry<String, Object> entry : oreList.entrySet()) {
String oreType = entry.getKey();
Double orePercentage = Double.parseDouble(entry.getValue().toString()); // Very dodgy indeed
oreCollection.add(orePercentage, oreType);
}
}
// remove all spawned blocks and clear hashmap
public void removeAllSpawnedOres() {
plugin.oreGenConfig.getConfig().set("spawned-ores", null);
plugin.oreGenConfig.saveConfig();
spawnedList.clear();
}
// yaml object path
public Map<String, Object> getYamlMap(String text) {
return plugin.oreGenConfig.getConfig().getConfigurationSection(text).getValues(false);
}
// a nice little stream that gets all the blocks that are next in line to spawn.
// this solves a big bug where config changes when you enter a different entity.
private HashMap<String, Deque<List<String>>> oreRegenStream = new HashMap<String, Deque<List<String>>>();
// regen ores by duration
public void regenOre(final Block block, final String duration, String entity) {
Integer seconds = OtherF.converDurationToSeconds(duration);
List<String> regenDetails = new ArrayList<String>();
regenDetails.add(oreCollection.next());
regenDetails.add(seconds.toString());
// if nothing in the list then add to parent hashmap else add to child hashmap
if (!oreRegenStream.containsKey(entity)) {
Deque<List<String>> regenDetailsList = new ArrayDeque<List<String>>();
regenDetailsList.add(regenDetails);
oreRegenStream.put(entity, regenDetailsList);
} else {
oreRegenStream.get(entity).add(regenDetails);
}
for (final Deque<List<String>> queryRegenDetailsList : oreRegenStream.values()) {
if (queryRegenDetailsList.size() > 0) {
final List<String> oreDetails = new ArrayList<String>(queryRegenDetailsList.getFirst());
final String oreType = oreDetails.get(0);
final Integer oreDuration = Integer.parseInt(oreDetails.get(1));
new BukkitRunnable() {
@Override
public void run() {
block.setType(Material.matchMaterial(oreType));
}
}.runTaskLater(plugin, (20 * oreDuration)); // seconds change the block
queryRegenDetailsList.removeFirst();
}
}
}
// This method reloads all the objects from yaml file into Hashmap.
private void loadSpawnedOres() {
try {
spawnedList.clear();
Map<String, Object> customSpawnedOres = getYamlMap("spawned-ores");
for (Map.Entry<String, Object> entry : customSpawnedOres.entrySet()) {
String blockID = entry.getKey();
String blockLOC = entry.getValue().toString();
spawnedList.put(blockID, blockLOC);
}
} catch (Exception e) {
}
}
// load each entity then reset blocks for those that werent respaawned
public void repairSpawnedOres() {
for (String entity : getEntityList()) {
if (plugin.oreGenConfigs.get(entity).getConfig().isSet("spawned-ores")) {
loadConfigVariables(entity, false);
Map<String, Object> spawnedOres = plugin.oreGenConfigs.get(entity).getConfig()
.getConfigurationSection("spawned-ores").getValues(false);
String configDefaultBlock = plugin.oreGenConfigs.get(entity).getConfig()
.getString("general.default-block");
for (Object spawnedOresLocs : spawnedOres.values()) {
Location loc = OtherF.deserializeLocation(plugin, spawnedOresLocs.toString());
Block myCustomblock = loc.getBlock();
if (isBlockMined(spawnedOresLocs.toString(), configDefaultBlock)) {
myCustomblock.setType(Material.matchMaterial(oreCollection.next()));
}
}
}
}
}
} |
package slimeknights.tconstruct.library.tileentity;
public interface IProgress {
float getProgress();
}
|
package sampleFlyingBoxes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FlyingBoxes {
public static void main(String[] args) {
new FlyingBoxes();
}
public interface Drawable {
public void update(JComponent comp);
public void draw(Graphics g);
}
public class Box implements Drawable {
private int x;
private int y;
private int width = 10;
private int height = 10;
private int xDelta;
private int yDelta;
public Box(int x, int y) {
this.x = x;
this.y = y;
xDelta = random();
yDelta = random();
}
@Override
public void update(JComponent comp) {
x += xDelta;
y += yDelta;
if (x < 0) {
x = 0;
xDelta *= -1;
} else if (x + width > comp.getWidth()) {
x = comp.getWidth() - width;
xDelta *= -1;
}
if (y < 0) {
y = 0;
yDelta *= -1;
} else if (y + height > comp.getHeight()) {
y = comp.getHeight() - height;
yDelta *= -1;
}
}
@Override
public void draw(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(x, y, width, height);
}
protected int random() {
int value = 0;
do {
value = -2 + (int)(Math.random() * 4);
} while (value == 0);
return value;
}
}
public FlyingBoxes() {
final List<Drawable> drawables;
drawables = new ArrayList<>(25);
for (int index = 0; index < 25; index++) {
int x = (int) (Math.random() * 190);
int y = (int) (Math.random() * 190);
drawables.add(new Box(x, y));
}
final TestPane tp = new TestPane(drawables);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (Drawable d : drawables) {
d.update(tp);
}
tp.repaint();
}
});
timer.start();
}
public class TestPane extends JPanel {
List<Drawable> drawables;
public TestPane(List<Drawable> drawables) {
this.drawables = drawables;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Drawable d : drawables) {
d.draw(g);
}
}
}
} |
package com.aidigame.hisun.imengstar.widget;
import com.aidigame.hisun.imengstar.util.LogUtil;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
public class ShakeSensor implements SensorEventListener{
//晃动的速度,当速度超过这个值时,进行事件处理
private static final int SHAKE_SPEED=3000;
//两次晃动的时间间隔,超过此时间进行事件处理
private static final int UPDATE_INTERVAL_TIME=70;
//传感器管理器
private SensorManager sensorManager;
//传感器
private Sensor sensor;
//晃动事件处理器
private OnShakeLisener onShakeLisener;
Context context;
float lastX;
float lastY;
float lastZ;
long lastTime;
public ShakeSensor(Context context){
this.context=context;
start();
}
public void start(){
//获得传感器管理器
sensorManager=(SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
//获得重力传感器
if(sensorManager!=null){
sensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
//注册重力传感器监听器
if(sensor!=null){
sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_GAME);
}
}
public void stop(){
if(sensorManager!=null){
sensorManager.unregisterListener(this);
}
}
public void setOnShakeListener(OnShakeLisener listener){
this.onShakeLisener=listener;
}
/**
* 当产生晃动事件时,回调的方法,也就是说晃动后要做的处理
* @author admin
*
*/
public interface OnShakeLisener{
void onShake();
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
long currentTime=System.currentTimeMillis();
long timeInterval=currentTime-lastTime;
if(timeInterval<UPDATE_INTERVAL_TIME){
return;
}
long time=currentTime-lastTime;
lastTime=currentTime;
float nowX=event.values[0];
float nowY=event.values[1];
float nowZ=event.values[2];
float dx=nowX-lastX;
float dy=nowY-lastY;
float dz=nowZ-lastZ;
lastX=nowX;
lastY=nowY;
lastZ=nowZ;
double speed=Math.sqrt(dx*dx+dy*dy+dz*dz)/time*10000;
if(speed>SHAKE_SPEED){
onShakeLisener.onShake();
LogUtil.i("pull", "x="+lastX+",y="+lastY+",z="+lastZ+",speed="+(speed)/10000+",time="+time+",distance="+Math.sqrt(dx*dx+dy*dy+dz*dz));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
|
/*
* @lc app=leetcode.cn id=49 lang=java
*
* [49] 字母异位词分组
*/
import java.util.*;
// @lc code=start
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] current = strs[i].toCharArray();
Arrays.sort(current);
String strKey = Arrays.toString(current);
if (map.containsKey(strKey)) {
map.get(strKey).add(strs[i]);
} else {
map.put(strKey, new ArrayList<>());
map.get(strKey).add(strs[i]);
}
}
return new ArrayList<>(map.values());
}
}
// @lc code=end
|
package varTypes;
public class Pez {
int pez_id, tipoPez_id, dueno_id, pecera_id;
String nombrePez, genero;
public Pez(String nombrePez, String genero, int tipoPez_id, int dueno_id, int pecera_id){
this.nombrePez = nombrePez;
this.genero = genero;
this.tipoPez_id = tipoPez_id;
this.dueno_id = dueno_id;
this.pecera_id = pecera_id;
}
public int getPez_id() {
return pez_id;
}
public void setPez_id(int pez_id) {
this.pez_id = pez_id;
}
public int getTipoPez_id() {
return tipoPez_id;
}
public void setTipoPez_id(int tipoPez_id) {
this.tipoPez_id = tipoPez_id;
}
public int getDueno_id() {
return dueno_id;
}
public void setDueno_id(int dueno_id) {
this.dueno_id = dueno_id;
}
public int getPecera_id() {
return pecera_id;
}
public void setPecera_id(int pecera_id) {
this.pecera_id = pecera_id;
}
public String getNombrePez() {
return nombrePez;
}
public void setNombrePez(String nombrePez) {
this.nombrePez = nombrePez;
}
public String getGenero() {
return genero;
}
public void setGenero(String genero) {
this.genero = genero;
}
}
|
package br.com.fitNet.model;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name="usuario")
public class Acesso {
@Id
@GeneratedValue
@Column(name="id_usuario", nullable = false)
private int id;
@Column(name="nomeUsuario", nullable = false)
private String usuario;
private String senha;
@Transient
private String confirmarSenha;
@Column(name="status")
private boolean statusAtivo;
private boolean eliminado;
@DateTimeFormat(pattern="yyyy-MM-dd")
@Temporal(TemporalType.DATE)
private Calendar dataCadastro;
@DateTimeFormat(pattern="yyyy-MM-dd")
@Temporal(TemporalType.DATE)
private Calendar dataAlteracao;
@Column(name="id_cliente")
private int idCliente;
@Column(name="id_funcionario")
private int idFuncionario;
public Acesso(){
this.idCliente = -1;
this.idFuncionario = -1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getConfirmarSenha() {
return confirmarSenha;
}
public void setConfirmarSenha(String confirmarSenha) {
this.confirmarSenha = confirmarSenha;
}
public boolean isStatusAtivo() {
return statusAtivo;
}
public void setStatusAtivo(boolean status) {
this.statusAtivo = status;
}
public boolean isEliminado() {
return eliminado;
}
public void setEliminado(boolean eliminado) {
this.eliminado = eliminado;
}
public Calendar getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Calendar dataCadastro) {
this.dataCadastro = dataCadastro;
}
public Calendar getDataAlteracao() {
return dataAlteracao;
}
public void setDataAlteracao(Calendar dataAlteracao) {
this.dataAlteracao = dataAlteracao;
}
public int getIdCliente() {
return idCliente;
}
public void setIdCliente(int idCliente) {
this.idCliente = idCliente;
}
public int getIdFuncionario() {
return idFuncionario;
}
public void setIdFuncionario(int idFuncionario) {
this.idFuncionario = idFuncionario;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((confirmarSenha == null) ? 0 : confirmarSenha.hashCode());
result = prime * result + ((dataAlteracao == null) ? 0 : dataAlteracao.hashCode());
result = prime * result + ((dataCadastro == null) ? 0 : dataCadastro.hashCode());
result = prime * result + (eliminado ? 1231 : 1237);
result = prime * result + id;
result = prime * result + idCliente;
result = prime * result + idFuncionario;
result = prime * result + ((senha == null) ? 0 : senha.hashCode());
result = prime * result + (statusAtivo ? 1231 : 1237);
result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Acesso other = (Acesso) obj;
if (confirmarSenha == null) {
if (other.confirmarSenha != null)
return false;
} else if (!confirmarSenha.equals(other.confirmarSenha))
return false;
if (dataAlteracao == null) {
if (other.dataAlteracao != null)
return false;
} else if (!dataAlteracao.equals(other.dataAlteracao))
return false;
if (dataCadastro == null) {
if (other.dataCadastro != null)
return false;
} else if (!dataCadastro.equals(other.dataCadastro))
return false;
if (eliminado != other.eliminado)
return false;
if (id != other.id)
return false;
if (idCliente != other.idCliente)
return false;
if (idFuncionario != other.idFuncionario)
return false;
if (senha == null) {
if (other.senha != null)
return false;
} else if (!senha.equals(other.senha))
return false;
if (statusAtivo != other.statusAtivo)
return false;
if (usuario == null) {
if (other.usuario != null)
return false;
} else if (!usuario.equals(other.usuario))
return false;
return true;
}
}
|
package edu.tridenttech.cpt237.plant.view;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class PlantWindow
{
private Stage myStage;
private Button findBtn = new Button("Find Stud");
private Button defectBtn = new Button("Show Findings");
private Button showBtn = new Button("Show Studs");
private Button doneBtn = new Button("Done");
public PlantWindow(Stage stage)
{
GridPane pane = new GridPane();
Scene scene = new Scene(pane);
myStage = stage;
myStage.setTitle("Plant");
myStage.setScene(scene);
pane.setPadding(new Insets(10, 10, 10, 10));
pane.setHgap(25);
pane.setVgap(15);
//action if find button clicked
findBtn.setOnAction(e ->
{
FindStud findStud = new FindStud();
//opens find stud window if not opened.
if (!findStud.isShowing())
{
findStud.show();
}
//if opened, brings find stud window to front.
else
{
findStud.toFront();
}
});
//action if show defects button is clicked
defectBtn.setOnAction(e ->
{
ShowDefects showDefects = new ShowDefects();
//opens show defects window if not opened.
if (!showDefects.isShowing())
{
showDefects.show();
}
//if opened, brings show defects window to front.
else
{
showDefects.toFront();
}
});
//action if show studs button is clicked
showBtn.setOnAction(e ->
{
ShowStuds showStud = new ShowStuds();
//opens show stud window if not opened.
if (!showStud.isShowing())
{
showStud.show();
}
//if opened, brings show stud window to front.
else
{
showStud.toFront();
}
});
//closes window if done button is clicked
doneBtn.setOnAction(e ->
{
stage.close();
});
pane.add(findBtn, 0, 0);
pane.add(defectBtn, 0, 1);
pane.add(showBtn, 0, 2);
pane.add(doneBtn, 0, 3);
GridPane.setHalignment(findBtn, HPos.CENTER);
GridPane.setHalignment(defectBtn, HPos.CENTER);
GridPane.setHalignment(showBtn, HPos.CENTER);
GridPane.setHalignment(doneBtn, HPos.CENTER);
}
//method that shows main window
public void show()
{
myStage.show();
}
}
|
package splichus.com.newsapp.model;
public class Source {
String id;
String name;
}
|
package com.vendas.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/teste")
@RestController
public class TesteController {
@GetMapping
public String getTeste() {
return "Teste OK";
}
}
|
/* */ package com.cza.service.vo;
/* */
/* */ import java.math.BigDecimal;
/* */ import java.util.List;
/* */
/* */ public class SkuVo
/* */ {
/* */ private Long sid;
/* */ private BigDecimal price;
/* */ private String barcode;
/* */ private List<SkuAttrVo> attrs;
/* */ private String goodsName;
/* */ private String skuPic;
/* */ private Long number;
/* */ private Long gid;
/* */ private Long stock;
/* */
/* */ public Long getGid()
/* */ {
/* 45 */ return this.gid;
/* */ }
/* */
/* */ public void setGid(Long gid)
/* */ {
/* 58 */ this.gid = gid;
/* */ }
/* */
/* */ public String getSkuPic()
/* */ {
/* 70 */ return this.skuPic;
/* */ }
/* */
/* */ public void setSkuPic(String skuPic)
/* */ {
/* 82 */ this.skuPic = skuPic;
/* */ }
/* */
/* */ public Long getStock()
/* */ {
/* 93 */ return this.stock;
/* */ }
/* */
/* */ public void setStock(Long stock)
/* */ {
/* 104 */ this.stock = stock;
/* */ }
/* */
/* */ public String getGoodsName()
/* */ {
/* 114 */ return this.goodsName;
/* */ }
/* */
/* */ public void setGoodsName(String goodsName)
/* */ {
/* 124 */ this.goodsName = goodsName;
/* */ }
/* */
/* */ public Long getSid()
/* */ {
/* 133 */ return this.sid;
/* */ }
/* */
/* */ public void setSid(Long sid)
/* */ {
/* 142 */ this.sid = sid;
/* */ }
/* */
/* */ public BigDecimal getPrice()
/* */ {
/* 150 */ return this.price;
/* */ }
/* */
/* */ public void setPrice(BigDecimal price)
/* */ {
/* 158 */ this.price = price;
/* */ }
/* */
/* */ public String getBarcode()
/* */ {
/* 166 */ return this.barcode;
/* */ }
/* */
/* */ public void setBarcode(String barcode)
/* */ {
/* 174 */ this.barcode = barcode;
/* */ }
/* */
/* */ public List<SkuAttrVo> getAttrs()
/* */ {
/* 182 */ return this.attrs;
/* */ }
/* */
/* */ public void setAttrs(List<SkuAttrVo> attrs)
/* */ {
/* 190 */ this.attrs = attrs;
/* */ }
/* */
/* */ public Long getNumber()
/* */ {
/* 201 */ return this.number;
/* */ }
/* */
/* */ public void setNumber(Long number)
/* */ {
/* 212 */ this.number = number;
/* */ }
/* */
/* */ public String toString()
/* */ {
/* 229 */ return "SkuVo [sid=" + this.sid + ", price=" + this.price + ", barcode=" + this.barcode + ", attrs=" + this.attrs + ", goodsName=" + this.goodsName + ", skuPic=" + this.skuPic + ", number=" + this.number + ", stock=" + this.stock + "]";
/* */ }
/* */ }
/* Location: C:\Users\Administrator.SKY-20141119XLJ\Downloads\rpc-server-0.0.1-SNAPSHOT.jar
* Qualified Name: com.cza.service.vo.SkuVo
* JD-Core Version: 0.6.2
*/ |
package com.ntt.controller;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name="NOTIFICATION")
public class Notification {
public Notification() {
// TODO Auto-generated constructor stub
System.out.println("constructor");
}
@Id
@GeneratedValue
private int id;
private String name;
private String notificationType;
private String notificationMsg;
@Transient
private String models;
private String modelYear;
private String targetURL;
private List<String> modelTypes = new ArrayList<String>();
public List<String> getModelTypes() {
modelTypes.add("BMW1");
modelTypes.add("BMW2");
modelTypes.add("BMW3");
System.out.println(modelTypes.size());
return modelTypes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNotificationType() {
return notificationType;
}
public void setNotificationType(String notificationType) {
this.notificationType = notificationType;
}
public String getNotificationMsg() {
return notificationMsg;
}
public void setNotificationMsg(String notificationMsg) {
this.notificationMsg = notificationMsg;
}
public String getModels() {
return models;
}
public void setModels(String models) {
this.models = models;
}
public String getModelYear() {
System.out.println("modelTypes: " + models);
if (models != null) {
if (models.equals("BMW1")) {
modelYear = "2000";
}
if (models.equals("BMW2")) {
modelYear = "2005";
}
if (models.equals("BMW3")) {
modelYear = "2017";
}
}
System.out.println("modelyear: " + modelYear);
return modelYear;
}
public void setModelYear(String modelYear) {
this.modelYear = modelYear;
}
public String getTargetURL() {
return targetURL;
}
public void setTargetURL(String targetURL) {
this.targetURL = targetURL;
}
public void setModelTypes(List<String> modelTypes) {
this.modelTypes = modelTypes;
}
}
|
package com.blog.servlet.user;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.blog.Iservice.IDongTaiService;
import com.blog.Iservice.IUserService;
import com.blog.bean.DongTai;
import com.blog.bean.Page;
import com.blog.bean.User;
import com.blog.service.impl.DongTaiService;
import com.blog.service.impl.UserService;
public class UserShouSuoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
if(session.getAttribute("u_name")!=null){
IUserService iUserService =new UserService();
String u_name = (String) session.getAttribute("u_name");
User user = iUserService.UserByname(u_name);
request.setAttribute("user", user);
}
String shousuo = request.getParameter("shousuo");
IDongTaiService dongTaiService=new DongTaiService();
Page page = new Page();
String cPage = request.getParameter("currentPage") ;//
if(cPage == null) {
cPage = "1" ;
}
int currentPage = Integer.parseInt( cPage );
page.setCurrentPage(currentPage);
int totalCount = dongTaiService.getTotalCountShouSuo(shousuo);//总数据数
page.setTotalCount(totalCount);
int pageSize=5;
int totalPage =totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
page.setTotalPage(totalPage);
List<DongTai> queryDongTaiAll = dongTaiService.dongtaiShouSuo(shousuo, currentPage, pageSize);
page.setDongtai(queryDongTaiAll);
//热度排序
Page page0 = new Page();
int ranking =1;
List<DongTai> queryDongTaiAll0 = dongTaiService.dongtaiByd_liulang(ranking, pageSize);
page0.setDongtai(queryDongTaiAll0);
request.setAttribute("shousuo", shousuo);
request.setAttribute("page", page);
request.setAttribute("page0", page0);
if(queryDongTaiAll.size()==0){
out.println("<script>alert('没有相关的动态');location.href='UserIndexServlet'</script>");
return;
}
request.getRequestDispatcher("user/u_shousuo.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
package com.esum.wp.ims.uaktinfo.service.impl;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.esum.appframework.service.impl.BaseService;
import com.esum.imsutil.util.ExcelCreater;
import com.esum.wp.ims.tld.XtrusLangTag;
import com.esum.wp.ims.uaktinfo.UaktInfo;
import com.esum.wp.ims.uaktinfo.dao.IUaktInfoDAO;
import com.esum.wp.ims.uaktinfo.service.IUaktInfoService;
public class UaktInfoService extends BaseService implements IUaktInfoService {
@Override
public void saveUaktInfoExcel(Object object, HttpServletRequest request,
HttpServletResponse response) throws Exception {
UaktInfo info = (UaktInfo) object;
IUaktInfoDAO iUaktInfoDAO = (IUaktInfoDAO)iBaseDAO;
Map map = iUaktInfoDAO.saveUaktInfoExcel(object);
List data = (List) map.get("data");
String table = (String) map.get("table");
String[] titles = (String[]) map.get("header");
int[] size = (int[]) map.get("size");
ExcelCreater excel = new ExcelCreater();
excel.createSheet(table, titles, size, data);
excel.download(info.getRootPath(), XtrusLangTag.getMessage("lm.ims.setting.component.uakt"), request, response);
}
}
|
package com.quickly.module.mvp.base;
import android.arch.lifecycle.Lifecycle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
public class MvpBaseActivity extends AppCompatActivity {
private static final String TAG = "MvpBaseActivity";
/**
* 初始化toolbar
* @param toolbar
* @param homeAsUpEnabled
* @param title
*/
protected void initToolbar(Toolbar toolbar, boolean homeAsUpEnabled, String title) {
toolbar.setTitle(title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(homeAsUpEnabled);
}
/**
* 啄个出栈
*/
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
/**
*Fragment 和 Activity 中添加AutoDispose解决RxJava内存泄漏 因为他们都继承了 LifecycleOwner 所以可以用
* @param <X>
* @return
*/
public <X> AutoDisposeConverter<X> bindAutoDispose() {
return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
.from(this, Lifecycle.Event.ON_DESTROY));
}
}
|
package com.sshfortress.dao.user.mapper;
import java.util.List;
import java.util.Map;
import com.sshfortress.common.base.BaseMapper;
import com.sshfortress.common.beans.MemberInfo;
import com.sshfortress.common.beans.SysUserInfo;
import com.sshfortress.common.beans.UserInfo;
import com.sshfortress.common.entity.TbUserInfo;
import com.sshfortress.common.model.UserDetailDto;
public interface SysUserInfoMapper extends BaseMapper<String,SysUserInfo>{
int addUser(SysUserInfo sui);
UserInfo selecLogintUserInfoByParam(Map<String ,Object> map);
UserInfo selecttUserInfoByManyUserType(Map<String ,Object> map);
List<MemberInfo> selectMemberInfoListPager(Map<String ,Object> map);
/**得到用户详情**/
UserDetailDto getUserDetail(Map<String,Object> map);
/**登录的时候获取用户信息**/
Map<String,Object> queryUserInfo(Map<String,Object> map);
} |
package net.sf.throughglass.utils;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import ye2libs.utils.DigestUtils;
import ye2libs.utils.Properties;
public class AndroidPropertiesFactoryImpl implements Properties.Factory {
private SharedPreferences sp;
public AndroidPropertiesFactoryImpl(SharedPreferences sp) {
this.sp = sp;
}
@Override
public Object read(String key, Object defValue) {
if (defValue instanceof Integer) {
return sp.getInt(key, (Integer) defValue);
} else if (defValue instanceof Long) {
return sp.getLong(key, (Long) defValue);
} else if (defValue instanceof String) {
return sp.getString(key, (String) defValue);
} else if (defValue instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defValue);
} else if (defValue instanceof Float) {
return sp.getFloat(key, (Float) defValue);
} else if (defValue instanceof byte[]) {
final String value = sp.getString(key, null);
if (value == null) {
return defValue;
}
return DigestUtils.str2hex(value, (byte[]) defValue);
}
return null;
}
@Override
public void write(String key, Object value) {
Editor e = sp.edit();
if (value instanceof Integer) {
e.putInt(key, (Integer) value);
} else if (value instanceof Long) {
e.putLong(key, (Long) value);
} else if (value instanceof String) {
e.putString(key, (String) value);
} else if (value instanceof Boolean) {
e.putBoolean(key, (Boolean) value);
} else if (value instanceof Float) {
e.putFloat(key, (Float) value);
} else if (value instanceof byte[]) {
e.putString(key, DigestUtils.hex2str((byte[]) value));
}
e.commit();
return;
}
}
|
package com.design.pattern.abstractfactory;
/**
* @Author: 98050
* @Time: 2019-01-10 14:55
* @Feature: 具体材料A2
*/
public class IngredientA2Impl implements IngredientA {
public void show() {
System.out.println("材料A2");
}
}
|
package definition;
import adt.ContactListADT;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList implements ContactListADT {
private Node head = null;
private int size = 0;
Scanner sc = new Scanner(System.in);
private Node getNode(int index) {
Node response = head;
for (int i = 0; i < index; i++) {
response = response.getNext();
}
return response;
}
public int getSize() {
return size;
}
private void addFirst(Person person) {
head = new Node(person, head);
size++;
}
private void addAfter(Node node, Person person) {
node.next = new Node(person, node.next);
size++;
}
public void add(int index, Person person) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(Integer.toString(index));
} else if (index == 0) {
addFirst(person);
} else {
Node temp = getNode(index - 1);
addAfter(temp, person);
}
}
@Override
public void add(Person person) {
add(size, person);
}
private String getContactNumber(ArrayList<Long> contactNumber) {
String conNum = "";
for (int i = 0; i < contactNumber.size(); i++) {
conNum = conNum + contactNumber.get(i) + (i < contactNumber.size() - 1 ? ", " : "");
}
return conNum;
}
public void viewContact(int index) {
Person person = this.getNode(index).getData();
System.out.println("First Name: " + person.getFirstName() + '\n' +
"Last Name: " + person.getLastName() + '\n' +
(person.getContactNumber().size() > 1 ? "Contact Number(s): " : "Contact Number: ") + this.getContactNumber(person.getContactNumber()) + '\n' +
"Email address: " + person.getEmail());
}
@Override
public void viewContact() {
for (int i = 0; i < size; i++) {
viewContact(i);
System.out.println();
}
}
@Override
public String searchContact(String firstName) {
String response = "";
for (int i = 0; i < size; i++) {
Person person = this.getNode(i).getData();
if (firstName.equals(person.getFirstName())) {
response = response + i;
}
}
return response;
}
private Person removeFirst() {
Person response = null;
Node temp = head;
if (head != null) {
head = head.getNext();
}
if (temp != null) {
size--;
response = temp.getData();
}
return response;
}
private Person removeAfter(Node node) {
Person response = null;
Node temp = node.getNext();
if (temp != null) {
node.next = temp.getNext();
size--;
response = temp.getData();
}
return response;
}
public Person remove(int index) {
Person response = null;
// check for valid index
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(Integer.toString(index));
} else if (index == 0) { /* check if the index is zero*/
response = removeFirst();
} else {
Node previousNode = getNode(index - 1);
response = removeAfter(previousNode);
}
return response;
}
@Override
public Person remove() {
return remove(size - 1);
}
private void swap(Node firstNode, Node secondNode) {
Node temp = firstNode;
firstNode = secondNode;
secondNode = temp;
}
public void sort() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < (size - 1) - i; j++) {
Node firstNode = this.getNode(j);
Node secondNode = this.getNode(j + 1);
int compare = (firstNode.getData().getFirstName()).compareTo(secondNode.getData().getFirstName());
if (compare > 0) {
swap(firstNode, secondNode);
}
}
}
}
public Person deleteContactMenu() {
System.out.println("Here are all your contacts: ");
for (int i = 0; i < size; i++) {
System.out.println((i + 1) + "." + this.getNode(i).getData().getFirstName() + " " + this.getNode(i).getData().getLastName());
}
System.out.print("Press the number against the contact to delete it: ");
int index = sc.nextInt();
Person person = this.remove(index - 1);
return person;
}
private static class Node {
private Person data;
private Node next;
public Node(Person data) {
this.data = data;
}
public Node(Person data, Node next) {
this.data = data;
this.next = next;
}
public Person getData() {
return data;
}
public Node getNext() {
return next;
}
}
}
|
package com.sl.web.category.dao;
import java.util.Map;
import com.sl.web.category.vo.WebCategoryListVO;
import net.sf.json.JSONObject;
public interface WebCategorySettingDAO {
boolean checkCategory(WebCategoryListVO vo);
JSONObject getCategoryListInfo(WebCategoryListVO vo);
JSONObject submitCategoryModify(String email, Map<String,Object> map);
boolean deleteCategoryModify(WebCategoryListVO vo);
}
|
package ch06;
//선택 정렬
public class Selection_Sort {
public static void main(String[] args) {
int n = 10;
int arr[] = {7, 5, 9, 0, 3, 1, 6, 2, 4, 8};
// 인덱스 0 1 2 3 4 5 6 7 8 9
//큰 for문
for(int i=0; i<n; i++) {
int min_index = i;
System.out.println("정렬된 데이터를 제외한 나머지 데이터를 기준으로 가장 앞에 있는 원소의 인덱스= "+min_index);
System.out.println("정렬된 데이터를 제외한 나머지 데이터를 기준으로 가장 앞에 있는 원소= "+arr[min_index]);
//선형 탐색 (순차 탐색)
for(int j=i+1; j<n; j++) {
// min_index: 가장 작은 원소의 인덱스
if(arr[min_index]>arr[j]) { //min_index의 값이 바로 뒷 숫자보다 더 크면
min_index = j; //j(인덱스)를 min_index로 변경
// i가 0일 때,min_index = 1 -> 3
System.out.println(arr[i]+"와 비교했을 때 가장 작은 원소의 인덱스= "+min_index);
System.out.println(arr[i]+"와 비교했을 때 가장 작은 원소= "+arr[min_index]);
}
System.out.println("");
}
for(int k=0; k<n; k++) {
System.out.print(arr[k]+" ");
}
System.out.println("");
System.out.println("i = "+i+", min_index= "+min_index);
//작은 for문이 종료된 후 큰 for문을 다시 돌리기 전
//스와프 : arr[i]와 arr[min_index]값을 서로 바꿔치기
System.out.println("arr["+i+"]= "+arr[i]);
System.out.println("arr["+min_index+"]= "+arr[min_index]);
System.out.println(arr[i]+"와 "+arr[min_index]+"를 바꾸면?");
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
for(int k=0; k<n; k++) {
System.out.print(arr[k]+" ");
}
System.out.println("");
System.out.println("");
}
System.out.println("------------");
// 출력용
for(int i=0; i<n; i++) {
System.out.print(arr[i]+" ");
}
}
}
|
package br.com.cursos.matheus.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestaCurso {
public static void main(String[] args) {
Curso javaCollections = new Curso("java Collections", "Matheus");
javaCollections.adiciona(new Aula("Trabalhando com arrays", 50));
javaCollections.adiciona(new Aula("Removendo listas", 25));
javaCollections.adiciona(new Aula("Implements é confiavel?", 35));
System.out.println(javaCollections.getAulas());
List<Aula> aulasImutaveis = javaCollections.getAulas();
System.out.println(aulasImutaveis);
List<Aula> aula = new ArrayList<Aula>(aulasImutaveis);
Collections.sort(aula);
System.out.println(aula);
int total = javaCollections.getTempoTotal();
System.out.println(total);
System.out.println(javaCollections);
}
}
|
package github.dwstanle.tickets.search;
import github.dwstanle.tickets.test.Slow;
import github.dwstanle.tickets.StringListSeatMap;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static github.dwstanle.tickets.SeatStatus.AVAILABLE;
@Category(Slow.class)
public class LeftFillGeneratorPerformanceTest {
private boolean printDebug = true;
@Before
public void setUp() {
}
@Ignore("Ignored until JUnit categories are configured")
@Test
public void solveLargeVenue() {
for (int i = 100; i <= 1000; i = i + 100) {
timeSolve(10, i);
}
}
@Ignore("Ignored until JUnit categories are configured")
@Test
public void solveLargeRequest() {
for (int i = 1; i <= 50; i++) {
timeSolve(i, 300);
}
}
private Duration timeSolve(int numSeats, int venueSize) {
StringListSeatMap seatMap = randomSeatMap(venueSize, venueSize);
Instant start = Instant.now();
new LeftFillGenerator(numSeats, seatMap).findAllSolutions();
Duration duration = Duration.between(start, Instant.now());
if (printDebug) {
System.err.println(String.format("Finding %d seats for a square venue of %d seats took %d ms.",
numSeats, venueSize * venueSize, duration.toMillis()));
}
return duration;
}
private StringListSeatMap randomSeatMap(int rows, int cols) {
List<List<String>> seats = new ArrayList<>(cols);
for (int i = 0; i < rows; i++) {
seats.add(new ArrayList<>(Collections.nCopies(cols, AVAILABLE.getCode())));
}
return new StringListSeatMap(seats);
}
} |
package Question26_50;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class _39_CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
int length = candidates.length;
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(candidates);
iteror(list, new ArrayList<>(), 0, target, candidates);
return list;
}
public void iteror(List result, List l, int cur, int target, int[] candidates) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(l));
return;
}
for (int i = cur; i < candidates.length; i++) {
if (i > 0 && candidates[i] == candidates[i - 1]) {
continue;
}
int key = candidates[i];
if (key <= target) {
l.add(key);
iteror(result, l, i, target - key, candidates);
l.remove(l.size() - 1);
} else {
break;
}
}
return;
}
}
|
package com.luv2code.springdemo.dao;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.luv2code.springdemo.entity.Customer;
@Repository
public class CustomerDAOImpl implements CustomerDAO {
private final SessionFactory sessionFactory;
@Autowired
public CustomerDAOImpl(final SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<Customer> getCustomers() {
Session session = this.sessionFactory.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
Root<Customer> root = cq.from(Customer.class);
Order orderByLastNameAsc = cb.asc(root.get("lastName"));
cq.select(root).orderBy(orderByLastNameAsc);
Query<Customer> query = session.createQuery(cq);
return query.getResultList();
}
@Override
public void createCustomer(Customer theCustomer) {
// Get current hibernate session
Session session = this.sessionFactory.getCurrentSession();
// Save the customer
session.save(theCustomer);
}
@Override
public Customer getCustomer(int theId) {
// Get current hibernate session
Session session = this.sessionFactory.getCurrentSession();
// Get customer by id
return session.get(Customer.class, theId);
}
@Override
public void updateCustomer(Customer theCustomer) {
// Get current hibernate session
Session session = this.sessionFactory.getCurrentSession();
session.update(theCustomer);
}
@Override
public void deleteCustomer(Customer theCustomer) {
// Get current hibernate session
Session session = this.sessionFactory.getCurrentSession();
session.delete(theCustomer);
}
@Override
public List<Customer> searchCustomers(String theSearchName) {
// Get current hibernate session
Session session = this.sessionFactory.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
Root<Customer> root = cq.from(Customer.class);
Predicate firstNameLike = cb.like(root.get("firstName"), "%" + theSearchName + "%");
Predicate lastNameLike = cb.like(root.get("lastName"), "%" + theSearchName + "%");
Predicate[] firstLastNameLikeArr = { firstNameLike, lastNameLike };
Predicate finalOrCondtions = cb.or(firstLastNameLikeArr);
Order orderByLastNameAsc = cb.asc(root.get("lastName"));
cq.select(root).where(finalOrCondtions).orderBy(orderByLastNameAsc);
Query<Customer> query = session.createQuery(cq);
List<Customer> matchedCustomers = query.getResultList();
return matchedCustomers;
}
}
|
package reporteConteos;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ConteoTeorico {
static String mensaje;
//static String inventarios="jdbc:postgresql://201.149.89.164:5932/inventarios";
//static String productivo="jdbc:postgresql://201.149.89.163:5932/openbravo";
static String inventarios="jdbc:postgresql://10.1.250.24:5932/inventarios";
static String usuario="postgres",contra="s3st2m1s4e";
static String productivo="jdbc:postgresql://10.1.250.20:5932/openbravo";
static Date date = new Date();
static DateFormat hourFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
public static String main(String almacenes, String repositorio){
try {
Class.forName("org.postgresql.Driver");
Connection cn = DriverManager.getConnection(inventarios, usuario, contra);
Connection co = DriverManager.getConnection(productivo, usuario, contra);
String[] almacen;
int h=0;
System.out.println("Ejecutando Query.......");
ResultSet rs = null,rsp = null;
WritableWorkbook wb = Workbook.createWorkbook(new File("/INFORMES/"+repositorio+"InventarioTeorico"+almacenes.replace("|", "-")+hourFormat.format(date)+".xls"));
almacen=almacenes.split("\\|");
for(int x=0;x<almacen.length;x++)
{
PreparedStatement ps = cn.prepareStatement("SELECT ub.almacen,ub.hueco,ub.MARBETE,CASE WHEN invent.codigo IS NULL THEN 'FALTA CONFIRMACION' ELSE invent.codigo END AS cod, "
+ "CASE WHEN invent.inventario_piezas IS NULL THEN 'FALTA CONFIRMACION' ELSE (round(invent.inventario_piezas::numeric))::text END AS cant,to_char(invent.fecha,'DD-MM-YYYY') AS "
+ "fecha_confirmado FROM ubicaciones AS ub LEFT JOIN inventario_teorico AS invent ON ub.hueco=invent.ubicacion WHERE ub.almacen similar to ('"+almacenes+"') ORDER BY almacen,"
+ "ub.marbete");
rs = ps.executeQuery();
ArrayList<String> col=new ArrayList<String>();
while (rs.next())
{
col.add(rs.getString(1));
col.add(rs.getString(2));
col.add(rs.getString(3));
col.add(rs.getString(4));
rsp=null;
ps=co.prepareStatement("SELECT description FROM m_product WHERE value='"+rs.getString(4)+"'");
rsp=ps.executeQuery();
while (rsp.next())
{
col.add(rsp.getString(1));
}
col.add(rs.getString(5));
col.add(rs.getString(6));
col.add("sp");
}
WritableSheet ws = wb.createSheet("INVENTARIOTEORICO"+almacen[x], h);
h++;
WritableFont wf = new WritableFont(WritableFont.TAHOMA, 10, WritableFont.NO_BOLD);
WritableCellFormat cf = new WritableCellFormat(wf);
int column = 0;
int row = 0;
Iterator<String> i = col.iterator();
Label ec1 = new Label(column, row, "ALMACEN", cf);
ws.addCell(ec1);
column++;
Label ec2 = new Label(column, row, "HUECO", cf);
ws.addCell(ec2);
column++;
Label ec3 = new Label(column, row, "MARBETE", cf);
ws.addCell(ec3);
column++;
Label ec4 = new Label(column, row, "CODIGO OB3", cf);
ws.addCell(ec4);
column++;
Label ec5 = new Label(column, row, "DESCRIPCION", cf);
ws.addCell(ec5);
column++;
Label ec6 = new Label(column, row, "CANTIDAD", cf);
ws.addCell(ec6);
column++;
Label ec7 = new Label(column, row, "FECHA CONFIRMADA", cf);
ws.addCell(ec7);
row = 1;
column = 0;
while (i.hasNext())
{
String campo = (String)i.next();
if (campo == null)
{
campo = " ";
}
if (campo.equals("sp"))
{
i.remove();
row++;
column = 0;
}
else
{
Label l1 = new Label(column, row, campo, cf);
ws.addCell(l1);
column++;
}
}
}
wb.write();
wb.close();
co.close();
cn.close();
mensaje="Informe Generado Correctamente";
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mensaje;
}
}
|
package slimeknights.tconstruct.tools.ranged.item;
import com.google.common.collect.ImmutableList;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nonnull;
import slimeknights.tconstruct.common.config.Config;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.entity.EntityProjectileBase;
import slimeknights.tconstruct.library.materials.ArrowShaftMaterialStats;
import slimeknights.tconstruct.library.materials.FletchingMaterialStats;
import slimeknights.tconstruct.library.materials.HeadMaterialStats;
import slimeknights.tconstruct.library.materials.Material;
import slimeknights.tconstruct.library.materials.MaterialTypes;
import slimeknights.tconstruct.library.tinkering.Category;
import slimeknights.tconstruct.library.tinkering.PartMaterialType;
import slimeknights.tconstruct.library.tools.IToolPart;
import slimeknights.tconstruct.library.tools.ProjectileNBT;
import slimeknights.tconstruct.library.tools.ranged.ProjectileCore;
import slimeknights.tconstruct.library.utils.ListUtil;
import slimeknights.tconstruct.tools.TinkerMaterials;
import slimeknights.tconstruct.tools.TinkerTools;
import slimeknights.tconstruct.tools.common.entity.EntityBolt;
import slimeknights.tconstruct.tools.melee.item.Rapier;
import slimeknights.tconstruct.tools.traits.TraitEnderference;
public class Bolt extends ProjectileCore {
protected final List<PartMaterialType> toolBuildComponents;
public Bolt() {
super(PartMaterialType.arrowShaft(TinkerTools.boltCore),
new BoltHeadPartMaterialType(TinkerTools.boltCore),
PartMaterialType.fletching(TinkerTools.fletching));
addCategory(Category.NO_MELEE, Category.PROJECTILE);
toolBuildComponents = ImmutableList.of(requiredComponents[0], requiredComponents[2]);
}
@Override
public List<PartMaterialType> getToolBuildComponents() {
return toolBuildComponents;
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
if(this.isInCreativeTab(tab)) {
for(Material head : TinkerRegistry.getAllMaterials()) {
List<Material> mats = new ArrayList<>(3);
if(head.hasStats(MaterialTypes.HEAD)) {
mats.add(TinkerMaterials.wood);
mats.add(head);
mats.add(TinkerMaterials.feather);
ItemStack tool = buildItem(mats);
// only valid ones
if(hasValidMaterials(tool)) {
subItems.add(tool);
if(!Config.listAllMaterials) {
break;
}
}
}
}
}
}
@Override
public Material getMaterialForPartForGuiRendering(int index) {
return super.getMaterialForPartForGuiRendering(index + 1);
}
@Override
public ItemStack buildItemForRenderingInGui() {
List<Material> materials = IntStream.range(0, getRequiredComponents().size())
.mapToObj(super::getMaterialForPartForGuiRendering)
.collect(Collectors.toList());
return buildItemForRendering(materials);
}
@Override
public float damagePotential() {
return 1f;
}
@Override
public double attackSpeed() {
return 1;
}
@Nonnull
@Override
public ItemStack buildItemFromStacks(NonNullList<ItemStack> inputStacks) {
List<ItemStack> stacks = inputStacks.stream().filter(itemStack -> !itemStack.isEmpty()).collect(Collectors.toList());
if(stacks.size() != 2) {
return ItemStack.EMPTY;
}
ItemStack boltCore = stacks.get(0);
ItemStack fletching = stacks.get(1);
// we only care about the material returned by getMaterial call
ItemStack boltCoreHead = BoltCore.getHeadStack(boltCore);
return super.buildItemFromStacks(ListUtil.getListFrom(boltCore, boltCoreHead, fletching));
}
@Override
public boolean dealDamageRanged(ItemStack stack, Entity projectile, EntityLivingBase player, Entity target, float damage) {
// friggin vanilla hardcode 2
if(target instanceof EntityEnderman && ((EntityEnderman) target).getActivePotionEffect(TraitEnderference.Enderference) != null) {
return target.attackEntityFrom(new DamageSourceProjectileForEndermen(DAMAGE_TYPE_PROJECTILE, projectile, player), damage);
}
DamageSource damageSource = new EntityDamageSourceIndirect(DAMAGE_TYPE_PROJECTILE, projectile, player).setProjectile();
return Rapier.dealHybridDamage(damageSource, target, damage);
}
@Override
public ProjectileNBT buildTagData(List<Material> materials) {
ProjectileNBT data = new ProjectileNBT();
ArrowShaftMaterialStats shaft = materials.get(0).getStatsOrUnknown(MaterialTypes.SHAFT);
HeadMaterialStats head = materials.get(1).getStatsOrUnknown(MaterialTypes.HEAD);
FletchingMaterialStats fletching = materials.get(2).getStatsOrUnknown(MaterialTypes.FLETCHING);
data.head(head);
data.fletchings(fletching);
data.shafts(this, shaft);
data.durability *= 0.8f;
return data;
}
@Override
public EntityProjectileBase getProjectile(ItemStack stack, ItemStack bow, World world, EntityPlayer player, float speed, float inaccuracy, float power, boolean usedAmmo) {
inaccuracy -= (1f - 1f / ProjectileNBT.from(stack).accuracy) * speed / 2f;
return new EntityBolt(world, player, speed, inaccuracy, power, getProjectileStack(stack, world, player, usedAmmo), bow);
}
private static class BoltHeadPartMaterialType extends PartMaterialType {
public BoltHeadPartMaterialType(IToolPart part) {
super(part, MaterialTypes.HEAD);
}
@Override
public boolean isValidMaterial(Material material) {
return material.isCastable() && super.isValidMaterial(material);
}
}
}
|
package cn.hrbcu.com.entity;
/**
* @author: XuYi
* @date: 2021/5/21 22:12
* @description: 编程语言栏目实体类
*/
public class CodeType {
/*语言编号*/
private int code_id;
/*语言名称*/
private String code_name;
/*构造方法*/
public CodeType() {}
public CodeType(int code_id, String code_name) {
this.code_id = code_id;
this.code_name = code_name;
}
/*Get和Set方法*/
public int getCode_id() {
return code_id;
}
public void setCode_id(int code_id) {
this.code_id = code_id;
}
public String getCode_name() {
return code_name;
}
public void setCode_name(String code_name) {
this.code_name = code_name;
}
/*toString方法*/
@Override
public String toString() {
return "CodeType{" +
"code_id=" + code_id +
", code_name='" + code_name + '\'' +
'}';
}
}
|
package com.xinhua.api.domain.yYqtbxxcdBean;
import com.apsaras.aps.increment.domain.AbstractIncResponse;
import java.io.Serializable;
import java.util.List;
/**
* Created by tanghao on 2015/8/29.
* 犹豫期退保信息传递
* 响应
*/
public class YYQTBXXCDResponse extends AbstractIncResponse implements Serializable {
private String bankDate;
private String transExeTime;
private String bankCode;
private String brNo1;
private String branch;
private String teller;
private String transRefGUID;
private String functionFlag;
private String carrierCode;
private String resultCode;
private String resultInfo;
private String getSurrDate;
private String insuTrans;
private String bkPlatSeqNo;
private String bkChnlNo;
private String bkBrchNo;
private String bkOthDate;
private String polNumber;
private String hOAppFormNumber;
private String bkRecNum;
private String bkOthTxCode;
private String piQdDate;
private String qdDate;
private String surrCount;
private String tbrName;
private String bbrName;
/**
* 主险信息循环
*/
private List<ResYyqMainProList> resYyqMainProList;
/**
* 附加险信息循环
*/
private List<ResYyqFjProList> resYyqFjProList;
public String getBankDate() {
return bankDate;
}
public void setBankDate(String bankDate) {
this.bankDate = bankDate;
}
public String getTransExeTime() {
return transExeTime;
}
public void setTransExeTime(String transExeTime) {
this.transExeTime = transExeTime;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getBrNo1() {
return brNo1;
}
public void setBrNo1(String brNo1) {
this.brNo1 = brNo1;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getTeller() {
return teller;
}
public void setTeller(String teller) {
this.teller = teller;
}
public String getTransRefGUID() {
return transRefGUID;
}
public void setTransRefGUID(String transRefGUID) {
this.transRefGUID = transRefGUID;
}
public String getFunctionFlag() {
return functionFlag;
}
public void setFunctionFlag(String functionFlag) {
this.functionFlag = functionFlag;
}
public String getCarrierCode() {
return carrierCode;
}
public void setCarrierCode(String carrierCode) {
this.carrierCode = carrierCode;
}
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultInfo() {
return resultInfo;
}
public void setResultInfo(String resultInfo) {
this.resultInfo = resultInfo;
}
public String getGetSurrDate() {
return getSurrDate;
}
public void setGetSurrDate(String getSurrDate) {
this.getSurrDate = getSurrDate;
}
public String getInsuTrans() {
return insuTrans;
}
public void setInsuTrans(String insuTrans) {
this.insuTrans = insuTrans;
}
public String getBkPlatSeqNo() {
return bkPlatSeqNo;
}
public void setBkPlatSeqNo(String bkPlatSeqNo) {
this.bkPlatSeqNo = bkPlatSeqNo;
}
public String getBkChnlNo() {
return bkChnlNo;
}
public void setBkChnlNo(String bkChnlNo) {
this.bkChnlNo = bkChnlNo;
}
public String getBkBrchNo() {
return bkBrchNo;
}
public void setBkBrchNo(String bkBrchNo) {
this.bkBrchNo = bkBrchNo;
}
public String getBkOthDate() {
return bkOthDate;
}
public void setBkOthDate(String bkOthDate) {
this.bkOthDate = bkOthDate;
}
public String getPolNumber() {
return polNumber;
}
public void setPolNumber(String polNumber) {
this.polNumber = polNumber;
}
public String gethOAppFormNumber() {
return hOAppFormNumber;
}
public void sethOAppFormNumber(String hOAppFormNumber) {
this.hOAppFormNumber = hOAppFormNumber;
}
public String getBkRecNum() {
return bkRecNum;
}
public void setBkRecNum(String bkRecNum) {
this.bkRecNum = bkRecNum;
}
public String getBkOthTxCode() {
return bkOthTxCode;
}
public void setBkOthTxCode(String bkOthTxCode) {
this.bkOthTxCode = bkOthTxCode;
}
public String getPiQdDate() {
return piQdDate;
}
public void setPiQdDate(String piQdDate) {
this.piQdDate = piQdDate;
}
public String getQdDate() {
return qdDate;
}
public void setQdDate(String qdDate) {
this.qdDate = qdDate;
}
public String getSurrCount() {
return surrCount;
}
public void setSurrCount(String surrCount) {
this.surrCount = surrCount;
}
public String getTbrName() {
return tbrName;
}
public void setTbrName(String tbrName) {
this.tbrName = tbrName;
}
public String getBbrName() {
return bbrName;
}
public void setBbrName(String bbrName) {
this.bbrName = bbrName;
}
public List<ResYyqMainProList> getResYyqMainProList() {
return resYyqMainProList;
}
public void setResYyqMainProList(List<ResYyqMainProList> resYyqMainProList) {
this.resYyqMainProList = resYyqMainProList;
}
public List<ResYyqFjProList> getResYyqFjProList() {
return resYyqFjProList;
}
public void setResYyqFjProList(List<ResYyqFjProList> resYyqFjProList) {
this.resYyqFjProList = resYyqFjProList;
}
@Override
public String toString() {
return "YYQTBXXCDResponse{" +
"bankDate='" + bankDate + '\'' +
", transExeTime='" + transExeTime + '\'' +
", bankCode='" + bankCode + '\'' +
", brNo1='" + brNo1 + '\'' +
", branch='" + branch + '\'' +
", teller='" + teller + '\'' +
", transRefGUID='" + transRefGUID + '\'' +
", functionFlag='" + functionFlag + '\'' +
", carrierCode='" + carrierCode + '\'' +
", resultCode='" + resultCode + '\'' +
", resultInfo='" + resultInfo + '\'' +
", getSurrDate='" + getSurrDate + '\'' +
", insuTrans='" + insuTrans + '\'' +
", bkPlatSeqNo='" + bkPlatSeqNo + '\'' +
", bkChnlNo='" + bkChnlNo + '\'' +
", bkBrchNo='" + bkBrchNo + '\'' +
", bkOthDate='" + bkOthDate + '\'' +
", polNumber='" + polNumber + '\'' +
", hOAppFormNumber='" + hOAppFormNumber + '\'' +
", bkRecNum='" + bkRecNum + '\'' +
", bkOthTxCode='" + bkOthTxCode + '\'' +
", piQdDate='" + piQdDate + '\'' +
", qdDate='" + qdDate + '\'' +
", surrCount='" + surrCount + '\'' +
", tbrName='" + tbrName + '\'' +
", bbrName='" + bbrName + '\'' +
", resYyqMainProList=" + resYyqMainProList +
", resYyqFjProList=" + resYyqFjProList +
'}';
}
}
|
package gitnetbeans;
public class GitNetBeans {
public static void main(String[] args) {
System.out.println("Exemplo de projeto entre Git e NetBeans");
System.out.println("Segundo commit via website do github");
System.out.println("Alterando pelo netbeans e fazendo commit no mesmo!");
}
}
|
package com.company.db;
import com.company.Item;
import org.sqlite.JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import static org.testng.Assert.assertTrue;
public class DBWorker {
private static DBWorker ourInstance = new DBWorker();
private static final String DBURL = "jdbc:sqlite:C:\\Users\\sergey.lugovskoi\\IdeaProjects\\bd_task\\mydb";
public static DBWorker getInstance() {
return ourInstance;
}
private DBWorker() {
}
private Connection connect(){
try {
return JDBC.createConnection(DBURL, new Properties());
} catch (SQLException e) {
System.out.println("can not connect");
return null;
}
}
public void insertItems(List<Item> list) throws SQLException {
Connection connection = connect();
assertTrue(connection!=null);
String insert = "insert into items " +
"(group1, group2, group3, group4, group5, name, art, fullname, price,code) " +
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(insert);
for(Item item: list){
statement.setString(1, item.getGroup1());
statement.setString(2, item.getGroup2());
statement.setString(3, item.getGroup3());
statement.setString(4, item.getGroup4());
statement.setString(5, item.getGroup5());
statement.setString(6, item.getName());
statement.setString(7, item.getArt());
statement.setString(8, item.getFullName());
statement.setFloat(9, item.getPrice());
statement.setString(10, item.getCode());
statement.addBatch();
}
statement.executeBatch();
statement.close();
connection.close();
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.converter.impl;
import xyz.noark.core.annotation.TemplateConverter;
import xyz.noark.core.converter.AbstractConverter;
import xyz.noark.core.exception.IllegalExpressionException;
import xyz.noark.core.lang.Point;
import xyz.noark.core.util.IntUtils;
import xyz.noark.core.util.StringUtils;
/**
* Point转化器.
*
* @author 小流氓[176543888@qq.com]
* @since 3.4
*/
@TemplateConverter(Point.class)
public class PointConverter extends AbstractConverter<Point> {
@Override
public Point convert(String value) {
String[] array = StringUtils.split(value, ",");
if (array.length == IntUtils.NUM_2) {
return Point.valueOf(Integer.parseInt(array[0]), Integer.parseInt(array[1]));
} else {
throw new IllegalExpressionException("坐标表达式格式错误(x,y):" + value);
}
}
@Override
public String buildErrorMsg() {
return "不是一个Point类型的值(x,y)";
}
} |
package algorithms.graph.process;
import java.util.ArrayDeque;
import java.util.BitSet;
import java.util.Deque;
import algorithms.graph.Graph;
import org.springframework.stereotype.Component;
/**
* Created by Chen Li on 2018/5/5.
* undirected graphs
*/
@Component
public class DepthFirstUndirectedCycleDetection implements CycleDetection {
private BitSet marked;
private boolean hasCycle;
private int[] edgesTo;
private Deque<Integer> cycle;
@Override
public void init(Graph graph) {
edgesTo = new int[graph.verticesCount()];
marked = new BitSet(graph.verticesCount());
hasCycle = false;
for (Integer v : graph.getVertices()) {
if (hasCycle()) {
break;
}
if (!marked.get(v)) {
dfs(graph, v, v);
}
}
}
/**
* be careful to terminate recursive call
*/
private void dfs(Graph graph, int vertex, int from) {
marked.set(vertex);
for (Integer adjacentVertex : graph.adjacentVertices(vertex)) {
if (hasCycle()) {
//be careful to terminate recursive call
return;
}
if (marked.get(adjacentVertex)) {
if (adjacentVertex != from) {
this.hasCycle = true;
cycle = new ArrayDeque<>();
for (int x = vertex; x != adjacentVertex; x = edgesTo[x]) {
cycle.push(x);
}
cycle.push(adjacentVertex);
cycle.push(vertex);
return;
}
} else {
edgesTo[adjacentVertex] = vertex;
dfs(graph, adjacentVertex, vertex);
}
}
}
@Override
public boolean hasCycle() {
return hasCycle;
}
@Override
public Iterable<Integer> cycle() {
return cycle;
}
}
|
package facade;
public class BankSystem {
public float checkAmountOnAccount(long cardNumber){
if(cardNumber == 12345){
return 1000f;
}else {
return 0f;
}
}
public void withdawCash(int amount){
System.out.println("Z konta wypłacono " + amount);
}
public void activateCard(long cardNumber){
System.out.println("Aktywowano kartę " + cardNumber);
}
public void payInMobile(){
}
public void makeTransfer(int amount, long destAccountNumber){
System.out.println("Wykonano przelew na kwotę: "+amount + " na numer konta" + destAccountNumber);
}
}
|
package pers.mine.scratchpad.base.classload;
/**
* 接口的初始化
* 通过查看字节码,SuperInterface存在clinit方法,但是ClassLoadInterfaceTest没有
*/
public class ClassLoadInterfaceTest {
public static void main(String[] args) {
// 接口中不能使用静态语句块,但仍然有变量初始化的赋值操作,因此接口与类一样都会生成<clinit>()方法。
// 但接口与类不同的是,执行接口的<clinit>()方法不需要先执行父接口的<clinit>()方法,
// 因为只有当父接口中定义的变量被使用时,父接口才会被初始化。
// 此外,接口的实现类在初始化时也一样不会执行接口的<clinit>()方法。
SubInterface sbi = new SubInterface() {
};
System.out.println("sbi.superO调用前...");
System.out.println(sbi.superO);
System.out.println("sbi.subO调用前...");
System.out.println(sbi.subO);
//当一个接口中定义了JDK 8新加入的默认方法(被default关键字修饰的接口方法)时,
//如果有这个接口的实现类发生了初始化,那该接口要在其之前被初始化。
DefaultSubInterface dsbi = new DefaultSubInterface() {
};
System.out.println("dsbi.superO调用前...");
System.out.println(dsbi.superO);
System.out.println("dsbi.subO调用前...");
System.out.println(dsbi.subO);
}
static interface SuperInterface {
static Object superO = new Object() {
{
System.out.println("super.superO");
}
};
}
static interface SubInterface extends SuperInterface {
static Object subO = new Object() {
{
System.out.println("sub.subO");
}
};
}
static interface DefaultSuperInterface {
static Object superO = new Object() {
{
System.out.println("default super.superO");
}
};
public default void test() {
System.out.println("test");
}
}
static interface DefaultSubInterface extends DefaultSuperInterface {
static Object subO = new Object() {
{
System.out.println("default sub.subO");
}
};
}
}
|
package com.mavenmokito.test.appmokito.TaskService;
import java.util.List;
// Application interface fetching service over network (already tested)
public interface TaskService {
// @return - expected a list or empty or null
public List<Integer> findAllTask();
}
|
package old.Data20180411;
import java.util.*;
public class WordBreak {
public static void main(String[] args) {
String s = "leetcode";
Set<String> dict = new HashSet<String>();
dict.add("leet");
dict.add("code");
System.out.println(wordBreak(s, dict));
}
public static boolean wordBreak(String s, Set<String> dict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 0; i < s.length(); i++){
for(int j = i; dp[i] == true && j <= s.length(); j++){
String str = s.substring(i, j);
if(dict.contains(str))
dp[j] = true;
}
}
return dp[s.length()];
}
}
|
package be.openclinic.datacenter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import webcab.lib.statistics.pdistributions.NormalProbabilityDistribution;
import webcab.lib.statistics.statistics.BasicStatistics;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.ScreenHelper;
public class ExporterLab extends Exporter {
public void export(){
if(!mustExport(getParam())){
return;
}
if(getParam().equalsIgnoreCase("lab.1")){
//Export a summary of all ICD-10 based in-patient mortality per month
//First find first month for which a summary must be provided
StringBuffer sb = new StringBuffer("<labtests>");
String firstMonth = MedwanQuery.getInstance().getConfigString("datacenterFirstLabSummaryMonth","0");
if(firstMonth.equalsIgnoreCase("0")){
//Find oldest diagnosis
Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection();
try {
PreparedStatement ps = oc_conn.prepareStatement("select count(*) total,min(resultdate) as firstMonth from requestedlabanalyses where finalvalidationdatetime is not null");
ResultSet rs = ps.executeQuery();
if(rs.next() && rs.getInt("total")>0){
firstMonth=new SimpleDateFormat("yyyyMM").format(rs.getDate("firstMonth"));
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
oc_conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
if(!firstMonth.equalsIgnoreCase("0")){
try {
boolean bFound=false;
Date lastDay=new Date(new SimpleDateFormat("yyyyMMdd").parse(new SimpleDateFormat("yyyyMM").format(new Date())+"01").getTime()-1);
Date firstDay=new SimpleDateFormat("yyyyMMdd").parse(firstMonth+"01");
if(firstDay.before(ScreenHelper.parseDate("01/01/2005"))){
firstDay=ScreenHelper.parseDate("01/01/2005");
}
int firstYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(firstDay));
int lastYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(lastDay));
for(int n=firstYear;n<=lastYear;n++){
int firstmonth=1;
if(n==firstYear){
firstmonth=Integer.parseInt(new SimpleDateFormat("MM").format(firstDay));;
}
int lastmonth=12;
if(n==lastYear){
lastmonth=Integer.parseInt(new SimpleDateFormat("MM").format(lastDay));;
}
for(int i=firstmonth;i<=lastmonth;i++){
//Find all diagnoses for this month
Date begin = ScreenHelper.parseDate("01/"+i+"/"+n);
Date end = ScreenHelper.parseDate(i==12?"01/01/"+(n+1):"01/"+(i+1)+"/"+n);
Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection();
try {
Hashtable analyses = new Hashtable();
//First numerical results
PreparedStatement ps = oc_conn.prepareStatement("select count(*) total, analysiscode,avg(resultvalue) as average,"+MedwanQuery.getInstance().getConfigString("stdevFunction","stdev")+"(resultvalue) as stddev from requestedlabanalyses a, labanalysis b where a.analysiscode=b.labcode and b.editor='numeric' and finalvalidationdatetime is not null and finalvalidationdatetime between ? and ? group by analysiscode order by count(*) desc");
ps.setTimestamp(1,new java.sql.Timestamp(begin.getTime()));
ps.setTimestamp(2,new java.sql.Timestamp(end.getTime()));
ResultSet rs = ps.executeQuery();
while(rs.next()){
String labcode=rs.getString("analysiscode");
sb.append("<labtest editor='numeric' code='"+labcode+"' count='"+rs.getInt("total")+"' average='"+rs.getDouble("average")+"' standarddeviation='"+rs.getDouble("stddev")+"' month='"+i+"' year='"+n+"'/>");
}
rs.close();
ps.close();
//then listbox results
ps = oc_conn.prepareStatement("select count(*) total, analysiscode, resultvalue from requestedlabanalyses a, labanalysis b where a.analysiscode=b.labcode and b.editor='listbox' and finalvalidationdatetime is not null and finalvalidationdatetime between ? and ? group by analysiscode,resultvalue order by count(*) desc");
ps.setTimestamp(1,new java.sql.Timestamp(begin.getTime()));
ps.setTimestamp(2,new java.sql.Timestamp(end.getTime()));
rs = ps.executeQuery();
while(rs.next()){
String labcode=rs.getString("labanalysiscode");
String resultvalue=rs.getString("resultvalue");
sb.append("<labtest editor='listbox' code='"+labcode+"' value='"+resultvalue+"' count='"+rs.getInt("total")+"' month='"+i+"' year='"+n+"'/>");
}
rs.close();
ps.close();
//then the other results
ps = oc_conn.prepareStatement("select count(*) total, analysiscode, editor from requestedlabanalyses a, labanalysis b where a.analysiscode=b.labcode and b.editor NOT in ('listbox','numeric') and finalvalidationdatetime is not null and finalvalidationdatetime between ? and ? group by analysiscode,editor order by count(*) desc");
ps.setTimestamp(1,new java.sql.Timestamp(begin.getTime()));
ps.setTimestamp(2,new java.sql.Timestamp(end.getTime()));
rs = ps.executeQuery();
while(rs.next()){
String labcode=rs.getString("labanalysiscode");
String editor=rs.getString("editor");
sb.append("<labtest editor='"+editor+"' code='"+labcode+"' count='"+rs.getInt("total")+"' month='"+i+"' year='"+n+"'/>");
}
rs.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
oc_conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
sb.append("</labtests>");
exportSingleValue(sb.toString(), "lab.1");
MedwanQuery.getInstance().setConfigString("datacenterFirstLabSummaryMonth", new SimpleDateFormat("yyyyMM").format(new Date(lastDay.getTime()+2)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
package SimpleCalculate;
//分数类
class FractionFormat {
private int Numerator; // 分子
private int Denominator; // 分母
public FractionFormat(int numerator, int denominator) {
this.Numerator = numerator;
if (denominator == 0) {
throw new ArithmeticException("分母不能为零");
} else {
this.Denominator = denominator;
}
change();
}
public int[] getNumber() {
return new int[]{getNumerator(), getDenominator()};
}
public int getNumerator() {
return Numerator;
}
public int getDenominator() {
return Denominator;
}
private FractionFormat change() {
int gcd = this.gcd(this.Numerator, this.Denominator);
this.Numerator /= gcd;
this.Denominator /= gcd;
return this;
}
/**
* 最大公因数
*/
private int gcd(int a, int b) {
int mod = a % b;
if (mod == 0) {
return b;
} else {
return gcd(b, mod);
}
}
/**
* 四则运算
*/
public FractionFormat add(FractionFormat second) {
return new FractionFormat(this.Numerator * second.Denominator + second.Numerator * this.Denominator,
this.Denominator * second.Denominator);
}
public FractionFormat sub(FractionFormat second) {
return new FractionFormat(this.Numerator * second.Denominator - second.Numerator * this.Denominator,
this.Denominator * second.Denominator);
}
public FractionFormat multiply(FractionFormat second) {
return new FractionFormat(this.Numerator * second.Numerator,
this.Denominator * second.Denominator);
}
public FractionFormat divide(FractionFormat second) {
return new FractionFormat(this.Numerator * second.Denominator,
this.Denominator * second.Numerator);
}
}
|
package com.networks.ghosttears.user_profiles;
/**
* Created by NetWorks on 8/24/2017.
*/
public class SubAchievement {
private int achievementTarget;
private String achievementDescription;
private int expRewards;
private int coinsRewards;
public SubAchievement(){}
public SubAchievement(String achievementDescription,int expRewards,int coinsRewards,int achievementTarget){
this.achievementDescription = achievementDescription;
this.expRewards = expRewards;
this.coinsRewards = coinsRewards;
this.achievementTarget = achievementTarget;
}
public String getAchievementDescription() {
return achievementDescription;
}
public int getExpRewards() {
return expRewards;
}
public int getCoinsRewards() {
return coinsRewards;
}
public int getAchievementTarget() {
return achievementTarget;
}
}
|
package service;
import java.util.List;
import dao.UserDAO;
import entity.User;
public class UserServiceImpl implements UserService{
private UserDAO userDAO;
//提供UserDAO对象的注入通道
public void setUserDAO(UserDAO userDAO){
this.userDAO=userDAO;
}
@Override
//添加用户
public int saveUser(User user) {
// TODO Auto-generated method stub
int flag=1;
if(userDAO.findById(user.getUser_id())==null){
userDAO.save(user);
return flag;
}
else
{
flag=0;
return flag;
}
}
@Override
public User getUser(String name) {
// TODO Auto-generated method stub
return userDAO.getUser(name);
}
@Override
public void delUser(int id) {
// TODO Auto-generated method stub
if(userDAO.findById(id)!=null){
userDAO.delUser(id);
}
}
@Override
public void updateUser(User user) {
// TODO Auto-generated method stub
if(userDAO.findById(user.getUser_id())!=null){
userDAO.update(user);
}
}
@Override
public User findById(int id) {
// TODO Auto-generated method stub
return userDAO.findById(id);
}
@Override
public List<User> findAll() {
// TODO Auto-generated method stub
return userDAO.findAll();
}
}
|
package com.culturaloffers.maps.services;
import com.culturaloffers.maps.model.Authority;
import org.hibernate.LazyInitializationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static com.culturaloffers.maps.constants.UserConstants.*;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:test-user-geo.properties")
public class AuthorityServiceIntegrationTest {
@Autowired
private AuthorityService authorityService;
@Test
public void testFindById() {
List<Authority> authorities = authorityService.findById(USER_ROLE_ID);
assertEquals(USER_ROLE_ID, authorities.get(0).getId());
}
@Test(expected = LazyInitializationException.class)
public void testFindByIdBad() {
List<Authority> authorities = authorityService.findById(USER_ROLE_ID_BAD);
assertNull(authorities.get(0).getName());
}
@Test
public void testFindByName() {
List<Authority> authorities = authorityService.findByName(USER_ROLE);
assertEquals(USER_ROLE, authorities.get(0).getName());
}
@Test
public void testFindByNameBad() {
List<Authority> authorities = authorityService.findByName(USER_ROLE_BAD);
assertNull(authorities.get(0));
}
}
|
/**
* Formatter
* package provides complete set of tools for formatting Java code
* @author michailremmele
*/
package it.sevenbits.codecorrector.formatter; |
package objects.provider;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import objects.Generic;
import service.utility.UserInteractions;
import java.util.ArrayList;
import static service.background_sim.SimulatorThread.randomNum;
public class Provider extends Generic {
private String account;
public Provider(String idProvider, String name, String account) {
super(idProvider, name);
this.account = account;
}
public Provider() {
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public ArrayList<String> gatherInfo() {
ArrayList<String> s = super.gatherInfo();
s.add(account);
return s;
}
public ArrayList<ArrayList<String>> gatherListedInfo() {
return null;
}
public boolean checkAccNum(){
if(this.account.length()!=24){
return false;
}
if(!Character.isLetter(this.getAccount().charAt(0)) || !Character.isLetter(this.getAccount().charAt(1))){
return false;
}
for(int i = 2;i<24;i++){
try{
Integer.parseInt(this.getAccount().substring(i,i+1));
}catch (NumberFormatException e){
return false;
}
}
return true;
}
public void modifyMe(ArrayList<String> atribMod) {
if (atribMod.contains("IBAN") || atribMod.contains("*")) {
this.setAccount(UserInteractions.strRequest("Introduzca su IBAN"));
if(this.account.equals("random")){
this.setAccount("ES");
do {
this.setAccount(this.getAccount() + randomNum(0, 9));
} while (this.getAccount().length() < 24);
System.out.println(this.account);
}
if(!this.checkAccNum()){
System.out.println("IBAN Invalido");
this.modifyMe(new ArrayList<String>(){{add("IBAN");}});
}
}
}
} |
package org.csikjsce.csi_kjsceofficial.POJO;
/**
* Created by sziraqui on 31/7/17.
*/
public class CouncilMember {
private String name;
private String post;
private String pic_url;
private String dept;
private int id;
CouncilMember(){}
CouncilMember(String name, String post, String pic_url, String dept){
this.name = name;
this.post = post;
this.pic_url = pic_url;
this.dept = dept;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(!( o instanceof CouncilMember))
return false;
else {
CouncilMember f = (CouncilMember) o;
if(post == f.getPost())
return true;
}
return false;
}
}
|
package com.example.hiparkingtest.register_user;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.hiparkingtest.R;
import com.example.hiparkingtest.user.User;
public class RegisterUser extends AppCompatActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
// 프래그먼트 매니저
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_register_container);
//
if(fragment == null){
fragment = new RegisterFragment();
fm.beginTransaction().add(R.id.fragment_register_container, fragment).commit();
}
}
}
|
package com.youkol.sms.core.service;
import com.youkol.sms.core.exception.SmsException;
/**
* 短信查询统计服务接口
*
* @author jackiea
*/
public interface SmsQueryStatsService {
/**
* 查询剩余短信数
*
* @return 返回剩余短信数量
* @throws SmsException 异常信息
*/
public int queryRemainedCount() throws SmsException;
/**
* 查询已发送短信数
*
* @return 返回已发送短信数
* @throws SmsException 异常信息
*/
public int querySendedCount() throws SmsException;
}
|
package com.blue33sun.recipe.ui.activity.category;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.blue33sun.recipe.R;
import com.blue33sun.recipe.model.category.Category;
import com.blue33sun.recipe.model.category.MenuCategory;
import com.blue33sun.recipe.ui.activity.BaseActivity;
import com.blue33sun.recipe.ui.activity.recipe.RecipeListActivity;
import com.blue33sun.recipe.ui.adapter.BaseAdapter;
import com.blue33sun.recipe.ui.adapter.category.CategoryListAdapter;
import com.blue33sun.recipe.utils.ActivityUtils;
import com.blue33sun.recipe.widget.Tipslayout;
import java.util.List;
/**
* ClassName:CategoryListActivity
* Description:
* Author:lanjing
* Date:2017/10/5 10:31
*/
public class CategoryListActivity extends BaseActivity implements BaseAdapter.OnItemClickListener{
public static final String EXTRA_MENU_CATEGORY = "menuCategory";
private RecyclerView mRvCategoryList;
private Tipslayout mTlTipsLayout;
private CategoryListAdapter mAdapter;
private MenuCategory mMenuCategory;
private List<Category> mCategoryList;
// private XRefreshView mXRefreshView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_list);
initView();
setListener();
initData();
}
private void initView() {
mTlTipsLayout = (Tipslayout)findViewById(R.id.tl_tips_layout);
mRvCategoryList = (RecyclerView)findViewById(R.id.rv_category_list);
//FullyGridLayoutManager lm = new FullyGridLayoutManager(this,3);
GridLayoutManager lm = new GridLayoutManager(this,3);
lm.setOrientation(GridLayoutManager.VERTICAL);
mRvCategoryList.setLayoutManager(lm);
mAdapter = new CategoryListAdapter(this);
mRvCategoryList.setAdapter(mAdapter);
}
private void setListener() {
mAdapter.setOnItemClickListener(this);
}
private void initData() {
Intent intent = getIntent();
mMenuCategory = intent.getParcelableExtra(EXTRA_MENU_CATEGORY);
if(mMenuCategory != null){
mCategoryList = mMenuCategory.getList();
if (mCategoryList!=null && mCategoryList.size()>0){
mAdapter.setLists(mCategoryList);
return;
}
}
}
@Override
public void onItemClickListener(View v) {
Category category = (Category) v.getTag();
Bundle bundle = new Bundle();
bundle.putParcelable(RecipeListActivity.EXTRA_CATEGORY,category);
ActivityUtils.goToNextPage(CategoryListActivity.this,RecipeListActivity.class,bundle,false);
}
}
|
/**
*
*/
package net.sf.taverna.t2.component.ui.menu.component;
import static net.sf.taverna.t2.component.ui.menu.component.ComponentMenuSection.COMPONENT_SECTION;
import java.net.URI;
import javax.swing.Action;
import net.sf.taverna.t2.ui.menu.AbstractMenuAction;
/**
* @author alanrw
*
*/
public class ComponentCloseMenuAction extends AbstractMenuAction {
private static final URI CLOSE_COMPONENT_URI = URI
.create("http://taverna.sf.net/2008/t2workbench/menu#componentClose");
private static Action componentCloseAction = new ComponentCloseAction();
public ComponentCloseMenuAction() {
super(COMPONENT_SECTION, 1000, CLOSE_COMPONENT_URI);
}
@Override
protected Action createAction() {
return componentCloseAction;
}
}
|
package fr.fireblaim.javafxhelper.builders;
import javafx.scene.control.Alert;
public class AlertBuilder {
public AlertBuilder(String title, String text, String headerText, Alert.AlertType alertType) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(text);
alert.show();
}
public AlertBuilder(String title, String text, String headerText) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(text);
alert.show();
}
public AlertBuilder(String title, String text, Alert.AlertType alertType) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText("Argh! There is a problem !");
alert.setContentText(text);
alert.show();
}
public AlertBuilder(String title, String text) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText("Argh! There is a problem !");
alert.setContentText(text);
alert.show();
}
}
|
/* ------------------------------------------------------------------------------
*
* 软件名称:泡泡娱乐交友平台(手机版)
* 公司名称:北京双迪信息技术有限公司
* 开发作者:Yongchao.Yang
* 开发时间:2012-8-16/2012
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容仅限于北京双迪信息技术有限公司内部使用 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.power.handler
* fileName:com.power.handler.StreamResponse.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.handler;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* @author Yongchao.Yang
*
*/
public class StreamResponse extends HttpServletResponseWrapper {
public StreamResponse(HttpServletResponse response) {
super(response);
}
}
|
System.out.println("Hello");
System.out.println("2019-06-01 22:12 change");
System.out.println("feature-A");
System.out.println("fix-B");
System.out.println("feature-C");
System.out.println("feature-D update by other");
System.out.println("first master update");
|
package com.android.albumslist.viewmodel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.android.albumslist.api.Api;
import com.android.albumslist.api.Client;
import com.android.albumslist.model.Album;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class AlbumsViewModel extends ViewModel {
Realm realm;
RealmResults<Album> results;
//this is the data that we will fetch asynchronously
private MutableLiveData<List<Album>> albumList;
RealmChangeListener<RealmResults<Album>> realmChangeListener = results -> {
if (results.isLoaded() && results.isValid()) {
albumList.setValue(results);
}
};
public AlbumsViewModel() {
realm = Realm.getDefaultInstance();
results = realm.where(Album.class).findAllAsync();
results.addChangeListener(realmChangeListener);
}
@Override
protected void onCleared() {
super.onCleared();
results.removeChangeListener(realmChangeListener);
realm.close();
realm = null;
}
//we will call this method to get the data
public LiveData<List<Album>> getAlbums() {
//if the list is null
if (albumList == null) {
albumList = new MutableLiveData<List<Album>>();
//we will load it asynchronously from server in this method
loadAlbums();
}
//finally we will return the list
return albumList;
}
//This method is using Retrofit to get the JSON data from URL
private void loadAlbums() {
Api api = com.android.albumslist.api.Client.retrofit.create(Api.class);
Call<List<Album>> call = api.getAlbums();
call.enqueue(new Callback<List<Album>>() {
@Override
public void onResponse(Call<List<Album>> call, Response<List<Album>> response) {
//finally we are setting the list to our MutableLiveData
albumList.setValue(response.body());
// copy the result into realm for future use
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(response.body());
realm.commitTransaction();
realm.close();
}
@Override
public void onFailure(Call<List<Album>> call, Throwable t) {
}
});
}
}
|
package com.thecupboardapp.cupboard;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import java.util.List;
import static android.app.Activity.RESULT_OK;
/**
* Created by Kyle on 1/12/2018.
*/
public class ShoppingListsFragment extends Fragment{
private final String TAG = "ShoppingListsFragment";
private FloatingActionButton mAddListFAB;
private RecyclerView mShoppingListsRecyclerView;
private List<ShoppingList> mShoppingLists;
private ShoppingListAdapter mAdapter;
static final int NEW_LIST_REQUEST = 1;
static final String NEW_LIST_REQUEST_ID =
"com.thecupboardapp.cupboard.new_shopping_list_id";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.title_lists);
mShoppingLists = UserData.get(getActivity()).getShoppingLists();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult: resultcode: " + resultCode);
if (requestCode == NEW_LIST_REQUEST) {
if (resultCode == RESULT_OK) {
mAdapter.notifyDataSetChanged();
Log.d(TAG, "new list result OK!");
} else {
mAdapter.notifyDataSetChanged();
Log.d(TAG, "new list result not ok");
}
}
}
@Override
public void onResume() {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
mAdapter = new ShoppingListAdapter(mShoppingLists);
mShoppingListsRecyclerView.setAdapter(mAdapter);
}
super.onResume();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
View v = inflater.inflate(R.layout.sign_in_fragment, container, false);
return v;
}
View v = inflater.inflate(R.layout.shopping_lists_fragment, container, false);
mAddListFAB = (FloatingActionButton) v.findViewById(R.id.add_list_fab);
mAddListFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ShoppingListActivity.class);
intent.putExtra(NEW_LIST_REQUEST_ID, NEW_LIST_REQUEST);
startActivityForResult(intent, NEW_LIST_REQUEST);
}
});
mShoppingListsRecyclerView = (RecyclerView) v.findViewById(R.id.shopping_lists_recycler_view);
mShoppingListsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int pos = viewHolder.getAdapterPosition();
ShoppingList list = mShoppingLists.get(pos);
mShoppingLists.remove(pos);
mAdapter.notifyItemRemoved(pos);
FirebaseDatabase.getInstance().getReference().child("lists")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(list.getFirebaseId()).removeValue();
Toast.makeText(getActivity(), "List Removed", Toast.LENGTH_SHORT).show();
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(mShoppingListsRecyclerView);
return v;
}
private void updateUI() {
if (mAdapter == null) {
mAdapter = new ShoppingListAdapter(mShoppingLists);
mShoppingListsRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
private class ShoppingListHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private ShoppingList mShoppingList;
private TextView mTitleTextView;
public ShoppingListHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.shopping_list_title_holder, parent, false));
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.shopping_list_title);
}
public void bind(ShoppingList shoppingList) {
mShoppingList = shoppingList;
mTitleTextView.setText(mShoppingList.getName());
}
@Override
public void onClick(View view) {
Intent intent = ShoppingListActivity.newIntent(getActivity(), mShoppingList.getId());
startActivity(intent);
}
}
private class ShoppingListAdapter extends RecyclerView.Adapter<ShoppingListHolder> {
private List<ShoppingList> mShoppingLists;
public ShoppingListAdapter(List<ShoppingList> shoppingLists) {
mShoppingLists = shoppingLists;
}
@Override
public ShoppingListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new ShoppingListHolder(layoutInflater, parent);
}
@Override
public void onBindViewHolder(ShoppingListHolder holder, int position) {
ShoppingList shoppingList = mShoppingLists.get(position);
holder.bind(shoppingList);
}
@Override
public int getItemCount() {
return mShoppingLists.size();
}
}
}
|
package com.gzc.dao.impl;
import com.gzc.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
public void saveAccount(){
System.out.println("保存了账户");
}
}
|
package thundercode.entrenament;
//Leyendo el diccionario
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class P143 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int mult, num, acum;
while((mult = sc.nextInt()) != 0 && (acum = 0) == 0){
while((num = sc.nextInt()) != 0){
acum += num * mult;
}
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date((acum * 1000) - 3600000)));
}
sc.close();
}
} |
package comp1110.ass2;
import java.util.*;
import static comp1110.ass2.Tile.*;
/*******************************************************************************
* Class: playerBoard *
* *
* Integrate storage, mosaic and floor *
* This class is contributed by WmFuZQ==, WXV4aW4= and Qm9nb25n *
* Author of some methods are not specified *
******************************************************************************/
public class PlayerBoard {
private final Player player;
private Storage storage;
private Mosaic mosaic;
private Floor floor;
private int score;
/**
* Player board constructor, initialize an empty player board with a player.
*
* @param player Set the player for player board.
*/
PlayerBoard(Player player) {
this.player = player;
this.storage = Storage.initStorage();
this.floor = Floor.initFloor();
this.score = 0;
}
/**
* Initialize a basic player board by a given player.
*
* @param player The player of a given board
* @return A basic player board
*/
static PlayerBoard initBasicPlayerBoard(Player player) {
PlayerBoard playerBoard = new PlayerBoard(player);
playerBoard.mosaic = Mosaic.initBasicMosaic();
return playerBoard;
}
/**
* Initialize a variant player board by a given player.
*
* @param player The player of a given board
* @return A variant player board
*/
static PlayerBoard initVariantPlayerBoard(Player player) {
PlayerBoard playerBoard = new PlayerBoard(player);
playerBoard.mosaic = Mosaic.initVariantMosaic();
return playerBoard;
}
/**
* Get player of current player board.
*
* @return player of current player board
*/
public Player getPlayer() {
return player;
}
/**
* Get score of current player's board.
*
* @return score of current player board
*/
public int getScore() {
return score;
}
/**
* Get mosaic of current player's board.
*
* @return mosaic of current player board
*/
public Mosaic getMosaic() {
return mosaic;
}
/**
* Get storage of current player's board.
*
* @return storage of current player board
*/
public Storage getStorage() {
return storage;
}
/**
* Get tiles on floor.
*
* @return An array of array of tiles.
* [first 7 tiles on floor, the rest of tiles on floor]
* Format: first element in array: first 7 tiles on floor
* second element in array: the rest of tiles on floor
*/
public Tile[] getTilesOnFloor() {
return floor.getFloor();
}
/**
* Get number of tiles on floor.
*
* @return Number of tiles on floor.
*/
public int getNumOfTilesOnFloor() {
return floor.getNumOfTilesOnFloor();
}
/**
* Check if the player of current player board is the first player in next
* round.
*
* @return True if we have first player token on floor
*/
boolean isFirstPlayer() {
return floor.hasFirstPlayerTokenOnFloor();
}
/**
* Check if current game board is a basic player board or variant player
* board.
*
* @return True if the game board is a basic mosaic board
*/
boolean isBasicMosaic() {
return mosaic.isBasicMosaic();
}
/**
* Determine if a tile can be placed into a row in storage.
*
* @param tile Tile to be placed into storage
* @param rowIndex Row to be placed
* @return If a tile can be placed into a row in storage
*/
public boolean isPlaceableRowInStorage(Tile tile, int rowIndex) {
boolean isStoragePlaceable = storage.isPlaceableRow(tile, rowIndex);
boolean isMosaicPlaceable = mosaic.isPlaceableRow(tile, rowIndex);
return isStoragePlaceable && isMosaicPlaceable;
}
/**
* Get all placeable row in storage by a tile.
*
* @param tile Tile to be placed into storage
* @return All placeable rows
*/
ArrayList<Integer> getPlaceableRowsByTileInStorage(Tile tile) {
ArrayList<Integer> placeableRows = new ArrayList<>();
for (int i = 0; i < 5; i++) {
if (isPlaceableRowInStorage(tile, i)) {
placeableRows.add(i);
}
}
return placeableRows;
}
/**
* Get all the placeable columns in mosaic by row index.
*
* @param rowIndex Index of placeable
* @return All the placeable columns
*/
public ArrayList<Integer> getPlaceableColsInMosaicByRow(int rowIndex) {
if (rowNotFullInStorage(rowIndex)) {
throw new IllegalArgumentException("Row is not full");
}
Tile occupiedTileInStorage = storage.getOccupiedTileByRow(rowIndex);
return mosaic.getPlaceableCols(occupiedTileInStorage, rowIndex);
}
/**
* Take a tiles from factory or centre. Place it into storage.
*
* @param tiles A list of tiles to be placed into storage
* **(Must NOT contain first player token)
* @param rowIndex Row to be placed
* @return Redundant tiles that cannot be placed into storage
*/
public ArrayList<Tile> moveTilesToStorage(ArrayList<Tile> tiles, int rowIndex) {
boolean hasFirstPlayerTokenInTiles = false;
// Remove first player token temporarily.
for (int i = 0; i < tiles.size(); i++) {
Tile currTile = tiles.get(i);
if (currTile == FirstPlayerToken) {
tiles.remove(i);
hasFirstPlayerTokenInTiles = true;
break;
}
}
if (!isPlaceableRowInStorage(tiles.get(0), rowIndex)) {
throw new IllegalArgumentException(
tiles.get(0).toString().toUpperCase()
+ " tile cannot be placed into row "
+ rowIndex
+ " in storage because "
+ tiles.get(0).toString().toUpperCase()
+ " is in " );
} else {
// Return redundant tiles that cannot be placed into storage
ArrayList<Tile> redundantTiles = storage.addMultiTilesToStorage(rowIndex, tiles);
if (hasFirstPlayerTokenInTiles) {
redundantTiles.add(0, FirstPlayerToken);
}
return redundantTiles;
}
}
/**
* Take a tiles from factory or centre. Place it into storage.
*
* @param tiles A list of tiles to be placed into floor
*/
public ArrayList<Tile> moveTilesToFloor(ArrayList<Tile> tiles) {
// Return redundant tiles
return floor.addMultipleTilesToFloor(tiles);
}
/**
* Get all tiles in a player board.
*
* @return All tiles in a player board.
*
* @author WmFuZSBIYWlkZXI=
*/
public ArrayList<Tile> getAllTilesInSinglePlayerBoard(){
ArrayList<Tile> tiles = new ArrayList<>();
List<Tile> listFloor = Arrays.asList(floor.floor);
tiles.addAll(listFloor);
tiles.addAll(convert2DArrayToArrayList(mosaic.mosaicGrids));
tiles.addAll(convert2DArrayToArrayList(storage.storageRows));
return tiles;
}
/**
* Tile tiles from storage to mosaic.
*
* @param rowIndex Index of the row to place tile in mosaic
* @param colIndex Index of the column to place tile in mosaic
*/
public void tileToBasicMosaic(int rowIndex, int colIndex) {
Tile currTile = storage.getOccupiedTileByRow(rowIndex);
mosaic.tileToBasicMosaic(rowIndex, colIndex, currTile);
}
/**
* Tile tiles from storage to mosaic.
*
* @param rowIndex Index of the row to place tile in mosaic
* @param colIndex Index of the column to place tile in mosaic
*/
public void tileToVariantMosaic(int rowIndex, int colIndex) {
Tile currTile = storage.getOccupiedTileByRow(rowIndex);
mosaic.tileToVariantMosaic(rowIndex, colIndex, currTile);
}
/**
* Calculate bonus score for linked tiles after tiling to mosaic
*
* @param rowIndex Index of the row which has placed tile in mosaic
* @param colIndex Index of the column which has placed tile in mosaic
*/
public int addLinkedBonusScoreAfterTiling(int rowIndex, int colIndex) {
int bonus = mosaic.getLinkedTilesBonusScore(rowIndex, colIndex);
score += bonus;
return score;
}
/**
* Remove tiles from a row in storage after tiling.
*
* @param rowIndex The row to be cleared in storage
* @return Tiles which has been removed from storage
* **(To be placed into discard)
*/
public ArrayList<Tile> removeTilesFromStorageByRow(int rowIndex) {
if (storage.getNumOfTilesByRow(rowIndex) == rowIndex + 1) {
ArrayList<Tile> tiles = storage.removeTilesByRow(rowIndex);
tiles.remove(0);
return tiles;
} else {
throw new IllegalArgumentException("Row "
+ rowIndex
+ " is not complete.");
}
}
/**
* Remove tiles from a row in storage after tiling return all tiles in the
* row.
*
* @param rowIndex The row to be cleared in storage
* @return Tiles which has been removed from storage
* **(To be placed into discard)
*/
public ArrayList<Tile> removeAllTilesFromStorageByRow(int rowIndex) {
if (storage.getNumOfTilesByRow(rowIndex) == rowIndex + 1) {
return storage.removeTilesByRow(rowIndex);
} else {
throw new IllegalArgumentException("Row "
+ rowIndex
+ " is not complete.");
}
}
/**
* Get rows that need to be tiled.
*
* @return A list of rows that has completed (untiled rows)
*/
public ArrayList<Integer> getUntiledRows() {
return storage.getCompleteRows();
}
/**
* Calculate points lost for tiles on floor.
*/
public int minusLostScoreOnFloor() {
int numOfTiles = floor.getNumOfTilesOnFloor();
score += switch (numOfTiles) {
case 0 -> 0;
case 1 -> -1;
case 2 -> -2;
case 3 -> -4;
case 4 -> -6;
case 5 -> -8;
case 6 -> -11;
// 7+ tiles on floor
default -> -14;
};
// Make score always greater or equal to 0.
score = Math.max(0, score);
return score;
}
/**
* Empty floor after tiling.
*
* @return Tiles to be placed into DISCARD
*/
public ArrayList<Tile> emptyFloor() {
return floor.emptyFloor();
}
/**
* Determine if we have complete rows in the current game board.
*
* @return If there exists a complete row in current game board
*/
boolean hasCompleteRow() {
for (int i = 0; i < 5; i++) {
if (mosaic.getNumOfTilesByRow(i) == 5) {
return true;
}
}
return false;
}
/**
* Add bonus score at the end of the game.
*
* @author Qm9nb25nIFdhbmc=
*/
public void addBonusScoreAtTheEndOfTheGame() {
score += mosaic.completeRowBonusScore();
score += mosaic.completeColumnBonusScore();
score += mosaic.fiveSameTilesBonusScore();
}
public ArrayList<Integer> getCompleteRowsInMosaic() {
ArrayList<Integer> rows = new ArrayList<>();
for (int i = 0; i < 5; i++) {
if (mosaic.getNumOfTilesByRow(i) == 5) {
rows.add(i);
}
}
return rows;
}
public ArrayList<Integer> getCompleteColumnsInMosaic() {
ArrayList<Integer> columns = new ArrayList<>();
for (int i = 0; i < 5; i++) {
if (mosaic.getNumOfTilesByCol(i) == 5) {
columns.add(i);
}
}
return columns;
}
public ArrayList<Tile> getCompletePattern() {
LinkedHashMap<Tile, Integer> tileCount = new LinkedHashMap<>();
for (int rowIndex = 0; rowIndex < 5; rowIndex++) {
for (int colIndex = 0; colIndex < 5; colIndex++) {
Tile tile = mosaic.getTileByRowAndCol(rowIndex, colIndex);
if (tile != null) {
tileCount.merge(tile, 1, Integer::sum);
}
}
}
ArrayList<Tile> completeTiles = new ArrayList<>();
for (Map.Entry<Tile, Integer> entry : tileCount.entrySet()) {
if (entry.getValue().equals(5)) {
completeTiles.add(entry.getKey());
}
}
return completeTiles;
}
/**
* Convert player board to its string representation.
*
* @return String representation of player board.
*/
String toPlayerState() {
return player.getId() + score +
'M' + mosaic.toMosaicString() +
'S' + storage.toStorageString() +
'F' + floor.toFloorString();
}
/**
* Convert a player state(String) into player board
*
* @param singlePlayerState String representation of game state.
*/
static PlayerBoard parsePlayerBoardFromSinglePlayerState(String singlePlayerState) {
// Split string by components in player's board.
String[] splitPlayerState = singlePlayerState.split("(?=\\s.|M|S|F)");
String playerAndScore = splitPlayerState[0];
Player player = Player.getPlayerById(playerAndScore.charAt(0));
PlayerBoard playerBoard = initVariantPlayerBoard(player);
playerBoard.score = Integer.parseInt(playerAndScore.substring(1));
/* If a mosaicStr can be processed into basic mosaic OR variant mosaic,
* convert to into basic mosaic.
* If a mosaic can ONLY be processed into variant mosaic, convert it into
* variant mosaic. */
String mosaicString = splitPlayerState[1].substring(1);
playerBoard.mosaic = Mosaic.parseFromMosaicString(mosaicString);
String storageString = splitPlayerState[2].substring(1);
playerBoard.storage = Storage.parseFromStorageString(storageString);
String floorString = splitPlayerState[3].substring(1);
playerBoard.floor = Floor.parseFloorFromString(floorString);
return playerBoard;
}
/**
* Convert a full player state(String) into a list of player board.
*
* @param playerStates A consecutive player state
* @return A list of player states
*/
static PlayerBoard[] parsePlayerBoardFromPlayerState(String playerStates) {
// Split by players.
String[] splitPlayerStatesByPlayers
= playerStates.split("(?=\\sA|B|C|D)");
PlayerBoard[] playerBoards = new PlayerBoard[splitPlayerStatesByPlayers.length];
// Get number of players.
int numOfPlayers = splitPlayerStatesByPlayers.length;
// Set player boards.
for (int i = 0; i < numOfPlayers; i++) {
String currPlayerStateStr = splitPlayerStatesByPlayers[i];
playerBoards[i] = PlayerBoard.
parsePlayerBoardFromSinglePlayerState(currPlayerStateStr);
}
/* Check if the player boards mixed basic player boards with variant
* player boards. */
boolean hasVariantBoard = false;
for (PlayerBoard playerBoard : playerBoards) {
if (!playerBoard.isBasicMosaic()) {
hasVariantBoard = true;
break;
}
}
if (hasVariantBoard) {
for (PlayerBoard playerBoard : playerBoards) {
playerBoard.convertToVariantMosaic();
}
}
return playerBoards;
}
/**
* Check if Storage is working harmony with Mosaic.
* <p>
* @return True if satisfies the following condition:
* The tile(s) occupied in a Storage row should not exists on Mosaic
*/
boolean isValidStorageAndMosaic() {
for (int i =0; i<mosaic.mosaicGrids.length; i++){
if (storage.getOccupiedTileByRow(i)!= null) {
if (Arrays.asList(mosaic.mosaicGrids[i]).contains(storage.getOccupiedTileByRow(i))){
return false;
}
}
}
return true;
}
/**
* Check if a row is full in storage.
*
* @param rowIndex Index of a row
* @return True if a row is full
*/
boolean rowNotFullInStorage(int rowIndex) {
return storage.getNumOfTilesByRow(rowIndex) != rowIndex + 1;
}
/**
* Convert a basic player board to variant player board.
*/
void convertToVariantMosaic() {
mosaic.convertToVariantMosaic();
}
@Override
public String toString() {
String[] storageRowsString = storage.toRowsString();
String[] mosaicRowsString = mosaic.toRowsString();
StringBuilder sb = new StringBuilder();
sb.append("\nCurrent Player: ");
sb.append(player);
sb.append("\nCurrent Score: ");
sb.append(score);
sb.append("\nStorage:");
String gap = " ";
sb.append(" ".repeat(storageRowsString[0].length()));
sb.append("Mosaic:\n");
for (int i = 0; i < 5; i++) {
sb.append(storageRowsString[i]);
sb.append(gap);
sb.append(mosaicRowsString[i]);
sb.append("\n");
}
sb.append("\nFloor: ");
sb.append(floor);
return sb.toString();
}
} |
package com.parser;
import java.util.ArrayList;
import java.lang.StringBuilder;
public class ParseStack {
private ArrayList<SyntaxNode> data = new ArrayList<SyntaxNode>();
public void push(SyntaxNode input) {
data.add(0, input);
}
public SyntaxNode at(int x) {
return data.get(x);
}
public ArrayList<SyntaxNode> pop(int amount) {
ArrayList<SyntaxNode> result = new ArrayList<SyntaxNode>();
for (int x = 0; x < amount; x++) {
result.add(data.get(0));
data.remove(0);
}
return result;
}
public ArrayList<SyntaxNode> peek(int amount) {
ArrayList<SyntaxNode> result = new ArrayList<SyntaxNode>();
for (int x = 0; x < amount; x++) {
result.add(data.get(x));
}
return result;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (SyntaxNode s : data) {
sb.append(s.getType() + "\n");
}
return sb.toString();
}
public int size() {
return data.size();
}
} |
package elements;
import java.util.LinkedList;
public class BinarySearchTree {
public Node root;
public BinarySearchTree(Node root){
this.root=root;
}
public void toPrintf(int level){
LinkedList<Node> thislevel = new LinkedList<Node>();
LinkedList<Node> nextlevel = new LinkedList<Node>();
thislevel.add(root);
do{
nextlevel.clear();
for(int i=0;i<level;i++){
System.out.print(" ");
}
while(!thislevel.isEmpty()){
Node courrant = thislevel.remove();
System.out.print(courrant.value());
if(courrant.value!=-1 && courrant.left!=null){
nextlevel.add(courrant.left);
}else if(courrant.value!=-1 && courrant.left==null){
nextlevel.add(new Node(-1));
}
if(courrant.value!=-1 && courrant.right!=null){
nextlevel.add(courrant.right);
}else if(courrant.value!=-1 && courrant.right==null){
nextlevel.add(new Node(-1));
}
System.out.print(" ");
}
level--;
System.out.println();
System.out.println();
thislevel.addAll(nextlevel);
}while(!nextlevel.isEmpty());
}
public Node search(Node x, int k){
x.lock.lock();
while(x!=null && k!= x.value){
if(x.left!=null){
x.left.lock.lock();
}if(x.right!=null){
x.right.lock.lock();
}
x.lock.unlock();
if(k<x.value){
if(x.right!=null){
x.right.lock.unlock();
}
x=x.left;
}else{
if(x.left!=null){
x.left.lock.unlock();
}
x=x.right;
}
}
x.lock.unlock();
return x;
}
public Node minimum(Node x){
x.lock.lock();
try{
while(x.left!=null){
x.left.lock.lock();
x=x.left;
x.parent.lock.unlock();
}
}finally{
x.lock.unlock();
}
return x;
}
public Node maximum(Node x){
x.lock.lock();
try{
while(x.right!=null){
x.left.lock.lock();
x=x.right;
x.parent.lock.unlock();
}
}finally{
x.lock.unlock();
}
return x;
}
public void insert(int x){
Node z = new Node(x);
Node y=null;
Node k=root;
k.lock.lock();
while(k!=null){
if(k.left!=null){
k.left.lock.lock();
}if(k.right!=null){
k.right.lock.lock();
}
k.lock.unlock();
y=k;
if(z.value<k.value){
if(k.right!=null){
k.right.lock.unlock();
}
k=k.left;
}else{
if(k.left!=null){
k.left.lock.unlock();
}
k=k.right;
}
}
z.parent=y;
if(z.value<y.value){
y.left=z;
}else{
y.right=z;
}
}
/**
* replaces subtree rooted at u with that rooted at v
* @param u a : Node
* @param v a : Node
*/
private void transplant(Node u, Node v){
if(u.parent==null){
root=v;
}else if(u.parent.left==u){
u.parent.left=v;
}else{
u.parent.right=v;
}
if(v!=null){
v.parent=u.parent;
}
}
public void delete(int x){
Node z = search(root, x);
z.lock.lock();
if(z.left==null){
z.parent.lock.lock();
if(z.right!=null){
z.right.lock.lock();
}
transplant(z, z.right);
z.parent.lock.unlock();
if(z.right!=null){
z.right.lock.unlock();
}
}else if(z.right==null){
z.parent.lock.lock();
if(z.left!=null){
z.left.lock.lock();
}
transplant(z, z.left);
z.parent.lock.unlock();
if(z.left!=null){
z.left.lock.unlock();
}
}else{
Node y = minimum(z.right);
y.lock.lock();
if(y.parent!=z){
transplant(y, y.right);
y.right=z.right;
y.right.parent=y;
}
transplant(z, y);
y.left=z.left;
y.left.parent=y;
y.lock.unlock();
}
}
}
|
package KataProblems.week5.SortTheOdd;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class SortTheOddTest {
@Test
public void exampleTest1() {
assertArrayEquals(new int[]{ 1, 3, 2, 8, 5, 4 }, SortTheOdd.sortArray(new int[]{ 5, 3, 2, 8, 1, 4 }));
}
@Test
public void exampleTest2() {
assertArrayEquals(new int[]{ 1, 3, 5, 8, 0 }, SortTheOdd.sortArray(new int[]{ 5, 3, 1, 8, 0 }));
}
@Test
public void exampleTest3() {
assertArrayEquals(new int[]{}, SortTheOdd.sortArray(new int[]{}));
}
@Test
public void exampleTest4() {
assertArrayEquals(new int[]{1}, SortTheOdd.sortArray(new int[]{1}));
}
@Test
public void exampleTest5() {
assertArrayEquals(new int[]{2}, SortTheOdd.sortArray(new int[]{2}));
}
@Test
public void exampleTest6() {
assertArrayEquals(new int[]{-1,3,5}, SortTheOdd.sortArray(new int[]{5,3,-1}));
}
}
|
package com.wepay.resource;
import com.wepay.helpers.Utilities;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("accounts")
public class AccountsResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response accountLookUp(@PathParam("id") final String accountId) {
return Response.ok().entity(Utilities.accountLookUp(accountId)).build();
}
@GET
@Path("{id}/capabilities")
@Produces(MediaType.APPLICATION_JSON)
public Response accountCapabilitiesLookUp(@PathParam("id") final String accountId) {
return Response.ok().entity(Utilities.accountCapabilitiesLookUp(accountId)).build();
}
}
|
package com.ddsolutions.rsvp.kinesis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import software.amazon.kinesis.processor.ShardRecordProcessor;
import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
import java.util.function.Supplier;
@Component(BeanDefinition.SCOPE_PROTOTYPE)
public class EventProcessorFactory implements ShardRecordProcessorFactory {
private Supplier<KinesisRecordProcessor> kinesisRecordProcessor;
@Autowired
public EventProcessorFactory(Supplier<KinesisRecordProcessor> kinesisRecordProcessor) {
this.kinesisRecordProcessor = kinesisRecordProcessor;
}
@Override
public ShardRecordProcessor shardRecordProcessor() {
return kinesisRecordProcessor.get();
}
}
|
package oim;
import java.util.*;
import javax.security.auth.login.LoginException;
import oracle.iam.accesspolicy.api.AccessPolicyService;
import oracle.iam.accesspolicy.vo.AccessPolicy;
import oracle.iam.accesspolicy.vo.AccessPolicy.OwnerType;
import oracle.iam.accesspolicy.vo.AccessPolicyElement;
import oracle.iam.accesspolicy.vo.AccessPolicyElement.ACTION_IF_NOT_APPLICABLE;
import oracle.iam.accesspolicy.vo.ChildAttribute;
import oracle.iam.accesspolicy.vo.ChildRecord;
import oracle.iam.accesspolicy.vo.DefaultData;
import oracle.iam.accesspolicy.vo.Record;
import oracle.iam.identity.rolemgmt.api.RoleManager;
import oracle.iam.identity.rolemgmt.api.RoleManagerConstants;
import oracle.iam.identity.rolemgmt.vo.Role;
import oracle.iam.platform.OIMClient;
import oracle.iam.platform.entitymgr.vo.SearchCriteria;
import oracle.iam.platform.entitymgr.vo.SearchCriteria.Operator;
import oracle.iam.provisioning.api.ApplicationInstanceService;
import oracle.iam.provisioning.vo.ApplicationInstance;
import oracle.iam.provisioning.vo.FormField;
import oracle.iam.provisioning.vo.FormInfo;
public class Main {
private static OIMClient oimClient;
private static final String AUTH_CONF = "<path to authwl.conf>";
private static final String APPSERVER_TYPE = "wls";
private static final String WEBLOGIC_NAME = "wls_oim1";
private static String ctxFactory = "weblogic.jndi.WLInitialContextFactory";
private static String serverURL = "t3://host:port";
private static String username = ">username>";
char[] password = "<Password>".toCharArray();
Properties envProp = new Properties();
public void init() throws LoginException {
System.out.println("====================Creating client....");
System.setProperty("java.security.auth.login.config", AUTH_CONF);
System.setProperty("APPSERVER_TYPE", APPSERVER_TYPE);
System.setProperty("weblogic.Name", WEBLOGIC_NAME);
envProp.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
envProp.put(OIMClient.JAVA_NAMING_PROVIDER_URL, serverURL);
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, ctxFactory);
env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, serverURL);
oimClient = new OIMClient(env);
System.out.println("Logging in");
oimClient.login(username, password);
System.out.println("Log in successful\n");
}
public static void main(String args[]) {
try {
Main oimSample = new Main();
oimSample.init();
// INPUT
String line = "Global Catalog;AD_VIA_API;cn=GC_RA_KIPOINT,ou=GC_AP_CONSULENTI,ou=applicazioni,dc=posteitaliane,dc=it";
System.out.println("splito la riga");
String[] arrayline = line.split(";");
if (arrayline.length != 3) {
System.out.println("\t errore line");
return;
}
String target = arrayline[0];
String rolename = arrayline[1];
String ent = arrayline[2];
// RUOLO
System.out.println("check esistenza ruolo: " + rolename);
RoleManager rolemanager = oimClient.getService(RoleManager.class);
SearchCriteria searchcrit = new SearchCriteria(RoleManagerConstants.ROLE_NAME, rolename, Operator.EQUAL);
Set<String> retAttrs = new HashSet<>();
List<Role> rmsearch = rolemanager.search(searchcrit, retAttrs, null);
System.out.println(rmsearch.size());
Role myrole = null;
if (rmsearch.size() == 1) {
for (Iterator<Role> iterator = rmsearch.iterator(); iterator.hasNext();) {
Role role = iterator.next();
myrole = role;
System.out.println("\t" + role.getDisplayName());
}
} else {
System.out.println("\terrore multipli ruoli");
return;
}
// APPLICATION INSTANCE
System.out.println("check esistenza target: " + target);
ApplicationInstance myappInstance = null;
FormInfo mychildform = null;
ApplicationInstanceService ais = oimClient.getService(ApplicationInstanceService.class);
SearchCriteria searchai = new SearchCriteria(ApplicationInstance.DISPLAY_NAME, target, Operator.EQUAL);
List<ApplicationInstance> ai = ais.findApplicationInstance(searchai, null);
System.out.println(ai.size());
if (ai.size() == 1) {
for (Iterator<ApplicationInstance> iterator = ai.iterator(); iterator.hasNext();) {
ApplicationInstance applicationInstance = (ApplicationInstance) iterator.next();
if (applicationInstance.getDisplayName().equals(target)) {
System.out.println("\t" + applicationInstance.getDisplayName());
myappInstance = applicationInstance;
List<FormInfo> childforms = applicationInstance.getChildForms();
for (Iterator<FormInfo> iterator2 = childforms.iterator(); iterator2.hasNext();) {
FormInfo childform = iterator2.next();
String tmp = childform.getName();
if (tmp.equals("UD_ADUSRC") || tmp.equals("UD_ADAMUSRC") || tmp.equals("UD_ALDSUSRC")
|| tmp.equals("UD_GC_GRP") || tmp.equals("UD_SAPRLBW") || tmp.equals("UD_SAPRLCRM")
|| tmp.equals("UD_SAPRL")) {
mychildform = childform;
System.out.println("\t\tmychildform: " + mychildform.getName());
}
System.out.println("\tchildform: " + tmp);
}
} else {
System.out.println("\terrore target non trovato");
return;
}
}
} else {
System.out.println("\terrore inesistenza/multipli Application Instance");
return;
}
// ACCESS POLICY
System.out.println("check esistenza access policy: " + "AP_" + rolename);
AccessPolicyService aps = oimClient.getService(AccessPolicyService.class);
SearchCriteria searchap = new SearchCriteria(AccessPolicy.ATTRIBUTE.NAME.getID(), "AP_" + rolename,
Operator.EQUAL);
List<AccessPolicy> listaap = aps.findAccessPolicies(searchap, null);
System.out.println(listaap.size());
if (listaap.size() == 0) {
// ADD ENTITLEMENT
System.out.println("\n\ncreating AP...");
List<AccessPolicyElement> elements = new ArrayList<AccessPolicyElement>();
AccessPolicyElement ape = new AccessPolicyElement(myappInstance.getApplicationInstanceKey(), false,
ACTION_IF_NOT_APPLICABLE.DISABLE);
DefaultData defaultData = new DefaultData();
Map<String, String> attrs = new HashMap<String, String>();
List<FormField> formfields = mychildform.getFormFields();
for (Iterator<FormField> iterator = formfields.iterator(); iterator.hasNext();) {
FormField f = iterator.next();
String formfield = f.getName();
System.out.println("\t" + formfield);
if (formfield.equals("UD_ADUSRC_GROUPNAME") || formfield.equals("UD_ADAMUSRC_GROUPNAME")
|| formfield.equals("UD_ALDSUSRC_GROUPNAME") || formfield.equals("UD_GC_GRP_GROUP_NAME")
|| formfield.equals("UD_SAPRLBW_USERROLE") || formfield.equals("UD_SAPRLCRM_USERROLE")
|| formfield.equals("UD_SAPRL_USERROLE")) {
attrs.put(formfield, myappInstance.getItResourceKey() + "~" + ent);
}
}
ChildRecord r = new ChildRecord(mychildform.getName(), 1, attrs);
defaultData.addChildData(r);
ape.setDefaultData(defaultData);
elements.add(0, ape);
// CREATE
long priority = aps.getLowestPriority() + 1;
AccessPolicy ap = new AccessPolicy("AP_" + rolename, "ap di " + rolename, true, priority,
OwnerType.USER, "1");
ap.setPolicyElements(elements);
aps.createAccessPolicy(ap);
System.out.println("AP_" + rolename + " created");
} else if (listaap.size() == 1) {
// update
System.out.println("\n\nupdating AP...");
// My access policy
AccessPolicy myap = aps.getAccessPolicy(listaap.get(0).getEntityId(), true);
// account provisioned
long myobjkey = myappInstance.getObjectKey();
List<AccessPolicyElement> pe = myap.getPolicyElements();
System.out.println("\taccount provisioned: " + pe.size());
for (Iterator<AccessPolicyElement> iterator = pe.iterator(); iterator.hasNext();) {
AccessPolicyElement accessPolicyElement = (AccessPolicyElement) iterator.next();
if (accessPolicyElement.getResourceObjectID() == myobjkey) {
System.out.println("\taccount gia esiste");
List<ChildRecord> childsdata = accessPolicyElement.getDefaultData().getChildData();
for (Iterator<ChildRecord> iterator2 = childsdata.iterator(); iterator2.hasNext();) {
ChildRecord childRecord = (ChildRecord) iterator2.next();
List<ChildAttribute> attrs = childRecord.getAttributes();
for (Iterator<ChildAttribute> iterator3 = attrs.iterator(); iterator3.hasNext();) {
ChildAttribute childAttribute = iterator3.next();
if (childAttribute.getAttributeValue().contains(ent)) {
System.out.println("\tentitlement gia esiste");
return;
}
}
}
System.out.println("\tset entitlement");
if (accessPolicyElement.getResourceObjectID() == myobjkey) {
Map<String, String> attrs1 = new HashMap<String, String>();
List<FormField> formfields = mychildform.getFormFields();
for (Iterator<FormField> iterator11 = formfields.iterator(); iterator11.hasNext();) {
FormField f = iterator11.next();
String formfield = f.getName();
System.out.println("\t" + formfield);
if (formfield.equals("UD_ADUSRC_GROUPNAME") || formfield.equals("UD_ADAMUSRC_GROUPNAME")
|| formfield.equals("UD_ALDSUSRC_GROUPNAME")
|| formfield.equals("UD_GC_GRP_GROUP_NAME")
|| formfield.equals("UD_SAPRLBW_USERROLE")
|| formfield.equals("UD_SAPRLCRM_USERROLE")
|| formfield.equals("UD_SAPRL_USERROLE")) {
attrs1.put(formfield, myappInstance.getItResourceKey() + "~" + ent);
}
}
ChildRecord r = new ChildRecord(mychildform.getName(), 1, attrs1);
childsdata.add(r);
aps.updateAccessPolicy(myap);
System.out.println("\t entitlement set");
return;
}
}
}
System.out.println("\t set account and entitlment entitlement");
List<AccessPolicyElement> elements = myap.getPolicyElements();
AccessPolicyElement ape = new AccessPolicyElement(myappInstance.getApplicationInstanceKey(), false,
ACTION_IF_NOT_APPLICABLE.DISABLE);
DefaultData defaultData = new DefaultData();
Map<String, String> attrs = new HashMap<String, String>();
List<FormField> formfields = mychildform.getFormFields();
for (Iterator<FormField> iterator = formfields.iterator(); iterator.hasNext();) {
FormField f = iterator.next();
String formfield = f.getName();
System.out.println("\t" + formfield);
if (formfield.equals("UD_ADUSRC_GROUPNAME") || formfield.equals("UD_ADAMUSRC_GROUPNAME")
|| formfield.equals("UD_ALDSUSRC_GROUPNAME") || formfield.equals("UD_GC_GRP_GROUP_NAME")
|| formfield.equals("UD_SAPRLBW_USERROLE") || formfield.equals("UD_SAPRLCRM_USERROLE")
|| formfield.equals("UD_SAPRL_USERROLE")) {
attrs.put(formfield, myappInstance.getItResourceKey() + "~" + ent);
}
}
ChildRecord r = new ChildRecord(mychildform.getName(), 1, attrs);
defaultData.addChildData(r);
ape.setDefaultData(defaultData);
elements.add(0, ape);
// CREATE
long priority = aps.getLowestPriority() + 1;
AccessPolicy ap = new AccessPolicy("AP_" + rolename, "ap di " + rolename, true, priority,
OwnerType.USER, "1");
ap.setPolicyElements(elements);
aps.updateAccessPolicy(myap);
System.out.println(myap.getName()+" updated");
return;
} else {
System.out.println("\terror access policy multiple");
return;
}
oimClient.logout();
System.out.println("Log out successful");
} catch (
Exception e) {
e.printStackTrace();
}
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.lang.reflect.Constructor;
import java.sql.BatchUpdateException;
import java.sql.SQLException;
import java.util.Arrays;
import javax.sql.DataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.PermissionDeniedDataAccessException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.InvalidResultSetAccessException;
import org.springframework.lang.Nullable;
import org.springframework.util.function.SingletonSupplier;
import org.springframework.util.function.SupplierUtils;
/**
* Implementation of {@link SQLExceptionTranslator} that analyzes vendor-specific error codes.
* More precise than an implementation based on SQL state, but heavily vendor-specific.
*
* <p>This class applies the following matching rules:
* <ul>
* <li>Try custom translation implemented by any subclass. Note that this class is
* concrete and is typically used itself, in which case this rule doesn't apply.
* <li>Apply error code matching. Error codes are obtained from the SQLErrorCodesFactory
* by default. This factory loads a "sql-error-codes.xml" file from the class path,
* defining error code mappings for database names from database meta-data.
* <li>Fallback to a fallback translator. {@link SQLStateSQLExceptionTranslator} is the
* default fallback translator, analyzing the exception's SQL state only. Since Java 6
* which introduces its own {@code SQLException} subclass hierarchy, we use
* {@link SQLExceptionSubclassTranslator} by default, which in turns falls back
* to Spring's own SQL state translation when not encountering specific subclasses.
* </ul>
*
* <p>The configuration file named "sql-error-codes.xml" is by default read from
* this package. It can be overridden through a file of the same name in the root
* of the class path (e.g. in the "/WEB-INF/classes" directory), as long as the
* Spring JDBC package is loaded from the same ClassLoader.
*
* <p>This translator is commonly used by default if a user-provided `sql-error-codes.xml`
* file has been found in the root of the classpath, as a signal to use this strategy.
* Otherwise, {@link SQLExceptionSubclassTranslator} serves as the default translator
* as of 6.0.
*
* @author Rod Johnson
* @author Thomas Risberg
* @author Juergen Hoeller
* @author Sam Brannen
* @see SQLErrorCodesFactory
* @see SQLStateSQLExceptionTranslator
*/
public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExceptionTranslator {
private static final int MESSAGE_ONLY_CONSTRUCTOR = 1;
private static final int MESSAGE_THROWABLE_CONSTRUCTOR = 2;
private static final int MESSAGE_SQLEX_CONSTRUCTOR = 3;
private static final int MESSAGE_SQL_THROWABLE_CONSTRUCTOR = 4;
private static final int MESSAGE_SQL_SQLEX_CONSTRUCTOR = 5;
private static final boolean userProvidedErrorCodesFilePresent =
new ClassPathResource(SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH,
SQLErrorCodesFactory.class.getClassLoader()).exists();
@Nullable
private SingletonSupplier<SQLErrorCodes> sqlErrorCodes;
/**
* Constructor for use as a JavaBean.
* The SqlErrorCodes or DataSource property must be set.
*/
public SQLErrorCodeSQLExceptionTranslator() {
setFallbackTranslator(new SQLExceptionSubclassTranslator());
}
/**
* Create an SQL error code translator for the given DataSource.
* Invoking this constructor will cause a Connection to be obtained
* from the DataSource to get the meta-data.
* @param dataSource the DataSource to use to find meta-data and establish
* which error codes are usable
* @see SQLErrorCodesFactory
*/
public SQLErrorCodeSQLExceptionTranslator(DataSource dataSource) {
this();
setDataSource(dataSource);
}
/**
* Create an SQL error code translator for the given database product name.
* Invoking this constructor will avoid obtaining a Connection from the
* DataSource to get the meta-data.
* @param dbName the database product name that identifies the error codes entry
* @see SQLErrorCodesFactory
* @see java.sql.DatabaseMetaData#getDatabaseProductName()
*/
public SQLErrorCodeSQLExceptionTranslator(String dbName) {
this();
setDatabaseProductName(dbName);
}
/**
* Create an SQLErrorCode translator given these error codes.
* Does not require a database meta-data lookup to be performed using a connection.
* @param sec error codes
*/
public SQLErrorCodeSQLExceptionTranslator(SQLErrorCodes sec) {
this();
this.sqlErrorCodes = SingletonSupplier.of(sec);
}
/**
* Set the DataSource for this translator.
* <p>Setting this property will cause a Connection to be obtained from
* the DataSource to get the meta-data.
* @param dataSource the DataSource to use to find meta-data and establish
* which error codes are usable
* @see SQLErrorCodesFactory#getErrorCodes(javax.sql.DataSource)
* @see java.sql.DatabaseMetaData#getDatabaseProductName()
*/
public void setDataSource(DataSource dataSource) {
this.sqlErrorCodes =
SingletonSupplier.of(() -> SQLErrorCodesFactory.getInstance().resolveErrorCodes(dataSource));
this.sqlErrorCodes.get(); // try early initialization - otherwise the supplier will retry later
}
/**
* Set the database product name for this translator.
* <p>Setting this property will avoid obtaining a Connection from the DataSource
* to get the meta-data.
* @param dbName the database product name that identifies the error codes entry
* @see SQLErrorCodesFactory#getErrorCodes(String)
* @see java.sql.DatabaseMetaData#getDatabaseProductName()
*/
public void setDatabaseProductName(String dbName) {
this.sqlErrorCodes = SingletonSupplier.of(SQLErrorCodesFactory.getInstance().getErrorCodes(dbName));
}
/**
* Set custom error codes to be used for translation.
* @param sec custom error codes to use
*/
public void setSqlErrorCodes(@Nullable SQLErrorCodes sec) {
this.sqlErrorCodes = SingletonSupplier.ofNullable(sec);
}
/**
* Return the error codes used by this translator.
* Usually determined via a DataSource.
* @see #setDataSource
*/
@Nullable
public SQLErrorCodes getSqlErrorCodes() {
return SupplierUtils.resolve(this.sqlErrorCodes);
}
@SuppressWarnings("deprecation")
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
SQLException sqlEx = ex;
if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
SQLException nestedSqlEx = sqlEx.getNextException();
if (nestedSqlEx.getErrorCode() > 0 || nestedSqlEx.getSQLState() != null) {
sqlEx = nestedSqlEx;
}
}
// First, try custom translation from overridden method.
DataAccessException dae = customTranslate(task, sql, sqlEx);
if (dae != null) {
return dae;
}
// Next, try the custom SQLException translator, if available.
SQLErrorCodes sqlErrorCodes = getSqlErrorCodes();
if (sqlErrorCodes != null) {
SQLExceptionTranslator customTranslator = sqlErrorCodes.getCustomSqlExceptionTranslator();
if (customTranslator != null) {
dae = customTranslator.translate(task, sql, sqlEx);
if (dae != null) {
return dae;
}
}
}
// Check SQLErrorCodes with corresponding error code, if available.
if (sqlErrorCodes != null) {
String errorCode;
if (sqlErrorCodes.isUseSqlStateForTranslation()) {
errorCode = sqlEx.getSQLState();
}
else {
// Try to find SQLException with actual error code, looping through the causes.
// E.g. applicable to java.sql.DataTruncation as of JDK 1.6.
SQLException current = sqlEx;
while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException sqlException) {
current = sqlException;
}
errorCode = Integer.toString(current.getErrorCode());
}
if (errorCode != null) {
// Look for defined custom translations first.
CustomSQLErrorCodesTranslation[] customTranslations = sqlErrorCodes.getCustomTranslations();
if (customTranslations != null) {
for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) {
if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0 &&
customTranslation.getExceptionClass() != null) {
dae = createCustomException(task, sql, sqlEx, customTranslation.getExceptionClass());
if (dae != null) {
logTranslation(task, sql, sqlEx, true);
return dae;
}
}
}
}
// Next, look for grouped error codes.
if (Arrays.binarySearch(sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new BadSqlGrammarException(task, (sql != null ? sql : ""), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getInvalidResultSetAccessCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new InvalidResultSetAccessException(task, (sql != null ? sql : ""), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getDuplicateKeyCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new DuplicateKeyException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getDataIntegrityViolationCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getPermissionDeniedCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new PermissionDeniedDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getDataAccessResourceFailureCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getTransientDataAccessResourceCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new TransientDataAccessResourceException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new org.springframework.dao.DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
}
else if (Arrays.binarySearch(sqlErrorCodes.getCannotSerializeTransactionCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new org.springframework.dao.CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx);
}
}
}
// We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator.
if (logger.isDebugEnabled()) {
String codes;
if (sqlErrorCodes != null && sqlErrorCodes.isUseSqlStateForTranslation()) {
codes = "SQL state '" + sqlEx.getSQLState() + "', error code '" + sqlEx.getErrorCode();
}
else {
codes = "Error code '" + sqlEx.getErrorCode() + "'";
}
logger.debug("Unable to translate SQLException with " + codes + ", will now try the fallback translator");
}
return null;
}
/**
* Subclasses can override this method to attempt a custom mapping from
* {@link SQLException} to {@link DataAccessException}.
* @param task readable text describing the task being attempted
* @param sql the SQL query or update that caused the problem (may be {@code null})
* @param sqlEx the offending SQLException
* @return {@code null} if no custom translation applies, otherwise a {@link DataAccessException}
* resulting from custom translation. This exception should include the {@code sqlEx} parameter
* as a nested root cause. This implementation always returns {@code null}, meaning that the
* translator always falls back to the default error codes.
* @deprecated as of 6.1, in favor of {@link #setCustomTranslator}
*/
@Deprecated(since = "6.1")
@Nullable
protected DataAccessException customTranslate(String task, @Nullable String sql, SQLException sqlEx) {
return null;
}
/**
* Create a custom {@link DataAccessException}, based on a given exception
* class from a {@link CustomSQLErrorCodesTranslation} definition.
* @param task readable text describing the task being attempted
* @param sql the SQL query or update that caused the problem (may be {@code null})
* @param sqlEx the offending SQLException
* @param exceptionClass the exception class to use, as defined in the
* {@link CustomSQLErrorCodesTranslation} definition
* @return {@code null} if the custom exception could not be created, otherwise
* the resulting {@link DataAccessException}. This exception should include the
* {@code sqlEx} parameter as a nested root cause.
* @see CustomSQLErrorCodesTranslation#setExceptionClass
*/
@Nullable
protected DataAccessException createCustomException(
String task, @Nullable String sql, SQLException sqlEx, Class<?> exceptionClass) {
// Find appropriate constructor for the given exception class
try {
int constructorType = 0;
Constructor<?>[] constructors = exceptionClass.getConstructors();
for (Constructor<?> constructor : constructors) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
if (parameterTypes.length == 1 && String.class == parameterTypes[0] &&
constructorType < MESSAGE_ONLY_CONSTRUCTOR) {
constructorType = MESSAGE_ONLY_CONSTRUCTOR;
}
if (parameterTypes.length == 2 && String.class == parameterTypes[0] &&
Throwable.class == parameterTypes[1] &&
constructorType < MESSAGE_THROWABLE_CONSTRUCTOR) {
constructorType = MESSAGE_THROWABLE_CONSTRUCTOR;
}
if (parameterTypes.length == 2 && String.class == parameterTypes[0] &&
SQLException.class == parameterTypes[1] &&
constructorType < MESSAGE_SQLEX_CONSTRUCTOR) {
constructorType = MESSAGE_SQLEX_CONSTRUCTOR;
}
if (parameterTypes.length == 3 && String.class == parameterTypes[0] &&
String.class == parameterTypes[1] && Throwable.class == parameterTypes[2] &&
constructorType < MESSAGE_SQL_THROWABLE_CONSTRUCTOR) {
constructorType = MESSAGE_SQL_THROWABLE_CONSTRUCTOR;
}
if (parameterTypes.length == 3 && String.class == parameterTypes[0] &&
String.class == parameterTypes[1] && SQLException.class == parameterTypes[2] &&
constructorType < MESSAGE_SQL_SQLEX_CONSTRUCTOR) {
constructorType = MESSAGE_SQL_SQLEX_CONSTRUCTOR;
}
}
// invoke constructor
Constructor<?> exceptionConstructor;
return switch (constructorType) {
case MESSAGE_SQL_SQLEX_CONSTRUCTOR -> {
Class<?>[] messageAndSqlAndSqlExArgsClass = new Class<?>[] {String.class, String.class, SQLException.class};
Object[] messageAndSqlAndSqlExArgs = new Object[] {task, sql, sqlEx};
exceptionConstructor = exceptionClass.getConstructor(messageAndSqlAndSqlExArgsClass);
yield (DataAccessException) exceptionConstructor.newInstance(messageAndSqlAndSqlExArgs);
}
case MESSAGE_SQL_THROWABLE_CONSTRUCTOR -> {
Class<?>[] messageAndSqlAndThrowableArgsClass = new Class<?>[] {String.class, String.class, Throwable.class};
Object[] messageAndSqlAndThrowableArgs = new Object[] {task, sql, sqlEx};
exceptionConstructor = exceptionClass.getConstructor(messageAndSqlAndThrowableArgsClass);
yield (DataAccessException) exceptionConstructor.newInstance(messageAndSqlAndThrowableArgs);
}
case MESSAGE_SQLEX_CONSTRUCTOR -> {
Class<?>[] messageAndSqlExArgsClass = new Class<?>[] {String.class, SQLException.class};
Object[] messageAndSqlExArgs = new Object[] {task + ": " + sqlEx.getMessage(), sqlEx};
exceptionConstructor = exceptionClass.getConstructor(messageAndSqlExArgsClass);
yield (DataAccessException) exceptionConstructor.newInstance(messageAndSqlExArgs);
}
case MESSAGE_THROWABLE_CONSTRUCTOR -> {
Class<?>[] messageAndThrowableArgsClass = new Class<?>[] {String.class, Throwable.class};
Object[] messageAndThrowableArgs = new Object[] {task + ": " + sqlEx.getMessage(), sqlEx};
exceptionConstructor = exceptionClass.getConstructor(messageAndThrowableArgsClass);
yield (DataAccessException)exceptionConstructor.newInstance(messageAndThrowableArgs);
}
case MESSAGE_ONLY_CONSTRUCTOR -> {
Class<?>[] messageOnlyArgsClass = new Class<?>[] {String.class};
Object[] messageOnlyArgs = new Object[] {task + ": " + sqlEx.getMessage()};
exceptionConstructor = exceptionClass.getConstructor(messageOnlyArgsClass);
yield (DataAccessException) exceptionConstructor.newInstance(messageOnlyArgs);
}
default -> {
if (logger.isWarnEnabled()) {
logger.warn("Unable to find appropriate constructor of custom exception class [" +
exceptionClass.getName() + "]");
}
yield null;
}
};
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Unable to instantiate custom exception class [" + exceptionClass.getName() + "]", ex);
}
return null;
}
}
private void logTranslation(String task, @Nullable String sql, SQLException sqlEx, boolean custom) {
if (logger.isDebugEnabled()) {
String intro = custom ? "Custom translation of" : "Translating";
logger.debug(intro + " SQLException with SQL state '" + sqlEx.getSQLState() +
"', error code '" + sqlEx.getErrorCode() + "', message [" + sqlEx.getMessage() + "]" +
(sql != null ? "; SQL was [" + sql + "]": "") + " for task [" + task + "]");
}
}
/**
* Check whether there is a user-provided `sql-error-codes.xml` file
* in the root of the classpath.
*/
static boolean hasUserProvidedErrorCodesFile() {
return userProvidedErrorCodesFilePresent;
}
}
|
package saga.controllers;
import saga.Verificador;
import saga.entities.Fornecedor;
import saga.entities.Produto;
import saga.repositories.FornecedorRepositorio;
import java.util.List;
/**
* Classe responsável pelo tratamento da lógica de produto.
*
* @author Mariane Carvalho
*/
public class ProdutoController {
/**
* Repositório de fornecedores.
*/
private FornecedorRepositorio fornecedores;
/**
* Constroi um controller de produto recebendo o repositório de fornecedores.
*
* @param fornecedorRepositorio Repositório de fornecedores.
*/
public ProdutoController(FornecedorRepositorio fornecedorRepositorio) {
this.fornecedores = fornecedorRepositorio;
}
/**
* Adiciona um produto ao repositório de um fornecedor.
* Caso o fornecedor não exista ou o produto já exista é lançada uma exceção.
*
* @param nomeFornecedor Nome do fornecedor.
* @param nome Nome do produto.
* @param descricao Descrição do produto.
* @param preco Preço do produto.
* @throws IllegalArgumentException Caso receba alguma informação inapropriada.
*/
public void adicionaProduto(String nomeFornecedor, String nome, String descricao, double preco) throws IllegalArgumentException{
Verificador.verificaStringNullVazia(nomeFornecedor, "Erro no cadastro de produto: fornecedor nao pode ser vazio ou nulo.");
Verificador.verificaStringNullVazia(nome, "Erro no cadastro de produto: nome nao pode ser vazio ou nulo.");
Verificador.verificaStringNullVazia(descricao, "Erro no cadastro de produto: descricao nao pode ser vazia ou nula.");
Verificador.verificaNumeroNegativo(preco, "Erro no cadastro de produto: preco invalido.");
Fornecedor fornecedor = this.fornecedores.consultaFornecedor(nomeFornecedor);
Verificador.verificaNull(fornecedor, "Erro no cadastro de produto: fornecedor nao existe.");
Produto produto = new Produto(nome, descricao, preco);
boolean cadastro = fornecedor.adicionaProduto(produto);
if(!cadastro) throw new IllegalArgumentException("Erro no cadastro de produto: produto ja existe.");
}
/**
* Obtém a representação de um produto.
* Caso o fornecedor ou o produto não exista é lançada uma exceção.
*
* @param nome Nome do produto.
* @param descricao Descrição do produto.
* @param nomeFornecedor Nome do fornecedor.
* @return A representação de um produto.
* @throws IllegalArgumentException Caso receba alguma informação inapropriada.
*/
public String exibeProduto(String nome, String descricao, String nomeFornecedor) throws IllegalArgumentException{
Verificador.verificaStringNullVazia(nomeFornecedor, "Erro na exibicao de produto: fornecedor nao pode ser vazio ou nulo.");
Verificador.verificaStringNullVazia(nome, "Erro na exibicao de produto: nome nao pode ser vazio ou nulo.");
Verificador.verificaStringNullVazia(descricao, "Erro na exibicao de produto: descricao nao pode ser vazia ou nula.");
Fornecedor fornecedor = this.fornecedores.consultaFornecedor(nomeFornecedor);
Verificador.verificaNull(fornecedor, "Erro na exibicao de produto: fornecedor nao existe.");
Produto produto = fornecedor.consultaProduto(nome,descricao);
Verificador.verificaNull(produto, "Erro na exibicao de produto: produto nao existe.");
return produto.toString();
}
/**
* Obtém a representação de todos os produtos de um fornecedor.
* Caso o fornecedor não exista é lançada uma exceção.
*
* @param nomeFornecedor Nome do fornecedor.
* @return A representação dos produtos de um fornecedor.
* @throws IllegalArgumentException Caso receba alguma informação inapropriada.
*/
public String exibeProdutosFornecedor(String nomeFornecedor) throws IllegalArgumentException{
Verificador.verificaStringNullVazia(nomeFornecedor, "Erro na exibicao de produto: fornecedor nao pode ser vazio ou nulo.");
Fornecedor fornecedor = this.fornecedores.consultaFornecedor(nomeFornecedor);
Verificador.verificaNull(fornecedor, "Erro na exibicao de produto: fornecedor nao existe.");
List<Produto> listaProdutos = fornecedor.consultaProdutos();
String representacao = "";
for(int i = 0; i < listaProdutos.size(); i++) {
if(i != listaProdutos.size() - 1) {
representacao += nomeFornecedor + " - " + listaProdutos.get(i).toString() + " | ";
} else representacao += nomeFornecedor + " - " + listaProdutos.get(i).toString();
}
return representacao;
}
/**
* Obtém a representação dos produtos de cada fornecedor.
*
* @return A representação dos produtos de cada fornecedor.
*/
public String exibeProdutos() {
String representacao = "";
List<Fornecedor> listaFornecedores = this.fornecedores.consultaFornecedores();
for(int i = 0; i < listaFornecedores.size(); i++) {
List<Produto> listaProdutos = listaFornecedores.get(i).consultaProdutos();
String nomeFornecedor = listaFornecedores.get(i).getNome();
if(listaProdutos.size() == 0) {
representacao += nomeFornecedor + " - | ";
continue;
}
for(int j = 0; j < listaProdutos.size(); j++){
if(i != listaFornecedores.size() - 1 || j != listaProdutos.size() - 1) {
representacao += nomeFornecedor + " - " + listaProdutos.get(j).toString() + " | ";
}else representacao += nomeFornecedor + " - " + listaProdutos.get(j).toString();
}
}
return representacao;
}
/**
* Edita o preço de um produto.
* Caso o fornecedor ou o produto não exista é lançada uma exceção.
*
* @param nome Nome do produto.
* @param descricao Descrição do produto.
* @param nomeFornecedor Nome do fornecedor.
* @param novoPreco Novo valor do preço.
* @throws IllegalArgumentException Caso receba alguma informação inapropriada.
*/
public void editaProduto(String nome, String descricao, String nomeFornecedor, double novoPreco) throws IllegalArgumentException{
Verificador.verificaStringNullVazia(nome, "Erro na edicao de produto: nome nao pode ser vazio ou nulo.");
Verificador.verificaStringNullVazia(descricao, "Erro na edicao de produto: descricao nao pode ser vazia ou nula.");
Verificador.verificaStringNullVazia(nomeFornecedor, "Erro na edicao de produto: fornecedor nao pode ser vazio ou nulo.");
Verificador.verificaNumeroNegativo(novoPreco, "Erro na edicao de produto: preco invalido.");
Fornecedor fornecedor = this.fornecedores.consultaFornecedor(nomeFornecedor);
Verificador.verificaNull(fornecedor, "Erro na edicao de produto: fornecedor nao existe.");
Produto produto = fornecedor.consultaProduto(nome,descricao);
Verificador.verificaNull(produto, "Erro na edicao de produto: produto nao existe.");
produto.setPreco(novoPreco);
}
/**
* Remove um produto do repositório de um fornecedor.
* Caso o fornecedor ou o produto não exista é lançada uma exceção.
*
* @param nome Nome do produto.
* @param descricao Descrição do produto.
* @param nomeFornecedor Nome do fornecedor.
* @throws IllegalArgumentException Caso receba alguma informação inapropriada.
*/
public void removeProduto(String nome, String descricao, String nomeFornecedor) throws IllegalArgumentException{
Verificador.verificaStringNullVazia(nome, "Erro na remocao de produto: nome nao pode ser vazio ou nulo.");
Verificador.verificaStringNullVazia(descricao, "Erro na remocao de produto: descricao nao pode ser vazia ou nula.");
Verificador.verificaStringNullVazia(nomeFornecedor, "Erro na remocao de produto: fornecedor nao pode ser vazio ou nulo.");
Fornecedor fornecedor = this.fornecedores.consultaFornecedor(nomeFornecedor);
Verificador.verificaNull(fornecedor, "Erro na remocao de produto: fornecedor nao existe.");
Produto produto = fornecedor.consultaProduto(nome,descricao);
Verificador.verificaNull(produto, "Erro na remocao de produto: produto nao existe.");
fornecedor.removeProduto(produto);
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
/**
* <a href="http://oj.leetcode.com/problems/integer-to-roman/">Integer To Roman</a>
* <p/>
* Copyright 2013 LeetCode
* <p/>
* Given an integer, convert it to a roman numeral.
* <p/>
* Input is guaranteed to be within the range from 1 to 3999.
* <p/>
*
* @see <a href="http://discuss.leetcode.com/questions/194/integer-to-roman">leetcode discussion</a>
* @see <a href="http://codesam.blogspot.com/2011/06/convert-integers-to-roman-numbers.html">codesam blog</a>
*/
public interface IntegerToRoman {
String intToRoman(int num);
}
|
package com.psl.training.inventory;
public abstract class Hardware implements IProduct {
String dimensions, capacity, brand, power_supply_requirements, battery ;
public Hardware(String dimensions,String capacity,String brand,String power_supply_requirements,String battery ) {
this.dimensions=dimensions;
this.capacity=capacity;
this.brand=brand;
this.power_supply_requirements=power_supply_requirements;
this.battery=battery;
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("These are Hardware Products. ");
}
public void details() {}
}
|
package tailminuseff.config;
import org.junit.Test;
public class PropertyChangeEventDebouncerTests {
@Test
public void test() {
}
}
|
package com.example.mongo.repository;
import com.example.mongo.model.Team;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface TeamRepository extends MongoRepository<Team, String> {
Optional<Team> findById(String id);
} |
package com.shopping.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.shopping.eneity.User;
import com.shopping.service.ContactsService;
import com.shopping.service.UserService;
import com.shopping.serviceimpl.SDKTestSendTemplateSMS;
@Controller
@RequestMapping(value = "User")
/**
* user
*
* @author ZhaoZhen
*
*/
public class UserController {
@Autowired
private UserService us;
@Autowired
private ContactsService cs;
public void setUs(UserService us) {
this.us = us;
}
private SDKTestSendTemplateSMS sms = new SDKTestSendTemplateSMS();
@RequestMapping(value = "/Login", method = RequestMethod.GET)
public String Login() {
return "Login";
}
@RequestMapping(value = "/Login", method = RequestMethod.POST)
public String Login(User user, Model model, HttpSession session) {
User u = us.Login(user);
if (u == null) {
model.addAttribute("bool", "账号或密码错误!");
return "Login";
}
session.setAttribute("User", u);
return "index";
}
@RequestMapping(value = "/UpdatePwd", method = RequestMethod.POST)
public String UpdatePwd(User user, Model model) {
if (!us.updatePwd(user)) {
model.addAttribute("bool", "修改成功!");
return "Login";
}
model.addAttribute("bool", "修改失败!");
return "UpPwd";
}
/**
* 获取验证码
*
* @param phone
* @return
*/
@RequestMapping(value = "/random", method = RequestMethod.POST)
@ResponseBody
public String random(String phone) {
/*
* Map<String,String> map = new HashMap<String,String>();
*
*
* map.put("suiji",sms.duanxin(phone));
*/
return sms.duanxin(phone);
}
/**
* 注册
*
* @param user
* @param model
* @return
*/
@RequestMapping(value = "/AddUser", method = RequestMethod.POST)
public String AddUser(User user, Model model) {
if (us.insertUser(user)) {
return "Login";
}
return "register";
}
@RequestMapping(value = "/chat")
public String webSocket(Model model, HttpSession session) {
/* logger.info("跳转到websocket的页面上"); */
User user = (User) session.getAttribute("User");
String json = JSON.toJSONString(user);
model.addAttribute("UserList", cs.queryContacts(user.getId()));
model.addAttribute("Juser", json);
return "customService";
/*
* } catch (Exception e){
* logger.info("跳转到websocket的页面上发生异常,异常信息是:"+e.getMessage()); return "error"; }
*/
}
}
|
package com.xianzaishi.wms.tmscore.dao.impl;
import java.util.Date;
import java.util.List;
import com.xianzaishi.wms.common.dao.impl.BaseDaoAdapter;
import com.xianzaishi.wms.tmscore.dao.itf.IPickingBasketStatuDao;
import com.xianzaishi.wms.tmscore.vo.PickingBasketStatuQueryVO;
import com.xianzaishi.wms.tmscore.vo.PickingBasketStatuVO;
public class PickingBasketStatuDaoImpl extends BaseDaoAdapter implements
IPickingBasketStatuDao {
public String getVOClassName() {
return "PickingBasketStatuDO";
}
public void assign(Long pickID, List<Long> basketIDs) {
for (int i = 0; i < basketIDs.size(); i++) {
PickingBasketStatuQueryVO queryVO = new PickingBasketStatuQueryVO();
queryVO.setBasketId(basketIDs.get(i));
List<PickingBasketStatuVO> statuVOs = queryDO(queryVO);
PickingBasketStatuVO statuVO = null;
if (statuVOs != null && statuVOs.size() > 0) {
statuVO = statuVOs.get(0);
} else {
statuVO = new PickingBasketStatuVO();
}
statuVO.setAssignmentId(pickID);
statuVO.setUsed(Short.parseShort("1"));
statuVO.setStartTime(new Date(System.currentTimeMillis()));
statuVO.setBasketId((Long) basketIDs.get(0));
statuVO.setStatu(0);
if (statuVO.getId() == null) {
addDO(statuVO);
} else {
updateDO(statuVO);
}
}
}
}
|
package com.lu.rest.bean;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
private String userName;
private String age;
public User() {};
public User( String userName, String age) {
this.userName = userName;
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
} |
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record10;
import org.jooq.Row10;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.ShoppingcartCourseregistrationcode;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ShoppingcartCourseregistrationcodeRecord extends UpdatableRecordImpl<ShoppingcartCourseregistrationcodeRecord> implements Record10<Integer, String, String, Timestamp, String, Byte, Integer, Integer, Integer, Integer> {
private static final long serialVersionUID = -833348967;
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.code</code>.
*/
public void setCode(String value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.code</code>.
*/
public String getCode() {
return (String) get(1);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.course_id</code>.
*/
public void setCourseId(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.course_id</code>.
*/
public String getCourseId() {
return (String) get(2);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.created_at</code>.
*/
public void setCreatedAt(Timestamp value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.created_at</code>.
*/
public Timestamp getCreatedAt() {
return (Timestamp) get(3);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.mode_slug</code>.
*/
public void setModeSlug(String value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.mode_slug</code>.
*/
public String getModeSlug() {
return (String) get(4);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.is_valid</code>.
*/
public void setIsValid(Byte value) {
set(5, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.is_valid</code>.
*/
public Byte getIsValid() {
return (Byte) get(5);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.created_by_id</code>.
*/
public void setCreatedById(Integer value) {
set(6, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.created_by_id</code>.
*/
public Integer getCreatedById() {
return (Integer) get(6);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.invoice_id</code>.
*/
public void setInvoiceId(Integer value) {
set(7, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.invoice_id</code>.
*/
public Integer getInvoiceId() {
return (Integer) get(7);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.order_id</code>.
*/
public void setOrderId(Integer value) {
set(8, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.order_id</code>.
*/
public Integer getOrderId() {
return (Integer) get(8);
}
/**
* Setter for <code>bitnami_edx.shoppingcart_courseregistrationcode.invoice_item_id</code>.
*/
public void setInvoiceItemId(Integer value) {
set(9, value);
}
/**
* Getter for <code>bitnami_edx.shoppingcart_courseregistrationcode.invoice_item_id</code>.
*/
public Integer getInvoiceItemId() {
return (Integer) get(9);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record10 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row10<Integer, String, String, Timestamp, String, Byte, Integer, Integer, Integer, Integer> fieldsRow() {
return (Row10) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row10<Integer, String, String, Timestamp, String, Byte, Integer, Integer, Integer, Integer> valuesRow() {
return (Row10) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.CODE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.COURSE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field4() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.CREATED_AT;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.MODE_SLUG;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Byte> field6() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.IS_VALID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field7() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.CREATED_BY_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field8() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.INVOICE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field9() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.ORDER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field10() {
return ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE.INVOICE_ITEM_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getCode();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getCourseId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value4() {
return getCreatedAt();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getModeSlug();
}
/**
* {@inheritDoc}
*/
@Override
public Byte value6() {
return getIsValid();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value7() {
return getCreatedById();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value8() {
return getInvoiceId();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value9() {
return getOrderId();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value10() {
return getInvoiceItemId();
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value2(String value) {
setCode(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value3(String value) {
setCourseId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value4(Timestamp value) {
setCreatedAt(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value5(String value) {
setModeSlug(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value6(Byte value) {
setIsValid(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value7(Integer value) {
setCreatedById(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value8(Integer value) {
setInvoiceId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value9(Integer value) {
setOrderId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord value10(Integer value) {
setInvoiceItemId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ShoppingcartCourseregistrationcodeRecord values(Integer value1, String value2, String value3, Timestamp value4, String value5, Byte value6, Integer value7, Integer value8, Integer value9, Integer value10) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached ShoppingcartCourseregistrationcodeRecord
*/
public ShoppingcartCourseregistrationcodeRecord() {
super(ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE);
}
/**
* Create a detached, initialised ShoppingcartCourseregistrationcodeRecord
*/
public ShoppingcartCourseregistrationcodeRecord(Integer id, String code, String courseId, Timestamp createdAt, String modeSlug, Byte isValid, Integer createdById, Integer invoiceId, Integer orderId, Integer invoiceItemId) {
super(ShoppingcartCourseregistrationcode.SHOPPINGCART_COURSEREGISTRATIONCODE);
set(0, id);
set(1, code);
set(2, courseId);
set(3, createdAt);
set(4, modeSlug);
set(5, isValid);
set(6, createdById);
set(7, invoiceId);
set(8, orderId);
set(9, invoiceItemId);
}
}
|
package ru.avokin.uidiff.fs.fsbrowser.model;
import ru.avokin.uidiff.common.model.AbstractModel;
import ru.avokin.uidiff.fs.common.model.FileTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.util.ArrayList;
import java.util.List;
/**
* User: Andrey Vokin
* Date: 02.08.2010
*/
public class FsBrowserModel extends AbstractModel {
private final DefaultTreeModel leftModel;
private final DefaultTreeModel rightModel;
private FileTreeNode firstSelectedItem;
private FileTreeNode secondSelectedItem;
private boolean compareActionEnabled;
private final List<FsBrowserModelListener> fsBrowserModelListenerList;
public FsBrowserModel(DefaultTreeModel rightModel, DefaultTreeModel leftModel) {
this.rightModel = rightModel;
this.leftModel = leftModel;
fsBrowserModelListenerList = new ArrayList<FsBrowserModelListener>();
}
public void addFsBrowserModelListener(FsBrowserModelListener fsBrowserModelListener) {
fsBrowserModelListenerList.add(fsBrowserModelListener);
}
public DefaultTreeModel getLeftModel() {
return leftModel;
}
public DefaultTreeModel getRightModel() {
return rightModel;
}
public FileTreeNode getFirstSelectedItem() {
return firstSelectedItem;
}
public void setSelectedItems(FileTreeNode firstSelectedItem, FileTreeNode secondSelectedItem) {
this.firstSelectedItem = firstSelectedItem;
this.secondSelectedItem = secondSelectedItem;
for (FsBrowserModelListener fsBrowserModelListener : fsBrowserModelListenerList) {
fsBrowserModelListener.selectedNodesChanged(firstSelectedItem, secondSelectedItem);
}
}
public FileTreeNode getSecondSelectedItem() {
return secondSelectedItem;
}
public boolean isCompareActionEnabled() {
return compareActionEnabled;
}
public void setCompareActionEnabled(boolean compareActionEnabled) {
this.compareActionEnabled = compareActionEnabled;
for (FsBrowserModelListener fsBrowserModelListener : fsBrowserModelListenerList) {
fsBrowserModelListener.compareActionEnablingChanged();
}
}
}
|
package com.example.youtubeex.usecases.network;
import com.example.youtubeex.entities.channelVideos.VideosChannelInfo;
import com.example.youtubeex.entities.channels.ChannelsInfo;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface YouTubeApi {
@GET("channels")
Observable<ChannelsInfo> getChannels(@Query("key") String key,
@Query("part") String part,
@Query("id") String ids);
@GET("search")
Observable<VideosChannelInfo> getChannelVideos(@Query("key") String key,
@Query("channelId") String channelId,
@Query("part") String part,
@Query("order") String order,
@Query("maxResults") String maxResults);
}
|
/*
* La classe PartitaTest serve solamente per creare una partita testuale e fare delle prove sulla logica del gioco,
* ad esempio, capire velocemente se funziona il controllo della mossa senza creare ogni volta una partita dal server.
*/
package model;
import java.util.Scanner;
/**
*
* @author AlessandroAchille ROSSI
*
*
*/
public class PartitaTest {
public static void main(String arg[]) {
Partita partita = new Partita("Partita di Test");
System.out.println();
System.out.println();
Scanner sc = new Scanner(System.in);
partita.campo.calcolaMosseValide("N");
System.out.println("Benventuto.. Per iniziare a giocare scrivi le coordinate x della casella nella quale vuoi posizionare la pedina, quindi premi invio.");
System.out.println("Poi scrivi le coordinate y, e premi invio; ed infine il colore (B oppure N) del colore della pedina.");
try {
do {
String oppC;
int a = sc.nextInt();
int b = sc.nextInt();
String c = sc.next().toUpperCase();
partita.campo.calcolaMosseValide(c);
partita.campo.posizionaNuovaCasella(a, b, c);
if (c.equals("N")) {
oppC = "B";
} else {
oppC = "N";
}
partita.campo.print();
partita.campo.calcolaMosseValide(oppC);
} while (partita.inCorso());
int pedineBianche = partita.campo.getPedineBianche();
int pedineNere = partita.campo.getPedineNere();
if (pedineBianche > pedineNere) {
System.out.println("Ha vinto il giocatore Bianco!");
System.out.println("Numero Pedine Bianche: " + pedineBianche);
System.out.println("Numero Pedine Nere: " + pedineNere);
} else if (pedineNere > pedineBianche) {
System.out.println("Ha vinto il giocatore Nere!");
System.out.println("Numero Pedine Bianche: " + pedineBianche);
System.out.println("Numero Pedine Nere: " + pedineNere);
} else {
System.out.println("Partita finita in parità.");
System.out.println("Numero Pedine Bianche: " + pedineBianche);
System.out.println("Numero Pedine Nere: " + pedineNere);
}
} catch (Exception exc) {
System.out.println("Generata un'eccezione non gestita. Le info di seguit potrebbero aiutare nel rispoverla.");
exc.printStackTrace();
}
}
}
|
package com.test.base;
import com.test.SolutionA;
import junit.framework.TestCase;
public class Example extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
public void testSolutionA()
{
solution = new SolutionA();
assertSolution();
}
private void assertSolution()
{
// A
TreeNode rootA = new TreeNode(3);
rootA.left = new TreeNode(9);
TreeNode rightA1 = new TreeNode(20);
rightA1.left = new TreeNode(15);
rightA1.right = new TreeNode(7);
rootA.right = rightA1;
assertEquals(2, solution.minDepth(rootA));
// B
TreeNode rootB = new TreeNode(1);
rootB.right = new TreeNode(2);
TreeNode rootB1 = new TreeNode(2);
rootB.left = rootB1;
rootB1.right = new TreeNode(3);
TreeNode rootB2 = new TreeNode(3);
rootB1.left = rootB2;
rootB2.left = new TreeNode(4);
rootB2.right = new TreeNode(4);
assertEquals(2, solution.minDepth(rootB));
// C
TreeNode rootC = new TreeNode(1);
rootC.left = new TreeNode(2);
assertEquals(2, solution.minDepth(rootC));
// D
TreeNode rootD = new TreeNode(1);
}
@Override
protected void tearDown()
throws Exception
{
solution = null;
super.tearDown();
}
}
|
package com.example.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.User;
import com.example.demo.model.UserCompletedTraining;
@Repository
public interface UserCompletedRepository extends CrudRepository<UserCompletedTraining, Integer>{
}
|
package assignment6;
import java.lang.Math;
public class Assignment6 {
// contains checks whether a double in an array of doubles fulfills the condition of (dubs[i] - d)
// < eps.
// pre-condition:
// The input dubs must be an non null array.
// post-condition:
// The output will be a boolean value.
public static boolean contains(double[] dubs, double eps, double d) {
for (int i = 0; i < dubs.length; i++) {
if (Math.abs(dubs[i] - d) < eps) {
return true;
}
}
return false;
}
// fastModExp finds the remainder of x to the power of y
// pre-conditon:
// The input y must be a non-negative integer.
// post-condition:
// The output must be an integer
public static int fastModExp(int x, int y, int m) {
if (y == 0) {
return 1;
} else if (y % 2 == 0) {
int temp = fastModExp(x, (y / 2), m);
return (temp * temp) % m;
} else {
return ((x % m) * (fastModExp(x, y - 1, m))) % m;
}
}
// allPairs creates an array of pairs that has all of the pairs that can be created by the
// integers in the array.
public static IntPair[] allPairs(int[] arr) {
// Throws exception if user enters a null as an array
if (arr == null) {
throw new IllegalArgumentException("Array is empty");
}
// Initialize an array with n^2 size
IntPair[] allP = new IntPair[(arr.length * arr.length)];
int pos = 0;
// Loop that fills in the positions in the array with the correct pair.
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
allP[pos] = new IntPair(i, j);
pos++;
}
}
return allP;
}
// concatAndReplicateAll creates a single string that compiles all the strings in an string array by n times
// according to the input, reps.
public static String concatAndReplicateAll(String[] arr, int reps) {
// If the user enters a null as the array, thrown an exception
if (arr == null) {
throw new IllegalArgumentException("Array is empty");
}
// Initialize an empty string to add the strings into it
String str = "";
// Loop that appends the strings together
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < reps; j++) {
str = str + arr[i];
}
}
return str;
}
// interleave creates an array with the size of length of arr1 + length of arr2 with the elements interleaving
// the elements in array1 and array2
// pre-condition:
// the arrays cannot be null
// post-condition
// returns an array with the size of size of arr1 + size of arr2
public static int[] interleave(int[] arr1, int[] arr2) {
int len1 = arr1.length;
int len2 = arr2.length;
// Initialize array
int[] arr3 = new int[(len1 + len2)];
int pos = 0;
// Interleaves the elements with matching positions
for (int i = 0; i < Math.min(len1, len2); i++) {
arr3[pos] = arr1[i];
pos++;
arr3[pos] = arr2[i];
pos++;
}
// Fills in the rest of the array with the elements in the longer array that are still not entered.
if (len1 > len2) {
for (int i = len2; i < len1; i++) {
arr3[pos] = arr1[i];
pos++;
}
} else {
for (int i = len1; i < len2; i++) {
arr3[pos] = arr2[i];
pos++;
}
}
return arr3;
}
}
|
package com.otherhshe.niceread.presenter;
import com.otherhshe.niceread.api.GirlService;
import com.otherhshe.niceread.net.ApiService;
import com.otherhshe.niceread.rx.RxManager;
import com.otherhshe.niceread.rx.RxSubscriber;
import com.otherhshe.niceread.ui.view.GirlItemView;
import com.otherhshe.niceread.utils.JsoupUtil;
/**
* Author: Othershe
* Time: 2016/8/12 14:29
*/
public class GirlItemPresenter extends BasePresenter<GirlItemView> {
public GirlItemPresenter(GirlItemView view) {
super(view);
}
public void getGirlItemData(String cid, int page) {
mSubscription = RxManager.getInstance()
.doSubscribe(ApiService.getInstance().initService(GirlService.class).getGirlItemData(cid, page),
new RxSubscriber<String>(false) {
@Override
protected void _onNext(String s) {
mView.onSuccess(JsoupUtil.parseGirls(s));
}
@Override
protected void _onError() {
mView.onError();
}
});
}
}
|
package com.noiprocs.network.server;
import com.noiprocs.network.CommunicationManager;
import java.io.*;
import java.net.Socket;
// TODO: Handle case to destroy when client disconnects
public class ServerInStreamRunnable implements Runnable {
private final CommunicationManager mCommunicationManager;
private InputStream inputStream;
public ServerInStreamRunnable(Socket socket, CommunicationManager mCommunicationManager) {
this.mCommunicationManager = mCommunicationManager;
try {
this.inputStream = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] bytes = new byte[16384];
while (true) {
int count = inputStream.read(bytes);
if (count == -1) {
// Notify server that client is disconnected
mCommunicationManager.clientDisconnect(this.hashCode());
return;
}
buffer.write(bytes, 0, count);
mCommunicationManager.receiveMessage(this.hashCode(), buffer.toByteArray());
buffer.reset();
}
} catch (Exception e) {
e.printStackTrace();
// Notify server that client is disconnected
mCommunicationManager.clientDisconnect(this.hashCode());
}
}
}
|
package hw3.q02;
import hw3.q01.Profiler;
import java.util.HashMap;
import java.util.Map;
public class FibonacciSequence
{
private Map<Integer,Integer> fibMap = new HashMap<>();
Profiler profiler = Profiler.getSingleton();
public int get(int sequenceID){
//clear the cache
Map<Integer,Integer> fibMap = new HashMap<>();
this.fibMap = fibMap;
Profiler.getSingleton().clear();
profiler.add("get");
return getInternal(sequenceID);
}
private int getInternal(int sequenceID){
int seq1;
int seq2;
if(sequenceID == 0){
return 0;
}
if(sequenceID == 1){
return 1;
}
seq1 = getInternal(sequenceID - 1);
seq2 = getInternal(sequenceID -2);
// String method_call_1 = Integer.toBinaryString(sequenceID - 1);
// String method_call_2 = Integer.toBinaryString(sequenceID - 2);
profiler.add("get");
profiler.add("get");
return seq1 + seq2;
}
public int getFaster(int sequenceID){
//clear the cache
Map<Integer,Integer> fibMap = new HashMap<>();
this.fibMap = fibMap;
Profiler.getSingleton().clear();
Profiler profiler = Profiler.getSingleton();
profiler.add("getFaster");
return getFasterInternal(sequenceID);
}
// private int putInMap(int sequenceID){
// int seq;
//
//// if(fibMap.containsKey(sequenceID)){
//// seq = fibMap.get(sequenceID);
//// }else{
//// seq = getFasterInternal(sequenceID);
//// profiler.add("getFaster");
//// fibMap.put(sequenceID, seq);
//// }
//
// return seq;
// }
public int getFasterInternal(int sequenceID){
int seq1 = 0;
int seq2 = 0;
if(sequenceID == 0){
fibMap.put(0, 0);
return 0;
}
if(sequenceID == 1){
fibMap.put(1, 1);
return 1;
}
if(fibMap.containsKey(sequenceID - 1)){
seq1 = fibMap.get(sequenceID - 1);
}else{
profiler.add("getFaster");
seq1 = getFasterInternal(sequenceID - 1 );
fibMap.put(sequenceID - 1, seq1);
}
if(fibMap.containsKey(sequenceID - 2)){
seq2 = fibMap.get(sequenceID - 2);
}else{
profiler.add("getFaster");
seq2 = getFasterInternal(sequenceID -2 );
fibMap.put(sequenceID -2, seq2);
}
return seq1 + seq2;
}
}
|
/*
* 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.
*/
/**
*
* @author publisy
*/
package smusemiv.connection;
import java.awt.HeadlessException;
import java.sql.*;
import javax.swing.*;
public class connection {
private static Connection con;
PreparedStatement pst = null;
public static Connection getConnection() {
try {
String url = "jdbc:mysql://localhost/smude_4th";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String password = "kishor";
try {
Class.forName(driver);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. fro example:
JOptionPane.showMessageDialog(null, "Error: Failed to create the database connection!!!");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
JOptionPane.showMessageDialog(null, "Error: Driver not found!!!");
}
return con;
}
catch(HeadlessException e){
JOptionPane.showMessageDialog(null, "Error: Connection file error!!!");
return con;
}
}
public static void main(String args[]) {
con = connection.getConnection();
}
public static ResultSet dbSelectProc( String procedure, String [] params ) throws SQLException{
String statement = "{ call "+ procedure +"(";
for(int i=0; i < params.length ;i++){
if (i+1 == params.length) {
statement +="?";
}
else {
statement +="?, ";
}
}
statement += ") }";
//System.out.println(statement);
CallableStatement proc = con.prepareCall(statement);
for(int i=0; i < params.length ;i++){
proc.setString(i+1,params[i]);
//System.out.println(params[i]);
}
return proc.executeQuery();
}
public static int dbExecuteProc( String procedure, String [] params ) throws SQLException{
String statement = "{ call "+ procedure +"(";
for(int i=0; i < params.length ;i++){
if (i+1 == params.length) {
statement +="?";
}
else {
statement +="?, ";
}
}
statement += ") }";
CallableStatement proc = con.prepareCall(statement);
for(int i=0; i < params.length ;i++){
proc.setString(i+1,params[i]);
}
return proc.executeUpdate();
}
public static ResultSet dbSelect( String sql, String [] params ) throws SQLException{
PreparedStatement pst;
//System.out.println(sql);
pst = con.prepareStatement(sql);
for(int i=0; i < params.length ;i++){
pst.setString(i+1,params[i]);
}
//displayResultSet(pst.executeQuery());
return pst.executeQuery();
}
public static int dbExecuteReturnID(String sql, String [] params ) throws SQLException{
PreparedStatement pst;
//System.out.println(sql);
pst = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for(int i=0; i < params.length ;i++){
//System.out.println(params[i]);
pst.setString(i+1,params[i]);
}
int numero = pst.executeUpdate();
ResultSet rs = pst.getGeneratedKeys();
int ID = 0;
if (rs.next()){
ID=rs.getInt(1);
}
return ID;
}
public static int dbExecute(String sql, String [] params ) throws SQLException{
PreparedStatement pst;
//System.out.println(sql);
pst = con.prepareStatement(sql);
for(int i=0; i < params.length ;i++){
//System.out.println(params[i]);
pst.setString(i+1,params[i]);
}
return pst.executeUpdate();
}
public static void displayResultSet(ResultSet rs ) throws SQLException{
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
System.out.println("");
}
}
} |
package com.example.applitionthree;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SecondActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Button button2=(Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(SecondActivity.this,ThirdActivity.class);
startActivity(intent);
}
});
TextView textView1=(TextView) findViewById(R.id.relative1);
TextView textView2=(TextView) findViewById(R.id.relative2);
TextView textView3=(TextView) findViewById(R.id.relative3);
TextView textView4=(TextView) findViewById(R.id.relative4);
TextView textView5=(TextView) findViewById(R.id.relative5);
TextView textView6=(TextView) findViewById(R.id.relative6);
TextView textView7=(TextView) findViewById(R.id.relative7);
textView1.setOnClickListener(this);
textView2.setOnClickListener(this);
textView3.setOnClickListener(this);
textView4.setOnClickListener(this);
textView5.setOnClickListener(this);
textView6.setOnClickListener(this);
textView7.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.relative1:
Intent intent1=new Intent(SecondActivity.this,ThirdActivity.class);
intent1.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲1信息");
startActivity(intent1);
break;
case R.id.relative2:
Intent intent2=new Intent(SecondActivity.this,ThirdActivity.class);
intent2.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲2信息");
startActivity(intent2);
break;
case R.id.relative3:
Intent intent3=new Intent(SecondActivity.this,ThirdActivity.class);
intent3.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲3信息");
startActivity(intent3);
break;
case R.id.relative4:
Intent intent4=new Intent(SecondActivity.this,ThirdActivity.class);
intent4.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲4信息");
startActivity(intent4);
break;
case R.id.relative5:
Intent intent5=new Intent(SecondActivity.this,ThirdActivity.class);
intent5.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲5信息");
startActivity(intent5);
break;
case R.id.relative6:
Intent intent6=new Intent(SecondActivity.this,ThirdActivity.class);
intent6.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲6信息");
startActivity(intent6);
break;
case R.id.relative7:
Intent intent7=new Intent(SecondActivity.this,ThirdActivity.class);
intent7.putExtra("SecondActivity-data", "这是歌曲管理页面下歌曲7信息");
startActivity(intent7);
break;
default:
break;
}
}
}
|
package com.example.ordenado;
import android.content.Context;
import android.widget.Toast;
public class HeapSort {
public Integer[] heapsort(Comparable[] a, Context context) {
long startTime = System.nanoTime();
for (int i = a.length / 2; i >= 0; i--) /* buildHeap */
percDown(a, i, a.length);
for (int i = a.length - 1; i > 0; i--) {
swapReferences(a, 0, i); /* deleteMax */
percDown(a, 0, i);
}
long endTime = System.nanoTime();
String duration = "Ordenado com HEAP em: "+(endTime - startTime)/0.000001 + " ns";
Toast.makeText(context, duration, Toast.LENGTH_LONG).show();
return (Integer[]) a;
}
private static int leftChild(int i) {
return 2 * i + 1;
}
private static void percDown(Comparable[] a, int i, int n) {
int child;
Comparable tmp;
for (tmp = a[i]; leftChild(i) < n; i = child) {
child = leftChild(i);
if (child != n - 1 && a[child].compareTo(a[child + 1]) < 0)
child++;
if (tmp.compareTo(a[child]) < 0)
a[i] = a[child];
else
break;
}
a[i] = tmp;
}
/**
* Method para trocar elementos em um array.
*/
public static final void swapReferences(Object[] a, int index1, int index2) {
Object tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
}
|
package com.aidigame.hisun.imengstar.view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class StaticViewPager extends ViewPager {
public boolean canScroll=false;
public StaticViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public void setCanScroll(boolean canScroll){
this.canScroll=canScroll;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
// return super.onInterceptTouchEvent(arg0);
return canScroll;
}
}
|
package us.gibb.dev.gwt.demo.server;
import us.gibb.dev.gwt.command.results.StringResult;
import us.gibb.dev.gwt.demo.client.command.GetHelloCommand;
import us.gibb.dev.gwt.demo.client.command.HelloResult;
import us.gibb.dev.gwt.demo.client.command.SayHelloCommand;
import us.gibb.dev.gwt.server.command.handler.CommandHandler;
import us.gibb.dev.gwt.server.command.handler.Context;
@SuppressWarnings("unchecked")
public interface HelloCommandHandler extends CommandHandler {
public StringResult sayHello(SayHelloCommand command, Context context);
public HelloResult getHello(GetHelloCommand command, Context context);
}
|
package co.bucketstargram.command.myBucket;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import co.bucketstargram.common.Command;
import co.bucketstargram.common.Primary;
import co.bucketstargram.dao.LoginDao;
import co.bucketstargram.dao.ReplyDao;
public class AppendReplyAction implements Command {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("\n--- AppendReplyAction.java ---");
String memberId = (String)request.getParameter("ownerId");
String bucketId = (String)request.getParameter("bucketId");
String replyCotents = (String)request.getParameter("replyCotent");
String replyId = Primary.create();
System.out.println("imageId = " + bucketId);
System.out.println("content = " + replyCotents);
System.out.println("usersId = " + memberId);
System.out.println("replyId = " + replyId );
boolean insertSuccess = false;
response.setContentType("text/html;charset=UTF-8");
ReplyDao dao = new ReplyDao();
insertSuccess = dao.insert(replyId, bucketId, memberId, replyCotents);
System.out.println("insertSuccess = " + insertSuccess);
LoginDao loginDao = new LoginDao();
String userImagePath = loginDao.getUserImagePath(memberId);
System.out.println("userImagePath = " + userImagePath);
if(insertSuccess) {
System.out.println("String.valueOf(insertSuccess) = " + String.valueOf(insertSuccess));
response.getWriter().write(String.valueOf(insertSuccess+"/"));
response.getWriter().write(userImagePath);
}
}
}
|
package com.bairuitech.server;
import javax.servlet.http.HttpServlet;
public class StartServerServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void init() {
BusinessServer server = new BusinessServer();
try {
server.initSystem();
} catch (Exception e) {
System.out.println("异常");
e.printStackTrace();
}
}
}
|
package com.sandrapenia.entities;
/** Clase para el codigo del template
**/
import com.sandrapenia.entities.uml.ElementTypeEnum;
public class CodeTemplate extends Entity {
private String name;
private ElementTypeEnum type;
private String code;
public CodeTemplate(String name, ElementTypeEnum type, String code) {
super();
this.name = name;
this.type = type;
this.code = code;
}
public CodeTemplate(String name) {
this(name, ElementTypeEnum.Class, "");
}
public CodeTemplate() {
this("");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ElementTypeEnum getType() {
return type;
}
public void setType(ElementTypeEnum type) {
this.type = type;
}
@Override
public String toString() {
return this.name;
}
}
|
/*
* 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 tema8;
/**
*
* @author joaquin
*/
class libreria {
/**
* Es verdadero si el número introducido es capiúa y falso si no lo es.
*
* @param n
* @return Si es capicúa Verdadero, en caso contrario Falso.
*/
public static boolean esCapicua(long n) {
long aux = 0;
long g = 0;
long aux2 = n;
do{
aux = aux2 % 10;
aux2 = aux2 / 10;
g = g * 10 + aux;
}while (aux2 > 0);
if (n == g){
return true;
}
else{
return false;
}
}
/**
* Es verdadero si el número introducido es primo y falso si no lo es.
*
* @param "n" Número a comprobar si es o no primo.
* @return Si es primo Verdadero, en caso contrario Falso.
*/
public static boolean esPrimo(long n) {
long aux = 1;
long aux2 = 0;
do{
if (n % aux == 0){
aux2 ++;
}
aux ++;
}while (aux <= n);
if (aux2 == 2){
return true;
}
else{
return false;
}
}
/**
* Siguiente primo
*
* @param "n" Número a comprobar si es o no primo.
* @return Si es primo Verdadero, en caso contrario Falso.
*/
public static long primoMayor(long n) {
long aux = 1;
long aux2 = 0;
boolean primo = false;
do{
n ++;
do{
if (n % aux == 0){
aux2 ++;
}
aux ++;
}while (aux <= n);
if (aux2 == 2){
primo = true;
}
else{
primo = false;
}
}while (primo = false);
return n;
}
public static long potencia(long b, long e ) {
long x = 1;
long aux = 1;
do{
x = x*b;
aux ++;
}while (aux <= e);
return x;
}
public static long cuentaNumeros(int n) {
int respuesta = 0;
int aux = 100;
do{
n = n / 10;
respuesta ++;
}while (n > 0);
return respuesta;
}
}
|
// Copyright (C) 2016 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.reviewit;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.widget.TextView;
import com.google.reviewit.app.Change;
import com.google.reviewit.util.FormatUtil;
import com.google.reviewit.util.Linkifier;
public class CommitMessageFragment extends PageFragment {
private Change change;
@Override
protected int getLayout() {
return R.layout.content_commit_message;
}
@Override
public @StringRes
int getTitle() {
return R.string.commit_message_title;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv(R.id.subject).setText(change.currentRevision().commit.subject);
TextView commitMsg = tv(R.id.commitMessage);
commitMsg.setText(FormatUtil.formatMessage(change));
(new Linkifier(getApp())).linkifyCommitMessage(commitMsg);
}
public void setChange(Change change) {
this.change = change;
}
}
|
package com.nisum.webflux.model;
import org.springframework.data.mongodb.core.mapping.Document;
//Builder Design Pattern
@Document
public class Product {
private final String id;
private final String name;
private final String price;
private Product(ProductBuilder builder) {
this.id=builder.id;
this.name=builder.name;
this.price=builder.price;
}
public static class ProductBuilder{
private final String id;
private String name;
private String price;
public ProductBuilder(String id) {
this.id=id;
}
public ProductBuilder name(String name) {
this.name=name;
return this;
}
public ProductBuilder price(String price) {
this.price=price;
return this;
}
public Product build() {
Product product=new Product(this);
validateProduct(product);
return product;
}
private void validateProduct(Product product) {
// TODO Auto-generated method stub
}
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
|
package craps_project;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PropBet {
static InputStreamReader ir = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(ir);
CrapsTable ct = new CrapsTable();
HopFour h4 = new HopFour();
HopFive h5 = new HopFive();
HopSix h6 = new HopSix();
HopSeven h7 = new HopSeven();
HopEight h8 = new HopEight();
HopNine h9 = new HopNine();
HopTen h10 = new HopTen();
AnyCrap aC = new AnyCrap();
Horn hb = new Horn();
HornMenu hm = new HornMenu();
public PropBet() {
}
public void coPropMenu() {
Options opt = new Options();
try {
System.out.println("______________________");
System.out.println("[1]Four [6]Nine");
System.out.println("[2]Five [7]Ten");
System.out.println("[3]Six [8]Any Crap");
System.out.println("[4]Seven [9]Horn Bet");
System.out.println("[5]Eight [10]Return");
System.out.println(" [0]Roll");
System.out.println("______________________");
while(true) {
int select = Integer.parseInt(br.readLine());
switch(select) {
case 1:
h4.hopFour();
break;
case 2:
h5.hopFive();
break;
case 3:
h6.hopSix();
break;
case 4:
h7.hopSeven();
break;
case 5:
h8.hopEight();
break;
case 6:
h9.hopNine();
break;
case 7:
h10.hopTen();
break;
case 8:
aC.anyCrap();
break;
case 9:
hm.coHornMenu();
//hb.horn();
break;
case 10:
opt.coMenu();
break;
case 0:
ct.pointOff();
break;
default:
break;
}
}
}catch(Exception e) {
System.out.println("Invalid Entry");
}
}
public void pePropMenu() {
Options opt = new Options();
try {
System.out.println("______________________");
System.out.println("[1]Four [6]Nine");
System.out.println("[2]Five [7]Ten");
System.out.println("[3]Six [8]Any Crap");
System.out.println("[4]Seven [9]Horn Bet");
System.out.println("[5]Eight [10]Return");
System.out.println(" [0]Roll");
System.out.println("______________________");
while(true) {
int select = Integer.parseInt(br.readLine());
switch(select) {
case 1:
h4.hopFour();
break;
case 2:
h5.hopFive();
break;
case 3:
h6.hopSix();
break;
case 4:
h7.hopSeven();
break;
case 5:
h8.hopEight();
break;
case 6:
h9.hopNine();
break;
case 7:
h10.hopTen();
break;
case 8:
aC.anyCrap();
break;
case 9:
hb.horn();
break;
case 10:
opt.peMenu();
break;
case 0:
ct.pointOn();
break;
default:
break;
}
}
}catch(Exception e) {
System.out.println("Invalid Entry");
}
}
}
|
package com.jecarm.rpc.server;
/**
* Created by loagosad on 2018/8/19.
*/
public class BootstrapServer {
private static int port = 9999;
/* public static void main(String[] args) {
new Thread(() -> {
Server server = new ServerCenter(port);
// 将HelloRpcService及其实现类注册到服务中心
server.register(HelloRpcService.class, HelloRpcServiceImpl.class);
System.out.println("register service: "+ HelloRpcService.class.getName());
// 启动
server.start();
}).start();
}*/
}
|
package sn.simplon.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import sn.simplon.entities.User;
@Repository
public interface IRoles extends JpaRepository<User, Integer>{
}
|
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/8.0.38
* Generated at: 2018-09-24 11:23:25 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.protected_;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class userAdm_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent,
org.apache.jasper.runtime.JspSourceImports {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
static {
_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(4);
_jspx_dependants.put("jar:file:/D:/iDesk/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/web/WEB-INF/lib/spring-webmvc-5.0.2.RELEASE.jar!/META-INF/spring-form.tld", Long.valueOf(1511774828000L));
_jspx_dependants.put("/WEB-INF/lib/spring-webmvc-5.0.2.RELEASE.jar", Long.valueOf(1533636232293L));
_jspx_dependants.put("jar:file:/D:/iDesk/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/web/WEB-INF/lib/jstl-1.2.jar!/META-INF/c.tld", Long.valueOf(1153377882000L));
_jspx_dependants.put("/WEB-INF/lib/jstl-1.2.jar", Long.valueOf(1533636261629L));
}
private static final java.util.Set<java.lang.String> _jspx_imports_packages;
private static final java.util.Set<java.lang.String> _jspx_imports_classes;
static {
_jspx_imports_packages = new java.util.HashSet<>();
_jspx_imports_packages.add("javax.servlet");
_jspx_imports_packages.add("javax.servlet.http");
_jspx_imports_packages.add("javax.servlet.jsp");
_jspx_imports_classes = null;
}
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fif_0026_005ftest;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005faction;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005fselect_0026_005fpath_005fmultiple_005fclass;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005foption_0026_005fvalue_005flabel_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005foptions_0026_005fitems_005fitemValue_005fitemLabel_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems;
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public java.util.Set<java.lang.String> getPackageImports() {
return _jspx_imports_packages;
}
public java.util.Set<java.lang.String> getClassImports() {
return _jspx_imports_classes;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fc_005fif_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005faction = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005fselect_0026_005fpath_005fmultiple_005fclass = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005foption_0026_005fvalue_005flabel_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005foptions_0026_005fitems_005fitemValue_005fitemLabel_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fc_005fif_0026_005ftest.release();
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005faction.release();
_005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.release();
_005fjspx_005ftagPool_005fform_005fselect_0026_005fpath_005fmultiple_005fclass.release();
_005fjspx_005ftagPool_005fform_005foption_0026_005fvalue_005flabel_005fnobody.release();
_005fjspx_005ftagPool_005fform_005foptions_0026_005fitems_005fitemValue_005fitemLabel_005fnobody.release();
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.release();
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("\n");
out.write("\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta charset=\"utf-8\">\n");
out.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n");
out.write("<link href=\"./resources/css/bootstrap.css\" rel=\"stylesheet\">\n");
out.write("<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.1.0/css/all.css\" integrity=\"sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt\" crossorigin=\"anonymous\">\n");
out.write("<link href=\"./resources/css/sidenav.css\" rel=\"stylesheet\">\n");
out.write("<link href=\"./resources/css/table.css\" rel=\"stylesheet\">\n");
out.write("<title>User Management</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("\t");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "../master/sidenav.jsp", out, false);
out.write("\n");
out.write("\t<div id=\"main\" class=\"main\">\n");
out.write("\t\t");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "../master/header.jsp", out, false);
out.write('\n');
out.write(' ');
out.write(' ');
if (_jspx_meth_c_005fif_005f0(_jspx_page_context))
return;
out.write('\n');
out.write(' ');
out.write(' ');
if (_jspx_meth_c_005fif_005f1(_jspx_page_context))
return;
out.write("\n");
out.write("\t\t<div class=\"mt-5 mx-1\">\n");
out.write("\t\t\t");
// form:form
org.springframework.web.servlet.tags.form.FormTag _jspx_th_form_005fform_005f0 = (org.springframework.web.servlet.tags.form.FormTag) _005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005faction.get(org.springframework.web.servlet.tags.form.FormTag.class);
try {
_jspx_th_form_005fform_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005fform_005f0.setParent(null);
// /protected/userAdm.jsp(26,3) name = method type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setMethod("GET");
// /protected/userAdm.jsp(26,3) name = action type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setAction("searchUser");
// /protected/userAdm.jsp(26,3) name = modelAttribute type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setModelAttribute("user");
int[] _jspx_push_body_count_form_005fform_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005fform_005f0 = _jspx_th_form_005fform_005f0.doStartTag();
if (_jspx_eval_form_005fform_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t\t<div class=\"row\">\n");
out.write("\t\t\t\t\t<div class=\"col-md-6\">\n");
out.write("\t\t\t\t\t\t");
if (_jspx_meth_form_005finput_005f0(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return;
out.write("\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\t\t\t\t\t<div class=\"col-md-6\">\n");
out.write("\t\t\t\t\t\t");
if (_jspx_meth_form_005finput_005f1(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return;
out.write("\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\t\t\t\t</div>\n");
out.write("\t\t\t\t<div class=\"row mt-1\">\n");
out.write("\t\t\t\t\t<div class=\"col-md-6\">\n");
out.write("\t\t\t\t\t\t");
if (_jspx_meth_form_005finput_005f2(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return;
out.write("\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\t\t\t\t\t<div class=\"col-md-6\">\n");
out.write("\t\t\t\t\t\t");
// form:select
org.springframework.web.servlet.tags.form.SelectTag _jspx_th_form_005fselect_005f0 = (org.springframework.web.servlet.tags.form.SelectTag) _005fjspx_005ftagPool_005fform_005fselect_0026_005fpath_005fmultiple_005fclass.get(org.springframework.web.servlet.tags.form.SelectTag.class);
try {
_jspx_th_form_005fselect_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005fselect_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /protected/userAdm.jsp(40,6) null
_jspx_th_form_005fselect_005f0.setDynamicAttribute(null, "class", "custom-select");
// /protected/userAdm.jsp(40,6) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fselect_005f0.setPath("roles");
// /protected/userAdm.jsp(40,6) name = multiple type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fselect_005f0.setMultiple("false");
int[] _jspx_push_body_count_form_005fselect_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005fselect_005f0 = _jspx_th_form_005fselect_005f0.doStartTag();
if (_jspx_eval_form_005fselect_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t\t\t\t\t");
// form:option
org.springframework.web.servlet.tags.form.OptionTag _jspx_th_form_005foption_005f0 = (org.springframework.web.servlet.tags.form.OptionTag) _005fjspx_005ftagPool_005fform_005foption_0026_005fvalue_005flabel_005fnobody.get(org.springframework.web.servlet.tags.form.OptionTag.class);
try {
_jspx_th_form_005foption_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005foption_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fselect_005f0);
// /protected/userAdm.jsp(41,7) name = value type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005foption_005f0.setValue("");
// /protected/userAdm.jsp(41,7) name = label type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005foption_005f0.setLabel("--Select Role--");
int[] _jspx_push_body_count_form_005foption_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005foption_005f0 = _jspx_th_form_005foption_005f0.doStartTag();
if (_jspx_th_form_005foption_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005foption_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005foption_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005foption_005f0.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005foption_0026_005fvalue_005flabel_005fnobody.reuse(_jspx_th_form_005foption_005f0);
}
out.write("\n");
out.write("\t\t\t\t\t\t\t");
if (_jspx_meth_form_005foptions_005f0(_jspx_th_form_005fselect_005f0, _jspx_page_context, _jspx_push_body_count_form_005fselect_005f0))
return;
out.write("\n");
out.write("\t\t\t\t\t\t");
int evalDoAfterBody = _jspx_th_form_005fselect_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_form_005fselect_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005fselect_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005fselect_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005fselect_005f0.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005fselect_0026_005fpath_005fmultiple_005fclass.reuse(_jspx_th_form_005fselect_005f0);
}
out.write("\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\t\t\t\t</div>\n");
out.write("\t\t\t\t<div class=\"row mt-1\">\n");
out.write("\t\t\t\t\t<div class=\"col-md-2\">\n");
out.write("\t\t\t\t\t\t<button type=\"submit\" class=\"btn btn-dark\" style=\"float: right; width: 100%;\">Search</button>\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\t\t\t\t</div>\n");
out.write("\t\t\t");
int evalDoAfterBody = _jspx_th_form_005fform_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_form_005fform_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005fform_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005fform_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005fform_005f0.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005faction.reuse(_jspx_th_form_005fform_005f0);
}
out.write("\n");
out.write("\t\t</div>\n");
out.write("\t\t<div class=\"mt-3 mx-1\">\n");
out.write("\t\t\t<table class=\"table table-bordered\" id=\"userTable\">\n");
out.write("\t\t\t\t<thead>\n");
out.write("\t\t\t\t\t<tr>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">Id</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">First Name</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">Last Name</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">Email</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">Username</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">Active</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\">Role</th>\n");
out.write("\t\t\t\t\t\t<th scope=\"col\"></th>\n");
out.write("\t\t\t\t\t</tr>\n");
out.write("\t\t\t\t</thead>\n");
out.write("\t\t\t\t");
if (_jspx_meth_c_005fforEach_005f0(_jspx_page_context))
return;
out.write("\n");
out.write("\t\t\t</table>\n");
out.write("\t\t\t<a class=\"btn btn-outline-primary\" href=\"addUser\">Add</a>\n");
out.write("\t\t</div>\n");
out.write("\n");
out.write("\t</div>\n");
out.write("\t<script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script>\n");
out.write("\t<script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"></script>\n");
out.write("\t<script src=\"./resources/js/bootstrap.min.js\"></script>\n");
out.write("</body>\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_005fif_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
try {
_jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fif_005f0.setParent(null);
// /protected/userAdm.jsp(19,2) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fif_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${not empty messageSuccess}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag();
if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t<div class=\"alert alert-success\" role=\"alert\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${messageSuccess}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</div>\n");
out.write("\t\t");
int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} finally {
_005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0);
}
return false;
}
private boolean _jspx_meth_c_005fif_005f1(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f1 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
try {
_jspx_th_c_005fif_005f1.setPageContext(_jspx_page_context);
_jspx_th_c_005fif_005f1.setParent(null);
// /protected/userAdm.jsp(22,2) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fif_005f1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${not empty messageFail}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_005fif_005f1 = _jspx_th_c_005fif_005f1.doStartTag();
if (_jspx_eval_c_005fif_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t<div class=\"alert alert-danger\" role=\"alert\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${messageFail}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</div>\n");
out.write("\t\t");
int evalDoAfterBody = _jspx_th_c_005fif_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_005fif_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} finally {
_005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f1);
}
return false;
}
private boolean _jspx_meth_form_005finput_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_005finput_005f0 = (org.springframework.web.servlet.tags.form.InputTag) _005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
try {
_jspx_th_form_005finput_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005finput_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /protected/userAdm.jsp(29,6) null
_jspx_th_form_005finput_005f0.setDynamicAttribute(null, "type", "text");
// /protected/userAdm.jsp(29,6) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f0.setPath("firstName");
// /protected/userAdm.jsp(29,6) null
_jspx_th_form_005finput_005f0.setDynamicAttribute(null, "class", "form-control");
// /protected/userAdm.jsp(29,6) null
_jspx_th_form_005finput_005f0.setDynamicAttribute(null, "placeholder", "First Name");
// /protected/userAdm.jsp(29,6) null
_jspx_th_form_005finput_005f0.setDynamicAttribute(null, "aria-label", "First Name");
int[] _jspx_push_body_count_form_005finput_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005finput_005f0 = _jspx_th_form_005finput_005f0.doStartTag();
if (_jspx_th_form_005finput_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005finput_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005finput_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005finput_005f0.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.reuse(_jspx_th_form_005finput_005f0);
}
return false;
}
private boolean _jspx_meth_form_005finput_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_005finput_005f1 = (org.springframework.web.servlet.tags.form.InputTag) _005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
try {
_jspx_th_form_005finput_005f1.setPageContext(_jspx_page_context);
_jspx_th_form_005finput_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /protected/userAdm.jsp(32,6) null
_jspx_th_form_005finput_005f1.setDynamicAttribute(null, "type", "text");
// /protected/userAdm.jsp(32,6) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f1.setPath("lastName");
// /protected/userAdm.jsp(32,6) null
_jspx_th_form_005finput_005f1.setDynamicAttribute(null, "class", "form-control");
// /protected/userAdm.jsp(32,6) null
_jspx_th_form_005finput_005f1.setDynamicAttribute(null, "placeholder", "Last Name");
// /protected/userAdm.jsp(32,6) null
_jspx_th_form_005finput_005f1.setDynamicAttribute(null, "aria-label", "Last Name");
int[] _jspx_push_body_count_form_005finput_005f1 = new int[] { 0 };
try {
int _jspx_eval_form_005finput_005f1 = _jspx_th_form_005finput_005f1.doStartTag();
if (_jspx_th_form_005finput_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005finput_005f1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005finput_005f1.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005finput_005f1.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.reuse(_jspx_th_form_005finput_005f1);
}
return false;
}
private boolean _jspx_meth_form_005finput_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_005finput_005f2 = (org.springframework.web.servlet.tags.form.InputTag) _005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
try {
_jspx_th_form_005finput_005f2.setPageContext(_jspx_page_context);
_jspx_th_form_005finput_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /protected/userAdm.jsp(37,6) null
_jspx_th_form_005finput_005f2.setDynamicAttribute(null, "type", "text");
// /protected/userAdm.jsp(37,6) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f2.setPath("username");
// /protected/userAdm.jsp(37,6) null
_jspx_th_form_005finput_005f2.setDynamicAttribute(null, "class", "form-control");
// /protected/userAdm.jsp(37,6) null
_jspx_th_form_005finput_005f2.setDynamicAttribute(null, "placeholder", "Username");
// /protected/userAdm.jsp(37,6) null
_jspx_th_form_005finput_005f2.setDynamicAttribute(null, "aria-label", "Username");
int[] _jspx_push_body_count_form_005finput_005f2 = new int[] { 0 };
try {
int _jspx_eval_form_005finput_005f2 = _jspx_th_form_005finput_005f2.doStartTag();
if (_jspx_th_form_005finput_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005finput_005f2[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005finput_005f2.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005finput_005f2.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005finput_0026_005ftype_005fplaceholder_005fpath_005fclass_005faria_002dlabel_005fnobody.reuse(_jspx_th_form_005finput_005f2);
}
return false;
}
private boolean _jspx_meth_form_005foptions_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fselect_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fselect_005f0)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// form:options
org.springframework.web.servlet.tags.form.OptionsTag _jspx_th_form_005foptions_005f0 = (org.springframework.web.servlet.tags.form.OptionsTag) _005fjspx_005ftagPool_005fform_005foptions_0026_005fitems_005fitemValue_005fitemLabel_005fnobody.get(org.springframework.web.servlet.tags.form.OptionsTag.class);
try {
_jspx_th_form_005foptions_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005foptions_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fselect_005f0);
// /protected/userAdm.jsp(42,7) name = items type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005foptions_005f0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${allRoles}", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
// /protected/userAdm.jsp(42,7) name = itemValue type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005foptions_005f0.setItemValue("id");
// /protected/userAdm.jsp(42,7) name = itemLabel type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005foptions_005f0.setItemLabel("name");
int[] _jspx_push_body_count_form_005foptions_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005foptions_005f0 = _jspx_th_form_005foptions_005f0.doStartTag();
if (_jspx_th_form_005foptions_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005foptions_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005foptions_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005foptions_005f0.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fform_005foptions_0026_005fitems_005fitemValue_005fitemLabel_005fnobody.reuse(_jspx_th_form_005foptions_005f0);
}
return false;
}
private boolean _jspx_meth_c_005fforEach_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
try {
_jspx_th_c_005fforEach_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fforEach_005f0.setParent(null);
// /protected/userAdm.jsp(67,4) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fforEach_005f0.setVar("emp");
// /protected/userAdm.jsp(67,4) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null
_jspx_th_c_005fforEach_005f0.setItems(new org.apache.jasper.el.JspValueExpression("/protected/userAdm.jsp(67,4) '${list}'",_jsp_getExpressionFactory().createValueExpression(_jspx_page_context.getELContext(),"${list}",java.lang.Object.class)).getValue(_jspx_page_context.getELContext()));
int[] _jspx_push_body_count_c_005fforEach_005f0 = new int[] { 0 };
try {
int _jspx_eval_c_005fforEach_005f0 = _jspx_th_c_005fforEach_005f0.doStartTag();
if (_jspx_eval_c_005fforEach_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t\t\t<tr>\n");
out.write("\t\t\t\t\t\t<th scope=\"row\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</th>\n");
out.write("\t\t\t\t\t\t<td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.firstName}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</td>\n");
out.write("\t\t\t\t\t\t<td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.lastName}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</td>\n");
out.write("\t\t\t\t\t\t<td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.email}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</td>\n");
out.write("\t\t\t\t\t\t<td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.username}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</td>\n");
out.write("\t\t\t\t\t\t<td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.active}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</td>\n");
out.write("\t\t\t\t\t\t<td>\n");
out.write("\t\t\t\t\t\t\t");
if (_jspx_meth_c_005fforEach_005f1(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0))
return true;
out.write("</td>\n");
out.write("\t\t\t\t\t\t<td class=\"table-buttons\"><a href=\"deleteUser-");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("\">\n");
out.write("\t\t\t\t\t\t\t\t<i class=\"far fa-trash-alt\"></i>\n");
out.write("\t\t\t\t\t\t\t</a> <a href=\"editUser-");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${emp.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("\">\n");
out.write("\t\t\t\t\t\t\t\t<i class=\"fas fa-pencil-alt\"></i>\n");
out.write("\t\t\t\t\t\t\t</a></td>\n");
out.write("\t\t\t\t\t</tr>\n");
out.write("\t\t\t\t");
int evalDoAfterBody = _jspx_th_c_005fforEach_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_005fforEach_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_c_005fforEach_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_005fforEach_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_005fforEach_005f0.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f0);
}
return false;
}
private boolean _jspx_meth_c_005fforEach_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
try {
_jspx_th_c_005fforEach_005f1.setPageContext(_jspx_page_context);
_jspx_th_c_005fforEach_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0);
// /protected/userAdm.jsp(76,7) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fforEach_005f1.setVar("role");
// /protected/userAdm.jsp(76,7) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null
_jspx_th_c_005fforEach_005f1.setItems(new org.apache.jasper.el.JspValueExpression("/protected/userAdm.jsp(76,7) '${emp.roles }'",_jsp_getExpressionFactory().createValueExpression(_jspx_page_context.getELContext(),"${emp.roles }",java.lang.Object.class)).getValue(_jspx_page_context.getELContext()));
int[] _jspx_push_body_count_c_005fforEach_005f1 = new int[] { 0 };
try {
int _jspx_eval_c_005fforEach_005f1 = _jspx_th_c_005fforEach_005f1.doStartTag();
if (_jspx_eval_c_005fforEach_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t\t\t\t\t\t<p class=\"table-inline\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${role.name}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
out.write("</p>\n");
out.write("\t\t\t\t\t\t\t");
int evalDoAfterBody = _jspx_th_c_005fforEach_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_005fforEach_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (java.lang.Throwable _jspx_exception) {
while (_jspx_push_body_count_c_005fforEach_005f1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_005fforEach_005f1.doCatch(_jspx_exception);
} finally {
_jspx_th_c_005fforEach_005f1.doFinally();
}
} finally {
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f1);
}
return false;
}
}
|
package com.turios.util;
public class Constants {
public static final String GATracker = "UA-42903975-2";
public static final String DELIMITER = "|";
public static final String INTENT_NETWORKSTATE_CHANGED = "android.net.conn.CONNECTIVITY_CHANGE";
public static final String INTENT_INCOMMING_MESSAGE = "cyrix.turios.INCOMMING_MESSAGE";
public static final String INTENT_INCOMMING_PARSESMS = "cyrix.turios.INCOMMING_PARSESMS";
public static final String INTENT_MESSAGE_SENT = "cyrix.turios.SENT";
public static final String INTENT_REFRESH_MODULES = "cyrix.turios.REFRESH_MODULES";
public static final String EXTRA_HOME = "cyrix.turios.HOME";
public static final String EXTRA_FILENAME = "cyrix.turios.FILENAME";
public static final String EXTRA_FILEPATH = "cyrix.turios.FILEPATH";
public static final String EXTRA_FOLDERPATH = "cyrix.turios.FOLDERPATH";
public static final String EXTRA_MODIFIED = "cyrix.turios.MODIFIED";
public static final String EXTRA_RECEIVER = "cyrix.turios.RECEIVER";
// public static final String EXTRA_SETUP = "cyrix.turios.SETUP";
public static final String EXTRA_ID = "cyrix.turios.ID";
public static final String EXTRA_ACTION = "cyrix.turios.ACTION";
public static final String EXTRA_SENDER = "cyrix.turios.SENDER";
public static final String EXTRA_TITLE = "cyrix.turios.TITLE";
public static final String EXTRA_MESSAGE = "cyrix.turios.MESSAGE";
public static final String EXTRA_STRING_MESSAGE = "cyrix.turios.STRING_MESSAGE";
public static final String EXTRA_CHANNELS = "cyrix.turios.CHANNELS";
public static final String EXTRA_ICON = "cyrix.turios.ICON";
public static final String EXTRA_RECEIVERS = "cyrix.turios.RECEIVERS";
public static final String EXTRA_SUCCESS = "cyrix.turios.SUCCESS";
public static final String EXTRA_DELETE = "cyrix.turios.DELETE";
public static final String EXTRA_PAGE = "cyrix.turios.PAGE";
public static final String EXTRA_DATE = "cyrix.turios.DATE";
public static final String EXTRA_STRINGARRAY = "cyrix.turios.STRINGARRAY";
public static final String EXTENSION_PDF = ".pdf";
public static final String EXTENSION_TXT = ".txt";
public static final int DELAY_DELETION_MINUTES = 30;
public static final String DROPBOX_APPKEY = "btn5vewgedxxmed";
public static final String DROPBOX_SECRETKEY = "pe2d7rzgsua0xpd";
public static final String UPDATE_VERSIONCHECK_URL = "http://www.turios.dk/latest-versioncode.txt";
public static final String UPDATE_DOWNLOAD_URL = "http://www.turios.dk/turios.apk";
public static final String FILETYPE_TXT = ".txt";
public static final String FILETYPE_CSV = ".csv";
public static final String FILETYPE_PNG = ".png";
}
|
package org.mehaexample.asdDemo.dao.alignprivate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.mehaexample.asdDemo.dao.alignpublic.MultipleValueAggregatedDataDao;
import org.mehaexample.asdDemo.enums.Campus;
import org.mehaexample.asdDemo.model.alignadmin.CompanyRatio;
import org.mehaexample.asdDemo.model.alignadmin.TopBachelor;
import org.mehaexample.asdDemo.model.alignadmin.TopEmployer;
import org.mehaexample.asdDemo.model.alignprivate.Privacies;
import org.mehaexample.asdDemo.model.alignprivate.StudentBasicInfo;
import org.mehaexample.asdDemo.model.alignprivate.StudentCoopList;
import org.mehaexample.asdDemo.model.alignprivate.WorkExperiences;
import org.mehaexample.asdDemo.model.alignpublic.MultipleValueAggregatedData;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WorkExperiencesDao {
private SessionFactory factory;
private PrivaciesDao privaciesDao;
/**
* Default constructor.
* it will check the Hibernate.cfg.xml file and load it
* next it goes to all table files in the hibernate file and loads them.
*/
public WorkExperiencesDao() {
privaciesDao = new PrivaciesDao();
this.factory = StudentSessionFactory.getFactory();
}
public WorkExperiencesDao(boolean test) {
if (test) {
privaciesDao = new PrivaciesDao(true);
this.factory = StudentTestSessionFactory.getFactory();
}
}
/**
* Find a Work Experience by the Work Experience Id.
* This method searches the work experience from the private database.
*
* @param workExperienceId work experience Id in private database.
* @return Work Experience if found.
*/
public WorkExperiences getWorkExperienceById(int workExperienceId) {
Session session = factory.openSession();
try {
org.hibernate.query.Query query = session.createQuery(
"FROM WorkExperiences WHERE workExperienceId = :workExperienceId");
query.setParameter("workExperienceId", workExperienceId);
List<WorkExperiences> listOfWorkExperience = query.list();
if (listOfWorkExperience.isEmpty())
return null;
return listOfWorkExperience.get(0);
} finally {
session.close();
}
}
/**
* Find work experience records of a student in private DB.
*
* @param neuId the neu Id of a student; not null.
* @return List of Work Experiences.
*/
public List<WorkExperiences> getWorkExperiencesByNeuId(String neuId) {
Session session = factory.openSession();
try {
org.hibernate.query.Query query = session.createQuery(
"FROM WorkExperiences WHERE neuId = :neuId");
query.setParameter("neuId", neuId);
return (List<WorkExperiences>) query.list();
} finally {
session.close();
}
}
/**
* Find work experience record of a student in private DB; however
* set null to the things that are supposed to be hidden.
*
* @param neuId student neu Id.
* @return list of work experiences.
*/
public List<WorkExperiences> getWorkExperiencesWithPrivacy(String neuId) {
Privacies privacy = privaciesDao.getPrivacyByNeuId(neuId);
if (!privacy.isCoop()) {
return new ArrayList<>();
} else {
return getWorkExperiencesByNeuId(neuId);
}
}
/**
* Create a work experience in the private database.
* This function requires the StudentsPublic object and the Companies
* object inside the work experience object to be not null.
*
* @param workExperience the work experience object to be created; not null.
* @return newly created WorkExperience if success. Otherwise, return null;
*/
public synchronized WorkExperiences createWorkExperience(WorkExperiences workExperience) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(workExperience);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e);
} finally {
session.close();
}
return workExperience;
}
/**
* Delete a work experience in the private database.
*
* @param workExperienceId the work experience Id to be deleted.
* @return true if work experience is deleted, false otherwise.
*/
public synchronized boolean deleteWorkExperienceById(int workExperienceId) {
WorkExperiences workExperiences = getWorkExperienceById(workExperienceId);
if (workExperiences != null) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(workExperiences);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e);
} finally {
session.close();
}
} else {
throw new HibernateException("work experience id does not exist");
}
return true;
}
/**
* Delete all work experiences corresponding to a student neu Id.
*
* @param neuId student neu Id.
* @return true if deleted.
* @throws HibernateException if neuId does not exist or connection
* has something wrong.
*/
public synchronized boolean deleteWorkExperienceByNeuId(String neuId) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
org.hibernate.query.Query query = session.createQuery("DELETE FROM WorkExperiences " +
"WHERE neuId = :neuId ");
query.setParameter("neuId", neuId);
query.executeUpdate();
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e);
} finally {
session.close();
}
return true;
}
/**
* Update a work experience in the private DB.
*
* @param workExperience work experience object; not null.
* @return true if the work experience is updated, false otherwise.
*/
public synchronized boolean updateWorkExperience(WorkExperiences workExperience) {
if (getWorkExperienceById(workExperience.getWorkExperienceId()) != null) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(workExperience);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
throw new HibernateException(e);
} finally {
session.close();
}
} else {
throw new HibernateException("Work Experience ID does not exist");
}
return true;
}
/**
* Get Top ten employers with the count of students from the private database
* based on the campus location and students' year of expected graduation.
*
* @param campuses campus location.
* @param year year of expected of graduation of students.
* @return list of top ten employers with count of students.
*/
public List<TopEmployer> getTopTenEmployers(List<Campus> campuses, Integer year) {
StringBuilder hql = new StringBuilder("SELECT NEW org.mehaexample.asdDemo.model.alignadmin.TopEmployer( " +
"we.companyName, Count(*) ) " +
"FROM Students s INNER JOIN WorkExperiences we " +
"ON s.neuId = we.neuId " +
"WHERE we.coop = false ");
if (campuses != null) {
hql.append("AND s.campus IN (:campuses) ");
}
if (year != null) {
hql.append("AND s.expectedLastYear = :year ");
}
hql.append("GROUP BY we.companyName ");
hql.append("ORDER BY Count(*) DESC ");
Session session = factory.openSession();
try {
TypedQuery<TopEmployer> query = session.createQuery(hql.toString(), TopEmployer.class);
query.setMaxResults(10);
if (campuses != null) {
query.setParameter("campuses", campuses);
}
if (year != null) {
query.setParameter("year", year);
}
return query.getResultList();
} finally {
session.close();
}
}
/**
* Find all students with their coop lists based on the campus location
* and students' year of expected graduation.
*
* @param campus campus location.
* @param year year of expected graduation.
* @return list of students with their coop lists.
*/
public List<StudentCoopList> getStudentCoopCompanies(List<Campus> campus, Integer year) {
StringBuilder hql = new StringBuilder("SELECT DISTINCT NEW org.mehaexample.asdDemo.model.alignprivate.StudentCoopList( " +
"s.neuId, s.firstName, s.lastName ) " +
"FROM Students s INNER JOIN WorkExperiences we " +
"ON s.neuId = we.neuId " +
"WHERE we.coop = true ");
if (campus != null) {
hql.append("AND s.campus IN (:campus) ");
}
if (year != null) {
hql.append("AND s.expectedLastYear = :year ");
}
Session session = factory.openSession();
try {
TypedQuery<StudentCoopList> query = session.createQuery(hql.toString(), StudentCoopList.class);
if (campus != null) {
query.setParameter("campus", campus);
}
if (year != null) {
query.setParameter("year", year);
}
List<StudentCoopList> studentCoopLists = query.getResultList();
for (StudentCoopList student : studentCoopLists) {
student.setCompanies(getCompaniesByNeuId(student.getNeuId()));
}
return studentCoopLists;
} finally {
session.close();
}
}
/**
* Get coop companies based on the neu Id. this method is for
* populating all the coop lists for each student in the
* getStudentCoopCompanies method.
*
* @param neuId student neuId.
* @return list of coop companies.
*/
private List<String> getCompaniesByNeuId(String neuId) {
Session session = factory.openSession();
try {
org.hibernate.query.Query query = session.createQuery(
"SELECT we.companyName FROM WorkExperiences we WHERE we.coop = true AND we.neuId = :neuId");
query.setParameter("neuId", neuId);
return (List<String>) query.list();
} finally {
session.close();
}
}
/**
* Get a student work in a specific company. The student return will only
* consist of first name, last name, and neu Id.a
*
* @param campus Campus location.
* @param year year of expected graduation.
* @param companyName name of company.
* @return list of students working in a specific company.
*/
public List<StudentBasicInfo> getStudentsWorkingInACompany(List<Campus> campus, Integer year, String companyName) {
StringBuilder hql = new StringBuilder("SELECT DISTINCT NEW org.mehaexample.asdDemo.model.alignprivate.StudentBasicInfo( " +
"s.firstName, s.lastName, s.neuId ) " +
"FROM Students s INNER JOIN WorkExperiences we " +
"ON s.neuId = we.neuId " +
"WHERE we.companyName = :companyName " +
"AND we.coop = false ");
if (campus != null) {
hql.append("AND s.campus IN (:campus)");
}
if (year != null) {
hql.append("AND s.expectedLastYear = :year ");
}
Session session = factory.openSession();
try {
TypedQuery<StudentBasicInfo> query = session.createQuery(hql.toString(), StudentBasicInfo.class);
query.setParameter("companyName", companyName);
if (campus != null) {
query.setParameter("campus", campus);
}
if (year != null) {
query.setParameter("year", year);
}
return query.getResultList();
} finally {
session.close();
}
}
/**
* Get list of students currently working in companies. This will also return
* the companies that the student is currently working on.
*
* @param campus campus location.
* @param year year of expected graduation.
* @return list of students currently working in companies.
*/
public List<StudentCoopList> getStudentCurrentCompanies(List<Campus> campus, Integer year) {
StringBuilder hql = new StringBuilder("SELECT DISTINCT NEW org.mehaexample.asdDemo.model.alignprivate.StudentCoopList( " +
"s.neuId, s.firstName, s.lastName ) " +
"FROM Students s INNER JOIN WorkExperiences we " +
"ON s.neuId = we.neuId ");
hql.append("WHERE we.currentJob = true AND we.coop = false ");
if (campus != null) {
hql.append("AND s.campus IN (:campus) ");
}
if (year != null) {
hql.append("AND ");
hql.append("s.expectedLastYear = :year ");
}
Session session = factory.openSession();
try {
TypedQuery<StudentCoopList> query = session.createQuery(hql.toString(), StudentCoopList.class);
if (campus != null) {
query.setParameter("campus", campus);
}
if (year != null) {
query.setParameter("year", year);
}
List<StudentCoopList> studentCoopLists = query.getResultList();
for (StudentCoopList student : studentCoopLists) {
student.setCompanies(getCurrentCompaniesByNeuId(student.getNeuId()));
}
return studentCoopLists;
} finally {
session.close();
}
}
/**
* Retrieving the yearly count ratio of students for a company
* @param campus a list of campus locations
* @param companyName company name
* @return a list of company ratio
*/
public List<CompanyRatio> getStudentCompanyRatio(List<Campus> campus, String companyName) {
String hql = "SELECT DISTINCT NEW org.mehaexample.asdDemo.model.alignadmin.CompanyRatio(" +
"YEAR(we.startDate), cast(Count(DISTINCT s.neuId) as integer)) " +
"FROM Students s INNER JOIN WorkExperiences we " +
"ON s.neuId = we.neuId " +
"WHERE we.companyName = :companyName " +
"AND s.campus IN (:campus) " +
"GROUP BY YEAR(we.startDate) " +
"ORDER BY YEAR(we.startDate) ASC ";
Session session = factory.openSession();
try {
TypedQuery<CompanyRatio> query = session.createQuery(hql, CompanyRatio.class);
query.setParameter("companyName", companyName);
query.setParameter("campus", campus);
List<CompanyRatio> companyRatioList = query.getResultList();
return companyRatioList;
} finally {
session.close();
}
}
/**
* Get list of current companies based on neu Id.
*
* @param neuId student neu Id.
* @return list of current companies.
*/
private List<String> getCurrentCompaniesByNeuId(String neuId) {
Session session = factory.openSession();
try {
org.hibernate.query.Query query = session.createQuery(
"SELECT we.companyName FROM WorkExperiences we " +
"WHERE we.currentJob = true AND we.neuId = :neuId AND we.coop = false");
query.setParameter("neuId", neuId);
return (List<String>) query.list();
} finally {
session.close();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.