text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void editLink(String classOneName, String classTwoName){
for (int i=0;i<components.size();i++){
if (components.get(i).name.equals(classOneName)){
for (int j = 0; j<components.get(i).links.size(); j++){
if (components.get(i).links.get(j).classTwoName.equals(classTwoName)){
//blank icon because i can't figure out how to not have one
ImageIcon icon = new ImageIcon("");
//set options for the dialog
Object[] possibilities = {"change cardinality", "delete", "change class two"};
//present dialog and save answer to s
String s = (String)JOptionPane.showInputDialog(diagramPanel,
"What would you like to do to the link?",
"Modify link..",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"delete");
//Asses the value returned and call necessarry function
if (s=="delete"){
components.get(i).links.remove(j);
JOptionPane.showMessageDialog(this.diagramPanel, "Success!\nLink removed!");
this.diagramPanel.repaint();
return;
} else if (s=="change cardinality"){
String newCardinality = JOptionPane.showInputDialog("Enter a new cardinality:\nEg. 1..*");
components.get(i).links.get(j).quantifier = newCardinality;
this.diagramPanel.repaint();
return;
} else if (s=="change class two"){
String newClassTwoName = JOptionPane.showInputDialog("Enter new Class Two Name:\nEg. Cheese");
components.get(i).links.get(j).classTwoName = newClassTwoName;
this.diagramPanel.repaint();
return;
} else {
System.out.println("uh oh!");
return;
}
}
}
}
}
} | 7 |
@RequestMapping("multiDel")
public String multiDel(String[] ids,String flag){
if(ids ==null ||ids.equals("")){
if(flag =="listAll" || flag.trim().equals("listAll")){
return "forward:/rescue/getAllMess";
}else{
//request.setAttribute("status",flag);
return "forward:/rescue/getStatusMess?status="+ flag;
}
}else{
rescueCarService.multiDel(ids);
if(flag =="listAll" || flag.trim().equals("listAll")){
return "forward:/rescue/getAllMess";
}else{
//request.setAttribute("status",flag);
return "forward:/rescue/getStatusMess?status="+ flag;
}
}
} | 6 |
public static List<Object[]> generateBatchQueryArguments(Object[] args, BatchDefinition batchDefinition) {
// 获取批量SQL/Shell的批数,即@BatchParam对应的几个数组的最小length
int batchSize = -1;
Integer[] batchParamIndexes = batchDefinition.getBatchParamIndexes();
for (int i = 0; i < batchParamIndexes.length; i++) {
int index = batchParamIndexes[i];
if (batchSize == -1) {
batchSize = ArrayHelper.getArrayOrListLength(args[index]);
} else {
batchSize = Math.min(batchSize, ArrayHelper.getArrayOrListLength(args[index]));
}
}
Method[] getterMethods = batchDefinition.getGetterMethods();
Integer[] parameterIndexes = batchDefinition.getParameterIndexes();
List<Object[]> paramArrays = new ArrayList<Object[]>(batchSize);
List<String> parameterNames = batchDefinition.getParsedExpression().getParameterNames();
// 每次克隆一组调用参数,然后用批量参数中这个批次中的批量参数值替换这个批量参数
for (int i = 0; i < batchSize; i++) {
Object[] cloneArgs = ArrayHelper.clone(args);
for (int j = 0; j < batchParamIndexes.length; j++) {
int index = batchParamIndexes[j];
cloneArgs[index] = fetchArrayValue(cloneArgs[index], i);
}
Object[] paramArray = fetchValues(getterMethods, parameterIndexes, cloneArgs, parameterNames);
paramArrays.add(paramArray);
}
return paramArrays;
} | 4 |
public void save(String fileName) {
try {
OutputStream file = new FileOutputStream(fileName);
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject(map.getData());
output.close();
buffer.close();
file.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 2 |
public static String findLongest(String input) {
//maintain this to record
boolean [][]isPalindrome = new boolean[input.length()][input.length()];
int maxLength = Integer.MIN_VALUE;
int start = -1;
//first find single length palindromes
for( int i = 0; i< input.length(); i++) {
isPalindrome[i][i] = true;
maxLength = 1;
start = i;
}
//Double length palindromes
for( int i = 1; i< input.length(); i++) {
if(input.charAt(i) == input.charAt(i-1)) {
isPalindrome[i-1][i] = true;
maxLength = 2;
start = i-1;
}
}
// for lengths 3 and more
for( int l = 3; l<= input.length(); l++) {
for( int i = 0; i<input.length()-l+1; i++) {
int j = l+i-1;
// check if first and last characters match or not and string by plucking both of them is also palindrome
if(input.charAt(i) == input.charAt(j) && isPalindrome[i+1][j-1]) {
// mark is palindrome to true
isPalindrome[i][j] = true;
// update maxLength if required
if(l > maxLength){
maxLength = l;
start = i;
}
}
}
}
return input.substring(start, start+maxLength);
} | 8 |
public boolean collectTypeInfo() {
typeInfo.clear();
for (int i = 0; i < moduleNum; i++) {
int rowPoint = 0;
while (true) {
String line = "";
for (int j = 0; j < 5; j++) {
String cell = null;
if (typeTable[i].getValueAt(rowPoint, j) != null) {
cell = (String) typeTable[i].getValueAt(rowPoint, j);
line += cell + ";";
} else {
line = null;
break;
}
}
if (line != null) {
System.out.println("Get Type Info:"
+ new String(moduleInfo.get(i)) + line);
typeInfo.add(new String(moduleInfo.get(i)) + line);
} else {
break;
}
rowPoint++;
}
}
return true;
} | 5 |
public void run() {
try {
while (!isInterrupted()) {
int msg = is.read();
if(msg == -1) return;
switch (msg) {
case OpCodes.DISCONNECT:
return;
case OpCodes.SET_IDLE: {
monitor.setMovieMode(false);
break;
}
case OpCodes.SET_MOVIE: {
monitor.setMovieMode(true);
break;
}
case OpCodes.SET_AUTO_ON: {
monitor.setAuto(true);
break;
}
case OpCodes.SET_AUTO_OFF: {
monitor.setAuto(false);
break;
}
default: {
System.out.println("Unrecognized operation code: " + msg);
}
}
}
} catch (IOException e) {
return;
}
} | 8 |
private void handleMessage(RoomMessage room_message)
{
if (!changing_room )
{
if ( bot_data.enablePlusPlus )
{
//TODO maybe I can make a special type of command that can get all text instead of matching on command?
//can use to run standup and plusplusbot?
handlePlusPlusBot(room_message);
}
//check if it is an early standup request
handleEarlyStandup(room_message);
if ( room_message.message.startsWith("/standup") )
{
//handle bot commands
RoomBotCommands.handleCommand(room_message.message, hippy_bot, this, bot_data);
}
else if ( current_standup_user != null && room_message.from.equals(current_standup_user.getName()))
{
current_standup_user_messages.add(room_message.message);
//TODO ID LIKE TO MOVE THIS STUFF OUT OF HERE?
//handle speaking during standup, current user
did_user_say_anything = true;
if ( bot_data.speaking_trigger_words != null )
{
//check if user used trigger word
Matcher tmatcher = speakingTrigger.matcher(room_message.message);
if ( tmatcher.find() )
{
if ( !did_user_speak )
{
did_user_speak = true;
num_spoke_on_turn++;
}
//super.sendMessage(from + " spoke on his turn");
}
}
}
else if ( current_standup_user != null )
{
//handle speaking during standup, other user
num_spoke_out_of_turn++;
}
}
} | 9 |
public static void graphDepthFirstTraversal(String[][] edgeList){
if(edgeList.length == 0){
return;
}else{
ArrayList<String> discovered = new ArrayList<String>();
timeStamp = 0;
for(String[] edge : edgeList){
String node1 = edge[0];
String node2 = edge[1];
if(!discovered.contains(node1)){
recursiveDFTraversal(node1, edgeList, discovered);
}else if(!discovered.contains(node2)){
recursiveDFTraversal(node2, edgeList, discovered);
}
}
}
} | 4 |
public void reducePlayerHealth(String userName){
try {
cs = con.prepareCall("{call reducePlayerHealth(?)}");
cs.setString(1, userName);
cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
public double[] nextDoubles(int n) throws IOException {
double[] res = new double[n];
for (int i = 0; i < n; ++i) {
res[i] = nextDouble();
}
return res;
} | 1 |
public Abrir() {
initComponents();
} | 0 |
public void placePieceOnBoard(Position myFreeposition, List<Position> freePositions) {
freePositions.remove(myFreeposition);
int x = myFreeposition.getX();
int y = myFreeposition.getY();
Position tmp = new Position(x, y);
for (int xx = x, yy = y; xx < did.getN() && yy < did.getM();) {
tmp.setX(xx++);
tmp.setY(yy++);
freePositions.remove(tmp);
freePositions.remove(tmp);
}
for (int xx = x, yy = y; xx > 0 && yy > 0;) {
tmp.setX(--xx);
tmp.setY(--yy);
freePositions.remove(tmp);
freePositions.remove(tmp);
}
for (int xx = x, yy = y + 1; xx < did.getN() && yy > 0;) {
tmp.setX(xx++);
tmp.setY(--yy);
freePositions.remove(tmp);
freePositions.remove(tmp);
}
for (int xx = x + 1, yy = y; xx > 0 && yy < did.getM();) {
tmp.setX(--xx);
tmp.setY(yy++);
freePositions.remove(tmp);
freePositions.remove(tmp);
}
} | 8 |
@SuppressWarnings("unchecked")
public Map<String, Object> readDaily(String file) {
Map<String, Object> result = new LinkedHashMap<String, Object>();
try{
// Open the file
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String sDate = "";
String strLine;
int soNgay = 0;
int soGiai = 0;
int soGiaiPhu = 0;
int n = 0;
String oldDB = "";
while ((strLine = br.readLine().trim()) != null) {
//
if(strLine.trim().isEmpty()) continue;
Map<String, String> cac_giai_cua_ngay = new LinkedHashMap<String, String>();
//Keep the date
if(strLine.startsWith("===")){
System.out.println("Start of day !!!!!!!!!!!!!!!!!!!!!");
//clean "="
strLine = strLine.replaceAll("=", "");
//clean "Ngay"
strLine = strLine.replaceAll("Ngay", "");
sDate = strLine.trim();
result.put(sDate, cac_giai_cua_ngay);
soNgay++;
soGiai=1;
soGiaiPhu=1;
n=1;
continue;
} else {
cac_giai_cua_ngay = (Map<String, String>) result.get(sDate);
}
//restric so ngay
if(soNgay > 30){
break;
}
String ten_giai = getTenGiai(soGiai, soGiaiPhu).trim();
//System.out.println("ten_giai========= '"+ten_giai);
String giai = strLine.trim();
//System.out.println("giai=========xxxx '"+giai);
cac_giai_cua_ngay.put(ten_giai, giai);
result.put(sDate, cac_giai_cua_ngay);
//
if(ten_giai.equalsIgnoreCase(DB_GIAI)) {
//
if(soNgay > 1){
DB.add(giai);
}
}
//
if(isChangeGiai(n)){
soGiai++;
soGiaiPhu=0;
}
if(n >= 27) {
//reset vars
System.out.println("so giai is "+n);
}
//
n++;
soGiaiPhu++;
}
}catch (Exception e){
System.err.println("readData: " + e.getMessage());
}
return result;
} | 9 |
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Terminate Scouting"))
{
//Terminate Scouting Button was Pressed
//Check if Good Quit or not
if(MainGUI.numConnected == numFinished)
{
//Nullify Communication Threads
for(int k = 0;k<=5;k++)
{
MainThread.connectionThreads[k] = null;
}
//Close Window
closeWindow();
//Shut Down System
System.exit(0);
}
else
{
//Alert User To Problems Before Termination
aG = new AlertGUI(new JPanel(null));
aG.setVisible(true);
}
}
else if(e.getActionCommand().equals("Yes"))
{
//User want to Terminate Early
//Nullify Connection Threads
for(int k = 0;k<=5;k++)
{
MainThread.connectionThreads[k] = null;
}
//Close Window
closeWindow();
//Shut Down System
System.exit(0);
}
} | 5 |
@Override
public Set<String> getEntities() throws DataLoadFailedException {
return getList("entities", "name");
} | 0 |
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == humanButton) {
isHuman = true;
isElf = false;
isDwarf = false;
}
else if(event.getSource() == elfButton) {
isHuman = false;
isElf = true;
isDwarf = false;
}
else if(event.getSource() == dwarfButton) {
isHuman = false;
isElf = false;
isDwarf = true;
}
else if(event.getSource() == nameButtonEnter && isHuman){
aRace = Race.HUMAN;
aName = nameTextField.getText();
nameDisplayLabel.setText(aName);
raceDisplayLabel.setText(aRace.toString());
}
else if(event.getSource() == nameButtonEnter && isElf){
aRace = Race.ELF;
aName = nameTextField.getText();
nameDisplayLabel.setText(aName);
raceDisplayLabel.setText(aRace.toString());
}
else if(event.getSource() == nameButtonEnter && isDwarf){
aRace = Race.DWARF;
aName = nameTextField.getText();
nameDisplayLabel.setText(aName);
raceDisplayLabel.setText(aRace.toString());
}
} | 9 |
@Override
public void setPhone(String phone) {
super.setPhone(phone);
} | 0 |
public HashMap<String, Integer> fillFoldersWithFiles(int minFileSize, int maxFileSize) throws FoldersNotCreated, IOException {
if (!this.foldersCreated) {
throw new FoldersNotCreated();
}
FileWriter fstream = new FileWriter(this.fsFolder + files_created);
BufferedWriter out = new BufferedWriter(fstream);
int freeSpace = totalData;
boolean fsFilled = false;
int totalFilled = 0;
int totalFiles = 0;
while (!fsFilled) {
int newFileSize = this.random.nextInt(maxFileSize - minFileSize + 1) + minFileSize;
freeSpace -= newFileSize;
totalFilled += newFileSize;
totalFiles++;
boolean created = this.createFile(newFileSize, totalFiles, out);
if (!created) {
totalFiles--;
freeSpace += newFileSize;
totalFilled -= newFileSize;
}
if (maxFileSize * 2 > freeSpace) {
logger.debug("Total data almost done.");
fsFilled = true;
}
}
logger.debug("Create two files of " + (freeSpace / 2));
this.createFile(freeSpace / 2, totalFiles + 1, out);
this.createFile(freeSpace / 2, totalFiles + 2, out);
totalFilled += freeSpace;
logger.debug("Created " + totalFilled + " kbytes from the total " + totalData);
totalFiles += 2;
logger.debug("Total files created: " + totalFiles);
out.close();
fstream.close();
return this.files;
} | 4 |
@Override
public String execute() throws Exception {
if (!this.userService.verifyLeader(cid, this.userService.getCurrentUser().getUid()))
return LOGIN;
System.out.println("-------------------- cid:" + cid + " account:" + account + " oldJob:" + oldJob + " newJob:" + newJob + " -------------------- ");
if (oldJob == null || newJob == null) {
System.out.println("emptyShit");
return "emptyShit";
}
int staffUid = userService.findUserByAccount(account).getUid(); // make it simple when refactor, like, "getUidByAccount()"
// member -> publisher
if (oldJob.equals("member") && newJob.equals("publisher")) {
System.out.println("===== member -> publisher =====");
// removed from member data first, then added to publisher data
clubService.removeMember(cid, staffUid);
clubService.addPublisher(cid, staffUid);
userService.updateUserClubJob(cid, staffUid, "publisher");
}
// publisher -> member
else if (oldJob.equals("publisher") && newJob.equals("member")) {
System.out.println("===== publisher -> member =====");
// removed from publisher data first, then added to member data
clubService.removePublisher(cid, staffUid);
clubService.addMember(cid, staffUid);
userService.updateUserClubJob(cid, staffUid, "member");
}
return SUCCESS;
} | 7 |
private Node getNext(Node u)
{
if (u.right == null)
{
Node n = u;
do {
u = n;
n = n.parent;
if (n == null) return null;
} while (u == n.right); //got nullpointer
return n;
}
Node n = u.right;
while (n.left != null)
n = n.left;
return n;
} | 4 |
@Override
public void actionPerformed(ActionEvent e) {
// CLEAR ALL THE LISTS!
DefaultListModel<ImageIcon> listModel = (DefaultListModel<ImageIcon>)imageSlider.iconList.getModel();
listModel.removeAllElements();
listModel.clear();
imageSlider.imageList.clear();
// Get the results depending on the selected item in the combobox
// Only return the available vehicles, 0 = available, 1 = not.
for (Vehicle vehicle : imageSlider.v.getAll()) {
if (vehicle.getAvailable() == 0 && vehicle.getVehicleCategory().equals(imageSlider.categoryBox.getSelectedItem().toString())) {
imageSlider.imageList.add(vehicle.getImageURL());
}
}
// Declare new ImageIcon
imageSlider.icons = new ImageIcon[imageSlider.imageList.size()];
new SwingWorker<Void, ImageIcon>() {
@Override
protected Void doInBackground() throws Exception {
// Foreach url in the imagelist, creage an image.
for (String imageUrl : imageSlider.imageList) {
BufferedImage img = ImageIO.read(new URL(imageUrl));
img = ImageUtil.createScaledImage(img);
ImageIcon icon = new ImageIcon(img, imageUrl);
publish(icon);
}
return null;
}
protected void process(java.util.List<ImageIcon> chunks) {
for (ImageIcon icon : chunks) {
imageSlider.iconListModel.addElement(icon);
}
};
protected void done() {
};
}.execute();
// Set the selectionmode and actionlistner
imageSlider.iconList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageSlider.iconList.addListSelectionListener(this);
} | 5 |
@Override
public void executeCommand(CommandSender sender, Command cmd, String[] args){
CommandHelper helper = new CommandHelper(sender, cmd);
Player player = (Player) sender;
//Usage: /ghostsquadron map <create/delete> <name>
if(args.length == 3){
if(args[0].equalsIgnoreCase("map")){
if(args[1].equalsIgnoreCase("create")){
if(MapUtils.isMap(args[2])){
PlayerUtils.sendMessage(player, ChatColor.RED + "The map '" + args[2] + "' already exists!");
return;
} else {
Selection selection = WorldEditUtils.getWorldEdit().getSelection(player);
if(selection != null){
MapUtils.createMap(args[2], selection);
PlayerUtils.sendMessage(player, ChatColor.GREEN + "Created map with the name '" + args[2] + "'! Now set the spawns!");
MapUtils.loadMaps();
return;
} else {
PlayerUtils.sendMessage(player, ChatColor.RED + "Select a region with WorldEdit first!");
return;
}
}
} else if(args[1].equalsIgnoreCase("delete")){
if(MapUtils.isMap(args[2])){
MapUtils.deleteMap(args[2]);
PlayerUtils.sendMessage(player, ChatColor.GREEN + "Successfully deleted the map with the name '" + args[2] + "'!");
MapUtils.loadMaps();
return;
} else {
PlayerUtils.sendMessage(player, ChatColor.RED + "Could not find the map '" + args[2] + "'!");
return;
}
}
}
helper.wrongArguments();
return;
}
helper.unknownCommand();
return;
} | 7 |
public void enter(Miner miner){
//if the miner is not already located at the goldmine, he must
//change location to the gold mine
if (miner.getLocation() != Location.goldmine)
{
System.out.println(miner.getName() + " Walkin' to the goldmine");
miner.changeLocation(Location.goldmine);
}
} | 1 |
public void parseCards() {
for (String msg : read) {
for (CardData list : CardData.values()) {
if (list.name.toLowerCase().equals(msg.toLowerCase())) {
cards.add(processedCard(list));
}
}
}
} | 3 |
public int[] searchRange(int[] A, int target) {
int[] out = {-1, -1};
if (A == null || A.length == 0)
return out;
int start = 0;
int end = A.length - 1;
while (start <= end) {
int mid = start + (end - start)/2;
if (A[mid] < target)
start = mid + 1;
else if (A[mid] > target)
end = mid - 1;
else {
int idx = mid;
while (idx > 0 && A[idx-1] == target)
idx--;
out[0] = idx;
idx = mid;
while (idx < A.length-1 && A[idx+1] == target)
idx++;
out[1] = idx;
break;
}
}
return out;
} | 9 |
private static int hexToBinNibble(char c) {
int result = -1;
if ((c >= '0') && (c <= '9'))
result = (c - '0');
else {
if ((c >= 'a') && (c <= 'f'))
result = (c - 'a') + 10;
else {
if ((c >= 'A') && (c <= 'F'))
result = (c - 'A') + 10;
// else pick up the -1 value set above
}
}
return result;
} | 6 |
public static int sumScores(Scores obj)
{
int total = 0;
// total up all the stored scoreds in the paramter object
for (int i = 0; i< obj.grades.length; i++)
{
total = total + obj.grades[i];
}
return total;
} | 1 |
@Override
public void gerer(Commande commandRyan, Commande commandAlex) {
HashMap<String, Boolean> estGele_atPre = new HashMap<>();
estGele_atPre.put(ryan().nom(), super.estGele(ryan().nom()));
estGele_atPre.put(alex().nom(), super.estGele(alex().nom()));
estGele_atPre.put(slick().nom(), super.estGele(slick().nom()));
for (GangsterService gangster : gangster()) {
estGele_atPre.put(gangster.nom(), super.estGele(gangster.nom()));
}
HashMap<String, Boolean> estFrappe_atPre = new HashMap<>();
estFrappe_atPre.put(ryan().nom(), super.estGele(ryan().nom()));
estFrappe_atPre.put(alex().nom(), super.estGele(alex().nom()));
estFrappe_atPre.put(slick().nom(), super.estGele(slick().nom()));
for (GangsterService gangster : gangster()) {
estFrappe_atPre.put(gangster.nom(), super.estGele(gangster.nom()));
}
checkInvariant();
super.gerer(commandRyan, commandAlex);
checkInvariant();
// post 1 : estFrappe pour perso :: pas faisable (depend de la cmd de
// l'attaqueur (donc du gangster))
//
// estFrappe(gerer(C, cr, ca), nom(perso))
// = !estGele(C,nom(attacker))
// && cmdAttacker=FRAPPE && attacker = collisionPerso(perso)
//
// post 2* : estFrappe pour gangster
//
// estFrappe(gerer(C, cr, ca), nom(gangster))
// = !estGele(C,nom(attacker))
// && cmdAttacker=FRAPPE && attacker = collisionGangster(gangster)
//
for (GangsterService gangster : gangster()) {
if (super.estFrappe(gangster.nom())) {
List<PersonnageService> attacker = super
.collisionGangster(gangster);
for (PersonnageService p : attacker) {
Commande cmdAttacker = null;
if (p == null)
continue;
if (p.nom().compareTo("Ryan") == 0) {
cmdAttacker = commandRyan;
} else {
cmdAttacker = commandAlex;
}
if (cmdAttacker != Commande.FRAPPE) {
throw new PostconditionError("Postcondtion numero 2");
}
if (estGele_atPre.get(p.nom())) {
throw new PostconditionError("Postcondition numero 2");
}
}
}
}
// post 3 : estGele pour perso :: pas faisable car pas d'accès au nombre
// de gel restant
//
// estGele(gerer(C, cr, ca), nom(perso))
// = estFrappe(gerer(C, cr, ca), nom(perso))
// || !estGele(C, nom(perso)) && cmdPerso = FRAPPE
//
// post 4 : estGele pour gangster :: pas faisable (depend de la cmd du
// gangster)
//
// estGele(gerer(C, cr, ca), nom(gangster))
// = estFrappe(gerer(C, cr, ca), nom(gangster))
// || !estGele(C, nom(gangster)) && cmdgangster = FRAPPE
//
// post 5 : ryan, faire retrait ou jeter si besoin :: pas faisable
// (depend des cmd aléatoires)
//
// ryan(gerer(C, cr, ca))
// = ryan(C) si !estFrappe(gerer(C, cr, ca), Personnage::nom(ryan(C)))
// = Personnage::retrait(ryan(C),
// Gangster::force(collisionPerso(C, ryan(C))))
// (si estEquipe(collisionPerso(C)) alors * 2)
//
// et si Gangster::estEquipe(collisionPerso(C, ryan(C))),
// => Gangster::jeter(collisionPerso(C, ryan(C)),
// Terrain::getBloc(getTerrain(C), Gangster::getX(collisionPerso(C,
// ryan(C))), Gangster::getY(collisionPerso(C, ryan(C))),
// Gangster::getZ(collisionPerso(C, ryan(C)))))
//
// post 6 : alex, faire retrait ou jeter si besoin :: pas faisable
// (depend des cmd aléatoires)
//
// alex(gerer(C, cr, ca))
// = alex(C) si !estFrappe(gerer(C, cr, ca), Personnage::nom(alex(C)))
// = Personnage::retrait(alex(C),
// Gangster::force(collisionPerso(C, ryan(C))))
// (si estEquipe(collisionPerso(C)) alors * 2)
//
// et si Gangster::estEquipe(collisionPerso(C, alex(C))),
// => Gangster::jeter(collisionPerso(C, alex(C)),
// Terrain::getBloc(getTerrain(C), Gangster::getX(collisionPerso(C,
// alex(C))), Gangster::getY(collisionPerso(C, alex(C))),
// Gangster::getZ(collisionPerso(C, alex(C)))))
//
// post 7* : slick, faire retrait ou jeter si besoin
//
// slick(gerer(C, cr, ca))
// = slick(C) si !estFrappe(gerer(C, cr, ca), Gangster::nom(slick(C)))
// = Gangster::retrait(slick(C),
// Personnage::force(collisionPerso(C, slick(C))))
// (si estEquipe(collisionGangster(C)) alors * 2)
//
// et si Personnage::estEquipe(collisionPerso(C, slick(C)),
// => Personnage::jeter(collisionPerso(C, slick(C),
// Terrain::getBloc(getTerrain(C), Personnage::getX(collisionPerso(C,
// slick(C)), Personnage::getY(collisionPerso(C, slick(C)),
// Personnage::getZ(collisionPerso(C, slick(C))))
//
// post 8* : pour chaque gangster, faire retrait ou jeter si besoin
//
// \foreach g \in gangster(C)
// g(gerer(C, cr, ca))
// = g(C) si !estFrappe(gerer(C, cr, ca), Gangster::nom(g(C)))
// = Gangster::retrait(g(C),
// Personnage::force(collisionPerso(C, g(C))))
// et si Gangster::estEquipe(g),
// => Gangster::jeter(g, Terrain::getBloc(getTerrain(C),
// Gangster::getX(g), Gangster::getY(g), Gangster::getZ(g)))
//
// post 9 : ryan : traitement cmd :: pas faisable (depend de 1)
//
// ryan(gerer(C, cr, ca)) =>
// Personnage::getY(ryan(gerer(C, cr, ca))) = Personnage::getY(ryan(C))
// si !estFrappe(gerer(C, cr, ca))
// si cr=GAUCHE
// Personnage::getX(ryan(gerer(C, cr, ca)))
// = max(0,
// Personnage::getX(ryan(gerer(C))) - 1)
// si cr=DROITE
// Personnage::getX(ryan(gerer(C, cr, ca)))
// = min(Terrain::nbBlocLargeur(getTerrain(C),
// Personnage::getX(ryan(gerer(C))) + 1))
// si cr=HAUT
// Personnage::getZ(ryan(gerer(C, cr, ca)))
// = max(0,
// Personnage::getX(ryan(gerer(C))) - 1))
// si cr=BAS
// Personnage::getZ(ryan(gerer(C, cr, ca)))
// = min(Terrain::nbBlocProfondeur(getTerrain(C),
// Personnage::getX(ryan(gerer(C))) + 1))
//
// si estFrappe(gerer(C, cr, ca))
// alors calcul de l'offset de déplacement sur X et Z
// dans un tableau offset[2]
// Personnage::getX(ryan(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocLargeur(getTerrain(C),
// Personnage::getX(ryan(gerer(C))) + offset[0]))
//
// Personnage::getZ(ryan(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocProfondeur(getTerrain(C),
// Personnage::getZ(ryan(gerer(C))) + offset[1]))
//
// post 10 : alex : traitement cmd :: pas faisable (depend de 1)
//
// alex(gerer(C, cr, ca)) =>
// Personnage::getY(alex(gerer(C, cr, ca))) = Personnage::getY(alex(C))
// si !estFrappe(gerer(C, cr, ca))
// si cr=GAUCHE
// Personnage::getX(alex(gerer(C, cr, ca)))
// = max(0,
// Personnage::getX(alex(gerer(C))) - 1)
// si cr=DROITE
// Personnage::getX(alex(gerer(C, cr, ca)))
// = min(Terrain::nbBlocLargeur(getTerrain(C),
// Personnage::getX(alex(gerer(C))) + 1))
// si cr=HAUT
// Personnage::getZ(alex(gerer(C, cr, ca)))
// = max(0,
// Personnage::getX(alex(gerer(C))) - 1))
// si cr=BAS
// Personnage::getZ(alex(gerer(C, cr, ca)))
// = min(Terrain::nbBlocProfondeur(getTerrain(C),
// Personnage::getX(alex(gerer(C))) + 1))
//
// si estFrappe(gerer(C, cr, ca))
// alors calcul de l'offset de déplacement sur X et Z
// dans un tableau offset[2]
// Personnage::getX(alex(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocLargeur(getTerrain(C),
// Personnage::getX(alex(gerer(C))) + offset[0]))
//
// Personnage::getZ(alex(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocProfondeur(getTerrain(C),
// Personnage::getZ(alex(gerer(C))) + offset[1]))
//
// post 11 : slick : traitement cmd :: pas faisable
//
// slick(gerer(C, cr, ca)) =>
// Gangster::getY(slick(gerer(C, cr, ca))) = Gangster::getY(slick(C))
// si !estFrappe(gerer(C, cr, ca))
// si cr=GAUCHE
// Gangster::getX(slick(gerer(C, cr, ca)))
// = max(0,
// Gangster::getX(slick(gerer(C))) - 1)
// si cr=DROITE
// Gangster::getX(slick(gerer(C, cr, ca)))
// = min(Terrain::nbBlocLargeur(getTerrain(C),
// Gangster::getX(slick(gerer(C))) + 1))
// si cr=HAUT
// Gangster::getZ(slick(gerer(C, cr, ca)))
// = max(0,
// Gangster::getX(slick(gerer(C))) - 1))
// si cr=BAS
// Gangster::getZ(slick(gerer(C, cr, ca)))
// = min(Terrain::nbBlocProfondeur(getTerrain(C),
// Gangster::getX(slick(gerer(C))) + 1))
//
// si estFrappe(gerer(C, cr, ca))
// alors calcul de l'offset de déplacement sur X et Z
// dans un tableau offset[2]
// Gangster::getX(slick(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocLargeur(getTerrain(C),
// Gangster::getX(slick(gerer(C))) + offset[0]))
//
// Gangster::getZ(slick(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocProfondeur(getTerrain(C),
// Gangster::getZ(slick(gerer(C))) + offset[1]))
//
// post 12 : pour chaque gangster, traitement cmd :: pas faisable
//
// \foreach g \in gangster(C)
// g(gerer(C, cr, ca)) =>
// Gangster::getY(g(gerer(C, cr, ca))) = Gangster::getY(g(C))
// si !estFrappe(gerer(C, cr, ca))
// si cr=GAUCHE
// Gangster::getX(g(gerer(C, cr, ca)))
// = max(0,
// Gangster::getX(g(gerer(C))) - 1)
// si cr=DROITE
// Gangster::getX(g(gerer(C, cr, ca)))
// = min(Terrain::nbBlocLargeur(getTerrain(C),
// Gangster::getX(g(gerer(C))) + 1))
// si cr=HAUT
// Gangster::getZ(g(gerer(C, cr, ca)))
// = max(0,
// Gangster::getX(g(gerer(C))) - 1))
// si cr=BAS
// Gangster::getZ(g(gerer(C, cr, ca)))
// = min(Terrain::nbBlocProfondeur(getTerrain(C),
// Gangster::getX(g(gerer(C))) + 1))
//
// si estFrappe(gerer(C, cr, ca))
// alors calcul de l'offset de déplacement sur X et Z
// dans un tableau offset[2]
// Gangster::getX(g(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocLargeur(getTerrain(C),
// Gangster::getX(g(gerer(C))) + offset[0]))
//
// Gangster::getZ(g(gerer(C, cr, ca)))
// = max(0,min(Terrain::nbBlocProfondeur(getTerrain(C),
// Gangster::getZ(g(gerer(C))) + offset[1]))
//
} | 9 |
private Collection<? extends Node> getDropNodes(BlockType type, int x, int lowestY, DropDirection dd) {
ArrayList<Node> result = new ArrayList<Node>();
switch(dd){
case UP:
if(type==BlockType.Corner){
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY+1)));
result.add(Node.getNode(Coordinate.getCoordinate(x+1, lowestY+1)));
} else if(type==BlockType.Line){
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY+1)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY+2)));
} else if(type==BlockType.Square){
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY+1)));
result.add(Node.getNode(Coordinate.getCoordinate(x+1, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x+1, lowestY+1)));
}
break;
case DOWN:
if(type==BlockType.Corner){
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY-1)));
result.add(Node.getNode(Coordinate.getCoordinate(x+1, lowestY)));
} else if(type==BlockType.Line){
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY-1)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY-2)));
} else if(type==BlockType.Square){
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x, lowestY-1)));
result.add(Node.getNode(Coordinate.getCoordinate(x+1, lowestY)));
result.add(Node.getNode(Coordinate.getCoordinate(x+1, lowestY-1)));
}
break;
}
return result;
} | 9 |
private boolean evaluatePairing ()
{
int toprank = 0;
int botrank = 0;
int topind = 0;
int botind = 0;
for (int i=Rank.NUM_RANK-1; i>=0; i--)
{
//int rankhashi = _rankhash[i];
int rankhashi = (int)((_Rankhash>>(4*i)) & 0xF);
if (rankhashi > toprank)
{
botrank = toprank;
botind = topind;
toprank = rankhashi;
topind = i;
}
else if (rankhashi > botrank)
{
botrank = rankhashi;
botind = i;
}
}
switch (toprank)
{
case 4:
_intval ^= FOUR_OF_A_KIND_MASK;
_intval ^= FOUR_OF_A_KIND << 16;
_intval ^= (topind << 4);
_intval ^= botind;
//Debug.out ("fish " + this + " -r");
return true;
//break;
case 3:
if (botrank > 1)
{
_intval ^= FULL_HOUSE_MASK;
_intval ^= FULL_HOUSE << 16;
_intval ^= (topind << 4);
_intval ^= botind;
return true;
}
else
{
_intval ^= THREE_OF_A_KIND_MASK;
_intval ^= THREE_OF_A_KIND << 16;
_intval ^= (topind << 8);
//_rankhash[topind] = 0; // hack so 3 pair works
_Rankhash -= (((_Rankhash>>(4*topind)) & 0xF)<<(4*topind));
fillHand (1,3);
}
break;
case 2:
if (botrank > 1)
{
_intval ^= TWO_PAIR_MASK;
_intval ^= TWO_PAIR << 16;
_intval ^= (topind << 8);
_intval ^= (botind << 4);
//_rankhash[topind] = _rankhash[botind] = 0; // hack so 3 pr works
_Rankhash -= (((_Rankhash>>(4*topind)) & 0xF)<<(4*topind));
_Rankhash -= (((_Rankhash>>(4*botind)) & 0xF)<<(4*botind));
fillHand (2,3);
}
else
{
_intval ^= ONE_PAIR_MASK;
_intval ^= ONE_PAIR << 16;
_intval ^= (topind << 12);
//_rankhash[topind] = 0; // hack so 3 pair works
_Rankhash -= (((_Rankhash>>(4*topind)) & 0xF)<<(4*topind));
fillHand(1,4);
}
break;
default:
_intval ^= NO_PAIR_MASK;
_intval ^= NO_PAIR << 16;
fillHand(0,5);
return false;
}
return false;
} | 8 |
private boolean addPosition(KrakenState state, XYLocation kingLocation,XYLocation location,
ArrayList<KrakenMove> list,XYLocation finalLocation){
if (state.distance(kingLocation, location, finalLocation)){
if (state.isEmpty(finalLocation)){
list.add(new KrakenMove(location, finalLocation));
return false;
}else{
if (!state.getValue(finalLocation).getColor().equals(color)){
list.add(new KrakenMove(location, finalLocation));
return true;
}else
return true;
}
}else{
if (state.getValue(finalLocation) != null && !state.getValue(finalLocation).getColor().equals(color)){
list.add(new KrakenMove(location, finalLocation));
return true;
}
}
return true;
} | 5 |
public static byte[] createChecksum(String filename) throws FileNotFoundException
{
InputStream fis = new FileInputStream(filename);
try
{
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do
{
numRead = fis.read(buffer);
if (numRead > 0)
{
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
return complete.digest();
} catch (IOException ex) {
Logger.getLogger(Checksum.class.getName()).log(Level.SEVERE, null, ex);
}
catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Checksum.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Checksum.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
} | 5 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
int[] nm = readInts(in.readLine());
int n = nm[0], m = nm[1];
Dijkstra G = new Dijkstra(n + 1);
G.init(n + 1);
int[] cost = readInts(in.readLine());
for (int i = 0; i < cost.length; i++)
G.cost[i] = cost[i];
for (int i = 0; i < m; i++) {
int[] uvl = readInts(in.readLine());
int u = uvl[0], v = uvl[1], l = uvl[2];
G.union(u, v, l, true);
}
int queries = Integer.parseInt(in.readLine().trim());
for (int i = 0; i < queries; i++) {
int[] cuv = readInts(in.readLine());
int u = cuv[1], v = cuv[2], c = cuv[0];
int ans = G.dijkstra(u, v, c);
if (ans == G.INF)
out.append("impossible\n");
else
out.append(ans + "\n");
}
System.out.print(out);
} | 4 |
public String getDate() {
return date;
} | 0 |
private Integer score(String name) {
int sum=0;
for(byte b:name.getBytes()){
sum+=b-'A'+1;
}
return sum;
} | 1 |
private boolean isPower(int n) {
if (n == 0 || n == 1) return true;
HashMap<Integer, Integer> frequencyMap = new HashMap<>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
if (frequencyMap.get(i) == null)
frequencyMap.put(i, 1);
else
frequencyMap.put(i, frequencyMap.get(i) + 1);
n = n / i;
}
}
List<Integer> frequencies = new ArrayList<>(frequencyMap.values());
Collections.sort(frequencies);
if (frequencies.isEmpty() || frequencies.get(0) == 1) return false;
else {
int result = frequencies.get(0);
for (int i = 1; i < frequencies.size(); i++) {
result = gcd(result, frequencies.get(i));
}
if (result > 1) return true;
else return false;
}
} | 9 |
private static boolean newAngleBeforeOldAngle(AngleInterval newAngle, AngleInterval oldAngle)
{
return newAngle != null &&
(oldAngle == null ||
((oldAngle.leftAngle < oldAngle.rightAngle && newAngle.leftAngle < oldAngle.rightAngle) ||
oldAngle.leftAngle > oldAngle.rightAngle));
} | 4 |
public String toString() {
try {
java.io.StringWriter strw = new java.io.StringWriter();
TabbedPrintWriter writer = new TabbedPrintWriter(strw);
writer.println(super.toString() + ": " + addr + "-"
+ (addr + length));
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INOUT) != 0) {
writer.println("in: " + in);
}
writer.tab();
block.dumpSource(writer);
writer.untab();
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INOUT) != 0) {
Iterator iter = successors.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
FlowBlock dest = (FlowBlock) entry.getKey();
SuccessorInfo info = (SuccessorInfo) entry.getValue();
writer.println("successor: " + dest.getLabel() + " gen : "
+ info.gen + " kill: " + info.kill);
}
}
return strw.toString();
} catch (RuntimeException ex) {
return super.toString() + ": (RUNTIME EXCEPTION)";
} catch (java.io.IOException ex) {
return super.toString();
}
} | 5 |
public static void main(String[] args) {
// AucBuyout.start();
String login = null;
String action = null;
if(args.length == 2 && args[1] == "gui") {
new Gui();
} else if (args.length == 3) {
login = args[1];
action = args[2];
}
while(login == null) {
login = select_login();
}
System.out.println("selected login: " + login);
while(action == null) {
action = select_action();
}
System.out.println("selected action: " + action);
handle(login, action);
} | 5 |
@Override
public int combine(MDDManager ddmanager, int first, int other) {
// NOTE: all operations do not return a node when merging it with itself (stable states, xor, ...)
NodeRelation status = ddmanager.getRelation(first, other);
MergeAction action = t[status.ordinal()];
if (action == MergeAction.ASKME) {
action = ask(ddmanager, status, first, other);
}
switch (action) {
case CUSTOM:
return custom(ddmanager, status, first, other);
case RECURSIVE:
return recurse(ddmanager, status, first, other);
case THIS:
return ddmanager.use(first);
case OTHER:
return ddmanager.use(other);
case MIN:
if (first > other) {
return ddmanager.use(other);
}
return ddmanager.use(first);
case MAX:
if (first > other) {
return ddmanager.use(first);
}
return ddmanager.use(other);
}
return -1;
} | 9 |
public void Play(){
if(Hero.x != x)
if(Hero.x > x){
if(!Terrain.checkOccupance(x+width+deltax, y+(height/2)+deltay))
x+=deltax;
} else {
if(!Terrain.checkOccupance(x-deltax, y+(height/2)))
x-= deltax;
}
if(Hero.y != y)
if(Hero.y > y){
if(!Terrain.checkOccupance(x+(width/2), y+height+deltay))
y+=deltay;
} else {
if(!Terrain.checkOccupance(x+(width/2), y-deltay))
y-= deltay;
}
} | 8 |
public void info(String... msg) {
if (!open)
throw new RuntimeException("Cannot log new items: the log has closed!");
if (parent != null)
parent.info(msg);
else {
Object[] args = new Object[msg.length - 1];
System.arraycopy(msg, 1, args, 0, msg.length - 1);
logQueue.offer(new LogItem(Level.INFO, String.format(msg[0], args), null));
}
} | 2 |
@Override
public void mouseClicked(MouseEvent e) {} | 0 |
public void itemStateChanged(ItemEvent evt) {
if (evt.getSource() == chb_alarmon) {
clkinput.alarmOn = evt.getStateChange() == ItemEvent.SELECTED;
clkinput.getSemaphoreInstance().give();
clkcanvas.repaint();
}
} | 1 |
public void validate() throws FtpWorkflowException, FtpIOException {
if (this.getLines().size() <= 0)
throw new FtpIOException("000", "Did not receive any reply!");
if (ReplyCode.isPermanentNegativeCompletionReply(this)) {
if (getReplyCode().intern() == ReplyCode.REPLY_530.intern())
throw new NotConnectedException(getReplyMessage());
if (getReplyCode().intern() == ReplyCode.REPLY_550.intern())
throw new FtpFileNotFoundException(getReplyMessage());
throw new FtpWorkflowException(this.getReplyCode(), this
.getReplyMessage());
} else if (ReplyCode.isTransientNegativeCompletionReply(this)) {
throw new FtpIOException(this.getReplyCode(), this
.getReplyMessage());
}
} | 5 |
private void knightBottomBottomRightPossibleMove(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if((x1 >= 0 && y1 >= 2) && (x1 <= 6 && y1 < maxHeight))
{
if(board.getChessBoardSquare(x1+1, y1-2).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
if(board.getChessBoardSquare(x1+1, y1-2).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print(" " + coordinateToPosition(x1+1, y1-2)+"*");
Position newMove = new Position(x1+1, y1-2);
piece.setPossibleMoves(newMove);
}
}
else
{
// System.out.print(" " + coordinateToPosition(x1+1, y1-2));
Position newMove = new Position(x1+1, y1-2);
piece.setPossibleMoves(newMove);
}
}
} | 6 |
private void parseLine(int vertexCount) {
String[] rawFaces = null;
int currentValue;
vertices = new Vertex[vertexCount];
for (int i = 1; i <= vertexCount; i++) {
rawFaces = words[i].split("/");
// v
currentValue = Integer.parseInt(rawFaces[0]);
vertices[i - 1] = object.getVertices().get(currentValue - 1); // -1 because references starts at 1
if (rawFaces.length == 1) continue;
if (!"".equals(rawFaces[1]) && rawFaces.length == 3) {
currentValue = Integer.parseInt(rawFaces[1]);
if (currentValue <= object.getTextures().size()) // This is to compensate the fact that if no texture is in the obj file, sometimes '1' is put instead of 'blank' (we find coord1/1/coord3 instead of coord1//coord3 or coord1/coord3)
textures[i - 1] = object.getTextures().get(currentValue - 1); // -1 because references starts at 1
}
currentValue = Integer.parseInt(rawFaces[rawFaces.length - 1]);
normals[i - 1] = object.getNormals().get(currentValue - 1); // -1 because references starts at 1
}
} | 5 |
public Expression bind(StructuredQName functionName, Expression[] arguments, StaticContext env)
throws XPathException {
final String uri = functionName.getNamespaceURI();
final String localName = functionName.getLocalName();
String targetURI = uri;
boolean builtInNamespace = uri.equals(NamespaceConstant.SCHEMA);
if (builtInNamespace) {
// it's a constructor function: treat it as shorthand for a cast expression
if (arguments.length != 1) {
throw new XPathException("A constructor function must have exactly one argument");
}
AtomicType type = (AtomicType)Type.getBuiltInItemType(targetURI, localName);
if (type==null || type.getFingerprint() == StandardNames.XS_ANY_ATOMIC_TYPE ||
type.getFingerprint() == StandardNames.XS_NOTATION) {
XPathException err = new XPathException("Unknown constructor function: {" + uri + '}' + localName);
err.setErrorCode("XPST0017");
err.setIsStaticError(true);
throw err;
}
return new CastExpression(arguments[0], type, true);
}
// Now see if it's a constructor function for a user-defined type
if (arguments.length == 1) {
int fp = config.getNamePool().getFingerprint(uri, localName);
if (fp != -1) {
SchemaType st = config.getSchemaType(fp);
if (st != null && st.isAtomicType()) {
return new CastExpression(arguments[0], (AtomicType)st, true);
}
}
}
return null;
} | 9 |
private Color getColor(Edge edge) {
if (edge == null) {
return Color.WHITE;
} else if (edge.getEdgeState() == EdgeState.BURNED) {
return Color.GREEN;
} else if (edge.getEdgeState() == EdgeState.CLOSED) {
return Color.BLUE;
} else {
return Color.BLACK;
}
} | 3 |
public Rectangle computeScaledBounds(final int zoom, final Dimension size) {
final double sDPI = dpi;
double width = sWidth * sDPI;
double height = sHeight * sDPI;
switch (zoom) {
case FIT_WIDTH: // FIT_WIDTH
{
double sw = ((double) size.width) / width;
if (favorFast && (sw < 1.0D)) {
sw = 1.0D / Math.ceil(1.0D / sw);
width *= sw;
} else {
width = size.width;
}
height *= sw;
break;
}
case FIT_PAGE: // FIT_PAGE
{
final double sw = (double) size.width / (double) width;
final double sh = (double) size.height / (double) height;
double s = (sw < sh) ? sw : sh;
if (favorFast && (s < 1.0D)) {
s = 1.0D / Math.ceil(1.0D / s);
}
width *= s;
height *= s;
break;
}
case 0: {
break;
}
default: // regular scaling
{
final double s = ((double) ((zoom < 1) ? 1 : zoom)) / sDPI;
width *= s;
height *= s;
break;
}
}
return new Rectangle(0, 0, (int) Math.ceil(width), (int) Math.ceil(height));
} | 9 |
public ArrayList<AlumneVo> llistarAlumnes() {
//crea ArrayList de persones per guardarles
ArrayList<AlumneVo> alumnes= new ArrayList< AlumneVo>();
//connexio amb la bd
DbConnection conex= new DbConnection();
try {
PreparedStatement consulta = conex.getConnection().prepareStatement("SELECT * FROM alumnes");
ResultSet res = consulta.executeQuery();
while(res.next()){
AlumneVo alum=(AlumneVo) Factory.factoryMethod("alumne");
alum.setNomUser((res.getString("nomUser")));
alum.setNom((res.getString("Nom")));
alum.setCognoms((res.getString("Cognoms")));
alum.setEdat((Integer.parseInt(res.getString("Edat"))));
alum.setPassword((res.getString("password")));
//afegir alumnes
alumnes.add(alum);
}
res.close();
consulta.close();
conex.desconectar();
} catch (Exception e) {
System.out.print("No s'ha pogut fer el llistat");
}
return alumnes;
} | 2 |
private static String infix2postfix(String[] tokens) throws CalcException {
double c;
String token;
postfix = new StringBuilder();
opStack = new Stack<Operator>();
brStack = new Stack<Bracket>();
intStack = new Stack<Integer>();
Operator op;
Bracket br;
int i, rpos;
for(i = 0; i < tokens.length; i++) {
token = tokens[i];
if((op = Operator.find(token)) != null) {
nextOp(op);
}
else if((br = Bracket.isOpen(token)) != null) {
opStack.push(Operator.SKP);
brStack.push(br);
intStack.push(i);
}
else if((br = Bracket.isClosed(token)) != null){
intStack.push(i);
nextClosed(br);
}else
try {
c = Double.valueOf(token);
postfix.append(token); postfix.append(" ");
}catch (NumberFormatException e) {
throw new CalcException("Parse Error: " + token);
}
}
while (!opStack.empty()) {
op = opStack.pop();
if (op == Operator.SKP) {
rpos = intStack.pop();
throw new CalcException(String.format(
"Mismatched Brackets: %s at position %d",
tokens[rpos], rpos+1 ));
}
postfix.append(op); postfix.append(" ");
}
return postfix.toString();
} | 7 |
void removeAwaitingResume(DccFileTransfer transfer) {
_awaitingResume.removeElement(transfer);
} | 0 |
public void startElement(String uri, String sname, String qname, Attributes atts) {
Object context = null;
if (!_contextStack.isEmpty()){
context = _contextStack.peek();
}
String attrName = atts.getValue(_attribute_name);
String attrLabel = atts.getValue(_attribute_label);
String attrDesc = atts.getValue(_attribute_description);
if (qname == _element_module){
}else if (qname == _element_querydef){
QueryDef queryDef = new QueryDef(-1,
attrName,
attrLabel,
attrDesc,
atts.getValue(_attribute_source),
atts.getValue(_attribute_type),
atts.getValue(_attribute_orderby));
newMeta(MetaDataType.QueryDef, attrName, queryDef);
_contextStack.push(queryDef);
}else if(qname == _element_columndef){
String columnName = atts.getValue(_attribute_column_name);
String joinTable = atts.getValue(_attribute_join);
String pickList = atts.getValue(_attribute_picklist);
String columnType = atts.getValue(_attribute_type);
ColumnDef columnDef = new ColumnDef(attrName, attrDesc,columnName, joinTable, pickList, columnType);
((QueryDef)context).addColumn(columnDef);
_contextStack.push(columnDef);
}else if(qname == _element_join){
String tableName = atts.getValue(_attribute_table_name);
String bString = atts.getValue(_attribute_outer);
Join join = new Join(attrName, attrLabel, tableName, !"false".equalsIgnoreCase(bString));
((QueryDef)context).addJoin(join);
_contextStack.push(join);
}else if(qname == _element_join_spec){
String source = atts.getValue(_attribute_source_filed);
String dest = atts.getValue(_attribute_target_field);
((Join)context).addJoinSpec(new JoinSpec(attrName, attrLabel, source, dest));
}else if(qname == _element_picklist){
}else if (qname == _element_pickmap){
String source = atts.getValue(_attribute_source_filed);
String dest = atts.getValue(_attribute_target_field);
String cons = atts.getValue(_attribute_cons);
((ColumnDef)context).addPickMap(source, dest, cons);
}else {
throw new RuntimeException("invalid tag: " + qname);
}
} | 8 |
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
ServletPrinter sp = null;
PreparedStatement stmt = null;
Connection conn = null;
sp = new ServletPrinter(response, "RegisterUser");
String categoryName, nickname, firstname, lastname, email;
String password = null, creation_date = null;
int userId;
int access = 0, id = 0, rating = 0;
ResultSet rs = null;
int updateResult;
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
nickname = request.getParameter("nickname");
email = request.getParameter("email");
password = request.getParameter("password");
if (firstname == null)
{
sp.printHTML("You must provide a story title!<br>");
return;
}
if (lastname == null)
{
sp.printHTML("<h3>You must provide a story body!<br></h3>");
return;
}
if (nickname == null)
{
sp.printHTML("<h3>You must provide a category!<br></h3>");
return;
}
if (email == null)
{
sp.printHTML("<h3>You must provide an email address!<br></h3>");
return;
}
if (password == null)
{
sp.printHTML("<h3>You must provide a password!<br></h3>");
return;
}
conn = getConnection();
//Authenticate the user
try
{
stmt = conn.prepareStatement("SELECT * FROM users WHERE nickname=\""
+ nickname + "\"");
rs = stmt.executeQuery();
}
catch (Exception e)
{
sp.printHTML("ERROR: Nickname query failed" + e);
closeConnection(stmt, conn);
return;
}
try
{
if (rs.first())
{
sp
.printHTML("The nickname you have chosen is already taken by someone else. Please choose a new nickname.<br>\n");
closeConnection(stmt, conn);
return;
}
stmt = conn.prepareStatement("INSERT INTO users VALUES (NULL, \""
+ firstname + "\", \"" + lastname + "\", \"" + nickname + "\", \""
+ password + "\", \"" + email + "\", 0, 0, NOW())");
updateResult = stmt.executeUpdate();
stmt.close();
stmt = conn.prepareStatement("SELECT * FROM users WHERE nickname=\""
+ nickname + "\"");
rs = stmt.executeQuery();
rs.first();
id = rs.getInt("id");
creation_date = rs.getString("creation_date");
rating = rs.getInt("rating");
access = rs.getInt("access");
}
catch (Exception e)
{
sp.printHTML("Exception registering user " + e + "<br>");
closeConnection(stmt, conn);
return;
}
closeConnection(stmt, conn);
sp
.printHTML("<h2>Your registration has been processed successfully</h2><br>\n");
sp.printHTML("<h3>Welcome " + nickname + "</h3>\n");
sp
.printHTML("RUBBoS has stored the following information about you:<br>\n");
sp.printHTML("First Name : " + firstname + "<br>\n");
sp.printHTML("Last Name : " + lastname + "<br>\n");
sp.printHTML("Nick Name : " + nickname + "<br>\n");
sp.printHTML("Email : " + email + "<br>\n");
sp.printHTML("Password : " + password + "<br>\n");
sp
.printHTML("<br>The following information has been automatically generated by RUBBoS:<br>\n");
sp.printHTML("User id :" + id + "<br>\n");
sp.printHTML("Creation date :" + creation_date + "<br>\n");
sp.printHTML("Rating :" + rating + "<br>\n");
sp.printHTML("Access :" + access + "<br>\n");
sp.printHTMLfooter();
} | 8 |
public static void jarviz() {
jButton1.setEnabled(false);
jButton2.setEnabled(false);
for (Shapes.Point point : points) {
copyArray.add(point);
}
bestPoints = new ArrayList<Shapes.Point>();
Shapes.Point cP = points.get(closestPoint());
bestPoints.add(cP);
points.remove(cP);
points.add(cP);
clearImage();
showPoints();
g.setColor(Color.GREEN);
while (true) {
int lastIndex = 0;
for (int i = 0; i < copyArray.size(); i++) {
if (myCompare(bestPoints.get(bestPoints.size() - 1), copyArray.get(lastIndex), copyArray.get(i)) == -1) {
g.setColor(Color.BLACK);
drawP(lastIndex);
lastIndex = i;
g.setColor(Color.BLUE);
} else {
g.setColor(Color.RED);
}
drawP(i);
jLabel1.update(jLabel1.getGraphics());
}
if (copyArray.get(lastIndex) == bestPoints.get(0)) {
break;
} else {
bestPoints.add(copyArray.get(lastIndex));
g.setColor(Color.GREEN);
drawB();
copyArray.remove(lastIndex);
jLabel1.update(jLabel1.getGraphics());
}
}
for (int i = 0; i < copyArray.size(); ++i) {
g.setColor(Color.RED);
if (!bestPoints.contains(copyArray.get(i))) {
g.fillOval(copyArray.get(i).getX() - 5, copyArray.get(i).getY() - 5, 10, 10);
}
}
for (int i = 0; i < bestPoints.size(); ++i) {
g.setColor(Color.BLUE);
g.fillOval(bestPoints.get(i).getX() - 5, bestPoints.get(i).getY() - 5, 10, 10);
}
g.setColor(Color.GREEN);
g.drawLine(bestPoints.get(bestPoints.size() - 1).getX(), bestPoints.get(bestPoints.size() - 1).getY(),
bestPoints.get(0).getX(), bestPoints.get(0).getY());
copyArray = new ArrayList<Shapes.Point>();
jButton1.setEnabled(true);
} | 8 |
protected static List<CCNode> processNodes(final List<String> nodeNameData,
final List<String> nodePositionData, final CCModel model)
throws Exception {
ArrayList<CCNode> nodes = new ArrayList<>();
/**
* Verifiy and add nodes *
*/
if (nodeNameData.size() == nodePositionData.size()) {
for (int i = 0; i < nodeNameData.size(); i++) {
CCNode node = processData(nodeNameData.get(i),
nodePositionData.get(i));
// node.setCCModel(model);
node.setCCModel(model);
nodes.add(node);
}
} else {
throw new Exception("Amount of node names isn't equal to the "
+ "amount of node positions defined");
}
return nodes;
} | 2 |
public String translate(String code, Object... args) {
if(translations.containsKey(code))
return String.format(translations.get(code), args);
if(code == null || code.equals(""))
return "";
if(translations.containsKey("translation.missing"))
System.err.println(translate("translation.missing", code));
else
System.err.println("translation.missing[" + code + "]");
return code + (args.length > 0 ? Arrays.toString(args) : "");
} | 5 |
*/
private static void initMap(DataRetriever data) {
for (int i = 0; i < data.generateFlights().length; i++) {
map.put(data.flights[i].toString(), new HashSet());
}
} | 1 |
public char skipTo(char to) throws JSONException {
char c;
try {
int startIndex = this.index;
int startCharacter = this.character;
int startLine = this.line;
reader.mark(Integer.MAX_VALUE);
do {
c = next();
if (c == 0) {
reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
back();
return c;
} | 3 |
public boolean isRotation(String s1, String s2){
if(s1.length()!=s2.length()){
return false;
}
s1 = s1+s1;
for(int i=0; i<s1.length()/2; i++){
if(s1.substring(i, s2.length()+i).equals(s2)){
return true;
}
}
return false;
} | 3 |
@EventHandler
public void PlayerInvisibility(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPlayerConfig().getDouble("Player.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getPlayerConfig().getBoolean("Player.Invisibility.Enabled", true) && damager instanceof Player && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getPlayerConfig().getInt("Player.Invisibility.Time"), plugin.getPlayerConfig().getInt("Player.Invisibility.Power")));
}
} | 6 |
public void renderPlatformScore(int yp, Sprite sprite) {
for(int y = 0; y < sprite.SIZE; y++) {
int ya = y + yp;
for(int x = 0; x < sprite.SIZE; x++) {
int xa = x + (Game.WIDTH/2);
if(xa < -sprite.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite.pixels[x + y * sprite.SIZE];
if(col != 0xFFFF00FF)
pixels[xa + ya * width] = col;
}
}
} | 8 |
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} | 8 |
public ArrayList<Restaurant> getAllRestaurants() throws IOException {
Document doc;
String url;
ArrayList<Restaurant> rList = new ArrayList<>();
Set<String> names = new HashSet<>();
int prevSize = -1;
for (int i = 1; i <= pages; i++) {
if (names.size() == prevSize) {
break;
}
prevSize = names.size();
url = "http://eat.fi/fi/helsinki/restaurants?page=" + i;
doc = null;
for (int j = 0; j < tries; j++) {
try {
doc = Jsoup.connect(url).get();
break;
} catch (SocketTimeoutException e) {
System.err.println("Timed out... Trying again. Tries: " + (j + 1));
}
}
if (doc == null) {
throw new SocketTimeoutException("Tried " + tries + " times, still no answer... :(");
}
Elements restaurantDivs = doc.select(".restaurant-entry*");
for (Element rDiv : restaurantDivs) {
Elements nameHrefs = rDiv.select("a[href]");
if (nameHrefs.size() != 1) {
System.err.println("Hmmm... Not one name href...");
}
String name = Jsoup.parse(nameHrefs.get(0).html()).text();
if (names.add(name)) {
String address = null;
Elements contactDivs = rDiv.select(".restaurant-contact-entry-value");
if (!contactDivs.isEmpty()) {
address = Jsoup.parse(contactDivs.get(0).html()).text();
}
Restaurant restaurant = new Restaurant();
restaurant.setName(name);
restaurant.setAddress(address);
rList.add(restaurant);
}
}
System.out.println("Names after page nr " + i + ": " + names.size());
}
Collections.sort(rList);
return rList;
} | 9 |
public String getRepositoryForDirectory(final String directory, final String repository) throws IOException {
// if there is no "CVS/Repository" file, try to search up the file-
// hierarchy
File repositoryFile = null;
String repositoryDirs = ""; // NOI18N
File dirFile = new File(directory);
while (true) {
// if there is no Repository file we cannot very well get any
// repository from it
if ((dirFile == null) || (dirFile.getName().length() == 0) || !dirFile.exists()) {
throw new FileNotFoundException("Repository file not found " + // NOI18N
"for directory " + directory); // NOI18N
}
repositoryFile = new File(dirFile, "CVS/Repository"); // NOI18N
if (repositoryFile.exists()) {
break;
}
repositoryDirs = '/' + dirFile.getName() + repositoryDirs;
dirFile = dirFile.getParentFile();
}
BufferedReader reader = null;
// fileRepository is the value of the repository read from the
// Repository file
String fileRepository = null;
try {
reader = new BufferedReader(new FileReader(repositoryFile));
fileRepository = reader.readLine();
} finally {
if (reader != null) {
reader.close();
}
}
if (fileRepository == null) {
fileRepository = ""; // NOI18N
}
fileRepository += repositoryDirs;
// absolute repository path ?
if (fileRepository.startsWith("/")) { // NOI18N
return fileRepository;
}
// #69795 'normalize' repository path
if (fileRepository.startsWith("./")) { // NOI18N
fileRepository = fileRepository.substring(2);
}
// otherwise the cvs is using relative repository path
// must be a forward slash, regardless of the local filing system
return repository + '/' + fileRepository;
} | 9 |
public static Boolean get(IntBuffer array, int index) {
int value = array.get(index >>> 4) >> ((index & 15) << 1);
switch (value & 3) {
case 0:
return false;
case 1:
return true;
case 2:
return null;
default:
throw new AssertionError();
}
} | 3 |
private boolean isValid(int[][] puzzle, int number, int row, int col){
//if the number is 0 it means it will be an empty box, so no need to check it.
if(number == 0 || number > 9){
return true;
}
//check the column
for(int k=0; k<9; k++){
if(puzzle[row][k] == number)
return false;
}
//check the row
for(int k=0; k<9; k++){
if(puzzle[k][col] == number)
return false;
}
//check the box
int boxNumCol = (col/3) * 3; //trying to find the 3x3 box which our small box belongs to
int boxNumRow = (row/3) * 3;
for (int k = boxNumRow; k<boxNumRow + 3; k++){
for (int m = boxNumCol; m<boxNumCol + 3; m++){
if(puzzle[k][m] == number)
return false;
}
}
return true;
} | 9 |
@Override
public void actionPerformed(ActionEvent e) {
// Handle open button action.
if (e.getSource() == view.getOpenButton()) {
int returnVal = fc.showOpenDialog(view);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
// This is where a real application would open the file.
view.getTextArea().setText(file.getName());
} else {
view.getTextArea().setText("Open command cancelled by user.");
}
}
if (e.getSource() == view.getExitButton()) {
if (this.view.getExitButton() == e.getSource()) {
control.getFrame().dispose();
}
}
if (e.getSource() == view.getTransferButton()) {
if(file != null){
User user = (User) view.getUserList().getSelectedItem();
this.client.sendFile(file.getAbsolutePath(), user.getIP());
this.control.getGui().addTransferMessage(this.client.getOwnUser().getIP(), user.getIP(), file.getName(), Timestamp.getCurrentTimeAsLong(), false);
control.getFrame().dispose();
} else {
new Popup("No file selected");
}
}
} | 6 |
private void clearColumnDividerHighlight() {
if (mMouseOverColumnDivider != -1) {
repaintDivider(mMouseOverColumnDivider);
mMouseOverColumnDivider = -1;
}
setCursor(Cursor.getDefaultCursor());
} | 1 |
* @return true if it worked.
*/
private boolean viEndWord(int count) throws IOException {
int pos = buf.cursor;
int end = buf.buffer.length();
for (int i = 0; pos < end && i < count; i++) {
if (pos < (end-1)
&& !isDelimiter(buf.buffer.charAt(pos))
&& isDelimiter(buf.buffer.charAt (pos+1))) {
++pos;
}
// If we are on white space, then move back.
while (pos < end && isDelimiter(buf.buffer.charAt(pos))) {
++pos;
}
while (pos < (end-1) && !isDelimiter(buf.buffer.charAt(pos+1))) {
++pos;
}
}
setCursorPosition(pos);
return true;
} | 9 |
protected int handleInput(Automaton automaton, AutomatonSimulator simulator, Configuration[] configs,
Object initialInput, List associatedConfigurations) {
JFrame frame = Universe.frameForEnvironment(getEnvironment());
// How many configurations have we had?
int numberGenerated = 0;
// When should the next warning be?
int warningGenerated = WARNING_STEP;
Configuration lastConsidered = configs[configs.length - 1];
while (configs.length > 0) {
numberGenerated += configs.length;
// Make sure we should continue.
if (numberGenerated >= warningGenerated) {
if (!confirmContinue(numberGenerated, frame)) {
associatedConfigurations.add(lastConsidered);
return 2;
}
while (numberGenerated >= warningGenerated)
warningGenerated *= 2;
}
// Get the next batch of configurations.
ArrayList next = new ArrayList();
for (int i = 0; i < configs.length; i++) {
lastConsidered = configs[i];
if (configs[i].isAccept()) {
associatedConfigurations.add(configs[i]);
return 0;
} else {
next.addAll(simulator.stepConfiguration(configs[i]));
}
}
configs = (Configuration[]) next.toArray(new Configuration[0]);
}
associatedConfigurations.add(lastConsidered);
return 1;
} | 6 |
public void resetSounds()
{
startClip.stop();
startClip.setMicrosecondPosition(0);
warnClip.stop();
warnClip.setMicrosecondPosition(0);
overClip.stop();
overClip.setMicrosecondPosition(0);
} | 0 |
public static void main(String[] args) throws Exception{
int repeated = 0;
/*
不断提交MapReduce作业直到相邻两次迭代聚类中心的距离小于阈值或到达设定的迭代次数
*/
do {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 6){
System.err.println("Usage: <int> <out> <oldcenters> <newcenters> <k> <threshold>");
System.exit(2);
}
//conf.setNumMapTasks(2);
conf.set("centerpath", otherArgs[2]);
conf.set("kpath", otherArgs[4]);
Job job = new Job(conf, "KMeansCluster");//新建MapReduce作业
job.setJarByClass(KMeansDriver.class);//设置作业启动类
Path in = new Path(otherArgs[0]);
Path out = new Path(otherArgs[1]);
FileInputFormat.addInputPath(job, in);//设置输入路径
FileSystem fs = FileSystem.get(conf);
if (fs.exists(out)){//如果输出路径存在,则先删除之
fs.delete(out, true);
}
FileOutputFormat.setOutputPath(job, out);//设置输出路径
job.setMapperClass(KMeansMapper.class);//设置Map类
job.setReducerClass(KMeansReducer.class);//设置Reduce类
job.setOutputKeyClass(IntWritable.class);//设置输出键的类
job.setOutputValueClass(Text.class);//设置输出值的类
job.waitForCompletion(true);//启动作业
++repeated;
System.out.println("We have repeated " + repeated + " times.");
} while (repeated < 10 && (Assistance.isFinished(args[2], args[3], Integer.parseInt(args[4]), Float.parseFloat(args[5])) == false));
//根据最终得到的聚类中心对数据集进行聚类
Cluster(args);
} | 4 |
public void method210()
{
for(int i = 0; i < anInt292; i++)
{
for(int j = 0; j < anInt293; j++)
if(i == 0 || j == 0 || i == anInt292 - 1 || j == anInt293 - 1)
anIntArrayArray294[i][j] = 0xffffff;
else
anIntArrayArray294[i][j] = 0x1000000;
}
} | 6 |
@Override
public String toString()
{
if (isEmpty()) return "empty";
String result = "";
Queue<Node> q = new Queue<>();
q.enqueue(root);
Node firstOnLevel = null;
while (!q.isEmpty())
{
Node u = q.dequeue();
if (u == firstOnLevel)
{
firstOnLevel = null;
result += "\n";
}
if (u != root) result += u.parent.key + "->";
if (u.isRed) result += "r";
result += u.key + " ";
if (u.left != null) q.enqueue(u.left);
if (u.right != null) q.enqueue(u.right);
if (firstOnLevel == null) firstOnLevel = (u.left == null) ? u.right : u.left;
}
return result + "\n---";
} | 9 |
private void borrowerSearch(){
boolean quit;
String keyword;
//BorrowerModel b = new BorrowerModel();
Class c = b.getClass();
ArrayList<Match> books = new ArrayList<Match>();
Object tempBooks;
quit = false;
//RETURN TYPES
try{
while (!quit){
System.out.println("Enter Search Keyword (or type quit to leave search): ");
keyword = in.readLine();
if(keyword.equals("quit")){
quit = true;
}else{
try{
Method findKeyword= c.getDeclaredMethod("findKeyword", String.class, Connection.class);
findKeyword.setAccessible(true);
tempBooks = findKeyword.invoke(b, keyword, con);
books = (ArrayList<Match>) tempBooks;
if (books.size() == 0){
System.out.println("No Results Match Search");
}else{
//callNumber, title, mainAuthor, isbn, numOfCopiesIn, numOfCopiesOut
System.out.printf("%-15s %-15s %-15s %-15s %-15s %-15s", "CallNumber", "Title", "Main Author","ISBN" ,"Num Copies In", "Num Copies Out");
System.out.println(" ");
for (int i = 0; i< books.size(); i++){
Match temp = books.get(i);
System.out.printf("%-15s %-15s %-15s %-15s %-15s %-15s", temp.callNumber, temp.title,temp.mainAuthor,temp.isbn ,temp.numOfCopiesIn, temp.numOfCopiesOut);
System.out.println(" ");
}
}
}catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (InvocationTargetException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
//in.close();
selectBorrower();
}
catch (IOException e)
{
System.out.println("IOException!");
try
{
con.close();
System.exit(-1);
}
catch (SQLException ex)
{
System.out.println("Message: " + ex.getMessage());
}
}
} | 9 |
private void loadPatientInformation(String patientID) {
ResultSet rs = dbQuery.Patient_GetPatientInformation(patientID);
if (rs != null) {
System.out.println("Patient Information Loaded Successfully.");
try {
while(rs.next()){
txt_PatientID.setText(rs.getObject("PatientID").toString());
txt_PatientID.setEnabled(false);
txt_SIN.setText(rs.getString("SocialInsuranceNumber"));
txt_FirstName.setText(rs.getString("FirstName"));
txt_LastName.setText(rs.getString("LastName"));
txt_Address.setText(rs.getString("Address"));
txt_PhoneNumber.setText(rs.getString("PhoneNumber"));
txt_HealthCardNum.setText(rs.getString("HealthCardNumber"));
}
ResultSet rs_date = dbQuery.Patient_GetLastVisitDate(patientID);
while(rs_date.next()){
txt_LastVisitDate.setText(rs_date.getString("LastVisitDate"));
txt_LastVisitDate.setEnabled(false);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("ERROR: Failed to load patient.");
// TODO: set error message
}
} | 4 |
public void sendMessageWrapper(String recipient, String nick, String message) {
// Split the string first into mutliple lines
StringTokenizer token = new StringTokenizer(message, " ");
StringBuilder chunk = new StringBuilder(MAXMSGLENGTH);
ArrayList<String> lines = new ArrayList<String>();
while (token.hasMoreTokens()) {
String word = token.nextToken();
if (chunk.length() + word.length() > MAXMSGLENGTH) {
lines.add(chunk.toString());
chunk.delete(0, chunk.length());
}
chunk.append(word + " ");
}
lines.add(chunk.toString());
// Send string
for(String line : lines) {
if(nick == null) {
sendMessage(recipient, line);
}
else {
sendMessage(recipient, nick + ": " + line);
}
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Parameter other = (Parameter) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
} | 9 |
public void teleport(Player p){
for (GameObject object : World.backgroundTiles) {
if(object.getClass() == this.getClass()){
Portal portal = (Portal) object;
if(portal.getId() == targetId){
p.setPosition(portal.getX(), portal.getY());
}
}
}
} | 3 |
public WindowAdapter(JFrame frame) {
this.frame = frame;
} | 0 |
public boolean moveLine(int x0,int y0,int x1,int y1)//让块按照直线走,走完返回true
{
int x=this.getX();
int y=this.getY();
if(x0==x1&&y0==y1)//not line
return true;
if(x0==x1)//horizen line
{
if(y0>y1)
y-=5;
else
y+=5;
if(y==y1)
{
this.setLocation(x, y);
return true;
}
}
if(y0==y1)//vertical line
{
if(x0>x1)
x-=5;
else
x+=5;
if(x==x1)
{
this.setLocation(x, y);
return true;
}
}
this.setLocation(x, y);
return false;
} | 8 |
@Test
public void generic() {
ArrayList<Unit<Integer, String>> haystack = new ArrayList<Unit<Integer, String>>();
int count = 100;
for (int i = 0; i < count; i++) {
if (i % 3 == 0) {
continue;
}
haystack.add(new Unit<Integer, String>(i, String.valueOf(i)));
}
for (int i = 0; i < count; i++) {
if (i % 3 == 0) {
continue;
}
String result = search.find(haystack, i);
Assert.assertEquals(String.valueOf(i), result);
}
for (int i = 0; i <= count; i++) {
if (i % 3 == 0) {
String result = search.find(haystack, i);
Assert.assertEquals(null, result);
}
}
} | 6 |
@Inject
public MarshallerPool(@Named("marshalContext") JAXBContext context) {
this.context = context;
} | 0 |
@SuppressWarnings("unchecked")
public ArrayList<T> list() {
Cursor c = null;
ArrayList<T> r = new ArrayList<T>();
c = getSQLCursor();
if (c.moveToFirst()) {
do {
try {
r.add((T) Model.load(mDB.mContext, E, c));
} catch (Throwable e) {
Util.Log(e);
}
} while (c.moveToNext());
}
c.close();
return r;
} | 3 |
public static String assign(Person person) {
String job = "";
// logic goes here
String currentJob =
person.getJobArray().get(person.getJobArray().size() - 1);
String previousJob =
person.getJobArray().get(person.getJobArray().size() - 2);
if (person.getDishes()) {
if (currentJob.equals(DS)) {
// LR -> KT
if (previousJob.equals(LR)){
job = KT;
}
// KT -> BR
if (previousJob.equals(KT)){
job = BR;
}
// BR -> LR
if (previousJob.equals(BR)){
job = LR;
}
}
else {
job = DS;
}
}
else {
// LR -> BR
if (currentJob.equals(LR)) {
job = BR;
}
// BR -> KT
else if (currentJob.equals(BR)) {
job = KT;
}
// KT -> LR
else if (currentJob.equals(KT)) {
job = LR;
}
}
return job;
} | 8 |
public synchronized Queue<String> getUnsearchList(){
return this.unsearchSitesList;
} | 0 |
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
} | 1 |
public static Graph perform( Graph g )
{
List< Set<Vertex> > sets = new LinkedList<>();
Edge [] edges = g.edges();
List<Edge> finalEdges = new LinkedList<>();
Queue<Edge> edgeQueue = new PriorityQueue<>(edges.length, new Comparator<Edge>()
{
public int compare(Edge e1, Edge e2)
{
return Double.compare(e1.weight, e2.weight);
}
});
for ( int i = 0; i < g.vertices.length; i++ )
{
Set<Vertex> currentSet = new HashSet<Vertex>();
currentSet.add( g.vertices[i] );
sets.add( currentSet );
}
for ( Edge e : edges )
{
edgeQueue.add( e );
}
int numOfSets = sets.size();
while ( edgeQueue.peek() != null && numOfSets > 1 )
{
Edge e = edgeQueue.remove();
Set<Vertex> sourceSet = null;
Set<Vertex> destSet = null;
for ( Set<Vertex> s : sets )
{
if ( s.contains( e.source ) )
{
sourceSet = s;
}
if ( s.contains( e.dest ) )
{
destSet = s;
}
}
if ( sourceSet == destSet )
{
continue;
}
// union the two sets together
sourceSet.addAll( destSet );
sets.remove( destSet );
numOfSets = sets.size();
finalEdges.add( e );
}
// go through final edges and turn it into a graph, and return
Edge [] finalEdgesArray = finalEdges.toArray(new Edge[0]);
return new Graph( finalEdgesArray );
} | 8 |
public static void main(String[] args) throws MalformedURLException {
for (int i = 0; i < 2000; i++) {
for (int j = 0; j < 1000; j++) {
URL url = new URL("http://www.gamestar.de/_misc/betatest/betatest.cfm?pk=" + i + "&pid=" + j);
if(verifyLink(url)){
SearchInfo search = new SearchInfo();
String html = search.readHTML(url);
Pattern pattern1 = Pattern.compile("<title>(.*?)</title>");
Pattern pattern2 = Pattern.compile("<strong>(.*?)</strong>");
html = (null == html ? "" : html);
if(!html.isEmpty()) {
Matcher m1 = pattern1.matcher(html);
Matcher m2 = pattern2.matcher(html);
if(m1.find() && m2.find()){
System.out.println(m1.group(1) + "\t" + m2.group(1));
}
}
} else {
break;
}
}
}
} | 7 |
public static void addPlayerMove()
{
do
{
System.out.println("Please enter the coordinates of your move. (ex. B1)");
Scanner keyboard = new Scanner(System.in);
move = keyboard.nextLine();
switch(move.substring(0,1))
{
case "A":
case "a":
row = 0;
break;
case "B":
case "b":
row = 1;
break;
case "C":
case "c":
row = 2;
break;
}
column= Integer.parseInt(move.substring(1)) - 1;
TicTacToeBoard.board[row][column] = playerMarker;
TicTacToeBoard.board[TicTacToePlayer.row][TicTacToePlayer.column] = TicTacToePlayer.playerMarker;
}
while(TicTacToeBoard.isMoveValid());
} | 7 |
@Override
public void serialize(Buffer buf) {
buf.writeUShort(aliases.length);
for (String entry : aliases) {
buf.writeString(entry);
}
buf.writeUShort(arguments.length);
for (String entry : arguments) {
buf.writeString(entry);
}
buf.writeUShort(descriptions.length);
for (String entry : descriptions) {
buf.writeString(entry);
}
} | 3 |
public int reverse(int x) {
boolean negative = false;
if (x == Integer.MIN_VALUE)
return 0;
if (x != Math.abs(x)) {
negative = true;
x = Math.abs(x);
}
int result = 0;
while (x != 0) {
if (result > Integer.MAX_VALUE / 10) {
return 0;
} else if (result == Integer.MAX_VALUE) {
if (x % 10 > Integer.MAX_VALUE % 10) {
return 0;
}
}
result = result * 10 + x % 10;
x = x / 10;
}
if (negative) {
return 0 - result;
}
return result;
} | 7 |
public void showMainInstructions(final int pageIndex) {
removeActionListeners(nextButton);
removeActionListeners(previousButton);
if (pageIndex < Text.TEXT_INSTRUCTIONS.length) {
//not last page
nextButton.setText(Text.BTN_NEXT);
nextButton.setVisible(true);
nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //on click, close the gui
showMainInstructions(pageIndex + 1);
}});
}
if (pageIndex > 1) {
//not first page
previousButton.setText(Text.BTN_PREVIOUS);
previousButton.setVisible(true);
previousButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //on click, close the gui
showMainInstructions(pageIndex - 1);
}});
} else {
previousButton.setVisible(false);
}
if (pageIndex == Text.TEXT_INSTRUCTIONS.length) {
//last page
nextButton.setText(Text.BTN_BEGIN);
nextButton.setVisible(true);
nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //on click, close the gui
previousButton.setVisible(false);
nextButton.setVisible(false);
Experiment.xp.displayAndContinue();
}});
}
setInstructions(Text.TEXT_INSTRUCTIONS[pageIndex - 1]);
} | 3 |
public void setCanEditFollow(boolean canEdit) {
canEditColumn[2] = canEdit;
} | 0 |
public static boolean isCommand(String command, String message)
{
String cmd = message.split(" ")[0];
//System.out.println("Len: " + cmd.replace("!", "").replace("/", "").length() + " vs. " + command.length());
if (cmd.replace("!", "").replace("/", "").length() != command.length())
return false;
//System.out.println("Ends: " + cmd.substring(cmd.replace("!", "/").lastIndexOf("/") + 1, command.length() + cmd.replace("!", "/").lastIndexOf("/") + 1));
if (cmd.toLowerCase().endsWith(command.toLowerCase()) && //Check End
cmd.substring(cmd.replace("!", "/").lastIndexOf("/") + 1, command.length() + cmd.replace("!", "/").lastIndexOf("/") + 1).equalsIgnoreCase(command)) //Check right after trigger
return true;
else
return false;
} | 3 |
private void removeReturnLocal(ReturnBlock ret) {
StructuredBlock pred = getPredecessor(ret);
if (!(pred instanceof InstructionBlock))
return;
Expression instr = ((InstructionBlock) pred).getInstruction();
if (!(instr instanceof StoreInstruction))
return;
Expression retInstr = ret.getInstruction();
if (!(retInstr instanceof LocalLoadOperator && ((StoreInstruction) instr)
.lvalueMatches((LocalLoadOperator) retInstr)))
return;
Expression rvalue = ((StoreInstruction) instr).getSubExpressions()[1];
ret.setInstruction(rvalue);
ret.replace(ret.outer);
} | 4 |
private void startGenerating() {
// check if number CAN be sorted
boolean sortCheck = Lib.checkInput(gui.getTextFields(), gui.getRingNumber());
// if number not sortable throws errorMsg
if (sortCheck) {
// divide fighters
int[] sortingFacts = Lib.PoolDivide(gui.getTextFields(), gui.getRingNumber());
// send in facts and get fighters sorted in correct number ofpools
List<List<String>> allPoolsWithFighters = Lib.poolGenerator(gui.getTextFields(), sortingFacts);
// New FileChooser for saving
gui.newFileChooser();
int k = gui.getFileChooser().showSaveDialog(gui.getFileChooser()); // show
// chooser
// window
try {
if (k == JFileChooser.APPROVE_OPTION) {
// generate sorting
for (int i = 0; i < sortingFacts[2]; i++) {
try {
String[] sortedFighters = (String[]) sortingSystem.newSorting(allPoolsWithFighters.get(i));
pdfGenerator.newPdf(allPoolsWithFighters.get(i), sortedFighters, i, gui.getFileChooser().getSelectedFile().getCanonicalPath(), gui.getTournamentNameField(), gui.getWeightBox(), gui.getGenderBox());
} catch (IllegalArgumentException e) {
gui.errorMsg("Cant sort numbers");
break;
}
}
// initiates successwindow...
gui.startSuccesWindow();
}
} catch (Exception e1) {
gui.errorMsg("Failed to instantiate sorting");
e1.printStackTrace();
}
} else {
gui.errorMsg("You must enter valid numbers" + "\n" + "And fill all textfields" + "\n" + "Please try again");
return;
}
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.