method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
c5e848be-8492-4ebe-ac6c-5a300a101b33
| 7
|
public void ElaboraDate()
{
try {
System.out.println("crea");
PrintWriter writer = new PrintWriter(new FileWriter(heidelDate, false));
for (Document d : documents)
{
for (HeidelTerm ht : d.HeidelTerms)
{
if (ht.Tipo.equals("DATE"))
{
String term = ht.Termine;
if (Arrays.asList(new String[] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"})
.contains(term))
{
term = "ggSettimana";
}
if (Arrays.asList(new String[] {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "Octeober", "November", "December"})
.contains(term))
{
term = "mmAnno";
}
if (Arrays.asList(new String[] {"1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989",
"1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999" })
.contains(term))
{
term = "xxAnno";
}
writer.printf("%s\t%s\n", d.Id, term);
}
}
}
writer.close();
}
catch(IOException ex)
{
}
}
|
1878e1ba-5f54-49fe-85e2-06d1477c5791
| 1
|
public Obuffer decodeFrame(Frame header, SoundStream stream)
throws DecoderException
{
if (!initialized)
{
initialize(header);
}
int layer = header.layer();
output.clear_buffer();
FrameDecoder decoder = retrieveDecoder(header, stream, layer);
decoder.decodeFrame();
output.write_buffer(1);
return output;
}
|
083598eb-a3de-43d9-83d5-2ce033133679
| 9
|
@Override
public void menu(User u) throws MenuExitException {
String menuString = "Configure Transport Action:\r\n";
menuString += "(01) Configure transport name \r\n";
menuString += "(02) Configure target room \r\n";
menuString += "(03) Configure prereq setting\r\n";
menuString += "(04) Configure range \r\n";
menuString += "(05) Configure success action \r\n";
menuString += "(06) configure success message \r\n";
menuString += "(07) Display structure \r\n";
menuString += "(08) save \r\n";
menuString += "Choose from the above. Type 'exit' to exit the menu.\r\n";
PromptForInteger p = new PromptForInteger(u, menuString, 8, 1);
while (p.display()) {
switch (p.getResult()) {
case 1:
this.configActionName(u);
break;
case 2:
this.configTargetRoom(u);
break;
case 3:
this.configActionPrereqSetting(u);
break;
case 4:
this.configActionRange(u);
break;
case 5:
this.configSuccessAction(u);
break;
case 6:
this.configActionSuccessMessage(u);
break;
case 7:
u.broadcast(this.getStructure());
break;
case 8:
this.configActionSave(u);
break;
}
}
u.broadcast("\r\nExiting Transport Configuration Menu.\r\n\r\n");
}
|
8a5d1652-55fb-4fc5-a0a6-f584cbadbfd6
| 6
|
private void loadFromFile(String fileName){
FileInputStream openFile;
ObjectInputStream ois;
try {
openFile = new FileInputStream(fileName);
setTitle("Pathfinder - " + fileName);
ois = new ObjectInputStream(openFile);
String bgImagePath = (String)ois.readObject();
setBg(bgImagePath);
neuronListGraph = (ListGraph<Neuron>)ois.readObject();
//manual counter
int counter = 1;
for(Map.Entry<Neuron, List<Edge>> entry : neuronListGraph.allNeurons.entrySet()){
//current ones
Neuron currentNeuron = entry.getKey();
currentNeuron.setWin(this);
List<Edge> currentNeuronEdges = entry.getValue();
//should be deselected for best user experience imho
currentNeuron.deselect();
//neuron need listeners back
currentNeuron.addListerner();
//paint it
layerPanel.add(currentNeuron, new Integer(counter)); //cant take pure int as second for layer pos
for (Edge<? extends Neuron> currentNeuronEdge : currentNeuronEdges) {
//addline method would be horror to read without this hahaha
Neuron start = currentNeuronEdge.getStart();
Neuron end = currentNeuronEdge.getDestination();
addLine("invokeOnLineClick", lineColor, neuronListGraph, neuronListGraph.getNeuronPair(start, end));
}
counter++;
}
Neuron.selectedNeurons = new ArrayList<>();
Neuron.setSelectedNeuronCount(0);
loadedFromFile = true;
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(win,"Kunde inte återställa all data");
} catch (FileNotFoundException fe) {
JOptionPane.showMessageDialog(win,"Kunde inte hitta filen, eller så har den fel rättigheter");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(win,"IO exception"+ioe.getCause());
ioe.printStackTrace();
}
}
|
b1bbd5dc-2ff0-465a-86a1-8c1cbe95c936
| 6
|
private ArrayList<HashSet> ConstructSetOfSCC(FiniteStateAutomaton dfa){
/* initial state of dfa*/
State init = dfa.getInitialState();
ArrayList<HashSet> setOfScc = new ArrayList<HashSet>();
HashSet<State> scc = new HashSet<State>();
FSAConfiguration config = new FSAConfiguration(init,
null, null, null);
//first visit
DFS(config);
// reset all states
for(State st: dfa.getStates()){
st.colorWhite();
}
//second visit
while (!st.isEmpty()){
State currentState = (State)st.pop();
if (currentState.isWhite()){
DFS(currentState ,dfa, scc);//cambia il nome di sta roba
setOfScc.add(scc);
System.out.println("giro");
if(scc.size()>0)
for (State s : scc)
SCCofState.put(s, scc);
scc = new HashSet<State>();
}
}
// reset all states
for(State st: dfa.getStates()){
st.colorWhite();
}
return setOfScc;
}
|
abe4c3e3-a6d5-4e88-a447-c5bb42be4f82
| 1
|
public void startWriting(String filename, int width, int widthC)
{
try
{
dos = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(filename)));
oneLineY = new byte[width];
oneLineCbCr = new byte[widthC];
}
catch (Exception e)
{
e.printStackTrace();
}
}
|
82ce256a-7e4c-466a-b010-90078ecf2310
| 6
|
public static void main (String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (InstantiationException ie) {
System.out.println(ie);
} catch (IllegalAccessException iae) {
System.out.println(iae);
} catch (UnsupportedLookAndFeelException ulafe) {
System.out.println(ulafe);
}
frameMain = new JFrame ("Calendar"); //Frame creation.
frameMain.setSize(320, 375); //Setting to 400x400 pixels.
pane = frameMain.getContentPane(); //Receive content pane.
pane.setLayout(null); //Apply single null layout.
frameMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Complete build on X.
labelMonth = new JLabel("January");
labelYear = new JLabel ("Year:");
comboYear = new JComboBox();
buttonPrevious = new JButton ("<<");
buttonNext = new JButton (">>");
tableModelCalendar = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
tableCalendar = new JTable(tableModelCalendar);
scrollCalendar = new JScrollPane(tableCalendar);
panelCalendar = new JPanel(null);
//Setting borderline.
panelCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
//Register action listeners.
buttonPrevious.addActionListener(new buttonPrevious_Action());
buttonNext.addActionListener(new buttonPrevious_Action());
comboYear.addActionListener(new comboYear_Action());
//App controls to pane.
pane.add(panelCalendar);
panelCalendar.add(labelMonth);
panelCalendar.add(labelYear);
panelCalendar.add(comboYear);
panelCalendar.add(buttonPrevious);
panelCalendar.add(buttonNext);
panelCalendar.add(scrollCalendar);
//Set boundaries.
panelCalendar.setBounds(0, 0, 320, 335);
labelMonth.setBounds(160-labelMonth.getPreferredSize().width/2, 25, 100, 25);
labelYear.setBounds(10, 305, 80, 20);
buttonPrevious.setBounds(10, 25, 50, 25);
buttonNext.setBounds(260, 25, 50, 25);
scrollCalendar.setBounds(10, 50, 300, 250);
//Make frame visible.
frameMain.setResizable(false);
frameMain.setVisible(true);
//Get real month/year.
GregorianCalendar cal = new GregorianCalendar(); //Create calendar.
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
//Add headers.
String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
for (int i=0; i<7; i++) {
tableModelCalendar.addColumn(headers[i]);
}
//Set background color.
tableCalendar.getParent().setBackground(tableCalendar.getBackground());
//No resize or reordering.
tableCalendar.getTableHeader().setResizingAllowed(false);
tableCalendar.getTableHeader().setReorderingAllowed(false);
//Single cell selection.
tableCalendar.setColumnSelectionAllowed(true);
tableCalendar.setRowSelectionAllowed(true);
tableCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Set row and column count.
tableCalendar.setRowHeight(38);
tableModelCalendar.setColumnCount(7);
tableModelCalendar.setRowCount(6);
//Populating table...
for (int i=realYear-100; i<=realYear+100; i++) {
comboYear.addItem(String.valueOf(i));
}
refreshCalendar (realMonth, realYear);
}
|
20b5d1e2-e981-4186-9ee4-bc313732e456
| 5
|
public JSONObject increment(String key) throws JSONException {
Object value = opt(key);
if (value == null) {
put(key, 1);
} else if (value instanceof Integer) {
put(key, ((Integer)value).intValue() + 1);
} else if (value instanceof Long) {
put(key, ((Long)value).longValue() + 1);
} else if (value instanceof Double) {
put(key, ((Double)value).doubleValue() + 1);
} else if (value instanceof Float) {
put(key, ((Float)value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
}
|
250820f8-2d77-4b17-8155-d023977866b6
| 6
|
private void onClick(){
String outDate;
int timeLimit = 0;
// Must check out at least one book
if (callNumbers.size() == 0) {
popMsg("Need to enter some books!");
return;
}
try {
timeLimit = LibraryDB.getManager().getTimeLimit(bid);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
// Find the current date
Date date = new Date();
Calendar currentCal = new GregorianCalendar(TimeZone.getTimeZone("PST")) ;
currentCal.setTime(date);
outDate = calendarToString(currentCal);
// currentCal will now store the due date
currentCal.add(Calendar.DATE, timeLimit);
for (int i=0;i<callNumbers.size();i++){
Borrowing b = new Borrowing(0,bid,callNumbers.get(i),copyNos.get(i),outDate,null);
try {
// create new tuple in borrowing table
LibraryDB.getManager().insertBorrowing(b);
// set the status of the checked out books to "out"
LibraryDB.getManager().updateBookCopy(b.getCallNumber(), b.getCopyNo(), BookCopy.OUT);
} catch (SQLException e1) {
determineError(e1);
return;
}
}
String message = "These books are due on " + calendarToString(currentCal) + " :\n";
for (int i=0;i<callNumbers.size();i++){
message += callNumbers.get(i) + " C" + copyNos.get(i) + "\n";
}
// deletes the holdrequests
for (String hid: hids){
System.out.println(hid);
LibraryDB.getManager().deleteHoldRequest(hid);
}
popMsg(message);
this.dispose();
}
|
869746a0-06c6-44f8-9321-6f1bd36e8acc
| 8
|
public void continueAfterBluffCall(boolean bluffCalled, PlayerWithChoices bluffCaller) {
if(bluffCalled){
playerUI.closeAllOtherPopups();
//TODO let player choose to not show they have the card
if(player.has(action.cardTypeRequired())){
playerUI.replaceCard(action.cardTypeRequired());
//Need special case for if bluff caller is also target of assassin... - this person is eliminated now!
if(action instanceof AssassinAction && action.targetedPlayers().get(0).equals(bluffCaller)){
bluffCaller.getFirstCard().reveal();
bluffCaller.getSecondCard().reveal();
playerUI.advanceToNextPlayer();
}else{
bluffCaller.revealACard(false);
completeAction();
}
}else{
player.revealACard();
}
}else{
if(--numNeedingToNotCallBluff <= 0){
if(action.defensesThatCanBlock().isEmpty()){ //TODO check to see if there are players who can block??
numNeedingToNotBlock = 0;
continueAction(null,null);
}else{
numNeedingToNotBlock = action.targetedPlayers().size();
playersWhoCanBlock = new ArrayList<PlayerWithChoices>();
for(Player respondingPlayer : action.targetedPlayers()){
if(respondingPlayer.eliminated()) continue; //Eliminated player can't still block foreign aid
PlayerWithChoices respondingPlayerWithChoice = (PlayerWithChoices) respondingPlayer;
playersWhoCanBlock.add(respondingPlayerWithChoice);
respondingPlayerWithChoice.checkIfWantToBlock(ActionButton.this, action.defensesThatCanBlock());
}
}
}
}
}
|
4c661aa0-a8d6-4307-9719-b9672c9ea7ff
| 2
|
public static boolean isValidEmail(String email) {
if (email == null) return false;
return email.matches("[\\w-_.]+@[\\w-.]+\\.[a-zA-Z]{2,4}")
&& email.length() <= 100;
}
|
2c95637c-8a25-4c79-a213-b86c4c423920
| 3
|
public boolean addUserIntoQueue(User user, Playmode playmode){
boolean playmodeExists = gameQueueMap.get(playmode.getPmID()) != null;
if(playmodeExists){
Queue<User> gameQueue = gameQueueMap.get(playmode.getPmID());
gameQueue.add(user);
int requiredPlayer = playmode.getNeededPlayerCount();
if(gameQueue.size() >= requiredPlayer){
User[] gameUser = new User[requiredPlayer];
for (int i = 0; i < gameUser.length; i++) {
gameUser[i]=gameQueue.poll();
leaveQueues(gameUser[i]);
}
GameManager.getInstance().createNewGame(playmode, gameUser);
}
}
return playmodeExists;
}
|
1cf450a5-bd0b-4467-a708-c992ba862ae9
| 3
|
public void addNewPiece() {
count++;
score++;
if (testMode && count == TEST_LIMIT+1) {
stopGame();
return;
}
// commit things the way they are
board.commit();
currentPiece = null;
Piece piece = pickNextPiece();
// Center it up at the top
int px = (board.getWidth() - piece.getWidth())/2;
int py = board.getHeight() - piece.getHeight();
// add the new piece to be in play
int result = setCurrent(piece, px, py);
// This probably never happens, since
// the blocks at the top allow space
// for new pieces to at least be added.
if (result>Board.PLACE_ROW_FILLED) {
stopGame();
}
updateCounters();
}
|
24ff37a8-9304-47b3-b3e1-703f4daffe39
| 1
|
@Test
public void isDeserializedCorrectly() throws IOException {
SubscribeMessage msg = new SubscribeMessage("/test/topic/1",
QoS.AT_LEAST_ONCE);
msg.addTopic("/test/topic/2", QoS.AT_MOST_ONCE);
byte[] data = msg.toBytes();
MessageInputStream in = new MessageInputStream(
new ByteArrayInputStream(data));
SubscribeMessage smsg=null;
try {
smsg=(SubscribeMessage)in.readMessage();
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
List<String> topics=smsg.getTopics();
List<QoS> topicQoSs=smsg.getTopicQoSs();
Assert.assertEquals(2, topics.size());
Assert.assertEquals(2, topicQoSs.size());
Assert.assertEquals("/test/topic/1", topics.get(0));
Assert.assertEquals("/test/topic/2", topics.get(1));
Assert.assertEquals(QoS.AT_LEAST_ONCE, topicQoSs.get(0));
Assert.assertEquals(QoS.AT_MOST_ONCE, topicQoSs.get(1));
}
|
1992ed4a-2e76-424f-933b-124e94f468f8
| 7
|
private ArrayList<Square> createRow(String line)
{
// Initialize the row
ArrayList<Square> row = new ArrayList<Square>();
for(int x = 0; x < line.length(); x++)
{
// For each character in the string, create a Square
String s = line.substring(x,x+1);
Square newSquare = new Square(0);
boolean squareSet = false;
// check if it's a zero string
for(int y = 0; y < zeroStrings.length; y++)
{
if(s.equals(zeroStrings[y]))
{
squareSet = true;
}
}
// check if it's an existing color
if(!squareSet)
{
for(int y = 0; y < colorList.size(); y++)
{
if(s.equals(colorList.get(y)))
{
newSquare.setColor(y+1);
squareSet = true;
}
}
}
// else add it as a new color
if(!squareSet)
{
colorList.add(s);
newSquare.setColor(colorList.size());
}
// add the Square to the row
row.add(newSquare);
}
return row;
}
|
3786068f-81b1-469d-b6b9-d58113bf9171
| 8
|
public DotExpression(ColorMapper colorMapper, String html, int defaultFontSize, HtmlColor color, String fontFamily,
int style, FileFormat fileFormat) {
if (html.contains("\n")) {
throw new IllegalArgumentException(html);
}
this.colorMapper = colorMapper;
this.fontFamily = fontFamily;
this.normalFont = new UFont("SansSerif", Font.PLAIN, defaultFontSize);
this.fontConfiguration = new FontConfiguration(normalFont, color);
this.fileFormat = fileFormat;
if ((style & Font.ITALIC) != 0) {
html = "<i>" + html;
}
if ((style & Font.BOLD) != 0) {
html = "<b>" + html;
}
html = html.replaceAll(" \\<[uU]\\>", "<u>");
html = html.replaceAll("\\</[uU]\\> ", "</u>");
underline = html.contains("<u>") || html.contains("<U>");
final Splitter splitter = new Splitter(html);
List<HtmlCommand> htmlCommands = splitter.getHtmlCommands(false);
for (HtmlCommand command : htmlCommands) {
if (command instanceof Img) {
hasImg = true;
}
}
if (hasImg) {
htmlCommands = splitter.getHtmlCommands(true);
sb.append("<TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"0\">");
for (Collection<HtmlCommand> cmds : split(htmlCommands)) {
sb.append("<TR><TD><TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"0\"><TR>");
manageCommands(cmds);
sb.append("</TR></TABLE></TD></TR>");
}
sb.append("</TABLE>");
} else {
manageCommands(htmlCommands);
}
}
|
77480d22-f739-4df4-817e-f820306f7979
| 6
|
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
if (file.toString().endsWith(".zip") || file.toString().endsWith(".jar"))
{
final File dir = new File(Vars.HOME_DIR + "natives/" + file.getFileName().toString().replaceAll(".zip", "").replaceAll(".jar", ""));
if (file.toString().endsWith(".zip"))
{
JavaFileHelper.unzip(file.toFile(), dir);
}
else if (file.toString().endsWith(".jar"))
{
JavaFileHelper.unjar(file.toFile(), dir);
}
try
{
JavaFileHelper.getModsFrom(dir, dir);
}
catch (final Exception e1)
{
e1.printStackTrace();
}
}
else if (!file.toFile().isHidden())
{
System.err.println("Random File: \"" + file + "\"");
}
return FileVisitResult.CONTINUE;
}
|
b3f9eadf-6852-47d6-a979-96924727466e
| 2
|
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
if (!file.toString().contains(
"dynmap" + System.getProperty("file.separator") + "web")) {// Comment out this if to allow copying of files in a folder called dynmap\web
try {
String sFile = file.toString();
copyToNew = Paths.get(fullPath
+ System.getProperty("file.separator")
+ sFile.substring(copyPath.toString().length()));
Files.copy(file, copyToNew);
System.out.println("Copying file " + file + " to " + copyToNew);
} catch (IOException e) {
System.out.println("Copying file " + file
+ " failed to copy to " + copyToNew);
}
} //end of the if to comment out
return CONTINUE;
}
|
beae59e4-8fca-4a59-b48e-c52a903f8560
| 8
|
public void deleteNote() {
int id_noteTmp = -1;
System.out.println("ID :");
id_noteTmp = Integer.parseInt(sc.nextLine());
NoteDB.setConnection(con);
NoteDB note = null;
note = new NoteDB(id_noteTmp);
try {
note.read();
} catch (Exception ex) {
Logger.getLogger(Controler_antho.class.getName()).log(Level.SEVERE, null, ex);
}
if (note.getId_note() != -1) {//client trouvé
String suppression = "";
System.out.println("Object trouvé :");
System.out.println(note.toString());
System.out.println("Supprimer cet object ?");
do {
System.out.println("Choix(oui/non) :");
suppression = sc.nextLine();
if (suppression.equals("oui")) {
try {
note.delete();
System.out.println("Suppression réussis");
} catch (Exception ex) {
Logger.getLogger(Controler_antho.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (suppression.equals("non")) {
System.out.println("Annulation de la suppression");
}
} while (!suppression.equals("oui") && !suppression.equals("non"));
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Controler_antho.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
abc8e0da-65f3-46b8-8c4f-a798eb21a0e0
| 9
|
public final void update() {
chunkUpdates++;
int sx = x;
int sy = y;
int sz = z;
int ex = x + chunkSize;
int ey = y + chunkSize;
int ez = z + chunkSize;
int renderPassType;
for (renderPassType = 0; renderPassType < 2; ++renderPassType) {
dirty[renderPassType] = true;
}
for (renderPassType = 0; renderPassType < 2; ++renderPassType) {
boolean needNextPass = false;
boolean wasRendered = false;
GL11.glNewList(baseListId + renderPassType, GL11.GL_COMPILE);
shapeRenderer.begin();
for (int posX = sx; posX < ex; ++posX) {
for (int posY = sy; posY < ey; ++posY) {
for (int posZ = sz; posZ < ez; ++posZ) {
int tile = level.getTile(posX, posY, posZ);
if (tile > 0) {
Block block = Block.blocks[tile];
if (block.getRenderPass() != renderPassType) {
needNextPass = true;
} else {
wasRendered |= block.render(level, posX, posY, posZ, shapeRenderer);
}
}
}
}
}
shapeRenderer.end();
GL11.glEndList();
if (wasRendered) {
dirty[renderPassType] = false;
}
if (!needNextPass) {
break;
}
}
}
|
e7ca2531-5999-4e67-8d91-af09e5e1c210
| 9
|
public char[] getCurrentIdentifierSource() {
//return the token REAL source (aka unicodes are precomputed)
//START EBAY MOD
if(m_enableFakeIdentifier){
return m_fakeIdentifierProvider.getTokenSource();
}
//END EBAY MOD
char[] result;
if (this.withoutUnicodePtr != 0) {
//0 is used as a fast test flag so the real first char is in position 1
System.arraycopy(
this.withoutUnicodeBuffer,
1,
result = new char[this.withoutUnicodePtr],
0,
this.withoutUnicodePtr);
} else {
int length = this.currentPosition - this.startPosition;
if (length == this.eofPosition) return this.source;
switch (length) { // see OptimizedLength
case 1 :
return optimizedCurrentTokenSource1();
case 2 :
return optimizedCurrentTokenSource2();
case 3 :
return optimizedCurrentTokenSource3();
case 4 :
return optimizedCurrentTokenSource4();
case 5 :
return optimizedCurrentTokenSource5();
case 6 :
return optimizedCurrentTokenSource6();
}
//no optimization
System.arraycopy(this.source, this.startPosition, result = new char[length], 0, length);
}
//newIdentCount++;
return result;
}
|
bc7cfd5b-5bda-4164-ad0a-130313117335
| 5
|
private void authenticate()
{
boolean isValid = false;
String username = "";
while (!isValid) {
synchronized (currentUser.getUsers()) {
try {
msg = (Message)inFromClient.readObject();
username = msg.getMessage();
if (!msg.getType().equals("login")) {
isValid = true;
pass = false;
break;
}
if (!currentUser.getUsers().containsKey(username)) {
currentUser.setUsername(username);
isValid = true;
msg.setType("Success");
msg.setMessage("You are now logged in as : " + username);
outToClient.writeObject(msg);
currentUser.getUsers().put(username, currentUser);
} else {
msg.setType("Fail");
msg.setMessage("Username already in use");//Use error codes?
outToClient.writeObject(msg);
}
} catch (IOException e) {
isValid = true;
pass = false;
} catch (ClassNotFoundException e) {
isValid = true;
pass = false;
}
}
}
}
|
f195c5e6-db5b-4cbf-8dc9-7d73adfd7827
| 4
|
public String terbilang(String nilai){
String temp="";
String temp2="";
int hasilBagi,sisaBagi;
int batas=3;//batas untuk ribuan
int maxBagian = 5;/*untuk menentukan ukuran array, jumlahnya sesuaikan dengan jumlah anggota dari array gradeNilai[] */
String[] gradeNilai={"","ribu","juta","milyar","triliun"};
//cek apakah ada angka 0 didepan ==> 00098, harus diubah menjadi 98
nilai = this.hapusNolDiDepan(nilai);
String[] nilaiTemp = ubahStringKeArray(batas, maxBagian, nilai);
//ubah menjadi bentuk TerbilangSalah
int j = nilai.length();
int banyakBagian = ((j % batas) == 0 ? (j / batas) :Math.round((j / batas) + 0.5f));//menentukan batas array
int h=0;
for(int i = banyakBagian - 1; i >=0; i-- ){
int nilaiSementara = Integer.parseInt(nilaiTemp[h]);
if (nilaiSementara == 1 && i == 1){
temp +="seribu ";}
else {
temp +=this.ubahRatusanKeHuruf(nilaiTemp[h])+" ";
temp += gradeNilai[i]+" ";
}
h++;
}
return temp;
}
|
7dde6a2d-f0a0-474a-8945-a039f694232e
| 9
|
public String sortingMethod(String[] stringList) {
String[] lexi = new String[stringList.length];
System.arraycopy(stringList, 0, lexi, 0, stringList.length);
Arrays.sort(lexi);
int[] original = new int[stringList.length];
int[] lengths = new int[stringList.length];
for (int i = 0; i < lengths.length; i++) {
original[i] = stringList[i].length();
lengths[i] = stringList[i].length();
}
Arrays.sort(lengths);
boolean lex = true;
for (int i = 0; i < lengths.length; i++) {
if (!stringList[i].equals(lexi[i])) {
lex = false;
break;
}
}
boolean len = true;
for (int i = 0; i < lengths.length; i++) {
if (lengths[i] != original[i]) {
len = false;
break;
}
}
if (lex && len) {
return "both";
} else if (lex) {
return "lexicographically";
} else if (len) {
return "lengths";
} else {
return "none";
}
}
|
bf5e5394-4381-4a99-b05e-7e4ab5cb1311
| 5
|
private void clearNode(TrinaryTreeNode<T> node)
{
TrinaryTreeNode<T> parentNode = node.getParentNode();
TrinaryTreeNode<T> leftNode = node.getLeft();
TrinaryTreeNode<T> centerNode = node.getMiddle();
TrinaryTreeNode<T> rightNode = node.getRight();
// clear this node from the parent node
if (parentNode != null)
{
parentNode.clearChildNode(node);
}
node = null;
// delete the root node
if (parentNode == null)
{
rootNode = null;
return;
}
// Add child nodes of this node back to the tree.
if(centerNode != null)
{
insertNode(parentNode, centerNode.getValue());
}
if(leftNode != null)
{
insertNode(parentNode, leftNode.getValue());
}
if(rightNode != null)
{
insertNode(parentNode, rightNode.getValue());
}
}
|
0da0f4eb-7ef6-4224-94d4-9314eaf64aae
| 7
|
private int get_prev_page(Page page) throws JOrbisException {
long begin=offset; //!!!
int ret;
int offst=-1;
while(offst==-1){
begin-=CHUNKSIZE;
if(begin<0)
begin=0;
seek_helper(begin);
while(offset<begin+CHUNKSIZE){
ret=get_next_page(page, begin+CHUNKSIZE-offset);
if(ret==OV_EREAD){ return OV_EREAD; }
if(ret<0){
if(offst == -1)
throw new JOrbisException();
break;
}
else{ offst=ret; }
}
}
seek_helper(offst); //!!!
ret=get_next_page(page, CHUNKSIZE);
if(ret<0){
//System.err.println("Missed page fencepost at end of logical bitstream Exiting");
//System.exit(1);
return OV_EFAULT;
}
return offst;
}
|
ac19e7f8-9d65-4169-b9ec-4bd0f75256d7
| 3
|
public List<String> alloc(String filename, int num_chunks) {
int chunkloc = 1;
String chunk_uuid;
List<String> chunk_uuids = new ArrayList<String>();
for (int i = 0; i < num_chunks; i++) {
chunk_uuid = UUID.randomUUID().toString();
chunk_uuids.add(chunk_uuid);
chunktable.put(chunk_uuid, chunkloc);
chunkloc = chunkloc % num_datanodes + 1;
}
filetable.put(filename, chunk_uuids);
// ӳ䡢Ľӡ
Iterator it = (Iterator) filetable.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<String, List<String>> me = (Entry<String, List<String>> ) it.next();
System.out.println(me.getKey() + "/" + me.getValue());
}
Iterator it2 = chunktable.entrySet().iterator();
while (it2.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<String, List<String>> me2 = (Entry<String, List<String>> ) it2.next();
System.out.println(me2.getKey() + "/" + me2.getValue());
}
return chunk_uuids;
}
|
798c98ca-ae8f-4500-9573-6e60801b4d3c
| 3
|
@Delete
public void deletelo(Intervention ivt) {
String id = (String) getRequest().getAttributes().get("id");
String ivid = (String) getRequest().getAttributes().get("ivid");
System.out.println("id: " + id);
System.out.println("ivid: " + ivid);
System.out.println("Remark: " + ivt.getRemark());
System.out.println("LOC: " + ivt.getLocation().getLatitude() + " "
+ ivt.getLocation().getLongitude());
// long idl = Long.parseLong(id);
try {
EntityManager em = emf.createEntityManager();
User users = em.find(User.class, Long.parseLong(id));
System.out.println(users);
for (Intervention iv : users.getIntervention()) {
if (iv.getId().getId() == Long.parseLong(ivid)) {
System.out.println(iv);
users.getIntervention().remove(iv);
}
}
em.getTransaction().begin();
em.merge(users);
em.getTransaction().commit();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
|
7c0f19ea-4640-4d59-8ef5-e439bccd8ee1
| 0
|
public Node getNode() {return this.hoistedNode;}
|
ff71da9e-c912-4c7f-bb6c-75c0b45c90d1
| 4
|
public void body()
{
initializeResultsFile();
createGridlet(super.get_id(), NUM_GRIDLETS);
// schedule the initial sending of gridlets in the future
// NOTE: if you have many resources and GIS entities, please make sure
// you wait for few minutes to allow GIS to receive registrations from
// resources. Otherwise, the resource does not exist when you submit.
int PAUSE = 10*60; // 10 mins
Random random = new Random();
int init_time = PAUSE + random.nextInt(5*60);
// sends a reminder to itself
super.send(super.get_id(), init_time, GridUserFailureEx03.SUBMIT_GRIDLET);
System.out.println(super.get_name() +
": initial SUBMIT_GRIDLET event will be at clock: " +
init_time + ". Current clock: " + GridSim.clock());
////////////////////////////////////////////////////////////
// Now, we have the framework of the entity:
while (Sim_system.running())
{
Sim_event ev = new Sim_event();
super.sim_get_next(ev); // get the next event in the queue
switch (ev.get_tag())
{
// submit a gridlet
case GridUserFailureEx03.SUBMIT_GRIDLET:
processGridletSubmission(ev); // process the received event
break;
// Receive a gridlet back
case GridSimTags.GRIDLET_RETURN:
processGridletReturn(ev);
break;
case GridSimTags.END_OF_SIMULATION:
System.out.println("\n============== " + super.get_name() +
". Ending simulation...");
break;
default:
System.out.println(super.get_name() +
": Received an event: " + ev.get_tag());
break;
} // switch
} // while
// wait for few seconds before printing the output
super.sim_pause( super.get_id()*2 );
// remove I/O entities created during construction of this entity
super.terminateIOEntities();
// prints the completed gridlets
printGridletList(GridletReceiveList_, super.get_name(), false,
gridletLatencyTime);
} // body()
|
516db38a-4353-41f7-9fe2-a1c31a4790a9
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Position))
return false;
Position other = (Position) obj;
if (facingPosition != other.facingPosition)
return false;
if (xCoord != other.xCoord)
return false;
if (yCoord != other.yCoord)
return false;
return true;
}
|
50e4b78d-7dd4-4855-acda-15c98b11ff88
| 0
|
public void addVertex(Vertex v) {
DoublyLinkedList<Vertex> neighbours = new DoublyLinkedList();
neighbours.insertLast(v);
this.adjacencyList.insert(neighbours);
}
|
12e505e8-7e5d-47c5-b773-ffe73971f890
| 4
|
public static HandshakeBuilder translateHandshakeHttp(byte[] buffer,
int readcount) throws Exception {
HandshakedataImpl1 draft = new HandshakedataImpl1();
ByteBuffer message = ByteBuffer.allocate(readcount);
message.put(buffer, 0, readcount);
byte[] lines = message.array();
int previndex = 0;
int index = findNewLine(lines, previndex);
if (index == lines.length)
throw new Exception("not an http header");
;
String line = new String(lines, previndex, index - previndex);
String[] firstLineTokens = line.split(" ");
// if( firstLineTokens.length != 3)
String path = firstLineTokens[1];
draft.setResourceDescriptor(path);
// TODO Care about resources here like: GET /chat HTTP/1.1
// if ( line.startsWith ( "GET" ) == false )
// if ( line.startsWith ( "HTTP" ) == false )
previndex = index + 2;
index = findNewLine(lines, previndex);
int length = index - previndex;
while (length != 0) {
line = new String(lines, previndex, length);
if (index != previndex) {
String[] pair = line.split(":", 2);
if (pair.length != 2)
throw new Exception("not an http header");
draft.put(pair[0], pair[1].replaceFirst("^ +", ""));
}
previndex = index + 2;
index = findNewLine(lines, previndex);
length = index - previndex;
}
previndex = index + 2;
length = lines.length - previndex;
draft.setContent(ByteBuffer.allocate(length)
.put(lines, previndex, length).array());
return draft;
}
|
2941d96e-ace5-4dbc-bca5-23c65e5bd858
| 6
|
public void draw(Transform transform) {
texture.bind();
updateTextureOffsets(transform);
GL11.glPushMatrix();
GL11.glTranslated(transform.x, transform.y, 0f);
GL11.glScalef(transform.scaleX, transform.scaleY, 0f);
if(transform.flipX) {
GL11.glRotatef(180f, 0, 1, 0);
}
if(transform.centerRotate) {
GL11.glTranslatef(texture.getImageWidth() / 2f, texture.getImageHeight() / 2f, 0);
// Use Math.toDegrees for dope cool spinning effect
GL11.glRotated(transform.rotation, 0, 0, 1);
GL11.glTranslatef(-texture.getImageWidth() / 2f, -texture.getImageHeight() / 2f, 0);
} else {
GL11.glRotated(transform.rotation, 0, 0, 1);
}
GL11.glColor4f(transform.color.x, transform.color.y, transform.color.z, transform.color.w);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(texXOffset, texYOffset);
GL11.glVertex2d(0, 0);
GL11.glTexCoord2f(texWidth, texYOffset);
GL11.glVertex2d(transform.width != 0 ? transform.width : getWidth(), 0);
GL11.glTexCoord2f(texWidth, texHeight);
GL11.glVertex2d(transform.width != 0 ? transform.width : getWidth(), transform.height != 0 ? transform.height : getHeight());
GL11.glTexCoord2f(texXOffset, texHeight);
GL11.glVertex2d(0, transform.height != 0 ? transform.height : getHeight());
}
GL11.glEnd();
GL11.glPopMatrix();
}
|
050cc1a4-2d5e-4838-bc45-67457f9a0522
| 7
|
@Override
public void paint(Graphics graphics) {
_image=_listener.getImage();
if(_image == null){ System.out.println("Houston, we have a problem..."); }
super.paint(graphics);
Dimension sz=getSize();
drawX = 0;
drawY = 0;
drawWidth = sz.width;
drawHeight = sz.height;
// Scale image to fit the window size while maintaining aspect ratio.
// Center the image in the unused space if window width or height too large.
// Note: this only makes sense for cam space.
if (_image != null && getLockAspectRatio()) {
float curasp=sz.width/(float)sz.height;
float tgtasp=getAspectRatio();
if(tgtasp<0)
tgtasp=_image.getWidth()/(float)_image.getHeight();
if(curasp>tgtasp) {
drawWidth = (int)(sz.height*tgtasp);
drawX = (sz.width-drawWidth)/2;
} else if(curasp<tgtasp) {
drawHeight = (int)(sz.width/tgtasp);
drawY = (sz.height-drawHeight)/2;
} else {
}
}
drawImage(graphics, _image, drawX, drawY, drawWidth, drawHeight);
// If requested, draw crosshairs for RawCam, SegCam.
// Crosshairs for SketchGUI are handled in SketchPanel.java.
if (crosshairsEnabled){
graphics.setXORMode(Color.GRAY);
graphics.setColor(Color.WHITE);
((Graphics2D)graphics).setStroke(new BasicStroke(1.0f));
graphics.drawLine(drawX+drawWidth/2,drawY, drawX+drawWidth/2, drawY+drawHeight);
graphics.drawLine(drawX, drawY+drawHeight/2, drawX+drawWidth, drawY+drawHeight/2);
graphics.setPaintMode();
}
}
|
1ae5ef13-445c-4175-aa19-955ebe59db2d
| 2
|
private boolean isColour()
{
ArrayList<Card> handCopy = (ArrayList<Card>) cards.clone();
boolean sameSuits = true;
Card first = handCopy.remove(0);
for (Card card : handCopy)
{
if ( !card.suit.equals(first.suit))
{
sameSuits = false;
break;
}
}
return sameSuits;
}
|
a4794ce4-54c7-41ce-9ef5-a49e08e414b7
| 4
|
public static void testArrays(){
// arrays
// Note: c++ style double var[] does work, but is not preferred
// double[12] does not work, need a new statement
//double[] array = new double[5];
double[] array={8,3,6,2,1};
double total=0;
// for each style statement (only available in >= JDK 1.5
printArray(array);
for (double elem: array){
total+=elem;
}
System.out.println("Total= "+String.valueOf(total));
//passing and returning arrays from methods
double[] reversed= reverse(array);
printArray(reversed);
java.util.Arrays.sort(array);
printArray(array);
// vectors exist too!
Vector v = new Vector(0);
v.addElement(new Double(4.0));
v.addElement(new Double(3.2));
v.addElement(new Double(2.4));
v.addElement(5.6);
v.addElement("test");
println("Vector capacity: "+v.size());
println("First Element: "+v.firstElement()+" Last element: "+v.lastElement());
println(v.contains(3.2));
println(v.elementAt(0));
for(int i=0; i<v.size(); i++){
System.out.print(v.elementAt(i)+"\t");
}
println("");
Enumeration vEnum = v.elements();
while(vEnum.hasMoreElements()){ System.out.print(vEnum.nextElement() + " "); }
System.out.println();
//ArrayList replaces Vector from Java 2
ArrayList a = new ArrayList();
a.add(2);
a.add(3.4);
a.add(7.2);
a.add("string");
for(int i=0; i<a.size(); i++){
println(a.get(i));
}
}
|
2e77170f-9204-4ef1-a01f-a35a6ac75069
| 0
|
public Integer getNumber() {
return number;
}
|
7d216d43-b7fa-4fdb-b524-93bd3d4b0adc
| 5
|
public void writeToFile() {
betterMap();
if (!(sortedFile.equals("")|| sortedFile == null)) {
try {
FileWriter fstream = new FileWriter(sortedFile);
BufferedWriter writer = new BufferedWriter(fstream);
for (String s : classSortedMap.keySet()) {
build = new RaceClassBuilder(maxNbrOfLaps, raceTime, driverAttributes);
build.writeResult(classSortedMap.get(s));
writer.write(build.toString());
}
build = new RaceClassBuilder(maxNbrOfLaps, raceTime, driverAttributes);
if (noClass.size() > 0) {
build.writeResult(noClass);
}
writer.write(build.toString());
writer.close();
} catch (Exception e) {
System.err.println("Error: Misslyckades med att skriva den sorterade filen");
e.printStackTrace();
System.exit(1);
}
} else {
}
}
|
6ac7c21d-1721-4908-b83d-0186fcea8d75
| 1
|
private Type getType(String name) throws BadBytecode {
try {
return Type.get(classPool.get(name));
} catch (NotFoundException e) {
throw new BadBytecode("Could not find class [pos = " + lastPos + "]: " + name);
}
}
|
46ad0583-8574-4b85-8711-3a3cc51dab6a
| 8
|
private void sendToClientFile(IoSession session, String fileName)
throws IOException {
InputStream openStream = null;
try {
URL resource = this.getClass().getClassLoader()
.getResource("flume.properties");
openStream = resource.openStream();
Properties properties = new Properties();
properties.load(openStream);
String flumeHistoryFolderStr = properties
.getProperty("flumeHistoryFolder");
File zipFile = new File(flumeHistoryFolderStr + "/" + fileName);
if (!zipFile.exists()) {
throw new RuntimeException("can't not found the flumeFolder :"
+ flumeHistoryFolderStr);
}
if (!zipFile.isFile()) {
throw new RuntimeException("flumeFolder '"
+ flumeHistoryFolderStr + "' is not a file!");
}
FileInputStream fin = null;
FileChannel fc = null;
try {
fin = new FileInputStream(zipFile);
fc = fin.getChannel();
ByteBuffer bb = ByteBuffer.allocate(2048 * 1000);
while (true) {
// 不间断发送会导致buffer异常
Thread.sleep(5);
bb.clear();
int i = fc.read(bb);
if (i == -1) {
break;
}
IoBuffer ib = IoBuffer.wrap(bb);
bb.flip();
session.write(ib);
}
} finally {
if (null != fc) {
fc.close();
}
if (null != fin) {
fin.close();
}
}
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
if (null != openStream) {
openStream.close();
}
}
}
|
2edcf09f-46b3-4877-a66f-0a5557c068ce
| 9
|
public static void main(String[] args) throws InterruptedException {
if (args.length != 2) {
printUsage();
System.exit(1);
} else {
if (args[0] != null && args[0].length() > 0) {
String filename = args[0];
Properties properties = loadProperties(filename);
if (properties == null) {
System.err.println("Error while loading the Properties file. Please check the messages above and try again");
System.exit(2);
} else {
if (args[1] != null && args[1].length() == 2) {
String mode = args[1].substring(1).toLowerCase();
if ("t".equals(mode)) {
runTests(filename);
} else if ("i".equals(mode)) {
runIndexer(properties);
} else if ("b".equals(mode)) {
runTests(filename);
runIndexer(properties);
} else {
System.err.println("Invalid mode specified!");
printUsage();
System.exit(4);
}
} else {
System.err.println("Invalid or no mode specified!");
printUsage();
System.exit(5);
}
}
} else {
System.err.println("The provided properties filename is empty or could not be read");
printUsage();
System.exit(3);
}
}
}
|
5f0b275f-5e8d-4369-aad1-1277a9738119
| 9
|
public static long playerNameToInt64(String s) {
long l = 0L;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
l *= 37L;
if (c >= 'A' && c <= 'Z')
l += (1 + c) - 65;
else if (c >= 'a' && c <= 'z')
l += (1 + c) - 97;
else if (c >= '0' && c <= '9')
l += (27 + c) - 48;
}
while (l % 37L == 0L && l != 0L)
l /= 37L;
return l;
}
|
b9c5969c-ef72-482e-867e-af866f876156
| 1
|
private static String getExtension(String filename) {
int index = filename.lastIndexOf(Preferences.EXTENSION_SEPARATOR);
if (index == -1) {
return null;
} else {
return filename.substring(index + 1, filename.length());
}
}
|
9df058c6-afd4-48e2-adbc-5b870687b18c
| 1
|
public boolean isEmpty(){
if(root == null)
return true;
return false;
}
|
306161ca-6f73-4550-94b9-2268574fc819
| 7
|
@Override
public void actionPerformed(ActionEvent e)
{
Object parent = e.getSource();
if (parent instanceof JButton)
{
JButton button = (JButton) parent;
String name = button.getText();
if (name.equals ("New Game"))
gui.reset();
else if (name.equals("Pause"))
StatsPanel.this.stopTimer ();
else if (name.equals ("Resume"))
{
if (gui.board.winner == 0)
StatsPanel.this.startTimer ();
else
gui.putWinner(-turn);
}
else if (name.equals("Resign"))
gui.putWinner (-turn);
else if (name.equals("Exit"))
gui.close ();
}
}
|
226077bb-494e-4eed-a9bb-d0f3eb7e4684
| 2
|
private void createNpcs(){
HashSet<String> npcPaths;
try {
npcPaths = KvReader.getKvFiles("./npcs");
} catch (IOException e){
e.printStackTrace(System.err);
return;
}
for(String s : npcPaths){
HashMap<String, String> npcAttributes = KvReader.readFile(s);
npcs.put(npcAttributes.get("name"), new NPC(this, npcAttributes));
}
}
|
d2b277a0-1fa2-41ae-9ba4-1b8e512d7dd1
| 4
|
public void accioBotoAccepta()
{
try
{
String contrasenya_nova_introduida = new String( contrasenya_nova.getPassword() );
if ( !contrasenya_nova_introduida.equals( new String( confirma_contrasenya_nova.getPassword() ) ) )
{
VistaDialeg dialeg = new VistaDialeg();
String[] botons = { "Accepta" };
String valor_seleccionat = dialeg.setDialeg( "Error", "Les dues contrasenyes no coincideixen.", botons,
JOptionPane.WARNING_MESSAGE );
}
else if ( contrasenya_nova_introduida.equals( new String( "" ) ) )
{
VistaDialeg dialeg = new VistaDialeg();
String[] botons = { "Accepta" };
String valor_seleccionat = dialeg.setDialeg( "Error", "Has d'introduir una contrasenya nova.", botons,
JOptionPane.WARNING_MESSAGE );
}
else
{
PresentacioCtrl.getInstancia()
.canviaContrasenyaJugadorPrincipal( new String( contrasenya_actual.getPassword() ),
contrasenya_nova_introduida );
PresentacioCtrl.getInstancia().guardaJugadorPrincipal();
PresentacioCtrl.getInstancia().vistaCanviaContrasenyaAMenuPrincipal();
}
}
catch ( IllegalArgumentException excepcio )
{
VistaDialeg dialeg = new VistaDialeg();
String[] botons = { "Accepta" };
String valor_seleccionat =
dialeg.setDialeg( "Error", excepcio.getMessage(), botons, JOptionPane.WARNING_MESSAGE );
}
catch ( Exception e )
{
VistaDialeg dialeg = new VistaDialeg();
String[] botons = { "Accepta" };
String valor_seleccionat = dialeg.setDialeg( "Error", "Error al guardar el fitxer d'usuari.", botons,
JOptionPane.ERROR_MESSAGE );
}
}
|
8aedb392-237a-444b-b980-bfdeba3e0783
| 4
|
private void updateFile(Vector stuList) {
//for some reason FileInputStream won't recognize a file unless the explicit file path is included
//is there a way to remedy this? EasyReader doesn't require this extra info
File file = new File(
"/Users/Shelley/Documents/DiningHallSeating/DHS/DiningHallSeating/Data/"
+ "Students0910.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
//regular expression (it matches one or more whitespace characters)
Pattern splitter = Pattern.compile("\\s+");
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
StringBuilder fileContent = new StringBuilder();
String first = br.readLine(); //takes column headings out of the loop but still adds them to the edited file
fileContent.append(first);
fileContent.append("\n");
int count = 0;
while ((str = br.readLine()) != null) {
System.out.println(str);
//returns an array of the line split into elements by whitespace
String parts[] = splitter.split(str);
if (parts.length > 0) {
if (parts[0].charAt(0) == '*') { // do not change lastTable value for day students
String newLine = parts[0] + " " + parts[1] + " "
+ parts[2] + " " + parts[3] + " " + parts[4]
+ " " + parts[5] + " " + parts[6] + " "
+ parts[7] + " " + parts[8] + " " + parts[9]
+ " " + parts[10] + " " + parts[11] + " "
+ parts[12] + " " + parts[13] + " " + parts[14]
+ " " + parts[15] + " " + parts[16];
System.out.println(newLine);
fileContent.append(newLine);
fileContent.append("\n");
} else {
Student stu = (Student) stuList.get(count);
//replace old table values with new ones
parts[14] = String.valueOf(stu.getTableNum());
parts[15] = String.valueOf(stu.getLastTableOne());
parts[16] = String.valueOf(stu.getLastTableTwo());
System.out.println("This student's last table was: "
+ parts[14]);
String newLine = parts[0] + " " + parts[1] + " "
+ parts[2] + " " + parts[3] + " " + parts[4]
+ " " + parts[5] + " " + parts[6] + " "
+ parts[7] + " " + parts[8] + " " + parts[9]
+ " " + parts[10] + " " + parts[11] + " "
+ parts[12] + " " + parts[13] + " " + parts[14]
+ " " + parts[15] + " " + parts[16];
System.out.println(newLine);
fileContent.append(newLine);
fileContent.append("\n");
count++; //the count is only incremented for boarding students
}
}
}
FileWriter writer = new FileWriter(
"/Users/Shelley/Documents/DiningHallSeating/DHS/DiningHallSeating/Data"
+ "Students0910.txt");
BufferedWriter bwrite = new BufferedWriter(writer);
bwrite.write(fileContent.toString());
bwrite.close();
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
|
e2405ba8-391f-4f14-ace3-7eb03e2a9dbd
| 7
|
public static int requestBuy(Player theCustomer,Field field) {
Object[] options = new Object[2];
options[0] = "Køb stedet";
options[1] = "Køb ikke";
String name="";
String type="";
int price=0;
int ftype=-1;
Brewery b = null;
ShippingLines sh = null;
Street st = null;
if (field.getClass()==Brewery.class) {
b = (Brewery)field;
name=b.Name;
ftype=0;
type="Bryggeriet";
price = b.Price;
}else if(field.getClass()==ShippingLines.class) {
sh = (ShippingLines)field;
name=sh.Name+" ("+sh.SubName+")";
type="Redderiet";
ftype=1;
price = sh.Price;
}else if(field.getClass()==Street.class) {
st = (Street)field;
name=st.Name;
type="Gaden";
ftype=2;
price = st.Price;
}else{
name ="fejl";
type = "fejl";
price = -1;
}
int choice=-1;
//if (theCustomer.GetMoney()>price) {
choice=JOptionPane.showOptionDialog(null, theCustomer.Name+":\n"+type+" '"+name+"' er til salg for "+price+" kr.\nVil du købe stedet?", "Valg",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]);
//}
if (choice==0) {
// User wants to buy
switch (ftype) {
case 0:
// brewery
b.Owner = Game.players.indexOf(theCustomer);
theCustomer.ChangeMoney(-price);
break;
case 1:
// ShippingLines
sh.Owner = Game.players.indexOf(theCustomer);
theCustomer.ChangeMoney(-price);
break;
case 2:
// Street
st.Owner = Game.players.indexOf(theCustomer);
theCustomer.ChangeMoney(-price);
break;
}
}
return choice;
}
|
eaf958c1-c7fb-44dd-8f7a-e97cdb8034e1
| 3
|
public boolean isValidLocation(Location loc) {
return (loc.getX() >= 0 && loc.getX() <= getWidth()
&& loc.getY() >= 0 && loc.getY() <= getHeight());
}
|
836f2b5f-9a93-44d2-8ff2-06932f53ca32
| 8
|
public static WaveReward[] loadWaveRewards(String xmlFilePath){
HashMap<HeroType, HeroData> statsMap = new HashMap<>();
NodeList rewardElements = getElements(xmlFilePath, "wave");
List<WaveReward> waveRewards = new ArrayList<>();
for(int i = 0; i < rewardElements.getLength(); i++){
WaveReward reward = new WaveReward();
Element rewardElement = (Element)rewardElements.item(i);
NodeList items = rewardElement.getElementsByTagName("item");
for(int j = 0; j < items.getLength(); j++){
Element itemElement = (Element) items.item(j);
if(itemElement.getParentNode() != rewardElement){
continue;
//THis is a nested item (inside an "exclusive"-node. They will be handled later
}
ItemType itemType = ItemType.valueOf(itemElement.getTextContent());
double probability = itemElement.hasAttribute("probability")?
Double.parseDouble(itemElement.getAttribute("probability"))
: 1;
reward.items.put(itemType, probability);
}
NodeList exclusiveElements = rewardElement.getElementsByTagName("exclusive");
for(int j = 0; j < exclusiveElements.getLength(); j++){
Element exclusiveElement = (Element) exclusiveElements.item(j);
NodeList exlusiveItemElements = exclusiveElement.getElementsByTagName("item");
HashMap<ItemType, Double> exlusiveItemsMap = new HashMap<>();
for(int k = 0; k < exlusiveItemElements.getLength(); k++){
Element exlusiveItemElement = (Element) exlusiveItemElements.item(k);
exlusiveItemsMap.put(
ItemType.valueOf(exlusiveItemElement.getTextContent()),
Double.parseDouble(exlusiveItemElement.getAttribute("probability")));
}
reward.exclusiveItems.add(new WaveReward.ExclusiveItems(exlusiveItemsMap));
}
NodeList towers = rewardElement.getElementsByTagName("tower");
for(int j = 0; j < towers.getLength(); j++){
reward.towers.add(TowerType.valueOf(towers.item(j).getTextContent()));
}
if(rewardElement.getElementsByTagName("money").getLength() > 0);
reward.money += Integer.parseInt(rewardElement.getElementsByTagName("money").item(0).getTextContent());
waveRewards.add(reward);
}
return waveRewards.toArray(new WaveReward[0]);
}
|
efbdc473-e306-42c0-8947-598023e12a71
| 9
|
public static int GCD(int x, int y){
if (x == 0)
return y;
else if (y == 0)
return x;
else if (!isOdd(x) && !isOdd(y)){
x >>= 1;
y >>= 1;
return GCD(x, y) << 1;
} else if (!isOdd(x) && isOdd(y)){
return GCD(x >> 1, y);
} else if (isOdd(x) && !isOdd(y)){
return GCD(x, y >> 1);
} else if (x <= y){
return GCD(x, y-x);
} else
return GCD(x-y, y);
}
|
71e2c437-97f5-4c69-a7ee-fc1fe3dcaa21
| 6
|
public Number getKey() {
if (this.keyList.size() == 0) {
return null;
}
if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
throw new RetrievalIdException("getKey方法只适用于单个主键的表结构,但当前表结构包含多个主键: " + this.keyList);
}
Iterator<Object> keyIterator = this.keyList.get(0).values().iterator();
if (keyIterator.hasNext()) {
Object key = keyIterator.next();
if (!(key instanceof Number)) {
throw new RetrievalIdException("生成的主键非数值类型,无法将[" + (key != null ? key.getClass().getName() : null)
+ "]类型转换为[" + Number.class.getName() + "]类型");
}
return (Number) key;
} else {
throw new RetrievalIdException("无法获取主键,请检查表结构中是否包含主键");
}
}
|
09149fee-68aa-472f-afa8-4bc85e9b4656
| 0
|
public static boolean isApplicable(Object object) {
return object instanceof Automaton;
}
|
a17c1c1e-81a9-45af-b41c-6bdf0ff79beb
| 9
|
public void quickSort(int[] array, int low, int high) {
if (array == null || array.length == 0) {
return;
}
if (high <= low) {
return;
}
//pick the pivot
int middle = low + (high - low) / 2;
int pivot = array[middle];
int i = low, j = high;
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
if (low < j) {
quickSort(array, low, j);
}
if (high > i) {
quickSort(array, i, high);
}
}
|
ff3cce57-574b-4138-98fc-edc27d5399cb
| 5
|
public synchronized void init() {
if (inited) {
return;
}
Object parentTree = library.getObject(entries, "Parent");
if (parentTree instanceof PageTree) {
parent = (PageTree) library.getObject(entries, "Parent");
}
kidsCount = library.getNumber(entries, "Count").intValue();
Vector boxDimensions = (Vector) (library.getObject(entries, "MediaBox"));
if (boxDimensions != null) {
mediaBox = new PRectangle(boxDimensions);
// System.out.println("PageTree - MediaBox " + mediaBox);
}
boxDimensions = (Vector) (library.getObject(entries, "CropBox"));
if (boxDimensions != null) {
cropBox = new PRectangle(boxDimensions);
// System.out.println("PageTree - CropBox " + cropBox);
}
kidsReferences = (Vector) library.getObject(entries, "Kids");
kidsPageAndPages = new Vector(kidsReferences.size());
kidsPageAndPages.setSize(kidsReferences.size());
// Rotation is only respected if child pages do not have their own
// rotation value.
Object tmpRotation = library.getObject(entries, "Rotate");
if (tmpRotation != null) {
rotationFactor = ((Number) tmpRotation).floatValue();
// mark that we have an inheritable value
isRotationFactor = true;
}
inited = true;
}
|
d0e1a7c1-2946-477f-9817-d98ebf7cb62c
| 3
|
public final synchronized char readChar(){
inputType = true;
charType = true;
String word="";
char ch=' ';
if(!this.testFullLine) this.enterLine();
word = nextWord();
if(word.length()!=1)throw new IllegalArgumentException("attempt to read more than one character into type char");
if(!eof)ch = word.charAt(0);
return ch;
}
|
a0cd02f8-16fa-4761-9ba7-67f9501f5e04
| 2
|
public void removeComponent(Component component){
components.remove(component);
if(Renderable.class.isInstance(component)){
renderers.remove((Renderable)component);
}
if(Updatable.class.isInstance(component)){
updaters.remove((Updatable)component);
}
}
|
8e212bd4-ed86-4aed-84e5-c276e6c6b764
| 4
|
private static void displayRegistration(BufferedReader reader, VideoStore videoStore) {
try {
String username = "";
String password = "";
String name;
String creditCard;
String address;
String phone;
while (username.isEmpty()) {
System.out.println("Please enter a username:");
username = reader.readLine();
}
while (password.isEmpty()) {
System.out.println("Please enter a password:");
password = reader.readLine();
System.out.println("Please enter the password again:");
if (!password.equals(reader.readLine())) {
System.out.println("Passwords did not match.");
password = "";
}
}
System.out.println("Please enter your name (optional):");
name = reader.readLine();
System.out.println("Please enter your credit card (optional):");
creditCard = reader.readLine();
System.out.println("Please enter your address (optional):");
address = reader.readLine();
System.out.println("Please enter your phone number (optional):");
phone = reader.readLine();
String result = videoStore.register(username, password, name, creditCard, address, phone);
System.out.println(result);
} catch (Exception e) {
System.out.println("There was an error while registering.");
}
}
|
25e11c77-4643-47ba-8446-13c4e5230b0d
| 0
|
@Override
public void destroy() {
super.destroy();
parent = null;
}
|
c0e98b0c-e4f1-477a-ac02-672c477828fa
| 8
|
private static Path processPoly(Element element, StringTokenizer tokens) throws ParsingException {
int count = 0;
ArrayList pts = new ArrayList();
boolean moved = false;
boolean reasonToBePath = false;
Path path = null;
while (tokens.hasMoreTokens()) {
try {
String nextToken = tokens.nextToken();
if (nextToken.equals("L")) {
float x = Float.parseFloat(tokens.nextToken());
float y = Float.parseFloat(tokens.nextToken());
path.lineTo(x, y);
continue;
}
if (nextToken.equals("z")) {
path.close();
continue;
}
if (nextToken.equals("M")) {
if (!moved) {
moved = true;
float x = Float.parseFloat(tokens.nextToken());
float y = Float.parseFloat(tokens.nextToken());
path = new Path(x, y);
continue;
}
reasonToBePath = true;
float x = Float.parseFloat(tokens.nextToken());
float y = Float.parseFloat(tokens.nextToken());
path.startHole(x, y);
continue;
}
if (nextToken.equals("C")) {
reasonToBePath = true;
float cx1 = Float.parseFloat(tokens.nextToken());
float cy1 = Float.parseFloat(tokens.nextToken());
float cx2 = Float.parseFloat(tokens.nextToken());
float cy2 = Float.parseFloat(tokens.nextToken());
float x = Float.parseFloat(tokens.nextToken());
float y = Float.parseFloat(tokens.nextToken());
path.curveTo(x, y, cx1, cy1, cx2, cy2);
continue;
}
} catch (NumberFormatException e) {
throw new ParsingException(element.getAttribute("id"), "Invalid token in points list", e);
}
}
if (!reasonToBePath) {
return null;
}
return path;
}
|
13411656-abb6-4c26-a3f2-953d1f2f765b
| 1
|
public void syncWithGraphics(){
int newRoundTime = graphicsContainer.get().thinktime;
if(newRoundTime != roundTimeMilliseconds){
roundTimeMilliseconds = newRoundTime;
Debug.info("Delay changed to " + newRoundTime);
Debug.guiMessage("Delay changed to " + newRoundTime);
}
}
|
a0a94d9e-70bf-4ce2-a72a-b7ab017926ba
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Marca other = (Marca) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
|
fd74c499-aaf6-4564-a314-bfd295529e81
| 6
|
public static boolean doEntitiesCollide(Entity e1, Entity e2) {
if (e1 == null || e2 == null || e1 instanceof EntityParticle
|| e2 instanceof EntityParticle) {
return false;
}
Area a1 = new Area();
for (int i = 0; i < Render.renderers[e1.getRenderId()].shapes.size(); i++) {
a1.add(new Area(Render.renderers[e1.getRenderId()].shapes.get(i)));
}
Area a2 = new Area();
for (int i = 0; i < Render.renderers[e2.getRenderId()].shapes.size(); i++) {
a2.add(new Area(Render.renderers[e2.getRenderId()].shapes.get(i)));
}
AffineTransform at1 = new AffineTransform();
at1.translate(e1.getX(), e1.getY());
at1.rotate(e1.getTilt());
AffineTransform at2 = new AffineTransform();
at2.translate(e2.getX(), e2.getY());
at2.rotate(e2.getTilt());
a1.transform(at1);
a2.transform(at2);
a1.intersect(a2);
return !a1.isEmpty();
}
|
0817bfaf-dc44-4502-aad6-a57e4eaaff4d
| 2
|
private static void SimpleBoolIf(Boolean b) {
if (b)
System.out.println("Item is true");
else if (!b)
System.out.println("Item is false");
}
|
75c5cb48-a58d-4cd1-b1d8-9f56b97bbd6e
| 2
|
public void testRemoveIntervalConverterSecurity() {
if (OLD_JDK) {
return;
}
try {
Policy.setPolicy(RESTRICT);
System.setSecurityManager(new SecurityManager());
ConverterManager.getInstance().removeIntervalConverter(StringConverter.INSTANCE);
fail();
} catch (SecurityException ex) {
// ok
} finally {
System.setSecurityManager(null);
Policy.setPolicy(ALLOW);
}
assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length);
}
|
a3f38bef-c4dd-41c0-8d1d-79596429803d
| 1
|
public static void deleteQuizTakenHistory(Quiz quiz) {
try {
String statement = new String("DELETE FROM " + DBTable + " WHERE qid=?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, quiz.quizID);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
|
54d79564-8e34-4504-9686-ff986dd0f9ab
| 8
|
protected static Ptg calcDCount( Ptg[] operands )
{
if( operands.length != 3 )
{
return new PtgErr( PtgErr.ERROR_NA );
}
DB db = getDb( operands[0] );
Criteria crit = getCriteria( operands[2] );
if( (db == null) || (crit == null) )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
int fNum = db.findCol( operands[1].getString().trim() );
if( fNum == -1 )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
int count = 0;
int nrow = db.getNRows();
// this is the colname to match
String colname = operands[1].getValue().toString();
for( int i = 0; i < nrow; i++ )
{ // loop thru all db rows
// check if current row passes criteria requirements
try
{
Ptg[] rr = db.getRow( i );
/* "passes" means that there is a matching
* cell in the row of the data db cells
*
*/
if( crit.passes( colname, rr, db ) )
{
// passes; now do action
Ptg cx = db.getCell( i, fNum );
String vtx = cx.getValue().toString();
if( vtx != null )
{
Double.parseDouble( vtx );
count++; // if it can be parsed into a number, increment count
}
}
}
catch( NumberFormatException e )
{
}
}
return new PtgNumber( count );
}
|
885f4392-6baf-4964-852e-4fa809be803e
| 8
|
private void updateCurSpot (final char[][] newMap,
final boolean[][] newIsFalling, final Point pos) {
final char curSpot = getNewSpot(pos, DIRECT_NONE);
if (curSpot == ROCK) {
final Point newPosOfRock = new Point(pos);
boolean isRockMoved = true;
if (fallDownTest(pos)) {
// Spot under the rock is empty, rock will fall down
moveSpot(newMap, pos, DIRECT_DOWN);
movePos(newPosOfRock, DIRECT_DOWN);
} else if (slideRightDownTest(pos)) {
// Rock falls to the right down
moveSpot(newMap, pos, DIRECT_RIGHTDOWN);
movePos(newPosOfRock, DIRECT_RIGHTDOWN);
} else if (slideLeftDownTest(pos)) {
// Rock falls to the left down
moveSpot(newMap, pos, DIRECT_LEFTDOWN);
movePos(newPosOfRock, DIRECT_LEFTDOWN);
} else if (minerCrushedTest(pos)) {
// The miner is crushed. So do not move rock, and gameSt over.
setSpot(newMap, pos, DIRECT_NONE, curSpot);
isRockMoved = false;
gameOver(STATE_FAILED);
} else {
// Rock do not move
setSpot(newMap, pos, DIRECT_NONE, curSpot);
isRockMoved = false;
} // if (fallDownTest(minerPos)) {
if (isRockMoved) {
// If the rock is falling down, record it.
newIsFalling[newPosOfRock.x][newPosOfRock.y] = true;
}
} else if (curSpot == LIFT) {
if (noGoldTest()) {
// All golds are collected, lift opens
setSpot(newMap, pos, DIRECT_NONE, OPEN);
} else {
// Lift remains
setSpot(newMap, pos, DIRECT_NONE, curSpot);
}
} else {
// All other item remains
setSpot(newMap, pos, DIRECT_NONE, curSpot);
}
}
|
c3c3b852-fe65-4132-9a64-4662f73abbbf
| 5
|
public void run() {
System.out.println("ApiRequestor " + name + " starting.");
try {
for (int i = 0; i < repeatCount; i++) {
final String testPhrase = name + "-" + Integer.toString(i + 1);
final String script = (name.equals("Long"))
? "(catch-task-processor-termination-quietly (progn (do-assertions (assertion))\n"
+ " \"" + testPhrase + "\"))"
: "(catch-task-processor-termination-quietly (progn (cdotimes (x "
+ durationFactor + "))\n" + " \"" + testPhrase + "\"))";
worker = new DefaultSubLWorkerSynch(script, cycAccess);
final Object answer = worker.getWork();
if (answer.toString().equals(":CANCEL")) {
System.out.println(name + " returned :CANCEL");
done = true;
return;
} else {
System.out.println(name + " iteration " + answer + " done.");
if (!answer.equals(testPhrase)) {
throw new RuntimeException(testPhrase + " not equal to " + answer);
}
}
}
} catch (Throwable e) {
System.out.println("ApiRequestor " + name + " exception: " + e.toString());
e.printStackTrace();
done = true;
return;
}
System.out.println("ApiRequestor " + name + " done.");
done = true;
}
|
6f3ac611-6e7b-4990-88a4-d51fbeda5c1a
| 9
|
public void enemySpawner() {
if(spawnFrame >= spawnTime) {
outerLoop: //Label so we can break from both loops.
for (int i = 0; i < levelEnemyList.size(); i++) {
for (int j = 0; j < levelEnemyList.get(i).length; j++) {
if(!levelEnemyList.get(i)[j].inGame && !levelEnemyList.get(i)[j].isDead) {
levelEnemyList.get(i)[j].spawnEnemy(levelEnemyType.get(i)[j]);
if(j == levelEnemyList.get(i).length - 1) {
if(!newWave[i]) {
if(myWaves != 0) myWaves -= 1;
spawnFrame = nextWaveWaitTime;
}
newWave[i] = true;
}
break outerLoop;
}
}
}
if(spawnFrame > 0 ) {
spawnFrame = 0;
}
}
else {
spawnFrame += 1;
}
}
|
8b4dc5c9-0164-4b42-924f-c233582e432e
| 0
|
protected Venue() {
super(Venue.class.getSimpleName());
}
|
ba6cc84a-404c-49c8-aa72-a15e33d38619
| 7
|
private void getImage(JPanel panel, Class figure) {
if (figure==Oval.class) {
try {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(ClassLoader.getSystemResource("oval.jpg"))));
panel.add(label);
} catch (IOException | IllegalArgumentException e) {
ErrorLogger.getInstance().log(e.getMessage());
//e.printStackTrace();
JLabel label = new JLabel("OVAL");
panel.add(label);
}
} else if (figure==Rectangle.class) {
try {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(ClassLoader.getSystemResource("rect.jpg"))));
panel.add(label);
} catch (IOException | IllegalArgumentException e) {
ErrorLogger.getInstance().log(e.getMessage());
//e.printStackTrace();
JLabel label = new JLabel("RECTANGLE");
panel.add(label);
}
} else if (figure==RoundedRectangle.class) {
try {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(ClassLoader.getSystemResource("roundrect.jpg"))));
panel.add(label);
} catch (IOException | IllegalArgumentException e) {
ErrorLogger.getInstance().log(e.getMessage());
//e.printStackTrace();
JLabel label = new JLabel("ROUNDED RECTANGLE");
panel.add(label);
}
} else {
try {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(ClassLoader.getSystemResource("Line.jpg"))));
panel.add(label);
} catch (IOException | IllegalArgumentException e) {
ErrorLogger.getInstance().log(e.getMessage());
//e.printStackTrace();
JLabel label = new JLabel("LINE");
panel.add(label);
}
}
}
|
fd70e5c2-6d8e-4e33-a762-66fb05ef6d6c
| 5
|
private void importSpritePlacements(File f) {
InputStream input;
try {
input = new FileInputStream(f);
Yaml yaml = new Yaml();
Map<Integer, Map<Integer, List<Map<String, Integer>>>> spritesMap = (Map<Integer, Map<Integer, List<Map<String, Integer>>>>) yaml
.load(input);
int y, x;
ArrayList<SpriteEntry> area;
for (Map.Entry<Integer, Map<Integer, List<Map<String, Integer>>>> rowEntry : spritesMap
.entrySet()) {
y = rowEntry.getKey();
for (Map.Entry<Integer, List<Map<String, Integer>>> entry : rowEntry
.getValue().entrySet()) {
x = entry.getKey();
area = this.spriteAreas[y][x];
area.clear();
if (entry.getValue() == null)
continue;
for (Map<String, Integer> spe : entry.getValue()) {
area.add(new SpriteEntry(spe.get("X"),
spe.get("Y"), spe.get("NPC ID")));
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
102f4256-5559-4846-ba96-c106eb89aa85
| 0
|
public Integer getQuantita() {
return quantita;
}
|
baa59181-5e49-447b-aef5-0f573d05f874
| 6
|
private void quickSortList(int low, int high)
{
int i = low, j = high;
int temp;
int pivot = numList.get(low + (high - low) / 2);
while (i <= j)
{
while (numList.get(i) < pivot)
i++;
while (numList.get(j) > pivot)
j--;
if (i <= j)
{
temp = numList.get(i);
numList.set(i, numList.get(j));
numList.set(j, temp);
i++;
j--;
}
}
if (low < j)
quickSortList(low, j);
if (i < high)
quickSortList(i, high);
}
|
01f77bee-e028-4940-ac87-8c3be4797b1b
| 1
|
public static String[] getRemoveFileNames(String version) throws IOException {
String s = OberienURL.get(version);
String[] fileNames = s.substring(s.indexOf("[remove]")+7, s.indexOf("[/remove]")).split("\n");
for (int i = 0; i < fileNames.length; i++) {
fileNames[i] = "Game/" + fileNames[i];
}
return fileNames;
}
|
3dc08745-a80d-4316-8994-b456ee851c1d
| 1
|
public ArrayList<LanguageId> getListOfLanguagesAsId() {
ArrayList<LanguageId> languagesList = new ArrayList<LanguageId>();
Set<String> supportedLanguagesKeys = supportedLanguages.keySet();
Iterator<String> iter = supportedLanguagesKeys.iterator();
String key;
while(iter.hasNext()) {
key = iter.next();
languagesList.add(new LanguageId(key, languageResourceBundle.getString(key)));
}
return languagesList;
}
|
0b5eb182-43f4-4858-be3a-d5b68dd403aa
| 2
|
public static double gamma(double x) {
double xcopy = x;
double first = x + lgfGamma + 0.5;
double second = lgfCoeff[0];
double fg = 0.0D;
if (x >= 0.0) {
first = Math.pow(first, x + 0.5) * Math.exp(-first);
for (int i = 1; i <= lgfN; i++)
second += lgfCoeff[i] / ++xcopy;
fg = first * Math.sqrt(2.0 * Math.PI) * second / x;
} else {
fg = -Math.PI / (x * Stat.gamma(-x) * Math.sin(Math.PI * x));
}
return fg;
}
|
f3bd030e-aaa0-4dfd-a69d-760f46635c9e
| 0
|
@Test
public void combine_shouldReturnEmptyList_whenSpecifiedLengthOutOfRange() {
String word = "abcd";
assertEquals("[]", combination.combine(word, 0).toString());
assertEquals("[]", combination.combine(word, 5).toString());
}
|
a2c7cf85-a8e7-4ab0-a6a2-6c6bae6659ab
| 0
|
@Basic
@Column(name = "cantidad")
public int getCantidad() {
return cantidad;
}
|
18194ea5-c4b3-432a-be80-bf9f958ea678
| 4
|
public void readBoards() {
availableBoards.clear();
String s = props.getProperty("mosquito.board.dir");
if (s == null) {
log.error("No board directory specified in conf file.");
}
File dir = new File(s);
if (!dir.isDirectory()) {
log.error("Board directory is invalid " + s);
return;
}
File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".xml");
}
});
/* Board b = new Board(1,1); */
for (int i = 0; i < files.length; i++) {
/*
* try{ b.load(files[i]); availableBoards.add(files[i]);
* }catch(IOException e){ log.error("Problem loading board file " +
* files[i]); } catch(BoardSanityException e){
* log.error("Sanity problem loading board file " +files[i]+". " +
* e); }
*/
availableBoards.add(files[i]);
}
if (availableBoards.size() > 0)
boardFile = availableBoards.get(0);
else
boardFile = null;
}
|
f1efdc82-4dec-44aa-92d6-4b0fb15b017c
| 9
|
static double calculateScore(ArrayList<seed> seedlist, double s) {
double total = 0;
for (int i = 0; i < seedlist.size(); i++) {
double score;
double chance = 0.0;
double totaldis = 0.0;
double difdis = 0.0;
for (int j = 0; j < seedlist.size(); j++) {
if (j != i) {
totaldis = totaldis
+ Math.pow(
distance(seedlist.get(i),
seedlist.get(j)), -2);
}
}
for (int j = 0; j < seedlist.size(); j++) {
if (j != i
&& ((seedlist.get(i).tetraploid && !seedlist.get(j).tetraploid) || (!seedlist
.get(i).tetraploid && seedlist.get(j).tetraploid))) {
difdis = difdis
+ Math.pow(
distance(seedlist.get(i),
seedlist.get(j)), -2);
}
}
//System.out.println(totaldis);
//System.out.println(difdis);
chance = difdis / totaldis;
score = chance + (1 - chance) * s;
seedlist.get(i).score = score;
total = total + score;
}
return total;
}
|
6ef832ac-b66b-4866-b2e4-14c3e96a0b99
| 3
|
public Path getImgPath_SliderMidBtn(Imagetype type) {
Path ret = null;
switch (type) {
case DEFAULT:
ret = this.imgSliderMidBtn_Def;
break;
case FOCUS:
ret = this.imgSliderMidBtn_Foc;
break;
case PRESSED:
ret = this.imgSliderMidBtn_Pre;
break;
default:
throw new IllegalArgumentException();
}
return ret;
}
|
a940aac5-eea1-41c1-8fe9-f552838f24ca
| 1
|
public void setAcknowledgement(Hashtable <String, Integer> Rpg){
for(String key : Rpg.keySet()){
this.acknowledgement.put(key, Rpg.get(key));
}
}
|
c9a7b941-c937-41b2-b8ec-7de712ad94ac
| 5
|
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// game loop
while (true) {
int SX = in.nextInt();
int SY = in.nextInt();
in.nextLine();
Integer max = null;
Integer maxPosition = null;
for (int i = 0; i < 8; i++) {
int current = in.nextInt();
if(max == null || max < current) {
max = current;
maxPosition = i;
}
in.nextLine();
}
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
if(SX == maxPosition) {
System.out.println("FIRE");
}
else {
System.out.println("HOLD"); // either: FIRE (ship is firing its phase cannons) or HOLD (ship is not firing).
}
}
}
|
d5fc98a0-e874-4083-a369-5cc5e5bc9568
| 8
|
public void helper(int[] map, int nthQueen, ArrayList<String[]> result) {
int N = map.length;
if(nthQueen == N){
String[] temp = new String[N];
for(int k = 0; k < N; ++k){
temp[k] = "";
for(int m = 0; m < N; ++m){
if(m == map[k])
temp[k] += "Q";
else {
temp[k] += ".";
}
}
}
result.add(temp);
return;
}
for(int i = 0; i < N; ++i){
if(columnState[i] == 0 && rightDiag[nthQueen + i] == 0 && leftDiag[i - nthQueen + N] == 0){
map[nthQueen] = i;
columnState[i] = 1;
rightDiag[nthQueen + i] = 1;
leftDiag[i - nthQueen + N] = 1;
helper(map, nthQueen + 1, result);
map[nthQueen] = -1;
columnState[i] = 0;
rightDiag[nthQueen + i] = 0;
leftDiag[i - nthQueen + N] = 0;
}else {
continue;
}
}
}
|
52d9f18d-e440-4ff6-b838-e420504a03f1
| 8
|
public char[] readInNeighbors(char[] neighbors, int row, int column){
if(row-1 >= 0){
neighbors[0] = this.grid[row-1][column];
}
if(row-2 >= 0){
neighbors[1] = this.grid[row-2][column];
}
if(row+1 < this.gridSize){
neighbors[2] = this.grid[row+1][column];
}
if(row+2 < this.gridSize){
neighbors[3] = this.grid[row+2][column];
}
if(column-1 >= 0){
neighbors[4] = this.grid[row][column-1];
}
if(column-2 >= 0){
neighbors[5] = this.grid[row][column-2];
}
if(column+1 < this.gridSize){
neighbors[6] = this.grid[row][column+1];
}
if(column+2 < this.gridSize){
neighbors[7] = this.grid[row][column+2];
}
return neighbors;
}
|
93607d51-9943-48ff-b773-5ec356fcdd11
| 4
|
public static String deleteAny(String inString, String charsToDelete) {
if (!hasLength(inString) || !hasLength(charsToDelete)) {
return inString;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
sb.append(c);
}
}
return sb.toString();
}
|
2823f71a-bd89-4309-998b-05ae016c2f2d
| 2
|
public static void main(String[] args) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
try {
// System.setProperty("java.rmi.server.hostname", "24.86.28.122");
System.setProperty("java.rmi.activation.port", "9005");
Registry registry = LocateRegistry.createRegistry(9005);
ServerInterface obj = new ServerInterfaceImpl();
// Registry registry = LocateRegistry.getRegistry();
registry.rebind("ServerInterfaceImpl", obj);
System.out.println("Student server " + obj + " registered");
} catch (Exception ex) {
ex.printStackTrace();
}
}
|
b96b6883-bc8e-432f-876b-129efa86331e
| 1
|
public boolean isReleased() {
if(isDisabled())
return false;
return released;
}
|
5b68083c-40e6-4643-bc84-e4fc916ccd92
| 1
|
public void show() {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
|
c28c22fe-dd1c-42c1-a5e3-aa91d735bd3c
| 2
|
public boolean equals(Object o) {
if (o instanceof RangeType) {
RangeType type = (RangeType) o;
return topType.equals(type.topType)
&& bottomType.equals(type.bottomType);
}
return false;
}
|
671b8814-ab13-4617-8ffa-fffa936d3365
| 2
|
private void sleep(int t) {
int end = (int) (System.currentTimeMillis() + t);
while (System.currentTimeMillis() < end) {
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.getStackTrace();
}
}
}
|
1cfd1b61-f8c6-4b0a-bf5f-c6d85b341f8f
| 0
|
public String getName() {
return name;
}
|
7788f5d6-5faa-4b0d-8b08-b78b9d3a32fb
| 2
|
public Node get(long key) {
Node previous = cache[(int) (key & size - 1)];
for (Node next = previous.next; next != previous; next = next.next) {
if (next.hash == key) {
return next;
}
}
return null;
}
|
4fe0829e-2410-4d5c-ab05-b193ce125d2e
| 3
|
public static Integer stringToIP(String text){
String[] bytes = text.trim().split("\\.");
if(bytes.length != 4)
return null;
try {
int ip = 0;
for(int i=0; i<4; i++){
int b = Integer.parseInt(bytes[i].trim());
ip |= b << (24 - 8*i);
}
return ip;
} catch (NumberFormatException e) {
return null;
}
}
|
7292e54f-f2d5-43e4-a8ce-14ad6dc908b2
| 1
|
private void initialize() {
this.setBounds(100, 100, 800, 600);
sourceImagePanel = new JPanel();
sourceImagePanel.setBounds(10, 30, 293, 447);
getContentPane().add(sourceImagePanel);
imageSourceLabel = new JLabel("");
sourceImagePanel.add(imageSourceLabel);
imageSourceLabel.setIcon(new ImageIcon(IMAGE_SOURCE_SECOND_STEP));
resultImagePanel = new JPanel();
resultImagePanel.setBounds(481, 30, 293, 447);
getContentPane().add(resultImagePanel);
imageResultLable = new JLabel("");
resultImagePanel.add(imageResultLable);
JButton btnProcess = new JButton("Process");
btnProcess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ImageUtil.step3(2f, 16, 2.f, 7.5f, false, IMAGE_SOURCE,
IMAGE_RESULT);
imageResultLable.setIcon(new ImageIcon(IMAGE_RESULT));
update();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
btnProcess.setBounds(346, 79, 89, 23);
getContentPane().add(btnProcess);
update();
}
|
75b8892b-a24d-4088-8bf0-49af0d01ec22
| 2
|
public static int deltaBetweenSequenceNumbers(int earlierSequenceNumber, int laterSequenceNumber) {
int delta = laterSequenceNumber - earlierSequenceNumber;
if(delta < (Packet.MINIMUM_SEQUENCE_NUMBER - Packet.MAXIMUM_SEQUENCE_NUMBER)/2)
delta += Packet.MAXIMUM_SEQUENCE_NUMBER - Packet.MINIMUM_SEQUENCE_NUMBER + 1;
else if(delta > (Packet.MAXIMUM_SEQUENCE_NUMBER - Packet.MINIMUM_SEQUENCE_NUMBER)/2)
delta -= Packet.MAXIMUM_SEQUENCE_NUMBER - Packet.MINIMUM_SEQUENCE_NUMBER + 1;
return delta;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.