method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
48dd9e69-f342-4d33-80e4-83c2acacb42b
| 7
|
public void setEditable(boolean value) {
if (inputText.getParentElement().getParentElement() == null && value) {
tagList.appendChild(inputText.getParentElement());
for (ItemTag<T> itemTag : getInputTags()) {
itemTag.listItem.getFirstChildElement().getNextSiblingElement().getStyle().setVisibility(Visibility.VISIBLE);
itemTag.listItem.addClassName("input-tag-list-item-deletable");
}
} else if (inputText.getParentElement().getParentElement() != null && !value) {
inputText.getParentElement().removeFromParent();
for (ItemTag<T> itemTag : getInputTags()) {
itemTag.listItem.getFirstChildElement().getNextSiblingElement().getStyle().setVisibility(Visibility.HIDDEN);
itemTag.listItem.removeClassName("input-tag-list-item-deletable");
}
}
if(value){
component.removeClassName("input-tag-mode-read-only");
}else{
component.addClassName("input-tag-mode-read-only");
}
}
|
e4c00ed0-a6ce-4c32-a51b-3bdb93d2eb01
| 6
|
public static void main( String args[] ) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for ( javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels() ) {
if ( "Nimbus".equals(info.getName()) ) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch ( ClassNotFoundException ex ) {
java.util.logging.Logger.getLogger(Help.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch ( InstantiationException ex ) {
java.util.logging.Logger.getLogger(Help.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch ( IllegalAccessException ex ) {
java.util.logging.Logger.getLogger(Help.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch ( javax.swing.UnsupportedLookAndFeelException ex ) {
java.util.logging.Logger.getLogger(Help.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Help().setVisible(true);
}
});
}
|
551beff0-014d-493d-a8bc-60fba67deaed
| 5
|
private Player createNewPlayer(Socket cs, Server server, String name, Connection c) throws SQLException, IOException, NoSuchAlgorithmException {
//Offer to create a new player
Telnet.writeLine(cs, "This is your first time logging in, do you want to create a new character? ");
String input = Telnet.readLine(cs);
while(!(input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("no"))) {
Telnet.writeLine(cs, "Yes or No please");
input = Telnet.readLine(cs);
}
if(input.equalsIgnoreCase("no")) {
return null;
}
String password, confirm;
while(true) {
Telnet.write(cs, "Password: <hidden>");
password = Telnet.readLine(cs);
Telnet.write(cs, "<reset>Confirm: <hidden>");
confirm = Telnet.readLine(cs);
if(!password.equals(confirm)) {
Telnet.writeLine(cs, "<reset>Passwords don't match!");
continue;
}
else {
Telnet.write(cs, "<reset>");
break;
}
}
//Hash password, give id, set location to 1, and insert into db
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashByte = digest.digest(password.getBytes("UTF-8"));
String hash = hashToString(hashByte);
PreparedStatement s = c.prepareStatement("INSERT INTO " + MySQLDatabase.playertable + "(username, password, location) VALUES( ?, ?, ?)");
s.setString(1, name);
s.setString(2, hash);
s.setInt(3, 1);
s.executeUpdate();
s = c.prepareStatement("SELECT id FROM " + MySQLDatabase.playertable + " WHERE username = ?");
s.setString(1, name);
ResultSet r = s.executeQuery();
r.next();
int id = r.getInt("id");
//Create the player, and return it
Player p = new Player(name, id, server.getRoomDB().getByID(1), cs);
playerList.add(p);
server.getRoomDB().getByID(1).add(p);
return p;
}
|
b91e52d5-cc84-492f-818e-b0517d3944bc
| 8
|
public int nstStraight(Block set, Material m, BlockFace bf)
{
int x = 1;
int a = gen.nextInt(40);
if (a < 12) {
a = 12;
}
while (x < a) {
int newx = x - 1;
Block otherset = set.getRelative(bf, newx);
Block set1 = otherset.getRelative(BlockFace.WEST, 1);
Block set2 = set1.getRelative(BlockFace.WEST, 1);
Block set3 = otherset.getRelative(BlockFace.EAST, 1);
Block set4 = set3.getRelative(BlockFace.EAST, 1);
Block clr1 = set3.getRelative(BlockFace.UP, 1);
Block clr2 = clr1.getRelative(BlockFace.UP, 1);
Block clr3 = clr2.getRelative(BlockFace.UP, 1);
Block clr4 = set1.getRelative(BlockFace.UP, 1);
Block clr5 = clr4.getRelative(BlockFace.UP, 1);
Block clr6 = clr5.getRelative(BlockFace.UP, 1);
Block clr7 = otherset.getRelative(BlockFace.UP, 1);
Block clr8 = clr7.getRelative(BlockFace.UP, 1);
Block clr9 = clr8.getRelative(BlockFace.UP, 1);
clr1.setType(Material.WATER);
clr2.setType(Material.AIR);
int i1 = gen.nextInt(10);
if (i1 == 3) {
clr3.setType(Material.WEB);
} else if (i1 == 4) {
Block otherside = clr3.getRelative(BlockFace.WEST, 2);
otherside.setType(Material.WEB);
clr3.setType(Material.AIR);
} else {
clr3.setType(Material.AIR);
}
clr6.setType(Material.AIR);
clr4.setType(Material.WATER);
clr5.setType(Material.AIR);
int i3 = gen.nextInt(10);
int i4 = gen.nextInt(5);
if (i3 == 2) {
if (i4 == 2) {
byte flags = 2;
clr7.setTypeIdAndData(97, flags, true);
}
else {
int ran16 = gen.nextInt(3);
clr7.setType(m);
clr7.setData((byte)ran16);
}
}
else {
clr7.setType(Material.WATER);
}
clr8.setType(Material.AIR);
clr9.setType(Material.AIR);
Block side1 = clr7.getRelative(BlockFace.EAST, 1);
int side1ran = gen.nextInt(3);
side1.setType(m);
side1.setData((byte)side1ran);
int other = gen.nextInt(3);
otherset.setType(m);
otherset.setData((byte)other);
int ran2 = gen.nextInt(3);
set3.setType(m);
set3.setData((byte)ran2);
int ran4 = gen.nextInt(3);
set4.setType(m);
set4.setData((byte)ran4);
int ran = gen.nextInt(3);
set1.setType(m);
set1.setData((byte)ran);
int ran1 = gen.nextInt(3);
set2.setType(m);
set2.setData((byte)ran1);
Block set5 = set4.getRelative(BlockFace.UP, 1);
Block set6 = set5.getRelative(BlockFace.UP, 1);
Block set7 = set6.getRelative(BlockFace.UP, 1);
Block set8 = set7.getRelative(BlockFace.UP, 1);
int ran3 = gen.nextInt(3);
int ran7 = gen.nextInt(3);
int ran5 = gen.nextInt(3);
int ran6 = gen.nextInt(3);
set5.setType(m);
set5.setData((byte)ran3);
set6.setType(m);
set6.setData((byte)ran7);
set7.setType(m);
int rtorch1 = gen.nextInt(15);
if (rtorch1 == 1) {
byte flags = 3;
Block torch = set7.getRelative(BlockFace.WEST, 1);
torch.setTypeIdAndData(50, flags, true);
}
set7.setData((byte)ran5);
set8.setType(m);
set8.setData((byte)ran6);
Block set9 = set8.getRelative(BlockFace.WEST, 1);
Block set10 = set9.getRelative(BlockFace.WEST, 1);
Block set11 = set10.getRelative(BlockFace.WEST, 1);
Block set12 = set11.getRelative(BlockFace.WEST, 1);
int ran11 = gen.nextInt(3);
int ran8 = gen.nextInt(3);
int ran9 = gen.nextInt(3);
int ran10 = gen.nextInt(3);
set9.setType(m);
set9.setData((byte)ran11);
set10.setType(m);
set10.setData((byte)ran8);
set11.setType(m);
set11.setData((byte)ran9);
set12.setType(m);
set12.setData((byte)ran10);
Block set13 = set12.getRelative(BlockFace.DOWN, 1);
Block set14 = set13.getRelative(BlockFace.DOWN, 1);
Block set15 = set14.getRelative(BlockFace.DOWN, 1);
Block set16 = set15.getRelative(BlockFace.DOWN, 1);
int ran12 = gen.nextInt(3);
int ran13 = gen.nextInt(3);
int ran14 = gen.nextInt(3);
int ran15 = gen.nextInt(3);
set13.setType(m);
set13.setData((byte)ran12);
set14.setType(m);
set14.setData((byte)ran13);
set15.setType(m);
set15.setData((byte)ran14);
set16.setType(m);
set16.setData((byte)ran15);
if (x == a - 1)
{
int ran16 = gen.nextInt(3);
clr1.setType(m);
clr1.setData((byte)ran16);
clr2.setType(Material.IRON_FENCE);
clr3.setType(Material.IRON_FENCE);
clr6.setType(Material.IRON_FENCE);
int ran17 = gen.nextInt(3);
clr4.setType(m);
clr4.setData((byte)ran17);
clr5.setType(Material.IRON_FENCE);
clr7.setType(Material.IRON_FENCE);
clr7.setType(Material.AIR);
clr8.setType(Material.AIR);
clr9.setType(Material.IRON_FENCE);
}
newx++;
x++;
}
return a;
}
|
aa70479a-8fb5-4594-9ea6-7de16c65e5e4
| 0
|
private ParticipantList() {
textColors = new ArrayList<String>();
textColors.add("0000FF");
textColors.add("FF0000");
textColors.add("00FF00");
textColors.add("FF00FF");
textColors.add("00FFFF");
textColors.add("FFFF00");
}
|
dd2c948d-f9ce-4d3f-a8d6-9f169cbca5c3
| 0
|
public int getIdEncargo() {
return idEncargo;
}
|
4bd2792e-2895-4d41-a234-27ad14d3ddea
| 8
|
private boolean isValidVertMove(int r1, int c1, int r2, int c2) {
if (c1 != c2) {
return false;
}
int step = r1 - r2 < 0 ? 1 : -1;
if (step > 0) {
for (int r = r1 + step; r < r2; r += step) {
if (board[r][c1] != EMPTY) {
return false;
}
}
} else if (step < 0) {
for (int r = r1 + step; r > r2; r += step) {
if (board[r][c1] != EMPTY) {
return false;
}
}
}
return true;
}
|
c9609d46-7e32-4df7-a53a-e8c7694da9a5
| 7
|
public void put(String key, MqttPersistable message) throws MqttPersistenceException {
checkIsOpen();
File file = new File(clientDir, key+MESSAGE_FILE_EXTENSION);
File backupFile = new File(clientDir, key+MESSAGE_FILE_EXTENSION+MESSAGE_BACKUP_FILE_EXTENSION);
if (file.exists()) {
// Backup the existing file so the overwrite can be rolled-back
boolean result = file.renameTo(backupFile);
if (!result) {
backupFile.delete();
file.renameTo(backupFile);
}
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(message.getHeaderBytes(), message.getHeaderOffset(), message.getHeaderLength());
if (message.getPayloadBytes()!=null) {
fos.write(message.getPayloadBytes(), message.getPayloadOffset(), message.getPayloadLength());
}
fos.getFD().sync();
fos.close();
if (backupFile.exists()) {
// The write has completed successfully, delete the backup
backupFile.delete();
}
}
catch (IOException ex) {
throw new MqttPersistenceException(ex);
}
finally {
if (backupFile.exists()) {
// The write has failed - restore the backup
boolean result = backupFile.renameTo(file);
if (!result) {
file.delete();
backupFile.renameTo(file);
}
}
}
}
|
37d53363-ca44-4c02-89cf-bf15ee986e0d
| 0
|
public String getOrder() {
return order;
}
|
d957ea7a-45f9-46ca-9792-125dbd2ee292
| 6
|
static final void method696(int i, int i_0_, int i_1_, int i_2_) {
if (i_2_ == -1007) {
if ((i ^ 0xffffffff) == -1010)
ScriptExecutor.method701(Class327.aClass273_4091, i_1_, i_0_);
else if ((i ^ 0xffffffff) != -1013) {
if (i == 1002)
ScriptExecutor.method701(Class348_Sub40_Sub32.aClass273_9415,
i_1_, i_0_);
else if (i == 1003)
ScriptExecutor.method701(Class348_Sub12.aClass273_6743, i_1_,
i_0_);
else if ((i ^ 0xffffffff) == -1007)
ScriptExecutor.method701(Class239_Sub17.aClass273_6018, i_1_,
i_0_);
} else
ScriptExecutor.method701(Class5_Sub2.aClass273_8356, i_1_, i_0_);
anInt1138++;
}
}
|
dfe19025-1e85-45bc-8698-4793f82f147b
| 9
|
@Override
public void compile(Possession possession, Team home, Team away, TimeStamp timeStamp)
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection("jdbc:mysql://localhost/nba",
"root","*******");
stmt = conn.prepareStatement("INSERT INTO `nba`.`foul` (`foul_type`,`team_foul`) VALUES (?,?);");
stmt.setString(1, this.foulType.getFoulType());
stmt.setBoolean(2, this.foulType.teamFoul());
stmt.executeUpdate();
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
if (rs.next()) {
this.foulID = rs.getInt(1);
} else {
// throw an exception from here
}
stmt = conn.prepareStatement("INSERT INTO `nba`.`foul_possession` (`foul_id`,`possession_id`" +
",`time_of_foul`) VALUES (?,?,?);");
stmt.setInt(1, this.foulID);
stmt.setInt(2, possession.GetPossessionID());
stmt.setDouble(3, timeStamp.GetTimeDouble());
stmt.executeUpdate();
// if (timeStamp instanceof PlayerTimeStamp)
// {
// PlayerTimeStamp ts = (PlayerTimeStamp)timeStamp;
// Player player;
// if (ts.GetTeam().equals(away))
// {
// player = away.GetPlayer(ts.GetPlayer());
// }
// else
// {
// player = home.GetPlayer(ts.GetPlayer());
// }
// stmt = conn.prepareStatement("INSERT INTO `nba`.`technical_foul_player` (`technical_foul_id`,`player_id`" +
// ") VALUES (?,?);");
// stmt.setInt(1, this.technicalID);
// stmt.setInt(2, player.getID());
// stmt.executeUpdate();
// }
}
catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
finally
{
if (rs != null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null)
{
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
cee6fae9-c3ed-4c22-8ab5-90358d1fa9ac
| 8
|
public static int oppgave2()
{
int antallFeil = 0;
DobbeltLenketListe<Integer> liste =
new DobbeltLenketListe<>();
if (!liste.toString().equals("[]"))
{
antallFeil++;
System.out.println("Oppgave 2a: Tom liste skal gi []!");
}
if (!liste.omvendtString().equals("[]"))
{
antallFeil++;
System.out.println
("Oppgave 2b: Tom liste skal gi []!");
}
liste.leggInn(1);
String s = liste.toString();
if (!s.equals("[1]"))
{
antallFeil++;
System.out.println
("Oppgave 2c: Du har " + s + ", skal være [1]!");
}
s = liste.omvendtString();
if (!s.equals("[1]"))
{
antallFeil++;
System.out.println
("Oppgave 2d: Du har " + s + ", skal være [1]!");
}
liste.leggInn(2);
s = liste.toString();
if (!s.equals("[1, 2]"))
{
antallFeil++;
System.out.println
("Oppgave 2e: Du har " + s + ", skal være [1, 2]!");
}
s = liste.omvendtString();
if (!s.equals("[2, 1]"))
{
antallFeil++;
System.out.println
("Oppgave 2f: Du har " + s + ", skal være [2, 1]!");
}
liste.leggInn(3);
liste.leggInn(4);
s = liste.toString();
if (!s.equals("[1, 2, 3, 4]"))
{
antallFeil++;
System.out.println
("Oppgave 2g: Du har " + s + ", skal være [1, 2, 3, 4]!");
}
s = liste.omvendtString();
if (!s.equals("[4, 3, 2, 1]"))
{
antallFeil++;
System.out.println
("Oppgave 2h: Du har " + s + ", skal være [4, 3, 2, 1]!");
}
return antallFeil;
}
|
1dbb784a-5fbd-4901-900b-e1440dd69ac7
| 5
|
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == jTextField1) {
PanelPedidos.this.jTextField1ActionPerformed(evt);
}
else if (evt.getSource() == jBtnDelete) {
PanelPedidos.this.jBtnDeleteActionPerformed(evt);
}
else if (evt.getSource() == jBtnUpdate) {
PanelPedidos.this.jBtnUpdateActionPerformed(evt);
}
else if (evt.getSource() == jButton1) {
PanelPedidos.this.jButton1ActionPerformed(evt);
}
else if (evt.getSource() == jBtnBorrar) {
PanelPedidos.this.jBtnBorrarActionPerformed(evt);
}
}
|
7491334c-0684-44fe-ae3a-655bc454d787
| 5
|
@Override
public void stateChanged(ChangeEvent e) {
if(objPanelMR != null) {
if(e.getSource().equals(objPanelMR.sliderWC)){
objPanelMR.textFieldWC.setText(objPanelMR.sliderWC.getValue()+"");
}
if(e.getSource().equals(objPanelMR.sliderWW)){
objPanelMR.textFieldWW.setText(objPanelMR.sliderWW.getValue()+"");
}
//--------->
/*int windowCenter = Integer.parseInt(objPanelMR.textFieldWC.getText());
int windowWidth = Integer.parseInt(objPanelMR.textFieldWW.getText());
if(objDcmImg.getEstudio().equals("MR")) {
objImagenFuente = objDcmImg.getImagenMR(windowCenter,windowWidth);
}
if(objDcmImg.getEstudio().equals("CR")) {
objImagenFuente = objDcmImg.getImagenCR(windowCenter,windowWidth);
}
//copia de objeto imagen fuente
objImagenProcesado = objImagenFuente.clone();
verAtributosImagen(objImagenFuente);
objVentanaAxpherPicture.canvasImagen.pintarImagen(objImagenFuente);*/
//----------------->
}
if(objVentanaSignal != null) {
if(e.getSource().equals(objVentanaSignal.sliderSignal)) {
System.out.println("Fila: "+objVentanaSignal.sliderSignal.getValue());
objVentanaSignal.canvasSignal.setFila(objVentanaSignal.sliderSignal.getValue());
objVentanaSignal.canvasSignal.repaint();
System.out.println("H "+objVentanaSignal.getHeight()+" W "+objVentanaSignal.getWidth());
}
}
System.out.println("Cambia Slider");
}
|
b9cf7ce3-0402-4b30-a1fe-0e461fd6f8aa
| 1
|
private void addPlanTicketToGroup(PlanTicket pt)
{
StopRange range = new StopRange();
range.start = pt.getStartStop();
range.end = pt.getEndStop();
int pos = CollectionUtils.binarySearchBy(this._stopRangeGroups, range, new Selector<StopRangeGroup, StopRange>(){
@Override
public StopRange select(StopRangeGroup item) {
return item.getRange();
}}, StopRangeComparator.Default);
StopRangeGroup group;
if(pos >= 0)
{
group = this._stopRangeGroups.get(pos);
}
else
{
group = new StopRangeGroup();
group.setRange(range);
this._stopRangeGroups.add(~pos, group);
}
pt.setGroup(group);
group.getTickets().add(pt);
}
|
f22bb6e0-1c50-46fd-a34c-d2fe659669c1
| 1
|
private void evaluateOperatorByCount(int n) throws BinaryOperatorException {
int count = 0;
while (count < n) {
evaluateOperator();
count++;
}
}
|
99d425c8-ac3c-41fd-b081-cd5fdd79f3e2
| 5
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UsersSubscribeHashtagsEntityPK that = (UsersSubscribeHashtagsEntityPK) o;
if (hashtagId != that.hashtagId) return false;
if (userId != that.userId) return false;
return true;
}
|
0a5754cf-65bb-4913-9a4e-08d06858db81
| 0
|
@Override
public void buildDough() { pizza.setDough("pan baked"); }
|
4de09d36-8098-4f13-a0e2-912208e1221e
| 2
|
public FIB getModel(int Question_ID) {
FIB fibQuestion = new FIB();
try {
StringBuffer sql = new StringBuffer("");
sql.append("SELECT QuestionID,QuestionType,QuestionText, Instructions");
sql.append(" FROM `FIB`");
sql.append(" where QuestionID=" + Question_ID);
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
ResultSet rs = sQLHelper.runQuery(sql.toString());
while (rs.next()) {
fibQuestion.setQtype_ID(rs.getInt("QuestionType"));
fibQuestion.setQuestion_ID(rs.getInt("QuestionID"));
fibQuestion.setQuestionText(rs.getString("QuestionText"));
fibQuestion.setQuestionInstructions(rs.getString("Instructions"));
}
} catch (SQLException ex) {
Logger.getLogger(FIB.class.getName()).log(Level.SEVERE, null, ex);
}
return fibQuestion;
}
|
f41d6688-c76e-4fe6-9fba-bd1f2f90dcce
| 3
|
protected static HashMap<String, String> parseHeaders(String wholeMessage){
HashMap<String, String> answer= new HashMap<String, String>();
try {
String tempMessage= wholeMessage;
int indexOfNewline= tempMessage.indexOf(StompFrame.endlineChar);
String newLine= tempMessage.substring(0, indexOfNewline);
tempMessage= tempMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar);
while (!newLine.equals("")) {
int indexOfDelimiter= newLine.indexOf(":");
Object oldVal= answer.put(newLine.substring(0, indexOfDelimiter), newLine.substring(indexOfDelimiter + 1));
if (null != oldVal)
return null;
indexOfNewline= tempMessage.indexOf(StompFrame.endlineChar);
newLine= tempMessage.substring(0, indexOfNewline);
tempMessage= tempMessage.substring(indexOfNewline + StompFrame.lenghtOfEndlineChar);
}
} catch (Exception e) {
return null;
}
return answer;
}
|
30f1c314-f6b2-430b-af65-ab4fe2e70c01
| 5
|
public void startClient() throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
InetAddress host = null;
BufferedReader stdIn = null;
try {
host = InetAddress.getLocalHost();
socket = new Socket(host.getHostName(), 5559);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
//Read from socket and write back the response to server.
while ((fromServer = in.readLine()) != null) {
System.out.println("Server - " + fromServer);
if (fromServer.equals("exit"))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client - " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Cannot find the host: " + host.getHostName());
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't read/write from the connection: " + e.getMessage());
System.exit(1);
} finally { //Make sure we always clean up
out.close();
in.close();
stdIn.close();
socket.close();
}
}
|
1c04a41f-e316-4a70-83e8-dfe5ec22fc92
| 1
|
public boolean register(String user, String password){
PreparedStatement st;
Integer rs;
String query;
query="INSERT INTO people(name,password) VALUES('"+user+"','"+password+"')";
try {
st = conn.prepareStatement(query);
rs = st.executeUpdate();
st.close();
} catch (SQLException e) {
return false;
}
return true;
}
|
8e4005ee-bd61-414d-80c8-a226f1302309
| 3
|
private void addBlankBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBlankBtnActionPerformed
try {
question = questionField.getText();
instructions = instructionField.getText();
hlanswer = questionField.getSelectedText();
hlanswer2="[" +hlanswer+ "]";
int start = questionField.getText().indexOf(hlanswer);
if (start >= 0 && hlanswer.length() > 0) {
questionField.replaceRange(hlanswer2, start,start + hlanswer.length() );
}
}
catch (Exception exc) {
exc.printStackTrace();
}
}//GEN-LAST:event_addBlankBtnActionPerformed
|
87789b44-45ba-4db8-be9d-b8d84487e817
| 6
|
public void setCombatModifiers(int typeID) {
switch (typeID) {
case 0: weakAgainst = 4;
strongAgainst = 2;
break;
case 1: weakAgainst = 0;
strongAgainst = 3;
break;
case 2: weakAgainst = 2;
strongAgainst = 4;
break;
case 3: weakAgainst = 3;
strongAgainst = 0;
break;
case 4: weakAgainst = 6;
strongAgainst = 6;
break;
case 5: weakAgainst = 6;
strongAgainst = 6;
break;
}
}
|
9b423cd5-ede5-4ecf-a363-8935b9e969fa
| 5
|
public static boolean isReservedAssignmentOp(String candidate) {
int START_STATE = 0;
int TERMINAL_STATE = 1;
char next;
if (candidate.length()!=1){
return false;
}
int state = START_STATE;
for (int i = 0; i < candidate.length(); i++)
{
next = candidate.charAt(i);
switch (state)
{
case 0:
switch ( next )
{
case '=': state++; break;
default : state = -1;
}
break;
}
}
if ( state == TERMINAL_STATE )
return true;
else
return false;
}
|
2c048c56-ca7e-4792-be01-d2444e634c00
| 7
|
@Override
public void removeMyAffectsFrom(Physical P)
{
if(!(P instanceof MOB))
return;
final List<Ability> V=getMySpellsV();
final Set<String> removedAbles = new HashSet<String>();
for(int v=0;v<V.size();v++)
{
final Ability A=V.get(v);
if(!A.isSavable())
{
removedAbles.add(A.ID());
((MOB)P).delAbility(A);
}
}
if(P==lastMOB)
{
for(final Iterator<String> e=lastMOBeffects.iterator();e.hasNext();)
{
final String AID=e.next();
final Ability A2=lastMOB.fetchEffect(AID);
if((A2!=null)&&(removedAbles.contains(A2.ID())))
{
A2.unInvoke();
lastMOB.delEffect(A2);
}
}
lastMOBeffects.clear();
}
}
|
8d0a6bff-5cdb-41eb-93ad-8081aee50c08
| 2
|
public static <T> NBTList fromArray(T[] args)
{
final NBTList list = new NBTList(args.length);
for (T arg : args)
{
final NamedBinaryTag tag = NBTParser.wrap(arg);
if (tag != null)
{
list.addTag(tag);
}
}
return list;
}
|
a3ac1cdc-db2c-4089-b22a-74257ac50e09
| 6
|
public boolean checkCollision(Cell[][] tiles){
for(int i = 0; i < tiles.length; i++){
for(int j = 0; j < tiles[i].length; j++){
if(tiles[i][j] != null && hitbox.checkCollision(tiles[i][j].getHitbox())){
return true;
}
else if(tiles[i][j] != null && feetBox.checkCollision(tiles[i][j].getHitbox())){
return true;
}
}
}
return false;
}
|
f7b3566b-6a09-43b0-8e3c-5e144c33c1bd
| 4
|
public void play(Sequence sequence, boolean loop) {
if (sequencer != null && sequence != null && sequencer.isOpen()) {
try {
sequencer.setSequence(sequence);
sequencer.start();
this.loop = loop;
}
catch (InvalidMidiDataException ex) {
ex.printStackTrace();
}
}
}
|
e937c25a-2baf-48c1-82b4-464e79340957
| 6
|
public static StringWrapper cppTranslateTypeSpec(StandardObject typespec) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(typespec);
if (Surrogate.subtypeOfParametricTypeSpecifierP(testValue000)) {
{ ParametricTypeSpecifier typespec000 = ((ParametricTypeSpecifier)(typespec));
if (StandardObject.arrayTypeSpecifierP(typespec000)) {
return (ParametricTypeSpecifier.cppTranslateArrayType(typespec000));
}
if (((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())) == Stella.KWD_CPP_STANDALONE) {
return (StringWrapper.wrapString(StandardObject.cppTranslateTypeSpec(typespec000.specifierBaseType).wrapperValue + "<" + StandardObject.cppTranslateAndPointerizeTypeSpec(((StandardObject)(typespec000.specifierParameterTypes.first()))).wrapperValue + ">"));
}
else if (((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())) == Stella.KWD_CPP) {
return (StandardObject.cppTranslateTypeSpec(typespec000.specifierBaseType));
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + ((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())) + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
else if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate typespec000 = ((Surrogate)(typespec));
if (((StringWrapper)(KeyValueList.dynamicSlotValue(((Stella_Class)(typespec000.surrogateValue)).dynamicSlots, Stella.SYM_STELLA_CLASS_CPP_NATIVE_TYPE, Stella.NULL_STRING_WRAPPER))).wrapperValue != null) {
return (StringWrapper.wrapString(((StringWrapper)(KeyValueList.dynamicSlotValue(((Stella_Class)(typespec000.surrogateValue)).dynamicSlots, Stella.SYM_STELLA_CLASS_CPP_NATIVE_TYPE, Stella.NULL_STRING_WRAPPER))).wrapperValue));
}
else {
return (GeneralizedSymbol.cppTranslateClassTypename(Surrogate.symbolize(((Stella_Class)(typespec000.surrogateValue)).classType)));
}
}
}
else {
{ OutputStringStream stream001 = OutputStringStream.newOutputStringStream();
stream001.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace()));
}
}
}
}
|
e33d19f7-9730-4f16-b138-891e17538d22
| 7
|
public Mensaje crearMensaje(String xml, String ip) {
Mensaje mensaje = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document document = builder.parse(is);
XPath xPath = XPathFactory.newInstance().newXPath();
String tipo = null;
tipo = document.getDocumentElement().getAttributes().getNamedItem("TYPE").getNodeValue();
if (tipo.equals("LIST-AUT"))
mensaje = new ListAuthentications(document);
if (tipo.equals("LIST-USERS"))
mensaje = new ListUsers(document);
if (tipo.equals("ADD"))
mensaje = new Add(document);
if (tipo.equals("REMOVE"))
mensaje = new Remove(document);
if (tipo.equals("MODIFY"))
mensaje = new Modify(document);
if (tipo.equals("AUTHENTICATE"))
mensaje = new Authenticate(document, ip);
} catch(Exception e) {
e.printStackTrace();
}
return mensaje;
}
|
c3dce10e-a75d-416b-a089-1b66614d9355
| 3
|
public static void restart(boolean ausloggen)
{
if(ausloggen)
{
try
{
startUp._client.logout();
}
catch(RemoteException e)
{
e.printStackTrace();
}
}
startUp._server = null;
startUp._client = null;
startUp = null;
System.gc();
KeyboardFocusManager
.setCurrentKeyboardFocusManager(new DefaultKeyboardFocusManager());
try
{
StartUp.main(StartUp._param);
}
catch(Exception e)
{
e.printStackTrace();
}
}
|
074ed418-3bb5-4ec9-a47b-1b6f111085bd
| 8
|
public void printFrameInfo() throws IOException {
int fn = -1;
FlacAudioFrame audio;
while ((audio=flac.getNextAudioPacket()) != null) {
fn++;
System.out.print("frame="+fn);
System.out.print(SPACER);
System.out.print("offset=??");
System.out.print(SPACER);
System.out.print("bits="+(audio.getData().length*8));
System.out.print(SPACER);
System.out.print("blocksize="+audio.getBlockSize());
System.out.print(SPACER);
System.out.print("sample_rate="+audio.getSampleRate());
System.out.print(SPACER);
System.out.print("channels="+audio.getNumChannels());
System.out.print(SPACER);
System.out.print("channel_assignment=??");
System.out.println();
for (int sfn=0; sfn<audio.getSubFrames().length; sfn++) {
FlacAudioSubFrame sf = audio.getSubFrames()[sfn];
System.out.print(INDENT1);
System.out.print("subframe="+sfn);
System.out.print(SPACER);
System.out.print("wasted_bits="+sf.getWastedBits());
System.out.print(SPACER);
System.out.print("type="+sf.getType());
System.out.print(SPACER);
System.out.print("order="+sf.getPredictorOrder());
if (sf instanceof SubFrameLPC) {
SubFrameLPC sflpc = (SubFrameLPC)sf;
System.out.print(SPACER);
System.out.print("qlp_coeff_precision="+sflpc.getLinearPredictorCoefficientPrecision());
System.out.print(SPACER);
System.out.print("quantization_level="+sflpc.getLinearPredictorCoefficientShift());
}
if (sf instanceof SubFrameWithResidual) {
SubFrameWithResidual sfr = (SubFrameWithResidual)sf;
System.out.print(SPACER);
System.out.print("residual_type="+sfr.getResidual().getType());
System.out.print(SPACER);
System.out.print("partition_order="+sfr.getResidual().getPartitionOrder());
System.out.println();
if (sf instanceof SubFrameLPC) {
SubFrameLPC sflpc = (SubFrameLPC)sf;
for (int qc=0; qc<sflpc.getCoefficients().length; qc++) {
System.out.print(INDENT2);
System.out.print("qlp_coeff["+qc+"]="+sflpc.getCoefficients()[qc]);
System.out.println();
}
}
for (int wn=0; wn<sfr.getWarmUpSamples().length; wn++) {
System.out.print(INDENT2);
System.out.print("warmup["+wn+"]="+sfr.getWarmUpSamples()[wn]);
System.out.println();
}
for (int pn=0; pn<sfr.getResidual().getNumPartitions(); pn++) {
System.out.print(INDENT2);
System.out.print("parameter["+pn+"]="+sfr.getResidual().getRiceParams()[pn]);
System.out.println();
}
} else {
// Rest TODO
System.out.println();
}
}
}
}
|
74b542f4-06a0-4d39-a570-f8e4e2929603
| 0
|
public boolean getColor (){
return color;
}
|
dacc4869-0455-43bf-8963-fd03527a2648
| 9
|
public void paint(Graphics g) {
g.setFont(f);
FontMetrics fm = g.getFontMetrics(f);
int ascent = fm.getAscent() / 2;
// ruler
int maxValue = 0;
if (type == PITCH) maxValue = maxPitchValue;
else if (type == RHYTHM) maxValue = maxRhythmValue;
else if (type == DYNAMIC) maxValue = maxDynamicValue;
else if (type == PAN) maxValue = maxPanValue;
for (int i = 0; i < 5; i++) {
g.setColor(Color.green);
String lString = "" + maxValue / 4 * i;
g.drawString(lString, this.getSize().width / 5 * i + lableSpace -
fm.stringWidth(lString) / 2, lableSpace - fm.getAscent() / 2);
g.setColor(Color.gray);
g.drawLine(this.getSize().width / 5 * i + lableSpace, lableSpace,
this.getSize().width / 5 * i + lableSpace, this.getSize().height);
}
// paint
switch (type) {
case PITCH: {
paintPitches(g);
break;
}
case RHYTHM: {
paintRhythms(g);
break;
}
case DYNAMIC: {
paintDynamics(g);
break;
}
case PAN: {
paintPans(g);
break;
}
}
}
|
8e360df3-fb77-4cbb-882b-db26ba8886d3
| 0
|
public Booking(String HKID, String userName, GregorianCalendar date){
this.HKID = HKID;
this.userName = userName;
this.date = date;
}
|
9375f0d2-8e53-471b-ac52-09fbdb838c06
| 2
|
public void reset(int width, int height, Minesweeper game) {
sections.clear();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
sections.add(new Section(x, y, game));
}
}
}
|
1fc74720-e6c7-40df-97f2-77bd8b3ec5c0
| 2
|
private void getDataFromSectionTable () {
try {
connection = DriverManager.getConnection(Utils.DB_URL);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT id, name FROM Section");
while (resultSet.next()) {
sectionNameMap.put(resultSet.getInt("id"), resultSet.getString("name"));
}
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
|
8fb3da1c-d26a-4764-86b0-cc6041b3b728
| 4
|
public static void iceManipulationWaterWalk(Player player) {
for (int x = -1; x < 2; x++) {
for (int z = -1; z < 2; z++) {
Location location = new Location(player.getWorld(), player.getLocation().getBlockX() + x, player.getLocation().getBlockY(), player.getLocation().getBlockZ() + z);
Block block = location.getBlock().getRelative(BlockFace.DOWN);
if (block.isLiquid() && !block.isEmpty()) {
block.setType(Material.ICE);
new IceRemoveHandler(player, player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ(), block.getTypeId()).runTaskLater(Heroes.instance(), 3);
}
}
}
}
|
e8b71b9a-f04d-4a18-929d-ff62d7a5adcf
| 4
|
private void doStop() throws Exception {
if (isActive()) {
doSetActive(false);
//..stop GarbageConnectios
try {
if ((garbageConnections != null) && (garbageConnections.isAlive())) {
garbageConnections.setStopped(true);
}
//..destroy listener
if (listener != null) {
listener.close();
listener = null;
}
}
finally {
//..close connections
closeConnections();
}
fireServerStopEvent(new ServerStopEvent(this));
}
}
|
96847354-81e6-4316-9215-643c63603e44
| 2
|
private static ServerSocketChannel createServerChannel() throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
for (int port = PORT_RANGE_LOWER; port <= PORT_RANGE_UPPER; port++) {
try {
serverChannel.bind(new InetSocketAddress(port));
System.out.println("[Server] Started on port " + port);
return serverChannel;
} catch (IOException e) {
// continue, port is in use
}
}
return null;
}
|
54b07265-6f45-472f-a7b3-422112e5b077
| 0
|
@Override
public String getErrorMessage() {
return errormessage;
}
|
c80c2070-2980-44f3-b642-390557795404
| 5
|
public static void main(String[] args) {
System.out.println("Initialisation du client");
System.out.println("Specifiez l'adresse IP (127.0.0.1 par defaut): ");
String ip ="";
int port1 = 9876;
try
{
ip = bufferedReader.readLine();
if(ip == null || ip == "")
{
ip = "127.0.0.1";
}
Client client = new Client(ip, port1);
InitialiseurDeRequete idr = new InitialiseurDeRequete(client);
String requete = "";
System.out.println("Bienvenue sur l'application HockeyLive!");
System.out.println("Voici la liste des commandes possibles:");
System.out.println("GetListMatch");
System.out.println("GetEquipesMatch/idPartie");
System.out.println("SetBet/idPartie/D ou V/Montant(avec un point si apres decimale)");
System.out.println("Voici la liste des matchs (ID, Equipe Receveur, Equipe Visiteur):");
idr.ParseAnswer(client.envoyerRequete(Commands.GET_LIST_MATCH.toString()));
while(true){
if(bufferedReader.ready()){
requete = bufferedReader.readLine();
idr.ParseAnswer(client.envoyerRequete(requete));
}
}
}
catch(IOException ioe)
{
System.out.println(ioe);
ioe.printStackTrace();
}
}
|
b4fbaa9c-0f83-4b72-a6ef-c5cdd0ba2305
| 8
|
@Override
public boolean equals(Object obj){
boolean out = false;
if (obj instanceof ChessGameConfiguration){
ChessGameConfiguration acg = (ChessGameConfiguration) obj;
if(this.currentBoard.length == acg.getCurrentBoard().length){
if (currentBoard.length <= CELL_NUMBER_TO_CALCULATE_HASHCODE){
out = this.hashCode() == acg.hashCode();
}else{
out = true;
for(int i= CELL_NUMBER_TO_CALCULATE_HASHCODE +1; out && (i < currentBoard.length);i++){
Cell thisCell = this.currentBoard[i];
Cell otherCell = acg.getCurrentBoard()[i];
if (thisCell instanceof PieceCell){
if (otherCell instanceof PieceCell){
PieceCell thisPieceCell = (PieceCell) thisCell;
PieceCell otherPieceCell = (PieceCell) otherCell;
out = thisPieceCell.getPiece() == otherPieceCell.getPiece();
}else{
out = false;
}
}else{
if (otherCell instanceof PieceCell){
out = false;
}
}
}
}
}
}
return out;
}
|
2088b0c5-b0aa-4f83-9153-e2e1298872ae
| 6
|
@Override
public void run() {
long beforeTime, afterTime, timeDiff, sleepTime;
long overSleepTime = 0L;
int noDelays = 0;
long excess = 0L;
beforeTime = System.nanoTime();
running = true;
while (running) {
update();
render();
paintScreen();
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (period - timeDiff) - overSleepTime;
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime / 1000000L);
} catch (InterruptedException e) {
overSleepTime = System.nanoTime() - afterTime - sleepTime;
}
} else {
overSleepTime = 0L;
excess -= sleepTime;
if (++noDelays >= NO_DELAYS_PER_YIELD) {
Thread.yield();
noDelays = 0;
}
}
beforeTime = System.nanoTime();
int skips = 0;
while (excess >= period && skips <= MAX_FRAME_SKIPS) {
excess -= period;
update();
skips++;
}
}
System.exit(0);
}
|
13713b9c-8a14-45ea-97d3-6eda1d499ecd
| 7
|
public ChatClient () {
client = new Client();
client.start();
// For consistency, the classes to be sent over the network are
// registered by the same method for both the client and server.
Network.register(client);
client.addListener(new Listener() {
public void connected (Connection connection) {
RegisterName registerName = new RegisterName();
registerName.name = name;
client.sendTCP(registerName);
}
public void received (Connection connection, Object object) {
if (object instanceof UpdateNames) {
UpdateNames updateNames = (UpdateNames)object;
chatFrame.setNames(updateNames.names);
return;
}
if (object instanceof ChatMessage) {
ChatMessage chatMessage = (ChatMessage)object;
chatFrame.addMessage(chatMessage.text);
return;
}
}
public void disconnected (Connection connection) {
EventQueue.invokeLater(new Runnable() {
public void run () {
// Closing the frame calls the close listener which will stop the client's update thread.
chatFrame.dispose();
}
});
}
});
// Request the host from the user.
String input = (String)JOptionPane.showInputDialog(null, "Host:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE,
null, null, "localhost");
if (input == null || input.trim().length() == 0) System.exit(1);
final String host = input.trim();
// Request the user's name.
input = (String)JOptionPane.showInputDialog(null, "Name:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE, null,
null, "Test");
if (input == null || input.trim().length() == 0) System.exit(1);
name = input.trim();
// All the ugly Swing stuff is hidden in ChatFrame so it doesn't clutter the KryoNet example code.
chatFrame = new ChatFrame(host);
// This listener is called when the send button is clicked.
chatFrame.setSendListener(new Runnable() {
public void run () {
ChatMessage chatMessage = new ChatMessage();
chatMessage.text = chatFrame.getSendText();
client.sendTCP(chatMessage);
}
});
// This listener is called when the chat window is closed.
chatFrame.setCloseListener(new Runnable() {
public void run () {
client.stop();
}
});
chatFrame.setVisible(true);
// We'll do the connect on a new thread so the ChatFrame can show a progress bar.
// Connecting to localhost is usually so fast you won't see the progress bar.
new Thread("Connect") {
public void run () {
try {
client.connect(5000, host, Network.port);
// Server communication after connection can go here, or in Listener#connected().
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
}.start();
}
|
20d12cd5-8053-4509-b6ab-0059e9c332bc
| 2
|
public ScreenEffect(Vector4f start, Vector4f end, float duration, boolean moveTo, Tween tween) {
if(moveTo) {
Vector4f.sub(end, start, end);
}
this.startingValue = start;
this.endingValue = end;
// Using a duration of zero causes the effects to return NaN
if(duration == 0) {
duration = 0.001f;
}
this.duration = duration;
this.currentTime = 0f;
this.tween = tween;
}
|
2f3c2708-14c4-4267-96a9-501fe06d7f69
| 5
|
private void nonTrivial(int[] section) {
int s, e;
for (e = buffer.length() - 1; e > 0 && buffer.charAt(e) == BLANK; e--)
;
if (buffer.charAt(e) != BLANK)
e++;
for (s = 0; s < e && buffer.charAt(s) == BLANK; s++)
;
section[0] = s;
section[1] = e;
}
|
027a08dd-2e26-470d-8eea-f49cd1472a61
| 9
|
public void takeClickDown(MouseEvent e)
{
if(drawing && selectedPoints.size()==0)
{
image.addPoint(e.getX(), e.getY()-22);
}
if(drawing && selectedPoints.size()==1)
{
image.insertPoint(e.getX(), e.getY()-22, iindex);
iindex++;
}
if(selecting)
{
p1 = new Point(e.getX(), e.getY()-22);
p2 = new Point(e.getX(), e.getY()-22);
}
if(moving)
{
p1 = new Point(e.getX(), e.getY()-22);
p2 = new Point(e.getX(), e.getY()-22);
}
if(!moving && !selecting && !drawing)
{
image.clickHedron(e.getX(), e.getY()-22);
selectedPoints.clear();
}
}
|
19bfb261-976e-49ef-9eba-3d59b3cdd7de
| 4
|
public int AddPhrase(String Text, String ID) {
//Controllo se l'ID sia presente nella lista
for (int i = 0; i < this._MyPhraseList.size(); i++) {
if (this._MyPhraseList.get(i).GetID().equals(ID)) {
//Creo la stringa che contiene il testo
Chunk TmpChunk = new Chunk(Text, FontFactory.getFont(this._MyPhraseList.get(i).GetBaseFont(), this._MyPhraseList.get(i).GetFontSize(), this._MyPhraseList.get(i).GetStyle(), this._MyPhraseList.get(i).GetTextColor()));
Paragraph TmpParagraph = new Paragraph(TmpChunk);
TmpParagraph.setAlignment(this._MyPhraseList.get(i).GetHorizontalAlignment());
TmpParagraph.setSpacingBefore(this._MyPhraseList.get(i).GetSpacingBefore());
TmpParagraph.setSpacingAfter(this._MyPhraseList.get(i).GetSpacingAfter());
//Se non ci sono capitoli lo aggiungo alla pagina
if (this._ChapterList.isEmpty()) {
try {
this._MyDocument.add(TmpChunk);
//Se non ho creato il documento oppure questo non è aperto
} catch (DocumentException ex) {
return -10;
}
}
//Se ci sono capitoli lo aggiungo all'ultimo capitolo
else this._ChapterList.get(this._ChapterList.size() - 1).add(TmpParagraph);
return 1;
}
}
//Se l'ID non è presente
return -1;
}
|
40cea826-c2ac-4de3-8494-c3135d8dec3a
| 4
|
public void mouseMoved(MouseEvent e) {
// @TODO not built to handle multiple mice
float x = e.getX();
float y = e.getY();
float dx = x - mouse_old_x;
float dy = y - mouse_old_y;
mouse_old_x = x;
mouse_old_y = y;
data.items_new[FIRST_MOUSE_AXIS+0].value += dx>0? dx:0;
data.items_new[FIRST_MOUSE_AXIS+1].value += dx<0?-dx:0;
data.items_new[FIRST_MOUSE_AXIS+2].value += dy>0? dy:0;
data.items_new[FIRST_MOUSE_AXIS+3].value += dy<0?-dy:0;
}
|
f45c167f-5b62-4285-880f-a47a9e945a39
| 9
|
public int getLevel()
{
if (experience < 250) {
return 1;
} else if (experience < 750) {
return 2;
} else if (experience < 1250) {
return 3;
} else if (experience < 2000) {
return 4;
} else if (experience < 3250) {
return 5;
} else if (experience < 5500) {
return 6;
} else if (experience < 10000) {
return 7;
} else if (experience < 18000) {
return 8;
} else if (experience < 32000) {
return 9;
} else {
return 10;
}
}
|
e26ce0f3-c41c-4f86-a5e5-c5fa975926fb
| 0
|
protected double getBreedingProbability()
{
return BREEDING_PROBABILITY;
}
|
539edda3-3b88-4681-860d-b2db7470283c
| 9
|
private void addLink(JLabel label, final Key key) {
label.setCursor(getPredefinedCursor(HAND_CURSOR));
label.addMouseListener(
new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Game game = gameListModel.getSelection();
String oldValue = null;
switch (key) {
case GAME_NAME :
oldValue = game.getName();
break;
case GAME_DEVELOPER :
oldValue = game.getDeveloper();
break;
case GAME_PUBLISHER :
oldValue = game.getPublisher();
break;
default :
break;
}
String newValue = inputValue(key, oldValue);
if (newValue != null) {
newValue = newValue.trim();
if (!isEmpty(newValue) && !newValue.equals(oldValue)) {
switch (key) {
case GAME_NAME :
game.setName(newValue);
gameListModel.sort();
gameList.setSelectedValue(game, true);
break;
case GAME_DEVELOPER :
game.setDeveloper(newValue);
break;
case GAME_PUBLISHER :
game.setPublisher(newValue);
break;
default :
break;
}
refreshGameInfo(game);
gameListModel.fireSelectedChange();
}
}
}
}
);
}
|
9907b385-ea15-4e5f-8bfa-aade466da285
| 2
|
@Override
public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
if (!initSoundPlayed) {
initSoundPlayed = true;
}
if (InputChecker.isInputPressed(container, KeyBindings.P1_INPUT)) {
GameState levelState = new LevelState();
levelState.init(container, game);
game.addState(levelState);
game.enterState(1);
}
}
|
2328965f-2a44-4913-bbec-5950ebe07c5e
| 8
|
public void shiftLeftClick() {
int flagCount = 0;
for (int i = -1; i < 2; ++i) {
for (int k = -1; k < 2; ++k) {
Tile update = this.board.getTile(super.row + i, super.col + k);
if (update != null) {
if (update.state.equals("flag")) {
++flagCount;
}
}
}
}
if (flagCount == this.numMinesSurrounding) {
for (int i = -1; i < 2; ++i) {
for (int k = -1; k < 2; ++k) {
Tile update = this.board.getTile(super.row + i, super.col
+ k);
if (update != null) {
update.leftClick();
}
}
}
}
}
|
3e326a41-4ba0-4655-a91e-b04cd5a702e9
| 0
|
public long getMax() {
return max;
}
|
1be009b9-581d-4d57-9ddd-bbd6854b5f70
| 6
|
static void addEntries(JSONArray entry_list, int index, Connection Con, String str, int start_index, int max_fetch) throws Exception {
switch(index) {
case 0: {
entry_list.addAll(Course.Query(Con,str,start_index,max_fetch));
break;
}
case 1: {
entry_list.addAll(Student.Query(Con,str,start_index,max_fetch));
break;
}
case 2: {
entry_list.addAll(Instructor.Query(Con,str,start_index,max_fetch));
break;
}
case 3: {
entry_list.addAll(Work.Query(Con,str,start_index,max_fetch));
break;
}
case 4: {
entry_list.addAll(Project.Query(Con,str,start_index,max_fetch));
}
case 5: {
entry_list.addAll(Post.Query(Con,str,start_index,max_fetch));
}
}
}
|
58e3e6c2-9390-4041-8a96-a7de697660b7
| 9
|
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int c=0,T=parseInt(in.readLine().trim());c++<T;) {
StringTokenizer st=new StringTokenizer(in.readLine());
int A=parseInt(st.nextToken()),B=parseInt(st.nextToken()),C=parseInt(st.nextToken());
if((A<B&&A>C)||(A<C&&A>B))System.out.println("Case "+c+": "+A);
else if((B<A&&B>C)||(B<C&&B>A))System.out.println("Case "+c+": "+B);
else System.out.println("Case "+c+": "+C);
}
}
|
7d79fb47-20bf-4a5d-8a4a-20bbbb54f0ec
| 6
|
public void setCurrent(int numberResults, Double timeInSeconds) {
if(run>=0 && timeInSeconds>=0.0) {
int queryNr = queryMix[currentQueryIndex];
int nrRuns = runsPerQuery[queryNr]++;
aqet[queryNr] = (aqet[queryNr] * nrRuns + timeInSeconds) / (nrRuns+1);
avgResults[queryNr] = (avgResults[queryNr] * nrRuns + numberResults) / (nrRuns+1);
aqetg[queryNr] += Math.log10(timeInSeconds);
if(timeInSeconds < qmin[queryNr])
qmin[queryNr] = timeInSeconds;
if(timeInSeconds > qmax[queryNr])
qmax[queryNr] = timeInSeconds;
if(numberResults < minResults[queryNr])
minResults[queryNr] = numberResults;
if(numberResults > maxResults[queryNr])
maxResults[queryNr] = numberResults;
queryMixRuntime += timeInSeconds;
}
currentQueryIndex++;
}
|
a6ae3c93-df9d-4675-8713-44dbc33a3a16
| 9
|
private void openSelected()
{
IFile file = ((SearchResult) resultList.get(resourceNames
.getSelectionIndex())).getFile();
try
{
// open the file
// @Eclipse2
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(file);
//@Eclipse3
//IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
// file);
if (file == null)
return;
// select the file
org.eclipse.ui.IViewPart view = null;
if (focus)
{
if (file.getName().toUpperCase().endsWith(".JAVA")
&& GotoFileE30Plugin
.getDefault()
.getPreferenceStore()
.getBoolean(
GotoFilePreferencePage.P_PACKAGEEXPLORER))
{
view = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().showView(
"org.eclipse.jdt.ui.PackageExplorer");
} else
{
view = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().showView(
"org.eclipse.ui.views.ResourceNavigator");
}
if (null != view && view instanceof ISetSelectionTarget)
{
org.eclipse.jface.viewers.ISelection selection = new StructuredSelection(
file);
((ISetSelectionTarget) view).selectReveal(selection);
}
}
try
{
// note that this mechanism of opening editors is now deprecated
// in E3,
// however E3 still maintains binary compatibility with the
// openEditor methods,
// so the E2 version of the plugin will still work in E3
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
if (page != null)
org.eclipse.ui.ide.IDE.openEditor(page, file);
//page.openEditor(new FileEditorInput(file), null, true);
//page.openEditor(file);
} catch (CoreException x)
{
String title = "Error opening Editor"; //$NON-NLS-1$
String message = "Could not open Editor"; //$NON-NLS-1$
//WorkbenchPlugin.log(title, x.getStatus());
ErrorDialog.openError(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell(), title, message,
x.getStatus());
}
} catch (PartInitException e1)
{
e1.printStackTrace();
}
}
|
736b5665-d7d9-4198-b1ae-901af6004ccc
| 7
|
public String sortingMethod(String[] stringList){
boolean lexSorted = true;
boolean lengthSorted = true;
int n = stringList.length;
for(int i=0; i<n-1; i++){
if(stringList[i].length()>stringList[i+1].length()) lengthSorted=false;
if(stringList[i].compareTo(stringList[i+1])>0) lexSorted=false;
}
if(lexSorted && lengthSorted) return "both";
if(lexSorted) return "lexicographically";
if(lengthSorted) return "lengths";
return "none";
}
|
7a6524de-58df-483e-899f-b986dbc14b52
| 6
|
public void createGUI(Composite parent) {
GridLayout gridLayout;
GridData gridData;
/*** Create principal GUI layout elements ***/
Composite displayArea = new Composite(parent, SWT.NONE);
gridLayout = new GridLayout();
gridLayout.numColumns = 1;
displayArea.setLayout(gridLayout);
// Creating these elements here avoids the need to instantiate the GUI elements
// in strict layout order. The natural layout ordering is an artifact of using
// SWT layouts, but unfortunately it is not the same order as that required to
// instantiate all of the non-GUI application elements to satisfy referential
// dependencies. It is possible to reorder the initialization to some extent, but
// this can be very tedious.
// paint canvas
final Canvas paintCanvas = new Canvas(displayArea, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL |
SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND);
gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
paintCanvas.setLayoutData(gridData);
paintCanvas.setBackground(paintColorWhite);
// color selector frame
final Composite colorFrame = new Composite(displayArea, SWT.NONE);
gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
colorFrame.setLayoutData(gridData);
// tool settings frame
final Composite toolSettingsFrame = new Composite(displayArea, SWT.NONE);
gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
toolSettingsFrame.setLayoutData(gridData);
// status text
final Text statusText = new Text(displayArea, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY);
gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
statusText.setLayoutData(gridData);
/*** Create the remaining application elements inside the principal GUI layout elements ***/
// paintSurface
paintSurface = new PaintSurface(paintCanvas, statusText, paintColorWhite);
// finish initializing the tool data
tools[Pencil_tool].data = new PencilTool(toolSettings, paintSurface);
tools[Airbrush_tool].data = new AirbrushTool(toolSettings, paintSurface);
tools[Line_tool].data = new LineTool(toolSettings, paintSurface);
tools[PolyLine_tool].data = new PolyLineTool(toolSettings, paintSurface);
tools[Rectangle_tool].data = new RectangleTool(toolSettings, paintSurface);
tools[RoundedRectangle_tool].data = new RoundedRectangleTool(toolSettings, paintSurface);
tools[Ellipse_tool].data = new EllipseTool(toolSettings, paintSurface);
tools[Text_tool].data = new TextTool(toolSettings, paintSurface);
// colorFrame
gridLayout = new GridLayout();
gridLayout.numColumns = 3;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
colorFrame.setLayout(gridLayout);
// activeForegroundColorCanvas, activeBackgroundColorCanvas
activeForegroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gridData.heightHint = 24;
gridData.widthHint = 24;
activeForegroundColorCanvas.setLayoutData(gridData);
activeBackgroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gridData.heightHint = 24;
gridData.widthHint = 24;
activeBackgroundColorCanvas.setLayoutData(gridData);
// paletteCanvas
final Canvas paletteCanvas = new Canvas(colorFrame, SWT.BORDER | SWT.NO_BACKGROUND);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = 24;
paletteCanvas.setLayoutData(gridData);
paletteCanvas.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
Rectangle bounds = paletteCanvas.getClientArea();
Color color = getColorAt(bounds, e.x, e.y);
if (e.button == 1) setForegroundColor(color);
else setBackgroundColor(color);
}
private Color getColorAt(Rectangle bounds, int x, int y) {
if (bounds.height <= 1 && bounds.width <= 1) return paintColorWhite;
final int row = (y - bounds.y) * numPaletteRows / bounds.height;
final int col = (x - bounds.x) * numPaletteCols / bounds.width;
return paintColors[Math.min(Math.max(row * numPaletteCols + col, 0), paintColors.length - 1)];
}
});
Listener refreshListener = new Listener() {
public void handleEvent(Event e) {
if (e.gc == null) return;
Rectangle bounds = paletteCanvas.getClientArea();
for (int row = 0; row < numPaletteRows; ++row) {
for (int col = 0; col < numPaletteCols; ++col) {
final int x = bounds.width * col / numPaletteCols;
final int y = bounds.height * row / numPaletteRows;
final int width = Math.max(bounds.width * (col + 1) / numPaletteCols - x, 1);
final int height = Math.max(bounds.height * (row + 1) / numPaletteRows - y, 1);
e.gc.setBackground(paintColors[row * numPaletteCols + col]);
e.gc.fillRectangle(bounds.x + x, bounds.y + y, width, height);
}
}
}
};
paletteCanvas.addListener(SWT.Resize, refreshListener);
paletteCanvas.addListener(SWT.Paint, refreshListener);
//paletteCanvas.redraw();
// toolSettingsFrame
gridLayout = new GridLayout();
gridLayout.numColumns = 4;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
toolSettingsFrame.setLayout(gridLayout);
Label label = new Label(toolSettingsFrame, SWT.NONE);
label.setText(getResourceString("settings.AirbrushRadius.text"));
final Scale airbrushRadiusScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
airbrushRadiusScale.setMinimum(5);
airbrushRadiusScale.setMaximum(50);
airbrushRadiusScale.setSelection(toolSettings.airbrushRadius);
airbrushRadiusScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
airbrushRadiusScale.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
toolSettings.airbrushRadius = airbrushRadiusScale.getSelection();
updateToolSettings();
}
});
label = new Label(toolSettingsFrame, SWT.NONE);
label.setText(getResourceString("settings.AirbrushIntensity.text"));
final Scale airbrushIntensityScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
airbrushIntensityScale.setMinimum(1);
airbrushIntensityScale.setMaximum(100);
airbrushIntensityScale.setSelection(toolSettings.airbrushIntensity);
airbrushIntensityScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
airbrushIntensityScale.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection();
updateToolSettings();
}
});
}
|
5ebcc3e7-9f3b-4bca-9004-fc28235f0e89
| 4
|
private boolean read() {
try {
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("X-API-Key", this.apiKey);
}
conn.addRequestProperty("User-Agent", Updater.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.size() == 0) {
this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id);
this.result = UpdateResult.FAIL_BADID;
return false;
}
this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
this.result = UpdateResult.FAIL_DBO;
}
this.plugin.getLogger().log(Level.SEVERE, null, e);
return false;
}
}
|
e03c450a-1dbe-4755-8198-b143cb7909b2
| 6
|
double[] compob(double x[]) {
for (int j = 0; j < parameters.length; j++) {
parameters[j] = x[j];
}
// singleRun();
// modelrun !!!!!!!!!
double F[] = new double[M];
for (int i = 0; i < M; i++) {
if (MaximizeEff[i] == Statistics.MINIMIZATION) {
F[i] = effValues[i];
} else if (MaximizeEff[i] == Statistics.ABSMINIMIZATION) {
F[i] = Math.abs(effValues[i]);
} else if (MaximizeEff[i] == Statistics.ABSMAXIMIZATION) {
F[i] = -Math.abs(effValues[i]);
} else if (MaximizeEff[i] == Statistics.MAXIMIZATION) {
F[i] = -effValues[i];
}
}
return F;
}
|
c2805f7a-7dad-4cf4-9189-3816fc78b522
| 3
|
public static TreeMap<Integer,Integer> pitchRangeTrunkate(TreeMap<Integer,Integer> pitchTreeIn){
TreeMap<Integer,Integer> pitchTreeOut = new TreeMap<Integer,Integer>();
Iterator<Integer> pitchIterator = pitchTreeIn.keySet().iterator();
while(pitchIterator.hasNext()){
int key = pitchIterator.next();
if(-24<=key && key<=24){
pitchTreeOut.put(key, pitchTreeIn.get(key));
}
else{
SinglePhraseSelector.pitchCount = SinglePhraseSelector.pitchCount-pitchTreeIn.get(key);
}
}
return pitchTreeOut;
}
|
fce6999b-01bf-4727-b065-1f00cc25de94
| 9
|
@Override
public boolean equals(Object person) {
if (Java8.Person2.this == person)
return true;
//if (!(person instanceof Person2))
if (person.getClass() != Person2.class)
return false;
Java8.Person2 p = (Java8.Person2) person;
boolean nameCheck = Java8.Person2.this.name == null ? (p.name != null ? false : true) : (p.name == null ? true : Java8.Person2.this.name == p.name);
boolean dateCheck = Java8.Person2.this.dob == null ? (p.dob != null ? false : true) : (p.dob == null ? true : Java8.Person2.this.dob.equals(p.dob));
return nameCheck && dateCheck;
}
|
ecc8e6b6-397d-4b33-882b-caa525dae6db
| 1
|
public void setMetadonnee(File doc) {
if (doc == null) {
nom = "Inconnu";
chemin = "0";
taille = 0;
dateModif = "Inconnu";
auteur = "Inconnu";
duree = "Inconnu";
note = 0;
icone = "img//icoNotFound.png";
listeSeries = null;
} else {
nom = doc.getName();
chemin = doc.getPath();
taille = (int) doc.length();
auteur = "Inconnu";
SimpleDateFormat formatDate = new SimpleDateFormat(
"MM/dd/yyyy à HH:mm");
dateModif = formatDate.format(doc.lastModified());
// auteur = "Inconnu";
duree = "Inconnu";
note = 0;
icone = "img//icoVideo.png";
listeSeries = new ArrayList<Serie>();
// listeSeries.add(new Serie(nom));
// listeSeries.add(new Serie(auteur));
}
}
|
67e61b88-fd08-47ea-91dc-f185de674748
| 0
|
public void setAccountId(String accountId) {
this.accountId = accountId;
}
|
39003dbe-a431-4ab0-bb06-c27cd28f2d0b
| 6
|
public Login1() {
Runnable obt_run = new Runnable() {
//check Caps Lock is On
public void run() {
while (check) {
if (Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
JOptionPane.showMessageDialog(null, "Caps Lock is On");
Toolkit.getDefaultToolkit().beep();
try {
Thread.sleep(6000);
} catch (InterruptedException ex) {
Logger.getLogger(Login1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
};
Thread thread_log = new Thread(obt_run);
thread_log.start();
initComponents();
Vector users = new Vector();
try {
DB.myConnection().createStatement().executeUpdate("delete from currentloggers where LibrianID>='000'");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error @ LOGIn1 == "+ex.getMessage(), "err", JOptionPane.OK_OPTION);
}
try {
ResultSet rs = DB.myConnection().createStatement().executeQuery("select UserName from login");
while (rs.next()) {
users.add(rs.getString("UserName"));
jComboBox1.setModel(new DefaultComboBoxModel(users));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error @ LOGIn 1ggg06= "+ex, "err", JOptionPane.OK_OPTION);
}
}
|
9c9003ef-fae1-461c-8b03-0a78d5bbe9d5
| 0
|
public IrcClient getCurrentClient(){ return CurrentClient; }
|
4dc79746-4d60-45d9-9ed0-72598d2ab8f3
| 5
|
@Override
public void run() {
while (this.parent.sckt.isConnected() && !this.parent.sckt.isInputShutdown()) {
try {
if (this.in.available() > 0) {
this.parent.onInputReceived(this.in);
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println("ListenThread " + this.getId() + "was interrupted during sleep.");
}
} catch (IOException ex) {
this.parent.onInputError(ex);
}
}
}
|
2104d360-cc84-4758-855c-12241094ce70
| 0
|
public void setDays(ArrayList <Day> list)
{
days = list;
}
|
1343820d-4af3-483e-a20f-bb2fb21db6de
| 2
|
public TreeNode getMaxNode() {
TreeNode current = root;
if (current == null)
return null;
while (current.right != null) {
current = current.right;
}
return current;
}
|
d65fd78d-b305-4dc3-96e0-e7fd900cf50e
| 7
|
static final int method3266(AbstractToolkit var_ha, int i, Class277 class277) {
try {
anInt9674++;
if ((((Class277) class277).anInt3569 ^ 0xffffffff) == 0) {
if (((Class277) class277).anInt3575 != -1) {
TextureDefinition class12 = ((AbstractToolkit) var_ha).aD4579.getTexture(
((Class277) class277).anInt3575, -6662);
if (!((TextureDefinition) class12).aBoolean209)
return ((TextureDefinition) class12).aShort208;
}
} else
return ((Class277) class277).anInt3569;
if (i <= 123)
return -68;
return ((Class277) class277).anInt3563;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception, ("gw.F("
+ (var_ha != null ? "{...}" : "null") + ',' + i + ','
+ (class277 != null ? "{...}" : "null") + ')'));
}
}
|
59c2e65d-af40-4bae-9dc9-a2c946c10553
| 8
|
public <T> void loadingMatches(final ObjectMapper<T> objectMapper) {
try {
while (getXmlStreamReader().hasNext()) {
getXmlStreamReader().nextTag();
if (getXmlStreamReader().getEventType() == XMLStreamConstants.START_ELEMENT) {
if (getXmlStreamReader().getLocalName().equals(LIVESCORE_DATA)) {
getXmlStreamReader().nextTag();
while (getXmlStreamReader().hasNext()) {
if (getXmlStreamReader().getEventType() == XMLStreamConstants.START_ELEMENT) {
if (SPORT.equals(xmlStreamReader.getLocalName())) {
JAXBElement<T> matchTypeJAXBElement = getUnmarshaller().unmarshal(getXmlStreamReader(), type);
T sportType = matchTypeJAXBElement.getValue();
objectMapper.buildRowFromMatchType(sportType);
}
}
getXmlStreamReader().next();
}
}
}
}
} catch (XMLStreamException e) {
LOGGER.warn("Can't load file", e);
} catch (JAXBException e) {
LOGGER.warn("Can't load file", e);
}
}
|
5166473c-084f-4153-8333-75ac90dbc0a0
| 4
|
private static TypeArgument[] parseTypeArgs(String sig, Cursor c) throws BadBytecode {
ArrayList args = new ArrayList();
char t;
while ((t = sig.charAt(c.position++)) != '>') {
TypeArgument ta;
if (t == '*' )
ta = new TypeArgument(null, '*');
else {
if (t != '+' && t != '-') {
t = ' ';
c.position--;
}
ta = new TypeArgument(parseObjectType(sig, c, false), t);
}
args.add(ta);
}
return (TypeArgument[])args.toArray(new TypeArgument[args.size()]);
}
|
0f63b221-2963-4bd8-90ae-a58ef7c72b91
| 9
|
private LinkedList<Vector2> findPath(Vector2 goal) {
// Get start position and direction
Vector2 start = iState.getAgentPosition();
int currentDirection = iState.getAgentDirection();
// Tentative G score
int tentativeG;
// Allows us to build the optimal path later
HashMap<Vector2, Vector2> cameFrom = new HashMap<Vector2, Vector2>();
// f and g scores as HashMap data structures
final HashMap<Vector2, Integer> g = new HashMap<Vector2, Integer>();
final HashMap<Vector2, Integer> f = new HashMap<Vector2, Integer>();
// Initialize the f and g scores of each position in the worldMap to 0
HashMap<Vector2, LocationInformation> worldMap = iState.getWorldMap();
Iterator<Entry<Vector2, LocationInformation>> it = worldMap.entrySet()
.iterator();
while (it.hasNext()) {
Vector2 pos = it.next().getKey();
f.put(pos, 0);
g.put(pos, 0);
}
// Open and closed sets. Note that the open set uses a priority queue on
// f-scores.
PriorityQueue<Vector2> open = new PriorityQueue<Vector2>(11,
new Comparator<Vector2>() { // This comparator ensures the
// priority queue is sorted by
// lowest f values.
public int compare(Vector2 a, Vector2 b) {
return f.get(a) - f.get(b);
}
});
Set<Vector2> closed = new HashSet<Vector2>();
g.put(start, 0);
f.put(start,
g.get(start)
+ Heuristics
.estimateCost(start, goal, currentDirection));
// Linked List to keep track of neighbors, as well as Vector2 elements
// for the neighbor and current node being expanded.
LinkedList<Vector2> neighbors;
Vector2 neighbor;
Vector2 current;
// Add the start node to the open set
open.add(start);
while (!open.isEmpty()) {
current = open.remove(); // This is always the lowest f-cost value
// since open is a priority queue
// Goal state reached, contruct the path
if (current.equals(goal)) {
return constructPath(cameFrom, goal);
}
// Move current to the closed set
open.remove(current);
closed.add(current);
// Look at all neighbors of the current position
neighbors = iState.neighbors(current);
Iterator<Vector2> it2 = neighbors.iterator();
while (it2.hasNext()) {
neighbor = it2.next();
// Compute the direction between the neighbor and
// current node being expanded
currentDirection = Vector2.vectorToDirection(Vector2.sub(
neighbor, current));
tentativeG = g.get(current)
+ InternalState.adjacentCost(current, neighbor,
currentDirection);
if (closed.contains(neighbor) && tentativeG >= g.get(neighbor)) {
continue;
}
// Update the appropriate data structures with new values if a
// better path was found
if (g.get(neighbor) == 0 || tentativeG < g.get(neighbor)) {
cameFrom.put(neighbor, current);
g.put(neighbor, tentativeG);
// This uses the heuristic that estimates cost based on both
// turns and Manhattan distance.
f.put(neighbor,
g.get(neighbor)
+ Heuristics.estimateCost(neighbor, goal,
currentDirection));
if (!open.contains(neighbor)) {
open.add(neighbor);
}
}
}
}
// No path was found, return null
return null;
}
|
0676fb64-cc92-4981-a86a-3508fa0c1dec
| 1
|
public Project updateProject(String projectName, String projectID,
String startDate, String endDate, String scope, String status,
String category, String outcome, String lastUpdated,
String updatedBy) {
Project prj = manager.find(Project.class, projectID);
if (prj != null) {
prj.setProjectName(projectName);
prj.setProjectID(projectID);
prj.setFromDate(startDate);
prj.setToDate(endDate);
prj.setScope(scope);
prj.setStatus(status);
prj.setCategory(category);
prj.setOutcome(outcome);
prj.setLastUpdated(lastUpdated);
prj.setUpdatedBy(scope);
}
return prj;
}
|
3e0d0b69-c6dc-4e05-b07b-380ea611c893
| 7
|
private boolean isDragOk(final java.io.PrintStream out,
final java.awt.dnd.DropTargetDragEvent evt) {
boolean ok = false;
// Get data flavors being dragged
java.awt.datatransfer.DataFlavor[] flavors = evt
.getCurrentDataFlavors();
// See if any of the flavors are a file list
int i = 0;
while (!ok && i < flavors.length) {
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support
// added.
// Is the flavor a file list?
final DataFlavor curFlavor = flavors[i];
if (curFlavor
.equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor)
|| curFlavor.isRepresentationClassReader()) {
ok = true;
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support
// added.
i++;
} // end while: through flavors
// If logging is enabled, show data flavors
if (out != null) {
if (flavors.length == 0)
log(out, "FileDrop: no data flavors.");
for (i = 0; i < flavors.length; i++)
log(out, flavors[i].toString());
} // end if: logging enabled
return ok;
} // end isDragOk
|
f4e76664-1cfa-4d93-babd-bfcfb080cf34
| 2
|
public static String squeeze(String s) {
s = StringDemo.allTrim(s);
int count = StringDemo.spaceCount(s);
char c[] = s.toCharArray();
char c1[] = new char[c.length - count];
for (int i = 0, j = 0; i < c.length; i++) {
if (c[i] != ' ') {
c1[j] = c[i];
j++;
}
}
s = new String(c1);
return s;
}
|
2efe593b-59ce-47d9-a5c9-5148e6ff0de4
| 7
|
public static String doNameRequest(String userID, Boolean isGroup) throws ParseException
{
URL vkRequest;
String jsonResponse;
JSONObject obj;
JSONArray array;
JSONParser parser = new JSONParser();
if (userID.isEmpty())
return null;
try
{
if (isGroup)
vkRequest = new URL("http://api.vk.com/method/groups.getById?group_id=" + userID);
else
vkRequest = new URL("http://api.vk.com/method/users.get?user_ids=" + userID);
BufferedReader reader = new BufferedReader(new InputStreamReader(vkRequest.openStream()));
jsonResponse = reader.readLine();
obj = (JSONObject)parser.parse(jsonResponse);
array = (JSONArray)obj.get("response");
obj = (JSONObject)array.get(0);
if(obj.containsKey("deactivated"))
return null;
if (isGroup)
return (String)obj.get("name");
else
return ((String)obj.get("first_name") + " " + (String)obj.get("last_name"));
}
catch(IOException e)
{return null;}
catch(NullPointerException e)
{return null;}
catch(IndexOutOfBoundsException e)
{return null;}
}
|
eebacfa9-8384-49b4-9443-3edbf8523c6c
| 8
|
public void getPeopleYouMightKnowToFile(FileWriter f) throws IOException {
ArrayList<String> ppl = new ArrayList<>();
for (User user : followers) {
if (user.getFollowers().size() == 0) {
ppl.add("The user: " + user.getName() + " doesn't follow anybody.\n");
} else {
for (User personYouMightKnow : user.getFollowers()) {
if (!personYouMightKnow.getName().equals(this.getName())) {
boolean alreadyAdded = false;
for (String aux : ppl) {
if (aux.contains(personYouMightKnow.getName())) {
alreadyAdded = true;
}
}
if (!alreadyAdded) {
ppl.add("You might know: " + personYouMightKnow.getName() + ".\n");
}
}
}
}
}
f.write("Dear " + this.getName() + ":\n");
for (String s : ppl) {
f.write(s);
}
}
|
38a3767f-8e01-4cc4-987b-2fbf515d8941
| 8
|
public static void main(String[] args) {
boolean teste = true;
MenuOpenHash menuOpenHash = null;
MenuClosedHash menuClosedHash = null;
MenuHma menuHma = null;
Scanner entrada = new Scanner(System.in);
while(teste) {
short opcao;
System.out.println("\n\n1- Open Hash\n2- Closed Hash\n3- HMA\n4- Sair");
opcao = entrada.nextShort();
switch(opcao) {
case 1:
if(menuOpenHash == null) {
menuOpenHash = new MenuOpenHash();
}
menuOpenHash.start();
break;
case 2:
if(menuClosedHash == null) {
menuClosedHash = new MenuClosedHash();
}
menuClosedHash.start();
break;
case 3:
if(menuHma == null) {
menuHma = new MenuHma();
}
menuHma.start();
break;
case 4:
teste = false;
System.out.println("Até Logo. õ/");
break;
default:
System.out.println("Opção inválida.");
}
}
entrada.close();
}
|
2ad07b3f-0150-49d9-8e5e-9d3b71e33304
| 5
|
@Override
public boolean valid() {
if (options.useBOB.get() && options.beastOfBurden.bobSpace() > 0 && System.currentTimeMillis() > script.nextSummon.get()) {
if (!ctx.summoning.summoned() || ctx.summoning.timeLeft() <= nextRenew) {
return ctx.summoning.canSummon(options.beastOfBurden);
}
}
return false;
}
|
5bb2e865-1351-40cf-bc7b-846af784a992
| 2
|
public static void main(String args[])
{
long begin=System.currentTimeMillis();
int total=1632442;
int limit=108829;
ExecutorService executorService=Executors.newFixedThreadPool(total/limit);
String name="";
for(int i=0;i<=total/limit;i++)
{
name="T"+i;
executorService.execute(new SetPaperAuthorList(i*limit, limit,name));
}
executorService.shutdown();
while(!executorService.isTerminated()){}
long end=System.currentTimeMillis();
System.out.println("total time: "+(end-begin)/1000+" seconds.");
}
|
a41f75ef-32c9-4db7-9b44-166d3598c85f
| 9
|
public String replaceDocRootDir(String htmlstr) {
// Return if no inline tags exist
int index = htmlstr.indexOf("{@");
if (index < 0) {
return htmlstr;
}
String lowerHtml = htmlstr.toLowerCase();
// Return index of first occurrence of {@docroot}
// Note: {@docRoot} is not case sensitive when passed in w/command line option
index = lowerHtml.indexOf("{@docroot}", index);
if (index < 0) {
return htmlstr;
}
StringBuilder buf = new StringBuilder();
int previndex = 0;
while (true) {
final String docroot = "{@docroot}";
// Search for lowercase version of {@docRoot}
index = lowerHtml.indexOf(docroot, previndex);
// If next {@docRoot} tag not found, append rest of htmlstr and exit loop
if (index < 0) {
buf.append(htmlstr.substring(previndex));
break;
}
// If next {@docroot} tag found, append htmlstr up to start of tag
buf.append(htmlstr.substring(previndex, index));
previndex = index + docroot.length();
if (configuration.docrootparent.length() > 0 && htmlstr.startsWith("/..", previndex)) {
// Insert the absolute link if {@docRoot} is followed by "/..".
buf.append(configuration.docrootparent);
previndex += 3;
} else {
// Insert relative path where {@docRoot} was located
buf.append(pathToRoot.isEmpty() ? "." : pathToRoot.getPath());
}
// Append slash if next character is not a slash
if (previndex < htmlstr.length() && htmlstr.charAt(previndex) != '/') {
buf.append('/');
}
}
return buf.toString();
}
|
f16d6c30-ae23-424d-8229-cf55402401c9
| 0
|
public GeoJsonObject()
{
type = getClass().getSimpleName();
}
|
036dc37e-8f0a-4e70-8926-bed25f3ad765
| 2
|
@Override
public String getMessageErreur(int index) throws Exception {
if (index >= 0 && index < erreurs.size()) {
return erreurs.get(index);
} else {
throw new Exception("Index d'activité hors limite.");
}
}
|
7bfcac85-b996-496d-9f90-20604065d43a
| 8
|
public void zoomOut(boolean center){
double x = EditorWindow.getPanelWidth()/2;
double y = EditorWindow.getPanelHeight()/2;
if ((mouseX-mainX)/tileBuffer.getMapPixelWidth() < 0 ||
(mouseX-mainX)/tileBuffer.getMapPixelWidth() > 1 ||
(mouseY-mainY)/tileBuffer.getMapPixelHeight() < 0 ||
(mouseY-mainY)/tileBuffer.getMapPixelHeight() > 1){
center = true;
}
if (!center){
x = mouseX;
y = mouseY;
}
if (blockSize > 4){
blockSize -= zoomAmount;
mainX += (x - mainX)/(((blockSize+zoomAmount))/zoomAmount);
mainY += (y - mainY)/(((blockSize+zoomAmount))/zoomAmount);
} else {
if (tileBuffer.getMapPixelWidth() < EditorWindow.getPanelWidth() &&
tileBuffer.getMapPixelHeight()< EditorWindow.getPanelHeight())
zoomFit(false);
}
}
|
0a50297b-d64d-4bb6-85d5-4d60a9621ab0
| 6
|
public static boolean containsAny(Collection<?> source,
Collection<?> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return false;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return true;
}
}
return false;
}
|
28245426-a7e8-4fc4-b3f4-c4d079d1cb6f
| 0
|
public void setPruebaCollection(Collection<Prueba> pruebaCollection) {
this.pruebaCollection = pruebaCollection;
}
|
4f33ef3d-4c38-48c8-b348-88dc787ed4d3
| 9
|
private boolean r_verb_suffix() {
int among_var;
int v_1;
int v_2;
int v_3;
// setlimit, line 164
v_1 = limit - cursor;
// tomark, line 164
if (cursor < I_pV)
{
return false;
}
cursor = I_pV;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 164
// [, line 165
ket = cursor;
// substring, line 165
among_var = find_among_b(a_4, 94);
if (among_var == 0)
{
limit_backward = v_2;
return false;
}
// ], line 165
bra = cursor;
switch(among_var) {
case 0:
limit_backward = v_2;
return false;
case 1:
// (, line 200
// or, line 200
lab0: do {
v_3 = limit - cursor;
lab1: do {
if (!(out_grouping_b(g_v, 97, 259)))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_3;
// literal, line 200
if (!(eq_s_b(1, "u")))
{
limit_backward = v_2;
return false;
}
} while (false);
// delete, line 200
slice_del();
break;
case 2:
// (, line 214
// delete, line 214
slice_del();
break;
}
limit_backward = v_2;
return true;
}
|
64a6fe89-e524-4f5a-a472-d49002c944be
| 2
|
@Override
public String convertToText(String language, String filePath) {
StringBuilder responseText = new StringBuilder();
try {
int responseCode = sendImage(language, filePath, responseText);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseText.toString();
}
|
3e54ff19-4d00-4527-8b85-7807dd828aa0
| 3
|
private FieldIdentifier findField(String name, String typeSig) {
for (Iterator i = fieldIdents.iterator(); i.hasNext();) {
FieldIdentifier ident = (FieldIdentifier) i.next();
if (ident.getName().equals(name) && ident.getType().equals(typeSig))
return ident;
}
return null;
}
|
5a8a4a8c-f4b6-48ed-a0e4-4470cc9884ee
| 8
|
private void checkOSStarted(VirtualMachine virtualMachine)
throws Exception {
String startTimeout = virtualMachine.getProperty(VirtualMachineConstants.START_TIMEOUT);
boolean checkTimeout = startTimeout != null;
int remainingTries = 0;
if (checkTimeout) {
remainingTries = Integer.parseInt(startTimeout) / START_RECHECK_DELAY;
}
while (true) {
Exception ex = null;
try {
if (HypervisorUtils.isLinuxGuest(virtualMachine)) {
ExecutionResult executionResult = exec(
virtualMachine, "/bin/echo check-started");
HypervisorUtils.checkReturnValue(executionResult);
break;
} else if (HypervisorUtils.isWindowsGuest(virtualMachine)) {
ExecutionResult executionResult = exec(
virtualMachine, "Echo check-started");
HypervisorUtils.checkReturnValue(executionResult);
break;
} else {
ex = new Exception("Guest OS not supported");
}
} catch (Exception e) {
if (checkTimeout && remainingTries-- == 0) {
ex = new Exception("Virtual Machine OS was not started. Please check you credentials.");
}
}
if (ex != null) {
throw ex;
}
Thread.sleep(1000 * START_RECHECK_DELAY);
}
}
|
2f533294-163b-4efa-8140-1fedfb8791f1
| 5
|
public static void GedExportTest(ArrayList<Dwarf> dwarfs) throws SAXException, IOException {
PrintWriter writer = new PrintWriter("dwarf.ged", "UTF-8");
for (int i = 0; i < dwarfs.size(); i++) {
if (dwarfs.get(i).getGender().contentEquals("MALE")) {
if (dwarfs.get(i).getSpouse() != null) {
writer.println("0 @F" + dwarfs.get(i).getId() + "@ FAM");
writer.println("1 HUSB @I" + dwarfs.get(i).getId() + "@");
writer.println("1 WIFE @I" + dwarfs.get(i).getSpouse().getId() + "@");
for (int j = 0; j < dwarfs.get(i).getChildren().size(); j++) {
writer.println("1 CHIL @I" + dwarfs.get(i).getChildren().get(j).getId() + "@");
}
writer.println("");
}
}
}
for (int i = 0; i < dwarfs.size(); i++) {
writer.println("0 @I" + dwarfs.get(i).getId() + "@ INDI");
writer.println("1 NAME " + dwarfs.get(i).getName());
writer.println("1 SEX " + dwarfs.get(i).getGender().substring(0, 1));
writer.println("1 BIRT");
writer.println("2 DATE " + dwarfs.get(i).getBirthday() + " " + dwarfs.get(i).getBirthyear());
writer.println("1 DEAT");
writer.println("2 DATE " + dwarfs.get(i).getDeathday() + " " + dwarfs.get(i).getDeathyear());
writer.println("");
}
writer.close();
}
|
c3bfdcc1-16d6-4012-bcc9-dbc72c100141
| 7
|
private void placeZAxis(final List<Player> orderedPlayerList) {
ListIterator<Player> it = orderedPlayerList.listIterator();
boolean hasLegalSpot = true;
while (it.hasNext() && hasLegalSpot) {
Player player = it.next();
Set<PlanetEntrance> availableEntrances = galaxy.getAvailableSpots();
if (availableEntrances.size() < 2) {
break;
} else {
hasLegalSpot = false;
checkLegal:
for (PlanetEntrance p : availableEntrances) {
Set<PlanetEntrance> otherEntrances = new HashSet<PlanetEntrance>(availableEntrances);
otherEntrances.remove(p);
for (PlanetEntrance p2 : otherEntrances) {
if (p.getPlanet() != p2.getPlanet()) {
hasLegalSpot = true;
break checkLegal;
}
}
}
}
if (hasLegalSpot) {
MultiMenuPlaceZAxis placeZAxisMenu = menuFactory.newMultiMenuPlaceZAxis(galaxy.getAvailableSpots(), player);
MultiMenuPlaceZAxisChoices choices = placeZAxisMenu.doSelection(factory);
PlanetEntrance entrance = choices.getEntrance();
PlanetEntrance exit = choices.getExit();
entrance.getPlanet().connect(exit.getPlanet(), entrance.getEntrance(), exit.getEntrance(), true, factory);
}
}
}
|
56232dbd-7911-4a00-a7a5-39b652cc6f4c
| 3
|
public void setEnderchestContents(ItemStack[] contents)
{
for (int i = 0; i < Enderchest.length; i++)
{
if (i < contents.length && contents[i] != null)
Enderchest[i] = contents[i].clone();
else
Enderchest[i] = null;
}
}
|
6eb630c2-77a0-48e5-8123-3dde9ba30749
| 1
|
@Override
protected void setReaction(Message message) {
try {
String url = getUrl(message.text);
reaction.add( getDefinition(url) );
} catch (Exception e) {
setError("Cannot load given URL.", e);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.