text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
public void executeTask() {
/* Redundant code here in the event Server and Client start diverting. */
try {
/* Casting to appropriate object. */
switch (node.NODE) {
case SERVER: {
server = (Server) node;
if (RoutingTable.getInstance().registerServer(server)) {
System.out.println("Registered server: "
+ node.getHostname());
selfClient = new Client();
selfClient.setCurrentIP(InetAddress.getLocalHost()
.getHostAddress());
selfClient.setHostname(InetAddress.getLocalHost()
.getHostName());
selfClient.setPort(ServerReceiverServlet.LISTENING_PORT);
selfClient.setUsername("Client "
+ DCServer.getLocalHostname());
selfClient.COMMAND = COMMAND_TYPE.REGISTER_NODE;
buffer = selfClient.toBytes();
dataGram = new DatagramPacket(buffer, buffer.length);
dataGram.setPort(server.getCurrentPort());
dataGram.setAddress(InetAddress.getByName(server
.getCurrentIP()));
}
break;
}
case CLIENT: {
client = (Client) node;
if (RoutingTable.getInstance().registerClient(client)) {
System.out.println("Registered client: "
+ node.getHostname());
selfServer = new Server();
selfServer.setCurrentIP(InetAddress.getLocalHost()
.getHostAddress());
selfServer.setHostname(InetAddress.getLocalHost()
.getHostName());
selfServer.setPort(ServerReceiverServlet.LISTENING_PORT);
selfServer.setUsername("Server "
+ DCServer.getLocalHostname());
selfServer.COMMAND = COMMAND_TYPE.REGISTER_NODE;
buffer = selfServer.toBytes();
dataGram = new DatagramPacket(buffer, buffer.length);
dataGram.setPort(client.getCurrentPort());
dataGram.setAddress(InetAddress.getByName(client
.getCurrentIP()));
}
break;
}
case NODE: {
break;
}
default: {
break;
}
}
/* NULL indicates no node was registered. */
if (dataGram != null) {
SocketManager.getInstance().sendDatagram(dataGram);
}
} catch (IOException e) {
e.printStackTrace();
}
stopTask();
} | 7 |
public List<Strichart> getAlleStricharten() {
ResultSet resultSet;
List<Strichart> listeStricharten = new ArrayList<Strichart>();
try {
resultSet = db
.executeQueryStatement("SELECT * FROM Stricharten");
while (resultSet.next()) {
listeStricharten.add(new Strichart(resultSet, db));
}
resultSet.close();
} catch (SQLException e) {
System.out.println(e);
return null;
}
return listeStricharten;
} | 2 |
@Override
protected void initPrototypeId(int id)
{
String s;
int arity;
switch (id) {
case Id_constructor: arity=1; s="constructor"; break;
case Id_toString: arity=1; s="toString"; break;
case Id_toLocaleString: arity=1; s="toLocaleString"; break;
case Id_toSource: arity=0; s="toSource"; break;
case Id_valueOf: arity=0; s="valueOf"; break;
case Id_toFixed: arity=1; s="toFixed"; break;
case Id_toExponential: arity=1; s="toExponential"; break;
case Id_toPrecision: arity=1; s="toPrecision"; break;
default: throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(NUMBER_TAG, id, s, arity);
} | 8 |
@Override
public String strip(String s) throws Exception {
int length = s.length();
if (oldChars.length < length + 1) {
oldChars = new char[length + 1];
}
s.getChars(0, length, oldChars, 0);
oldChars[length] = '\0'; // avoiding explicit bound check in while
// find first non-printable,
// if there are none it ends on the null char I appended
int newLen = -1;
while (oldChars[++newLen] >= ' ');
// no control characters found? early bail out with existing string
if (newLen == length)
return s;
for (int j = newLen; j < length; j++) {
char ch = oldChars[j];
if (ch >= ' ') {
oldChars[newLen] = ch; // the while avoids repeated overwriting here when newLen==j
newLen++;
}
}
return new String(oldChars, 0, newLen);
} | 5 |
public static boolean printText(int textId) {
switch(textId) { // texts taken from http://www.mahnerfolg.de/
case 1:
System.out.printf("Sehr geehrter Herr Kunde,\n" +
"\n" +
"in Bezug auf unsere Rechnung Nr.: %d mussten wir heute feststellen, dass Ihre Zahlung bei uns noch nicht eingegangen ist. Sollten Sie die Zahlung bereits vorgenommen haben, dann setzen Sie sich bitte mit uns in Verbindung, um den Sachverhalt zu klären. Möglicherweise konnten wir Ihre Zahlung nicht zuordnen, weil z.B. der Verwendungszweck nicht korrekt angegeben wurde.\n" +
"\n" +
"Mit freundlichen Grüßen\n" +
"\n" +
"Firma Muster\n", invoiceId);
return true;
case 2:
System.out.printf("Sehr geehrter Herr Kunde,\n" +
"\n" +
"in Bezug auf unsere Rechnung Nr.: %d und unsere 1. Mahnung mussten wir heute feststellen, dass Ihre Zahlung bei uns noch immer nicht eingegangen ist. Sicherlich haben Sie bislang vergessen, die Zahlung vorzunehmen. Dies sollten Sie nun jedoch umgehend nachholen.\n" +
"Sollten Sie die Zahlung bereits vorgenommen haben, dann setzen Sie sich bitte mit uns in Verbindung, um dies abzuklären. Möglicherweise konnten wir Ihre Zahlung nicht zuordnen, weil z.B. der Verwendungszweck nicht korrekt angegeben wurde.\n" +
"\n" +
"Mit freundlichen Gruessen\n" +
"Firma Muster\n", invoiceId);
return true;
case 3:
System.out.printf("Sehr geehrter Herr Kunde,\n" +
"\n" +
"in Bezug auf unsere Rechnung Nr.: %d und unsere 1. sowie auch unsere 2. Mahnung mussten wir heute feststellen, dass Ihre Zahlung bei uns noch immer nicht eingegangen ist. Dies bedeutet einen einseitigen Vertragsbruch Ihrerseits. Nach geltendem Recht könnten wir die offene Forderung bereits jetzt bei Gericht anmelden. Wir geben Ihnen jedoch trotzdem noch eine letzte Möglichkeit, Ihre vertragliche Verpflichtung zu erfüllen, indem Sie unverzüglich die ausstehende Summe in Höhe von 243.00 EURO an uns zur Zahlung bringen.\n" +
"Nach geltendem Recht sind wir befugt, die anfallenden Kosten geltend zu machen. Alle bereits angefallenen und noch entstehenden Kosten (Mahnkosten, Rechtsanwalts- und Gerichtskosten) gehen zu Ihren Lasten.\n" +
"\n" +
"Vermeiden Sie unnötigen Ärger und weitere Kosten und erfüllen Sie den mit uns abgeschlossenen Vertrag!\n", invoiceId);
return true;
default:
System.out.println("FEHLER: Der angegebene Mahnungstext wurde nicht gefunden.");
return false;
}
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MessageBus other = (MessageBus) obj;
if (mapSubscriberToTopics == null) {
if (other.mapSubscriberToTopics != null)
return false;
} else if (!mapSubscriberToTopics.equals(other.mapSubscriberToTopics))
return false;
if (mapTopicToSubscribers == null) {
if (other.mapTopicToSubscribers != null)
return false;
} else if (!mapTopicToSubscribers.equals(other.mapTopicToSubscribers))
return false;
return true;
} | 9 |
public boolean commit(){
if(isSetForCommitting()){
session.getTransaction().commit();
return true;
}
return false;
} | 1 |
public byte[] toByteArray() {
return cw == null ? null : cw.toByteArray();
} | 1 |
public static Color convertStringToColor(String in) {
Color out = Color.black;
if (in.equals("yellow")) {
out = Color.yellow;
} else if (in.equals("blue")) {
out = Color.blue;
} else if (in.equals("red")) {
out = Color.red;
} else if (in.equals("green")) {
out = Color.green;
}
return out;
} | 4 |
public void stopGame() {
// Setting isRunning to false will
// make the thread stop (see run())
this.isRunning = false;
// Unset the game model...
this.view.setModel(null);
// Stop listening for events
this.view.removeKeyListener(this.keyListener);
// Make sure we wait until the thread has stopped...
if (this.gameThread != null) {
while (this.gameThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// Pass the call on.
Thread.currentThread().interrupt();
}
}
}
} | 3 |
public synchronized boolean deleteVar(String key)
{
Utils.logger.log(Level.INFO, "Deletting var " + key);
List<String> oldConfiguration;
oldConfiguration = this.currentConfig;
FileWriter fileWriter;
try
{
fileWriter = new FileWriter(this.configFile, false);
}
catch(final IOException exception)
{
Utils.logger.log(Level.WARNING, "Failed to write config file!", exception);
return false;
}
final PrintWriter printWriter = new PrintWriter(new BufferedWriter(fileWriter));
if(oldConfiguration != null)
for(String string : oldConfiguration)
{
if(string.startsWith(key + ":"))
continue;
printWriter.println(string);
}
printWriter.close();
this.currentConfig = readSmallTextFile(this.configFile);
Utils.logger.log(Level.INFO, "Config file wrote");
return true;
} | 4 |
private static void validateAmt(char[][] vMap) {
int manAmt = 0, boxAmt = 0, aimAmt = 0;
for (char[] row : vMap) {
for (char cell : row) {
switch (cell) {
case SokobanMap.AIM_CHAR:
aimAmt++;
break;
case SokobanMap.BOX_CHAR:
boxAmt++;
break;
case SokobanMap.MAN_CHAR:
manAmt++;
break;
case SokobanMap.MAN_AIM_CHAR:
manAmt++;
aimAmt++;
break;
case SokobanMap.BOX_AIM_CHAR:
boxAmt++;
aimAmt++;
break;
}
}
}
if (manAmt != 1) {
throw new RuntimeException(
"man only should have one man control position!!! now the man position amount is:" + manAmt);
}
if (boxAmt != aimAmt) {
throw new RuntimeException("BOX char amount is not equels AIM char amount!!! BOX amt:" + boxAmt
+ ",AIM amt:" + aimAmt);
}
} | 9 |
public static boolean deleteFile(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
if (!deleteFile(new File(file, children[i]))) {
return false;
}
}
}
return file.delete();
} | 3 |
private String readInput() throws IOException {
return this.keyboard.readLine();
} | 0 |
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("ChangeFocusAction");
OutlinerCellRendererImpl textArea = null;
boolean isIconFocused = true;
Component c = (Component) e.getSource();
if (c instanceof OutlineButton) {
textArea = ((OutlineButton) c).renderer;
} else if (c instanceof OutlineLineNumber) {
textArea = ((OutlineLineNumber) c).renderer;
} else if (c instanceof OutlineCommentIndicator) {
textArea = ((OutlineCommentIndicator) c).renderer;
} else if (c instanceof OutlinerCellRendererImpl) {
textArea = (OutlinerCellRendererImpl) c;
isIconFocused = false;
}
// Shorthand
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
//System.out.println(e.getModifiers());
switch (e.getModifiers()) {
case 0:
if (isIconFocused) {
changeFocusToTextArea(node, tree, layout);
} else {
changeFocusToIcon(node, tree, layout);
}
break;
case 1:
if (isIconFocused) {
changeToParent(textArea, tree, layout);
} else {
}
break;
}
} | 8 |
public void printCita(int codpac, int numcita)throws IOException{
if(pacienteExiste(codpac)){
String nompac = rpacs.readUTF();
String citapath = getCitaPath(nompac, codpac, numcita);
File cita = new File(citapath);
if(cita.exists()){
System.out.println("Cita de " + nompac);
RandomAccessFile rcita = new RandomAccessFile(cita,"rw");
//leo dr
int coddr = rcita.readInt();
if(doctorExiste(coddr)){
//el puntero esta antes del nombre
String drname = rdocs.readUTF();
System.out.println("Cita Atendida por "+coddr+"-" +
drname);
//fecha
System.out.println("Fecha: " + new Date(rcita.readLong()));
//sintomas
System.out.println("Sintomas: " + rcita.readUTF());
//Monto
System.out.println("Monto: Lps."+ rcita.readDouble());
//estado
System.out.print("Estado: ");
switch(rcita.readInt()){
case CITA_ATENDIDA:
System.out.println("Atendida");
break;
case CITA_CANCELADA:
System.out.println("Cancelada");
break;
default:
System.out.println("Pendiente");
}
//receta
System.out.println("Receta: " + rcita.readUTF());
rcita.close();
}
}
else
System.out.println("Cita No Existe");
}
else
System.out.println("Paciente No Existe");
} | 5 |
public void render() {
AbstractAlgorithm imgGen;
/*
* Now generate the appropriate image! Done separate to above so will
* re-draw whenever any button is pressed.
*/
double scaleSize = gui.getScaleSize();
int width = (int) (gui.imageWidth() / scaleSize), height = (int) (gui
.imageHeight() / scaleSize);
if (imageType.equals("Spots")) {
imgGen = new ImageSpots(colourType, width, height,
gui.getTextArea());
} else if (imageType.equals("Spots 2")) {
imgGen = new ImageSpots2(colourType, width, height,
gui.getTextArea());
} else if (imageType.equals("Spiral")) {
imgGen = new ImageDiamond(colourType, width, height,
gui.getTextArea());
} else {
imgGen = new TrueRandom(colourType, width, height);
}
gui.drawImage(imgGen, scaleSize);
} | 3 |
public void setBackLeftTrim(int backLeftTrim) {
this.backLeftTrim = backLeftTrim;
if ( ccDialog != null ) {
ccDialog.getTrim3().setText( Integer.toString(backLeftTrim) );
}
} | 1 |
public byte[] gextractEncPayload() {
int i, j, k = 0, n_ent;
int total_size;
byte[] temp;
total_size = gmeasureEncPayload();
if (total_size == 0) return null;
n_ent = encrypted_truth_table.size() ;
// Create a result byte array with the appropriate size
byte[] res = new byte[total_size];
// Now gather all the data into a result byte array
for (i = 0; i < n_ent; i++, k++) // Encrypted perm bytes
res[k] = encrypted_perm[i];
for (i = 0; i < n_ent; i++) { // Encrypted truth table
temp = encrypted_truth_table.elementAt(i) ;
for (j = 0; j < temp.length; j++, k++)
res[k] = temp[j];
}
if (isAliceOutput()) { // Hashes of Alice codes
for (j = 0; j < hcode0.length; j++, k++)
res[k] = hcode0[j];
for (j = 0; j < hcode1.length; j++, k++)
res[k] = hcode1[j];
}
return res;
} | 7 |
public ImageIcon getImageIcon(byte imageData[], int size) throws IOException {
if(imageData==null)
return null;
ImageIcon ico = new ImageIcon(imageData);
int h=ico.getIconHeight();
int w=ico.getIconWidth();
if(size<=0)// || (h <= size && w <= size))
return ico;
int newh,neww;
if(h >= w) {
newh=size;
neww= (int) (w * (1.0 * newh / h));
} else {
neww=size;
newh= (int) (h * (1.0 * neww / w));
}
ico.setImage(
ico.getImage().getScaledInstance(neww, newh, Image.SCALE_SMOOTH));
return ico;
} | 3 |
protected void linkProgram(List<VertexAttrib> attribLocations) throws LWJGLException {
if (!valid())
throw new LWJGLException("trying to link an invalid (i.e. released) program");
uniforms.clear();
// bind user-defined attribute locations
if (attribLocations != null) {
for (VertexAttrib a : attribLocations) {
if (a != null)
GL20.glBindAttribLocation(program, a.location, a.name);
}
}
attachShaders();
GL20.glLinkProgram(program);
int comp = GL20.glGetProgrami(program, GL20.GL_LINK_STATUS);
int len = GL20.glGetProgrami(program, GL20.GL_INFO_LOG_LENGTH);
String err = GL20.glGetProgramInfoLog(program, len);
if (err != null && err.length() != 0)
log = err + "\n" + log;
if (log != null)
log = log.trim();
if (comp == GL11.GL_FALSE)
throw new LWJGLException(log.length()!=0 ? log : "Could not link program");
fetchUniforms();
fetchAttributes();
} | 9 |
public void SetOver(boolean isOver){
boolean test = false;
if (test || m_test) {
System.out.println("GameWindow :: SetOver() BEGIN");
}
getDrawing().SetOver(isOver);
if (test || m_test) {
System.out.println("GameWindow :: SetOver() END");
}
} | 4 |
private boolean r_postlude() {
int among_var;
int v_1;
// repeat, line 70
replab0: while(true)
{
v_1 = cursor;
lab1: do {
// (, line 70
// [, line 72
bra = cursor;
// substring, line 72
among_var = find_among(a_1, 3);
if (among_var == 0)
{
break lab1;
}
// ], line 72
ket = cursor;
switch(among_var) {
case 0:
break lab1;
case 1:
// (, line 73
// <-, line 73
slice_from("i");
break;
case 2:
// (, line 74
// <-, line 74
slice_from("u");
break;
case 3:
// (, line 75
// next, line 75
if (cursor >= limit)
{
break lab1;
}
cursor++;
break;
}
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
} | 8 |
public static Vector<String> getAllProxyIPs(String ipLibURL)
throws ClientProtocolException, IOException, URISyntaxException {
Vector<String> IPsPageLinks = getIPsPageLinks(ipLibURL);// "http://www.youdaili.cn/"
Vector<String> onePageIPs = new Vector<String>();
Vector<String> allIPs = new Vector<String>();
for (int i = 0; i < IPsPageLinks.size(); i++) {
String url = IPsPageLinks.get(i);
String[] html = new HTML().getHTML(url);
int iReconn1 = 0;
int reConnectTimes1 = 5;
while (html[1].equals("null")) {
if (iReconn1 == (reConnectTimes1 - 1)) {
System.out.println("连续" + reConnectTimes1
+ "次失败,继续获取吓一条IP库的代理IP");
break;
}
System.out.println("****重新链接****");
html[1] = new HTML().getHTML(ipLibURL)[1];
iReconn1++;
}
System.out.println("next");
int page = 2;
while (html[0].equals("200")) {
System.out.println("start finding proxy IPs under this link: "
+ url);
// JTARunInfo.paintImmediately(JTARunInfo.getBounds());
onePageIPs = getProxyIPs(html[1]);
for (int j = 0; j < onePageIPs.size(); j++) {
String s = onePageIPs.get(j);
if (!allIPs.contains(s)) {
allIPs.add(s);
}
}
if (url.contains("_")) {
url = url.substring(0, url.indexOf("_") + 1) + page
+ ".html";
} else {
url = url.substring(0, url.indexOf(".html")) + "_" + page
+ ".html";
}
// System.out.println("page = "+page);
html = new HTML().getHTML(url);
int iReconn = 0;
int reConnectTimes = 5;
while (html[1].equals("null")) {
if (iReconn == (reConnectTimes - 1)) {
System.out.println("连续" + reConnectTimes
+ "次失败,继续获取吓一条IP库的代理IP");
break;
}
System.out.println("****重新链接****");
html = new HTML().getHTML(url);
iReconn++;
}
System.out.println("״状态吗" + html[0]);
page++;
}
}
System.out.println("total proxy IP number::: " + allIPs.size());
return allIPs;
} | 9 |
@Override
public HeightMap applyTo(HeightMap... heightMaps){
double[][] finalHeights = new double[heightMaps[0].getHeights().length][heightMaps[0].getHeights()[0].length];
for(HeightMap heightMap: heightMaps) {
double[][] currentHeights = heightMap.getHeights();
for (int x = 0; x < finalHeights.length; x++) {
if (x % 10 == 0) System.out.println("AverageFilter" + 100 * x / finalHeights.length + "% complete");
for (int y = 0; y < finalHeights[0].length; y++) {
finalHeights[x][y] += currentHeights[x][y] / heightMaps.length;
}
}
}
return new HeightMap(finalHeights);
} | 4 |
public static boolean isIsomorphic(String one, String two) {
if (null == one || null == two) {
return false;
}
if (one.length() != two.length()) {
return false;
}
if (one.length() == 1) {
return true;
}
Map<Character, Integer> mapA = countFrequencies(one);
Map<Character, Integer> mapB = countFrequencies(two);
Map<Integer, List<Character>> reversedTable = reverseTable(mapB);
for (Map.Entry<Character, Integer> entry : mapA.entrySet()) {
Integer frequency = entry.getValue();
List<Character> list = reversedTable.get(frequency);
if (null == list || list.isEmpty()) {
return false;
}
list.remove(0);
}
// now check if all characters/frequencies were removed
for (List<Character> values : reversedTable.values()) {
if (!values.isEmpty()) {
return false;
}
}
return true;
} | 9 |
public boolean isValidSudoku(char[][] board) {
int i ,j, k = 0;
for (i = 0; i< 3; i++)
{
for (j =0; j<9; j++)
choice[i][j] = new HashSet<Integer>();
}
for (i = 0;i<9;i++)
for (j = 0 ;j< 9 ; j++)
{
if (board[i][j] == '.')
{
k ++ ;
}else
{
int tmp = board[i][j] - '0';
if (!suitAble(i, j, tmp)) return false;
add(i,j,tmp,board);
}
}
return solute(board, k);
} | 6 |
public Object nextContent() throws JSONException {
char c;
StringBuffer sb;
do {
c = next();
} while (Character.isWhitespace(c));
if (c == 0) {
return null;
}
if (c == '<') {
return XML.LT;
}
sb = new StringBuffer();
for (;;) {
if (c == '<' || c == 0) {
back();
return sb.toString().trim();
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
c = next();
}
} | 7 |
protected void saveClusterer(String name, Clusterer clusterer,
Instances trainHeader, int[] ignoredAtts) {
File sFile = null;
boolean saveOK = true;
int returnVal = m_FileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
sFile = m_FileChooser.getSelectedFile();
if (!sFile.getName().toLowerCase().endsWith(MODEL_FILE_EXTENSION)) {
sFile = new File(sFile.getParent(), sFile.getName()
+ MODEL_FILE_EXTENSION);
}
m_Log.statusMessage("Saving model to file...");
try {
OutputStream os = new FileOutputStream(sFile);
if (sFile.getName().endsWith(".gz")) {
os = new GZIPOutputStream(os);
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
objectOutputStream.writeObject(clusterer);
if (trainHeader != null) objectOutputStream.writeObject(trainHeader);
if (ignoredAtts != null) objectOutputStream.writeObject(ignoredAtts);
objectOutputStream.flush();
objectOutputStream.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Save Failed",
JOptionPane.ERROR_MESSAGE);
saveOK = false;
}
if (saveOK)
m_Log.logMessage("Saved model (" + name
+ ") to file '" + sFile.getName() + "'");
m_Log.statusMessage("OK");
}
} | 7 |
public static ArrayList<bConsulta2> getMediaHoras(String data_in, Integer gmp, String arg_prod) throws SQLException, ClassNotFoundException {
ArrayList<bConsulta2> sts = new ArrayList();
Connection conPol = conMgr.getConnection("PD");
ResultSet rs;
if (conPol == null) {
throw new SQLException("Numero Maximo de Conexoes Atingida!");
}
try {
call = conPol.prepareCall("{call sp_consulta_mediahoras( ?, ?, ?)}");
call.setString(1, arg_prod);
call.setString(2, data_in);
call.setInt(3, gmp);
rs = call.executeQuery();
while (rs.next()) {
bConsulta2 bConsulta2 = new bConsulta2();
bConsulta2.setData_in(rs.getString("txt"));
bConsulta2.setPosto(rs.getString("posto"));
bConsulta2.setCont(rs.getInt("cont"));
sts.add(bConsulta2);
}
} finally {
if (conPol != null) {
conMgr.freeConnection("PD", conPol);
}
}
return sts;
} | 3 |
private Token matchNumber() {
SourcePosition pos = new SourcePosition(lineNo, columnNo);
StringBuilder sb = new StringBuilder();
boolean decimal = false;
int character = lookAhead(1);
while ((character >= '0' && character <= '9') || character == '.') {
if (decimal && character == '.') {
throw new LexerException("Unexcepted '.' character", lineNo, columnNo);
} else if (character == '.') {
decimal = true;
}
sb.append((char) character);
character = next();
}
return new Token(pos, TokenType.NUMBER, sb.toString());
} | 6 |
public static void main(String[] args) {
String ficPropertiesJdbc = "gsbJdbc.properties"; // nom du fichier de properties
Properties propertiesJdbc; // objet de propriétés (paramètres de l'appplication) pour Jdbc
FileInputStream input; // flux de lecture des properties
CtrlPrincipal ctrlPrincipal; // référence vers le contrôleur principal
// si au moins un paramètre a été passé sur la ligne de commandes
// le premier est le nom du fichier contenant les propriétés de connexion JDBC
if (args.length > 0) {
ficPropertiesJdbc = args[0];
}
// 1- instancier le singleton de connexion Jdbc en fonction d'un fichier de paramètres
// La classe Jdbc étant un singleton, la connexion s'obtient ainsi :
// Jdbc.getInstance().getConnexion()
// La connexion est utilisée dans les classes Dao
try {
FabriqueJdbc.creer(ficPropertiesJdbc);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Lanceur Main - Fichier de propriétés JDBC introuvable", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Lanceur Main - Erreur lors du chargement du fichier de propriétés JDBC", JOptionPane.ERROR_MESSAGE);
}
// 2 - ouvrir la connexion
try {
Jdbc.getInstance().connecter();
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Lanceur Main - connexion à la BDD - pilote JDBC non trouvé", JOptionPane.ERROR_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Lanceur Main - connexion à la BDD", JOptionPane.ERROR_MESSAGE);
}
// Pour lancer l'application, instancier le contrôleur principal
ctrlPrincipal = new CtrlPrincipal();
ctrlPrincipal.action();
} | 5 |
public static int RoomService(Client joueur) {
int tempDette = 0;
int choiceInt = -1;
boolean wrong = false;
System.out.println("Que voulez vous prendre?"
+ "\n pour de la nourriture tapez 1 (20€)"
+ "\n pour de la boisson tapez 2");
do {
String choice = keyboard.nextLine();
try {
choiceInt = Integer.parseInt(choice);
if (choiceInt != 1 && choiceInt != 2) {
throw new Exception("not 1, 2");
}
wrong = false;
} catch (Exception e) {
System.out.println("Mauvaise valeur inseree");
}
} while (wrong);
switch (choiceInt) {
case 1:
prendreNourriture(joueur);
tempDette += 20;
break;
case 2:
tempDette += prendreBoisson(joueur);
break;
}
return tempDette;
} | 6 |
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
AccessPerfiles accessPerfiles;
try {
accessPerfiles = em.getReference(AccessPerfiles.class, id);
accessPerfiles.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The accessPerfiles with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
List<AccessConfigUser> accessConfigUserListOrphanCheck = accessPerfiles.getAccessConfigUserList();
for (AccessConfigUser accessConfigUserListOrphanCheckAccessConfigUser : accessConfigUserListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This AccessPerfiles (" + accessPerfiles + ") cannot be destroyed since the AccessConfigUser " + accessConfigUserListOrphanCheckAccessConfigUser + " in its accessConfigUserList field has a non-nullable idPerfiles field.");
}
List<AccessRoles> accessRolesListOrphanCheck = accessPerfiles.getAccessRolesList();
for (AccessRoles accessRolesListOrphanCheckAccessRoles : accessRolesListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This AccessPerfiles (" + accessPerfiles + ") cannot be destroyed since the AccessRoles " + accessRolesListOrphanCheckAccessRoles + " in its accessRolesList field has a non-nullable idPerfil field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(accessPerfiles);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} | 7 |
protected void checkForHit(){
if (ballX>=(paddleX-ballSize)) { //check for a hit
if (ballY>=paddleY-ballSize+1 && ballY<=paddleY+paddleLength-1) {
hits++;
dx=left;
dy=0; // this is a direct hit
int paddleCenter = paddleY + paddleLength/2;
int ballCenter = ballY + ballSize/2;
double offset = ballCenter - paddleCenter;
double halfPaddle = paddleLength/2;
//set dx and dy dependent on region of paddle hit
double angleDeg = 90.0 + 60.0 * (offset/halfPaddle);
dx = -step * Math.sin(Math.toRadians(angleDeg));
if (offset < 0) {
dy = -Math.sqrt(step*step - dx*dx);
} else if (offset > 0) {
dy = Math.sqrt(step*step - dx*dx);
}
}
}
} | 5 |
private Individual tournamentSelection(Population pop) {
//Create a tournament population
Individual[] tournament = new Individual[GeneticAlgorithmConstants.TOURNAMENT_SIZE];
//For each place in the tournament get an individual
for (int i = 0; i < tournament.length - 1; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament[i] = pop.getIndividual(randomId);
}
//return the fittest individual
Individual fittest = tournament[0];
for (int i = 0; i < tournament.length - 1; i++) {
if (GeneticAlgorithmConstants.ISGENERALISING) {
if (fittest.getFitness() < tournament[i].getFitness()) { //compare fitness
fittest = tournament[i];
} else if (fittest.getFitness() == tournament[i].getFitness()) {
if (fittest.numRules > tournament[i].numRules) { //check which has smaller ruleset
fittest = tournament[i];
}
}
} else { //just compare fitness
if (fittest.getFitness() <= tournament[i].getFitness()) {
fittest = tournament[i];
}
}
}
return fittest;
} | 7 |
@Override
public void onEnable()
{
// Load config
File configFile = new File(this.getDataFolder(), "config.yml");
if(!configFile.exists())
{
configFile.getParentFile().mkdirs();
copy(this.getResource(configFile.getName()), configFile);
}
if(this.getConfig().getInt("version",1) < 2)
{
try
{
if(configFile.delete())
{
System.out.println("Deleting old config file...");
}
else
{
System.out.println("Unable to delete config.yml, you should do this manually and then reload the plugin.");
}
copy(this.getResource(configFile.getName()), configFile);
this.reloadConfig();
System.out.println("config.yml reloaded, new version: "+this.getConfig().getInt("version"));
}
catch(Exception e)
{
e.printStackTrace();
}
}
MAX_UPDATE_DISTANCE = getConfig().getInt("update-distance") ^ 2;
MAKE_PLAYERS_INVISIBLE = getConfig().getBoolean("make-players-invisible",true);
UNDISGUISE_ON_PVP = getConfig().getBoolean("undisguise-on-pvp",true);
UNDISGUISE_ON_CLICK = getConfig().getBoolean("undisguise-on-click",true);
BLACKLISTED_BLOCKS = new ArrayList<Integer>();
for(String sMaterial : getConfig().getStringList("blacklisted-blocks"))
{
Material m = Material.matchMaterial(sMaterial);
if(m != null)
{
BLACKLISTED_BLOCKS.add(m.getId());
}
else
{
this.getLogger().log(Level.INFO, "{0} is not a valid material!", sMaterial);
}
}
// Setup managers
this.disguiseManager = new DisguiseManager(this);
// Setup listeners
Bukkit.getPluginManager().registerEvents(new BlockDisguisePlayerListener(this), this);
Bukkit.getPluginCommand("bd").setExecutor(new BlockDisguiseCommandExecutor(this));
} | 6 |
private void managementPlanUpdate() {
// TODO add your handling code here:
//create an array of arrays to hold all values in chart form
String tempArray[][];
if (!Stakeholders.isEmpty()){
tempArray = new String[Stakeholders.size()][10];
for (int i = 0; i < Stakeholders.size(); i++){
tempArray[i][0] = Stakeholders.get(i).getName();
tempArray[i][1] = Stakeholders.get(i).getWants();
tempArray[i][2] = Stakeholders.get(i).getClassification();
tempArray[i][3] = Stakeholders.get(i).getAttitude();
tempArray[i][4] = String.format("%.3f", Stakeholders.get(i).getInfluence());
tempArray[i][5] = Stakeholders.get(i).getStrategy();
tempArray[i][6] = Stakeholders.get(i).getEngagement();
tempArray[i][7] = Stakeholders.get(i).getLastEngaged();
tempArray[i][8] = Stakeholders.get(i).getResponsible();
tempArray[i][9] = Stakeholders.get(i).getNotes();
}
}
else {
tempArray = new String [2][10];
for (int i = 0; i < 2; i++){
for (int e = 0; e < 10; e++){
tempArray[i][e] = "nada "+e;
}
}
}
//set the table model
managementPlanTable.setModel(new javax.swing.table.DefaultTableModel(
tempArray,
new String [] {
"Name", "Wants", "Classification", "Attitude", "Influence", "Strategy",
"<html>Method of<br>Engagement", "<html>Last<br>Engaged",
"<html>Responsible<br>Party", "Notes"
}
){
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, true, true, true, true};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];}
});
//add a listener to save changes in editable columns
managementPlanTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
managementPlanTablePropertyChange(evt);}});
//set table header height
managementPlanTable.getTableHeader().setPreferredSize(new Dimension(managementPlanTable.getColumnModel().getTotalColumnWidth(), 32));
//allow table word wrap
for (int i = 0; i < 10; i++)
{
managementPlanTable.getColumnModel().getColumn(i).setCellRenderer(new TableCellLongTextRenderer ());
}
//copy back the original order of the stakeholders if sorting was performed
Stakeholders.clear();
for(Stakeholder s : OriginalStakeholders)
{ Stakeholders.add(s); }
} | 6 |
public static double EuclideanDistance(ArrayList<Double> l1, ArrayList<Double> l2){
if(l1.size() != l2.size()){
System.err.print("erro in input size\n");
}
int size = l1.size();
double sum = 0;
for(int i = 0; i < size; i++){
sum += (l1.get(i) - l2.get(i)) * (l1.get(i) - l2.get(i));
}
return Math.sqrt(sum);
} | 2 |
private static void remove(CuratorFramework client, String command, String[] args) throws Exception {
if (args.length != 1) {
System.err.println("syntax error (expected remove <path>): " + command);
return;
}
String name = args[0];
if (name.contains("/")) {
System.err.println("Invalid node name" + name);
return;
}
String path = ZKPaths.makePath(PATH, name);
try {
client.delete().forPath(path);
} catch (KeeperException.NoNodeException e) {
// ignore
}
} | 3 |
@Override
public TurnAction next() {
// TODO Auto-generated method stub
TurnAction nextPossibleAction = null;
int checkedRow = currentRow;
int checkedTokens = iteratedState.checkRow(checkedRow)- 1;
boolean searchingForNext = !(checkedTokens >= 0);
while(searchingForNext){
checkedTokens = iteratedState.checkRow(checkedRow)- 1;
boolean tokensValid = (checkedTokens >= 0);
if(tokensValid){
searchingForNext = false;
nextPossibleAction = new TurnAction();
BoardState nextPossibleState = new BoardState(iteratedState.cloneRows());
nextPossibleState.setTokensInRow(checkedRow, checkedTokens);
nextPossibleAction.setTargetRow(checkedRow);
nextPossibleAction.setTokenAmount(nextPossibleState.checkRow(checkedRow)-checkedTokens);
}else if(checkedRow != maxRowNumber){
checkedRow++;
}
}
return nextPossibleAction;
} | 3 |
private static boolean validateStringLength(String param){
boolean isValid = false;
if(param.length() > 0){
isValid = true;
}
return isValid;
} | 1 |
public static boolean isRequestEnd(byte[] request, int length) {
if (length < 4) {
return false;
}
return request[length - 4] == '\r' &&
request[length - 3] == '\n' &&
request[length - 2] == '\r' &&
request[length - 1] == '\n';
} | 4 |
public void cargarTabla(int perfil){
System.out.println("tabla");
String[] columnas = getColumnas();
Class[] tipoDatosColumnas=getTipoColumnas();
Vector<Vector<Object>> contenidoTabla = new Vector();
contenidoTabla = getContenidoTabla(perfil);
modelo = new DefaultTableModel();
for(int i=0;i<modelo.getRowCount();i++)
modelo.removeRow(i);
modelo.setColumnIdentifiers(columnas);
for(int i=0;i<contenidoTabla.size();i++){
modelo.addRow(contenidoTabla.elementAt(i));
}
if(modelo.getRowCount()!=contenidoTabla.size()){
int r=campoRepetido();
while(r!=-1){
modelo.removeRow(r);
r=campoRepetido();
}
}
jTable1.setModel(modelo);
for(int i=1;i<columnas.length;i++){
jTable1.getColumnModel().getColumn(i).setCellEditor(new Clase_CellEditor());
jTable1.getColumnModel().getColumn(i).setCellRenderer(new Clase_CellRender());
}
} | 5 |
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
char c = 'A';
int asc = (int) c;
System.out.println(asc);
String message = null;
fr=new FileReader("MyTextFile.txt");
br =new BufferedReader(fr);
message = br.readLine();
System.out.println(message);
String [] msgArray = message.split(",");
for (int i = 0; i < msgArray.length; i++) {
System.out.println(msgArray[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.out.println("Nahi hai");
}
finally{
if(fr != null){
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} | 6 |
@Override
public void run(int interfaceId, int componentId) {
if (stage == -1) {
sendDialogue(SEND_2_OPTIONS, new String[] {
player.getDisplayName(), "I'd like to trade.",
"Can you repair my items for me?" });
stage = 1;
} else if (stage == 1) {
if (componentId == 1) {
sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] {
NPCDefinitions.getNPCDefinitions(npcId).name,
"Great! I buy and sell pickaxes and hatchets.",
"There are plenty to choose from." }, IS_NPC, npcId,
9827);
stage = 2;
} else if (componentId == 2) {
sendEntityDialogue(
SEND_2_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(npcId).name,
"Of course I can, though materials may cost you. Just ",
"hand me the item and I'll take a look." },
IS_NPC, npcId, 9827);
stage = 3;
}
} else if (stage == 2) {
ShopsHandler.openShop(player, 1);
end();
} else if (stage == 3) {
player.getPackets()
.sendGameMessage("Item repair is not yet added.");
end();
}
} | 6 |
public static void main(String[] args)
{
int numero = 0,c = 0;
for (int i = 0; i < 2; i++)
{
numero = Integer.parseInt(JOptionPane.showInputDialog(null, "Ingrese un Número Entero Positivo"));
if (numero > 0)
{
i = 2;
}
else
{
i = 0;
JOptionPane.showMessageDialog(null, "Debe de Ingresar Valores Enteros Positivos, es decir, Números Mayores a 0" );
}
}
long[] arreglo = new long[numero];
for (int i = 0; i < arreglo.length; i++)
{
arreglo[i] = (i * i);
}
for (int i = 0; i < arreglo.length; i++)
{
if (numero == arreglo[i])
{
i = arreglo.length;
c = 1;
}
}
if ((c == 1) || (numero == 1))
{
JOptionPane.showMessageDialog(null, "TRUE" );
}
else
{
JOptionPane.showMessageDialog(null, "FALSE" );
}
} | 7 |
public double getSpeed(){
return this.speed;
} | 0 |
void requireWhitespace() throws java.lang.Exception
{
char c = readCh();
if (isWhitespace(c)) {
skipWhitespace();
} else {
error("whitespace expected", c, null);
}
} | 1 |
public Widget createWidget(Composite parent, int style)
{
String tooltip = getTooltip();
GridData controlGD = new GridData( SWT.FILL, SWT.TOP, false, false );
// label
if ( control.getLabel() != null ) {
label = new Label( parent, SWT.NONE );
label.setText( control.getLabel() );
if ( tooltip != null ) label.setToolTipText( tooltip );
label.setLayoutData( new GridData( SWT.LEFT, SWT.TOP, false, false ) );
controlGD.horizontalSpan = 1;
} else {
controlGD.horizontalSpan = 2;
}
// dropDownList
style = style | SWT.BORDER;
if ( control instanceof MultiSelectListT )
{
style |= SWT.MULTI;
}
else if ( control instanceof SingleSelectListT )
{
style |= SWT.SINGLE;
}
listBox = new List( parent, style );
listBox.setLayoutData( controlGD );
// listBox items
java.util.List<ListItemT> listItems = control instanceof MultiSelectListT ? ( (MultiSelectListT) control ).getListItem()
: ( (SingleSelectListT) control ).getListItem();
for ( ListItemT listItem : listItems )
{
listBox.add( listItem.getUiRep() );
}
// tooltip
if ( tooltip != null ) listBox.setToolTipText( tooltip );
// init value
String initValue = (String) ControlHelper.getInitValue( control, getAtdl4jOptions() );
if ( initValue != null )
setValue( initValue, true );
return parent;
} | 8 |
public static IntegrationMethods fromString(String name) {
if (name != null) {
for (IntegrationMethods b : IntegrationMethods.values()) {
if (name.equalsIgnoreCase(b.name)) {
return b;
}
}
}
return null;
} | 3 |
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
out.write("<head>\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
out.write("<title>Untitled Document</title>\n");
out.write("\n");
out.write("\n");
out.write("<script src=\"facefiles/jquery-1.2.2.pack.js\" type=\"text/javascript\"></script>\n");
out.write("<link href=\"facefiles/facebox.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />\n");
out.write("\n");
out.write("<link href=\"css/css1.css\" rel=\"stylesheet\" type=\"text/css\" />\n");
out.write("<script type=\"text/javascript\" src=\"jquery/jquery-1.7.1.min.js\"></script>\n");
out.write("</head>\n");
out.write("<script type=\"text/javascript\">\n");
out.write("function hideall(){\n");
out.write("$(\"#a11\").hide();\n");
out.write("$(\"#a12\").hide();\n");
out.write("$(\"#a14\").hide();\n");
out.write("$(\"#a15\").hide();\n");
out.write("$(\"#a21\").hide();\n");
out.write("$(\"#a23\").hide();\n");
out.write("$(\"#a24\").hide();\n");
out.write("}\n");
out.write("\n");
out.write("$(document).ready(function(){\n");
out.write("hideall();\n");
out.write("\n");
out.write("$(\"#q11\").click(function(){\n");
out.write("hideall();\n");
out.write("$(\"#a11\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("\n");
out.write("$(\"#q12\").click(function(){\n");
out.write("hideall();\n");
out.write("$(\"#a12\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("\n");
out.write("\n");
out.write("$(\"#q14\").click(function(){\n");
out.write("hideall();\n");
out.write("$(\"#a14\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("\n");
out.write("$(\"#q15\").click(function(){\n");
out.write("hideall();\n");
out.write("$(\"#a15\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("\n");
out.write("$(\"#q24\").click(function(){hideall();\n");
out.write("$(\"#a24\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("$(\"#q21\").click(function(){\n");
out.write("hideall();\n");
out.write("$(\"#a21\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("$(\"#q23\").click(function(){\n");
out.write("hideall();\n");
out.write("$(\"#a23\").toggle('slow');\n");
out.write("}\n");
out.write(");\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("$(\"#q21\").click(function(){\n");
out.write("$(\"#ResortRating\").toggle('slow');\n");
out.write("}\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write(");\n");
out.write("});\n");
out.write("</script>\n");
out.write("<body>\n");
out.write("<table width=\"865\" height=\"541\" border=\"1\">\n");
out.write(" <tr>\n");
out.write(" <td width=\"855\" align=\"left\"><div align=\"center\">Customer Information</div></td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td height=\"506\"><table width=\"855\" height=\"298\" border=\"1\">\n");
out.write(" <tr>\n");
out.write(" <td width=\"403\">Booking Information</td>\n");
out.write(" <td width=\"436\">Resort Information</td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td ><p id=\"q11\"><a href=\"JavaScript:void()\"> Find booking info</a></p>\n");
out.write(" <p id=\"q12\"><a href=\"JavaScript:void()\"> List all resort and days by Client</a></p>\n");
out.write(" <p id=\"q14\"><a href=\"JavaScript:void()\"> Find activities by string</a></p>\n");
out.write(" <p id=\"q15\"><a href=\"JavaScript:void()\"> Find agent by group</a></p></td>\n");
out.write(" <td><p id=\"q21\"><a href=\"JavaScript:void()\"> Find resort rating</a> </p>\n");
out.write(" <p id=\"q22\"><a href=\"query1.php?act=a22\"> List resorts have all amenities</a></p>\n");
out.write(" <p id=\"q23\"><a href=\"JavaScript:void()\">Most popular resort</a></p>\n");
out.write(" <p id=\"q24\"><a href=\"JavaScript:void()\">List number of resorts by country</a></p>\n");
out.write(" <p id=\"q25\"><a href=\"query1.php?act=a25\"> Country has highest average Sun Rate</a></p></td>\n");
out.write(" </tr>\n");
out.write(" </table>\n");
out.write(" <div id=\"a11\">\n");
out.write(" <p><strong>Booking Info</strong></p>\n");
out.write(" \n");
out.write(" <label></label>\n");
out.write(" <form id=\"form1\" name=\"form1\" method=\"post\" action=\"query1.php?act=a11\">\n");
out.write(" <label>Client Name\n");
out.write(" <input type=\"text\" name=\"value\" id=\"value\" />\n");
out.write("</label>\n");
out.write(" \n");
out.write(" <label>\n");
out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Search\" />\n");
out.write(" </label>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" <div id=\"a21\">\n");
out.write(" <p><strong>Resort Rating</strong></p>\n");
out.write(" <form id=\"form2\" name=\"form1\" method=\"post\" action=\"query1.php?act=a21\">\n");
out.write(" <label> Name of Resort\n");
out.write(" <input type=\"text\" name=\"value\" id=\"value\" />\n");
out.write(" </label>\n");
out.write(" \n");
out.write(" <label>\n");
out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Search\" />\n");
out.write(" </label>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" <div id=\"a24\">\n");
out.write(" <p><strong>Resort by city - country</strong></p>\n");
out.write(" <form id=\"form3\" name=\"form1\" method=\"post\" action=\"query1.php?act=a24\">\n");
out.write(" <label>City of Country \n");
out.write(" <input type=\"text\" name=\"value\" id=\"value\" />\n");
out.write(" </label>\n");
out.write(" \n");
out.write(" <label>\n");
out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Search\" />\n");
out.write(" </label>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" \n");
out.write(" <div id=\"a12\">\n");
out.write(" <p><strong>Resort and Day by client</strong></p>\n");
out.write(" <form id=\"form4\" name=\"form1\" method=\"post\" action=\"query1.php?act=a12\">\n");
out.write(" <label></label> \n");
out.write(" <label>\n");
out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Search\" />\n");
out.write(" </label>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" \n");
out.write(" <div id=\"a14\">\n");
out.write(" <p><strong>Find activities by name</strong></p>\n");
out.write(" <form id=\"form5\" name=\"form1\" method=\"post\" action=\"query1.php?act=a14\">\n");
out.write(" <label>Activitiy name\n");
out.write(" <input type=\"text\" name=\"value\" id=\"value\" />\n");
out.write("</label>\n");
out.write(" \n");
out.write(" <label>\n");
out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Search\" />\n");
out.write(" </label>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" <div id=\"a15\">\n");
out.write(" <p><strong>Find agent by group ID</strong></p>\n");
out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"query1.php?act=a15\">\n");
out.write(" <label>Group ID: \n");
out.write(" <input type=\"text\" name=\"value2\" id=\"value\" />\n");
out.write(" </label>\n");
out.write(" \n");
out.write(" <la23abel>\n");
out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Search\" />\n");
out.write(" </label>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" <div id=\"a23\">\n");
out.write(" <p><strong>The most popular resorts:</strong></p>\n");
out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"query1.php?act=a23\">\n");
out.write(" \n");
out.write(" \n");
out.write(" <label></label>\n");
out.write(" <p>\n");
out.write(" <label>\n");
out.write(" <input type=\"radio\" name=\"radio\" id=\"radio\" value=\"radio1\" />\n");
out.write(" One Sun Rate</label>\n");
out.write(" <label>\n");
out.write(" <input type=\"radio\" name=\"radio\" id=\"radio\" value=\"radio2\" />\n");
out.write(" Two Sun Rate</label>\n");
out.write(" <label>\n");
out.write(" <input type=\"radio\" name=\"radio\" id=\"radio\" value=\"radio3\" />\n");
out.write(" Three Sun Rate</label>\n");
out.write(" <label>\n");
out.write(" <input type=\"radio\" name=\"radio\" id=\"radio\" value=\"radio4\" />\n");
out.write(" Over all</label>\n");
out.write(" \n");
out.write(" <input type=\"submit\" name=\"button2\" id=\"button2\" value=\"Search\" />\n");
out.write(" </p>\n");
out.write(" </form>\n");
out.write(" </div> \n");
out.write(" \n");
out.write(" <p> </p> </td>\n");
out.write(" </tr>\n");
out.write("</table>\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} | 5 |
private void HelpInsert(IInfo<T> op){
if(op==null || !(op instanceof IInfo) )
return;
CAS_CHILD(op.p, op.l, op.newInternal,op.stamps.pLeftStamp,op.stamps.pRightStamp);
StateInfo<T> app = op.p.si.getReference();
if(app.isIFlag() && app.info == op){
op.p.si.compareAndSet(app, new StateInfo<T>(StateInfo.CLEAN,op), op.stamps.siStamp, ++op.stamps.siStamp);
}
} | 4 |
public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if(object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String) object).equalsIgnoreCase("false"))) {
return false;
} else if(object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String) object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a Boolean.");
} | 6 |
public double score(String dna) {
if (logOdds == null) calcLogOddsWeight();
char bases[] = dna.toCharArray();
double score = 0;
for (int i = 0; i < bases.length; i++)
score += getLogOdds(bases[i], i);
return score / length;
// return ((double) score) / (length * SCALE);
} | 2 |
public CtConstructor getClassInitializer() {
CtMember.Cache memCache = getMembers();
CtMember cons = memCache.consHead();
CtMember consTail = memCache.lastCons();
while (cons != consTail) {
cons = cons.next();
CtConstructor cc = (CtConstructor)cons;
if (cc.isClassInitializer())
return cc;
}
return null;
} | 2 |
static String toHex4String(int pValue)
{
String s = Integer.toString(pValue, 16);
//force length to be four characters
if (s.length() == 0) {return "0000" + s;}
else
if (s.length() == 1) {return "000" + s;}
else
if (s.length() == 2) {return "00" + s;}
else
if (s.length() == 3) {return "0" + s;}
else{
return s;
}
}//end of Log::toHex4String | 4 |
public Sound(String soundFile) {
//soundFile is a .wav audio file from music file
try {
File file = new File(soundFile);
if (file.exists()) {
AudioInputStream sound = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(sound);
}
else {
throw new RuntimeException("Sound: RuntimeException Error: " + soundFile);
}
}
catch (MalformedURLException ex) {
ex.printStackTrace();
throw new RuntimeException("Sound: Malformed URL Exception Error: " + ex);
}
catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
throw new RuntimeException("Sound: Unsupported Audio File Exception Error: " + ex);
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException("Sound: IOException Error: " + ex);
}
catch (LineUnavailableException ex) {
ex.printStackTrace();
throw new RuntimeException("Sound: Line Unavailable Exception Error: " + ex);
}
} | 5 |
public boolean load()
{
if (!this.Valid) {
return false;
}
int i2 = 24;
try
{
DataInputStream localDataInputStream = new DataInputStream(this.rawdata);
int i = localDataInputStream.readInt();
int j = localDataInputStream.readInt();
int k = localDataInputStream.readInt();
int m = localDataInputStream.readInt();
int n = localDataInputStream.readInt();
int i1 = localDataInputStream.readInt();
byte[] arrayOfByte1 = new byte[j - i2];
localDataInputStream.read(arrayOfByte1);
if (i != 779316836)
{
throw new IOException("Not an audio file");
}
if (m != 1)
{
throw new IOException("Not correct encoding");
}
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
byte[] arrayOfByte2 = new byte[4096];
int i3;
while ((i3 = localDataInputStream.read(arrayOfByte2)) > 0)
{
localByteArrayOutputStream.write(arrayOfByte2, 0, i3);
}
this.ad = new AudioData(localByteArrayOutputStream.toByteArray());
return true;
}
catch (IOException localIOException)
{
System.err.println("SunSound.load(): Failed attempt to read Audio Resource:");
localIOException.printStackTrace();
}
return false;
} | 5 |
public static boolean eat(final Player player, Item item, int slot) {
Food food = Food.forId(item.getId());
if (food == null)
return false;
if (player.getFoodDelay() > Utils.currentTimeMillis())
return true;
if (!player.getControlerManager().canEat(food))
return true;
player.getPackets().sendGameMessage(
"You eat the "
+ ItemDefinitions.getItemDefinitions(food.getId())
.getName().toLowerCase() + ".");
player.setNextAnimation(EAT_ANIM);
player.addFoodDelay(1800);
player.FOODS_EATEN++;
if (player.FOODS_EATEN == 1000) {
for (Player players : World.getPlayers()) {
players.getPackets().sendGameMessage(
"<img=8> <col=996600>"
+ player.getDisplayName() + " just ate 1,000 foods!");
}
}
if (player.getActionManager().getActionDelay() < 3)
player.getActionManager().setActionDelay(3);
player.getInventory()
.getItems()
.set(slot,
food.getNewId() == 0 ? null : new Item(food.getNewId(),
1));
player.getInventory().refresh(slot);
int hp = player.getHitpoints();
player.heal(food.getHeal() * 10, food.getExtraHP() * 10);
if (player.getHitpoints() > hp)
player.getPackets().sendGameMessage("It heals some health.");
player.getInventory().refresh();
if (food.effect != null) {
food.effect.effect(player);
}
return true;
} | 9 |
public void action() {
do {
ACLMessage msgPerception = myAgent.blockingReceive();
// if(log.isLoggable(Logger.WARNING))
// try {
// log.log(Logger.WARNING, "Nachricht empfangen: " + ((WumpusPerception) msgPerception.getContentObject()).toString());
// } catch (UnreadableException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
if (msgPerception.getPerformative() == ACLMessage.INFORM){
perception = new WumpusPerception(msgPerception.getContent());
// ContentElement content = null;
// try {
// content = man.extractContent(msgPerception);
// if(log.isLoggable(Logger.WARNING))
// log.log(Logger.WARNING, "Content extrahiert");
// perception = (WumpusPerception) content;
// } catch (UngroundedException e) {
// if(log.isLoggable(Logger.WARNING))
// log.log(Logger.WARNING, "Ungrounded Exception: " + e.getMessage());
// throw new RuntimeException(e);
// } catch (CodecException e) {
// if(log.isLoggable(Logger.WARNING))
// log.log(Logger.WARNING, "Codec Exception: " + e.getMessage());
// throw new RuntimeException(e);
// } catch (OntologyException e) {
// if(log.isLoggable(Logger.WARNING))
// log.log(Logger.WARNING, "Ontology Exception: " + e.getMessage());
// throw new RuntimeException(e);
// }
if(log.isLoggable(Logger.WARNING))
log.log(Logger.WARNING, "Hunter-Perception: " + perception.toString());
} else {
if(log.isLoggable(Logger.WARNING)) {
log.log(Logger.WARNING, "Keine INFORM-Message, sondern: " + msgPerception.getPerformative());
log.log(Logger.WARNING, "(REFUSE wäre: " + ACLMessage.REFUSE + ")");
}
break;
}
String nextAction = null;
nextAction = ((HunterAgent) myAgent).processPerceptionAndGetNextStep(perception);
reply = msgPerception.createReply();
reply.setPerformative(ACLMessage.REQUEST);
reply.setContent(nextAction);
myAgent.send(reply);
} while (true);
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// msg.setContent(WumpusConsts.ACTION_DEREGISTER);
// myAgent.send(msg);
} | 4 |
public void shiftRelease() {
HUD hud = null;
for (int i = (huds.size() - 1); i >= 0; i--) {
hud = huds.get(i);
hud.shiftRelease();
}
} | 1 |
private void insertEmployeeIntoTable(Employee employee, int daysOfMonth) {
if (employee.isCallWorker() || employee.isClerk() || employee.isMuseumEducator()) {
Object[] fields = new Object[daysOfMonth + 3];
fields[0] = employee.getEmployeeNumber();
fields[1] = employee.getFullName();
fields[2] = employee.getContractHours();
for (int i = 1; i <= daysOfMonth; i++) {
calendar.set(Calendar.DAY_OF_MONTH, i);
WorkHours hour = RoosterProgramma.getQueryManager().getWorkHours(employee, getDate(calendar));
fields[i + 2] = hour.getShouldWork();
}
model.addRow(fields);
}
} | 4 |
@Override
public final void enter() {
// cancel enter action if checkField caused a state change
if (checkField()) {
return;
}
menu.getContinueButton().setEnabled(true);
IPlayer player = game.getCurrentPlayer();
// Only enable rolling if player has not rolled for movement this round
if (!player.hasRolledPlayer()) {
menu.getRollDieButton().setEnabled(true);
} else if (player.getSteps() > 0) {
menu.getDie().setIcon(DieGraphic.getDiefromInt(player.getSteps()));
}
if (player.getSteps() == 0 && player.hasRolledPlayer()) {
game.setState(new ZombieState(window));
}
} | 5 |
public boolean setItem(FieldItem item, Position position) {
if (isOccupied(position)) {
return false;
}
if (isInField(item)) {
return false;
}
if (!item.getPosition().equals(position)) {
return false;
}
field.put(position, item);
itemCounterUp(item);
return true;
} | 3 |
public void startGame() {
// Arrange pieces
this.window.board.clearBoard();
this.window.board.arrangeWhitePieces();
this.window.board.arrangeBlackPieces();
// Game active
this.isActive = true;
// White and black player
this.playerWhite = new Player(true);
this.playerBlack = new Player(false);
// White begins
this.playersTurn = playerWhite;
// this.isWhitesTurn = true;
this.setWindowTitle();
// Timer
this.stopTime();
this.startTime();
} | 0 |
private void JBSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBSalvarActionPerformed
try{
if(consultaAnt != null){
int linhaMedico = JTabelaMedico.getSelectedRow();
int linhaPaciente = JTabelaPaciente.getSelectedRow();
try{
consultaAnt.setCodMedico( this.verificaMedico((int) modeloMedico.getValueAt(linhaMedico,0)));
consultaAnt.setCodPaciente((int) modelo.getValueAt(linhaPaciente,0));
consultaAnt.setCodProcedimento(JCBProcedimento.getSelectedIndex());
}catch(Exception e){
Logger.getLogger(CadastrarConsultaUI.class.getName()).log(Level.SEVERE, e.getMessage());
}
try{
// Manipulação da Data
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date data = sdf.parse(JFTDataConsulta.getText());
consultaAnt.setData(data);
}catch(ParseException e){}
// consultaAnt.setProcedimento(JTAProcedimento.getText()); Virou ComboBox
consultaAnt.setObservacao(JTAObservacao.getText());
ConsultaController.obterInstancia().alterar(consultaAnt);
}else{
Consulta consulta = new Consulta();
// Obtenção das Linhas
int linhaMedico = JTabelaMedico.getSelectedRow();
int linhaPaciente = JTabelaPaciente.getSelectedRow();
// Obtem os dados pela linha selecionada
try{
consulta.setCodMedico(this.verificaMedico((int) modeloMedico.getValueAt(linhaMedico,0)));
consulta.setCodPaciente((int) modelo.getValueAt(linhaPaciente,0));
consulta.setCodProcedimento(JCBProcedimento.getSelectedIndex());
}catch(Exception e){
Logger.getLogger(CadastrarConsultaUI.class.getName()).log(Level.SEVERE, e.getMessage());
}
// consulta.setProcedimento(JTAProcedimento.getText()); Virou ComboBox
consulta.setObservacao(JTAObservacao.getText());
try{
// Manipulação da Data
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date data = sdf.parse(JFTDataConsulta.getText());
consulta.setData(data);
}catch(ParseException e){}
ConsultaController.obterInstancia().cadastrar(consulta);
}
JOptionPane.showMessageDialog(this, "Cadastrado com sucesso !");
this.dispose();
}catch(Exception e){
JOptionPane.showMessageDialog(this, "Erro: "+e.getMessage(),"ERRO",0);
}
}//GEN-LAST:event_JBSalvarActionPerformed | 6 |
public GetSetPixelDemo() {
MinuetoWindow window; // The Minueto window
// Create a 640 by 480 window
window = new MinuetoFrame(640, 480, true);
// Show the game window.
window.setVisible(true);
MinuetoImage image = new MinuetoImage(640, 480);
boolean first = true;
// Game/rendering loop
while(true) {
// Clear the window.
window.clear(MinuetoColor.BLACK);
window.draw(image, 0, 0);
// Draw 10 horizontal lines and 10 vertical lines.
for(int i = 0; i< 11; i++) {
if (i < 5) {
image.setPixel(50+i, 50+i, MinuetoColor.BLUE);
} else {
image.setPixel(50+i,60-i, MinuetoColor.GREEN);
}
if (first) {
if (i < 5) {
System.out.println("Pxel Color: " + image.getPixel(50+i, 50+i));
} else {
System.out.println("Pxel Color: " + image.getPixel(50+i, 60-i));
}
}
}
first = false;
// Render all graphics in the back buffer.
window.render();
}
} | 5 |
public void setName(String name) {
this.name = name;
} | 0 |
@Test
public void wrap_book() {
Book<Color, CopyPaper<Color>, Paper<Color>, List<CopyPaper<Color>>> book1 = new Book<Color, CopyPaper<Color>, Paper<Color>, List<CopyPaper<Color>>>();
BookBuilderSpec<?> bookBuilder = wrap(book1);
assertTrue(book1 == bookBuilder.getWrappedObject());
Book<? extends Color, ? extends Paper<? extends Color>, ? extends Recordable<? extends Color>, ? extends List<? extends Paper<? extends Color>>> book = bookBuilder.toBook();
assertTrue(book1 == book);
} | 9 |
public void findSignChange() {
double upLim = this.upLimPlus();
double lowLim = this.lowLimNeg();
// Choosing delta for intervals
double delta = (Math.abs(upLim) + Math.abs(lowLim)) / 10000;
System.out.println("delta = " + delta);
double point1 = lowLim;
double point2 = lowLim + delta;
double value1 = 0;
double value2 = 0;
int step = 0;
while (point2 < upLim) {
value1 = calcValue(point1);
value2 = calcValue(point2);
if ((value1 * value2) <= 0){
step++;
System.out.println(step + ")");
System.out.println("f(" + point1 + ") = " + value1);
System.out.println("f(" + point2 + ") = " + value2);
newtonAlg(point1 + delta / 2);
}
point1 = point2;
point2 = point2 + delta;
}
} | 2 |
public static int lcs(String a, String b) {
int lenA = a.length(), lenB = b.length();
int[] x = new int[lenB + 1];
int[] y = new int[lenB + 1];
int[] w = new int[lenA];
for (int i = 0; i <= lenA; i++) {
for (int j = 0; j <= lenB; j++) {
if (i == 0 || j == 0)
x[j] = 0;
else if (a.charAt(i - 1) == b.charAt(j - 1))
x[j] = y[j - 1] + 1;
else
x[j] = Math.max(y[j], x[j - 1]);
}
if (i > 0)
w[i - 1] = x[lenB];
for (int j = 0; j <= lenB; j++)
y[j] = x[j];
}
return w[lenA - 1];
} | 7 |
@Override
public GameState[] allActions(GameState state, Card card, int time) {
GameState[] states = new GameState[1];
states[0] = state;
if(time == Time.DAY)
{
GameState frenchState = new GameState(state);
states = new GameState[]{frenchDay(frenchState,card,false)};
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
states = temp.allActions(new GameState(state), card, time);
}
else if(time == Time.NIGHT)
{
//Nothing to do
}
return states;
} | 3 |
public void blink() {
if (getWorld().getObjects(Dolphin.class).size() != 0) {
getXD = ((Dolphin) getWorld().getObjects(Dolphin.class).get(0)).getX();
getYD = ((Dolphin) getWorld().getObjects(Dolphin.class).get(0)).getY();
setLocation(getXD + 30, getYD + 25);
}
if (shocked > 0) {
if (blinks <= 30) {
setImage(a1);
}
else if (blinks > 30 && blinks < 60) {
setImage(a2);
}
}
else if (shocked == 0) {
getWorld().removeObject(this);
}
} | 6 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Visist Handler");
HttpSession session = request.getSession();
if(session.getAttribute("user") != null && !session.getAttribute("user").equals("")){
response.sendRedirect("2.0/dashboard.jsp");
}else {
response.sendRedirect("2.0/index.jsp");
}
} | 2 |
@Override
public void addUser(UserDTO user) throws SQLException {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
catch (Exception e) {
System.err.println("Error while adding an user!");
}
finally {
if (session != null && session.isOpen())
session.close();
}
} | 3 |
@Override
public boolean execute(Player player) {
if(!this.hasSecondWord()) {
// if there is no second word, we don't know where to go...
GameEngine.gui.println("Go where?");
return false;
}
String direction = this.getSecondWord();
// Try to leave current room.
Room nextRoom = player.getCurrentRoom().getExit(direction);
if (nextRoom == null)
GameEngine.gui.println("There is no door!");
else {
player.changeRoom(nextRoom);
GameEngine.gui.println(player.getCurrentRoom().getLongDescription());
if(player.getCurrentRoom().getImageName() != null)
GameEngine.gui.showImage(player.getCurrentRoom().getImageName());
}
return false;
} | 3 |
private double getSautDeGeneration() {
return Double.parseDouble(vTxtGeneration.getText());
} | 0 |
public static void main(String[] args)
{
try
{
String currentPath = System.getProperty("user.dir");
System.out.println("currentPath :" + currentPath );
ComJdbc.connection( currentPath + File.separator + "configdb.properties");
ConfigGetDb getsql = new ConfigGetDb(currentPath + File.separator + "selectSql.ddl");
String strSql = getsql.execSql; // 将sql中将;去掉
ResultSet rs = ComJdbc.execQuery(strSql);
ResultSetMetaData metaDate = rs.getMetaData();
int columnCount = metaDate.getColumnCount();
List exportData = new ArrayList();
Map row1 = null;
while (rs.next())
{
row1 = new LinkedHashMap();
for (int i = 1; i <= columnCount; i++)
{
row1.put(new Integer(i), rs.getString(i));
}
exportData.add(row1);
}
LinkedHashMap map = new LinkedHashMap();
for (int i = 1; i <= columnCount; i++)
{
map.put(new Integer(i), metaDate.getColumnName(i));
}
CsvUtil.createCSVFile(exportData, map, currentPath + File.separator, args[0]);
} catch (SQLException e)
{
e.printStackTrace();
} finally
{
ComJdbc.close();
}
} | 4 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if((msg.amISource(mob))
&&(msg.tool() instanceof Ability))
{
if(remember.contains(msg.tool()))
return true;
if(forgotten.contains(msg.tool()))
{
mob.tell(L("You still can't remember @x1!",msg.tool().name()));
return false;
}
if(mob.fetchAbility(msg.tool().ID())==msg.tool())
{
if(CMLib.dice().rollPercentage()>(mob.charStats().getSave(CharStats.STAT_SAVE_MIND)+25))
{
forgotten.add((Ability)msg.tool());
mob.tell(L("You can't remember @x1!",msg.tool().name()));
return false;
}
else
remember.add((Ability)msg.tool());
}
}
return super.okMessage(myHost,msg);
} | 7 |
public Core() {
infoPacksByType = new HashMap<Class<? extends IInfoPack>, IInfoPack>();
systems = new ArrayList<ISystem>();
entitiesByID = new HashMap<String, IEntity>();
entitiesByPack = new HashMap<Class<? extends IInfoPack>, List<IEntity>>();
handlersByMessage = new HashMap<Class<? extends IMessage>, List<IMessageHandler<? extends IMessage>>>();
this.timeLastChecked = System.nanoTime();
LOGGER.log(Level.INFO, "Core initialized.");
} | 4 |
private String makeDurationString(Duration dur) {
Dur d = VEventHelper.durationToICALDur(dur);
String out = "";
int days = d.getDays();
if (days > 0)
out += days + " " + (days == 1 ? ApplicationSettings.getInstance().getLocalizedMessage("lvip.day") : ApplicationSettings.getInstance().getLocalizedMessage("lvip.days"));
int hrs = d.getHours();
if (hrs > 0) {
if (out.length() > 0)
out += ", ";
out += +hrs + " " + (hrs == 1 ? ApplicationSettings.getInstance().getLocalizedMessage("lvip.hr") : ApplicationSettings.getInstance().getLocalizedMessage("lvip.hrs"));
}
int mins = d.getMinutes();
if (mins > 0) {
if (out.length() > 0)
out += ", ";
out += mins + " " + (mins == 1 ? ApplicationSettings.getInstance().getLocalizedMessage("lvip.min") : ApplicationSettings.getInstance().getLocalizedMessage("lvip.mins"));
}
return out;
} | 8 |
public synchronized void publishCurrentMarket(MarketDataDTO md) throws Exception {
int bv = md.buyVolume;
int sv = md.sellVolume;
String product = md.product;
String exString = "publishers.CurrentMarketPublisher#publishCurrentMarket";
if (ExceptionHandler.checkIntNegative(bv, exString) && ExceptionHandler.checkIntNegative(sv, exString)
&& ExceptionHandler.checkString(product, exString)) {
Price bp = md.buyPrice;
bp = checkPrice(bp);
Price sp = md.sellPrice;
sp = checkPrice(sp);
if (!myPublisher.getSubscribers().isEmpty()) {
HashMap<String, HashMap> subscribers = myPublisher.getSubscribers();
if (subscribers.get(product) != null) {
HashMap<Integer, User> users = subscribers.get(product);
if (!users.isEmpty()) {
Iterator it = users.entrySet().iterator();
while (it.hasNext()) {
Map.Entry userEntry = (Map.Entry) it.next();
if (userEntry.getValue() != null) {
User u = (User) userEntry.getValue();
u.acceptCurrentMarket(product, bp, bv, sp, sv);
}
}
}
}
}
}
} | 8 |
public static void asm_incf(Integer akt_Befehl, Prozessor cpu) {
Integer f = getOpcodeFromToBit(akt_Befehl, 0, 6);
Integer result = cpu.getSpeicherzellenWert(f) + 1;
// Speicherort abfragen
if(getOpcodeFromToBit(akt_Befehl, 7, 7) == 1) {
// in f Register speichern
cpu.setSpeicherzellenWert(f, result, true);
}
else {
// in w Register speichern
cpu.setW(result, true);
}
cpu.incPC();
} | 1 |
public static int randomized_partiton(int[] array, int start, int end){
Random r = new Random();
int a = r.nextInt(end);
while(a < start){
a = r.nextInt(end);
}
exchange(array,a,end);
return partition(array,start,end);
} | 1 |
public static String getLibraryTitle(Class<?> libraryClass) {
if (libraryClass == null) {
errorMessage("Parameter 'libraryClass' null in method"
+ "'getLibrayTitle'");
return null;
}
if (!Library.class.isAssignableFrom(libraryClass)) {
errorMessage("The specified class does not extend class "
+ "'Library' in method 'getLibraryTitle'");
return null;
}
Object o = runMethod(libraryClass, "getTitle", new Class[0],
new Object[0]);
if (o == null) {
errorMessage("Method 'Library.getTitle' returned "
+ "'null' in method 'getLibraryTitle'");
return null;
}
return ((String) o);
} | 4 |
@EventHandler(ignoreCancelled = true)
public void onBreak(BlockBreakEvent event) {
Arena arena = OITG.instance.getArenaManager().getArena(event.getPlayer());
if (arena != null && !arena.isBlockBreakingAllowed()) {
event.setCancelled(true);
event.getPlayer().sendMessage(OITG.prefix + ChatColor.RED + "Block breaking is disabled in this arena.");
return;
}
arena = OITG.instance.getArenaManager().getArena(event.getBlock().getLocation());
if (arena == null)
return;
if (!event.getPlayer().hasPermission("dodgeball.arena.signs")) {
event.setCancelled(true);
event.getPlayer().sendMessage(OITG.prefix + ChatColor.RED + "You don't have permission to break arena signs!");
return;
}
arena.removeSignLocation(event.getBlock().getLocation());
event.getPlayer().sendMessage(OITG.prefix + "Removed a sign for arena: " + arena.toString());
} | 4 |
public void eliminarAntesDeX(T x){
Nodo<T> q = this.p;
Nodo<T> t = new Nodo<T>();
Nodo<T> r = new Nodo<T>();
boolean bandera = true;
if(this.p.getValor() == x){
System.out.println("No hay valor que proceda de que contenga X");
}else{
q = this.p;
t = this.p;
while(q.getValor() != x && bandera){
if(q.getLiga() != null){
r = t;
t = q;
q = q.getLiga();
}else{
bandera = false;
}
}
if(!bandera){
System.out.println("Elemento no se encuentra");
}else{
if(p.getLiga() == q){
p = q;
}else{
r.setLiga(q);
}
}
}
} | 6 |
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//Prints.msg("BeforeClass <--> Passei pelo setUpBeforeClass - Antes da classe.");
} | 0 |
public void backToMenu()
{
int reply = JOptionPane.showConfirmDialog(null, "Would you like to return to the Main Menu?");
if(reply == JOptionPane.YES_OPTION)
{
timer.stop();
reply = JOptionPane.showConfirmDialog(null, "Would you like to save your progress before quiting?");
if(reply == JOptionPane.YES_OPTION)
{
saveGame();
JOptionPane.showMessageDialog(null, "Puzzle Saved", "Success", JOptionPane.INFORMATION_MESSAGE);
MainMenu menu = new MainMenu(1000,800, user);
menu.setSize(1000,800);
menu.setVisible(true);
menu.setTitle("CSE360 Sudoku Main Menu");
dispose();
}
else
{
reply = JOptionPane.showConfirmDialog(null, "Would you like to see the solution?");
if(reply == JOptionPane.YES_OPTION)
{
MainMenu menu = new MainMenu(1000,800, user);
menu.setSize(1000,800);
menu.setVisible(true);
menu.setTitle("CSE360 Sudoku Main Menu");
ShowSolution solution;
switch(difficulty)
{
case "Easy":
solution = new ShowSolution("easy16x16Solution.txt", "16x16");
solution.setTitle("Easy 16x16 Solution");
break;
case "Medium":
solution = new ShowSolution("medium16x16Solution.txt", "16x16");
solution.setTitle("Medium 16x16 Solution");
break;
case "Hard":
solution = new ShowSolution("hard16x16Solution.txt", "16x16");
solution.setTitle("Hard 16x16 Solution");
break;
default:
solution = new ShowSolution("evil16x16Solution.txt", "16x16");
solution.setTitle("Evil 16x16 Solution");
break;
}
solution.setSize(700,700);
solution.setVisible(true);
solution.setResizable(false);
dispose();
}
else
{
MainMenu menu = new MainMenu(1000,800, user);
menu.setSize(1000,800);
menu.setVisible(true);
menu.setTitle("CSE360 Sudoku Main Menu");
dispose();
}
}
}
} | 6 |
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
} // end method startSetup | 0 |
public void write(String msg) {
if (!isPaused) {
try {
fileWriter.write(msg + LINE_END);
fileWriter.flush();
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
} | 2 |
public CacheEntry[] getCacheEntries() {
List<CacheEntry> result = new ArrayList<CacheEntry>(17);
for(final Class<?> cacheType: caches.keySet()) {
Cache cache = caches.get(cacheType);
for (final Object readerKey : cache.readerCache.keySet()) {
// we've now materialized a hard ref
// innerKeys was backed by WeakHashMap, sanity check
// that it wasn't GCed before we made hard ref
if (null != readerKey && cache.readerCache.containsKey(readerKey)) {
Map<Entry, Object> innerCache = cache.readerCache.get(readerKey);
for (final Map.Entry<Entry, Object> mapEntry : innerCache.entrySet()) {
Entry entry = mapEntry.getKey();
result.add(new CacheEntryImpl(readerKey, entry.field,
cacheType, entry.custom,
mapEntry.getValue()));
}
}
}
}
return result.toArray(new CacheEntry[result.size()]);
} | 6 |
@Override
public void validateCredentials(final String consumerKey, final String consumerSecret) throws IOException
{
if(twitterOAuthCredentials == null)
twitterOAuthCredentials = new TwitterOAuthCredentials();
twitterOAuthCredentials.setOAuthConsumerKey(consumerKey);
twitterOAuthCredentials.setOAuthConsumerSecret(consumerSecret);
//simulate long running operation
for(int i = 1; i<=3; i++)
{
appendStatus("Update from non event dispatch thread: " + i); //TODO: add to ResourceBundle
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
model.validateCredentials(twitterOAuthCredentials);
} | 3 |
private static void backward() {
destination.remove(MAN);
source.add(MAN);
if (!isSomethingWillBeEaten(destination)) {
return;
}
for (int i = 0; i < destination.size(); i++) {
if (destination.get(i).equals(lastTransfer)) {
continue;
}
ArrayList<String> sourceSimulator = new ArrayList<String>(source);
ArrayList<String> destinationSimulator = new ArrayList<String>(destination);
String toBeTransfer = destination.get(i);
destinationSimulator.remove(toBeTransfer);
sourceSimulator.add(toBeTransfer);
if (isSomethingWillBeEaten(sourceSimulator)
|| isSomethingWillBeEaten(destinationSimulator)) {
continue;
}
destination.remove(toBeTransfer);
source.add(toBeTransfer);
lastTransfer = toBeTransfer;
}
} | 5 |
public void fillWithNoise(CPRect r) {
CPRect rect = new CPRect(0, 0, width, height);
rect.clip(r);
int value;
Random rnd = new Random();
for (int j = rect.top; j < rect.bottom; j++) {
for (int i = rect.left; i < rect.right; i++) {
value = rnd.nextInt();
value &= 0xff;
value |= (value << 8) | (value << 16) | 0xff000000;
data[i + j * width] = value;
}
}
} | 2 |
public void visitInsn(final int opcode) {
minSize += 1;
maxSize += 1;
if (mv != null) {
mv.visitInsn(opcode);
}
} | 1 |
@Override
public void run() {
int sum = 0;
for(int i = 1; i <= 1000; i++) {
// System.out.println(" " + sum);
if(i == 100) {
sum += 10;
continue;
}
if(m_numberMap.containsKey(String.valueOf(i))) {
sum += m_numberMap.get(String.valueOf(i)).getLength();
// System.out.print(m_numberMap.get(String.valueOf(i)) + " ");
continue;
}
if(i < 100) {
String s = String.valueOf(i);
sum += m_numberMap.get(s.substring(0, 1) + "0").getLength();
// System.out.print(m_numberMap.get(s.substring(0, 1) + "0") + " ");
sum += m_numberMap.get(s.substring(1)).getLength();
// System.out.print(m_numberMap.get(s.substring(1)) + " ");
continue;
}
if(i < 1000) {
String s = String.valueOf(i);
sum += m_numberMap.get(s.substring(0, 1)).getLength();
// System.out.print(m_numberMap.get(s.substring(0, 1)) + " ");
sum += m_numberMap.get("100").getLength(); //HUNDRED
// System.out.print(m_numberMap.get("100") + " ");
if(i % 100 == 0) {
//We're done because this is a round hundred value
continue;
}
sum += 3; // AND as in TWO HUNDRED AND FIFTY ONE
// System.out.print("AND ");
if(m_numberMap.containsKey(s.substring(1, 3))) {
sum += m_numberMap.get(s.substring(1, 3)).getLength();
// System.out.print(m_numberMap.get(s.substring(1, 3)) + " ");
continue;
}
sum += m_numberMap.get(s.substring(1, 2) + "0").getLength();
// System.out.print(m_numberMap.get(s.substring(1, 2) + "0") + " ");
sum += m_numberMap.get(s.substring(2)).getLength();
// System.out.print(m_numberMap.get(s.substring(2)));
}
}
setAnswer(String.valueOf(sum));
} | 7 |
public void calcTargets(int location, int steps){
visited[location] = true;
if(steps == 0){
targets.add(location);
}
else{
try{
if(!getAdjList(location).isEmpty()){
for(int adj : getAdjList(location)){
if(!visited[adj]){
if(getCell(adj).isDoorway()){
if( checkDoorDirection(getCell(location), getCell(adj)) ){
targets.add(adj);
}
continue;
}
calcTargets(adj, steps-1);
}
}
}
} catch (NullPointerException e){
System.out.println(e.getMessage());
}
}
visited[location] = false;
} | 7 |
@Override
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < array.length; i++)
if (array[i] == null)
return i;
} else {
for (int i = 0; i < array.length; i++)
if (o.equals(array[i]))
return i;
}
return -1;
} | 5 |