text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main (String [] args){
int mark=50;
System.out.println("The mark is " + mark);
if (mark>=50){
System.out.println("PASS");
}else{
System.out.println("FAIL");
}
} | 1 |
private void jButtonSaveOrderActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonSaveOrderActionPerformed
{//GEN-HEADEREND:event_jButtonSaveOrderActionPerformed
if (jTextFieldCustomerNo.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "Der mangler et kunde nummer");
} else
{
int kundeNo = 0;
try
{
kundeNo = Integer.parseInt(jTextFieldCustomerNo.getText());
} catch (Exception e)
{
JOptionPane.showMessageDialog(null, "KundeNo skal vรฆre hel tal");
}
Calendar cal = Calendar.getInstance();
Date date = (Date) cal.getTime();
String dag = jComboBoxDag.getSelectedItem().toString();
String mรฅned = jComboBoxMaaned.getSelectedItem().toString();
String aar = jComboBoxAar.getSelectedItem().toString();
String dato = aar + mรฅned + dag;
DateFormat newDate = new SimpleDateFormat("yyyyMMdd");
try
{
date = newDate.parse(dato);
} catch (ParseException ex)
{
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Customer> customerlist = control.loadCustomerlist();
for (int i = 0; i < customerlist.size(); i++)
{
if (customerlist.get(i).getCustomerID() == kundeNo && kundeNo != 0)
{
control.createOrder(orderItemList, customerlist.get(i), date);
modelVareTilOrdre.clear();
jTextFieldCustomerNo.setText("");
}
}
try
{
String ordreNummer = control.saveOrder();
jLabelOrderSavedNotSaved.setText("Ordre nummer: " + ordreNummer);
int ordreNo = Integer.parseInt(ordreNummer);
for (int i = 0; i < orderItemList.size(); i++)
{
if (orderItemList.get(i).getItemName().equals("Telt"))
{
Employee employee1 = new Employee(emp.get(0).getEmployeeID(), date, ordreNo);
Employee employee2 = new Employee(emp.get(1).getEmployeeID(), date, ordreNo);
control.saveEmployeeWithDate(employee1);
control.saveEmployeeWithDate(employee2);
}
}
control.loadOrdersWithDate(date);
visVareliste();
} catch (SQLException ex)
{
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
orderItemList.clear();
}
}//GEN-LAST:event_jButtonSaveOrderActionPerformed | 9 |
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(timer)) {
if (ballMovement) {
updateStatus();
ai.moveAi(ball.x, ball.y, ball.width, ball.height);
moveBall();
repaint();
}
} else if (e.getSource().equals(_timer)) {
repaint();
ballMovement = true;
_timer.stop();
timer.start();
}
} | 3 |
public int clear() {
System.out.print("Distribution: ");
for (int i = 0; i < 4; ++i){
System.out.print(distribution[i] + ", ");
distribution[i] = 0;
}
System.out.println();
String response;
for (SocketClient sClient : sClients){
try{
response = sClient.sendRequest("clr");
} catch (IOException e){
return 2;
}
if (!response.equals("0")){
return Integer.parseInt(response);
}
}
return 0;
} | 4 |
private void editAmount() {
setVisible(false);
ArrayList<Booking> bookings = table.getSelectedObjects();
for (Booking booking : bookings) {
Transaction transaction = booking.getTransaction();
Account account = booking.getAccount();
//TODO: or JournalGUI.table should contain Movements iso Bookings
// booking must be removed and re-added to Transaction to re-calculate the totals
transaction.removeBusinessObject(booking);
BigDecimal amount = journalInputGUI.askAmount(account, booking.isDebit());
if (amount != null) {
booking.setAmount(amount);
}
transaction.addBusinessObject(booking);
journalInputGUI.fireTransactionDataChanged();
}
} | 2 |
public void recalc_matches() {
try {
int non_matches_map = 0;
int non_matches_file = 0;
int map_index = comboBoxMapLayer.getSelectedIndex();
int file_index = comboBoxFileLinkColumn.getSelectedIndex();
if( map_index < 0 || file_index < 0) {
System.out.println("recalc: bad index");
return;
}
HashMap<String,String> hmfile = new HashMap<String,String>();
for( int i = 0; i < data.length; i++) {
hmfile.put(data[i][file_index].trim().toLowerCase(), data[i][file_index]);
}
HashMap<String,String> hmmap = new HashMap<String,String>();
for( int i = 0; i < map_data.length; i++) {
hmmap.put(map_data[i][map_index].trim().toLowerCase(), map_data[i][map_index]);
}
for( int i = 0; i < map_data.length; i++) {
if( !hmfile.containsKey(map_data[i][map_index].trim().toLowerCase())) {
non_matches_map++;
}
}
for( int i = 0; i < data.length; i++) {
if( !hmmap.containsKey(data[i][file_index].trim().toLowerCase())) {
non_matches_file++;
}
}
lblNonmatchesMap.setText(""+non_matches_map+" non-matches");
lblNonmatchesFile.setText(""+non_matches_file+" non-matches");
System.out.println("recalc: done.");
comboBoxMapLayer.repaint();
comboBoxFileLinkColumn.repaint();
} catch (Exception ex) { ex.printStackTrace(); }
} | 9 |
@Override
public String getDesc() {
return "FrostDiver";
} | 0 |
public void resume() {isPaused = false;} | 0 |
@Override
public void update(GameContainer gc, StateBasedGame sb, int delta) {
float rotation = owner.getRotation();
float scale = owner.getScale();
Vector2f position = owner.getPosition();
Input input = gc.getInput();
if(input.isKeyDown(Input.KEY_A)) {
rotation -= 0.2f * delta;
}
if(input.isKeyDown(Input.KEY_D)) {
rotation += 0.2f * delta;
}
if(input.isKeyDown(Input.KEY_W)) {
float joint = 0.4f * delta;
position.x += joint * Math.sin(Math.toRadians(rotation));
position.y -= joint * Math.cos(Math.toRadians(rotation));
}
if(input.isKeyDown(Input.KEY_S)) {
float joint = -0.4f * delta;
position.x += joint * Math.sin(Math.toRadians(rotation));
position.y -= joint * Math.cos(Math.toRadians(rotation));
}
owner.setPosition(position);
owner.setRotation(rotation);
owner.setScale(scale);
} | 4 |
protected static Ptg calcErf( Ptg[] operands ) throws FunctionNotSupportedException
{
if( operands.length < 1 )
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
try
{
double lower_limit = operands[0].getDoubleVal();
double upper_limit = Double.NaN; //lower_limit;
if( operands.length == 2 )
{
upper_limit = operands[1].getDoubleVal();
}
// If lower_limit is negative, ERF returns the #NUM! error value.
// If upper_limit is negative, ERF returns the #NUM! error value.
// if (lower_limit < 0 /*|| upper_limitupper_limit < 0*/) return new PtgErr(PtgErr.ERROR_NUM);
boolean neg = (lower_limit < 0);
lower_limit = Math.abs( lower_limit );
double result;
double limit = lower_limit;
/*
// try this: from "Computation of the error function erf in arbitrary precision with correct rounding"
double r= 0;
double r1= 0;
double estimate= (2/Math.sqrt(Math.PI))*(limit - Math.pow(limit, 3)/3.0);
double convergence= Math.pow(2, estimate-15);
for (int i= 0, n= 0; n < 100; i++, n++) {
double factor= 2.0*n + 1.0;
double z= Math.pow(limit, factor);
double zz= (MathFunctionCalculator.factorial(n)*factor);
double zzz= z/zz;
if ((i % 2)!=0)
r= r-zzz;
else
r= r+zzz;
if (Math.abs(r)-r1) <
r1= Math.abs(r1);
}
result= r*(2.0/Math.sqrt(Math.PI));*/
if( limit < 0.005 )
{
/* A&S 7.1.1 - good to at least 6 digts ... but not for larger values ... sigh ...*/
double r = 0;
for( int i = 0, n = 0; n < 12; i++, n++ )
{
double factor = (2.0 * n) + 1.0;
double z = Math.pow( limit, factor );
double zz = (MathFunctionCalculator.factorial( n ) * factor);
double zzz = z / zz;
if( (i % 2) != 0 )
{
r = r - zzz;
}
else
{
r = r + zzz;
}
}
result = r * (2.0 / Math.sqrt( Math.PI ));
}
else
{
result = erf_try1( limit );
}
if( neg )
{
result *= -1;
}
if( !Double.isNaN( upper_limit ) )
{ // Erf(upper)-Erf(lower)
Ptg result2 = calcErf( new Ptg[]{ operands[1] } );
if( result2 instanceof PtgNumber )
{
result = result2.getDoubleVal() - result;
}
else
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
}
return new PtgNumber( result );
}
catch( Exception e )
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
} | 9 |
public JPanel getSecOptMenu() {
if (!isInitialized()) {
IllegalStateException e = new IllegalStateException("Call init first!");
throw e;
}
return this.secOptMenu;
} | 1 |
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(this.imageMenuItem)){
this.onInsertImageMenuItemClick(e);
}
else if (e.getSource().equals(this.scrollMenuItem)){
this.handleScrolling();
}
else if (e.getSource().equals(this.spellCheckMenuItem)){
this.handleSpellChecking();
}
else if (e.getSource().equals(this.aboutMenuItem)){
JOptionPane.showMessageDialog(this, "Lext editor implementation\nDeveloper: Amit Dutta" +
"\nEmail: adutta@cis.uab.edu\nWeb: http://www.amitdutta.net", "Lexi", JOptionPane.INFORMATION_MESSAGE);
}
else if (e.getSource().equals(this.exitMenuItem)){
this.document.removeObserver(this);
this.dispose();
}
else if (e.getSource().equals(this.saveMenuItem)) {
this.handleSaveMenuItemClick();
}
else if (e.getSource().equals(this.openMenuItem)) {
this.handleOpenMenuItemClick();
}
} | 7 |
void drawLoadingText(int percentage, String s) {
while (gameGraphics == null) {
gameGraphics = getGameComponent().getGraphics();
try {
getGameComponent().repaint();
} catch (Exception _ex) {
}
try {
Thread.sleep(1000L);
} catch (Exception _ex) {
}
}
Font helveticaBold = new Font("Helvetica", 1, 13);
FontMetrics fontmetrics = getGameComponent().getFontMetrics(
helveticaBold);
Font helvetica = new Font("Helvetica", 0, 13);
getGameComponent().getFontMetrics(helvetica);
if (clearScreen) {
gameGraphics.setColor(Color.black);
gameGraphics.fillRect(0, 0, width, height);
clearScreen = false;
}
Color color = new Color(140, 17, 17);
int centerHeight = height / 2 - 18;
gameGraphics.setColor(color);
gameGraphics.drawRect(width / 2 - 152, centerHeight, 304, 34);
gameGraphics.fillRect(width / 2 - 150, centerHeight + 2,
percentage * 3, 30);
gameGraphics.setColor(Color.black);
gameGraphics.fillRect((width / 2 - 150) + percentage * 3,
centerHeight + 2, 300 - percentage * 3, 30);
gameGraphics.setFont(helveticaBold);
gameGraphics.setColor(Color.white);
gameGraphics.drawString(s, (width - fontmetrics.stringWidth(s)) / 2,
centerHeight + 22);
} | 4 |
public void loadTag() throws Exception{
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(decompressedData));
byte tagType = stream.readByte();
if (tagType != NbtTag.TAG_COMPOUND) {
throw new Exception("Top tag wasn't a compound!");
}
tag = new NbtTagCompound();
tag.readName(stream);
tag.readTag(stream);
//System.out.println(tag.toString());
//PrintWriter pw = new PrintWriter("chunk.txt");
//pw.print(tag.toString());
//pw.close();
NbtTagCompound levelTag = (NbtTagCompound) tag.tags.get("Level");
NbtTagList sections = (NbtTagList) levelTag.tags.get("Sections");
for (int i = 0; i < sections.tags.size(); i++) {
NbtTagCompound item = (NbtTagCompound)sections.tags.get(i);
byte sectionNum = ((NbtTagByte)item.tags.get("Y")).value;
byte[] list = ((NbtTagByteArray)item.tags.get("Blocks")).value;
int l = 0; //sectionNum * 16 * 16;
for (int y = sectionNum * 16; y < sectionNum * 16 + 16; y++){
for (int z = 0; z < 16; z++){
for (int x = 0; x < 16; x++){
blockType[x][y][z] = BlockType.fromInt(list[l]);
l++;
}
}
}
}
} | 5 |
public void remove(int key) {
HashPrinter.tryRemove(key);
/** Run along the array */
int runner = 0;
int hash = (key % TABLE_INITIAL_SIZE);
while (table[hash] != null && runner < TABLE_INITIAL_SIZE) {
if (table[hash].getKey() == key) {
break;
}
runner++;
hash = ((key + runner) % TABLE_INITIAL_SIZE);
}
if (runner >= TABLE_INITIAL_SIZE) {
HashPrinter.notFound(key);
} else {
table[hash] = DeletedNode.getUniqueDeletedNode();
HashPrinter.remotionSuccessful(key, hash);
}
} | 4 |
public void setNumeroReal(TNumeroReal node)
{
if(this._numeroReal_ != null)
{
this._numeroReal_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._numeroReal_ = node;
} | 3 |
public MageView()
{
for (int j = 0; j < 4; j++)
{
String direction = "";
if (j == 0)
{
direction = "left";
}
if (j == 1)
{
direction = "right";
}
if (j == 2)
{
direction = "down";
}
if (j == 3)
{
direction = "up";
}
String frameName = "";
String key = "";
// Walking 1
frameName = "images/characters/fire_mage/fire_mage_" + direction + "_walking.png";
key = direction + "1";
m_images.put(key, new ImageIcon(frameName).getImage());
// Walking 2
frameName = "images/characters/fire_mage/fire_mage_" + direction + "_walking2.png";
key = direction + "2";
m_images.put(key, new ImageIcon(frameName).getImage());
// Standing
frameName = "images/characters/fire_mage/fire_mage_" + direction + "_face.png";
key = direction + "S";
m_images.put(key, new ImageIcon(frameName).getImage());
// Attacking
frameName = "images/characters/fire_mage/fire_mage_" + direction + "_attack.png";
key = direction + "A";
m_images.put(key, new ImageIcon(frameName).getImage());
// Defending
frameName = "images/characters/fire_mage/fire_mage_" + direction + "_defend.png";
key = direction + "D";
m_images.put(key, new ImageIcon(frameName).getImage());
}
m_images.put("dead", new ImageIcon("images/characters/knight/knight_dead.png").getImage());
} | 5 |
private void setRect(double minLat, double minLng, double maxLat, double maxLng)
{
if (!(minLat < maxLat))
{
throw new IllegalArgumentException("GeoBounds is not valid - minLat must be less that maxLat.");
}
if (!(minLng < maxLng))
{
if (minLng > 0 && minLng < 180 && maxLng < 0)
{
rects = new Rectangle2D[] {
// split into two rects e.g. 176.8793 to 180 and -180 to
// -175.0104
new Rectangle2D.Double(minLng, minLat, 180 - minLng, maxLat - minLat),
new Rectangle2D.Double(-180, minLat, maxLng + 180, maxLat - minLat) };
}
else
{
rects = new Rectangle2D[] { new Rectangle2D.Double(minLng, minLat, maxLng - minLng, maxLat - minLat) };
throw new IllegalArgumentException("GeoBounds is not valid - minLng must be less that maxLng or "
+ "minLng must be greater than 0 and maxLng must be less than 0.");
}
}
else
{
rects = new Rectangle2D[] { new Rectangle2D.Double(minLng, minLat, maxLng - minLng, maxLat - minLat) };
}
} | 5 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CategoriaChamado)) {
return false;
}
CategoriaChamado other = (CategoriaChamado) object;
if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
void prepare() {
System.out.println("Preparing " + name);
System.out.println("Tossing dough...");
System.out.println("Adding sauce...");
System.out.println("Adding toppings: ");
for (int i = 0; i < toppings.size(); i++) {
System.out.println(" " + toppings.get(i));
}
} | 1 |
private String getType(String extension)
{
switch(extension)
{
case "gif":
return "image/gif";
case "html":
return "text/html";
case "jpeg":
return "image/jpeg";
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "txt":
return "text/plain";
default:
return "";
}
} | 6 |
protected static String getCheckSum(File file) {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new InternalError("MD5 not supported!");
}
FileInputStream fis;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
return null;
}
byte[] buffer = new byte[65535];
try {
int i;
while ((i = fis.read(buffer)) > 0)
messageDigest.update(buffer, 0, i);
} catch (Exception e) {
return null;
} finally {
try {
fis.close();
} catch (IOException ignored) {
}
}
return String.format("%1$032x", new BigInteger(1, messageDigest.digest()));
} | 5 |
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.setStroke(new BasicStroke(2));
for (int i = 0; i < next; i++)
{
if (RightObjects.get(i).getClass().equals(TickerPanel.class))
g2.setColor((((TickerPanel)RightObjects.get(i)).getColor()));
if (LeftObjects.get(i).getClass().equals(TickerPanel.class))
g2.setColor((((TickerPanel)LeftObjects.get(i)).getColor()));
int finalLX = leftGenerateX(LeftObjects.get(i));
int finalLY = GenerateY(LeftObjects.get(i));
int finalRX = rightGenerateX(RightObjects.get(i));
int finalRY = GenerateY(RightObjects.get(i));
if (RightObjects.get(i).getClass().equals(TickerPanel.class))
finalRX -= 5;
if (LeftObjects.get(i).getClass().equals(DynamicImagePanel.class))
finalLX -= 5;
if (RightObjects.get(i).getClass().equals(ImageButton.class))
finalRX -= 5;
g2.drawLine(finalLX, finalLY, finalRX, finalRY);
if (Target.get(i) == true)
{
double length = 12;
int A = finalRX - finalLX;
int B = finalRY - finalLY;
double C = Math.sqrt(A*A + B*B);
int E = 25;
double con = 57.2957795;
double D = Math.asin(B/C) * con;
//if (D < 0) D += 360;
double Y = Math.sin((D-E+180)/con);
double X = Math.cos((D-E+180)/con);
int iX = (int) (X*length);
int iY = (int) (Y*length);
g2.drawLine(finalRX, finalRY, finalRX+iX, finalRY+iY);
Y = Math.sin((D+E+180)/con);
X = Math.cos((D+E+180)/con);
iX = (int) (X*length);
iY = (int) (Y*length);
g2.drawLine(finalRX, finalRY, finalRX+iX, finalRY+iY);
}
}
} | 7 |
public void loadImage(File file, int place) {
System.out.println("loading image into [" + place + "]");
try {
imageView[place] = ImageIO.read(file);
imageArrays[place] = convertTo2D(imageView[place]);
filterBody(imageArrays[place], place); // 1, 2, 3
imagePaths[place] = file.getPath();
System.out.println("view [" + place + "]: " + topViewCoordinates.size());
} catch(IOException i) {
System.out.println("error loading image");
System.out.println(i);
}
} | 1 |
public String getFrameScore(){
String score="";
String thirdPoint;
checkS();
// ์ธ๋ฒ์งธ ๊ณต์ ๋์ง์ง ์์์ ๋, ๋ถ๋ชจ ํด๋์ค์ ์ ์ํ ๋ฐํ์ ์ฌ์ฉํ๋ค.
if(pins.size()!=3)
return super.getFrameScore();
// ์ธ๋ฒ์งธ ๊ณต์ ๋์ก์ ๋, ์คํธ๋ผ์ดํฌ ํน์ ๊ฑฐํฐ ์ฌ๋ถ๋ฅผ ํ์ธํ๋ค.
if(pins.get(2)==10)
thirdPoint="X";
else if(pins.get(2)==0)
thirdPoint="-";
else
thirdPoint=pins.get(2)+"";
if (isStrike)
return (super.getFrameScore() + thirdPoint + " |");
if (isSpare)
return (super.getFrameScore() + thirdPoint + " |");
for(int i=0; i<pins.size()-1; i++){
if(pins.get(i)==0)
score += "- ";
else{
score += pins.get(i);
score += " ";
}
}
return score+" |";
} | 7 |
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
ResultStatus status = new ResultStatus();
Gson gson = new Gson();
String command = req.getParameter("command");
String jsonedPuzzle = req.getParameter("puzzle");
//if input contains something that is not int[][], we will get exception. so if user enters
//things like letters, i want the server side to protect itself (doing it in the UI is nice
//but if i have several UIs like several HTMLs, i dont want wach one of them to contains protection...
try
{
String errMsg = "";
int[][] inputPuzzle = gson.fromJson(jsonedPuzzle, int[][].class);
SudukuPuzzle input = new SudukuPuzzle(inputPuzzle);
SudukuSolver solver = new SudukuSolver();
//we need to put TABLE_SIZE numbers, each one TABLE_SIZE times:
SolutionItem puzzleToSolve = new SolutionItem(input, 0, -1);
SolutionItem solved = null;
if( command.equals( "solve" ))
{
solved = solver.solve(puzzleToSolve);
}
else if( command.equals( "gethint" ))
{
solved = solver.getHint(puzzleToSolve);
}
else
{
errMsg = "illegal command from the javascript";
}
//Gson gson = new GsonBuilder().serializeNulls().create();
gson = new Gson();
if(solved == null) //could not solve or illegal command
{
errMsg = (errMsg == "") ? "ERROR: could not solve this fucking puzzle; took me " + solver.getNumSteps() + " steps" : errMsg;
status.setSuccess(false);
status.setMessage( errMsg );
}
else
{
status.setSuccess(true);
status.setMessage("solved puzzle in " + solver.getNumSteps() + " steps");
//since i work with Json i get the table and transfer it as is:
status.setPuzzle(solved.puzzle.getTable());
}
}
catch(JsonParseException jpe)
{
status.setSuccess(false);
status.setMessage("ERROR: The input must contains ONLY numbers");
}
String json = gson.toJson( status );
System.out.println( json );
writer.println( json );
} | 5 |
public void printRAM() throws Exception
{
for(int i = 0; i < jList.size(); ++i)
{
Job tempJob = jList.get(i);
System.out.println("ID: " + tempJob.getID());
System.out.println("Priority: " + tempJob.getPri());
System.out.println("Number of Instructions: " + tempJob.getJobs());
for(int j = 0; j < tempJob.getJobs(); ++j)
{
System.out.println(tempJob.iList.get(j));
}
}
} | 2 |
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int msj_p, msj_c, num, num2, tmp1, tmp2, tmp3, tmp4, aux;
boolean continua;
do{
continua = false;
System.out.println("Ingrese un numero entero de 4 digitos: ");
msj_p = entrada.nextInt();
if(msj_p < 1000 || msj_p > 9999)
continua = true;
}while(continua);
num = msj_p;
num2 = 0;
aux=0;
tmp1 = 0; tmp2 = 0; tmp3 = 0; tmp4 = 0;
do{
num2 = (num2*10) + (num % 10);
num2 += 7;
num2 %= 10;
num = (int)(num/10);
if(aux==0){
tmp1 = num2;
System.out.printf("\n%d", num2);
}
else if(aux==1){
tmp2 = num2;
System.out.printf("\n%d", num2);
}
else if(aux==2){
tmp3 = num2;
System.out.printf("\n%d", num2);
}
else if(aux==3){
tmp4 = num2;
System.out.printf("\n%d", num2);
}
aux++;
}while(num != 0);
aux = tmp1;
tmp1 = tmp3;
tmp3 = aux;
aux = tmp2;
tmp2 = tmp4;
tmp4 = aux;
msj_c = tmp1 + tmp2*10 + tmp3*100 + tmp4*1000;
System.out.printf("\nMensaje cifrado: %d\n", msj_c);
} | 8 |
private void showTeachingPlan() {
content = null;
head = null;
Object fb = logic.showTPHead();
if (fb instanceof Feedback) {
JOptionPane.showMessageDialog(null, ((Feedback) fb).getContent());
} else if (fb instanceof String[]) {
head = (String[]) fb;
fb = logic.showTPContent();
if ((fb instanceof Feedback) && fb != Feedback.LIST_EMPTY) {
JOptionPane.showMessageDialog(null,
((Feedback) fb).getContent());
} else if (fb instanceof String[][]) {
content = (String[][]) fb;
}
}
if (content != null) {
fBtn[0].setEnabled(false);
fBtn[1].setEnabled(true);
map = new TeachingPlanMap(content);
dtm = new DefaultTableModel(content.length, head.length);
table2 = new CTable(map, dtm);
dtm.setColumnIdentifiers(head);
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
if (content[i][j].contains("null-null")) {
content[i][j] = content[i][j].replaceAll("null-null",
"");
}
dtm.setValueAt(content[i][j], i, j);
}
}
table2.setEnabled(false);
js2.setViewportView(table2);
cl.show(cardp, "2");
}
this.repaint();
this.validate();
} | 9 |
public Player winner() {
Player p = null;
Player owner = null;
Player owner1 = null;
for(CityImpl c : this.game.getAllCities()) {
if(Player.RED == c.getOwner()) {
owner = c.getOwner();
}
if(Player.BLUE == c.getOwner()) {
owner1 = c.getOwner();
}
}
if(owner == null) {
p = Player.BLUE;
}
if(owner1 == null) {
p = Player.RED;
}
return p;
} | 5 |
private List<DbTableRecord> getRecords(String sourceDB,
DbDefinition dbDefinition, DbTableDefinition tableDefinition) {
List<DbTableRecord> allRecords = new ArrayList<DbTableRecord>();
if (sourceDB.equals(AppConstants.CONN_STRING_BASELINE_DB)) {
try {
if (null == dbConnectionBaseline
|| dbConnectionBaseline.isClosed()) {
dbConnectionBaseline = getDbConnection(dbDefinition,
AppConstants.CONN_STRING_BASELINE_DB);
}
allRecords = getRecordsFromDb(dbConnectionBaseline,
tableDefinition);
} catch (Exception ex) {
ex.printStackTrace();
logger.fatal(Utils.buildExceptionMessage(ex));
logger.info("The application has exited...");
System.exit(0);
}
} else {
try {
if (null == dbConnectionTarget || dbConnectionTarget.isClosed()) {
dbConnectionTarget = getDbConnection(dbDefinition,
AppConstants.CONN_STRING_TARGET_DB);
}
allRecords = getRecordsFromDb(dbConnectionTarget,
tableDefinition);
} catch (Exception ex) {
ex.printStackTrace();
logger.fatal(Utils.buildExceptionMessage(ex));
logger.info("The application has exited...");
System.exit(0);
}
}
return allRecords;
} | 7 |
protected void readImage() {
ix = readShort(); // (sub)image position & size
iy = readShort();
iw = readShort();
ih = readShort();
int packed = read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
if (lctFlag) {
lct = readColorTable(lctSize); // read table
act = lct; // make local table active
} else {
act = gct; // make global table active
if (bgIndex == transIndex)
bgColor = 0;
}
int save = 0;
if (transparency) {
save = act[transIndex];
act[transIndex] = 0; // set transparent color if specified
}
if (act == null) {
status = STATUS_FORMAT_ERROR; // no color table defined
}
if (err())
return;
decodeImageData(); // decode pixel data
skip();
if (err())
return;
frameCount++;
// create new image to receive frame data
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
setPixels(); // transfer pixel data to image
frames.add(new GifFrame(image, delay)); // add image to frame list
if (transparency) {
act[transIndex] = save;
}
resetFrame();
} | 7 |
public void selectAttributesCVSplit(Instances split) throws Exception {
double[][] attributeRanking = null;
// if the train instances are null then set equal to this split.
// If this is the case then this function is more than likely being
// called from outside this class in order to obtain CV statistics
// and all we need m_trainIstances for is to get at attribute names
// and types etc.
if (m_trainInstances == null) {
m_trainInstances = split;
}
// create space to hold statistics
if (m_rankResults == null && m_subsetResults == null) {
m_subsetResults = new double[split.numAttributes()];
m_rankResults = new double[4][split.numAttributes()];
}
m_ASEvaluator.buildEvaluator(split);
// Do the search
int[] attributeSet = m_searchMethod.search(m_ASEvaluator,
split);
// Do any postprocessing that a attribute selection method might
// require
attributeSet = m_ASEvaluator.postProcess(attributeSet);
if ((m_searchMethod instanceof RankedOutputSearch) &&
(m_doRank == true)) {
attributeRanking = ((RankedOutputSearch)m_searchMethod).
rankedAttributes();
// System.out.println(attributeRanking[0][1]);
for (int j = 0; j < attributeRanking.length; j++) {
// merit
m_rankResults[0][(int)attributeRanking[j][0]] +=
attributeRanking[j][1];
// squared merit
m_rankResults[2][(int)attributeRanking[j][0]] +=
(attributeRanking[j][1]*attributeRanking[j][1]);
// rank
m_rankResults[1][(int)attributeRanking[j][0]] += (j + 1);
// squared rank
m_rankResults[3][(int)attributeRanking[j][0]] += (j + 1)*(j + 1);
// += (attributeRanking[j][0] * attributeRanking[j][0]);
}
} else {
for (int j = 0; j < attributeSet.length; j++) {
m_subsetResults[attributeSet[j]]++;
}
}
m_trials++;
} | 7 |
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof KeyedValues)) {
return false;
}
KeyedValues that = (KeyedValues) obj;
int count = getItemCount();
if (count != that.getItemCount()) {
return false;
}
for (int i = 0; i < count; i++) {
Comparable k1 = getKey(i);
Comparable k2 = that.getKey(i);
if (!k1.equals(k2)) {
return false;
}
Number v1 = getValue(i);
Number v2 = that.getValue(i);
if (v1 == null) {
if (v2 != null) {
return false;
}
}
else {
if (!v1.equals(v2)) {
return false;
}
}
}
return true;
} | 8 |
private String toRules(){
if (numInstances() == 0)
return "No Rules (Empty Exemplar)";
String s = "", sep = "";
for(int i = 0; i < numAttributes(); i++){
if(i == classIndex())
continue;
if(attribute(i).isNumeric()){
if(m_MaxBorder[i] != m_MinBorder[i]){
s += sep + m_MinBorder[i] + "<=" + attribute(i).name() + "<=" + m_MaxBorder[i];
} else {
s += sep + attribute(i).name() + "=" + m_MaxBorder[i];
}
sep = " ^ ";
} else {
s += sep + attribute(i).name() + " in {";
String virg = "";
for(int j = 0; j < attribute(i).numValues() + 1; j++){
if(m_Range[i][j]){
s+= virg;
if(j == attribute(i).numValues())
s += "?";
else
s += attribute(i).value(j);
virg = ",";
}
}
s+="}";
sep = " ^ ";
}
}
s += " ("+numInstances() +")";
return s;
} | 8 |
private static int check(int value, int maxBits) throws NumberFormatException {
if (value > (1 << maxBits) - 1) {
throw new NumberFormatException(INVALID_VERSION_FORMAT);
}
return value;
} | 1 |
* @Description: TODO
* @param: @param data_set
* @param: @return
* @return: SplitPair
* @throws
* @author UncleLee
*/
private SplitPair chooseBestFeature(List<DataEntry<double[], Double>> data_set, double error_sum){
int m = data_set.size();
if(m <= DEFAULT_MIN_NUMS)
return null;
int n = data_set.get(0).data_vec.length;
SplitPair best_sp = null;
SplitPair sp = new SplitPair(-1, -1);
double min_error = Double.MAX_VALUE;
for(int i=0;i<n;i++){
sp.idx = i;
Set<Double> val_set = new HashSet<Double>();
for(int j=0;j<m;j++)
val_set.add(data_set.get(j).data_vec[i]);
for(double val:val_set){
sp.val = val;
double error = 0.0;
List<DataEntry<double[], Double>>[] temp_data = binSplitData(data_set, sp);
if(temp_data[0].size()>0){
LinearRegressionModel<Double> left = new LinearRegression(temp_data[0], false);
error += left.error_sum;
}
if(temp_data[1].size()>0){
LinearRegressionModel<Double> right = new LinearRegression(temp_data[1], false);
error += right.error_sum;
}
if(error<min_error){
best_sp = sp;
min_error = error;
}
}
}
if(min_error/error_sum>MIN_INCREMENT_RATE)
return null;
return best_sp;
} | 8 |
public void setSourceText(String sourceText) {
if( !sourceText.equals(AlchemyAPI_NamedEntityParams.CLEANED) && !sourceText.equals(AlchemyAPI_NamedEntityParams.CLEANED_OR_RAW)
&& !sourceText.equals(AlchemyAPI_NamedEntityParams.RAW) && !sourceText.equals(AlchemyAPI_NamedEntityParams.CQUERY)
&& !sourceText.equals(AlchemyAPI_NamedEntityParams.XPATH))
{
throw new RuntimeException("Invalid setting " + sourceText + " for parameter sourceText");
}
this.sourceText = sourceText;
} | 5 |
public void togglePalettes() {
if (hiddenFrames.isEmpty()) {
for (CPPaletteFrame frame : paletteFrames) {
if (frame.isVisible()) {
for (CPPalette pal : frame.getPalettesList()) {
showPalette(pal, false);
}
hiddenFrames.add(frame);
}
}
} else {
for (CPPaletteFrame frame : hiddenFrames) {
if (!frame.isVisible()) {
for (CPPalette pal : frame.getPalettesList()) {
showPalette(pal, true);
}
}
}
hiddenFrames.clear();
}
} | 7 |
private Dimension getHeadingSize() {
Dimension s = new Dimension();
int c = getComponentCount();
for (int i = 0; i < c; i++) {
Component comp = getComponent(i);
TabWrapper tab = (TabWrapper) tabs.get(comp);
if (tab != null) {
int thw =
(HORIZONTAL_GAP * 2)
+
(metrics != null ?
metrics.stringWidth(tab.text == null ? "" : tab.text) : 0) //$NON-NLS-1$
+ (tab.image == null ? 0 : (IMAGE_TEXT_GAP + tab.image.getWidth(this)));
int thh = (VERTICAL_GAP * 2) +
Math.max(metrics != null ? metrics.getHeight() : 0,
tab.image == null ? 0 : tab.image.getHeight(this));
if (position == TOP || position == BOTTOM) {
s.width += thw;
s.height = Math.max(s.height, thh);
}
else {
s.height += thh;
s.width = Math.max(s.width, thw);
}
}
else {
/*DEBUG*/System.err.println(Messages.getString("TabbedPanel.tabWrapperCouldNotBeFound") + i + " [" + comp + //$NON-NLS-1$ //$NON-NLS-2$
" could not be found"); //$NON-NLS-1$
}
}
return s;
} | 9 |
@SuppressWarnings ("unchecked" )
@Override
public Collection<?> get( ByteBuffer in )
{
Integer size = Compress.getIntUnsignedNullable( in );
if (size == null)
{
return null;
}
Integer flag = Integer.valueOf( in.get() & 0xFF );
Constructor<?> constructor = constructorMap.get( flag );
try
{
Collection<Object> collection = (Collection<Object>)constructor.newInstance();
Reflect<Class<?>> componentClassReflect = ReflectRegistry.get( Class.class );
Class<?> componentType = componentClassReflect.get( in );
Reflect<Object> componentReflect = ReflectFactory.create( componentType );
for (int i = 0; i < size; i++)
{
collection.add( componentReflect.get( in ) );
}
return collection;
}
catch (Exception e)
{
throw new RuntimeException( e );
}
} | 7 |
private void makeSymbolTable( )
{
for( SemanticAction def: startNode.getBranches() )
{
String defName = def.getName();
if( defName.equals("print") ){
System.out.println( "User-defined print function not allowed." );
} else if( defName.equals("main") ){
mainCounter++;
}
for( SemanticAction defNode: def.getBranches() )
{
if( defNode.type == SemanticAction.TYPE.TYPE ||
defNode.type == SemanticAction.TYPE.FORMAL )
symbolTable.put( defName, defNode );
}
}
if( mainCounter < 1 )
System.out.println( "No main function defined." );
else if( mainCounter > 1 )
System.out.println( "Too many main functions defined." );
} | 8 |
public static String getCPI(String date, String state)
{
DB db = _mongo.getDB(DATABASE_NAME);
DBCollection coll = db.getCollection(COLLECTION_CPI);
BasicDBObject query = new BasicDBObject();
query.put("year", "" + getYear(date));
query.put("quarter", "" + ((getMonth(date) % 4) + 1));
DBCursor cur = coll.find(query);
DBObject doc = null;
if (cur.hasNext()) {
doc = cur.next();
return getValue(doc, state);
}
return "";
} | 1 |
void invoke(Page page) {
pageTextBox.setPage(page);
page.deselect();
createContentPane();
if (needNewDialog(dialog, page)) {
dialog = ModelerUtilities.getChildDialog(page, true);
String s = Modeler.getInternationalText("CustomizeTextBoxDialogTitle");
dialog.setTitle(s != null ? s : "Customize text box");
dialog.setContentPane(contentPane);
dialog.pack();
dialog.setLocationRelativeTo(dialog.getOwner());
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
cancel = true;
dialog.dispose();
}
public void windowActivated(WindowEvent e) {
textArea.requestFocusInWindow();
}
});
}
uidField.setText(pageTextBox.getUid());
indexLabel.setText(pageTextBox.index == -1 ? "to be decided" : "#" + (pageTextBox.index + 1));
if (pageTextBox.widthIsRelative) {
widthField.setValue(pageTextBox.widthRatio);
}
else {
widthField.setValue(pageTextBox.getPreferredSize().width);
}
if (pageTextBox.heightIsRelative) {
heightField.setValue(pageTextBox.heightRatio);
}
else {
heightField.setValue(pageTextBox.getPreferredSize().height);
}
String text = pageTextBox.getText();
textArea.setText(ModelerUtilities.deUnicode(text)); // Victor Vicovlov
if (text != null && text.trim().length() >= 6) {
pageTextBox.setContentType(text.trim().substring(0, 6).toLowerCase().equals("<html>") ? "text/html"
: "text/plain");
}
else {
pageTextBox.setContentType("text/plain");
}
textArea.setCaretPosition(0);
borderComboBox.setSelectedItem(pageTextBox.getBorderType());
transparentCheckBox.setSelected(pageTextBox.isTransparent());
bgComboBox.setColor(pageTextBox.getTextComponent().getBackground());
dialog.setVisible(true);
} | 8 |
private AbstractNode createHigherLevels(List boundablesOfALevel, int level) {
Assert.isTrue(!boundablesOfALevel.isEmpty());
List parentBoundables = createParentBoundables(boundablesOfALevel, level + 1);
if (parentBoundables.size() == 1) {
return (AbstractNode) parentBoundables.get(0);
}
return createHigherLevels(parentBoundables, level + 1);
} | 1 |
public ByteBuffer getData() {
int size = getLength();
ByteBuffer buf = ByteBuffer.allocate(size);
// write the offsets
for (int i = 0; i < glyphs.length; i++) {
Object o = glyphs[i];
if (o == null) {
continue;
}
ByteBuffer glyfData = null;
if (o instanceof ByteBuffer) {
glyfData = (ByteBuffer) o;
} else {
glyfData = ((Glyf) o).getData();
}
glyfData.rewind();
buf.put(glyfData);
glyfData.flip();
}
// reset the start pointer
buf.flip();
return buf;
} | 3 |
@Override
public void putAll(Map<? extends String, ? extends Competicao> m) {
throw new UnsupportedOperationException("Not supported yet.");
} | 2 |
public void escribirFichero(ArrayList<clsPersona> personas){
try{
FileWriter fichero = new FileWriter(rutaPrincipal);
PrintWriter pw = new PrintWriter(fichero);
for(clsPersona p : personas){
pw.println(p.getCodigo()+","+p.getNombre()+","+p.getTelefonoFijo()+","+p.getCelular()+","+p.getEmail()+","+p.getSexo()+","+p.getTipoPersona()+","+p.getEstado()+","+p.getDia()+","+p.getMes()+","+p.getAnio());
}
fichero.close();
}catch(Exception e){
e.printStackTrace();
}
} | 2 |
public Iterator getAttributes() {
if (unknownAttributes != null)
return unknownAttributes.values().iterator();
return Collections.EMPTY_SET.iterator();
} | 1 |
public static Class infoClass(Class cmp) {
Class info = null;
try {
info = Class.forName(cmp.getName() + "CompInfo");
} catch (ClassNotFoundException E) { // there is no info class,
info = cmp;
}
return info;
} | 1 |
public void broadcastEvent(String eventName) {
HashMap<Object, String> eventCallbacks = this.eventMap.get(eventName);
try {
if(eventCallbacks != null) {
Set<Object> keys = eventCallbacks.keySet();
Iterator<Object> it = keys.iterator();
while (it.hasNext()){
Object objReference = it.next();
String callback = eventCallbacks.get(objReference);
Class<?> c = Class.forName(objReference.getClass().getName());
Method method = c.getDeclaredMethod (callback);
method.invoke (objReference);
}
}
} catch (Exception e) {
// log some error here
}
} | 4 |
private Object readArgument(char type) {
switch (type) {
case 'i' :
return readInteger();
case 'h' :
return readBigInteger();
case 'f' :
return readFloat();
case 'd' :
return readDouble();
case 's' :
return readString();
case 'c' :
return readChar();
case 'T' :
return Boolean.TRUE;
case 'F' :
return Boolean.FALSE;
case 't' :
return readTimeTag();
default:
return null;
}
} | 9 |
protected JComponent initTreePanel() {
treePanel=new SelectableUnrestrictedTreePanel(this);
return treePanel;
} | 0 |
public void computeBoundingBox() {
// TODO: Compute the bounding box and store the result in
// averagePosition, minBound, and maxBound.
// Hint: The bounding box is not the same as just minPt and maxPt, because
// this object can be transformed by a transformation matrix.
Point3 p1,p2,p3,p4,p5,p6,p7,p8;
p1 = new Point3(minPt.x,minPt.y,minPt.z);
p2 = new Point3(minPt.x,minPt.y,maxPt.z);
p3 = new Point3(minPt.x,maxPt.y,minPt.z);
p4 = new Point3(maxPt.x,minPt.y,minPt.z);
p5 = new Point3(minPt.x,maxPt.y,maxPt.z);
p6 = new Point3(maxPt.x,minPt.y,maxPt.z);
p7 = new Point3(maxPt.x,maxPt.y,minPt.z);
p8 = new Point3(maxPt.x,maxPt.y,maxPt.z);
tMat.rightMultiply(p1);
tMat.rightMultiply(p2);
tMat.rightMultiply(p3);
tMat.rightMultiply(p4);
tMat.rightMultiply(p5);
tMat.rightMultiply(p6);
tMat.rightMultiply(p7);
tMat.rightMultiply(p8);
double minX = p1.x;
double minY = p1.y;
double minZ = p1.z;
double maxX = p1.x;
double maxY = p1.y;
double maxZ = p1.z;
Point3[] points = new Point3[8];
points[0] = p1;
points[1] = p2;
points[2] = p3;
points[3] = p4;
points[4] = p5;
points[5] = p6;
points[6] = p7;
points[7] = p8;
for (Point3 p : points){
if (p.x<minX) minX = p.x;
if (p.y<minY) minY = p.y;
if (p.z<minZ) minZ = p.z;
if (p.x>maxX) maxX = p.x;
if (p.y>maxY) maxY = p.y;
if (p.z>maxZ) maxZ = p.z;
}
minBound = new Point3(minX,minY,minZ);
maxBound = new Point3(maxX,maxY,maxZ);
averagePosition = new Point3((minX+maxX)/2, (minY+maxY)/2, (minZ+maxZ)/2);
} | 7 |
public static void main(String[] args) {
//Please input the value of "String[] args" from the settings of Java application.
TypeDesc desc = new TypeDesc();
for(String name : args){
try {
Class<?> startClass = Class.forName(name);
desc.printType(startClass, 0, basic);
} catch (ClassNotFoundException e) {
System.err.println(e);//report the error
}
}
} | 3 |
public static void count_digits(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') count++;
}
System.out.println(count);
} | 3 |
public static int getEndOfBrackets(String function, int posActuelle) {
int nbrBracketsOpened = 0;
int nbrBracketsClosed = 0;
int endPosition = 0;
for (int j = posActuelle; j < function.length(); j++) {
if (function.charAt(j) == '(')
nbrBracketsOpened++;
else if (function.charAt(j) == ')')
nbrBracketsClosed++;
if (nbrBracketsOpened == nbrBracketsClosed) {
endPosition = j;
break;
}
}
return endPosition;
} | 4 |
@Override
public void actionPerformed(GuiButton button)
{
if(button.id == 0)
holder.closeWindow(this);
else if(button.id == 1 && holder instanceof GuiEditor)
{
GuiEditor editor = (GuiEditor)holder;
editor.confirmOperation(new OperationSaveMap(editor,textField.text));
}
} | 3 |
@EventHandler
public void SlimeMiningFatigue(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSlimeConfig().getDouble("Slime.MiningFatigue.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getSlimeConfig().getBoolean("Slime.MiningFatigue.Enabled", true) && damager instanceof Slime && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getSlimeConfig().getInt("Slime.MiningFatigue.Time"), plugin.getSlimeConfig().getInt("Slime.MiningFatigue.Power")));
}
} | 6 |
public String getName() {
return name;
} | 0 |
private void onDownload(FileDownloadEvent event){
for(FileDownloadListener listener : listeners){
listener.onProgressChanged(event);
}
} | 1 |
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
String input = sc.nextLine().toLowerCase();
String[] words = input.split("\\W+");
TreeMap<String, Integer> wordsMap = new TreeMap<>();
for (int i = 0; i < words.length; i++) {
if(!wordsMap.containsKey(words[i])){
wordsMap.put(words[i], 1);
}
else {
wordsMap.put(words[i], wordsMap.get(words[i]) + 1);
if(wordsMap.get(words[i]) > max) {
max = wordsMap.get(words[i]);
}
}
}
for (String key : wordsMap.keySet()) {
if(wordsMap.get(key) == max) {
System.out.print(key + " -> " + wordsMap.get(key) + " times");
System.out.println();
}
}
} | 5 |
public static ArrayList<Customer> showAll() {
ArrayList<Customer> customers = new ArrayList<Customer>();
Database db = dbconnect();
try {
db.prepare("SELECT * FROM customer WHERE bDeleted = 0 ORDER BY CID");
ResultSet rs = db.executeQuery();
while(rs.next()) {
customers.add(CustomerObject(rs));
}
db.close();
} catch (SQLException e) {
Error_Frame.Error(e.toString());
}
return customers;
} | 2 |
public void onEnable() {
sessions = new LinkedList<CTFSession>();
CTFPlugin.plugin = this;
CTFPlugin.weplugin = (WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit");
Bukkit.getPluginManager().registerEvents(this, this);
CTFTypes.registerType(NoEditSession.class);
CTFTypes.registerType(EditSession.class);
CTFTypes.registerType(PigSession.class);
//make sure to get all players currently in on reload in our map
for (World w : Bukkit.getWorlds()) {
if (!w.getPlayers().isEmpty()) {
for (Player p : w.getPlayers()) {
CTFPlugin.hashPlayer(p);
}
}
}
} | 3 |
static final void method449(String string, String string_1_, boolean bool,
int i, boolean bool_2_) {
do {
try {
anInt849++;
BufferedPacket class348_sub47 = Class203.method1478(true);
((BufferedPacket) class348_sub47).buffer
.putByte
(((HandshakePacket) Class178.aClass29_2348).opcode);
((BufferedPacket) class348_sub47).buffer
.putShort(0);
int i_3_
= (((ByteBuffer) (((BufferedPacket) class348_sub47)
.buffer))
.position);
((BufferedPacket) class348_sub47).buffer
.putShort(634);
int[] is = Class50_Sub1.method463(class348_sub47, false);
int i_4_
= (((ByteBuffer) (((BufferedPacket) class348_sub47)
.buffer))
.position);
((BufferedPacket) class348_sub47).buffer
.putJStr((byte) -5, string_1_);
((BufferedPacket) class348_sub47).buffer
.putShort(SocketWorker.affiliateId);
((BufferedPacket) class348_sub47).buffer
.putJStr((byte) -5, string);
((BufferedPacket) class348_sub47).buffer
.putLong(TextureLoader.aLong4615);
((BufferedPacket) class348_sub47).buffer
.putByte(Class348_Sub33.gameLanguage);
((BufferedPacket) class348_sub47).buffer
.putByte
((((GameMode) Class348_Sub42_Sub8_Sub2.gameType)
.id));
s_Sub2.getClientSignature((((BufferedPacket) class348_sub47)
.buffer),
(byte) 55);
String string_5_ = Class14_Sub1.aString8605;
((BufferedPacket) class348_sub47).buffer
.putByte(string_5_ == null ? 0 : 1);
if (string_5_ != null)
((BufferedPacket) class348_sub47)
.buffer
.putJStr((byte) -5, string_5_);
((BufferedPacket) class348_sub47).buffer
.putByte(i);
((BufferedPacket) class348_sub47).buffer
.putByte(!bool_2_ ? 0 : 1);
((ByteBuffer) (((BufferedPacket) class348_sub47)
.buffer)).position
+= 7;
((BufferedPacket) class348_sub47).buffer
.encipherXtea
(is, i_4_,
(((ByteBuffer) (((BufferedPacket) class348_sub47)
.buffer))
.position));
((BufferedPacket) class348_sub47).buffer
.finalizeVarShort
(1809639944,
(((ByteBuffer) (((BufferedPacket) class348_sub47)
.buffer)).position
+ -i_3_));
Class348_Sub42_Sub14.queuePacket(2, class348_sub47);
GameFont.connectionOpcode = -3;
Class367_Sub2.anInt7297 = 1;
Class169.anInt2264 = 0;
NativeRaster.anInt8398 = 0;
if ((i ^ 0xffffffff) <= -14)
break;
Class330.aBoolean4127 = true;
Class286_Sub8.method2172(60);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("iq.D("
+ (string != null ? "{...}"
: "null")
+ ','
+ (string_1_ != null ? "{...}"
: "null")
+ ',' + bool + ',' + i + ','
+ bool_2_ + ')'));
}
break;
} while (false);
} | 8 |
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
String inputLine = "" , outputLine;
// Do the login name
outputLine = "Please enter a username" ;
out.println(outputLine);
while((inputLine = in.readLine()) != null && server.checkUser(inputLine)) {
outputLine = "'" + inputLine + "' is taken. Please enter a unique username" ;
System.out.println(outputLine);
out.println(outputLine);
}
if(inputLine != null) {
server.addUser(inputLine);
server.systemMessage("Added user " + inputLine);
out.println("Welcome to ChatServer!");
username = inputLine ;
loggedin = true ;
while((inputLine = in.readLine()) != null && loggedin) {
if(inputLine.equals("-exit"))
break ;
server.sendMessage(this, inputLine);
}
}
server.removeUser(username);
loggedin = false ;
socket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
System.err.println("Concurrency error");
}
} | 8 |
public void handleClassThatIsAttribute(ClassMeta c) {
System.out.println("Handling: " + c.name);
for(AssociationEndMeta ae : EntityMeta.all_association_ends.values()) {
if(ae.target_id.equals(c.id)) {
System.out.println("found an ae");
AssociationMeta assoc = EntityMeta.all_associations.get(ae.assoc_id);
AssociationEndMeta other_end;
if(ae.equals(assoc.target)) {
other_end = assoc.source;
}
else
other_end = assoc.target;
ClassMeta real_class = EntityMeta.all_classes.get(other_end.target_id);
AttributeMeta a = new AttributeMeta();
a.id = c.id;
a.name = c.name;
a.owner_class = real_class.id;
a.multiplicity = ae.multiplicity;
real_class.attributes.add(a);
System.out.println("attr added to: " + real_class.name);
for(int i = 0; i < c.attributes.size(); ++i) {
if(c.attributes.get(i).name.equals("type"))
a.type = c.attributes.get(i).default_value;
}
assoc.is_creatable = false;
}
}
} | 5 |
public static void outputDisplay(List<Flight> SearchedFlights, FlightDTO dto) {
if (SearchedFlights == null) {
System.out.println("No Flights found for given Locations");
} else if (SearchedFlights.size() == 0) {
System.out
.println("Sorry No flight for this combination of Date and Class");
} else {
if (dto.getOutputPreferences().equalsIgnoreCase("1")) {
Collections.sort(SearchedFlights, Flight.FareSorter);
} else {
Collections.sort(SearchedFlights, Flight.FareDurationSorter);
}
System.out.printf("\n|%-10s | %-12s |%-12s |%-15s |%-10s |\n",
"Flight No", "Valid Till", "Flight Time",
"Flight Duration", "Fare");
String date = null;
for (Flight flight : SearchedFlights) {
try {
date = StringDateConverter.DateToStringConvertor(flight
.getValidTill());
} catch (NewCustomException exception) {
// If conversion not done successfully then converting date
// object to String
date = flight.getValidTill().toString();
}
int fare = flight.getFare();
if (dto.getFlightClass().equalsIgnoreCase("b")) {
fare = fare + (int) (0.4 * fare);
}
System.out.printf("|%-10s | %-12s |%-12s |%-15s |%-10d |\n",
flight.getFlightNo(), date, flight.getFlightTime(),
flight.getFlightDuration(), fare);
}
}
} | 6 |
private Boolean find_driver()
{
try
{
if (driver_class == null)
driver_class = Class.forName(driver_name);
if (driver_class == null)
driver_class = Class.forName(driver_name, true, ClassLoader.getSystemClassLoader());
return true;
}
catch (Exception ex)
{
throw new InvalidQueryException("Unable to find database driver");
}
} | 3 |
public void tick(boolean preview)
{
if(System.currentTimeMillis()-startTime < systemLength || systemLength == -1)
{
for(int x=0;x<maxSpawnRate;x++)
spawnParticle();
}
for(int x=0;x<particles.size();x++)
{
boolean despawn = !particles.get(x).tick(map);
if(despawn)
{
particles.remove(x);
x--;
}
}
} | 5 |
public World(int numWater, int xMin, int yMin, int xMax, int yMax, int yMid)
{
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.yMid = yMid;
// no need to generate air molecules, because that is adjusted every tick based on the temperature
// generate Water molecules
for(int i = 0; i < numWater; i++)
addWater();
updatePerm(perm);
} | 1 |
public static void PROVJERI_naredba_grananja(){
String linija = mParser.ParsirajNovuLiniju(); // ucitaj KR_IF
UniformniZnak uz_kr_if = UniformniZnak.SigurnoStvaranje(linija);
linija = mParser.ParsirajNovuLiniju(); // ucitaj L_ZAGRADA
UniformniZnak uz_l_zagrada = UniformniZnak.SigurnoStvaranje(linija);
linija = mParser.ParsirajNovuLiniju(); // ucitaj <izraz>
Tip_LIzraz_Const_Niz izraz = Izrazi_Sem.PROVJERI_izraz();
linija = mParser.ParsirajNovuLiniju(); // ucitaj D_ZAGRADA
UniformniZnak uz_d_zagrada = UniformniZnak.SigurnoStvaranje(linija);
linija = mParser.ParsirajNovuLiniju(); // ucitaj <naredba>1
PROVJERI_naredba();
// ima li jos i "else"?
Boolean elseExists = false;
linija = mParser.DohvatiProviriVrijednost();
UniformniZnak uz_else = null;
if (linija != null){
uz_else = UniformniZnak.SigurnoStvaranje(linija);
if (uz_else != null && uz_else.mNaziv.equals("KR_ELSE")) elseExists = true;
}
// ispis u slucaju pogreske
if (!Utilities_Sem.ImplicitnaPretvorbaMoguca(izraz.mTip, Tip._int) || izraz.mNiz){
String greska = "<naredba_grananja> ::= " + uz_kr_if.FormatZaIspis() + " " +
uz_l_zagrada.FormatZaIspis() + " <izraz> " + uz_d_zagrada.FormatZaIspis() + " <naredba>";
if (elseExists) greska += " " + uz_else.FormatZaIspis() + " <naredba>";
Utilities_Sem.WriteStringLineToOutputAndExit(greska);
}
if (elseExists){
linija = mParser.ParsirajNovuLiniju(); // ucitaj KR_ELSE (jer smo ga dobavili samo privirkivanjem)
linija = mParser.ParsirajNovuLiniju(); // ucitaj <naredba>2
PROVJERI_naredba();
return;
}
} | 7 |
public void selectHero(Object hero)
{
System.out.println("?! "+heroesSelected);
WidgetChooserButton button = (WidgetChooserButton)(heroesInner.itemAt(heroesSelected).widget());
if (hero != heroes.get(heroesSelected)) {
heroesSelected = heroes.indexOf(hero);
button.setChecked(false);
} else {
button.setChecked(true);
}
this.hero = (Hero)hero;
scroll.ensureVisible(this.hero.getX()*64, this.hero.getY()*64, 64*4, 64*4);
heroChanged.emit(this.hero);
} | 1 |
public void create(Fornecedor fornecedor) throws PreexistingEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(fornecedor);
em.getTransaction().commit();
} catch (Exception ex) {
if (findFornecedor(fornecedor.getCpf()) != null) {
throw new PreexistingEntityException("Fornecedor " + fornecedor + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} | 3 |
private void preenceTabela(List<FormasPagamento> lista){
this.modelo = new DefaultTableModel();
modelo.addColumn("id");
modelo.addColumn("Nome");
for(FormasPagamento f : lista){
Vector valores = new Vector();
valores.add(0,f.getId());
valores.add(1,f.getNome());
modelo.addRow(valores);
}
tblListagem.setModel(modelo);
tblListagem.repaint();
} | 1 |
public void loadOrder(){
orderDataAccesor dataAccessOrder=new orderDataAccesor();
List<order> orderList=new ArrayList();
DefaultTableModel orderDataTable=new DefaultTableModel();
Object[ ] columnNames=new Object[5];
Object[ ] fieldValues=new Object[5];
//Patient myPatient=null;
try{
orderList=dataAccessOrder.retrieveOrderData(supplierDetailsOrderCombo.getSelectedItem().toString());
}
catch(SQLException e){
System.out.println(e.getMessage());
}
if(orderList.isEmpty()){
JOptionPane.showMessageDialog(null,"No orders from the selected supplier ","Information",JOptionPane.WARNING_MESSAGE);
}
columnNames[0]="OrderID";
columnNames[1]="Supplier Name";
columnNames[2]="Order Date";
columnNames[3]="Order Info";
columnNames[4]="Order Amount";
orderDataTable.setColumnIdentifiers(columnNames);
if(orderList.size()>0){
for (order newOrder : orderList) {
tempOrder = newOrder;
fieldValues[0]=tempOrder.getOrderID();
fieldValues[1]=tempOrder.getSupplierName();
fieldValues[2]=tempOrder.getOrderDate();
fieldValues[3]=tempOrder.getOrderInfo();
fieldValues[4]=tempOrder.getOrderAmount();
orderDataTable.addRow(fieldValues);
}
this.orderTable.setModel(orderDataTable);
this.orderTable.setVisible(true);
}
} | 4 |
public static void ChooseAllen ()
{
if (Game.characterChoice == 1)
{
Game.CharacterOne = "Allen";
Game.CharacterOneHP = CharacterStats.AllenHP;
Game.CharacterOneAttack = CharacterStats.AllenAttack;
Game.CharacterOneMana = CharacterStats.AllenMana;
Game.CharacterOneRegen = CharacterStats.AllenRegen;
Game.MovesOne = CharacterMoves.AllenMoves;
Game.MoveOneValue [0] = CharacterStats.AllenAttack;
Game.MoveOneValue [1] = CharacterMoves.HaHa;
Game.MoveOneValue [2] = CharacterMoves.LeapAttack;
Game.MoveOneValue [3] = CharacterMoves.Crush;
Game.MoveOneValue [4] = CharacterMoves.Avatar;
Game.MoveOneCost [0] = CharacterMoves.AttackCost;
Game.MoveOneCost [1] = CharacterMoves.HaHaCost;
Game.MoveOneCost [2] = CharacterMoves.LeapAttackCost;
Game.MoveOneCost [3] = CharacterMoves.CrushCost;
Game.MoveOneCost [4] = CharacterMoves.AvatarCost;
Game.OptionsOne [0] = "Attack (" + CharacterMoves.AttackCost + " mana)";
Game.OptionsOne [1] = "HaHa (" + CharacterMoves.HaHaCost + " mana)";
Game.OptionsOne [2] = "LeapAttack (" + CharacterMoves.LeapAttackCost + " mana)";
Game.OptionsOne [3] = "Crush (" + CharacterMoves.CrushCost + " mana)";
Game.OptionsOne [4] = "Avatar (" + CharacterMoves.AvatarCost + " mana)";
Game.ActionOne [0] = Game.CharacterOne + " attacks " + Game.CharacterTwo + ".";
Game.ActionOne [1] = "Allen laughs at " + Game.CharacterTwo + ".";
Game.ActionOne [2] = "Allen leaps into the air and lands on " + Game.CharacterTwo + ".";
Game.ActionOne [3] = "Allen crushes " + Game.CharacterTwo + ".";
Game.ActionOne [4] = "Allen turns into an unstoppable force.";
}
else if (Game.characterChoice == 2)
{
Game.CharacterTwo = "Allen";
Game.CharacterTwoHP = CharacterStats.AllenHP;
Game.CharacterTwoAttack = CharacterStats.AllenAttack;
Game.CharacterTwoMana = CharacterStats.AllenMana;
Game.CharacterTwoRegen = CharacterStats.AllenRegen;
Game.MovesTwo = CharacterMoves.AllenMoves;
Game.MoveTwoValue [0] = CharacterStats.AllenAttack;
Game.MoveTwoValue [1] = CharacterMoves.HaHa;
Game.MoveTwoValue [2] = CharacterMoves.LeapAttack;
Game.MoveTwoValue [3] = CharacterMoves.Crush;
Game.MoveTwoValue [4] = CharacterMoves.Avatar;
Game.MoveTwoCost [0] = CharacterMoves.AttackCost;
Game.MoveTwoCost [1] = CharacterMoves.HaHaCost;
Game.MoveTwoCost [2] = CharacterMoves.LeapAttackCost;
Game.MoveTwoCost [3] = CharacterMoves.CrushCost;
Game.MoveTwoCost [4] = CharacterMoves.AvatarCost;
Game.OptionsTwo [0] = "Attack (" + CharacterMoves.AttackCost + " mana)";
Game.OptionsTwo [1] = "HaHa (" + CharacterMoves.HaHaCost + " mana)";
Game.OptionsTwo [2] = "LeapAttack (" + CharacterMoves.LeapAttackCost + " mana)";
Game.OptionsTwo [3] = "Crush (" + CharacterMoves.CrushCost + " mana)";
Game.OptionsTwo [4] = "Avatar (" + CharacterMoves.AvatarCost + " mana)";
Game.ActionTwo [0] = Game.CharacterTwo + " attacks " + Game.CharacterOne + ".";
Game.ActionTwo [1] = "Allen laughs at " + Game.CharacterOne + ".";
Game.ActionTwo [2] = "Allen leaps into the air and lands on " + Game.CharacterOne + ".";
Game.ActionTwo [3] = "Allen crushes " + Game.CharacterOne + ".";
Game.ActionTwo [4] = "Allen turns into an unstoppable force.";
}
} | 2 |
public SecuredTaskTriggerBean execute(SecuredTaskTriggerBean task) throws GranException {
//String clientDataUDFName = KernelManager.getFind().findUdf(INCIDENT_CLIENTDATA_UDFID).getCaption();
String client = task.getUdfValue(INCIDENT_CLIENT_UDF);
introduceNewClient(task, client);
SecuredUserBean clientUser = task.getSecure().getUser();
if (client!=null && client.length()>0)
clientUser = AdapterManager.getInstance().getSecuredUserAdapterManager().findByName(task.getSecure(), client);
else {
task.setUdfValue(INCIDENT_CLIENT_UDF, clientUser.getName());
task.setUdfValue(INCIDENT_EMAIL_UDF, clientUser.getEmail());
task.setUdfValue(INCIDENT_PHONE_UDF, clientUser.getTel());
task.setUdfValue(INCIDENT_COMPANY_UDF, clientUser.getCompany());
}
if (task.getHandlerUserId()==null){
// set Assignee
ArrayList statuses = KernelManager.getAcl().getEffectiveStatuses(task.getParentId(), task.getSubmitterId());
if (statuses.contains(FIRST_LINE_ROLE_ID) && !statuses.contains(ESCALATOR_BOT_ROLE)) {
task.setHandlerGroupId(null);
task.setHandlerUserId(task.getSubmitterId());
} else if (statuses.contains(CLIENT_ROLE_ID)){
task.setHandlerGroupId(FIRST_LINE_ROLE_ID);
}
}
return task;
} | 6 |
public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
if (averageGroundLevel < 0)
{
averageGroundLevel = getAverageGroundLevel(par1World, par3StructureBoundingBox);
if (averageGroundLevel < 0)
{
return true;
}
boundingBox.offset(0, ((averageGroundLevel - boundingBox.maxY) + 9) - 1, 0);
}
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 1, 7, 5, 4, 0, 0, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 0, 8, 0, 5, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 5, 0, 8, 5, 5, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 6, 1, 8, 6, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 7, 2, 8, 7, 3, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
int i = getMetadataWithOffset(Block.stairCompactPlanks.blockID, 3);
int j = getMetadataWithOffset(Block.stairCompactPlanks.blockID, 2);
for (int k = -1; k <= 2; k++)
{
for (int i1 = 0; i1 <= 8; i1++)
{
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, i, i1, 6 + k, k, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, j, i1, 6 + k, 5 - k, par3StructureBoundingBox);
}
}
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 0, 0, 1, 5, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 5, 8, 1, 5, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 8, 1, 0, 8, 1, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 2, 1, 0, 7, 1, 0, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 2, 0, 0, 4, 0, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 2, 5, 0, 4, 5, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 8, 2, 5, 8, 4, 5, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 8, 2, 0, 8, 4, 0, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 2, 1, 0, 4, 4, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 2, 5, 7, 4, 5, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 8, 2, 1, 8, 4, 4, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 2, 0, 7, 4, 0, Block.planks.blockID, Block.planks.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 2, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 5, 2, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 6, 2, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 3, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 5, 3, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 6, 3, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 3, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 3, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 8, 2, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 8, 2, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 8, 3, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 8, 3, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 2, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 3, 2, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 5, 2, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 6, 2, 5, par3StructureBoundingBox);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 4, 1, 7, 4, 1, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 4, 4, 7, 4, 4, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 3, 4, 7, 3, 4, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.planks.blockID, 0, 7, 1, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, getMetadataWithOffset(Block.stairCompactPlanks.blockID, 0), 7, 1, 3, par3StructureBoundingBox);
int l = getMetadataWithOffset(Block.stairCompactPlanks.blockID, 3);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, l, 6, 1, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, l, 5, 1, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, l, 4, 1, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, l, 3, 1, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 6, 1, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.pressurePlatePlanks.blockID, 0, 6, 2, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 4, 1, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.pressurePlatePlanks.blockID, 0, 4, 2, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.workbench.blockID, 0, 7, 1, 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, 0, 0, 1, 1, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, 0, 0, 1, 2, 0, par3StructureBoundingBox);
placeDoorAtCurrentPosition(par1World, par3StructureBoundingBox, par2Random, 1, 1, 0, getMetadataWithOffset(Block.doorWood.blockID, 1));
if (getBlockIdAtCurrentPosition(par1World, 1, 0, -1, par3StructureBoundingBox) == 0 && getBlockIdAtCurrentPosition(par1World, 1, -1, -1, par3StructureBoundingBox) != 0)
{
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 1, 0, -1, par3StructureBoundingBox);
}
for (int j1 = 0; j1 < 6; j1++)
{
for (int k1 = 0; k1 < 9; k1++)
{
clearCurrentPositionBlocksUpwards(par1World, k1, 9, j1, par3StructureBoundingBox);
fillCurrentPositionBlocksDownwards(par1World, Block.cobblestone.blockID, 0, k1, -1, j1, par3StructureBoundingBox);
}
}
spawnVillagers(par1World, par3StructureBoundingBox, 2, 1, 2, 1);
return true;
} | 8 |
@Test(expected = PersistencyException.class)
public void WhenLoadingFromFileWithInvalidAddress_ExpectPersistencyException() throws PersistencyException {
RoutingTable routingTable = new RoutingTable();
try {
persistenceDelegate_.load(INVALID_ADDRESS_FILE, routingTable);
} catch (FileNotFoundException e) {
}
} | 1 |
public static String toString( double[][] matrix )
{
String retVal = "";
int m = matrix.length;
int n = matrix[0].length;
for ( int i = 0; i < m; ++i )
{
for ( int j = 0; j < n; ++j )
{
retVal += fillString(Double.toString(matrix[i][j]), 24);
}
retVal += "\n";
}
return(retVal);
} | 2 |
public static Change add(final CourseRec course, final OffRec offering) {
offering.setCourse(course);
Change change = new Change(course.getSource(), Change.ADD, offering) {
@Override
public String getDescription() {
return "Offering";
}
@Override
public Object getTarget() {
return "[" + course.getStatus() + "]" + course.getName();
}
@Override
public Object getNewValue() {
return offering.getStartStr();
}
@Override
public Object getOldValue() {
return null;
}
@Override
public void apply(CourseModel model) {
// Does class already have a MAYBE or REGISTERED offering?
boolean alreadyHas = false;
for (OffRec or : course.getOfferings()) {
if (or.getStatus() == Status.MAYBE
|| or.getStatus() == Status.REGISTERED) {
alreadyHas = true;
break;
}
}
// Add first to avoid exception in setStatus.
course.addOffering(offering);
Status sc = course.getStatus();
if (alreadyHas || sc == Status.NO || sc == Status.DONE
|| sc == Status.AUDITED || sc == Status.CHAIN)
offering.setStatus(Status.NO);
}
};
StringBuffer b = new StringBuffer("<html><b>New offerring");
if (offering.getStart() != null)
b.append(" on ").append(OffRec.dformat.format(offering.getStart()));
b.append("<br/>for ");
appendCourse(b, course);
return change.setOrder(3).setToolTop(b.toString());
} | 9 |
static void skykid_draw_sprites(osd_bitmap bitmap)
{
int offs;
for (offs = 0; offs < spriteram_size[0]; offs += 2){
int number = spriteram.read(offs) | ((spriteram_3.read(offs) & 0x80) << 1);
int color = (spriteram.read(offs+1) & 0x3f);
int sx = 256 - ((spriteram_2.read(offs+1)) + 0x100*(spriteram_3.read(offs+1) & 0x01)) + 72;
int sy = spriteram_2.read(offs) - 7;
int flipy = spriteram_3.read(offs) & 0x02;
int flipx = spriteram_3.read(offs) & 0x01;
int width, height;
if (number >= 128*3) continue;
switch (spriteram_3.read(offs) & 0x0c){
case 0x0c: /* 2x both ways */
width = height = 2; number &= (~3); break;
case 0x08: /* 2x vertical */
width = 1; height = 2; number &= (~2); break;
case 0x04: /* 2x horizontal */
width = 2; height = 1; number &= (~1); break;
default: /* normal sprite */
width = height = 1; sx += 16; break;
}
{
int x_offset[]= { 0x00, 0x01 };
int y_offset[] = { 0x00, 0x02 };
int x,y, ex, ey;
for( y=0; y < height; y++ ){
for( x=0; x < width; x++ ){
ex = flipx!=0 ? (width-1-x) : x;
ey = flipy!=0 ? (height-1-y) : y;
drawgfx(bitmap,Machine.gfx[2+(number >> 7)],
(number)+x_offset[ex]+y_offset[ey],
color,
flipx, flipy,
sx+x*16,sy+y*16,
Machine.drv.visible_area,
TRANSPARENCY_COLOR,255);
}
}
}
}
} | 9 |
public int getParameter(String paramname){
if(paramname == "HoodSize"){return map.getBrushLength();}
if(paramname == "NextX"){return map.getNextX();}
if(paramname == "NextY"){return map.getNextY();}
if(paramname == "Age"){ return age;}
if(paramname == "Fade"){ return fade;}
if(paramname == "MirrX"){ return hoodx;}
if(paramname == "MirrY"){ return hoody;}
if(paramname == "InMode"){return inmode;}
if(paramname == "OutMode"){return outmode;}
return -1;} | 9 |
@Override
public int hashCode() {
int hash = 0;
hash += (idLaptop != null ? idLaptop.hashCode() : 0);
return hash;
} | 1 |
public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} | 6 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MapleMessengerCharacter other = (MapleMessengerCharacter) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} | 6 |
public void resize(double scaleFactor){
scaleFactor = (double)(Gui.getSlidePanel().getWidth())
/ (double)slideDimension.width;
if (Debug.video) System.out.println("VideoPlayer -> resize -> resize called");
if ((null != player) && (realizeComplete) && (!Gui.isVideoFullScreenOn())){
// Calculate the new scaled coordinates and dimensions.
scaledXCoord = (int) (xCoord * scaleFactor);
scaledYCoord = (int) (yCoord * scaleFactor);
scaledXDim = (int) (xDim * scaleFactor);
scaledYDim = (int) (yDim * scaleFactor);
// Set the new dimensions, depending if controls are present or not.
if (true == controls){
mediaPanel.setBounds(0, 0, scaledXDim, scaledYDim+25);
outerPanel.setBounds(scaledXCoord, scaledYCoord, scaledXDim, scaledYDim+25);
controlComponent.setBounds(0, scaledYDim, scaledXDim, 25);
}
else{
mediaPanel.setBounds(0, 0, scaledXDim, scaledYDim);
outerPanel.setBounds(scaledXCoord, scaledYCoord, scaledXDim, scaledYDim);
}
videoComponent.setBounds(0, 0, scaledXDim, scaledYDim);
MouseMonitor.rescale(scaledXDim, scaledYDim);
MouseMonitor.reposition(scaledXCoord, scaledYCoord);
if (Debug.video) System.out.println("VideoPlayer -> resize -> mediaPanel new size : " + mediaPanel.getSize());
}
} | 6 |
@Test
public void testCreatingPhoneNumberWithNullNumberShouldFail() {
try {
new PhoneNumber("home", null);
fail("Was expecting an Exception when no country code is provided.");
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Please provide a value for Number as it is a non-nullable field.", iae.getMessage());
}
} | 1 |
public int getID() {
return this.id;
} | 0 |
public E dequeue(){
if(total == 0) throw new NoSuchElementException();
E e = first.e;
first = first.next;
if(--total == 0) last = null;
return e;
} | 2 |
public boolean load(){
return false;
} | 0 |
public static void main(String[] args) throws Exception {
if (args.length != 8) {
System.err
.print("Syntax error. Correct syntax:\n"
+ " <trainfile_supervised> <trainfile_semisupervised> "
+ "<supervised_weight> <observation_feature> <state_feature> "
+ "<modelfile> <numiterations> <seed>\n");
System.exit(1);
}
int arg = 0;
String trainFileNameS = args[arg++];
String trainFileNameSS = args[arg++];
double weightS = Double.parseDouble(args[arg++]);
String observationFeatureLabel = args[arg++];
String stateFeatureLabel = args[arg++];
String modelFileName = args[arg++];
int numIterations = Integer.parseInt(args[arg++]);
int seed = Integer.parseInt(args[arg++]);
System.out.println(String.format(
"Unsupervised training HMM model with the following parameters:\n"
+ "\tSupervised train file: %s\n"
+ "\tSemi-supervised train file: %s\n"
+ "\tSupervised weight: %f\n"
+ "\tObservation feature: %s\n"
+ " State feature: %s\n" + "\tModel file: %s\n"
+ " # iterations: %d\n" + "\tSeed: %d\n",
trainFileNameS, trainFileNameSS, weightS,
observationFeatureLabel, stateFeatureLabel, modelFileName,
numIterations, seed));
if (seed > 0)
RandomGenerator.gen.setSeed(seed);
// State labels from the initial model.
String[] stateFeaturesV = { "0", "B-PER", "I-PER", "B-LOC", "I-LOC",
"B-ORG", "I-ORG", "B-MISC", "I-MISC" };
// Load the first trainset (supervised).
Corpus trainsetS = new Corpus(trainFileNameS);
int size1 = trainsetS.getNumberOfExamples();
// Load the second trainset (semi-supervised).
Corpus trainsetSS = new Corpus(trainFileNameSS,
trainsetS.getFeatureValueEncoding());
int size2 = trainsetSS.getNumberOfExamples();
// Join the two datasets.
trainsetS.add(trainsetSS);
trainsetSS = null;
// Create and fill the weight vector.
Vector<Object> weights = new Vector<Object>(size1 + size2);
weights.setSize(size1 + size2);
int idxExample = 0;
for (; idxExample < size1; ++idxExample)
weights.set(idxExample, weightS);
for (; idxExample < size1 + size2; ++idxExample)
weights.set(idxExample, 1.0);
// Supervised train an initial model on the joined dataset.
WeightedHmmTrainer wHmmTrainer = new WeightedHmmTrainer();
wHmmTrainer.setWeights(weights);
HmmModel modelSupervised = wHmmTrainer.train(trainsetS,
observationFeatureLabel, stateFeatureLabel, "0");
// Fill the tagged flag vector.
Vector<Object> flags = new Vector<Object>(size1 + size2);
// All examples in the first dataset are flagged as tagged.
idxExample = 0;
for (; idxExample < size1; ++idxExample)
flags.add(new Boolean(true));
// The tokens tagged different of 0 are flagged as tagged. The rest are
// flagged as untagged.
for (; idxExample < size1 + size2; ++idxExample) {
DatasetExample example = trainsetS.getExample(idxExample);
Vector<Boolean> flagsEx = new Vector<Boolean>(example.size());
for (int token = 0; token < example.size(); ++token) {
if (example.getFeatureValueAsString(token, stateFeatureLabel)
.equals("0"))
flagsEx.add(false);
else
flagsEx.add(true);
}
flags.add(flagsEx);
}
// Train an HMM model.
SemiSupervisedHmmTrainer ssHmmTrainer = new SemiSupervisedHmmTrainer();
ssHmmTrainer.setTaggedExampleFlags(flags);
ssHmmTrainer.setWeights(weights);
ssHmmTrainer.setInitialModel(modelSupervised);
HmmModel model = ssHmmTrainer.train(trainsetS, observationFeatureLabel,
stateFeatureLabel, stateFeaturesV, numIterations);
// Save the model.
model.save(modelFileName);
} | 8 |
public AmmoPackItem retrieveAmmoPack(BulletType bulletType) {
List<Item> list = inventory.getAll("ammopack.");
AmmoPackItem ap = null;
for (Item i : list) {
AmmoPackItem pack = (AmmoPackItem) i;
if (pack.getBulletType() == bulletType) {
if ((ap == null || pack.getAmount() > ap.getAmount()) && pack.getQuantity() > 0) {
ap = (AmmoPackItem) pack.makeClone(1);
}
}
}
if (ap != null)
inventory.removeItem(ap);
return ap;
} | 6 |
@Override
protected void initConstraint()
{
if ( Theme.list == null )
{
Theme.list = new HashSet<String>();
String jarPath = Window.class.getResource("game").getPath();
jarPath = jarPath.substring(5, jarPath.indexOf("!"));
JarFile jar = null;
try {
jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
} catch (IOException ex) {
Logger.getLogger(Theme.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
Enumeration<JarEntry> jarContent = jar.entries();
while (jarContent.hasMoreElements()) {
JarEntry entry = jarContent.nextElement();
String fileName = entry.getName();
if (!entry.isDirectory() || !fileName.contains("game") || fileName.endsWith("game/"))
continue;
String[] theme = fileName.split("/");
Theme.list.add(theme[theme.length-1]);
}
}
} | 6 |
public static void rangeCheck(Object comp, boolean in, boolean out) throws Exception {
ComponentAccess cp = new ComponentAccess(comp);
Collection<Access> acc = new ArrayList<Access>();
if (in) {
acc.addAll(cp.inputs());
}
if (out) {
acc.addAll(cp.outputs());
}
for (Access a : acc) {
String name = a.getField().getName();
Object val = a.getFieldValue();
Range range = a.getField().getAnnotation(Range.class);
if (range != null) {
if (val instanceof Number) {
double v = ((Number) val).doubleValue();
if (!Annotations.inRange(range, v)) {
throw new ComponentException(name + " not in range " + v);
}
} else if (val instanceof double[]) {
double[] v = (double[]) val;
for (int i = 0; i < v.length; i++) {
if (!Annotations.inRange(range, v[i])) {
throw new ComponentException(name + " not in range " + v[i]);
}
}
}
}
}
} | 9 |
@Override
public void deserialize(Buffer buf) {
super.deserialize(buf);
year = buf.readShort();
if (year < 0)
throw new RuntimeException("Forbidden value on year = " + year + ", it doesn't respect the following condition : year < 0");
month = buf.readShort();
if (month < 0)
throw new RuntimeException("Forbidden value on month = " + month + ", it doesn't respect the following condition : month < 0");
day = buf.readShort();
if (day < 0)
throw new RuntimeException("Forbidden value on day = " + day + ", it doesn't respect the following condition : day < 0");
hour = buf.readShort();
if (hour < 0)
throw new RuntimeException("Forbidden value on hour = " + hour + ", it doesn't respect the following condition : hour < 0");
minute = buf.readShort();
if (minute < 0)
throw new RuntimeException("Forbidden value on minute = " + minute + ", it doesn't respect the following condition : minute < 0");
} | 5 |
public boolean tjekLogind(String brugernavn, String kode) {
boolean tjek = false;
ResultSet rs = null;
PreparedStatement pst = null;
String SQLString1 =
"SELECT * from BRUGER_LOGIN_TBL WHERE BRUGERNAVN=? AND KODEORD=?";
try{
pst = con.prepareStatement(SQLString1);
pst.setString(1, brugernavn);
pst.setString(2, kode);
rs = pst.executeQuery();
if(rs.next()){
tjek = true;
}
}
catch (SQLException e) {
System.out.println("Fail in OrderMapper - getOrder");
System.out.println(e.getMessage());
}
finally {
try {
if (pst != null) {
pst.close();
}
}
catch (SQLException e) {
System.out.println("Fail in OrderMapper - getOrder");
System.out.println(e.getMessage());
}
}
return tjek;
} | 4 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + day;
result = prime * result + hour;
result = prime * result + minute;
result = prime * result + month;
result = prime * result + second;
result = prime * result + year;
return result;
} | 0 |
private void initComponents() {
setLayout(new GroupLayout());
add(getJLabel0(), new Constraints(new Leading(105, 10, 10), new Leading(22, 10, 10)));
add(getJLabel1(), new Constraints(new Leading(70, 208, 12, 12), new Leading(89, 10, 10)));
add(getJButton0(), new Constraints(new Leading(59, 10, 10), new Leading(153, 10, 10)));
add(getJButton1(), new Constraints(new Leading(185, 10, 10), new Leading(153, 27, 12, 12)));
setSize(320, 240);
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.