text
stringlengths
10
2.72M
/* * Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.frdfsnlght.transporter.command; import com.frdfsnlght.transporter.Context; import com.frdfsnlght.transporter.Economy; import com.frdfsnlght.transporter.GateImpl; import com.frdfsnlght.transporter.Gates; import com.frdfsnlght.transporter.Global; import com.frdfsnlght.transporter.LocalAreaGateImpl; import com.frdfsnlght.transporter.LocalGateImpl; import com.frdfsnlght.transporter.Permissions; import com.frdfsnlght.transporter.RemoteGateImpl; import com.frdfsnlght.transporter.Server; import com.frdfsnlght.transporter.Utils; import com.frdfsnlght.transporter.api.ExpandDirection; import com.frdfsnlght.transporter.api.GateType; import com.frdfsnlght.transporter.api.TransporterException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.Command; /** * * @author frdfsnlght <frdfsnlght@gmail.com> */ public class GateCommand extends TrpCommandProcessor { private static final String GROUP = "gate "; @Override public boolean matches(Context ctx, Command cmd, List<String> args) { return super.matches(ctx, cmd, args) && GROUP.startsWith(args.get(0).toLowerCase()); } @Override public List<String> getUsage(Context ctx) { List<String> cmds = new ArrayList<String>(); cmds.add(getPrefix(ctx) + GROUP + "list"); cmds.add(getPrefix(ctx) + GROUP + "select <gate>"); cmds.add(getPrefix(ctx) + GROUP + "info [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "open [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "close [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "rebuild [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "destroy [<gate>] [unbuild]"); cmds.add(getPrefix(ctx) + GROUP + "rename <newname> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "link add [<from>] <to> [rev]"); cmds.add(getPrefix(ctx) + GROUP + "link remove [<from>] <to> [rev]"); cmds.add(getPrefix(ctx) + GROUP + "link next [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "pin add <pin> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "pin remove <pin>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "ban item list [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "ban item add <item> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "ban item remove <item>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "allow item list [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "allow item add <item> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "allow item remove <item>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "replace item list [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "replace item add <old> <new> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "replace item remove <old>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "ban potion list [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "ban potion add <potion> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "ban potion remove <potion>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "allow potion list [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "allow potion add <potion> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "allow potion remove <potion>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "replace potion list [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "replace potion add <old> <new> [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "replace potion remove <old>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "resize <num>[,<direction>] [<gate>]"); if (ctx.isPlayer()) { cmds.add(getPrefix(ctx) + GROUP + "corner 1|2 [pick] [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "create <designname>|area|server <gatename> [<to> [rev]]"); } cmds.add(getPrefix(ctx) + GROUP + "get <option>|* [<gate>]"); cmds.add(getPrefix(ctx) + GROUP + "set <option> <value> [<gate>]"); return cmds; } @Override public void process(Context ctx, Command cmd, List<String> args) throws TransporterException { args.remove(0); if (args.isEmpty()) throw new CommandException("do what with a gate?"); String subCmd = args.remove(0).toLowerCase(); if ("list".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.list"); List<LocalGateImpl> localGates = new ArrayList<LocalGateImpl>(Gates.getLocalGates()); if ((! ctx.isConsole()) && (! ctx.isOp())) for (Iterator<LocalGateImpl> i = localGates.iterator(); i.hasNext(); ) if (i.next().getHidden()) i.remove(); if (localGates.isEmpty()) ctx.send("there are no local gates"); else { Collections.sort(localGates, new Comparator<LocalGateImpl>() { @Override public int compare(LocalGateImpl a, LocalGateImpl b) { return a.getLocalName().compareToIgnoreCase(b.getLocalName()); } }); ctx.send("%d local gates:", localGates.size()); for (LocalGateImpl gate : localGates) ctx.send(" %s", gate.getLocalName()); } List<RemoteGateImpl> remoteGates = new ArrayList<RemoteGateImpl>(Gates.getRemoteGates()); if ((! ctx.isConsole()) && (! ctx.isOp())) for (Iterator<RemoteGateImpl> i = remoteGates.iterator(); i.hasNext(); ) if (i.next().getHidden()) i.remove(); if (remoteGates.isEmpty()) ctx.send("there are no remote gates"); else { Collections.sort(remoteGates, new Comparator<RemoteGateImpl>() { @Override public int compare(RemoteGateImpl a, RemoteGateImpl b) { return a.getFullName().compareToIgnoreCase(b.getFullName()); } }); ctx.send("%d remote gates:", remoteGates.size()); for (RemoteGateImpl gate : remoteGates) ctx.send(" %s", gate.getFullName()); } return; } if ("select".startsWith(subCmd)) { LocalGateImpl gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.select." + gate.getFullName()); Gates.setSelectedGate(ctx.getPlayer(), gate); ctx.send("selected gate '%s'", gate.getFullName()); return; } if ("info".startsWith(subCmd)) { LocalGateImpl gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.info." + gate.getFullName()); ctx.send("Full name: %s", gate.getFullName()); ctx.send("Type: %s", gate.getType().toString()); ctx.send("Creator: %s", gate.getCreatorName()); if (Economy.isAvailable()) { if (gate.getLinkLocal()) ctx.send("On-world travel cost: %s/%s", Economy.format(gate.getSendLocalCost()), Economy.format(gate.getReceiveLocalCost())); if (gate.getLinkWorld()) ctx.send("Off-world travel cost: %s/%s", Economy.format(gate.getSendWorldCost()), Economy.format(gate.getReceiveWorldCost())); if (gate.getLinkServer()) ctx.send("Off-server travel cost: %s/%s", Economy.format(gate.getSendServerCost()), Economy.format(gate.getReceiveServerCost())); } List<String> links = gate.getLinks(); ctx.send("Links: %d", links.size()); for (String link : links) ctx.send(" %s%s", link.equals(gate.getDestinationLink()) ? "*": "", link); return; } if ("open".startsWith(subCmd)) { LocalGateImpl gate = getGate(ctx, args); if (gate.isOpen()) ctx.warn("gate '%s' is already open", gate.getName(ctx)); else { Permissions.require(ctx.getPlayer(), "trp.gate.open." + gate.getFullName()); gate.open(); ctx.sendLog("opened gate '%s'", gate.getName(ctx)); } return; } if ("close".startsWith(subCmd)) { LocalGateImpl gate = getGate(ctx, args); if (gate.isOpen()) { Permissions.require(ctx.getPlayer(), "trp.gate.close." + gate.getFullName()); gate.close(); ctx.sendLog("closed gate '%s'", gate.getName(ctx)); } else ctx.warn("gate '%s' is already closed", gate.getName(ctx)); return; } if ("rebuild".startsWith(subCmd)) { LocalGateImpl gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.rebuild." + gate.getFullName()); gate.rebuild(); ctx.sendLog("rebuilt gate '%s'", gate.getName(ctx)); return; } if ("destroy".startsWith(subCmd)) { boolean unbuild = false; if ((args.size() > 0) && "unbuild".startsWith(args.get(args.size() - 1).toLowerCase())) { unbuild = true; args.remove(args.size() - 1); } LocalGateImpl gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.destroy." + gate.getFullName()); Gates.destroy(gate, unbuild); ctx.sendLog("destroyed gate '%s'", gate.getName(ctx)); return; } if ("rename".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("new name required"); String newName = args.remove(0); LocalGateImpl gate = getGate(ctx, args); String oldName = gate.getName(ctx); Permissions.require(ctx.getPlayer(), "trp.gate.rename"); Gates.rename(gate, newName); ctx.sendLog("renamed gate '%s' to '%s'", oldName, gate.getName(ctx)); return; } if ("link".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("do what with a link?"); subCmd = args.remove(0).toLowerCase(); if ("next".startsWith(subCmd)) { LocalGateImpl fromGate = getGate(ctx, args); fromGate.nextLink(); return; } if (args.isEmpty()) throw new CommandException("destination endpoint required"); boolean reverse = false; if ("reverse".startsWith(args.get(args.size() - 1).toLowerCase())) { reverse = true; args.remove(args.size() - 1); } if (args.isEmpty()) throw new CommandException("destination endpoint required"); String toGateName = args.remove(args.size() - 1); LocalGateImpl fromGate = getGate(ctx, args); GateImpl toGate = Gates.find(ctx, toGateName); if ("add".startsWith(subCmd)) { fromGate.addLink(ctx, toGateName); if (reverse && (ctx.getSender() != null) && (toGate != null)) { if (toGate.isSameServer()) Global.plugin.getServer().dispatchCommand(ctx.getSender(), "trp gate link add \"" + toGate.getFullName() + "\" \"" + fromGate.getFullName() + "\""); else { Server server = (Server)((RemoteGateImpl)toGate).getRemoteServer(); if (! server.isConnectionConnected()) ctx.send("unable to add reverse link from offline server"); else server.sendLinkAdd(ctx.getPlayer(), (LocalGateImpl)fromGate, (RemoteGateImpl)toGate); } } return; } if ("remove".startsWith(subCmd)) { fromGate.removeLink(ctx, toGateName); if (reverse && (ctx.getSender() != null) && (toGate != null)) { if (toGate.isSameServer()) Global.plugin.getServer().dispatchCommand(ctx.getSender(), "trp gate link remove \"" + fromGate.getFullName() + "\" \"" + toGate.getFullName() + "\""); else { Server server = (Server)((RemoteGateImpl)toGate).getRemoteServer(); if (! server.isConnectionConnected()) ctx.send("unable to remove reverse link from offline server"); else server.sendLinkRemove(ctx.getPlayer(), (LocalGateImpl)fromGate, (RemoteGateImpl)toGate); } } return; } throw new CommandException("do what with a link?"); } if ("pin".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("do what with a pin?"); subCmd = args.remove(0).toLowerCase(); if (args.isEmpty()) throw new CommandException("pin required"); String pin = args.remove(0); LocalGateImpl gate = getGate(ctx, args); if ("add".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.pin.add." + gate.getFullName()); if (gate.addPin(pin)) ctx.send("added pin to '%s'", gate.getName(ctx)); else throw new CommandException("pin is already added"); return; } if ("remove".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.pin.remove." + gate.getFullName()); if (pin.equals("*")) { gate.removeAllPins(); ctx.send("removed all pins from '%s'", gate.getName(ctx)); } else if (gate.removePin(pin)) ctx.send("removed pin from '%s'", gate.getName(ctx)); else throw new CommandException("pin not found"); return; } throw new CommandException("do what with a pin?"); } if ("ban".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("what type of ban?"); String type = args.remove(0).toLowerCase(); if (args.isEmpty()) throw new CommandException("do what with a ban?"); subCmd = args.remove(0).toLowerCase(); LocalGateImpl gate; if ("item".startsWith(type)) { if ("list".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.ban.item.list." + gate.getFullName()); List<String> items = new ArrayList<String>(gate.getBannedItems()); Collections.sort(items); ctx.send("%s items", items.size()); for (String item : items) ctx.send(" %s", item); return; } if (args.isEmpty()) throw new CommandException("item required"); String item = args.remove(0); gate = getGate(ctx, args); if ("add".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.ban.item.add." + gate.getFullName()); if (gate.addBannedItem(item)) ctx.send("added banned item to '%s'", gate.getName(ctx)); else throw new CommandException("item is already banned"); return; } if ("remove".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.ban.item.remove." + gate.getFullName()); if (item.equals("*")) { gate.removeAllBannedItems(); ctx.send("removed all banned items from '%s'", gate.getName(ctx)); } else if (gate.removeBannedItem(item)) ctx.send("removed banned item from '%s'", gate.getName(ctx)); else throw new CommandException("banned item not found"); return; } throw new CommandException("do what with an item ban?"); } if ("potion".startsWith(type)) { if ("list".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.ban.potion.list." + gate.getFullName()); List<String> potions = new ArrayList<String>(gate.getBannedPotions()); Collections.sort(potions); ctx.send("%s potion effects", potions.size()); for (String potion : potions) ctx.send(" %s", potion); return; } if (args.isEmpty()) throw new CommandException("potion effect required"); String potion = args.remove(0); gate = getGate(ctx, args); if ("add".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.ban.potion.add." + gate.getFullName()); if (gate.addBannedPotion(potion)) ctx.send("added banned potion effect to '%s'", gate.getName(ctx)); else throw new CommandException("potion effect is already banned"); return; } if ("remove".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.ban.potion.remove." + gate.getFullName()); if (potion.equals("*")) { gate.removeAllBannedPotions(); ctx.send("removed all banned potion effects from '%s'", gate.getName(ctx)); } else if (gate.removeBannedPotion(potion)) ctx.send("removed banned potion effect from '%s'", gate.getName(ctx)); else throw new CommandException("banned potion effect not found"); return; } throw new CommandException("do what with a potion effect ban?"); } throw new CommandException("do what with a ban?"); } if ("allow".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("what type of allow?"); String type = args.remove(0).toLowerCase(); if (args.isEmpty()) throw new CommandException("do what with an allow?"); subCmd = args.remove(0).toLowerCase(); LocalGateImpl gate; if ("item".startsWith(type)) { if ("list".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.allow.item.list." + gate.getFullName()); List<String> items = new ArrayList<String>(gate.getAllowedItems()); Collections.sort(items); ctx.send("%s items", items.size()); for (String item : items) ctx.send(" %s", item); return; } if (args.isEmpty()) throw new CommandException("item required"); String item = args.remove(0); gate = getGate(ctx, args); if ("add".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.allow.item.add." + gate.getFullName()); if (gate.addAllowedItem(item)) ctx.send("added allowed item to '%s'", gate.getName(ctx)); else throw new CommandException("item is already allowed"); return; } if ("remove".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.allow.item.remove." + gate.getFullName()); if (item.equals("*")) { gate.removeAllAllowedItems(); ctx.send("removed all allowed items from '%s'", gate.getName(ctx)); } else if (gate.removeAllowedItem(item)) ctx.send("removed allowed item from '%s'", gate.getName(ctx)); else throw new CommandException("allowed item not found"); return; } throw new CommandException("do what with an item allow?"); } if ("potion".startsWith(type)) { if ("list".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.allow.potion.list." + gate.getFullName()); List<String> potions = new ArrayList<String>(gate.getAllowedPotions()); Collections.sort(potions); ctx.send("%s potion effects", potions.size()); for (String potion : potions) ctx.send(" %s", potion); return; } if (args.isEmpty()) throw new CommandException("potion effect required"); String potion = args.remove(0); gate = getGate(ctx, args); if ("add".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.allow.potion.add." + gate.getFullName()); if (gate.addAllowedPotion(potion)) ctx.send("added allowed potion effect to '%s'", gate.getName(ctx)); else throw new CommandException("potion effect is already allowed"); return; } if ("remove".startsWith(subCmd)) { Permissions.require(ctx.getPlayer(), "trp.gate.allow.potion.remove." + gate.getFullName()); if (potion.equals("*")) { gate.removeAllAllowedPotions(); ctx.send("removed all allowed potions from '%s'", gate.getName(ctx)); } else if (gate.removeAllowedPotion(potion)) ctx.send("removed allowed potion effect from '%s'", gate.getName(ctx)); else throw new CommandException("allowed potion effect not found"); return; } throw new CommandException("do what with a potion effect allow?"); } throw new CommandException("do what with an allow?"); } if ("replace".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("what type of replace?"); String type = args.remove(0).toLowerCase(); if (args.isEmpty()) throw new CommandException("do what with a replace?"); subCmd = args.remove(0).toLowerCase(); LocalGateImpl gate; if ("item".startsWith(type)) { if ("list".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.replace.item.list." + gate.getFullName()); Map<String,String> items = new HashMap<String,String>(gate.getReplaceItems()); List<String> keys = new ArrayList<String>(items.keySet()); Collections.sort(keys); ctx.send("%s items", items.size()); for (String key : keys) ctx.send(" %s => %s", key, items.get(key)); return; } if (args.isEmpty()) throw new CommandException("item required"); String oldItem = args.remove(0); if ("add".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("new item required"); String newItem = args.remove(0); gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.replace.item.add." + gate.getFullName()); if (gate.addReplaceItem(oldItem, newItem)) ctx.send("added replace item to '%s'", gate.getName(ctx)); else throw new CommandException("item is already replaced"); return; } if ("remove".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.replace.item.remove." + gate.getFullName()); if (oldItem.equals("*")) { gate.removeAllReplaceItems(); ctx.send("removed all replace items from '%s'", gate.getName(ctx)); } else if ( gate.removeReplaceItem(oldItem)) ctx.send("removed replace item from '%s'", gate.getName(ctx)); else throw new CommandException("replace item not found"); return; } throw new CommandException("do what with an item replace?"); } if ("potion".startsWith(type)) { if ("list".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.replace.potion.list." + gate.getFullName()); Map<String,String> potions = new HashMap<String,String>(gate.getReplacePotions()); List<String> keys = new ArrayList<String>(potions.keySet()); Collections.sort(keys); ctx.send("%s potion effects", potions.size()); for (String key : keys) ctx.send(" %s => %s", key, potions.get(key)); return; } if (args.isEmpty()) throw new CommandException("potion effect required"); String oldPotion = args.remove(0); if ("add".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("new potion effect required"); String newPotion = args.remove(0); gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.replace.potion.add." + gate.getFullName()); if (gate.addReplacePotion(oldPotion, newPotion)) ctx.send("added replace potion effect to '%s'", gate.getName(ctx)); else throw new CommandException("potion effect is already replaced"); return; } if ("remove".startsWith(subCmd)) { gate = getGate(ctx, args); Permissions.require(ctx.getPlayer(), "trp.gate.replace.potion.remove." + gate.getFullName()); if (oldPotion.equals("*")) { gate.removeAllReplacePotions(); ctx.send("removed all replace potion effects from '%s'", gate.getName(ctx)); } else if ( gate.removeReplacePotion(oldPotion)) ctx.send("removed replace potion effect from '%s'", gate.getName(ctx)); else throw new CommandException("replace potion effect not found"); return; } throw new CommandException("do what with a potion replace?"); } throw new CommandException("do what with a replace?"); } if ("resize".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("number and direction required"); String numDir = args.remove(0); String[] numDirParts = numDir.split(","); int num; ExpandDirection dir = ExpandDirection.ALL; try { num = Integer.parseInt(numDirParts[0]); } catch (NumberFormatException nfe) { throw new CommandException("invalid number"); } if (numDirParts.length > 1) try { dir = Utils.valueOf(ExpandDirection.class, numDirParts[1]); } catch (IllegalArgumentException iae) { throw new CommandException(iae.getMessage() + " direction"); } LocalGateImpl gate = getGate(ctx, args); if (gate.getType() != GateType.AREA) throw new CommandException("this command is only valid for %s gates", GateType.AREA); Permissions.require(ctx.getPlayer(), "trp.gate.resize." + gate.getFullName()); ((LocalAreaGateImpl)gate).resize(num, dir); return; } if ("corner".startsWith(subCmd)) { if (! ctx.isPlayer()) throw new CommandException("must be a player to use this command"); if (args.isEmpty()) throw new CommandException("corner number required"); String numStr = args.remove(0); int num; boolean pick = false; if ((! args.isEmpty()) && ("pick".startsWith(args.get(0).toLowerCase()))) { pick = true; args.remove(0); } try { num = Integer.parseInt(numStr); } catch (NumberFormatException nfe) { throw new CommandException("invalid corner number"); } if ((num < 1) || (num > 2)) throw new CommandException("number must be 1 or 2"); Location loc; if (pick) { Block block = ctx.getPlayer().getTargetBlock(null, 1000); if ((block == null) || (block.getType() == Material.AIR)) throw new CommandException("no block found"); loc = block.getLocation(); } else loc = ctx.getPlayer().getLocation().getBlock().getLocation(); LocalGateImpl gate = getGate(ctx, args); if (gate.getType() != GateType.AREA) throw new CommandException("this command is only valid for %s gates", GateType.AREA); Permissions.require(ctx.getPlayer(), "trp.gate.corner." + gate.getFullName()); if (num == 1) ((LocalAreaGateImpl)gate).setP1Location(loc); else if (num == 2) ((LocalAreaGateImpl)gate).setP2Location(loc); return; } if ("create".startsWith(subCmd)) { if (! ctx.isPlayer()) throw new CommandException("must be a player to use this command"); ctx.getPlayer().performCommand("trp design create " + rebuildCommandArgs(args)); return; } if ("set".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("option name required"); String option = args.remove(0); if (args.isEmpty()) throw new CommandException("option value required"); String value = args.remove(0); LocalGateImpl gate = getGate(ctx, args); gate.setOption(ctx, option, value); return; } if ("get".startsWith(subCmd)) { if (args.isEmpty()) throw new CommandException("option name required"); String option = args.remove(0); LocalGateImpl gate = getGate(ctx, args); gate.getOptions(ctx, option); return; } throw new CommandException("do what with a gate?"); } private LocalGateImpl getGate(Context ctx, List<String> args) throws CommandException { GateImpl gate; if (! args.isEmpty()) { gate = Gates.find(ctx, args.get(0)); if ((gate == null) || (! (gate instanceof LocalGateImpl))) throw new CommandException("unknown gate '%s'", args.get(0)); args.remove(0); } else gate = Gates.getSelectedGate(ctx.getPlayer()); if (gate == null) throw new CommandException("gate name required"); if (! gate.isSameServer()) throw new CommandException("this command cannot be used on a remote endpoint"); return (LocalGateImpl)gate; } }
package au.rmit.bde; import java.io.IOException; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; //import org.apache.log4j.Logger; public class RatingCalculatorJobConf extends Configured implements Tool { //Map Class static public class RatingCalculatorMapper extends Mapper<LongWritable, Text, Text, FloatWritable> { // private Logger logger = Logger.getLogger(RatingCalculatorMapper.class); //Simple Mapper @Override protected void map(LongWritable offset, Text text, Context context) throws IOException, InterruptedException { if (offset.get() != 0) { String[] review = text.toString().split("\t"); String productId = "none"; int rating; productId = review[3]; rating = Integer.parseInt(review[7]); context.write(new Text(productId), new FloatWritable(rating)); } else return; } // private Map<String, Float> tokenMap; // // // @Override // protected void setup(Context context) throws IOException, InterruptedException { // tokenMap = new HashMap<String, Float>(); // } // // @Override // protected void map(LongWritable offset, Text text, Context context) throws IOException, InterruptedException { // if (offset.get() != 0) { // String[] review = text.toString().split("\t"); // // String productId = "none"; // float rating; // // productId = review[3]; // rating = Float.parseFloat(review[7]); // // context.write(new Text(productId), new FloatWritable(rating)); // } // else // return; // } // @Override // protected void cleanup(Context context) throws IOException, InterruptedException { // IntWritable writableCount = new IntWritable(); // Text text = new Text(); // Set<String> keys = tokenMap.keySet(); // for (String s : keys) { // text.set(s); // writableCount.set(tokenMap.get(s)); // context.write(text,writableCount); // } // } } static public class RatingCalculatorReducer extends Reducer<Text, FloatWritable, Text, FloatWritable> { private FloatWritable averageRating = new FloatWritable(); @Override protected void reduce(Text token, Iterable<FloatWritable> ratings, Context context) throws IOException, InterruptedException { long counter = 0; float totalRating = 0; //Calculate average of ratings for (FloatWritable rating : ratings) { counter++; totalRating += rating.get(); } DecimalFormat df = new DecimalFormat("#.##"); float average = Float.parseFloat(df.format((float)totalRating/counter)); averageRating.set(average); context.write(token, averageRating); } } // public static class RatingCalculatorPartioner extends Partitioner<Text, LongWritable>{ // public int getPartition(Text key, LongWritable value, int numReduceTasks){ // if(numReduceTasks==0) // return 0; // if(key.equals(new Text("Cricket")) && !value.equals(new Text("India"))) // return 0; // if(key.equals(new Text("Cricket")) && value.equals(new Text("India"))) // return 1; // else // return 2; // } // } public int run(String[] args) throws Exception { Configuration configuration = getConf(); // configuration.set("mapreduce.job.jar", "/home/hadoop/wordcount.jar"); configuration.set("mapreduce.job.jar", args[2]); //Initialising Map Reduce Job Job job = new Job(configuration, "Rating Average"); //Set Map Reduce main jobconf class job.setJarByClass(RatingCalculatorMapper.class); //Set Mapper class job.setMapperClass(RatingCalculatorMapper.class); //Set Combiner class job.setCombinerClass(RatingCalculatorReducer.class); //set Reducer class job.setReducerClass(RatingCalculatorReducer.class); //set Input Format job.setInputFormatClass(TextInputFormat.class); //set Output Format job.setOutputFormatClass(TextOutputFormat.class); //set Output key class job.setOutputKeyClass(Text.class); //set Output value class job.setOutputValueClass(FloatWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args [1])); return job.waitForCompletion(true) ? 0 : -1; } public static void main(String[] args) throws Exception { System.exit(ToolRunner.run(new RatingCalculatorJobConf(), args)); } }
package br.com.teste.agenda.service.command; import br.com.teste.agenda.dto.command.TelefoneCommandDto; public interface ITelefoneCommandService { TelefoneCommandDto salvar(TelefoneCommandDto telefoneDto); void remover(String id); }
package com.example.mvpclean.domain.filters; import com.example.mvpclean.datas.HomeCategory; import java.util.List; /** * HomeCategory 탭의 데이터 가공하는 인터페이스 */ public interface CategoryFilter { List<HomeCategory> filter(List<HomeCategory> tasks); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package openopoly.err; /** * * @author amferraz */ public class UnmortgageablePlaceException extends GameException{ /** * O construtor da classe configura uma mensagem especifica da exceção */ public UnmortgageablePlaceException() { super("This place can't be mortgaged"); } }
package ca.csf.dfc.poo.adaptateur.classes; public interface MediaPlayer { public void play(String audioType, String fileName); }
package com.rc.portal.webapp.action; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.rc.app.framework.webapp.action.BaseAction; import com.rc.app.framework.webapp.model.page.PageWraper; import com.rc.portal.service.OpenSqlManage; import com.rc.portal.service.TCouponCardManager; import com.rc.portal.service.TCouponManager; import com.rc.portal.vo.TCoupon; import com.rc.portal.vo.TCouponCard; import com.rc.portal.vo.TMember; import com.rc.portal.webapp.util.PageResult; /** * 会员优惠券 * @author 刘天灵 * */ public class MemberCouponAction extends BaseAction{ private static final long serialVersionUID = 678674541L; private static int PAGE_SIZE = 10; private TCoupon tcoupon; private TCouponCard tcouponcard; private TCouponManager tcouponmanager; private TCouponCardManager tcouponcardmanager; private OpenSqlManage opensqlmanage; private PageWraper pw = new PageWraper(); private PageWraper usedpw = new PageWraper(); private PageWraper timeoutpw = new PageWraper(); public PageWraper getPw() { return pw; } public void setPw(PageWraper pw) { this.pw = pw; } public PageWraper getUsedpw() { return usedpw; } public void setUsedpw(PageWraper usedpw) { this.usedpw = usedpw; } public PageWraper getTimeoutpw() { return timeoutpw; } public void setTimeoutpw(PageWraper timeoutpw) { this.timeoutpw = timeoutpw; } private PageResult rs = new PageResult(); public TCoupon getTcoupon() { return tcoupon; } public void setTcoupon(TCoupon tcoupon) { this.tcoupon = tcoupon; } public TCouponManager getTcouponmanager() { return tcouponmanager; } public void setTcouponmanager(TCouponManager tcouponmanager) { this.tcouponmanager = tcouponmanager; } public OpenSqlManage getOpensqlmanage() { return opensqlmanage; } public void setOpensqlmanage(OpenSqlManage opensqlmanage) { this.opensqlmanage = opensqlmanage; } public PageResult getRs() { return rs; } public TCouponCard getTcouponcard() { return tcouponcard; } public void setTcouponcard(TCouponCard tcouponcard) { this.tcouponcard = tcouponcard; } public TCouponCardManager getTcouponcardmanager() { return tcouponcardmanager; } public void setTcouponcardmanager(TCouponCardManager tcouponcardmanager) { this.tcouponcardmanager = tcouponcardmanager; } public void setRs(PageResult rs) { this.rs = rs; } public Object getModel() { return null; } public void setModel(Object o) {} /** * 我的优惠券 * @return */ public String index(){ String type = this.getRequest().getParameter("type"); if(StringUtils.isEmpty(type)){ type = "1"; } TMember member = (TMember)this.getSession().getAttribute("member"); Map<String,Object> param = new HashMap<String,Object>(); param.put("memberId", member.getId()); //未使用优惠券 this.getRequest().setAttribute("countUse", this.opensqlmanage.selectObjectByObject(param, "t_coupon_card.selectCountUse")); //已使用优惠券 this.getRequest().setAttribute("countUsed", this.opensqlmanage.selectObjectByObject(param, "t_coupon_card.selectCountUsed")); //已过期优惠券 this.getRequest().setAttribute("countTimeOUt", this.opensqlmanage.selectObjectByObject(param, "t_coupon_card.selectCountTimeout")); if(type.equals("2")){ //已使用 this.pw = this.opensqlmanage.selectForPageByMap(param, "t_coupon_card.selectCountUsed", "t_coupon_card.selectUsedList", rs.getP_curPage(), PAGE_SIZE); }else if(type.equals("3")){ //已过期 this.pw = this.opensqlmanage.selectForPageByMap(param, "t_coupon_card.selectCountTimeout", "t_coupon_card.selectTimeoutList", rs.getP_curPage(), PAGE_SIZE); }else{ //未使用 this.pw = this.opensqlmanage.selectForPageByMap(param, "t_coupon_card.selectCountUse", "t_coupon_card.selectUseList", rs.getP_curPage(), PAGE_SIZE); } List result = pw.getResult(); for(int i=0;i<result.size();i++){ Map object = (Map) result.get(i); Long cid = (Long) object.get("id"); Map<String,Object> cidMap = new HashMap<String,Object>(); cidMap.put("cid", cid); Integer scope = (Integer) object.get("scope"); String name=""; if(scope==0){ name="全场通用"; }else if(scope==1){ name="免运费"; }else if(scope==2){ name=(String) this.opensqlmanage.selectObjectByObject(cidMap, "t_coupon_card.selectCategoryName"); }else if(scope==3){ name=(String) this.opensqlmanage.selectObjectByObject(cidMap, "t_coupon_card.selectBrandName"); }else if(scope==4){ name=(String) this.opensqlmanage.selectObjectByObject(cidMap, "t_coupon_card.selectPshortName"); }else{ name=""; } object.put("useName", name); } pw.setResult(result); System.out.println("result---》"+result); this.getRequest().setAttribute("type", type); return "index"; } /** * 删除优惠券 * @return * @throws Exception * @throws NumberFormatException */ public void deleteCoupon() throws Exception{ String couponCardId = this.getRequest().getParameter("couponCardId");//优惠码ID String type = this.getRequest().getParameter("type"); int flag=0; if(null!=couponCardId || !"".equals(couponCardId)){ this.getRequest().setCharacterEncoding("utf-8"); this.getResponse().setContentType("text/plain;charset=utf-8"); PrintWriter out = getResponse().getWriter(); this.tcouponcardmanager.deleteByPrimaryKey(Long.valueOf(couponCardId)); if(type.equals("1")){ flag=1; }else{ flag=3; } out.print(flag); out.close(); } } /** * 优惠券规则 * @return */ public String rule(){ return "rule"; } }
package com.example.homestay_kha; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; public class Splash_Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { GoogleApiClient mGoogleApiClient; public static final int REQUEST_LOCATION_PERMISSION = 1; Location my_location; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_activity); setUpLocationClientIfNeeded(); requestLocationPermissions(); } @SuppressWarnings("Permission") private void requestLocationPermissions() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION); } else { mGoogleApiClient.connect(); } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION_PERMISSION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mGoogleApiClient.connect(); } else { requestLocationPermissions(); } break; } } private void setUpLocationClientIfNeeded() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onConnected(Bundle bundle) { my_location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (my_location != null) { new Handler().postDelayed( new Runnable() { @Override public void run() { startActivity(new Intent(Splash_Activity.this, MainActivity.class)); SharedPreferences sharedPreferences = getSharedPreferences("my_location", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("longitude", String.valueOf(my_location.getLongitude())); editor.putString("latitude", String.valueOf(my_location.getLatitude())); editor.commit(); finish(); } }, 1500); } else { Toast.makeText(this, "Vui lòng bật vị trí của thiết bị", Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onConnectionSuspended(int i) { mGoogleApiClient.connect(); } @Override protected void onDestroy() { super.onDestroy(); mGoogleApiClient.disconnect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Toast.makeText(this, "Lỗi kết nối: " + connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show(); } }
package com.samples.queue; public class PriorityQueueTest { }
package com.tencent.mm.plugin.wallet_core.id_verify; import android.app.Activity; import android.content.Intent; import com.tencent.mm.g.a.sz; import com.tencent.mm.g.a.tk; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class a$1 implements Runnable { final /* synthetic */ Intent dgK; final /* synthetic */ Activity ews; final /* synthetic */ sz pjW; final /* synthetic */ a pjX; a$1(a aVar, sz szVar, Intent intent, Activity activity) { this.pjX = aVar; this.pjW = szVar; this.dgK = intent; this.ews = activity; } public final void run() { this.pjW.bJX = null; a.a(this.pjX); tk tkVar; if (bi.oW(a.b(this.pjX)) || bi.oW(a.c(this.pjX))) { this.pjX.ag(this.ews); if (a.d(this.pjX) == -1) { tkVar = new tk(); tkVar.ceX.result = a.d(this.pjX); a.sFg.m(tkVar); return; } return; } x.i("MicroMsg.RealNameVerifyProcess", "real name verify process end,jump to " + a.b(this.pjX) + a.c(this.pjX)); boolean z = this.pjX.jfZ.getBoolean("process_finish_stay_orgpage", true); this.dgK.putExtra("key_process_is_end", true); this.dgK.putExtra("key_process_is_stay", z); a.a(this.pjX, this.ews, a.b(this.pjX), a.c(this.pjX), a.d(this.pjX), this.dgK, z); if (a.d(this.pjX) == -1) { tkVar = new tk(); tkVar.ceX.result = a.d(this.pjX); a.sFg.m(tkVar); } } }
/** * */ package com.goodhealth.design.demo.Singleton; /** * @author 24663 * @date 2018年10月19日 * @Description 线程安全的饿汉式单例 不是按需加载,直接初始化实例对象 */ public class SingletonB { //访问方式: SingletonB instance=SingletonB.getInstance(); private static SingletonB single=new SingletonB(); private SingletonB(){ } public static SingletonB getInstance(){ return single; } }
package components; public class Matrix { int size; private int[][] matrice; public Matrix(int size) { this.size = size; this.matrice = new int[size][size]; int x = 0; while (x < size) { int y = 0; while (y < size) { this.matrice[x][y] = -1; ++y; } ++x; } } public int getSize() { return this.size; } public int getVal(int x, int y) { if (x >= 0 && y >= 0 && x < this.size && y < this.size) { return this.matrice[x][y]; } return -1; } public void rotation(boolean sens) { int x; int temp; int y = 0; while (y < this.size / 2) { x = 0; while (x < this.size) { temp = this.matrice[x][y]; this.matrice[x][y] = this.matrice[x][this.size - 1 - y]; this.matrice[x][this.size - 1 - y] = temp; ++x; } ++y; } if (sens) { y = 0; while (y < this.size) { x = 0; while (x < this.size - y) { temp = this.matrice[x][y]; this.matrice[x][y] = this.matrice[this.size - 1 - y][this.size - 1 - x]; this.matrice[this.size - 1 - y][this.size - 1 - x] = temp; ++x; } ++y; } } else { this.transpose(); } } public void setVal(int x, int y, int val) { if (x >= 0 && y >= 0 && x < this.size && y < this.size) { this.matrice[x][y] = val; } } public void transpose() { int y = 0; while (y < this.size) { int x = 0; while (x < y) { int temp = this.matrice[x][y]; this.matrice[x][y] = this.matrice[y][x]; this.matrice[y][x] = temp; ++x; } ++y; } } }
package tr.edu.fsm.javaprogramingapp.konu; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import tr.edu.fsm.javaprogramingapp.R; /** * Created by dilara on 02/12/16. */ public class Aciklamalar extends Activity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aciklamalar_main); webView = (WebView) findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); Bundle bndl = getIntent().getExtras(); String strUrl = bndl.getString("url1"); webView.loadUrl(strUrl); } }
// Write a Java program that takes a number as input and prints its multiplication table upto 10. // Test Data: // Input a number: 8 // Expected Output : // 8 x 1 = 8 // 8 x 2 = 16 // 8 x 3 = 24 // ... // 8 x 10 = 80 class task7{ public static void main(String[] args) { Integer numeris; System.out.print("Ivesti skaiciu: "); numeris = Integer.valueOf(System.console().readLine()); for (int i=1; i<=10; i++){ System.out.println(numeris + " x " + i + " = " + (numeris * i)); } } }
package com.uii.academico.Adapter; import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.uii.academico.Model.ObrolanObject; import com.uii.academico.R; import com.uii.academico.Volley.MySingleton; import java.util.List; /** * Created by Fakhrus on 5/27/16. */ public class AdapterObrolan extends BaseAdapter { Context activity; List<ObrolanObject> itemObrolan; public AdapterObrolan(Context activity, List<ObrolanObject> itemObrolan) { this.activity = activity; this.itemObrolan = itemObrolan; } @Override public int getCount() { return itemObrolan.size(); } @Override public Object getItem(int position) { return itemObrolan.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = View.inflate(activity, R.layout.item_obrolan, null); ImageLoader imageLoader = MySingleton.getInstance(activity).getImageLoader(); //panggil ID TextView namaChatRoom = (TextView) v.findViewById(R.id.namaChatroom); TextView pesanTerakhir = (TextView) v.findViewById(R.id.pesanTerakhir); final NetworkImageView fotoObrolan = (NetworkImageView) v.findViewById(R.id.IV_fotoObrolan); final ProgressBar progressObrolan = (ProgressBar) v.findViewById(R.id.PB_progresObrolan); final RelativeLayout relativeLayout = (RelativeLayout) v.findViewById(R.id.RL_warnaObrolan); fotoObrolan.setVisibility(View.GONE); progressObrolan.setVisibility(View.VISIBLE); //ambil data tiap baris ObrolanObject dataObrolan = itemObrolan.get(position); // pasang teksnya namaChatRoom.setText(dataObrolan.getNamaObrolan()); pesanTerakhir.setText(dataObrolan.getPesanTerakhir()); // Cargo image loader (progress bar loading muncul ketika image blm terambil) String imageUrl = dataObrolan.getUrlFotoObrolan(); if(imageLoader !=null && imageUrl!=null) { imageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onErrorResponse(VolleyError error) { progressObrolan.setVisibility(View.GONE); } @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { if (response.getBitmap() != null) { fotoObrolan.setVisibility(View.VISIBLE); fotoObrolan.setImageBitmap(response.getBitmap()); progressObrolan.setVisibility(View.GONE); } } }); fotoObrolan.setImageUrl(imageUrl, imageLoader); } if (dataObrolan.getTipeObrolan().equals("chat_dpa") || dataObrolan.getTipeObrolan().equals("chat_kajur")){ relativeLayout.setBackgroundColor(Color.parseColor("#ffb007")); } else if (dataObrolan.getTipeObrolan().equals("chat_mhs")){ relativeLayout.setBackgroundColor(Color.parseColor("#64b5f6")); }else { // default warna biru tua } return v; } }
package enthu_leitner; public class e_982 { private static int loop = 15; static final int INTERVAL = 10; boolean flag; static { System.out.println("Static"); } static { loop = 1; } static { loop += INTERVAL; } { flag = true; loop = 0; } public static void main(String[] args) { } }
package com.yiki.blog.SecurityLearn; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service public class JWTservice { @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private UserMapper userMapper; public void test(User user) { String encodePsw = bCryptPasswordEncoder.encode(user.getPassword()); user.setPassWord(encodePsw); userMapper.InsertUser(user); } public User loginEcode(User user) { User admin = userMapper.getUserByUserName(user.getUsername()); if (admin != null && bCryptPasswordEncoder.matches(user.getPassword(), admin.getPassword())) { return admin; } return null; } }
package com.jlgproject.adapter.newDebt; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.jlgproject.R; import com.jlgproject.model.newDebt.Item; import java.util.List; /** * Created by yarolegovich on 07.03.2017. */ public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ViewHolder> { private List<com.jlgproject.model.newDebt.SonLevelListBean> data; private Context context; private OnClickImageViewListener onClickImageViewListener; public ShopAdapter(List<com.jlgproject.model.newDebt.SonLevelListBean> data, Context context) { this.data = data; this.context=context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View v = inflater.inflate(R.layout.item_shop_card, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { Glide.with(holder.itemView.getContext()) .load(data.get(position).getUrl()) .into(holder.image); holder.image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickImageViewListener.onClick(data.get(position).getPId(),data.get(position).getId(),data.get(position).getName()); } }); holder.textView.setText(data.get(position).getName()); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { private ImageView image; private TextView textView; public ViewHolder(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.image); textView= (TextView) itemView.findViewById(R.id.tv_title); } } public interface OnClickImageViewListener { void onClick(String erjiId, String sanjiId, String snajiStr); } public void setOnClickImageViewListener(OnClickImageViewListener onClickImageViewListener) { this.onClickImageViewListener = onClickImageViewListener; } }
package com.cmpickle.volumize.view; /** * @author Cameron Pickle * Copyright (C) Cameron Pickle (cmpickle) on 4/6/2017. */ public interface TopLevelRouter { void moveToVolumePage(); void moveToSchedulePage(); void moveToProfilePage(); void moveToSettingsPage(); void moveToAboutPage(); }
package com.example.faisal.explicit_intent; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class newActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_activity); Intent i = getIntent(); String name = i.getStringExtra("name"); String message = i.getStringExtra("message"); ((TextView) findViewById(R.id.textview1)).setText(name + message); Bundle bundle = i.getExtras(); String status1 = bundle.getString("status1"); String status2 = bundle.getString("status2"); String status3 = bundle.getString("status3"); String status4 = bundle.getString("status4"); Toast.makeText(this, status1 + status2 + status3 + status4, Toast.LENGTH_SHORT).show(); Button button=(Button)findViewById(R.id.Newb1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myintent =new Intent(newActivity.this,MainActivity.class); startActivity(myintent); } }); } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /* * 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 Naren Thanikesh */ public class vrequests extends javax.swing.JFrame { public static Connection con; public static PreparedStatement pstmt; public static Statement stmt; public static Statement stmt1; public static ResultSet rs; public static ResultSet rs1; String a; /** * Creates new form vrequests */ public vrequests() { try { // DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Class.forName("oracle.jdbc.driver.OracleDriver"); }catch (ClassNotFoundException e) { System.out.println("MySQL JDBC Driver missing!!!"); e.printStackTrace(); return; } try { con=DriverManager.getConnection("jdbc:oracle:thin:@//orca.csc.ncsu.edu:1521/orcl.csc.ncsu.edu","nthanik","200152371"); } catch(SQLException ex) { System.out.println("ASD"); JOptionPane.showMessageDialog(this,ex.getMessage()); } initComponents(); try{ DefaultTableModel tm=(DefaultTableModel)t1.getModel(); tm.setRowCount(0); stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY); rs=stmt.executeQuery ("select * from pending "); rs.first(); do { Object row[]={rs.getString(3),rs.getString(2),rs.getString(1),Integer.parseInt(rs.getString(4))}; tm.addRow(row); }while(rs.next()); } catch(SQLException ex){} } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); t1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); t1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "sid", "course ID", "class ID", "Credits" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); t1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { t1MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { t1MouseEntered(evt); } }); jScrollPane1.setViewportView(t1); jButton1.setText("Approve"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Reject"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel1.setText("Menu"); jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 25, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2))) .addGap(56, 56, 56)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(25, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addGap(38, 38, 38) .addComponent(jLabel1) .addGap(31, 31, 31)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void t1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_t1MouseClicked // TODO add your handling code here: }//GEN-LAST:event_t1MouseClicked private void t1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_t1MouseEntered // TODO add your handling code here: }//GEN-LAST:event_t1MouseEntered private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: try{ int row=t1.getSelectedRow(); String sid=(t1.getModel().getValueAt(row, 0).toString()); String course_id=(t1.getModel().getValueAt(row, 1).toString()); String class_id=(t1.getModel().getValueAt(row, 2).toString()); int c=Integer.parseInt(t1.getModel().getValueAt(row, 3).toString()); String query="delete from pending where class_id= ? and course_id= ? and sid = ?"; pstmt=con.prepareStatement(query); pstmt.setString(1,class_id); pstmt.setString(2,course_id); pstmt.setString(3,sid); pstmt.executeUpdate(); query="insert into enroll(course_id,class_id,sid,num_of_credits) values(?,?,?,?)"; pstmt=con.prepareStatement(query); pstmt.setString(1,course_id); pstmt.setString(2,class_id); pstmt.setString(3,sid); pstmt.setInt(4,c); pstmt.executeUpdate(); new admin_page().setVisible(true); this.setVisible(false); } catch(SQLException ex){JOptionPane.showMessageDialog(this,ex.getMessage()); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: try{ int row=t1.getSelectedRow(); String sid=(t1.getModel().getValueAt(row, 0).toString()); String course_id=(t1.getModel().getValueAt(row, 1).toString()); String class_id=(t1.getModel().getValueAt(row, 2).toString()); int c=Integer.parseInt(t1.getModel().getValueAt(row, 3).toString()); String query="insert into reject1(course_id,class_id,sid) values(?,?,?)"; pstmt=con.prepareStatement(query); pstmt.setString(1,course_id); pstmt.setString(2,class_id); pstmt.setString(3,sid); pstmt.executeUpdate(); query="delete from pending where class_id= ? and course_id= ? and sid = ?"; pstmt=con.prepareStatement(query); pstmt.setString(1,class_id); pstmt.setString(2,course_id); pstmt.setString(3,sid); pstmt.executeUpdate(); new admin_page().setVisible(true); this.setVisible(false); } catch(SQLException ex){JOptionPane.showMessageDialog(this,ex.getMessage()); } }//GEN-LAST:event_jButton2ActionPerformed private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked // TODO add your handling code here: new admin_page().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jLabel1MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(vrequests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(vrequests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(vrequests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(vrequests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vrequests().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable t1; // End of variables declaration//GEN-END:variables }
/* package com.demo.test.abstractfactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCPoolUtil { private static JDBCPool pool = JDBCPool.getJdbcPoolInstance(); public static void main(String[] args) throws SQLException { System.out.println("JDBCPoolUtil Testing Start ===============>"); getConnection(); System.out.println("JDBCPoolUtil Testing End ===============>"); } */ /** *  获取资源 *//* public static Connection getConnection() throws SQLException { return pool.getConnection(); } */ /** *  关闭资源 *  @param resultSet 查询返回的结果集,没有为空 *  @param statement    *  @param connection *//* public static void close(ResultSet resultSet, Statement statement, Connection connection) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { throw new RuntimeException(e); } resultSet = null; } if (statement != null) { try { statement.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } } */
package me.zeus.MoarSoundz; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class CommandHandling implements CommandExecutor { //======================================================================= private Main plugin; public CommandHandling(Main plugin){ this.plugin = plugin; } //======================================================================= @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { if (sender.hasPermission("MoarSoundz.Reload")) { plugin.reloadConfig(); sender.sendMessage(ChatColor.GREEN + " MoarSoundz config reloaded. "); } return false; } //======================================================================= }
package com.mastercom.ps.connector.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.invoke.MethodHandles; import java.util.Properties; import org.apache.log4j.Logger; import com.mastercard.api.core.ApiConfig; import com.mastercard.api.core.model.Environment; import com.mastercard.api.core.security.oauth.OAuthAuthentication; import com.peoplesoft.pt.integrationgateway.framework.ConnectorInfo; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CustomHttpClientBuilder; /** * Classe di configurazione properties e sicurezza. * * * @author SabatiniJa * */ public class ServiceConfiguration { private final Logger log = Logger.getLogger(MethodHandles.lookup().lookupClass()); private Properties properties; private String P12; private String consumerKey; private String keyAlias; private String keyPassword; private String setDebug; // da impostare per gli ambienti di sviluppo in 'local' o 'dev' mentre in // produzione: 'prod' private String env; private String host; private int port; private String username; private String password; private int socketTimeout; private int connectTimeout; private int connectionRequestTimeout; public ServiceConfiguration() { setLocalConfig(); } public ServiceConfiguration(ConnectorInfo connInfo) { setConfig(connInfo); } /** * @see <a href="https://developer.mastercard.com/page/java-sdk-guide#http-proxy">https://developer.mastercard.com/page/java-sdk-guide#http-proxy</a> * * @author SabatiniJa * */ public class HttpProxyConfiguration { private String host; private int port; private String username; private String password; public HttpProxyConfiguration(String host, int port, String username, String password) { super(); this.setHost(host); this.setPort(port); this.setUsername(username); this.setPassword(password); this.setProxy(this.getHost(), this.getPort(), this.getUsername(), this.getPassword()); } private void setProxy(String host, int port, String username, String password) { CustomHttpClientBuilder builder = ApiConfig.getHttpClientBuilder(); HttpHost proxy = new HttpHost(host, port); builder.setProxy(proxy); // For other authentication mechanisms look at Apache HttpClient documentation // https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/CredentialsProvider.html CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(username, password)); builder.setDefaultCredentialsProvider(credentialsProvider); } private String getHost() { return host; } private void setHost(String host) { this.host = host; } private int getPort() { return port; } private void setPort(int port) { this.port = port; } private String getUsername() { return username; } private void setUsername(String username) { this.username = username; } private String getPassword() { return password; } private void setPassword(String password) { this.password = password; } @Override public String toString() { return "HttpProxyConfiguration [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password + "]"; } } public class ConnectionTimeout { private int socketTimeout; private int connectTimeout; private int connectionRequestTimeout; public ConnectionTimeout(int socketTimeout, int conntectTimeout, int connectionRequestTimeout) { super(); this.setSocketTimeout(socketTimeout); this.setConnectTimeout(conntectTimeout); this.setConnectionRequestTimeout(connectionRequestTimeout); this.setConnectionTimeout(this.getSocketTimeout(), this.getConnectTimeout(), this.getConnectionRequestTimeout()); } private void setConnectionTimeout(int socketTimeout, int connectTimeout, int connectionRequestTimeout){ RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); // Limit the amount of time waiting for data requestConfigBuilder.setSocketTimeout(1000); // Limit the amount of time waiting for a connection to the server to be // established requestConfigBuilder.setConnectTimeout(1000); // Limit the amount of time waiting for a connection from the connection pool requestConfigBuilder.setConnectionRequestTimeout(1000); ApiConfig.getHttpClientBuilder().setDefaultRequestConfig(requestConfigBuilder.build()); } private int getSocketTimeout() { return socketTimeout; } private void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } private int getConnectTimeout() { return connectTimeout; } private void setConnectTimeout(int conntectTimeout) { this.connectTimeout = conntectTimeout; } private int getConnectionRequestTimeout() { return connectionRequestTimeout; } private void setConnectionRequestTimeout(int connectionRequestTimeout) { this.connectionRequestTimeout = connectionRequestTimeout; } @Override public String toString() { return "ConnectionTimeout [socketTimeout=" + socketTimeout + ", connectTimeout=" + connectTimeout + ", connectionRequestTimeout=" + connectionRequestTimeout + "]"; } } /** * */ private void setProperties() { InputStream is = null; try { File file = new File("local.properties"); is = new FileInputStream(file); properties = new Properties(); properties.load(is); } catch (IOException exc) { log.error("Properties exception: " + exc.getMessage()); } } private void setLocalConfig() { try { setProperties(); log.debug("--------------init Local Properties--------------"); this.env = properties.getProperty("env"); log.debug("env: " + env); this.P12 = properties.getProperty("P12"); log.debug("P12: " + P12); this.consumerKey = properties.getProperty("consumerKey"); log.debug("consumerKey: " + consumerKey); this.keyAlias = properties.getProperty("keyAlias"); log.debug("keyAlias: " + keyAlias); this.keyPassword = properties.getProperty("keyPassword"); log.debug("keyPassword: " + keyPassword); this.setDebug = properties.getProperty("setDebug"); log.debug("setDebug: " + setDebug); InputStream is = new FileInputStream(P12); ApiConfig.setAuthentication(new OAuthAuthentication(this.consumerKey, is, this.keyAlias, this.keyPassword)); log.debug("ApiConfig.setAuthentication done!"); // Enable http wire logging ApiConfig.setDebug(Boolean.parseBoolean(this.setDebug)); log.debug("ApiConfig.setDebug done!"); // This is needed to change the environment to run the sample code. For // production: use ApiConfig.setSandbox(false); if ("local".equalsIgnoreCase(this.env) || "dev".equalsIgnoreCase(this.env)) { ApiConfig.setEnvironment(Environment.parse("sandbox")); log.debug("Set Environment: sandbox"); } else if ("prod".equalsIgnoreCase(this.env)) { ApiConfig.setSandbox(false); log.debug("Set Environment: prod"); } this.host = properties.getProperty("host"); log.debug("host: " + host); this.port = Integer.valueOf(properties.getProperty("port")); log.debug("port: " + port); this.username = properties.getProperty("username"); log.debug("username: " + username); this.password = properties.getProperty("password"); log.debug("password: " + password); if (!"local".equalsIgnoreCase(this.env)) { @SuppressWarnings("unused") HttpProxyConfiguration proxyConfiguration = new HttpProxyConfiguration(this.host, this.port, this.username, this.password); log.debug("Set Proxy"); } } catch (FileNotFoundException e) { e.printStackTrace(); } log.info("--------------Local Properties impostato--------------"); } private void setConfig(ConnectorInfo connInfo) { log.debug("--------------init Properties--------------"); env = connInfo.getFieldValue("env"); log.debug("env: " + env); P12 = connInfo.getFieldValue("P12"); log.debug("P12: " + P12); consumerKey = connInfo.getFieldValue("consumerKey"); log.debug("consumerKey: " + consumerKey); keyAlias = connInfo.getFieldValue("keyAlias"); log.debug("keyAlias: " + keyAlias); keyPassword = connInfo.getFieldValue("keyPassword"); log.debug("keyPassword: " + keyPassword); setDebug = connInfo.getFieldValue("setDebug"); log.debug("setDebug: " + setDebug); InputStream is = null; try { is = new FileInputStream(P12); } catch (FileNotFoundException e) { e.printStackTrace(); } ApiConfig.setAuthentication(new OAuthAuthentication(consumerKey, is, keyAlias, keyPassword)); log.debug("Authenticazione impostato!"); // Enable http wire logging ApiConfig.setDebug(Boolean.parseBoolean(setDebug)); log.debug("Debug http wire impostato a " + setDebug); // This is needed to change the environment to run the sample code. For // production: use ApiConfig.setSandbox(false); if ("local".equalsIgnoreCase(env) || "dev".equalsIgnoreCase(env)) { ApiConfig.setEnvironment(Environment.parse("sandbox")); log.debug("Environment impostato a sandbox"); } else if ("prod".equalsIgnoreCase(env)) { ApiConfig.setSandbox(false); log.debug("Environment impostato a Produzione"); } this.host = connInfo.getFieldValue("host"); log.debug("host: " + host); this.port = Integer.valueOf(connInfo.getFieldValue("port")); log.debug("port: " + port); this.username = connInfo.getFieldValue("username"); log.debug("username: " + username); this.password = connInfo.getFieldValue("password"); log.debug("password: " + password); this.connectTimeout = Integer.valueOf(connInfo.getFieldValue("connectTimeout")); log.debug("password: " + password); @SuppressWarnings("unused") HttpProxyConfiguration proxyConfiguration = new HttpProxyConfiguration(this.host, this.port, this.username, this.password); log.debug("Proxy impostato"); this.connectTimeout = Integer.valueOf(connInfo.getFieldValue("connectTimeout")); log.debug("connectTimeout: " + connectTimeout); this.socketTimeout = Integer.valueOf(connInfo.getFieldValue("socketTimeout")); log.debug("socketTimeout: " + socketTimeout); this.connectionRequestTimeout = Integer.valueOf(connInfo.getFieldValue("connectionRequestTimeout")); log.debug("connectionRequestTimeout: " + connectionRequestTimeout); @SuppressWarnings("unused") ConnectionTimeout connectionTimeout = new ConnectionTimeout(this.socketTimeout, this.connectTimeout, this.connectionRequestTimeout); log.debug("Connection Timeout impostato"); log.info("--------------Properties impostate--------------"); } }
package com.ireslab.sendx.electra.electra; import java.util.UUID; import org.apache.commons.text.RandomStringGenerator; public class TestOperationsClass { public static void main(String[] args) { System.out.println(UUID.randomUUID().toString().replaceAll("-", "")); System.out.println(new RandomStringGenerator.Builder().withinRange('0', 'z').build().generate(10)); } }
import java.util.Random; public class EstadoTabuleiro { private int casas[][]; private int numRainhas; private int heuristica[][]; private int posRainhas[]; public EstadoTabuleiro(int dimensao) { this.numRainhas = dimensao; this.casas = new int[dimensao][dimensao]; this.heuristica = new int[dimensao][dimensao]; this.posRainhas = new int[dimensao]; } public void inicializarCasasComRainha() { Random r = new Random(); for(int i = 0; i < numRainhas; ++i) { int pos = r.nextInt(numRainhas-1); casas[i][pos] = 1; posRainhas[i] = pos; } } public void construirHeuristica() { int linha; int coluna; for(linha = 0; linha < numRainhas; ++linha) { int posI = posRainhas[linha]; casas[linha][posI] = 0; for(coluna = 0; coluna < numRainhas; ++coluna) { casas[linha][coluna] = 1; heuristica[linha][coluna] = contarConflitos()/2; casas[linha][coluna] = 0; } casas[linha][posI] = 1; heuristica[linha][posI] = Integer.MAX_VALUE; } } public EstadoTabuleiro clonar() { EstadoTabuleiro clone = new EstadoTabuleiro(numRainhas); for(int i = 0; i < casas.length; ++i) { for(int j = 0; j < casas.length; ++j) { clone.casas[i][j] = casas[i][j]; clone.heuristica[i][j] = heuristica[i][j]; } clone.posRainhas[i] = posRainhas[i]; } return clone; } public int[][] getHeuristica() { return this.heuristica; } public int contarConflitos() { int conflitos = 0; for(int i = 0; i < numRainhas; ++i) { for(int j = 0; j < numRainhas; ++j) { if(casas[i][j] == 1) { int cc = j; int ll = i+1; while(ll < numRainhas) { if(casas[ll][cc] == 1) { conflitos++; } ll++; } cc = j; ll = i-1; while(ll >= 0) { if(casas[ll][cc] == 1) { conflitos++; } ll--; } cc = j + 1; ll = i + 1; while(cc < numRainhas && ll < numRainhas) { if(casas[ll][cc] == 1) { conflitos++; } cc++; ll++; } cc = j - 1; ll = i - 1; while(cc >= 0&& ll >= 0) { if(casas[ll][cc] == 1) { conflitos++; } cc--; ll--; } cc = j + 1; ll = i - 1; while(cc < numRainhas && ll >= 0) { if(casas[ll][cc] == 1) { conflitos++; } cc++; ll--; } cc = j - 1; ll = i + 1; while(cc >= 0&& ll < numRainhas) { if(casas[ll][cc] == 1) { conflitos++; } cc--; ll++; } } } } return conflitos; } public int[][] getCasas() { return this.casas; } public int getDimensaoTabuleiro() { return casas.length; } public void mostrarEstado() { for(int i = 0; i < casas.length; ++i) { for(int j = 0; j < casas.length; ++j) { System.out.print(casas[i][j]+" "); } System.out.println(); } } public boolean compararCom(EstadoTabuleiro estado) { for(int i = 0; i < numRainhas; ++i) { for(int j = 0; j < numRainhas; ++j ) { if(casas[i][j] != estado.casas[i][j]) { return false; } } } return true; } public EstadoTabuleiro moverRainha(int idRainha, int pos) { EstadoTabuleiro novoEstado = clonar(); int aux = posRainhas[idRainha]; novoEstado.casas[idRainha][aux] = 0; novoEstado.casas[idRainha][pos] = 1; novoEstado.posRainhas[idRainha] = pos; return novoEstado; } public void mostrarEstadoHeuristica() { for(int i = 0; i < casas.length; ++i) { for(int j = 0; j < casas.length; ++j) { System.out.print(heuristica[i][j]+" "); } System.out.println(); } } }
package ProgramacionModular; import java.util.Scanner; public class FactorialRecursividad { static Scanner entrada = new Scanner(System.in); public static void main(String[] args) { int numero =pedirNumero(); int resultado=factorial(numero); verResultado(resultado); } /////////////////////////////////////////////////////////////////// private static int pedirNumero() { System.out.println("Introduce el numero a factorizar que sea mayor que 0"); int numi= entrada.nextInt(); if (numi <=0) { System.out.println("El numero introducido no es valido"); return pedirNumero(); } else return numi; } /////////////////////////////////////////////////////////////////// private static int factorial(int numero) { if (numero==0) //esto funciona porque genera una pila LIFO por lo que el ultimo return es el primero en ejecutarse asi que //luego se ejecutan secuencialmente todos los else y el ultimo return da el resultado de la multiplicacion de llamadas. La recursividad funciona //siempre con la regla LIFO. return 1; else return numero*(factorial(numero-1)); } /////////////////////////////////////////////////////////////////// private static void verResultado(int resultado) { System.out.println("El resultado es "+ resultado); } }
package com.crewmaker.controller; import com.crewmaker.dto.response.ApiResponse; import com.crewmaker.dto.response.ImageResponse; import com.crewmaker.service.ImageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.Optional; @Controller @CrossOrigin @RestController @RequestMapping("/api") public class ImageController { @Autowired ImageService imageService; @GetMapping("/event-place-image/{eventPlaceID}") public ResponseEntity<ImageResponse> getEventPlaceImage(@PathVariable(value = "eventPlaceID") Long eventPlaceID) { return Optional.ofNullable(imageService.getEventPlaceImage(eventPlaceID, 256, 256)).map(retrivedImage -> ResponseEntity .ok().body(new ImageResponse(retrivedImage, "eventPlace" + eventPlaceID))).orElseGet(() -> ResponseEntity.notFound().build()); } @Transactional @PostMapping("/event-place-image/{eventPlaceID}") public ResponseEntity<?> uploadEventPlaceImage(@RequestParam("file") MultipartFile file, @PathVariable(value = "eventPlaceID") Long eventPlaceID) throws IOException { boolean successfulUpload = imageService.uploadEventPlaceImage(file, eventPlaceID); return ResponseEntity.ok(new ApiResponse(successfulUpload, successfulUpload ? "Image uploaded successfully" : "Error, couldn't upload image")); } @GetMapping("/user-profile-image/{username}") public ResponseEntity<ImageResponse> getUserProfileImage(@PathVariable(value = "username") String username, @RequestParam(value = "isSmall", required = true) boolean isSmall) { return Optional.ofNullable(imageService.getUserProfileImage(username, isSmall)).map(retrivedImage -> ResponseEntity .ok().body(new ImageResponse(retrivedImage, "userProfileImage" + username))).orElseGet(() -> ResponseEntity.notFound().build()); } @Transactional @PostMapping("/user-profile-image") public ResponseEntity<?> uploadUserImage(@RequestParam("file") MultipartFile file) throws IOException { boolean successfulUpload = imageService.uploadUserImage(file); return ResponseEntity.ok(new ApiResponse(successfulUpload, successfulUpload ? "Image uploaded successfully" : "Error, couldn't upload image")); } }
package de.zarncke.lib.index.crit; import java.io.Serializable; import java.util.Collection; import java.util.LinkedHashSet; /** * Represents constraints on elements of a specific type by any of a number of keys. * * @author Gunnar Zarncke * @param <K> key type * @param <T> object type */ public abstract class CollectionCriteria<K, T> implements Criteria<K, T>, Serializable { private static final long serialVersionUID = 1L; private final Collection<K> keys; private final Class<K> type; protected CollectionCriteria(final Collection<K> keys, final Class<K> type) { this.keys = new LinkedHashSet<K>(keys); this.type = type; } @Override public Collection<K> getKeys() { return this.keys; } @Override public boolean matches(final T entry) { Collection<? extends K> values = getValues(entry); for (K value : values) { if (this.keys.contains(value)) { return true; } } return false; } protected abstract Collection<? extends K> getValues(T entry); @Override public Class<K> getType() { return this.type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.keys == null ? 0 : this.keys.hashCode()); result = prime * result + (this.type == null ? 0 : this.type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CollectionCriteria<?, ?> other = (CollectionCriteria<?, ?>) obj; if (this.keys == null) { if (other.keys != null) { return false; } } else if (!this.keys.equals(other.keys)) { return false; } if (this.type == null) { if (other.type != null) { return false; } } else if (!this.type.equals(other.type)) { return false; } return true; } @Override public String toString() { return "any of " + this.keys + "(" + this.type.getSimpleName() + ")"; } }
package architecture; import java.io.File; import java.util.Scanner; import rdbms.RDBMS; import tools.BasicFunctions; import dataStructure.ParseTreeNode; import dataStructure.Query; import edu.stanford.nlp.parser.lexparser.LexicalizedParser; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import components.*; public class CommandInterface { LexicalizedParser lexiParser; RDBMS db; Document tokens; Query query; public String feedback = ""; public static void main(String [] args) throws Exception { CommandInterface system = new CommandInterface(); System.out.println("NaLIR Loaded. Type 'exit' to quit."); // system.executeCommand("#useDB mas"); Scanner scan = new Scanner(System.in); while (true) { System.out.print("NaLIR> "); String command = scan.nextLine(); if (command.equals("exit")) { break; } system.executeCommand(command); } scan.close(); } public CommandInterface() throws Exception { lexiParser = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); tokens = builder.parse(new File("/Users/cjbaik/dev/NaLIR/src/zfiles/tokens.xml")); } public void executeCommand(String command) throws Exception { System.out.println("command: " + command); if(command.startsWith("#useDB") && command.length() > 7) { db = new RDBMS(command.substring(7)); feedback = FeedbackGenerator.feedbackGenerate(db.history, query); query = null; } else if(command.startsWith("#query") && command.length() > 7) { inputQuery(command.substring(7)); feedback = FeedbackGenerator.feedbackGenerate(db.history, query); } else if(command.startsWith("#mapSchema") && command.length() > 11) { mapChoice(command.substring(11)); feedback = FeedbackGenerator.feedbackGenerate(db.history, query); } else if(command.startsWith("#mapValue") && command.length() > 10) { mapValueChoice(command.substring(10)); feedback = FeedbackGenerator.feedbackGenerate(db.history, query); } else if(command.startsWith("#general") && command.length() > 9) { setGeneral(command.substring(9)); feedback = FeedbackGenerator.feedbackGenerate(db.history, query); } else if(command.startsWith("#specific") && command.length() > 10) { deleteSpecific(command.substring(10)); feedback = FeedbackGenerator.feedbackGenerate(db.history, query); } System.out.println(FeedbackGenerator.feedbackGenerate(db.history, query)); } public void inputQuery(String queryInput) throws Exception { query = new Query(queryInput, db.schemaGraph); components.StanfordNLParser.parse(query, lexiParser); components.NodeMapper.phraseProcess(query, db, tokens); components.EntityResolution.entityResolute(query); components.TreeStructureAdjustor.treeStructureAdjust(query, db); components.Explainer.explain(query); components.SQLTranslator.translate(query, db); } public void mapChoice(String choiceInput) throws Exception { String [] commands = choiceInput.split(" "); if(commands.length == 2) { int wordOrder = Integer.parseInt(commands[0]); int schemaChoice = Integer.parseInt(commands[1]); ParseTreeNode node = query.parseTree.searchNodeByOrder(wordOrder); node.choice = schemaChoice; } components.EntityResolution.entityResolute(query); components.TreeStructureAdjustor.treeStructureAdjust(query, db); components.Explainer.explain(query); components.SQLTranslator.translate(query, db); } public void mapValueChoice(String choiceInput) throws Exception { String [] commands = choiceInput.split(" "); if(commands.length >= 2) { int wordOrder = Integer.parseInt(commands[0]); int valueChoice = Integer.parseInt(commands[1]); ParseTreeNode node = query.parseTree.searchNodeByOrder(wordOrder); node.mappedElements.get(node.choice).choice = valueChoice; } components.EntityResolution.entityResolute(query); components.TreeStructureAdjustor.treeStructureAdjust(query, db); components.Explainer.explain(query); components.SQLTranslator.translate(query, db); } public void setGeneral(String choiceInput) { if(BasicFunctions.isNumeric(choiceInput)) { query.queryTreeID = Integer.parseInt(choiceInput); components.SQLTranslator.translate(query, db); } } private void deleteSpecific(String deleteID) { if(BasicFunctions.isNumeric(deleteID)) { components.NodeInserter.deleteNode(query.queryTree, query.NLSentences.get(query.queryTreeID), Integer.parseInt(deleteID)); components.SQLTranslator.translate(query, db); } } }
package com.lingnet.vocs.dao.impl.workorder; import java.util.List; import org.hibernate.SQLQuery; import org.springframework.stereotype.Repository; import com.lingnet.common.dao.impl.BaseDaoImplInit; import com.lingnet.util.Pager; import com.lingnet.vocs.dao.workorder.WorkOrderLogDao; import com.lingnet.vocs.entity.WorkOrder; import com.lingnet.vocs.entity.WorkOrderLog; /** * 工单 * @ClassName: WorkOrderDao * @Description: TODO * @author 薛硕 * @date 2017年6月28日 下午2:25:06 * */ @Repository("workOrderLogDao") public class WorkOrderLogDaoImpl extends BaseDaoImplInit<WorkOrderLog, String> implements WorkOrderLogDao { @SuppressWarnings("unchecked") @Override public List<Object[]> findFollowMap(String workOrderCode) { String sql = "select w.czdate, w.czdj, w.cztype, a.name, a.path from wo_log w join attachments a on w.id=a.entity_id where a.deleted=0 and w.czdj='"+workOrderCode+"' order by w.czdate"; SQLQuery query=this.getSession().createSQLQuery(sql); return query.list(); } @SuppressWarnings("unchecked") @Override public List<Object> findCzdjs(String sql) { SQLQuery query=this.getSession().createSQLQuery(sql); return query.list(); } @SuppressWarnings("unchecked") @Override public List<WorkOrder> findCz() { StringBuilder sqls= new StringBuilder(); String sql="SELECT w.id,w.work_order_title,w.work_order_code,w.work_order_type,w.fault_type,w.expect_date,w.work_order_level,w.equipment_code,w.resource,w.createperson, p.name as customer,w.customer_phone,w.customer_cell_phone,w.partner,w.partner_cell_phone,w.replay_phone,w.replay_cell_phone,w.sales,w.sales_phone,w.specific_req,w.fault_explain,w.upload_file,w.work_order_follow,w.createDate,w.modifyDate,w.state,w.customer_address,w.check_date,cause,w.rec_item_charges,w.rea_item_charges,w.rec_mainter_charges,w.rea_mainter_charges," + "w.receive,w.transfer_orders_id,w.actual_maintenanceDate,w.score,w.opinion,w.contacts,w.confirm,w.confirm_date,w.province,w.city,w.district,w.partner_phone,w.replay_person FROM WORKORDER w left join PARTNER p on w.customer=p.id where w.score>'3' order by w.modifyDate desc "; SQLQuery query=this.getSession().createSQLQuery(sql); query.addEntity(WorkOrder.class); List<WorkOrder> list = query.list(); return list; } @Override public List<WorkOrder> findNotp(Pager pager) { StringBuilder sqls= new StringBuilder(); String sql="SELECT w.id,w.work_order_title,w.work_order_code,w.work_order_type,w.fault_type,w.expect_date,w.work_order_level,w.equipment_code,w.resource,w.createperson, p.name as customer,w.customer_phone,w.customer_cell_phone,w.partner,w.partner_cell_phone,w.replay_phone,w.replay_cell_phone,w.sales,w.sales_phone,w.specific_req,w.fault_explain,w.upload_file,w.work_order_follow,w.createDate,w.modifyDate,w.state,w.customer_address,w.check_date,cause,w.rec_item_charges,w.rea_item_charges,w.rec_mainter_charges,w.rea_mainter_charges," + "w.receive,w.transfer_orders_id,w.actual_maintenanceDate,w.score,w.opinion,w.contacts,w.confirm,w.confirm_date,w.province,w.city,w.district,w.partner_phone,w.replay_person FROM WORKORDER w left join PARTNER p on w.customer=p.id where w.score<'4' order by w.modifyDate desc "; SQLQuery query=this.getSession().createSQLQuery(sql); query.addEntity(WorkOrder.class); List<WorkOrder> list = query.list(); return list; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.util; import java.io.IOException; import java.util.Objects; import org.apache.commons.io.output.ByteArrayOutputStream; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import com.fasterxml.jackson.databind.ObjectMapper; /** * Custom {@link BaseMatcher Matcher} to assert that the serialization of an object matches the one stored in file. * * @param <T> * the type parameter of the matcher */ public class JSONMatcher<T> extends BaseMatcher<T> { private final ObjectMapper mapper = new ObjectMapper(); private final String expectedSerialization; /** * Will return true if the JSON serialization of the actual is equal to the trimmed serialization of the JSON * contained in the provided path * * @param pathToExpected * path in the classpath to the file containing the expected JSON string, it can contain a beautified JSON * @throws IOException */ public JSONMatcher(final String pathToExpected) throws IOException { try (final ByteArrayOutputStream bout = new ByteArrayOutputStream()) { bout.write(getClass().getResourceAsStream(pathToExpected)); expectedSerialization = bout.toString().replaceAll("[\t\n\r\\s]+", ""); } } @Override public boolean matches(final Object actual) { try { final String actualSerialization = mapper.writeValueAsString(actual); return Objects.equals(actualSerialization, expectedSerialization); } catch (final IOException e) { return false; } } @Override public void describeTo(final Description description) { description.appendText("was expecting ").appendText(expectedSerialization); } }
package group.wnrcorp.com.navigationproject; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FirstFragment3 extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; TextView subtraction_result; InterfaceSolution interfaceSolution; int value; public FirstFragment3() { } public static FirstFragment3 newInstance(String param1, String param2) { FirstFragment3 fragment = new FirstFragment3(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View childview= inflater.inflate(R.layout.fragment_first_fragment3, container, false); subtraction_result=(TextView) childview.findViewById(R.id.subtraction); try { value = getArguments().getInt("sub"); subtraction_result.setText(""+value); } catch(Exception e) { System.out.println("exceptionCheck....."+e); } System.out.println("fragmentCheck2..."+value); return childview; } }
package fr.isima.cours.jee.server; import fr.isima.cours.jee.business.UserDisplay; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { static String DB_DRIVER = "org.h2.Driver"; static String DB_CONNECTION = "jdbc:h2:mem:test"; static String DB_USER = "sa"; static String DB_PASSWORD = ""; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/resources/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .successHandler((request, response, authentication) -> { request.getSession().setAttribute("username", authentication.getName()); response.sendRedirect("/home"); }).permitAll(); http.csrf().disable(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { try { Class.forName(DB_DRIVER); Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); String selectQuery = "SELECT id, username, password FROM users"; PreparedStatement preparedStatement = dbConnection.prepareStatement(selectQuery); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()) { auth.inMemoryAuthentication().withUser(User.withDefaultPasswordEncoder().username(rs.getNString("username")).password(rs.getNString("password")).roles("USER")); } dbConnection.close(); } catch (Exception e) { e.printStackTrace(); } } }
package com.worldchip.advertising.client.entity; public class System { private Date date; private Time time; private int Vol; private int Angle; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Time getTime() { return time; } public void setTime(Time time) { this.time = time; } public int getVol() { return Vol; } public void setVol(int vol) { Vol = vol; } public int getAngle() { return Angle; } public void setAngle(int angle) { Angle = angle; } }
package com.example.userportal.service.impl; import com.example.userportal.domain.Product; import com.example.userportal.domain.SpecificationPosition; import com.example.userportal.exception.ResourceNotFoundException; import com.example.userportal.repository.ProductRepository; import com.example.userportal.repository.SpecificationPositionRepository; import com.example.userportal.requestmodel.WarehouseStateUpdateRequest; import com.example.userportal.service.ProductService; import com.example.userportal.service.RecommendationService; import com.example.userportal.service.dto.ProductDTO; import com.example.userportal.service.mapper.ProductMapper; import com.google.common.collect.Lists; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @Service @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class ProductServiceImpl implements ProductService { private final ProductRepository repository; private final SpecificationPositionRepository specificationPositionRepository; private final RecommendationService recommendationService; private final ProductMapper mapper; @Override @Transactional public ProductDTO create(ProductDTO productDto) { Product product = mapper.toProduct(productDto); Collection<SpecificationPosition> specificationPositions = product.getSpecificationPositions(); product.setSpecificationPositions(null); repository.save(product); specificationPositions .forEach(position -> { position.setProduct(product); specificationPositionRepository.save(position); }); product.setSpecificationPositions(specificationPositions); return mapper.toProductDto(product); } @Override public ProductDTO delete(int id) { Optional<Product> product = repository.findById(id); product.ifPresent(repository::delete); return mapper.toProductDto(product .orElseThrow(() -> new ResourceNotFoundException("Order id=" + id + " could not be found"))); } @Override public List<ProductDTO> findAll() { Iterable<Product> products = repository.findAll(); return mapper.toProductDtos(Lists.newArrayList(products)); } @Override public Page<ProductDTO> findPaginated(Pageable pageRequest) { Page<Product> productPage = repository.findAll(pageRequest); return mapper.toPageOfProductDtos(productPage); } @Override public Page<ProductDTO> findCategoryPaginated(int categoryId, Pageable pageRequest) { Page<Product> productPage = repository.findProductsByProductCategoryId(categoryId, pageRequest); return mapper.toPageOfProductDtos(productPage); } @Override public Page<ProductDTO> findSubcategoryPaginated(int subcategoryId, Pageable pageRequest) { Page<Product> productPage = repository.findProductsByProductSubcategoryId(subcategoryId, pageRequest); return mapper.toPageOfProductDtos(productPage); } @Override public ProductDTO findById(int id) { Product product = repository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Product id=" + id + " could not be found")); return mapper.toProductDto(product); } @Override @Transactional public ProductDTO update(ProductDTO productDto) { Product product = mapper.toProduct(productDto); List<Integer> newSpecificationPositionIds = product.getSpecificationPositions() .stream() .map(SpecificationPosition::getId) .collect(Collectors.toList()); List<SpecificationPosition> oldSpecificationPositions = StreamSupport.stream(specificationPositionRepository.findAllByProductId(product.getId()).spliterator(), false) .collect(Collectors.toList()); oldSpecificationPositions .stream() .filter(oldPosition -> !newSpecificationPositionIds.contains(oldPosition.getId())) .forEach(specificationPositionRepository::delete); product.getSpecificationPositions() .forEach(position -> position.setProduct(product)); Product savedProduct = repository.save(product); return mapper.toProductDto(savedProduct); } @Override public ProductDTO takeProductFromWarehouse(WarehouseStateUpdateRequest request){ return updatePhysicalQuantity(request.getProductId(),request.getQuantity() * (-1)); } @Override public ProductDTO putProductIntoWarehouse(WarehouseStateUpdateRequest request){ return updatePhysicalQuantity(request.getProductId(),request.getQuantity() * (-1)); } private ProductDTO updatePhysicalQuantity(int productId, int quantity) { Optional<Product> product = repository.findById(productId); product.ifPresent(p -> { Integer currentPhysicalQuantity = p.getPhysicalQuantityInStock(); p.setPhysicalQuantityInStock(currentPhysicalQuantity + quantity); repository.save(p); }); return mapper.toProductDto(product.orElseThrow(() -> new ResourceNotFoundException("Product id=" + productId + " could not be found"))); } @Override public List<ProductDTO> getProductRecommendation(int productId) throws RedisConnectionFailureException { ProductDTO product = findById(productId); List<ProductDTO> productDTOList = new ArrayList<>(); productDTOList.add(product); Set<String> recommendations = this.recommendationService.getRecommendation(productDTOList, 8); return recommendations .stream() .mapToInt(Integer::parseInt) .mapToObj(this::findById) .collect(Collectors.toList()); } }
package org.bashemera.openfarm.service; import java.util.List; import org.bashemera.openfarm.model.Config; import org.bashemera.openfarm.repository.ConfigRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ConfigManager implements ConfigService { @Autowired ConfigRepository configRepository; @Override public Config getConfig() { List<Config> configs = configRepository.findAll(); if (configs.size() == 0) return null; else return configRepository.findAll().get(0); } @Override public Config save(Config config) { return configRepository.save(config); } }
package www.mapscloud.cn.listdemo.activity; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; import java.util.List; import www.mapscloud.cn.listdemo.R; import www.mapscloud.cn.listdemo.adapter.RecyclerViewVerticalAdapter; /** * Created by wangyongcan on 2018/7/3. */ public class RecyclerviewVerticalActivity extends Activity { private RecyclerView rv_recyclerviewvertical; // 数据源 private List<String> names = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recyclerviewvertical); initView(); addData(); setView(); } private void setView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); rv_recyclerviewvertical.setLayoutManager(linearLayoutManager); RecyclerViewVerticalAdapter recyclerViewVerticalAdapter = new RecyclerViewVerticalAdapter(this, names); // 显示层 rv_recyclerviewvertical.setAdapter(recyclerViewVerticalAdapter); } private void addData() { names.add("赵"); names.add("钱"); names.add("孙"); names.add("李"); names.add("周"); names.add("吴"); names.add("郑"); names.add("王"); } private void initView() { rv_recyclerviewvertical = (RecyclerView) findViewById(R.id.rv_recyclerviewvertical); } }
package plp.orientadaObjetos1.declaracao.variavel; import plp.expressions2.memory.VariavelJaDeclaradaException; import plp.expressions2.memory.VariavelNaoDeclaradaException; import plp.orientadaObjetos1.excecao.declaracao.ClasseJaDeclaradaException; import plp.orientadaObjetos1.excecao.declaracao.ClasseNaoDeclaradaException; import plp.orientadaObjetos1.excecao.declaracao.ObjetoJaDeclaradoException; import plp.orientadaObjetos1.excecao.declaracao.ObjetoNaoDeclaradoException; import plp.orientadaObjetos1.excecao.declaracao.ProcedimentoJaDeclaradoException; import plp.orientadaObjetos1.excecao.declaracao.ProcedimentoNaoDeclaradoException; import plp.orientadaObjetos1.expressao.leftExpression.Id; import plp.orientadaObjetos1.memoria.AmbienteCompilacaoOO1; import plp.orientadaObjetos1.memoria.AmbienteExecucaoOO1; import plp.orientadaObjetos1.util.Tipo; /** * Declaração de variável composta. */ public class CompostaDecVariavel implements DecVariavel { /** * Primeira declaração de variável. */ private DecVariavel declaracao1; /** * Restante da declaração de variáveis. */ private DecVariavel declaracao2; /** * Construtor. * * @param parametro1 * Primeira declaraçao de variável. * @param parametro2 * Restante da declaração de variáveis. */ public CompostaDecVariavel(DecVariavel declaracao1, DecVariavel declaracao2) { this.declaracao1 = declaracao1; this.declaracao2 = declaracao2; } /** * Obtém o tipo de uma variável nessa declaração. * * @param id * O identificador da variável. * @return o tipo deste identificador nessa declaraçao. * @throws VariavelNaoDeclaradaException * Quando nao há nenhuma variável declarada com esse id na * declaração. */ public Tipo getTipo(Id id) throws VariavelNaoDeclaradaException { Tipo tipo; try { tipo = declaracao1.getTipo(id); } catch (VariavelNaoDeclaradaException e) { tipo = declaracao2.getTipo(id); } return tipo; } /** * Cria um mapeamento dos identificadores para os valores das expressões * desta declaração composta no AmbienteExecucao * * @param ambiente * o ambiente que contem o mapeamento entre identificadores e * valores. * @return o ambiente modificado pelas inicializações das variáveis. * @throws ObjetoJaDeclaradoException * @throws ObjetoNaoDeclaradoException * @throws ClasseNaoDeclaradaException * @throws ClasseJaDeclaradaException * @throws VariavelNaoDeclaradaException * @throws VariavelJaDeclaradaException * @throws ProcedimentoNaoDeclaradoException * @throws ProcedimentoJaDeclaradoException */ public AmbienteExecucaoOO1 elabora(AmbienteExecucaoOO1 ambiente) throws VariavelJaDeclaradaException, VariavelNaoDeclaradaException, ClasseJaDeclaradaException, ClasseNaoDeclaradaException, ObjetoNaoDeclaradoException, ObjetoJaDeclaradoException { return declaracao2.elabora(declaracao1.elabora(ambiente)); } /** * Verifica se as declarações estão bem tipadas, ou seja, se as expressões * de inicialização estão bem tipadas. * * @param ambiente * o ambiente que contem o mapeamento entre identificadores e * seus tipos. * @return <code>true</code> se os tipos da declaração são válidos; * <code>false</code> caso contrario. */ public boolean checaTipo(AmbienteCompilacaoOO1 ambiente) throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException, ClasseNaoDeclaradaException, ClasseJaDeclaradaException { return declaracao1.checaTipo(ambiente) && declaracao2.checaTipo(ambiente); } }
package day20passbyvaluepassbyreferencedate; import java.util.ArrayList; import java.util.List; public class ForEachLoop01 { //Remove repeated elements from a list //Example: [a, b, c, b, a, a, d] ==> [a, b, c, d] public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("b"); list.add("a"); list.add("a"); list.add("d"); //1. Way List<String> distincList = new ArrayList<>(); for (String w: list) { if(distincList.contains(w)) { continue; } distincList.add(w); } System.out.println(distincList);//[a, b, c, d] //2.Way List<String> distincList1 = new ArrayList<>(); for (String w: list) { if(!distincList1.contains(w)) { distincList1.add(w); } } System.out.println(distincList1);//[a, b, c, d] } }
package li.cil.ceres.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to mark fields as serialized for generated serializers. * <p> * This annotation may also be used on classes, in which case all eligible fields in the class * are marked as serialized. Fields ignored by this are fields marked {@code transient} and * {@code final} fields holding immutable values. * <p> * This annotation is used when a serializer is requested via {@link li.cil.ceres.Ceres#getSerializer(Class)} * and no such serializer has been registered before. Ceres will attempt to generate a serializer * by scanning the specified type for serializable fields. * <p> * Adding this annotation to a {@code transient} field or a {@code final} field holding an immutable * value will lead to a {@link SerializationException} during serializer generation. */ @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Serialized { }
package com.base.ifocus.myapplication.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Response; import com.android.volley.VolleyError; import com.base.ifocus.myapplication.Adapter.EventListAdapter; import com.base.ifocus.myapplication.Network.Helper; import com.base.ifocus.myapplication.Network.HttpConn; import com.base.ifocus.myapplication.R; /** * Created by iFocus on 10-09-2015. */ public class EventFragment extends Fragment implements Response.Listener, Response.ErrorListener { private HttpConn menuConn; private Response.Listener responseString; private Response.ErrorListener errorListener; private ViewGroup view; private RecyclerView categoryList; private RecyclerView.Adapter mRecentAdapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); errorListener = this; responseString = this; menuConn = new HttpConn(Helper.getCompleteUrl(getString(R.string.allEvents), getActivity()), getActivity()); menuConn.getAsyncJsonArrayData(getString(R.string.allcat), responseString, errorListener); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = (ViewGroup) inflater.inflate(R.layout.event_frag, null); categoryList = (RecyclerView) view.findViewById(R.id.categoryList); return view; } @Override public void onErrorResponse(VolleyError error) { Log.e("Response Error", error.toString()); } @Override public void onResponse(Object response) { Log.e("Response ", response.toString()); createAdapter(response); } private void createAdapter(Object response) { try { categoryList.setLayoutManager(new LinearLayoutManager(getActivity())); mRecentAdapter = new EventListAdapter(Helper.parseEventsArray(response),getActivity()); categoryList.setAdapter(mRecentAdapter); } catch (Exception e) { e.printStackTrace(); } } }
package com.hawk.mgc.repository.springdatajpa; import java.sql.Timestamp; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import com.hawk.mgc.model.MgcPackage; import com.hawk.mgc.model.MgcPackageDetail; import com.hawk.mgc.model.SearchMgcPackageVo; public class PackageDetailRepositoryImpl implements PackageDetailRepositoryCustom { private static final Logger LOGGER = LoggerFactory .getLogger(PackageDetailRepositoryImpl.class); @PersistenceContext private EntityManager em; public void setEntityManager(EntityManager em) { this.em = em; } public List<MgcPackageDetail> searchPackageDetails( SearchMgcPackageVo searchMgcPackageVo) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MgcPackageDetail> criteriaQuery = cb .createQuery(MgcPackageDetail.class); Root<MgcPackageDetail> cRoot = criteriaQuery .from(MgcPackageDetail.class); criteriaQuery.select(cRoot); Predicate mainPredicate = null; mainPredicate = buildPackage(cb, mainPredicate, cRoot, searchMgcPackageVo.getMgcPackage()); mainPredicate = buildProduct(cb, mainPredicate, cRoot, searchMgcPackageVo.getMgcProduct()); // data from & data to mainPredicate = buildDateParemeters(cb, mainPredicate, cRoot, searchMgcPackageVo.getDateFrom(), searchMgcPackageVo.getDateTo()); if (mainPredicate != null) { LOGGER.info(":www:" + mainPredicate); criteriaQuery.where(mainPredicate); } Expression<Timestamp> createdDateColumn = cRoot .<Timestamp> get("detailDate"); criteriaQuery.orderBy(cb.desc(createdDateColumn)); TypedQuery<MgcPackageDetail> query = em.createQuery(criteriaQuery); List<MgcPackageDetail> results = query.getResultList(); return results; } private Predicate buildDateParemeters(CriteriaBuilder cb, Predicate mainPredicate, Root<MgcPackageDetail> cRoot, Date dateFrom, Date dateTo) { if (dateFrom != null && dateTo != null) { Predicate tempPredicate = cb.between( cRoot.<Timestamp> get("detailDate"), new Timestamp(dateFrom.getTime()), new Timestamp(dateTo.getTime())); mainPredicate = combinePredicate(cb, mainPredicate, tempPredicate); } return mainPredicate; } private Predicate buildPackage(CriteriaBuilder cb, Predicate mainPredicate, Root<MgcPackageDetail> cRoot, MgcPackage mgcPackage) { if (mgcPackage != null && mgcPackage.getId() != null) { Predicate tempPredicate = cb.equal(cRoot.get("mgcPackage") .get("id"), mgcPackage.getId()); mainPredicate = combinePredicate(cb, mainPredicate, tempPredicate); } return mainPredicate; } private Predicate buildProduct(CriteriaBuilder cb, Predicate mainPredicate, Root<MgcPackageDetail> cRoot, String product) { if (!StringUtils.isEmpty(product)) { Predicate tempPredicate = cb.equal( cRoot.get("mgcPackage").get("productionName"), product); mainPredicate = combinePredicate(cb, mainPredicate, tempPredicate); } return mainPredicate; } public Predicate combinePredicate(CriteriaBuilder cb, Predicate mainPredicate, Predicate tempPredicate) { if (mainPredicate == null) { mainPredicate = tempPredicate; } else { mainPredicate = cb.and(mainPredicate, tempPredicate); } return mainPredicate; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package graphics; import graphics.Sprite; import java.util.logging.Level; import java.util.logging.Logger; import org.lwjgl.util.vector.Vector2f; import org.newdawn.slick.Animation; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.SpriteSheet; /** * * @author Lars Aksel */ public class Car extends Sprite { private Vector2f moveDirection; private float initX; private float initY; private float speed; private boolean isExploded; private Animation animate; private SpriteSheet ss; private static final int duration = 25; public Car(Car c) { super(c.xPos, c.yPos, c.sizeX, c.sizeY, c.image); this.moveDirection = new Vector2f(c.moveDirection); this.initX = c.initX; this.initY = c.initY; this.speed = c.speed; this.isExploded = c.isExploded; this.ss = c.ss; this.animate = new Animation(c.ss, duration); this.animate.setAutoUpdate(false); this.animate.setLooping(false); } public Car(float xPos, float yPos, float sizeX, float sizeY, float speed, String filetype, String filepath, Vector2f v) { super(xPos, yPos, sizeX, sizeY, filetype, filepath); this.moveDirection = v; this.initX = xPos; this.initY = yPos; this.speed = speed; this.isExploded = false; try { this.ss = new SpriteSheet("res/images/explosion.png", 100, 100); } catch (SlickException e) { } this.animate = new Animation(this.ss, duration); this.animate.setAutoUpdate(false); this.animate.setLooping(false); } public boolean update(float delta) { if (!isExploded) { this.xPos += moveDirection.x * (speed * (float) delta); this.yPos += moveDirection.y * (speed * (float) delta); return true; } else if (isExploded && !animate.isStopped()) { animate.update((long) delta); return true; } return false; } public void refresh() { this.xPos = initX; this.yPos = initY; } public void explode() { if (!isExploded) { new Thread( new Runnable() { @Override public void run() { try { new Sound("res/sfx/explosion.ogg").play(1, 0.5f); } catch (SlickException ex) { //Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } this.isExploded = true; } @Override public void draw() { if (this.animate.getFrame() < this.animate.getFrameCount() / 20) super.draw(); if (animate.getFrameCount() > 0 && animate.getFrame() != 0) { animate.draw(xPos, yPos, sizeX, sizeX); } //if (animate.getFrameCount() - 1 == animate.getFrame()) animate.stop(); } }
package com.shsy.tubebaby.Converter; import android.accounts.NetworkErrorException; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import okhttp3.ResponseBody; import retrofit2.Converter; /** * Created by mashihao on 2017/11/14. */ public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> { private static String CHARSET = "UTF-8"; private final Gson gson; private final TypeAdapter<T> adapter; private final boolean isRemoveShell; GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter, boolean isRemoveShell) { this.gson = gson; this.adapter = adapter; this.isRemoveShell = isRemoveShell; } @Override public T convert(ResponseBody value) throws IOException { //如果不是 移除 外壳 if (!isRemoveShell) { JsonReader jsonReader = gson.newJsonReader(value.charStream()); try { return adapter.read(jsonReader); } finally { value.close(); } } JSONObject jb; try { String data = value.string(); jb = new JSONObject(data); } catch (JSONException e) { e.printStackTrace(); //抛出 数据异常 后面的 Rxjava 会捕获到异常 throw new IOException("the response data is error"); } //可能为 null String realData = null; try { boolean isSuccess = jb.optBoolean("isSuccess"); String message = jb.optString("message"); if (!isSuccess) { throw new NetworkErrorException(message == null || "".equals(message) ? "the request is fail" : message); } realData = jb.optString("result"); } catch (NetworkErrorException e) { throw new NetWorkErrorException(e); } if (realData == null) { realData = ""; } // Log.e("MSH", realData); InputStream inputStream = new ByteArrayInputStream(realData.getBytes(CHARSET)); Reader reader = new InputStreamReader(inputStream, CHARSET); JsonReader jsonReader = gson.newJsonReader(reader); try { return adapter.read(jsonReader); } finally { value.close(); } } }
package power; /** * Square is a class used to represent a box of the grid. */ public class Square { private int x; //column position private int y; //line position private CoinColor color; /** * Create a Square item with given coordinates. * * @param x the value of the column position * @param y the value of the line position */ public Square(int x, int y) { if (x > 0) { this.x = x; } if (y > 0) { this.y = y; } this.color = CoinColor.NONE; } /** * Get the state of the Square. * * @return the state of the free attribute */ public boolean isFree() { return color == CoinColor.NONE; } /** * Get the color of the Square. * * @return the color attribute */ public CoinColor getColor() { return this.color; } /** * Set the color of the Square. * * @param color the given color to set */ public void setColor(CoinColor color) { try { if (color != null) { this.color = color; } else { System.out.println("setColor: null parameter"); } } catch (IllegalArgumentException e) { System.out.println("setColor: incorrect color"); } } /** * Get the value of the x coordinate of the Square. * * @return the value of the x coordinate */ public int getX() { return this.x; } /** * Get the value of the y coordinate of the Square. * * @return the value of the y coordinate */ public int getY() { return this.y; } /** * Print the state of the Square. * * @return the symbol of the state */ public String toString() { String color = " "; if (this.color == CoinColor.YELLOW) { color = "X"; } else if (this.color == CoinColor.RED){ color = "O"; } return color; } }
package day38interview; public class PostAndPreIncrement { public static void main(String[] args) { // int a= 12; a= a++; System.out.println(a);//12 int b= 22; b++; System.out.println(b);//23 int c= 32; c= ++c; System.out.println(c);//33 } }
package com.sdk4.boot.util; import javax.servlet.http.HttpServletRequest; /** * @author sh */ public class DruidUtils { private DruidUtils() { throw new IllegalStateException("Utility class"); } public static void setLoginedName(HttpServletRequest request, String username) { if (username == null || username.trim().isEmpty()) { request.getSession().removeAttribute("druid-user"); } else { request.getSession().setAttribute("druid-user", username); } } }
package com.zhiyou100.controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.zhiyou100.service.exception.LoginException; import com.zhiyou100.service.exception.SeckillException; // @ControllerAdvice 设置当前类为异常处理类 // 可以在这个类中统一处理 controller 层产生的所有异常 // 1. 统一处理异常 // 2. 避免大量的 try-catch @ControllerAdvice public class ExceptionController { // @ExceptionHandler 绑定异常和处理方法 // @ExceptionHandler({class1, class2,...}) // 如果 () 不写内容,就是处理所有的异常 == ({Exception.class}) // @ExceptionHandler // public String exception(Exception e, Model model) { // // model.addAttribute("errorMessage", e.getMessage()); // // // 如果没有 forward 或者 redirect 关键字,那么会自动拼接前后缀 // return "error"; // } // 登录的异常需要在 login.jsp 展示,秒杀的异常需要在 error.jsp 展示 // 所以两种异常需要分开处理 @ExceptionHandler(SeckillException.class) public String seckillException(SeckillException e, Model model) { model.addAttribute("errorMessage", e.getMessage()); return "error"; } @ExceptionHandler(LoginException.class) public String loginException(LoginException e, Model model) { model.addAttribute("errorMessage", e.getMessage()); return "forward:/login.jsp"; } }
package com.smxknife.flink.useranalysis.hotitemsanalysis; import com.smxknife.flink.useranalysis.hotitemsanalysis.model.ItemViewCount; import org.apache.flink.api.common.state.ListState; import org.apache.flink.api.common.state.ListStateDescriptor; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.KeyedProcessFunction; import org.apache.flink.util.Collector; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author smxknife * 2020/8/22 */ public class TopNHotItems extends KeyedProcessFunction<Long, ItemViewCount, String> { private int count; private ListState<ItemViewCount> itemState; public TopNHotItems(int count) { this.count = count; } @Override public void processElement(ItemViewCount itemViewCount, Context context, Collector<String> collector) throws Exception { // 把每条数据存入状态列表 itemState.add(itemViewCount); context.timerService().registerEventTimeTimer(itemViewCount.getWindowEnd() + 1); } @Override public void open(Configuration parameters) throws Exception { itemState = getRuntimeContext().getListState(new ListStateDescriptor<ItemViewCount>("itemStat", ItemViewCount.class)); } // 定时器触发时,对所有数据排序并输出结果 @Override public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception { // 将所有state中数据取出 List<ItemViewCount> allItems = new ArrayList<>(); itemState.get().forEach(allItems::add); // 按照count大小排序,并获取前count个 List<ItemViewCount> topNItems = allItems.stream().sorted((o1, o2) -> { return o2.getCount().compareTo(o1.getCount()); // return o1.getCount() > o2.getCount() ? -1 : 1; // 这种写法是有错误的,如果遇到两者相等的情况下,会抛出Comparison method violates its general contract!,因为不满足自反性,所以必须要处理相等的情况。另外还要考虑null的情况,如果前者为null怎么处理,后者为null怎么处理,两者都为null怎么处理 }).limit(count).collect(Collectors.toList()); // 清空状态 itemState.clear(); // 将排名结果格式化输出 StringBuilder result = new StringBuilder(); result.append("时间:").append(new Timestamp(timestamp - 1)).append("\n"); Stream.iterate(0, idx -> idx + 1).limit(topNItems.size()).forEach(idx -> { ItemViewCount itemViewCount = topNItems.get(idx); result.append("No").append(idx + 1).append(" : ") .append(" 商品ID=").append(itemViewCount.getItemId()).append(" 浏览量=").append(itemViewCount.getCount()) .append("\n") .append("------------------------------------------\n"); }); // 控制输出频率 TimeUnit.SECONDS.sleep(1); out.collect(result.toString()); } }
package ngordnet; import java.util.HashMap; import java.util.Collection; import edu.princeton.cs.introcs.In; public class NGramMap { HashMap<Integer, YearlyRecord> words; TimeSeries<Long> counts; /** Constructs an NGramMap from WORDSFILENAME and COUNTSFILENAME. */ public NGramMap(String wordsFilename, String countsFilename) { words = new HashMap<Integer, YearlyRecord>(); counts = new TimeSeries<Long>(); In file = new In(wordsFilename); while(file.hasNextLine()) { String word = file.readString(); Integer i = file.readInt(); if(!words.containsKey(i)) words.put(i, new YearlyRecord()); words.get(i).put(word, file.readInt()); file.readInt(); } file = new In(countsFilename); while(file.hasNextLine()) { String line = file.readLine(); String[] parts = line.split(","); counts.put(Integer.parseInt(parts[0]), Long.parseLong(parts[1])); } } /** Returns the absolute count of WORD in the given YEAR. If the word * did not appear in the given year, return 0. */ public int countInYear(String word, int year) { if(words.containsKey(year)) return words.get(year).count(word); else return 0; } /** Returns a defensive copy of the YearlyRecord of YEAR. */ public YearlyRecord getRecord(int year) { if(words.containsKey(year)) return words.get(year); else return null; } /** Returns the total number of words recorded in all volumes. */ public TimeSeries<Long> totalCountHistory() { return counts; } /** Provides the history of WORD between STARTYEAR and ENDYEAR. */ public TimeSeries<Integer> countHistory(String word, int startYear, int endYear) { TimeSeries<Integer> res = new TimeSeries<Integer>(); for(int i = startYear; i < endYear; ++i) { if(words.containsKey(i)) { int tmp = words.get(i).count(word); res.put(i, tmp); } } return res; } /** Provides a defensive copy of the history of WORD. */ public TimeSeries<Integer> countHistory(String word) { TimeSeries<Integer> res = new TimeSeries<Integer>(); for(int i: words.keySet()) { if(words.containsKey(i)) { int tmp = words.get(i).count(word); res.put(i, tmp); } } return res; } /** Provides the relative frequency of WORD between STARTYEAR and ENDYEAR. */ public TimeSeries<Double> weightHistory(String word, int startYear, int endYear) { return countHistory(word, startYear, endYear).dividedBy(counts); } /** Provides the relative frequency of WORD. */ public TimeSeries<Double> weightHistory(String word) { return countHistory(word).dividedBy(counts); } /** Provides the summed relative frequency of all WORDS between * STARTYEAR and ENDYEAR. If a word does not exist, ignore it rather * than throwing an exception. */ public TimeSeries<Double> summedWeightHistory(Collection<String> words, int startYear, int endYear) { TimeSeries<Double> res = new TimeSeries<Double>(); for(String s: words) { res = res.plus(weightHistory(s, startYear, endYear)); } return res; } /** Returns the summed relative frequency of all WORDS. */ public TimeSeries<Double> summedWeightHistory(Collection<String> words) { TimeSeries<Double> res = new TimeSeries<Double>(); for(String s: words) { res = res.plus(weightHistory(s)); } return res; } /** Provides processed history of all words between STARTYEAR and ENDYEAR as processed * by YRP. */ public TimeSeries<Double> processedHistory(int startYear, int endYear, YearlyRecordProcessor yrp) { TimeSeries<Double> res = new TimeSeries<Double>(); for(int i = startYear; i <= endYear; ++i) { if(words.containsKey(i)) res.put(i, yrp.process(words.get(i))); else res.put(i, 0.0); } return res; } /** Provides processed history of all words ever as processed by YRP. */ public TimeSeries<Double> processedHistory(YearlyRecordProcessor yrp) { TimeSeries<Double> res = new TimeSeries<Double>(); for(Integer i: words.keySet()) { if(words.containsKey(i)) res.put(i, yrp.process(words.get(i))); else res.put(i, 0.0); } return res; } }
package principal.base.utils; public class Constantes { public static final String URL = "rapiservi-rapitaxi.rhcloud.com"; public static final String PUERTO = ""; public static final String SERVLET = "rapiServer"; public static final String SERVICIOS = "rest"; public static final String URL_COMPLETA = "http://" + URL + "" + PUERTO + "/" + SERVLET + "/" + SERVICIOS + "/"; public static final String CHOFERES = "chofer/"; public static final String PASAJEROS = "pasajero/"; public static final String USUARIOS = "usuario/"; public static final String VIAJES = "viaje/"; public static final String TURNOS = "turnos/"; public static final String ACEPTAR = "aceptar"; public static final String INICIAR_VIAJE = "iniciar"; public static final String FINALIZAR_VIAJE = "finalizar"; public static final String ACTUALIZAR_PUNTO = "actualizar_punto"; public static final String INICIAR_TURNO = "iniciarTurno"; public static final String CERRAR_TURNO = "cerrarTurno"; public static final String TURNO_CHOFER = "turnoChofer"; public static final String REGISTRAR = "registrar"; public static class Calificaciones { public static final int NEGATIVA = -1; public static final int NEUTRAL = 0; public static final int POSITIVA = 1; } public static class Choferes { public static final String SERVICIO = "chofer/"; public static final String INICIAR_SESION = "iniciarSesion"; public static final String CERRAR_SESION = "cerrarSesion"; public static final String CHECK_DATOS = "checkDatos"; public static final String REGISTRAR_FROM_PASAJERO = "registrarFromPasajero"; } public static class Pasajeros { public static final String SERVICIO = "pasajero/"; public static final String REGISTRO = "registrar"; public static final String INICIAR_SESION = "iniciarSesion"; public static final String CERRAR_SESION = "cerrarSesion"; public static final String FAVORITOS = "favoritos"; public static final String GUARDAR_FAVORITOS = "agregarFavorito"; public static final String CHECK_DATOS = "checkDatos"; public static final String REGISTRAR_FROM_CHOFER = "registrarFromChofer"; } public static class Moviles { public static final String SERVICIO = "movil/"; public static final String MOVILES_CHOFER = "movilesChofer"; public static final String REGISTRAR_MOVIL = "registrarMovil"; } public static class Caracteristicas { public static final String SERVICIO = "caracteristicas/"; public static final String TODAS = "todas"; public static final String NUEVA = "nueva"; } public static class Turnos { public static final String SERVICIO = "turnos/"; public static final String ASIGNAR_MOVIL = "asignarMovil"; } public static class Viajes { public static final String SERVICIO = "viaje/"; public static final String VIAJE_CHOFER = "viajeChofer"; public static final String VIAJE_PASAJERO = "viajePasajero"; public static final String SOLICITAR = "solicitar"; public static final String TIEMPO_ESTIMADO = "tiempoEstimado"; public static final String RECHAZAR = "rechazar"; } public static class TipoGCM { public static final String SOLICITUD_VIAJE = "solicitud viaje"; public static final String CHOFER_ASIGNADO = "chofer asignado"; public static final String VIAJE_INCIADO = "viaje iniciado"; public static final String VIAJE_FINALIZADO = "viaje finalizado"; public static final String VIAJE_CANCELADO = "viaje cancelado"; public static final String SIN_CHOFER = "no hay choferes"; } public static class FILTER_GCM { public static final String CHOFER = "gcm_chofer"; public static final String PASAJERO = "gcm_pasajero"; } public static class Registro { public static final int OK = 0; public static final int FALLO_PERSISTENCIA = 1; public static final int EMAIL_EXISTENTE = 2; public static final int FALTAN_DATOS = 3; public static final int NULL = 4; } public static class RegistroUsuario { public static final int REGISTRO_PASAJERO = 0; public static final int REGISTRO_CHOFER = 1; public static final String MOVIL = "MOVIL"; public static final String CHOFER = "CHOFER"; } public static class DataBundle { public static final String TURNO = "turno"; public static final String MOVIL = "movil"; public static final String CHOFER = "chofer"; public static final String PASAJERO = "pasajero"; } public static class Archivos { public static final String GCM = "gcm.txt"; public static final String id = "id.txt"; } }
package co.uniqueid.authentication.client; import com.google.gwt.json.client.JSONObject; public class UniqueIDGlobalVariables { public static JSONObject uniqueID = null; public static JSONObject companyUniqueID = null; }
package com.sinata.rwxchina.component_basic.basic.basiccomment; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.widget.ImageView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.lzy.ninegrid.ImageInfo; import com.lzy.ninegrid.NineGridView; import com.lzy.ninegrid.preview.NineGridViewClickAdapter; import com.sinata.rwxchina.basiclib.HttpPath; import com.sinata.rwxchina.basiclib.basic.basicComment.CommentEntity; import com.sinata.rwxchina.basiclib.utils.imageUtils.ImageUtils; import com.sinata.rwxchina.component_basic.R; import java.util.ArrayList; import java.util.List; /** * @author HRR * @datetime 2017/12/18 * @describe 评论列表适配器 * @modifyRecord */ public class CommentAdapter extends BaseQuickAdapter<CommentEntity,BaseViewHolder> { private Context mC; //默认显示图片张数:3张,如需显示其他张数,需调set方法 private int num=3; public void setNum(int num) { this.num = num; } public CommentAdapter(Context context, @LayoutRes int layoutResId, @Nullable List<CommentEntity> data) { super(layoutResId, data); this.mC=context; } @Override protected void convert(BaseViewHolder helper, CommentEntity item) { helper.setText(R.id.pingjia_name,item.getUser_name()) .setText(R.id.pingjia_time,item.getCreatedate()) .setText(R.id.pingjia_tv,item.getEvaluation_comment()); ImageUtils.showCircleImage(mC, HttpPath.IMAGEURL+item.getUser_head(), (ImageView) helper.getView(R.id.comment_item_name)); //传入到九宫格的集合 ArrayList<ImageInfo> imageInfo = new ArrayList<>(); List<String> imageDetails = item.getEvaluation_comment_pic(); if (imageDetails != null) { for (String imageDetail : imageDetails) { ImageInfo info = new ImageInfo(); info.setThumbnailUrl(HttpPath.IMAGEURL+imageDetail); info.setBigImageUrl(HttpPath.IMAGEURL+imageDetail); imageInfo.add(info); if (imageInfo.size()>=num){ break; } } } NineGridView nineGridView=helper.getView(R.id.nineGrid); nineGridView.setAdapter(new NineGridViewClickAdapter(mC,imageInfo)); } }
package com.mahirkole.walkure.aspect; import com.mahirkole.walkure.exception.CoreException; import com.mahirkole.walkure.util.CoreResponse; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; /* @Aspect @Order(2) @Component public class CoreExceptionAdvice extends CoreAspect { @Around("execution(* com.mahirkole.walkure.controller.*.*(..)) && !beanAnnotatedWithMapperAspect()") public ResponseEntity handleCoreException(ProceedingJoinPoint proceedingJoinPoint) { ResponseEntity responseEntity; try { responseEntity = (ResponseEntity) proceedingJoinPoint.proceed(); } catch (CoreException coreException) { return new ResponseEntity<>( new CoreResponse(false, coreException.getMessage()), HttpStatus.OK); } catch (Throwable throwable) { throwable.printStackTrace(); return new ResponseEntity<>( new CoreResponse(false, throwable.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return responseEntity; } } */
package com.example.structural.proxy; /** * Copyright (C), 2020 * FileName: Girl * * @author: xieyufeng * @date: 2020/10/27 10:58 * @description: */ public interface Girl { void eat(); void shopping(); }
package gcodeviewer.utils; public class Bounds { // these define a BoundingBox MutablePoint5d lower, upper; // this is a bounding sphere float radius; public Bounds() { lower = new MutablePoint5d(Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE); upper = new MutablePoint5d(Float.MIN_VALUE, Float.MIN_VALUE, Float.MIN_VALUE); radius = 1; } public void add(Point5d p5f) { if (p5f.x() > upper.x()) upper.setX(p5f.x()); if (p5f.y() > upper.y()) upper.setY(p5f.y()); if (p5f.z() > upper.z()) upper.setZ(p5f.z()); if (p5f.x() < lower.x()) lower.setX(p5f.x()); if (p5f.y() < lower.y()) lower.setY(p5f.y()); if (p5f.z() < lower.z()) lower.setZ(p5f.z()); double r = Math.pow(p5f.x(), 2) + (float) Math.pow(p5f.y(), 2) + (float) Math.pow(p5f.z(), 2); r = Math.sqrt(r); if (r > radius) { radius = (float) r; } } }
package test; import java.util.Comparator; import model.AccessPoint; import model.GridPoint; /** * Sort based on the distance between a given reference point * @author Quentin Braet * */ public class APDistanceComparator implements Comparator<AccessPoint> { private GridPoint reference; /** * Constructor for comparing with a reference AP * @param reference */ public APDistanceComparator(AccessPoint reference){ this.reference = reference.getCoordinates(); } /** * Constructor for comparing with another gridpoint * @param reference */ public APDistanceComparator(GridPoint reference) { this.reference = reference; } @Override public int compare(AccessPoint ap1, AccessPoint ap2) { Double d1 = new Double(ap1.getCoordinates().distance(reference)); Double d2 = new Double(ap2.getCoordinates().distance(reference)); return d1.compareTo(d2); } }
// salesperson class public class SalesPerson { private String name = null; private int numItem1sold = 0; private int numItem2sold = 0; private int numItem3sold = 0; private int numItem4sold = 0; private double totalSales = 0.0; private double weekWage = 0.0; private final double rate =0.09; private final double base = 200.0; private final double valItem1 = 239.99; private final double valItem2 = 129.55; private final double valItem3 = 99.95; private final double valItem4 = 350.89; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getTotalSales() { totalSales = numItem1sold*valItem1 + numItem2sold*valItem2 + numItem3sold*valItem3 + numItem4sold*valItem4; return totalSales; } public double getWeekWage() { weekWage = getTotalSales() * rate + base; return weekWage; } public void setNumItem1sold(int numItem1sold) { this.numItem1sold = numItem1sold; } public void setNumItem2sold(int numItem2sold) { this.numItem2sold = numItem2sold; } public void setNumItem3sold(int numItem3sold) { this.numItem3sold = numItem3sold; } public void setNumItem4sold(int numItem4sold) { this.numItem4sold = numItem4sold; } public int getNumItem1sold() { return numItem1sold; } public int getNumItem2sold() { return numItem2sold; } public int getNumItem3sold() { return numItem3sold; } public int getNumItem4sold() { return numItem4sold; } }
package com.bank.investments.request; import com.bank.investments.domain.Investment; import com.bank.investments.domain.InvestmentStatus; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; @Getter @Setter @AllArgsConstructor public class InvestmentRequest { private BigDecimal investmentAmmount; private String accountId; public Investment convert(InvestmentStatus status){ return new Investment(0, this.investmentAmmount, this.accountId, status); } }
package com.jt.order.service.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jt.order.mapper.OrderItemMapper; import com.jt.order.mapper.OrderMapper; import com.jt.order.mapper.OrderShippingMapper; import com.jt.order.pojo.Order; import com.jt.order.pojo.OrderItem; import com.jt.order.pojo.OrderShipping; import com.jt.order.service.OrderService; @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderMapper orderMapper; @Autowired private OrderItemMapper orderItemMapper; @Autowired private OrderShippingMapper orderShippingMapper; //登录用户id+当前时间戳 @Override public String saveOrder(Order order) { String orderId = ""+order.getUserId()+System.currentTimeMillis(); System.out.println(order); Date date = new Date(); //实现订单入库 order.setOrderId(orderId); order.setStatus(1); //表示未付款 order.setCreated(date); order.setUpdated(date); orderMapper.insert(order); System.out.println("订单入库成功"); //实现订单物流入库 OrderShipping orderShipping = order.getOrderShipping(); orderShipping.setOrderId(orderId); orderShipping.setCreated(date); orderShipping.setUpdated(date); orderShippingMapper.insert(orderShipping); System.out.println("订单物流入库成功"); //实现订单商品入库 List<OrderItem> orderItemList = order.getOrderItems(); for (OrderItem orderItem : orderItemList) { orderItem.setOrderId(orderId); orderItem.setCreated(date); orderItem.setUpdated(date); orderItemMapper.insert(orderItem); } System.out.println("订单商品入库成功!"); return orderId; } @Override public Order findOrderById(String orderId) { Order order = orderMapper.selectByPrimaryKey(orderId); OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId); OrderItem orderItem = new OrderItem(); orderItem.setOrderId(orderId); List<OrderItem> orderItemList = orderItemMapper.select(orderItem); //数据封装 order.setOrderShipping(orderShipping); order.setOrderItems(orderItemList); return order; } }
package com.tencent.mm.ui; public class ae$b { int egS; int id; int order; int tpN; public ae$b(int i, int i2, int i3) { this(i, i2, i3, 0); } public ae$b(int i, int i2, int i3, int i4) { this.id = i; this.tpN = i2; this.egS = i3; this.order = i4; } }
public class Main { // public static void main(String[] args) throws InterruptedException { // Thread thread = Thread.currentThread(); // System.out.println("Current thread: " + thread.getName()); // // Thread.sleep(3000); // // System.out.println("Current thread: " + thread.getName()); // } // public static void main(String[] args) { // // 1. Extend the Thread class // // 2. Use Runnable interface // // MyThread myThread = new MyThread(); // myThread.run(); // } // // static class MyThread extends Thread { // public void run() { // setName("MyThread"); // System.out.println("Current thread: " + Thread.currentThread().getName()); // } // } public static void main(String[] args) throws InterruptedException { System.out.println("[1] Current thread: " + Thread.currentThread().getName()); Thread thread = new Thread( () -> { System.out.println("[2] Current thread: " + Thread.currentThread().getName()); } ); thread.setName("MyThread"); thread.start(); thread.join(); System.out.println("[3] Current thread: " + Thread.currentThread().getName()); } }
package spring.setup.service.impl; import java.util.List; import org.springframework.stereotype.Service; import spring.setup.dao.UserDao; import spring.setup.model.User; import spring.setup.service.UserService; @Service public class UserServiceImpl implements UserService { private final UserDao userDao; public UserServiceImpl(UserDao userDao) { this.userDao = userDao; } public void add(User user) { userDao.add(user); } public List<User> listUsers() { return userDao.findAllUsers(); } }
package com.nurhossen.bdjosbnurassignment.service.network; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static com.nurhossen.bdjosbnurassignment.utils.ApiConstant.BASE_URL; public class RetrofitClient { private static volatile Retrofit retrofitinstance =null; private RetrofitClient(){} public static Retrofit getInstance(){ if(retrofitinstance==null){ synchronized(RetrofitClient.class){ if(retrofitinstance==null){ retrofitinstance = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } } } return retrofitinstance; } }
package edu.wayne.cs.severe.redress2.parser; import edu.wayne.cs.severe.redress2.entity.CompilationUnit; import edu.wayne.cs.severe.redress2.entity.TypeDeclaration; import edu.wayne.cs.severe.redress2.exception.CompilUnitException; import java.util.ArrayList; import java.util.List; /** * This is a compilation unit parser. It parses the srcML files to get the * information on those. * * @author ojcchar */ public abstract class CompilUnitParser { List<TypeDeclaration> getAllTypes(List<TypeDeclaration> sysTypeDcls) { List<TypeDeclaration> allTypes = new ArrayList<TypeDeclaration>(); if (sysTypeDcls == null) { return allTypes; } for (TypeDeclaration typeDcl : sysTypeDcls) { allTypes.add(typeDcl); List<TypeDeclaration> allTypes2 = getAllTypes(typeDcl.getSubTypes()); allTypes.addAll(allTypes2); } return allTypes; } /** * Parses the compilation units and return the list of type declarations * implemented in the units * * @param compUnits the compilation units * @return the list of type declarations * @throws CompilUnitException if something goes wrong */ public abstract List<TypeDeclaration> getClasses( List<CompilationUnit> compUnits) throws CompilUnitException; }
/* * 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 com.mcc.poliklinik.controller; import com.mcc.poliklinik.entities.Jadwal; import com.mcc.poliklinik.services.JadwalService; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; /** * * @author ASUS */ @Controller public class JadwalController { @Autowired JadwalService jadwalService; @GetMapping("/jadwal") public String index(Model model) { model.addAttribute("jadwal", new Jadwal()); model.addAttribute("jadwals", jadwalService.getAll()); return "jadwal"; } @PostMapping("/jadwal/save") public String save(@Valid Jadwal jadwal) { jadwalService.save(jadwal); return "redirect:/jadwal"; } @GetMapping("/jadwal/{id}") public String getById(Model model, @PathVariable("id") String id) { model.addAttribute("jadwal", jadwalService.findById(Integer.parseInt(id))); model.addAttribute("jadwals", jadwalService.getAll()); return "redirect:/jadwal"; } @GetMapping("/jadwal/delete/{id}") public String delete(Model model, @PathVariable("id") String id) { jadwalService.delete(Integer.parseInt(id)); return "redirect:/jadwal"; } }
package com.xiruan.demand.demand.job; import com.xiruan.demand.entity.automation.JobTemplate; import com.xiruan.demand.repository.JobTemplateDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; import org.springside.modules.persistence.DynamicSpecifications; import org.springside.modules.persistence.SearchFilter; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import java.util.List; import java.util.Map; /** * Created by Chen.Ju on 2015/7/11. */ @Component @Transactional public class JobTemplateService { @Autowired private JobTemplateDao jobTemplateDao; public JobTemplate saveJobTemplate(JobTemplate jobTemplate){ return jobTemplateDao.save(jobTemplate); } public Page<JobTemplate> getJobTemplate(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType) { PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); // Specification<JobTemplate> spec = buildSpecification(searchParams); return jobTemplateDao.findAll(new Specification<JobTemplate>() { @Override public Predicate toPredicate(Root<JobTemplate> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { return null; } }, pageRequest); } public Page<JobTemplate> getJobTemplate(int pageNumber, int pageSize, String sortType) { PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); // Specification<JobTemplate> spec = buildSpecification(searchParams); return jobTemplateDao.findAll(new Specification<JobTemplate>() { @Override public Predicate toPredicate(Root<JobTemplate> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { return null; } }, pageRequest); } /** * 创建分页请求. */ private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) { Sort sort = null; if ("auto".equals(sortType)) { sort = new Sort(Sort.Direction.DESC, "id"); } else if ("title".equals(sortType)) { sort = new Sort(Sort.Direction.ASC, "title"); } return new PageRequest(pageNumber - 1, pagzSize, sort); } /** * 创建动态查询条件组合. */ private Specification<JobTemplate> buildSpecification(Map<String, Object> searchParams) { Map<String, SearchFilter> filters = SearchFilter.parse(searchParams); // filters.put("user.id", new SearchFilter("user.id", SearchFilter.Operator.EQ, userId)); Specification<JobTemplate> spec = DynamicSpecifications.bySearchFilter(filters.values(), JobTemplate.class); return spec; } public List<JobTemplate> findAllTemplate(){ return (List<JobTemplate>)jobTemplateDao.findAll(); } public JobTemplate findOne(Long id){ return jobTemplateDao.findOne(id); } public void deleteTemplate(Long id){ jobTemplateDao.delete(id); } }
/* * 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 sprint4.project; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JOptionPane; /** * * @author mati */ public class Sprint4Project { /** * @param args the command line arguments */ public static void main(String[] args) { File fichero = new File("Registros/classroom.txt"); //File fichero = crearFichero(); boolean encontrarFichero = fichero.exists(); if (encontrarFichero == false) { fichero = crearFichero(); } boolean fin = false; Usuario[] usuario = null; boolean comprobar = false; File ficheroUsuario = new File("usuarios.dat"); boolean comprobarUsuario = ficheroUsuario.exists(); if (comprobarUsuario == false) { usuarios(); } int posicion = menuInicio(fichero); } //--------------------------------------SPRINT 1--------------------------------------------------- /** * Funcion que permite leer el fichero * * @param fichero archivo classroom.txt donde se alnacenan los datos de las * aulas */ private static void leerClassroom(File fichero) { //numLineas sera necesario para contar los registros int numLineas = 0; // Se intentara leer el archivo classroom.txt try { // Codificación ISO-8859-1 (ANSI) o UTF-8 dependiendo de cómo esté creado el fichero de texto Scanner lectorFichero = new Scanner(fichero, "UTF-8"); //hasNext dentro del bucle permitira leer todas las filas de classroom //Se imprimira todo el contenido de classroom ordenado por tipo de dato while (lectorFichero.hasNext()) { numLineas++; String[] linea = lectorFichero.nextLine().split(","); System.out.println("Id: " + linea[0]); System.out.println("Nombre de aula: " + linea[1]); System.out.println("Cantidad de alumnos: " + linea[2]); System.out.println("Hay pc's: " + linea[3]); System.out.println("Cantidad de pc's disponibles: " + linea[4]); System.out.println("Hay proyector: " + linea[5]); System.out.println("Insonorizada: " + linea[6]); System.out.println(""); } lectorFichero.close(); //Se mostrara a partir del contador numLineas el numero de registros en classroom System.out.println("Hay " + numLineas + " registros de aulas"); //En caso de error se imprimira el siguiente mensaje } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } } //--------------------------------------SPRINT 2--------------------------------------------------- /** * Esta funcion muestra al usuario el menu para profesores * * @param fichero documento classroom.txt * @param pos posicion del usuario en el array */ private static void menuProfesor(File fichero, int pos) { Scanner lector = new Scanner(System.in); boolean salir = false; Usuario[] usuario = null; try { ObjectInputStream archivo = new ObjectInputStream(new FileInputStream("usuarios.dat")); usuario = (Usuario[]) archivo.readObject(); archivo.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } do { String menu[] = {"Ver los registros","Crear un registro","Editar registro", "Eliminar registro","Cerrar sesión","Apagar"}; int opciones = JOptionPane.showOptionDialog(null ,"Seleccione una opcion: " ,"Gestion de aulas" ,JOptionPane.NO_OPTION ,JOptionPane.PLAIN_MESSAGE ,null ,menu ,"default"); switch (opciones) { case 0: leerClassroom(fichero); break; case 1: crearRegistro(fichero); break; case 2: editarClassroom(fichero); break; case 3: eliminarRegistro(fichero); break; case 4: menuInicio(fichero); System.out.println(""); salir = true; break; case 5: salir = true; break; } } while (salir != true); } private static File crearFichero() { File fichero = new File("Registros/classroom.txt"); try { FileWriter writer = new FileWriter(fichero); writer.write("M08,Aula11,25,Si,25,Si,No\n"); writer.write("M09,Aula10,30,Si,32,Si,Si\n"); writer.write("M12,Aula26,25,Si,28,Si,No\n"); writer.write("M04,Aula30,25,Si,27,Si,No\n"); writer.write("FOL,Aula25,25,No,Null,Si,Si\n"); writer.write("EIE,Aula25,25,No,Null,Si,No\n"); writer.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al crear/escribir en el fichero", "Error de escritura", JOptionPane.WARNING_MESSAGE); } return fichero; } /** * Esta funcion se encarga de crear un nuevo registro de un aula * * @param fichero archivo classroom.txt donde se almacenan los datos de las * aulas */ private static void crearRegistro(File fichero) { //registro guardara los nuevos registros creados dentro de la funcion crearNuevaLinea String registroNuevo = crearNuevalinea() + "\n"; try { //agregar una nueva linea al fichero(true para agregar una linea y no sobreescribirla) //Se escribira en el fichero el registro nuevo FileWriter writer = new FileWriter(fichero, true); writer.write(registroNuevo); writer.close(); JOptionPane.showMessageDialog(null, "El registro ha sido creado con exito"); //En caso de error se imprimira el siguiente mensaje } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al crear/escribir en el fichero", "Error de escritura", JOptionPane.WARNING_MESSAGE); } } /** * Esta funcion se encarga de editar un registro * * @param fichero archivo classroom.txt donde se almacenan los datos de las * aulas */ private static void editarClassroom(File fichero) { Scanner lector = new Scanner(System.in); String lineadeseada, lineanueva; // Se busca a partir del ID poder editar la fila donde este se encuentra // y que cualquier ID que escribas se convierta en mayusculas. lineadeseada = JOptionPane.showInputDialog("Introduce el ID del aula que quieres modificar:").trim().toUpperCase(); // Array para guardar todas las líneas leídas del fichero ArrayList<String> lineas = new ArrayList<>(); // Abrimos el fichero de texto para leerlo en memoria try { //Se verificara la existencia del fichero classroom Scanner lectorFichero = new Scanner(fichero); while (lectorFichero.hasNext()) { lineas.add(lectorFichero.nextLine()); } lectorFichero.close(); //En caso de error se imprimira el siguiente mensaje } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } // Abrimos el fichero de texto para sobreescribirlo try { //Se comprovara que el ID coincida con el ID dentro del fichero FileWriter writer = new FileWriter(fichero); boolean prueba = false; for (String linea : lineas) { //En caso de que se encuentre el ID escrito //Se ejecutara la funcion nuevaLinearegistro() con tal de //reemplazar los registros de la fila donde se encuentra el ID if (lineadeseada.equals(linea.substring(0, 3))) { String registroNuevo = crearNuevalinea(); writer.write(registroNuevo + "\n"); prueba = true; } else { writer.write(linea + "\n"); } } //Dependiendo de que la modificacion haya tenido exito o no se //mostrara un mensaje u otro mediante la variable prueba if (prueba == true) { JOptionPane.showMessageDialog(null, "Se ha modificado"); } else { JOptionPane.showMessageDialog(null, "No se ha modificado", "Error de ID", JOptionPane.WARNING_MESSAGE); } writer.close(); //En caso de error se imprimira el siguiente mensaje } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir/sobreescribir en el fichero", "Error de escritura", JOptionPane.WARNING_MESSAGE); } } /** * Esta funcion se encarga de eliminar un registro * * @param fichero archivo classroom.txt donde se almacenan los datos de las * aulas */ private static void eliminarRegistro(File fichero) { Scanner lector = new Scanner(System.in); //Le pedimos al usuario que ID quiere eliminar //Creamos un variable en donde se guarda el ID que quiere eliminar el usuario String ID; ID = JOptionPane.showInputDialog("Introduce el ID del aula que quieres eliminar: ").trim().toUpperCase(); //Elimina toda la linea del ID introducido // Array para guardar todos los registros leídos del fichero ArrayList<String> registros = new ArrayList<>(); // Abrimos el fichero de texto para leerlo en memoria try { Scanner lectorFichero = new Scanner(fichero); while (lectorFichero.hasNext()) { registros.add(lectorFichero.nextLine()); } lectorFichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } // Abrimos el fichero de texto para sobreescribirlo // Eliminaremos el registro que quiera el usuario // Despues cuando el usuario haya introducido el ID que quiere eliminar, la maquina nos dira si se ha eliminado bien o no try { FileWriter writer = new FileWriter(fichero); boolean idEliminado = false; for (String registro : registros) { if (!ID.equals(registro.substring(0, 3))) { writer.write(registro + "\n"); } else { idEliminado = true; } } if (idEliminado == true) { JOptionPane.showMessageDialog(null, "El registro se ha eliminado"); } else { JOptionPane.showMessageDialog(null, "El ID no existe/no se ha encontrado", "Error de ID", JOptionPane.WARNING_MESSAGE); } writer.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir/sobreescribir en el fichero", "Error de escritura", JOptionPane.WARNING_MESSAGE); } } /** * Esta funcion se encarga de pedir al usuario parametros sobre sobre el * nuevo registro, en esta ocasion esta sera usada para reemplazar la vieja * informacion de un registro por la nueva * * @return devuelve la linea creada */ private static String crearNuevalinea() { Scanner lector = new Scanner(System.in); String registroNuevo; String cantidadPc; String[] cambiar = new String[3]; String id = JOptionPane.showInputDialog(null, "Introduce un nuevo ID (Max 3 caracteres): ").trim().toUpperCase(); String nombreAula = JOptionPane.showInputDialog(null, "Nombre de aula: ").trim(); //lector.nextLine(); String cantidadAlumnos = JOptionPane.showInputDialog(null, "Capacidad de alumnos: ").trim(); cambiar[0] = JOptionPane.showInputDialog(null, "Hay pc's(Si/No): ").trim().toLowerCase(); if (cambiar[0].equals("no")) { cantidadPc = "Null"; } else { cantidadPc = JOptionPane.showInputDialog(null, "Cantidad de pc's disponibles: ").trim(); } cambiar[1] = JOptionPane.showInputDialog(null, "Hay proyector(Si/No): ").trim().toLowerCase(); cambiar[2] = JOptionPane.showInputDialog(null, "El aula esta insonorizada(Si/No): ").trim().toLowerCase(); //Poner las primeras letras en mayuscula for (int i = 0; i < cambiar.length; i++) { cambiar[i] = cambiar[i].substring(0, 1).toUpperCase() + cambiar[i].charAt(1); } nombreAula = nombreAula.substring(0, 1).toUpperCase() + nombreAula.substring(1); //String donde se guarda la linea de datos en formato CSV registroNuevo = id + "," + nombreAula + "," + cantidadAlumnos + "," + cambiar[0] + "," + cantidadPc + "," + cambiar[1] + "," + cambiar[2]; return registroNuevo; } //--------------------------------------SPRINT 3--------------------------------------------------- /** * Esta funcion se encarga de comparar si el usuario es un admin o un * profesor y mostar el menu correspondiente * * @param fichero datos del documento classroom.txt * @param posicion posicion en la que se encuentra el usuario en el array */ private static void ingresarUsuario(File fichero, int posicion) { Usuario[] comprobante = null; //variable para finalizar bucle boolean fin = false; try { ObjectInputStream archivo = new ObjectInputStream(new FileInputStream("usuarios.dat")); comprobante = (Usuario[]) archivo.readObject(); archivo.close(); } catch (Exception e) { System.out.println("Error al abrir o leer el fichero"); } //comparar el usuario con las dos opciones dependiando cual sea mostrara un menu distinto if (comprobante[posicion].rol.equals("Administrador")) { menuAdministrador(posicion, fichero); } else if (comprobante[posicion].rol.equals("Profesor")) { menuProfesor(fichero, posicion); } } /** * Esta funcion se encarga de prefuntar al usuario su usuario y contraseña * * @return devolvera la posicion del usuario en el array */ private static int menuInicio(File fichero) { Scanner lector = new Scanner(System.in); String usuarioIngresado = JOptionPane.showInputDialog("Ingrese el usuario: ").trim(); String contraseña = JOptionPane.showInputDialog("Ingrese la contraseña: ").trim(); Usuario[] comprobante = null; int posicion = 0; boolean comprobar = false; //finalizar bucle boolean fin = false; try { ObjectInputStream archivo = new ObjectInputStream(new FileInputStream("usuarios.dat")); comprobante = (Usuario[]) archivo.readObject(); // Cerramos el fichero archivo.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al leer el archivo", "Error de lectura", JOptionPane.WARNING_MESSAGE); } //bucle para recorrer el array se detendra cuando ingrese en if o cuando se recorra todo el array for (int i = 0; fin != true && i < comprobante.length; i++) { if (comprobante[i] != null && comprobante[i].usuario != null) { if (usuarioIngresado.equals(comprobante[i].usuario) && contraseña.equals(comprobante[i].contraseña)) { posicion = i; comprobar = true; fin = true; } } } if (comprobar == true) { JOptionPane.showMessageDialog(null, "Usuario y contraseña correctos"); ingresarUsuario(fichero, posicion); } else { JOptionPane.showMessageDialog(null, "Usuario o contraseña introducidos erroneos", "Error de inicio sesión", JOptionPane.WARNING_MESSAGE); menuInicio(fichero); } return posicion; } /** * Esta funcion es el menu que se le cederá al administrador Que tendra como * funciones añadir, modificar, eliminar y lista usuarios. * * @return devuelve la linea creada */ private static void menuAdministrador(int pos, File fichero) { Scanner lector = new Scanner(System.in); boolean salir = false; Usuario[] usuario = null; try { ObjectInputStream archivo = new ObjectInputStream(new FileInputStream("usuarios.dat")); usuario = (Usuario[]) archivo.readObject(); archivo.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } do { String menu[] = {"Crear usuario","Enumerar usuarios","Modificar usuario", "Eliminar usuario","Cerrar sesión","Apagar"}; int opciones = JOptionPane.showOptionDialog(null ,"Seleccione una opcion: " ,"Gestion de usuarios" ,JOptionPane.NO_OPTION ,JOptionPane.PLAIN_MESSAGE ,null ,menu ,"default"); switch (opciones) { case 0: crearUsuario(); break; case 1: mostrarUsuario(); break; case 2: editarUsuario(); break; case 3: eliminarUsuario(); break; case 4: menuInicio(fichero); System.out.println(""); salir = true; break; case 5: salir = true; break; } } while (salir != true); } /** * Esta funcion crea el unico usuario admin */ private static void usuarios() { Usuario[] usuario = new Usuario[100]; usuario[0] = new Usuario(); usuario[0].rol = "Administrador"; usuario[0].nombre = "Jose Andres"; usuario[0].usuario = "joan00"; usuario[0].contraseña = "1234"; usuario[1] = new Usuario(); usuario[1].rol = "Profesor"; usuario[1].nombre = "Matias Martinez"; usuario[1].usuario = "mat01"; usuario[1].contraseña = "12345"; try { ObjectOutputStream fichero = new ObjectOutputStream(new FileOutputStream("usuarios.dat")); // Con writeObject escribimos directamente todo el array de Usuario fichero.writeObject(usuario); // Cerramos el fichero fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } } /** * Esta funcion lista todos los usuarios */ private static void mostrarUsuario() { Usuario[] usuario = null; try { ObjectInputStream fichero = new ObjectInputStream(new FileInputStream("usuarios.dat")); usuario = (Usuario[]) fichero.readObject(); fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } int contuser = 0; System.out.println("------------------------------------------------------------"); for (Usuario user : usuario) { if (user != null && !user.rol.equalsIgnoreCase(" ")) { contuser++; System.out.print(contuser + ")Rol: " + user.rol + " | "); System.out.print("Nombre: " + user.nombre + " | "); System.out.println("Usuario: " + user.usuario); System.out.println("------------------------------------------------------------"); } } System.out.println("El numero total de usuarios guardados es de " + contuser + ".\n"); } /** * Esta funcion servira para crear el usuario junto a su contraseña, * usuario, nombre real y rol. * * @return devuelve la linea creada */ private static void crearUsuario() { String[] nuevoUsuario = nuevoUsuario(); boolean fin = false; int cont = 0; Usuario[] usuario = null; try { ObjectInputStream fichero = new ObjectInputStream(new FileInputStream("usuarios.dat")); usuario = (Usuario[]) fichero.readObject(); fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } for (int i = 0; fin != true || usuario[cont] == null; i++) { cont++; if (usuario[cont] == null || usuario[cont].equals(" ")) { usuario[cont] = new Usuario(); usuario[cont].rol = nuevoUsuario[0]; usuario[cont].nombre = nuevoUsuario[1]; usuario[cont].usuario = nuevoUsuario[2]; usuario[cont].contraseña = nuevoUsuario[3]; fin = true; JOptionPane.showMessageDialog(null, "Usuario y contraseña correctos"); } } try { ObjectOutputStream fichero = new ObjectOutputStream(new FileOutputStream("usuarios.dat")); // Con writeObject escribimos directamente todo el array de Usuario fichero.writeObject(usuario); // Cerramos el fichero fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } } /** * Esta funcion pide al usuario los datos para un nuevo usuario y los guarda * en una array * * @return devuelve el array con los datos cargados */ private static String[] nuevoUsuario() { boolean comprobar = false; String nuevoUsuario[] = new String[4]; while (comprobar != true) { Scanner lector = new Scanner(System.in); nuevoUsuario[0] = JOptionPane.showInputDialog(null, "Rol del usuario(Administrador/Profesor):").toLowerCase(); nuevoUsuario[1] = JOptionPane.showInputDialog(null, "Nombre y Apellido:").toLowerCase(); nuevoUsuario[2] = JOptionPane.showInputDialog(null, "Nombre de usuario:").trim(); nuevoUsuario[3] = JOptionPane.showInputDialog(null, "Contraseña:").trim(); //correccion de letras nuevoUsuario[0] = nuevoUsuario[0].substring(0, 1).toUpperCase() + nuevoUsuario[0].substring(1); nuevoUsuario[1] = nuevoUsuario[1].substring(0, 1).toUpperCase() + nuevoUsuario[1].substring(1, nuevoUsuario[1].indexOf(" ")) + nuevoUsuario[1].substring(nuevoUsuario[1].indexOf(" "), nuevoUsuario[1].indexOf(" ") + 2).toUpperCase() + nuevoUsuario[1].substring(nuevoUsuario[1].indexOf(" ") + 2); if (nuevoUsuario[0].equals("Administrador") || nuevoUsuario[0].equals("Profesor")) { comprobar = true; } else { JOptionPane.showMessageDialog(null, "El rol introduciso no es valido, vuelve a intentarlo", "Error de rol", JOptionPane.WARNING_MESSAGE); } } return nuevoUsuario; } //--------------------------------------SPRINT 4--------------------------------------------------- /** * Esta funcion se encarga de solicitar el nombre del usuario que desea * editar, luego lo edita con los nuevos parametros */ private static void editarUsuario() { Scanner lector = new Scanner(System.in); Usuario[] usuario = null; boolean fin = false; try { ObjectInputStream fichero = new ObjectInputStream(new FileInputStream("usuarios.dat")); usuario = (Usuario[]) fichero.readObject(); fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } String editar = JOptionPane.showInputDialog(null, "Nombre del Usuario que desea editar:"); editar = editar.substring(0, 1).toUpperCase() + editar.substring(1, editar.indexOf(" ")) + editar.substring(editar.indexOf(" "), editar.indexOf(" ") + 2).toUpperCase() + editar.substring(editar.indexOf(" ") + 2); String[] nuevoUsuario = nuevoUsuario(); for (Usuario user : usuario) { if (user != null && user.nombre.equals(editar)) { user.rol = nuevoUsuario[0]; user.nombre = nuevoUsuario[1]; user.usuario = nuevoUsuario[2]; user.contraseña = nuevoUsuario[3]; JOptionPane.showMessageDialog(null, "Usuario editado"); fin = true; } } try { ObjectOutputStream fichero = new ObjectOutputStream(new FileOutputStream("usuarios.dat")); // Con writeObject escribimos directamente todo el array de Usuario fichero.writeObject(usuario); // Cerramos el fichero fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } } /** * Esta funcion se encarga de eliminar un usuario */ public static void eliminarUsuario() { Scanner lector = new Scanner(System.in); Usuario[] usuario = null; try { //Aquí accederemos al fichero a leer mediante la variable fichero ObjectInputStream fichero = new ObjectInputStream(new FileInputStream("usuarios.dat")); // Y rellenamos con lo recuperado de leer el fichero mediante readObject // readObject recibe todo un array de Empleados y por eso lo casteamos (Empleado[]) usuario = (Usuario[]) fichero.readObject(); // Cerramos el fichero fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al abrir o leer el fichero", "Error de lectura", JOptionPane.WARNING_MESSAGE); } boolean fin = false; String nombreBorrar = ""; // BORRAR DATOS // Buscaremos por la clave primaria o varios campos, en este caso por Nombre y borraremos el registro while (fin != true) { nombreBorrar = JOptionPane.showInputDialog(null, "Introduce el nombre del usuario a eliminar: "); nombreBorrar = nombreBorrar.substring(0, 1).toUpperCase() + nombreBorrar.substring(1, nombreBorrar.indexOf(" ")) + nombreBorrar.substring(nombreBorrar.indexOf(" "), nombreBorrar.indexOf(" ") + 2).toUpperCase() + nombreBorrar.substring(nombreBorrar.indexOf(" ") + 2); for (Usuario user : usuario) { if (user != null && user.nombre.equals(nombreBorrar)) { user.rol = " "; user.nombre = " "; user.usuario = " "; user.contraseña = " "; user = null; fin = true; } } if (fin == false) { JOptionPane.showMessageDialog(null, "Nombre incorrecto", "Error de nombre", JOptionPane.WARNING_MESSAGE); } } // AMPLIACIÓN: Comprobar si se ha encontrado o no ese usuario a borrar e informar al usuario boolean comprobar = true; for (Usuario user : usuario) { if (user != null && user.nombre.equals(nombreBorrar)) { comprobar = false; } } if (comprobar == false) { JOptionPane.showMessageDialog(null, "ERROR. No se ha borrado correctamente el Usuario", "Error de borrado", JOptionPane.WARNING_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Se ha eliminado correctamente el usuario"); } // GUARDAR FICHERO try { // A partir de aquí accederemos al fichero a guardar mediante la variable fichero ObjectOutputStream fichero = new ObjectOutputStream(new FileOutputStream("usuarios.dat")); // Con writeObject escribimos directamente todo el array de Empleados fichero.writeObject(usuario); // Cerramos el fichero fichero.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Ha ocurrido un error al guardar el fichero", "Error de guardado", JOptionPane.WARNING_MESSAGE); } } }
package org.firstinspires.ftc.teamcode.robot; /* Class for drive functionality. Called in other classes. */ import org.firstinspires.ftc.robotcore.external.Telemetry; public class Wobbler { Hardware robot; Telemetry telemetry; boolean toggleWasPressed; boolean isOpen; int closeTimer = 11; public Wobbler(Hardware hardware, Telemetry telemetryInstance) { isOpen = false; robot = hardware; telemetry = telemetryInstance; } public void armRaise() { robot.lift1.setPosition(robot.lift1.getPosition() - 0.01); robot.lift2.setPosition(robot.lift2.getPosition() - 0.01); } public void armLower() { robot.lift1.setPosition(robot.lift1.getPosition() + 0.01); robot.lift2.setPosition(robot.lift2.getPosition() + 0.01); } public void armLefter() { robot.spin.setPosition(robot.spin.getPosition() - 0.01); } public void armRighter() { robot.spin.setPosition(robot.spin.getPosition() + 0.01); } public void armSide() { robot.spin.setPosition(0.72); } public void armBack() { robot.spin.setPosition(0.32); } public void armDown() { robot.lift1.setPosition(0.95); robot.lift2.setPosition(0.95); } public void armMiddle() { robot.lift1.setPosition(0.85); robot.lift2.setPosition(0.85); } public void armVertical() { robot.lift1.setPosition(0.5); robot.lift2.setPosition(0.5); } public void close() { robot.wobbleClawLeft.setPosition(0.9); robot.wobbleClawRight.setPosition(0.18); isOpen = false; } public void open() { robot.wobbleClawLeft.setPosition(0.62); robot.wobbleClawRight.setPosition(0.48); isOpen = true; } public void wobble(boolean toggleClaw, boolean armVertical, boolean armUp, boolean armDown, boolean armSide, boolean armBack, boolean upVertical, boolean downLeft) { if (toggleClaw) { if (!toggleWasPressed) { if (isOpen) { closeTimer = 0; close(); } else { open(); } } toggleWasPressed = true; } else { toggleWasPressed = false; } if (armVertical) { armVertical(); } if (armUp) { armMiddle(); } if (armDown) { armDown(); } if (armSide) { armSide(); } if (armBack) { armBack(); } if (upVertical && closeTimer > 10) { armVertical(); armBack(); } if (downLeft) { armDown(); armSide(); open(); } closeTimer += 1; //telemetry.addData("Left Claw Pos: ", robot.wobbleClawLeft.getPosition()); // telemetry.addData("Right Claw Pos: ", robot.wobbleClawRight.getPosition()); telemetry.addData("Arm Phi: ", robot.lift1.getPosition()); telemetry.addData("Arm Theta: ", robot.spin.getPosition()); } }
package 集合; import java.io.*; /** * @Author: Mr.M * @Date: 2019-03-12 20:44 * @Description: **/ public class IO { public static void main(String[] args) throws Exception { // A(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( "osw2.txt")); osw.write('a'); osw.write(97); // osw.flush(); osw.close(); // 写数据 // public void write(int c):写一个字符 // osw.write('a'); // osw.write(97); // 为什么数据没有进去呢? // 原因是:字符=2字节 } private static void A() throws IOException { // try (PrintWriter pw = new PrintWriter(new FileWriter("aa.txt"))) { // pw.println(123); // pw.println(456); // } catch (IOException e) { // e.printStackTrace(); // } BufferedOutputStream bufferedWriter =new BufferedOutputStream(new FileOutputStream("aabb.txt")); SequenceInputStream sequenceInputStream = new SequenceInputStream(new FileInputStream("aa.txt"), new FileInputStream("aa.txt")); // SequenceInputStream sequenceInputStream = new SequenceInputStream(new FileReader("aa.txt"), // new FileReader("aa.txt")); // System.out.println((char)sequenceInputStream.read()); // System.out.println((char)sequenceInputStream.read()); byte[] buf = new byte[1024]; int length = 0 ; while((length = sequenceInputStream.read(buf))!=-1){ bufferedWriter.write(buf,0,length); } //关闭资源 sequenceInputStream.close(); bufferedWriter.close(); } }
package com.example.jkl.dao; import com.example.jkl.mapper.UserOrderShipMapper; import com.example.jkl.pojo.Order; import com.example.jkl.pojo.UserOrderShip; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.entity.Example; import java.util.List; @Repository public class UserOrderShipDao { @Autowired UserOrderShipMapper userOrderShipMapper; public Integer addOrderRecord(UserOrderShip userOrderShip){ return userOrderShipMapper.insert(userOrderShip); } public Integer deleteOderRecord(Integer id){ return userOrderShipMapper.deleteByPrimaryKey(id); } public Integer deleteOrderListRecord(List<Integer> ids){ Example example= new Example(Order.class); example.createCriteria().andIn("id",ids); return userOrderShipMapper.deleteByExample(ids); } }
package com.oakfusion.router; import com.oakfusion.router.util.UriTree; import java.lang.reflect.Method; import static java.lang.String.format; public class Router { public static final Route R_404 = new Route("", "", null, null); protected RouteContext ctx; private final HttpMethodBuilder httpMethodBuilder = new HttpMethodBuilder(); private final HandlerClassBuilder handlerClassBuilder = new HandlerClassBuilder(); private final HandlerMethodBuilder handlerMethodBuilder = new HandlerMethodBuilder(); private final MethodLoader methodLoader = new MethodLoader(); private final UriTree<Route> routes = new UriTree<>("/"); public HttpMethodBuilder route(String uri) { ctx = new RouteContext(); ctx.uri = uri; return httpMethodBuilder; } public Route getRouteFor(String httpMethod, String uri) { String path = format("/%s%s", httpMethod, uri); UriTree<Route> node = routes.get(path); if (node == null) { return R_404; } return node.getData(); } protected class RouteContext { public String uri; public String httpMethod; public Class<?> controllerClass; public String controllerMethodName; } private RouteContext getContext() { return ctx; } private Router completeChain() { try { Method method = methodLoader.load(ctx.controllerClass, ctx.controllerMethodName); Route route = new Route(ctx.httpMethod, ctx.uri, ctx.controllerClass, method); routes.put(ctx.httpMethod).put(ctx.uri, route); return this; } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private enum HttpMethod { // http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT } public class HttpMethodBuilder { public HandlerClassBuilder whenOPTIONS() { return when(HttpMethod.OPTIONS); } public HandlerClassBuilder whenGET() { return when(HttpMethod.GET); } public HandlerClassBuilder whenHEAD() { return when(HttpMethod.HEAD); } public HandlerClassBuilder whenPOST() { return when(HttpMethod.POST); } public HandlerClassBuilder whenPUT() { return when(HttpMethod.PUT); } public HandlerClassBuilder whenDELETE() { return when(HttpMethod.DELETE); } public HandlerClassBuilder whenTRACE() { return when(HttpMethod.TRACE); } public HandlerClassBuilder whenCONNECT() { return when(HttpMethod.CONNECT); } private HandlerClassBuilder when(HttpMethod httpMethod) { return when(httpMethod.name()); } public HandlerClassBuilder when(String httpMethod) { getContext().httpMethod = httpMethod; return handlerClassBuilder; } } public HandlerClassBuilder whenOPTIONS() { return when(HttpMethod.OPTIONS); } public HandlerClassBuilder whenGET() { return when(HttpMethod.GET); } public HandlerClassBuilder whenHEAD() { return when(HttpMethod.HEAD); } public HandlerClassBuilder whenPOST() { return when(HttpMethod.POST); } public HandlerClassBuilder whenPUT() { return when(HttpMethod.PUT); } public HandlerClassBuilder whenDELETE() { return when(HttpMethod.DELETE); } public HandlerClassBuilder whenTRACE() { return when(HttpMethod.TRACE); } public HandlerClassBuilder whenCONNECT() { return when(HttpMethod.CONNECT); } private HandlerClassBuilder when(HttpMethod httpMethod) { return when(httpMethod.name()); } public HandlerClassBuilder when(String httpMethod) { if (getContext() == null) { throw new RuntimeException("Route context not initialized"); } return httpMethodBuilder.when(httpMethod); } public class HandlerClassBuilder { public HandlerMethodBuilder handleIn(Class<?> controllerClass) { getContext().controllerClass = controllerClass; return handlerMethodBuilder; } } public class HandlerMethodBuilder { public Router by(String methodName) { getContext().controllerMethodName = methodName; return completeChain(); } } }
import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFileChooser; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JOptionPane; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.swing.JTextArea; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; @SuppressWarnings("serial") public class ExamApp_ServerEdition extends JFrame { private JPanel contentPane; private JTextField textField; static ServerSocket serverSocket; boolean serverStatus=true; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ExamApp_ServerEdition frame = new ExamApp_ServerEdition(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ExamApp_ServerEdition() { setTitle("ExamAppForFaculty"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 449, 335); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btnNewButton = new JButton("SwitchOn Server"); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { serverSocket = new ServerSocket(3434); Socket socket ; while(true){ socket = serverSocket.accept(); ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); try { Request request = (Request) input.readObject(); System.out.println(request.type); if(request.type.equals("Upload")) { Upload urequest = (Upload)(request); System.out.println(urequest.filename); System.out.println(urequest.file.length); FileOutputStream fos = new FileOutputStream("J:\\Answers\\"+urequest.filename); fos.write(urequest.file); fos.close(); } else if(request.type.equals("View")) { System.out.println("here"); ObjectOutputStream out = new ObjectOutputStream(socket. getOutputStream()); File f = new File("J:\\exam_question"); String[] data = f.list(); System.out.println(data.length); out.writeObject(data); } else if(request.type.equals("Download")) { System.out.println("here2"); Download drequest = (Download)(request); String file = "J:\\exam_question\\" + drequest.selectedFile; System.out.println(file); Path p = Paths.get(file); byte[] afile = Files.readAllBytes(p); ObjectOutputStream out = new ObjectOutputStream(socket. getOutputStream()); out.writeObject(afile); System.out.println("buffer"); } } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 13)); btnNewButton.setBounds(54, 24, 152, 37); contentPane.add(btnNewButton); textField = new JTextField(); textField.setBounds(54, 81, 152, 20); contentPane.add(textField); textField.setColumns(10); JButton btnBrowse = new JButton("Browse"); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnBrowse.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { final JFileChooser fc = new JFileChooser(); int response = fc.showOpenDialog(ExamApp_ServerEdition.this); if(response==JFileChooser.APPROVE_OPTION) { textField.setText(fc.getSelectedFile().toString()); System.out.println(fc.getSelectedFile().toString()); } else { JOptionPane.showMessageDialog(null, "Error Opening File", "Error", JOptionPane.WARNING_MESSAGE); } } }); btnBrowse.setBounds(225, 80, 89, 23); contentPane.add(btnBrowse); JButton btnNewButton_1 = new JButton("Upload QuestionPaper"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnNewButton_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { InputStream inStream = null; OutputStream outStream = null; try{ File source =new File(textField.getText()); String s = textField.getText(); String required = s.substring(s.lastIndexOf("\\")+1,s.length()); File dest =new File("J:\\exam_question\\" + required ); inStream = new FileInputStream(source); outStream = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } if (inStream != null)inStream.close(); if (outStream != null)outStream.close(); System.out.println("File Copied.."); textField.setText(""); JOptionPane.showMessageDialog(null, "File Uploaded", "Message", JOptionPane.INFORMATION_MESSAGE); }catch(IOException e1){ e1.printStackTrace(); } } }); btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 12)); btnNewButton_1.setBounds(119, 112, 152, 23); contentPane.add(btnNewButton_1); DefaultListModel<String> model = new DefaultListModel<>(); JTextArea textArea = new JTextArea(); textArea.setToolTipText("will show the list of answer sheets."); textArea.setEditable(false); textArea.setBounds(37, 188, 321, 97); contentPane.add(textArea); JButton btnNewButton_2 = new JButton("View AnswerSheets"); btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnNewButton_2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { File f = new File("J:\\Answers"); String[] data = f.list(); for(String filename : data) { textArea.append(filename +"\n"); model.addElement(filename); System.out.println(filename); } } }); btnNewButton_2.setFont(new Font("Tahoma", Font.BOLD, 12)); btnNewButton_2.setBounds(92, 146, 223, 23); contentPane.add(btnNewButton_2); JButton btnNewButton_3 = new JButton("SwitchOff Server"); btnNewButton_3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { serverStatus = false; } }); btnNewButton_3.setFont(new Font("Tahoma", Font.BOLD, 13)); btnNewButton_3.setBounds(225, 24, 144, 37); contentPane.add(btnNewButton_3); } public static void testmethod() { try { serverSocket = new ServerSocket(3434); Socket socket ; // while(true){ socket = serverSocket.accept(); ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); try { Request request = (Request) input.readObject(); System.out.println(request.type); if(request.type.equals("Upload")) { Upload urequest = (Upload)(request); System.out.println(urequest.filename); System.out.println(urequest.file.length); FileOutputStream fos = new FileOutputStream("J:\\Answers\\"+urequest.filename); fos.write(urequest.file); fos.close(); } else if(request.type.equals("View")) { System.out.println("here"); ObjectOutputStream out = new ObjectOutputStream(socket. getOutputStream()); File f = new File("J:\\exam_question"); String[] data = f.list(); System.out.println(data.length); out.writeObject(data); } else if(request.type.equals("Download")) { System.out.println("here2"); Download drequest = (Download)(request); String file = "J:\\exam_question\\" + drequest.selectedFile; System.out.println(file); Path p = Paths.get(file); byte[] afile = Files.readAllBytes(p); ObjectOutputStream out = new ObjectOutputStream(socket. getOutputStream()); out.writeObject(afile); System.out.println("buffer"); } } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
package com.tencent.mm.booter.notification; import java.io.Serializable; class c$a implements Serializable { public int cYz; public String userName; private c$a() { } public /* synthetic */ c$a(byte b) { this(); } public final String toString() { return "[" + this.userName + "(" + this.cYz + ")]"; } }
package engine; import engine.cutCondition.CutCondition; import java.util.List; public class TimeStepSimulator { private final double timeDelta; private final double saveTimeDelta; private final CutCondition cutCondition; private final FileGenerator fileGenerator; private final List<Particle> particles; private final double innerRadius; private final double outerRadius; private final double minRadius; private final double maxRadius; private final double maxVelocity; private final double beta; private final double tau; private double time; private double timeToSave; public TimeStepSimulator(double timeDelta, double saveTimeDelta, CutCondition cutCondition, FileGenerator fileGenerator, List<Particle> particles, double innerRadius, double outerRadius, double minRadius, double maxRadius, double maxVelocity, double beta, double tau) { this.timeDelta = timeDelta; this.saveTimeDelta = saveTimeDelta; this.cutCondition = cutCondition; this.fileGenerator = fileGenerator; this.particles = particles; this.timeToSave = saveTimeDelta; this.innerRadius = innerRadius; this.outerRadius = outerRadius; this.minRadius = minRadius; this.maxRadius = maxRadius; this.maxVelocity = maxVelocity; this.beta = beta; this.tau = tau; this.time = 0; } public void simulate() { fileGenerator.addToFile(particles, time); while (!cutCondition.isFinished(particles, time)) { checkCollisionsAndEscapeVelocities(particles); changeRadiusAndMoveParticles(particles); time += timeDelta; if (time >= timeToSave) { fileGenerator.addToFile(particles, time); timeToSave += saveTimeDelta; } } fileGenerator.closeFile(); } private void checkCollisionsAndEscapeVelocities(List<Particle> particles) { for (Particle p1 : particles) { p1.setOverlapped(false); Vector escapeVelocity = new Vector(0, 0); boolean overlappedParticle = false; for (Particle p2 : particles) { // Other particles if (!p1.equals(p2)) { if (p1.getPosition().distance(p2.getPosition()) <= p1.getRadius() + p2.getRadius()) { // Check if it's overlapping another particle escapeVelocity = escapeVelocity.add(p2.getPosition().perpendicularVector(p1.getPosition())); overlappedParticle = true; } } } if (Math.hypot(p1.getPosition().getX(), p1.getPosition().getY()) >= (outerRadius - p1.getRadius())) { // Check if it's overlapping outer wall double particlePositionAngle = Math.atan2(p1.getPosition().getY(), p1.getPosition().getX()); double outerWallXPosition = Math.abs(outerRadius * Math.cos(particlePositionAngle)); double outerWallYPosition = Math.abs(outerRadius * Math.sin(particlePositionAngle)); outerWallXPosition = Math.signum(p1.getPosition().getX()) * outerWallXPosition; outerWallYPosition = Math.signum(p1.getPosition().getY()) * outerWallYPosition; Vector wallPosition = new Vector(outerWallXPosition, outerWallYPosition); double xEscape = Math.abs(wallPosition.perpendicularVector(p1.getPosition()).getX()); double yEscape = Math.abs(wallPosition.perpendicularVector(p1.getPosition()).getY()); if (p1.getPosition().getX() >= 0 && p1.getPosition().getY() >= 0) { escapeVelocity = escapeVelocity.add(new Vector(-xEscape, -yEscape)); } else if (p1.getPosition().getX() < 0 && p1.getPosition().getY() >= 0) { escapeVelocity = escapeVelocity.add(new Vector(xEscape, -yEscape)); } else if (p1.getPosition().getX() >= 0 && p1.getPosition().getY() < 0) { escapeVelocity = escapeVelocity.add(new Vector(-xEscape, yEscape)); } else { escapeVelocity = escapeVelocity.add(new Vector(xEscape, yEscape)); } overlappedParticle = true; } else if (Math.hypot(p1.getPosition().getX(), p1.getPosition().getY()) <= (innerRadius + p1.getRadius())) { // Check if it's overlapping inner wall double particlePositionAngle = Math.atan2(p1.getPosition().getY(), p1.getPosition().getX()); double innerWallXPosition = Math.abs(innerRadius * Math.cos(particlePositionAngle)); double innerWallYPosition = Math.abs(innerRadius * Math.sin(particlePositionAngle)); innerWallXPosition = Math.signum(p1.getPosition().getX()) * innerWallXPosition; innerWallYPosition = Math.signum(p1.getPosition().getY()) * innerWallYPosition; Vector wallPosition = new Vector(innerWallXPosition, innerWallYPosition); escapeVelocity = escapeVelocity.add(wallPosition.perpendicularVector(p1.getPosition())); overlappedParticle = true; } if (overlappedParticle) { escapeVelocity = escapeVelocity.normalize().multiply(maxVelocity); p1.setVelocity(escapeVelocity); p1.setOverlapped(true); } } } private void changeRadiusAndMoveParticles(List<Particle> particles) { for (Particle particle : particles) { // Change radius if (particle.isOverlapped()) { particle.setRadius(minRadius); } else if (particle.getRadius() < maxRadius) { double newRadius = particle.getRadius() + (minRadius / (tau / timeDelta)); particle.setRadius(Math.min(newRadius, maxRadius)); } // Change velocity if not overlapped with new radius if (!particle.isOverlapped()) { double velocityAngle = Math.atan2(particle.getPosition().getX(), particle.getPosition().getY()) - Math.PI / 2; double velocityModule = maxVelocity * Math.pow((particle.getRadius() - minRadius) / (maxRadius - minRadius), beta); double xVelocity = velocityModule * Math.sin(velocityAngle); double yVelocity = velocityModule * Math.cos(velocityAngle); particle.setVelocity(new Vector(xVelocity, yVelocity)); } // Set position with new velocity Vector newPosition = particle.getPosition().add(particle.getVelocity().multiply(timeDelta)); particle.setPosition(newPosition); } } }
package ProjectPersonal.Thethreecarddealer; import java.util.Random; import java.util.Vector; public class ProbabilityGame { //A class that will create Deck of 52. public class DeckofCards{ //this class stores Card number, color and suite or shape. private class Node{ String cardnumber; String color; String shape; //constructor Node(){} } public Node card = new Node(); //main constructor DeckofCards(){} //customize constructor. DeckofCards(String card, String color, String shape){ setCard(card); setColor(color); setShape(shape); } //these are gets and sets functions. public String getCard() {return card.cardnumber;} public String getColor() {return card.color;} public String getShape() {return card.shape;} public void setCard(String number) { card.cardnumber = number; } public void setColor(String color) { card.color = color; } public void setShape(String shape) { card.shape = shape; } }//end of class DeckofCards //declaring a variable to access the class. Vector<DeckofCards> deck; //making the deck of cards. public void makeDeck() { deck = new Vector<DeckofCards>(); //these variables are used to store the values, colours and suites per each card. String[] number = { "A","K","Q","J","2","3","4", "5", "6", "7", "8", "9", "10" }; String[] suites = { "diamonds", "clubs", "hearts", "spades" }; //using for loops and if statements to create the virtual card deck. for (String i:suites) { //if its a diamonds or clubs recall they are black. if((i == "diamonds") || (i == "clubs")){ for (String j : number) { deck.add(new DeckofCards(j,"black",i)); } } else { for (String j : number) { deck.add(new DeckofCards(j, "red", i)); } } } }//end of the makeDeck() //this function will help in calculate probability. private double prob(int x) { if (x == 1) { return 1.0; } else {return(x * prob(x - 1));} } //this function is used primarily to find out what is the chance of selecting // a random card regardless of color, number, and/or shape. public Vector<String> selectCard(String card, String suite) { Vector<String> a = new Vector<String>(); //locating the selected card from the 52 cards for (int i = 0; i < 52; i++) { if ((deck.get(i).getCard().equals(card)) && (deck.get(i).getShape().equals(suite))) { a.add(card); a.add(suite); //making the probability of selecting the same card calculation. double x = (1.0 / 52.0) * 100; a.add(String.valueOf(x)); //making the probabilty of selecting the same suite calculation. double y = (12.0 / 51.0) * 100; a.add(String.valueOf(y)); //making the probabilty of selecting the same colour calculation. double z = (25.0 / 51.0) * 100; a.add(String.valueOf(z)); //making the probabilty of selecting the same number calculation. double b = (3.0 / 51.0) * 100; a.add(String.valueOf(b)); } } return a; } //to get the deck ventra. Vector<DeckofCards> getDeck(){return this.deck;} }
public class Second { Simple simple; String s; public Second(String si) { s = si; // 'simple' not initialized } public void check() { if(simple == null) System.out.println("not initialized"); else System.out.println("initialized"); } private Simple lazy() { if(simple == null) { System.out.println("Creating Simple"); simple = new Simple(s); } return simple; } public Simple getSimple() { return lazy(); } public String toString() { return lazy().toString(); } public void setSimple(String sNew) { lazy().setString(sNew); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.unpack200; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import org.apache.harmony.pack200.BHSDCodec; import org.apache.harmony.pack200.Codec; import org.apache.harmony.pack200.CodecEncoding; import org.apache.harmony.pack200.Pack200Exception; import org.apache.harmony.pack200.PopulationCodec; import org.apache.harmony.unpack200.bytecode.CPAnyMemberRef; import org.apache.harmony.unpack200.bytecode.CPBootstrapMethod; import org.apache.harmony.unpack200.bytecode.CPClass; import org.apache.harmony.unpack200.bytecode.CPDouble; import org.apache.harmony.unpack200.bytecode.CPFieldRef; import org.apache.harmony.unpack200.bytecode.CPFloat; import org.apache.harmony.unpack200.bytecode.CPInteger; import org.apache.harmony.unpack200.bytecode.CPInterfaceMethodRef; import org.apache.harmony.unpack200.bytecode.CPInvokeDynamic; import org.apache.harmony.unpack200.bytecode.CPLoadableValue; import org.apache.harmony.unpack200.bytecode.CPLong; import org.apache.harmony.unpack200.bytecode.CPMethodHandle; import org.apache.harmony.unpack200.bytecode.CPMethodRef; import org.apache.harmony.unpack200.bytecode.CPMethodType; import org.apache.harmony.unpack200.bytecode.CPNameAndType; import org.apache.harmony.unpack200.bytecode.CPString; import org.apache.harmony.unpack200.bytecode.CPUTF8; import org.apache.harmony.unpack200.bytecode.ClassFileEntry; /** * Abstract superclass for a set of bands */ abstract class BandSet { public abstract void read(InputStream inputStream) throws IOException, Pack200Exception; public abstract void unpack() throws IOException, Pack200Exception; public void unpack(InputStream in) throws IOException, Pack200Exception { read(in); unpack(); } protected Segment segment; protected SegmentHeader header; public BandSet(Segment segment) { this.segment = segment; this.header = segment.getSegmentHeader(); } /** * Decode a band and return an array of <code>int</code> values * * @param name * the name of the band (primarily for logging/debugging * purposes) * @param in * the InputStream to decode from * @param codec * the default Codec for this band * @param count * the number of elements to read * @return an array of decoded <code>int</code> values * @throws IOException * if there is a problem reading from the underlying input * stream * @throws Pack200Exception * if there is a problem decoding the value or that the value is * invalid */ public int[] decodeBandInt(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] band; // Useful for debugging if(count > 0) { System.out.println("decoding " + name + " " + count); } Codec codecUsed = codec; if (codec.getB() == 1 || count == 0) { return codec.decodeInts(count, in); } int[] getFirst = codec.decodeInts(1, in); if (getFirst.length == 0) { return getFirst; } int first = getFirst[0]; if (codec.isSigned() && first >= -256 && first <= -1) { // Non-default codec should be used codecUsed = CodecEncoding.getCodec((-1 - first), header .getBandHeadersInputStream(), codec); band = codecUsed.decodeInts(count, in); } else if (!codec.isSigned() && first >= codec.getL() && first <= codec.getL() + 255) { // Non-default codec should be used codecUsed = CodecEncoding.getCodec(first - codec.getL(), header .getBandHeadersInputStream(), codec); band = codecUsed.decodeInts(count, in); } else { // First element should not be discarded band = codec.decodeInts(count - 1, in, first); } // Useful for debugging -E options: if(!codecUsed.equals(codec)) { int bytes = codecUsed.lastBandLength; System.out.println(count + " " + name + " encoded with " + codecUsed + " " + bytes); } if (codecUsed instanceof PopulationCodec) { PopulationCodec popCodec = (PopulationCodec) codecUsed; int[] favoured = (int[]) popCodec.getFavoured().clone(); Arrays.sort(favoured); for (int i = 0; i < band.length; i++) { boolean favouredValue = Arrays.binarySearch(favoured, band[i]) > -1; Codec theCodec = favouredValue ? popCodec.getFavouredCodec() : popCodec.getUnfavouredCodec(); if (theCodec instanceof BHSDCodec && ((BHSDCodec) theCodec).isDelta()) { BHSDCodec bhsd = (BHSDCodec) theCodec; long cardinality = bhsd.cardinality(); while (band[i] > bhsd.largest()) { band[i] -= cardinality; } while (band[i] < bhsd.smallest()) { band[i] += cardinality; } } } } return band; } /** * Decode a band and return an array of <code>int[]</code> values * * @param name * the name of the band (primarily for logging/debugging * purposes) * @param in * the InputStream to decode from * @param defaultCodec * the default codec for this band * @param counts * the numbers of elements to read for each int array within the * array to be returned * @return an array of decoded <code>int[]</code> values * @throws IOException * if there is a problem reading from the underlying input * stream * @throws Pack200Exception * if there is a problem decoding the value or that the value is * invalid */ public int[][] decodeBandInt(String name, InputStream in, BHSDCodec defaultCodec, int[] counts) throws IOException, Pack200Exception { int[][] result = new int[counts.length][]; int totalCount = 0; for (int i = 0; i < counts.length; i++) { totalCount += counts[i]; } int[] twoDResult = decodeBandInt(name, in, defaultCodec, totalCount); int index = 0; for (int i = 0; i < result.length; i++) { try { result[i] = new int[counts[i]]; for (int j = 0; j < result[i].length; j++) { result[i][j] = twoDResult[index]; index++; } } catch (RuntimeException e){ throw new RuntimeException("Problem decoding band: " + name + " default codec: " + defaultCodec, e); } } return result; } public long[] parseFlags(String name, InputStream in, int count, BHSDCodec codec, boolean hasHi) throws IOException, Pack200Exception { return parseFlags(name, in, new int[] { count }, (hasHi ? codec : null), codec)[0]; } public long[][] parseFlags(String name, InputStream in, int counts[], BHSDCodec codec, boolean hasHi) throws IOException, Pack200Exception { return parseFlags(name, in, counts, (hasHi ? codec : null), codec); } public long[] parseFlags(String name, InputStream in, int count, BHSDCodec hiCodec, BHSDCodec loCodec) throws IOException, Pack200Exception { return parseFlags(name, in, new int[] { count }, hiCodec, loCodec)[0]; } public long[][] parseFlags(String name, InputStream in, int counts[], BHSDCodec hiCodec, BHSDCodec loCodec) throws IOException, Pack200Exception { int count = counts.length; if (count == 0) { return new long[][] { {} }; } int sum = 0; long[][] result = new long[count][]; for (int i = 0; i < count; i++) { result[i] = new long[counts[i]]; sum += counts[i]; } int[] hi = null; int[] lo; if (hiCodec != null) { hi = decodeBandInt(name, in, hiCodec, sum); lo = decodeBandInt(name, in, loCodec, sum); } else { lo = decodeBandInt(name, in, loCodec, sum); } int index = 0; for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[i].length; j++) { if (hi != null) { result[i][j] = ((long) hi[index] << 32) | (lo[index] & 4294967295L); } else { result[i][j] = lo[index]; } index++; } } return result; } /** * Helper method to parse <i>count</i> references from <code>in</code>, * using <code>codec</code> to decode the values as indexes into * <code>reference</code> (which is populated prior to this call). An * exception is thrown if a decoded index falls outside the range * [0..reference.length-1]. * * @param name * the band name * @param in * the input stream to read from * @param codec * the BHSDCodec to use for decoding * @param count * the number of references to decode * @param reference * the array of values to use for the references * * @throws IOException * if a problem occurs during reading from the underlying stream * @throws Pack200Exception * if a problem occurs with an unexpected value or unsupported * Codec */ public String[] parseReferences(String name, InputStream in, BHSDCodec codec, int count, String[] reference) throws IOException, Pack200Exception { return parseReferences(name, in, codec, new int[] { count }, reference)[0]; } /** * Helper method to parse <i>count</i> references from <code>in</code>, * using <code>codec</code> to decode the values as indexes into * <code>reference</code> (which is populated prior to this call). An * exception is thrown if a decoded index falls outside the range * [0..reference.length-1]. Unlike the other parseReferences, this * post-processes the result into an array of results. * * @param name * TODO * @param in * the input stream to read from * @param codec * the BHSDCodec to use for decoding * @param counts * the numbers of references to decode for each array entry * @param reference * the array of values to use for the references * * @throws IOException * if a problem occurs during reading from the underlying stream * @throws Pack200Exception * if a problem occurs with an unexpected value or unsupported * Codec */ public String[][] parseReferences(String name, InputStream in, BHSDCodec codec, int counts[], String[] reference) throws IOException, Pack200Exception { int count = counts.length; if (count == 0) { return new String[][] { {} }; } String[][] result = new String[count][]; int sum = 0; for (int i = 0; i < count; i++) { result[i] = new String[counts[i]]; sum += counts[i]; } // TODO Merge the decode and parsing of a multiple structure into one String[] result1 = new String[sum]; int[] indices = decodeBandInt(name, in, codec, sum); for (int i1 = 0; i1 < sum; i1++) { int index = indices[i1]; if (index < 0 || index >= reference.length) throw new Pack200Exception( "Something has gone wrong during parsing references, index = " + index + ", array size = " + reference.length); result1[i1] = reference[index]; } String[] refs = result1; // TODO Merge the decode and parsing of a multiple structure into one int pos = 0; for (int i = 0; i < count; i++) { int num = counts[i]; result[i] = new String[num]; System.arraycopy(refs, pos, result[i], 0, num); pos += num; } return result; } public CPInteger[] parseCPIntReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] reference = segment.getCpBands().getCpInt(); int[] indices = decodeBandInt(name, in, codec, count); CPInteger[] result = new CPInteger[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; if (index < 0 || index >= reference.length) throw new Pack200Exception( "Something has gone wrong during parsing references, index = " + index + ", array size = " + reference.length); result[i1] = segment.getCpBands().cpIntegerValue(index); } return result; } public CPDouble[] parseCPDoubleReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPDouble[] result = new CPDouble[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = segment.getCpBands().cpDoubleValue(index); } return result; } public CPFloat[] parseCPFloatReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPFloat[] result = new CPFloat[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = segment.getCpBands().cpFloatValue(index); } return result; } public CPLong[] parseCPLongReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { long[] reference = segment.getCpBands().getCpLong(); int[] indices = decodeBandInt(name, in, codec, count); CPLong[] result = new CPLong[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; if (index < 0 || index >= reference.length) throw new Pack200Exception( "Something has gone wrong during parsing references, index = " + index + ", array size = " + reference.length); result[i1] = segment.getCpBands().cpLongValue(index); } return result; } public CPUTF8[] parseCPUTF8References(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPUTF8[] result = new CPUTF8[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = segment.getCpBands().cpUTF8Value(index); } return result; } public CPUTF8[][] parseCPUTF8References(String name, InputStream in, BHSDCodec codec, int[] counts) throws IOException, Pack200Exception { CPUTF8[][] result = new CPUTF8[counts.length][]; int sum = 0; for (int i = 0; i < counts.length; i++) { result[i] = new CPUTF8[counts[i]]; sum += counts[i]; } CPUTF8[] result1 = new CPUTF8[sum]; int[] indices = decodeBandInt(name, in, codec, sum); for (int i1 = 0; i1 < sum; i1++) { int index = indices[i1]; result1[i1] = segment.getCpBands().cpUTF8Value(index); } CPUTF8[] refs = result1; int pos = 0; for (int i = 0; i < counts.length; i++) { int num = counts[i]; result[i] = new CPUTF8[num]; System.arraycopy(refs, pos, result[i], 0, num); pos += num; } return result; } public CPString[] parseCPStringReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPString[] result = new CPString[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = segment.getCpBands().cpStringValue(index); } return result; } public CPInterfaceMethodRef[] parseCPInterfaceMethodRefReferences( String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { CpBands cpBands = segment.getCpBands(); int[] indices = decodeBandInt(name, in, codec, count); CPInterfaceMethodRef[] result = new CPInterfaceMethodRef[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = cpBands.cpIMethodValue(index); } return result; } public CPMethodRef[] parseCPMethodRefReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { CpBands cpBands = segment.getCpBands(); int[] indices = decodeBandInt(name, in, codec, count); CPMethodRef[] result = new CPMethodRef[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = cpBands.cpMethodValue(index); } return result; } public CPFieldRef[] parseCPFieldRefReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { CpBands cpBands = segment.getCpBands(); int[] indices = decodeBandInt(name, in, codec, count); CPFieldRef[] result = new CPFieldRef[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = cpBands.cpFieldValue(index); } return result; } public CPNameAndType[] parseCPDescriptorReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { CpBands cpBands = segment.getCpBands(); int[] indices = decodeBandInt(name, in, codec, count); CPNameAndType[] result = new CPNameAndType[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = cpBands.cpNameAndTypeValue(index); } return result; } public CPUTF8[] parseCPSignatureReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPUTF8[] result = new CPUTF8[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = segment.getCpBands().cpSignatureValue(index); } return result; } protected CPUTF8[][] parseCPSignatureReferences(String name, InputStream in, BHSDCodec codec, int[] counts) throws IOException, Pack200Exception { CPUTF8[][] result = new CPUTF8[counts.length][]; int sum = 0; for (int i = 0; i < counts.length; i++) { result[i] = new CPUTF8[counts[i]]; sum += counts[i]; } CPUTF8[] result1 = new CPUTF8[sum]; int[] indices = decodeBandInt(name, in, codec, sum); for (int i1 = 0; i1 < sum; i1++) { int index = indices[i1]; result1[i1] = segment.getCpBands().cpSignatureValue(index); } CPUTF8[] refs = result1; int pos = 0; for (int i = 0; i < counts.length; i++) { int num = counts[i]; result[i] = new CPUTF8[num]; System.arraycopy(refs, pos, result[i], 0, num); pos += num; } return result; } public CPClass[] parseCPClassReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPClass[] result = new CPClass[indices.length]; for (int i1 = 0; i1 < count; i1++) { int index = indices[i1]; result[i1] = segment.getCpBands().cpClassValue(index); } return result; } public CPMethodHandle [] parseCPMethodHandleReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPMethodHandle [] result = new CPMethodHandle[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().cpMethodHandleValue(il); } return result; } public CPMethodType [] parseCPMethodTypeReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPMethodType [] result = new CPMethodType[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().cpMethodTypeValue(il); } return result; } public CPBootstrapMethod [] parseCPBootstrapMethodReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPBootstrapMethod [] result = new CPBootstrapMethod[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().cpBootstrapMethodValue(il); } return result; } public CPInvokeDynamic [] parseCPInvokeDynamicReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPInvokeDynamic [] result = new CPInvokeDynamic[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().cpInvokeDynamicValue(il); } return result; } public CPLoadableValue [] parseCPLoadableValueReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPLoadableValue [] result = new CPLoadableValue[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().cpLoadableValue(il); } return result; } public CPAnyMemberRef [] parseCPAnyMemberReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); CPAnyMemberRef [] result = new CPAnyMemberRef[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().cpAnyMemberValue(il); } return result; } public ClassFileEntry [] parseCPAllReferences(String name, InputStream in, BHSDCodec codec, int count) throws IOException, Pack200Exception { int[] indices = decodeBandInt(name, in, codec, count); ClassFileEntry [] result = new ClassFileEntry[indices.length]; for (int il = 0; il < count; il++){ result[il] = segment.getCpBands().all(il); } return result; } protected String[] getReferences(int[] ints, String[] reference) { String[] result = new String[ints.length]; for (int i = 0; i < result.length; i++) { result[i] = reference[ints[i]]; } return result; } protected String[][] getReferences(int[][] ints, String[] reference) { String[][] result = new String[ints.length][]; for (int i = 0; i < result.length; i++) { result[i] = new String[ints[i].length]; for (int j = 0; j < result[i].length; j++) { result[i][j] = reference[ints[i][j]]; } } return result; } }
package cn.canlnac.onlinecourse.data.entity; import com.google.gson.annotations.SerializedName; import java.util.List; /** * 话题列表. */ public class ChatListEntity { @SerializedName("total") private int total; @SerializedName("chats") private List<ChatEntity> chats; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<ChatEntity> getChats() { return chats; } public void setChats(List<ChatEntity> chats) { this.chats = chats; } }
package org.japo.java.basics.main; public class HorarioComercial { public static void main(String[] args) { // Apertura int HA = 9; int MA = 30; int SA = 0; // Cierre int HC = 23; int MC = 59; int SC = 59; // Hora arbitraria (CORRECTA) int hh = 6; int mm = 35; int ss = 26; // Conversion a segundos int horaIni = HA * 3600 + MA * 60 + SA; int horaFin = HC * 3600 + MC * 60 + SC; int horaAct = hh * 3600 + mm * 60 + ss; // Análisis: true > abierto - falae > cerrado boolean testOK = horaAct >= horaIni && horaAct <= horaFin; // Generar mensaje String mensaje = testOK ? "Abierto" : "Cerrado"; // Mostrar resultados System.out.printf("Hora apertura ....: %02d:%02d:%02d\n", HA, MA, SA); System.out.printf("Hora cierre ......: %02d:%02d:%02d\n", HC, MC, SC); System.out.printf("Hora análisis ....: %02d:%02d:%02d\n", hh, mm, ss); System.out.printf("Centro comercial .: %s\n", mensaje); } }
package com.todolist.app.ws.io.entity; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity(name = "todolists") public class ToDoListEntity implements Serializable { private static final long serialVersionUID = 5849649716377121924L; @Id @GeneratedValue private long id; @Column(length = 30, nullable = false) private String todoListId; @Column(length = 100, nullable = false) private String name; @ManyToOne @JoinColumn(name = "users_id") private UserEntity userDetails; @OneToMany(mappedBy = "toDoListDetails", cascade = CascadeType.ALL) private List<ToDoItemEntity> todoitems; public String getTodoListId() { return todoListId; } public void setTodoListId(String todoListId) { this.todoListId = todoListId; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public UserEntity getUserDetails() { return userDetails; } public void setUserDetails(UserEntity userDetails) { this.userDetails = userDetails; } public List<ToDoItemEntity> getTodoItems() { return todoitems; } public void setTodoItems(List<ToDoItemEntity> todoitems) { this.todoitems = todoitems; } }
package com.tb.bughub.order.demo.model; import javax.persistence.*; import java.util.Objects; @Entity @Table(name="MENU_ITEM") public class MenuItem { @Id @Column(name = "id") private String id; @Column(name = "name") private String name; @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY) @JoinColumn(name = "order_id") private Order order; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MenuItem menuItem = (MenuItem) o; return Objects.equals(id, menuItem.id) && Objects.equals(name, menuItem.name) && Objects.equals(order, menuItem.order); } @Override public int hashCode() { return Objects.hash(id, name, order); } public MenuItem() { super(); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return super.toString(); } @Override protected void finalize() throws Throwable { super.finalize(); } }
// // Generated by JTB 1.3.2 // package visitor; import syntaxtree.*; import java.util.*; /** * Provides default methods which visit each node in the tree in depth-first * order. Your visitors may extend this class. */ public class ConverttoMiniRA1 extends GJDepthFirst<Arginfo,Arginfo>{ // // Auto class visitors--probably don't need to be overridden. // public int stmtctr=0; HashMap<String,Integer> premap; HashMap<Integer,Set<Integer> > preuse; HashMap<Integer,Set<Integer> > predef; public Arginfo visit(NodeList n, Arginfo argu) { Arginfo _ret=null; int _count=0; for ( Enumeration<Node> e = n.elements(); e.hasMoreElements(); ) { e.nextElement().accept(this,argu); _count++; } return _ret; } public Arginfo visit(NodeListOptional n, Arginfo argu) { if ( n.present() ) { Arginfo _ret=null; int _count=0; for ( Enumeration<Node> e = n.elements(); e.hasMoreElements(); ) { e.nextElement().accept(this,argu); _count++; } return _ret; } else return null; } public Arginfo visit(NodeOptional n, Arginfo argu) { if ( n.present() ){ Label temp=(Label) n.node; premap.put(temp.f0.tokenImage,stmtctr); return n.node.accept(this,argu); } else return null; } public Arginfo visit(NodeSequence n, Arginfo argu) { Arginfo _ret=null; int _count=0; for ( Enumeration<Node> e = n.elements(); e.hasMoreElements(); ) { e.nextElement().accept(this,argu); _count++; } return _ret; } public Arginfo visit(NodeToken n, Arginfo argu) { return null; } // // User-generated visitor methods below // /** * f0 -> "MAIN" * f1 -> StmtList() * f2 -> "END" * f3 -> ( Procedure() )* * f4 -> <EOF> */ public Arginfo visit(Goal n, Arginfo argu) { argu.labelno.put(n.f0.tokenImage,new Table()); premap=argu.labelno.get(n.f0.tokenImage).prefunc; preuse=argu.labelno.get(n.f0.tokenImage).use; predef=argu.labelno.get(n.f0.tokenImage).def; stmtctr=0; argu.labelno.get(n.f0.tokenImage).numargs=0; Arginfo _ret=null; n.f0.accept(this, argu); n.f1.accept(this, argu); n.f2.accept(this, argu); n.f3.accept(this, argu); n.f4.accept(this, argu); return argu; } /** * f0 -> ( ( Label() )? Stmt() )* */ public Arginfo visit(StmtList n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); return _ret; } /** * f0 -> Label() * f1 -> "[" * f2 -> IntegerLiteral() * f3 -> "]" * f4 -> StmtExp() */ public Arginfo visit(Procedure n, Arginfo argu) { Arginfo _ret=null; Arginfo temp=n.f0.accept(this, argu); argu.labelno.put(temp.labelname,new Table()); premap=argu.labelno.get(temp.labelname).prefunc; preuse=argu.labelno.get(temp.labelname).use; predef=argu.labelno.get(temp.labelname).def; stmtctr=0; argu.labelno.get(temp.labelname).numargs=Integer.valueOf(n.f2.f0.tokenImage); n.f1.accept(this, argu); n.f2.accept(this, argu); n.f3.accept(this, argu); n.f4.accept(this, argu); return _ret; } /** * f0 -> NoOpStmt() * | ErrorStmt() * | CJumpStmt() * | JumpStmt() * | HStoreStmt() * | HLoadStmt() * | MoveStmt() * | PrintStmt() */ public Arginfo visit(Stmt n, Arginfo argu) { Arginfo _ret=null; stmtctr++; preuse.put(stmtctr-1,new HashSet<Integer>()); predef.put(stmtctr-1,new HashSet<Integer>()); n.f0.accept(this, argu); return _ret; } /** * f0 -> "NOOP" */ public Arginfo visit(NoOpStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); return _ret; } /** * f0 -> "ERROR" */ public Arginfo visit(ErrorStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); return _ret; } /** * f0 -> "CJUMP" * f1 -> Temp() * f2 -> Label() */ public Arginfo visit(CJumpStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc=n.f1.accept(this, argu); n.f2.accept(this, argu); Set<Integer> temp=preuse.get(stmtctr-1); temp.add(tempacc.tempnumber); return _ret; } /** * f0 -> "JUMP" * f1 -> Label() */ public Arginfo visit(JumpStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); n.f1.accept(this, argu); return _ret; } /** * f0 -> "HSTORE" * f1 -> Temp() * f2 -> IntegerLiteral() * f3 -> Temp() */ public Arginfo visit(HStoreStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc1=n.f1.accept(this, argu); n.f2.accept(this, argu); Arginfo tempacc2=n.f3.accept(this, argu); Set<Integer> temp=preuse.get(stmtctr-1); temp.add(tempacc1.tempnumber); temp.add(tempacc2.tempnumber); return _ret; } /** * f0 -> "HLOAD" * f1 -> Temp() * f2 -> Temp() * f3 -> IntegerLiteral() */ public Arginfo visit(HLoadStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc1=n.f1.accept(this, argu); Arginfo tempacc2=n.f2.accept(this, argu); n.f3.accept(this, argu); Set<Integer> temp1=preuse.get(stmtctr-1); Set<Integer> temp2=predef.get(stmtctr-1); temp2.add(tempacc1.tempnumber); temp1.add(tempacc2.tempnumber); return _ret; } /** * f0 -> "MOVE" * f1 -> Temp() * f2 -> Exp() */ public Arginfo visit(MoveStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc1=n.f1.accept(this, argu); argu.temptemps.clear(); argu.exptemps.clear(); Arginfo tempacc2=n.f2.accept(this, argu); Set<Integer> temp1=preuse.get(stmtctr-1); Set<Integer> temp2=predef.get(stmtctr-1); temp2.add(tempacc1.tempnumber); //add tempacc2.exptemps to temp1 temp1.addAll(tempacc2.exptemps); return _ret; } /** * f0 -> "PRINT" * f1 -> SimpleExp() */ public Arginfo visit(PrintStmt n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc=n.f1.accept(this, argu); if(tempacc.tempnumber!=-1){ Set<Integer> temp1=preuse.get(stmtctr-1); temp1.add(tempacc.tempnumber); } return _ret; } /** * f0 -> Call() * | HAllocate() * | BinOp() * | SimpleExp() */ public Arginfo visit(Exp n, Arginfo argu) { Arginfo _ret=null; Arginfo ret=n.f0.accept(this, argu); return ret; } /** * f0 -> "BEGIN" * f1 -> StmtList() * f2 -> "RETURN" * f3 -> SimpleExp() * f4 -> "END" */ public Arginfo visit(StmtExp n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); n.f1.accept(this, argu); n.f2.accept(this, argu); stmtctr++; preuse.put(stmtctr-1,new HashSet<Integer>()); predef.put(stmtctr-1,new HashSet<Integer>()); Arginfo tempacc=n.f3.accept(this, argu); if(tempacc.tempnumber!=-1){ Set<Integer> temp1=preuse.get(stmtctr-1); temp1.add(tempacc.tempnumber); } n.f4.accept(this, argu); return _ret; } /** * f0 -> "CALL" * f1 -> SimpleExp() * f2 -> "(" * f3 -> ( Temp() )* * f4 -> ")" */ public Arginfo visit(Call n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc1=n.f1.accept(this, argu); n.f2.accept(this, argu); argu.isstar=1; n.f3.accept(this, argu); argu.isstar=0; n.f4.accept(this, argu); Arginfo ret=new Arginfo(); if(tempacc1.tempnumber!=-1){ ret.exptemps.add(tempacc1.tempnumber); } ret.exptemps.addAll(argu.temptemps); return ret; } /** * f0 -> "HALLOCATE" * f1 -> SimpleExp() */ public Arginfo visit(HAllocate n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc=n.f1.accept(this, argu); Arginfo ret=new Arginfo(); if(tempacc.tempnumber!=-1){ ret.exptemps.add(tempacc.tempnumber); } return ret; } /** * f0 -> Operator() * f1 -> Temp() * f2 -> SimpleExp() */ public Arginfo visit(BinOp n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo tempacc1=n.f1.accept(this, argu); Arginfo tempacc2=n.f2.accept(this, argu); Arginfo ret=new Arginfo(); ret.exptemps.add(tempacc1.tempnumber); if(tempacc2.tempnumber!=-1){ ret.exptemps.add(tempacc2.tempnumber); } return ret; } /** * f0 -> "LE" * | "NE" * | "PLUS" * | "MINUS" * | "TIMES" * | "DIV" */ public Arginfo visit(Operator n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); return _ret; } /** * f0 -> Temp() * | IntegerLiteral() * | Label() */ public Arginfo visit(SimpleExp n, Arginfo argu) { Arginfo _ret=null; Arginfo ret=n.f0.accept(this, argu); if(ret.tempnumber!=-1){ ret.exptemps.add(ret.tempnumber); } return ret; } /** * f0 -> "TEMP" * f1 -> IntegerLiteral() */ public Arginfo visit(Temp n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); n.f1.accept(this, argu); Arginfo ret=new Arginfo(); ret.tempnumber=Integer.valueOf(n.f1.f0.tokenImage); if(argu.isstar==1){ argu.temptemps.add(ret.tempnumber); } return ret; } /** * f0 -> <INTEGER_LITERAL> */ public Arginfo visit(IntegerLiteral n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo ret=new Arginfo(); return ret; } /** * f0 -> <IDENTIFIER> */ public Arginfo visit(Label n, Arginfo argu) { Arginfo _ret=null; n.f0.accept(this, argu); Arginfo ret=new Arginfo(); ret.labelname=n.f0.tokenImage; return ret; } }
package com.java.smart_garage.contracts.serviceContracts; import com.java.smart_garage.models.Currency; import java.util.List; public interface CurrencyMultiplierService { List<Currency> getAllCurrency(); double getCurrency(String value); }
package com.example.sonata.personaldiary; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity{ private SQLiteHelper db; private ListView listview; private final static String SharedPreferencesFileName="config"; //插入请求 private static final int INSERT_REQUESTCODE = 1; //插入结果 private static final int INSERT_RESULTCODE = 1; //修改请求 private static final int UPDATE_REQUESTCODE = 2; //修改结果 private static final int UPDATE_RESULTCODE = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = new SQLiteHelper(this,"diary.db", null, 1); listview = (ListView) findViewById(R.id.list); query(); registerForContextMenu(listview); //为每个项创建上下文菜单 listview.setOnItemClickListener(new OnItemClickListener() { //单击调用 @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { ListView list_View = (ListView)adapterView; HashMap<String,String> map = (HashMap<String,String>)list_View.getItemAtPosition(position); Diary diary = new Diary(); String str = String.valueOf(map.get("id")); int _id = Integer.parseInt(str); diary.setId(_id); diary.setTitle(map.get("title")); diary.setData(map.get("data")); diary.setText(map.get("text")); diary.setBitmap(map.get("bitmap")); Intent intent = new Intent(MainActivity.this,Main2Activity.class); intent.putExtra("update_diary",diary); startActivityForResult(intent,UPDATE_REQUESTCODE); } }); listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ListView list_View = (ListView)parent; HashMap<String,String> map = (HashMap<String,String>)list_View.getItemAtPosition(position); String str = String.valueOf(map.get("id")); final int _id = Integer.parseInt(str); final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("提示"); builder.setMessage("您确定要删除吗?"); builder.setPositiveButton("确定",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int i) { db.deleteDiary(_id); query(); showMessage("删除成功"); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.show(); return true; } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case INSERT_REQUESTCODE: if (resultCode == INSERT_RESULTCODE) { // 插入请求 if (data != null) { //接收对象 Diary diary = (Diary) data.getSerializableExtra("insert_diary"); db.addDiary(diary); query(); showMessage("添加成功"); } else { showMessage("添加失败"); } } case UPDATE_REQUESTCODE: if (resultCode == UPDATE_RESULTCODE) if (data != null) { Diary diary = (Diary) data.getSerializableExtra("update_diary"); int id = diary.getId(); Log.e("mytag", String.valueOf(id)); if(db.queryDiaryById(diary.getId())!=null) { db.updateDiary(diary); query(); showMessage("修改成功"); } else { showMessage("修改失败"); } } break; } } protected void query() { List<Map<String,Object>> items = db.queryAllDiary(); //查询所有的Diary SimpleAdapter adapter=new SimpleAdapter(this,items,R.layout.activity_list_item,new String[]{"title","data","text"},new int[]{R.id.Title,R.id.Data,R.id.Text}); listview.setAdapter(adapter); } protected void querySearch(String title) { List<Map<String,Object>> items = db.queryDiaryByTitle(title); //查询所有的Diary SimpleAdapter adapter=new SimpleAdapter(this,items,R.layout.activity_list_item,new String[]{"title","data","text"},new int[]{R.id.Title,R.id.Data,R.id.Text}); listview.setAdapter(adapter); } private void showMessage(String msg) { Toast.makeText(this,msg,Toast.LENGTH_LONG).show(); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main,menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.addNew: final Intent intent = new Intent(this,Main2Activity.class); startActivityForResult(intent,INSERT_REQUESTCODE); break; case R.id.search: final View view = getLayoutInflater().inflate(R.layout.activity_search,null); final AlertDialog.Builder dialog2 = new AlertDialog.Builder(MainActivity.this); dialog2.setTitle("搜索"); dialog2.setView(view); dialog2.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { EditText search = (EditText) view.findViewById(R.id.search); String title = search.getText().toString(); querySearch(title); showMessage("查询成功"); } }); dialog2.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog2.show(); break; default: } return true; } }
package www.movieapp.Constant; /** * Created by amy on 10/24/2017. */ public class Constant { public static String END_POINT="http://api.themoviedb.org/3/"; public static String POSTER_PATH="http://image.tmdb.org/t/p/w185"; public static String SORT_BY_TOP_RATED="movie/top_rated"; public static String SORT_BY_POPULAR="movie/popular"; public static String API_KEY="3da1e7a1d933168c0b6156c502c05557"; public static String PARAM_QUERY="api_key"; public static String MOVIE_TITLE="movieTitle"; public static String MOVIE_SYNOPSIS="movieSynopsis"; public static String MOVIE_RATING="movieRating"; public static String MOVIE_IMAGE_POSTER="movieImagePoster"; public static String MOVIE_ReleaseDate="movieReleaseDate"; public static String MOVIE_ID="movieID"; public static String YOUTUBE_API="AIzaSyChxPW6ZSUK596gtPzdFGhkJ_BNkOFgcGM"; }
package com.sxf.service; import com.sxf.entity.Manager; public interface ManagerService { Manager find(String username); void add(String username, String number); void del(Integer mid); void edit(Integer mid, String username, String password); }
package q0581; import java.util.Arrays; import java.util.Stack; public class ShortestUnsortedContinuousSubarray { /** 给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。 你找到的子数组应是最短的,请输出它的长度。 示例 1: 输入: [2, 6, 4, 8, 10, 9, 15] 输出: 5 解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。 */ public static int findUnsortedSubarray1(int[] nums) { Stack<Integer> stack = new Stack<Integer>(); int left = nums.length; int right = 0; for(int i=0; i<nums.length; i++){ while(!stack.isEmpty() && nums[stack.peek()]>nums[i]){ left = Math.min(left, stack.pop()); } stack.push(i); } stack.clear(); for(int i=nums.length-1; i>=0; i--){ while(!stack.isEmpty() && nums[stack.peek()]<nums[i]){ right = Math.max(right, stack.pop()); } stack.push(i); } if(right-left>0){ return right-left+1; }else{ return 0; } } public static int findUnsortedSubarray2(int[] nums) { int[] snums = nums.clone(); Arrays.sort(snums); int start = snums.length, end = 0; for (int i = 0; i < snums.length; i++) { if (snums[i] != nums[i]) { start = Math.min(start, i); end = Math.max(end, i); } } return end - start >= 0 ? end - start + 1 : 0; } public static void main(String[] args) { int[] nums = {2, 6, 4, 8, 10, 9, 15}; int res = findUnsortedSubarray1(nums); System.out.println(res); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.representation; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.io.InputStream; /** * * @author reto */ @RunWith(JUnitPlatform.class) public class ParserTest { private static boolean providerAInvoked; private static boolean providerBInvoked; private ParsingProvider parsingProviderA = new ParsingProviderA(); private ParsingProvider parsingProviderB = new ParsingProviderB(); @Test public void registerOneProvider() { Parser parser = new Parser(null); parser.bindParsingProvider(parsingProviderA); providerAInvoked = false; parser.parse(null, "application/x-fantasy2+rdf"); Assertions.assertTrue(providerAInvoked); } @Test public void registerAndUnregisterSecond() { Parser parser = new Parser(null); parser.bindParsingProvider(parsingProviderA); parser.bindParsingProvider(parsingProviderB); providerAInvoked = false; providerBInvoked = false; parser.parse(null, "application/x-fantasy2+rdf"); Assertions.assertFalse(providerAInvoked); Assertions.assertTrue(providerBInvoked); providerAInvoked = false; providerBInvoked = false; parser.parse(null, "application/x-fantasy1+rdf"); Assertions.assertTrue(providerAInvoked); Assertions.assertFalse(providerBInvoked); parser.unbindParsingProvider(parsingProviderB); providerAInvoked = false; providerBInvoked = false; parser.parse(null, "application/x-fantasy2+rdf"); Assertions.assertTrue(providerAInvoked); Assertions.assertFalse(providerBInvoked); } @SupportedFormat({"application/x-fantasy1+rdf", "application/x-fantasy2+rdf"}) static class ParsingProviderA implements ParsingProvider { @Override public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { providerAInvoked = true; } }; @SupportedFormat("application/x-fantasy2+rdf") static class ParsingProviderB implements ParsingProvider { @Override public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { providerBInvoked = true; } }; }
package com.example.radio.Model; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("jsonschema2pojo") public class TemplateParams { @SerializedName("user_name") @Expose private String userName; @SerializedName("user_email") @Expose private String userEmail; @SerializedName("user_subject") @Expose private String userSubject; @SerializedName("to_email") @Expose private String toEmail; @SerializedName("user_message") @Expose private String userMessage; @SerializedName("to_name") @Expose private String toName; public TemplateParams(String userName, String userEmail, String userSubject, String toEmail, String userMessage, String toName) { this.userName = userName; this.userEmail = userEmail; this.userSubject = userSubject; this.toEmail = toEmail; this.userMessage = userMessage; this.toName = toName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserSubject() { return userSubject; } public void setUserSubject(String userSubject) { this.userSubject = userSubject; } public String getToEmail() { return toEmail; } public void setToEmail(String toEmail) { this.toEmail = toEmail; } public String getUserMessage() { return userMessage; } public void setUserMessage(String userMessage) { this.userMessage = userMessage; } public String getToName() { return toName; } public void setToName(String toName) { this.toName = toName; } }
package com.elvarg.world.entity.combat.magic; import java.util.Iterator; import java.util.Optional; import com.elvarg.world.World; import com.elvarg.world.entity.combat.CombatFactory; import com.elvarg.world.entity.combat.hit.PendingHit; import com.elvarg.world.entity.combat.method.impl.MagicCombatMethod; import com.elvarg.world.entity.impl.Character; import com.elvarg.world.entity.impl.npc.NPC; import com.elvarg.world.entity.impl.player.Player; import com.elvarg.world.model.Item; import com.elvarg.world.model.Locations.Location; import com.elvarg.world.model.MagicSpellbook; /** * A {@link CombatSpell} implementation that is primarily used for spells that * are a part of the ancients spellbook. * * @author lare96 */ public abstract class CombatAncientSpell extends CombatSpell { @Override public MagicSpellbook getSpellbook() { return MagicSpellbook.ANCIENT; } @Override public void finishCast(Character cast, Character castOn, boolean accurate, int damage) { // The spell wasn't accurate, so do nothing. if (!accurate || damage <= 0) { return; } // Do the spell effect here. spellEffect(cast, castOn, damage); // The spell doesn't support multiple targets or we aren't in a // multicombat zone, so do nothing. if (spellRadius() == 0/* || !Locations.Location.inMulti(castOn)*/) { return; } // We passed the checks, so now we do multiple target stuff. Iterator<? extends Character> it = null; if (cast.isPlayer() && castOn.isPlayer()) { it = ((Player) cast).getLocalPlayers().iterator(); } else if (cast.isPlayer() && castOn.isNpc()) { it = ((Player) cast).getLocalNpcs().iterator(); } else if (cast.isNpc() && castOn.isNpc()) { it = World.getNpcs().iterator(); } else if (cast.isNpc() && castOn.isPlayer()) { it = World.getPlayers().iterator(); } for (Iterator<? extends Character> $it = it; $it.hasNext();) { Character next = $it.next(); if (next == null) { continue; } if(next.isNpc()) { NPC n = (NPC)next; if(!n.getDefinition().isAttackable()) { continue; } } else { Player p = (Player)next; if(p.getLocation() != Location.WILDERNESS || !Location.inMulti(p)) { continue; } } if (next.getPosition().isWithinDistance(castOn.getPosition(), spellRadius()) && !next.equals(cast) && !next.equals(castOn) && next.getHitpoints() > 0 && next.getHitpoints() > 0) { PendingHit qH = new PendingHit(cast, next, CombatFactory.MAGIC_COMBAT, true, 0).setHandleAfterHitEffects(false); if(qH.isAccurate()) { //Successful hit, send graphics and do spell effects. endGraphic().ifPresent(next::performGraphic); spellEffect(cast, next, qH.getTotalDamage()); } else { //Unsuccessful hit. Send splash graphics for the spell because it wasn't accurate next.performGraphic(MagicCombatMethod.SPLASH_GRAPHIC); } CombatFactory.addPendingHit(qH); } } } @Override public Optional<Item[]> equipmentRequired(Player player) { // Ancient spells never require any equipment, although the method can // still be overridden if by some chance a spell does. return Optional.empty(); } /** * The effect this spell has on the target. * * @param cast * the entity casting this spell. * @param castOn * the person being hit by this spell. * @param damage * the damage inflicted. */ public abstract void spellEffect(Character cast, Character castOn, int damage); /** * The radius of this spell, only comes in effect when the victim is hit in * a multicombat area. * * @return how far from the target this spell can hit when targeting * multiple entities. */ public abstract int spellRadius(); }
package com.cpe.mysql.webblog.controller; import com.cpe.mysql.webblog.entity.Role; import com.cpe.mysql.webblog.model.RoleModel; import com.cpe.mysql.webblog.repository.RoleRepository; import com.cpe.mysql.webblog.services.RoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin(origins = "http://localhost:8080") @RestController @RequestMapping("/webblog/role/") public class RoleController { @Autowired private RoleRepository roleRepository; private RoleService roleService; public RoleController(RoleService roleService) { this.roleService = roleService; } @GetMapping("details/all") public List<Role> getAllRole() { return roleRepository.findAll(); } @PostMapping("create") public ResponseEntity<Object> addRole(@RequestBody RoleModel role) { return roleService.addRole(role); } @DeleteMapping("delete/{id}") public ResponseEntity<Object> deleteRole(@PathVariable Long id) { return roleService.deleteRole(id); } }
package smart.entity; import jakarta.persistence.*; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; @DynamicInsert @DynamicUpdate @Entity @Table(name = "t_admin_user") public class AdminUserEntity extends BaseEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private Long userId; private Long roleId; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } }
package com.javarush.task.task18.task1822; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.Buffer; import java.util.Arrays; /* Поиск данных внутри файла */ public class Solution { public static void main(String[] args) { try (BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); BufferedReader file = new BufferedReader(new FileReader(console.readLine()))) { while (file.ready()) { String[] data = file.readLine().split(" "); if (data[0].equals(args[0])) { Arrays.stream(data).forEach(x -> System.out.print(x + " ")); break; } } } catch (IOException e) { e.printStackTrace(); } } }
package com.kuali.sim; import java.util.ArrayList; import java.util.List; public class Elevator { /* * identity of this elevator */ private String name; private int idx; /* * Occupied, UnOccupied, Maintenance */ private Service.Status status; /* * Opended, Closed */ private Service.DoorStatus doorStatus; /* * current floor this elevator is * index pointed to floors */ private Floor currentFloor; /* * current location of this evevator (from 0 to (floorNum-1) * Service.MOVING_TIME * * 0 - first floor * 0+Service.MOVING_TIME - second floor * 0+2*Service.MOVING_TIME - third floor */ private int location = 0; /* * Floor this elevator associated with */ private List<Floor> floors; /* * request queue */ private List<Request> requests = new ArrayList<Request>(); /* * trip count for this elevator */ private int trip = 0; /** * Elevator cosntructor * @param name * @param floors */ public Elevator(int idx, List<Floor> floors) { this.idx = idx; this.name = String.valueOf(idx); this.floors = floors; this.init(); } /** * initial state of this elevator */ public void init() { this.requests.clear(); this.trip = 0; this.currentFloor = this.floors.get(0); this.status = Service.Status.UNOCCUPIED; this.doorStatus = Service.DoorStatus.CLOSED; } /** * Add a new request to this elevator and increment trip by 1 * @param request */ public void addRequest(Request request) { /* * in maintian mode, no new request accepted */ if (this.status == Service.Status.MAINTAINED) { return; } this.requests.add(request); this.trip++; } public void removeRequest(Request request) { if (!this.requests.isEmpty()) { this.requests.remove(request); } } public void goUp() { this.location++; } public void goDown() { this.location--; } public Floor atWhichFloor() { for (Floor floor : this.floors) { if (floor.isAtThisFloor(this.location)) { return floor; } } return null; } public List<Request> getRequests() { return this.requests; } public boolean isIdle() { return this.requests.size() == 0; } public boolean isMaintained() { return status == Service.Status.MAINTAINED; } public int getIdx() { return this.idx; } public String getName() { return this.name; } public Service.Status getStatus() { return this.status; } public void setStatus(Service.Status status) { this.status = status; /* * if the status is Service.Status.MAINTAINED, initialize this elevator */ /*if (this.status == Service.Status.MAINTAINED) { this.init(); this.doorStatus = Service.DoorStatus.OPENED; }*/ } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Elevator ").append(this.name).append(" - "); sb.append("Floor ").append(this.currentFloor.getName()).append(", "); sb.append("Door ").append(this.doorStatus==Service.DoorStatus.CLOSED ? "CLOSED, " : "OPENED, "); String status = "OCCUPIED, "; if (this.status == Service.Status.UNOCCUPIED) { status = "UNOCCUPIED, "; } else if (this.status == Service.Status.MAINTAINED) { status = "MAINTANIED, "; } sb.append(status); sb.append("Trip ").append(this.trip); return sb.toString(); } public Service.DoorStatus getDoorStatus() { return doorStatus; } public void setDoorStatus(Service.DoorStatus doorStatus) { this.doorStatus = doorStatus; } public Floor getCurrentFloor() { return this.currentFloor; } public void setCurrentFloor(Floor currentFloor) { this.currentFloor = currentFloor; } public List<Floor> getFloors() { return this.floors; } public int getTrip() { return trip; } }
package pl.polsl.wkiro.recognizer.logic; import com.openalpr.jni.Alpr; import com.openalpr.jni.AlprPlateResult; import com.openalpr.jni.AlprResults; import com.openalpr.jni.exceptions.ProcessingException; import com.openalpr.jni.exceptions.TaskInterruptedException; import pl.polsl.wkiro.recognizer.dto.ProcessingResult; import pl.polsl.wkiro.recognizer.dto.Settings; import pl.polsl.wkiro.recognizer.utils.Dictionary; import pl.polsl.wkiro.recognizer.utils.DrawUtils; import pl.polsl.wkiro.recognizer.utils.Logger; import pl.polsl.wkiro.recognizer.utils.TaskUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import static pl.polsl.wkiro.recognizer.utils.Constants.Paths.OPENALPR_CONFIG; import static pl.polsl.wkiro.recognizer.utils.Constants.Paths.OPENALPR_RUNTIME_DIR; public class RecognitionProcessor { private static final Logger log = new Logger(RecognitionProcessor.class); public ProcessingResult recognize(BufferedImage image, Settings settings, long timeMicroSeconds, ProcessingResult processingResult, boolean saveFrame) throws ProcessingException, TaskInterruptedException { TaskUtils.checkTaskInterrupted(true); if (processingResult == null) { processingResult = new ProcessingResult(); } if (image == null || image.getGraphics() == null) { String msg = "No valid image provided to recognize"; log.error("recognize", msg); throw new ProcessingException(msg); } String key = formatTime(timeMicroSeconds); String path = settings.getOutputDirectoryPath() + "/" + key + ".png"; key = key.replace("_", ":"); Alpr alprProcessor = null; AlprResults results = null; try { byte[] imageByteArray = convertToByteArray(image); log.debug("recognize", "Process start, image size: " + imageByteArray.length); alprProcessor = preconfigure(settings); results = alprProcessor.recognize(imageByteArray); Set<String> recognizedPlates = new HashSet<>(); for (AlprPlateResult result : results.getPlates()) { TaskUtils.checkTaskInterrupted(true); recognizedPlates.add(result.getBestPlate().getCharacters()); DrawUtils.drawPlates(settings.isSelectFoundPlates(), settings.isDrawRecognitionOnPlate(), image, result.getPlatePoints(), result.getBestPlate().getCharacters()); } if (results == null || results.getPlates().isEmpty()) { return null; } if(saveFrame) { ImageIO.write(image, "png", new File(path)); log.info("recognize", "Frame saved to: " + path + "\n" + "Plates recognized: " + Arrays.toString(recognizedPlates.toArray())); } else { path = ""; } if (processingResult.getFrameNames() == null) { processingResult.setFrameNames(new ArrayList<>()); } processingResult.getFrameNames().add(key); if (processingResult.getFrames() == null) { processingResult.setFrames(new LinkedHashMap<>()); } processingResult.getFrames().put(key, new ProcessingResult.ProcessedFrame(results.getPlates(), key, path, results.getTotalProcessingTimeMs())); } catch (Throwable e) { log.error("recognize", "Error while recognizing plates: " + e.getMessage()); throw new ProcessingException(e.getMessage(), e); } finally { if (alprProcessor != null) { alprProcessor.unload(); } log.debug("recognize", "Unloaded ALPR processor"); } log.debug("recognize", "Processing result: " + results.getPlates()); return processingResult; } private Alpr preconfigure(Settings settings) { Alpr alpr = new Alpr(settings.getPlateRegion(), OPENALPR_CONFIG, OPENALPR_RUNTIME_DIR); alpr.setTopN(settings.getTopMatchResult()); if (!Dictionary.NOT_SELECTED.equals(settings.getSpecificRegion())) { alpr.setDefaultRegion(settings.getSpecificRegion()); } else { alpr.setDefaultRegion(""); } return alpr; } private String formatTime(long timeMicro) { final int MILISECOND_FACTOR = 1000; final String TIME_FORMAT = "mm_ss_SSS"; Date date = new Date(timeMicro / MILISECOND_FACTOR); DateFormat formatter = new SimpleDateFormat(TIME_FORMAT); String dateFormatted = formatter.format(date); long hours = (timeMicro / (MILISECOND_FACTOR * MILISECOND_FACTOR)) / 3600; dateFormatted = String.format("%02d_%s", hours, dateFormatted); return dateFormatted; } private byte[] convertToByteArray(BufferedImage image) throws IOException { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); baos.flush(); return baos.toByteArray(); } finally { baos.close(); } } }
package br.com.nozinho.ejb.service.impl; import javax.ejb.Stateless; import br.com.nozinho.ejb.service.RegionalService; import br.com.nozinho.model.Regional; @Stateless public class RegionalServiceImpl extends GenericServiceImpl<Regional, Long> implements RegionalService { }
package boundary; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.sql.SQLException; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.plaf.metal.MetalBorders.TableHeaderBorder; import javax.swing.table.DefaultTableModel; import com.sun.javafx.fxml.BeanAdapter; import java.awt.Toolkit; import controller.AgendaController; import sun.awt.image.ToolkitImage; public class AgendaBoundary implements ActionListener, MouseListener{ private AgendaController control; private JFrame janela = new JFrame("Consulta de Contatos - Camera Press"); private JPanel panelPrincipal = new JPanel(new BorderLayout()); private JTable tabelaContatos ; private JTextField txtPesquisar; private JButton btnVisualizar; private JButton btnPesquisar; private int id; public AgendaBoundary() { //JLabel logo = new JLabel(); janela.setIconImage(Toolkit.getDefaultToolkit().getImage(AgendaBoundary.class.getResource("/resources/agenda.png"))); JLabel titulo = new JLabel("Agenda de Contatos", SwingConstants.CENTER); titulo.setIcon(new ImageIcon(AgendaBoundary.class.getResource("/resources/logocp.jpg"))); titulo.setHorizontalTextPosition( SwingConstants.CENTER ); titulo.setFont(new Font("Palatino Linotype", Font.BOLD, 30)); titulo.setVerticalTextPosition(SwingConstants.BOTTOM); panelPrincipal.setBackground(Color.WHITE); panelPrincipal.add(titulo, BorderLayout.NORTH); panelPrincipal.add(centroTabela(), BorderLayout.CENTER); panelPrincipal.add(rodape(), BorderLayout.SOUTH); janela.setVisible(true); janela.setSize(900, 600); janela.setContentPane(panelPrincipal); janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public JComponent centroTabela (){ JPanel panelCentro = new JPanel(new BorderLayout()); panelCentro.setBackground(Color.WHITE); JScrollPane ScroolPaneContatos = new JScrollPane(); panelCentro.add(ScroolPaneContatos); tabelaContatos= new JTable(); DefaultTableModel modelo = new DefaultTableModel(new Object[][]{},new String[] { "ID","Empresa", "Nome / Contato", "Telefone", "Celular" } ); ScroolPaneContatos.setViewportView(tabelaContatos); tabelaContatos.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "ID","Empresa", "Nome / Contato", "Telefone", "Celular" }) { /** * */ private static final long serialVersionUID = 1L; boolean[] canEdit = new boolean[] { false, false, false, false, false }; @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } } ); tabelaContatos.getColumnModel().getColumn(0).setPreferredWidth(40); tabelaContatos.getColumnModel().getColumn(1).setPreferredWidth(236); tabelaContatos.getColumnModel().getColumn(2).setPreferredWidth(196); tabelaContatos.getColumnModel().getColumn(3).setPreferredWidth(250); tabelaContatos.getColumnModel().getColumn(4).setPreferredWidth(150); tabelaContatos.setFont(new Font("Tahoma", Font.PLAIN, 12)); tabelaContatos.revalidate(); tabelaContatos.setBorder(null); tabelaContatos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tabelaContatos.addMouseListener(this); control = new AgendaController(tabelaContatos); control.listarContatos(); return panelCentro; } public JComponent rodape(){ JPanel panelRodape = new JPanel(); txtPesquisar = new JTextField(30); txtPesquisar.addActionListener(this); panelRodape.add(txtPesquisar); btnPesquisar = new JButton("Pesquisar"); panelRodape.add(btnPesquisar); btnPesquisar.addActionListener(this); btnVisualizar = new JButton("Visualizar contato"); panelRodape.add(btnVisualizar); btnVisualizar.setEnabled(false); btnVisualizar.addActionListener(this); panelRodape.setBackground(Color.LIGHT_GRAY); return panelRodape; } public static void main(String[] args) { new AgendaBoundary(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == btnPesquisar || e.getSource() == txtPesquisar){ control.ConsultaNome(txtPesquisar.getText()); }else if (e.getSource() == btnVisualizar){ ContatoDados cDados = new ContatoDados(control.VisualizaContato(id)); tabelaContatos.clearSelection(); btnVisualizar.setEnabled(false); } } @Override public void mouseClicked(MouseEvent arg0) { if (arg0.getSource() == tabelaContatos) { int linha = tabelaContatos.getSelectedRow(); btnVisualizar.setEnabled(true); id = (int) tabelaContatos.getValueAt(linha, 0); } if(arg0.getClickCount() == 2) { ContatoDados cDados = new ContatoDados(control.VisualizaContato(id)); tabelaContatos.clearSelection(); btnVisualizar.setEnabled(false); } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }
package com.FileL.打印流; /* * printStream * printWriter * println()调用的就是打印流的各种重载的函数*/ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; public class Demo { //1.PrintStream public static void main(String[] args) throws FileNotFoundException { InputStream inputStream = new FileInputStream("D:\\test\\test\\zhang.txt"); System.setIn(inputStream); } //2.PirntWriter }