text stringlengths 14 410k | label int32 0 9 |
|---|---|
private void checkDisplayCollision() {
int futureX = this.getLocation().x - moveRichtungX;
int futureY = this.getLocation().y - moveRichtungY;
if (futureX > 0)
futureX += moveRichtungX;
if (futureY > 0)
futureY += moveRichtungY;
if (this.getLocation().x + getLevelWidth() - moveRichtungX < Start
.getFrameWidth())
futureX += moveRichtungX;
if (this.getLocation().y + getLevelHeight() - moveRichtungY < Start
.getFrameHeight())
futureY += moveRichtungY;
this.setBounds(futureX, futureY, this.getWidth(), this.getHeight());
} | 4 |
private boolean canMoveDiagonal(Grid grid, Position pos) {
for (Element element : grid.getElementsOnGrid()) {
if (element instanceof Player
&& ((Player) element).getLightTrail().getPositions().contains(new Position(pos.getxCoordinate(), pos.getyCoordinate() - 1))
&& ((Player) element).getLightTrail().getPositions().contains(new Position(pos.getxCoordinate() - 1, pos.getyCoordinate())))
return false;
}
return true;
} | 4 |
public void getKnightGraph(mxAnalysisGraph aGraph, int xDim, int yDim)
{
if (xDim < 3 || yDim < 3)
{
throw new IllegalArgumentException();
}
int numVertices = xDim * yDim;
mxGraph graph = aGraph.getGraph();
Object parent = graph.getDefaultParent();
Object[] vertices = new Object[numVertices];
for (int i = 0; i < numVertices; i++)
{
vertices[i] = graph.insertVertex(parent, null, new Integer(i).toString(), 0, 0, 25, 25);
}
//now we set up the starting conditions
int[] currCoords = new int[2];
//the main loop
for (int i = 0; i < (xDim * yDim); i++)
{
currCoords = getVertexGridCoords(xDim, yDim, i);
Object[] neighborMoves = getKnightMoveVertexes(aGraph, xDim, yDim, currCoords[0], currCoords[1]);
for (int j = 0; j < neighborMoves.length; j++)
{
// connect current with the possible move that has minimum number of its (possible moves)
if (!mxGraphStructure.areConnected(aGraph, vertices[i], neighborMoves[j]))
{
graph.insertEdge(parent, null, getNewEdgeValue(aGraph), vertices[i], neighborMoves[j]);
}
// that vertex becomes the current vertex and we repeat until no possible moves
}
}
}; | 6 |
public double value() {return value;} | 0 |
private void setChars(char [][] board)
{
for(int x = 1; x < board.length; x++)
{
for(int y = 1; y < board[x].length; y++)
{
//matches each index to their corresponding char in the sym array and replaces them
//based on the char number generated earlier
if(board[x][y] == '1')
board[x][y] = sym[chn][1];
else if(board[x][y] == '2')
board[x][y] = sym[chn][2];
else if(board[x][y] == '3')
board[x][y] = sym[chn][3];
else if(board[x][y] == '4')
board[x][y] = sym[chn][4];
else
board[x][y] = '!'; //if the number is not found for some reason, set it to '!'
}
}
} | 6 |
public void drawGround(Graphics2D gI)
{
gI.setColor(new Color(10, 170, 10));
gI.fillRect(0, 0, Chunk.getPixelLength(), Chunk.getPixelLength());
} | 0 |
protected void write(String event, int resID, double clock)
{
if (!record_) {
return;
}
// Write into a results file
FileWriter fwriter = null;
try
{
fwriter = new FileWriter(super.get_name(), true);
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while opening file " + super.get_name());
}
try
{
fwriter.write(event + "\t" + resID + "\t" + clock + "\n");
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while writing on file " + super.get_name());
}
try
{
fwriter.close();
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while closing file " + super.get_name());
}
} | 4 |
public void keyReleased(KeyEvent e) {
// Si se presiona la tecla P, se pausa y despausa el juego
if (e.getKeyCode() == KeyEvent.VK_P) {
if(!gameover & inicia){
pausa =! pausa;
}
}
// Si se presiona la tecla S, suena o deja de sonar la musica
if (e.getKeyCode() == KeyEvent.VK_S) {
if(contMusica == 0) {
musicaJuego.stop();
contMusica++;
}
else {
musicaJuego.play();
contMusica--;
}
}
// Hace que el Flappy suba
if (e.getKeyCode() == KeyEvent.VK_SPACE){
clickSpace = true;
contVecesArriba = 0;
inicia = true; // Inicia el juego
if (gameover){
reinicia();
}
}
// Boton para cuando haya errores en juego de reinicio
if (e.getKeyCode() == KeyEvent.VK_R){
gameover = false;
reinicia();
}
//si se presiona la tecla G, se graba el juego
if (e.getKeyCode() == KeyEvent.VK_G){
//if(!instrucciones)
save = !save;
}
//si se presiona la tecla C, se carga el juego
if (e.getKeyCode() == KeyEvent.VK_C){
//if(!instrucciones)
load = !load;
}
} | 9 |
public static RepNotification UPDATE_REPONSE(OVNotification ovNotification) throws SQLException {
RepNotification rep = new RepNotification();
Connection connexion = GET_CONNECTION();
try {
Statement statement = connexion.createStatement();
int resultat = statement.executeUpdate("UPDATE reponse SET etat = " + ovNotification.getReponseEnvoye().getEtat() + " WHERE idReponse = " + ovNotification.getReponseEnvoye().getId() + ";");
if (resultat == 0) {
rep.erreur = true;
rep.messageErreur = "Aucune ligne mise à jour!";
}
// Ajout de la promotion //
if (ovNotification.getReponseEnvoye().getEtat() == 1 && ovNotification.getOvPromotion() != null) {
resultat = statement.executeUpdate("INSERT intO promotionutilisateur (idUtilisateur, idPromotion) VALUES (" + ovNotification.getIdUtilisateur() + "," + ovNotification.getOvPromotion().getId() + ");", Statement.RETURN_GENERATED_KEYS);
if (resultat == 0) {
rep.erreur = true;
rep.messageErreur = "Aucune ligne inséré!";
}
}
} catch (SQLException ex) {
rep.erreur = true;
rep.messageErreur = ex.getMessage();
}
return rep;
} | 5 |
public void dieHero(Hero hero)
{
if (heroes.remove(hero)) {
deadHeroes.add(hero);
}
} | 1 |
public static void formatTriangles(byte data[], int id) {
if (data == null) {
ModelHeader modelHeader = Model.modelHeaderCache[id] = new ModelHeader();
modelHeader.vertexCount = 0;
modelHeader.triangleCount = 0;
modelHeader.texturedTriangleCount = 0;
return;
}
Stream buffer = new Stream(data);
buffer.offset = data.length - 18;
ModelHeader header = Model.modelHeaderCache[id] = new ModelHeader();
header.buffer = data;
header.vertexCount = buffer.getUnsignedShort();
header.triangleCount = buffer.getUnsignedShort();
header.texturedTriangleCount = buffer.getUnsignedByte();
int faceOff = buffer.getUnsignedByte();
int priOff = buffer.getUnsignedByte();
int transOff = buffer.getUnsignedByte();
int skinOff = buffer.getUnsignedByte();
int vSkinOff = buffer.getUnsignedByte();
int vertXOff = buffer.getUnsignedShort();
int vertYOff = buffer.getUnsignedShort();
int vertZOff = buffer.getUnsignedShort();
int colorOff = buffer.getUnsignedShort();
int off = 0;
header.vertexModOffset = off;
off += header.vertexCount;
header.triangleMeshLinkOffset = off;
off += header.triangleCount;
header.trianglePriorityOffset = off;
if (priOff == 255) {
off += header.triangleCount;
} else {
header.trianglePriorityOffset = -priOff - 1;
}
header.triangleSkinningOffset = off;
if (skinOff == 1) {
off += header.triangleCount;
} else {
header.triangleSkinningOffset = -1;
}
header.triangleFaceTypeOffset = off;
if (faceOff == 1) {
off += header.triangleCount;
} else {
header.triangleFaceTypeOffset = -1;
}
header.vertexSkinOffset = off;
if (vSkinOff == 1) {
off += header.vertexCount;
} else {
header.vertexSkinOffset = -1;
}
header.triangleTransparencyOffset = off;
if (transOff == 1) {
off += header.triangleCount;
} else {
header.triangleTransparencyOffset = -1;
}
header.triangleVertexPointOffset = off;
off += colorOff;
header.triangleColorOffset = off;
off += header.triangleCount * 2;
header.triangleTextureOffset = off;
off += header.texturedTriangleCount * 6;
header.vertexOffsetX = off;
off += vertXOff;
header.vertexOffsetY = off;
off += vertYOff;
header.vertexOffsetZ = off;
off += vertZOff;
} | 6 |
public void delete(String whereString){
StringBuffer sql = new StringBuffer("");
sql.append("Delete from `SubSection`");
if (whereString.trim() != "") {
sql.append(" where " + whereString);
}
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
sQLHelper.runUpdate(sql.toString());
sQLHelper.sqlClose();
} | 1 |
public static void changeSelectionToNode(JoeTree tree, OutlineLayoutManager layout) {
Node selectedNode = tree.getOldestInSelection();
// Update Selection
tree.clearSelection();
tree.addNodeToSelection(selectedNode);
// Record State
tree.setEditingNode(selectedNode);
tree.setCursorPosition(0);
tree.getDocument().setPreferredCaretPosition(0);
// Redraw and Set Focus
layout.draw(selectedNode, OutlineLayoutManager.ICON);
} | 0 |
public void endElement(String uri, String localName,
String qName)
throws SAXException {
if(qName.equals("hits")) {
inHits = false;
}
if(qName.equals("score")) {
inScore = false;
}
if(qName.equals("color")) {
inColor = false;
}
if(qName.equals("brickConfiguration")) {
gameEngine.getBrickConfigurations().add(new BrickConfiguration(hits, score, color));
}
} | 4 |
public void makeStep() {
if(Utils.DEBUG) {
curAli.checkCons();
if(curDist != distCalc.dist(curAli))
throw new Error("Inconsistency in distance calculation");
if(curPi != logPi(curDist))
throw new Error("Inconsistency in likelihood calculation: "+logPi(curDist));
}
int type = Utils.generator.nextInt(3);
switch (type) {
case 0:
slideChar(); break;
case 1:
breakCol(); break;
default:
joinCol();
}
// save distance distribution info
Integer cnt = distCnts.get(curDist);
cnt = cnt == null ? 1 : cnt+1;
distCnts.put(curDist, cnt);
if(Utils.DEBUG) {
curAli.checkCons();
if(curDist != distCalc.dist(curAli))
throw new Error("Inconsistency in distance calculation");
if(curPi != logPi(curDist))
throw new Error("Inconsistency in likelihood calculation: "+logPi(curDist));
}
} | 9 |
@Override
public void setStructure(boolean[][] adjMatrix) throws RuntimeException {
if( adjMatrix.length != nodeIndexing.getNodesNumber() || adjMatrix[0].length != nodeIndexing.getNodesNumber())
throw new IllegalArgumentException("Error: the adjacency matrix must be an NxN matrix where N is the number of nodes in the general indexing");
for(int i = 0; i < this.nodeIndexing.getNodesNumber(); ++i) {
if( this.getNode(i) == null)
throw new RuntimeException("Error: not all the nodes defined in the general indexing are set");
this.getNode(i).removeAllParents();
}
for(int i = 0; i < adjMatrix.length; ++i) {
NodeType parentNode = this.getNode(i);
for(int j = 0; j < adjMatrix[0].length; ++j)
if( adjMatrix[i][j])
parentNode.addChild(this.getNode(j));
}
} | 7 |
@EventHandler
public void BlazeHarm(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.getBlazeConfig().getDouble("Blaze.Harm.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getBlazeConfig().getBoolean("Blaze.Harm.Enabled", true) && damager instanceof Blaze && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getBlazeConfig().getInt("Blaze.Harm.Time"), plugin.getBlazeConfig().getInt("Blaze.Harm.Power")));
}
} | 6 |
private void declaration_list(){
tokenActual = analizadorLexico.consumirToken();
if(tokenActual!=null){
if(tokenActual.obtenerLexema().equals("void") || tokenActual.obtenerLexema().equals("int") || tokenActual.obtenerLexema().equals("char")){
tokenActual = analizadorLexico.consumirToken();
if(tokenActual.obtenerToken().equals("identifier")){
analizadorLexico.retroceso();
analizadorLexico.retroceso();
declaration();
declaration_list();
}else if(tokenActual.obtenerLexema().equals("main")){
analizadorLexico.retroceso();
analizadorLexico.retroceso();
main_declaration();
}
}else if(tokenActual.obtenerLexema().equals(";")){
declaration();
declaration_list();
}else if(tokenActual.obtenerLexema().equals("}")){
declaration();
declaration_list();
}else{
error(4, tokenActual.obtenerLexema(),tokenActual.obtenerLinea());
}
}else{
analizadorLexico.retroceso();
}
} | 8 |
public void setCanvas(PersistentCanvas canvas) {
this.canvas = canvas;
} | 0 |
public static int maxPathSum(int[][] grid) {
int path[][] = new int[grid.length][grid[0].length];
int col, row;
row = grid.length;
col = grid[0].length;
path[0][0] = grid[0][0];
for (int i = 1; i < row; i++) {
path[i][0] = path[i-1][0] + grid[i][0];
}
for (int j = 1; j < col; j++) {
path[0][j] = path[0][j-1] + grid[0][j];
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
path[i][j] = path[i-1][j]>path[i][j-1]?path[i-1][j]+grid[i][j]:path[i][j-1]+grid[i][j];
}
}
return path[row-1][col-1];
} | 5 |
@Test
public void testValueOf() {
UserAgent userAgent = UserAgent.parseUserAgentString("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
UserAgent retrievedUserAgent = UserAgent.valueOf(userAgent.getId());
assertEquals(userAgent, retrievedUserAgent);
} | 0 |
public E pop() {
final E returnValue = (E) stack.get(stack.getSize()-1);
stack.delete(stack.getSize()-1);
return returnValue;
} | 0 |
public static SpriteID getAbilitySprite(AbilityType type) {
SpriteID sprite = null;
switch (type) {
case abil_tar_heal:
sprite = AbilitySprite.heal;
break;
case abil_aim_fire:
sprite = AbilitySprite.fire;
break;
case abil_dir_cleave:
sprite = AbilitySprite.cleave;
break;
case abil_inv_melee:
sprite = AbilitySprite.cleave;
break;
}
return sprite;
} | 4 |
public Vector splitAsciiTo(int split,String msg)
{
Vector blocks=new Vector();
String ascii=this.return_ascii(msg);
int i=0;
System.out.println();
while(true)
{
//System.out.println(i);
if(i+split<ascii.length())
blocks.addElement(ascii.substring((int)i,(int)(i+split)));
else
{
blocks.addElement(ascii.substring((int)i,ascii.length()));
break;
}
i+=split;
}
return blocks;
} | 2 |
@Override
public Object clone() {
Object clonedObject;
try {
clonedObject = super.clone();
TransactionRecord t = (TransactionRecord)clonedObject;
if (account != null)
account.addReference();
if (transferAccount != null)
transferAccount.addReference();
if (category != null)
category.addReference();
if (security != null)
security.addReference();
if (splits != null)
t.splits = TransactionSplit.copySplits(splits);
} catch (CloneNotSupportedException exc) {
throw new UnsupportedOperationException("Unable to clone transaction", exc);
}
return clonedObject;
} | 6 |
@Override
protected void parseInternal(Method method, Map<String, Integer> paramIndexes,
Map<String, Integer> batchParamIndexes) throws DaoGenerateException {
super.parseInternal(method, paramIndexes, batchParamIndexes);
// 解析Vkey的相关表达式级参数信息
if (StringUtils.isNotEmpty(vkey)) {// 对于单个缓存对象,可以允许不设置vkey
ExpressionParser parser = ParserFactory.createExpressionParser(ExpressionType.CACHE_KEY);
parsedVkey = parser.parse(vkey);
List<String> vkeyParameterNames = parsedVkey.getParameterNames();
Object[] vkeyGettersAndIndexes = getVkeyGettersAndIndexes(method, vkeyParameterNames, paramIndexes,
batchParamIndexes);
vkeyGetterMethods = (Method[]) vkeyGettersAndIndexes[0];
vkeyParameterIndexes = (Integer[]) vkeyGettersAndIndexes[1];
}
} | 1 |
public Main() {
setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/net/lotusdev/medusa/client/res/keyboard.png")));
setTitle("Medusa Logger (v" + getVersion() + ")");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 488, 317);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnMain = new JMenu("Client");
menuBar.add(mnMain);
JMenuItem mntmSettings = new JMenuItem("Settings");
mntmSettings.setIcon(new ImageIcon(Main.class.getResource("/net/lotusdev/medusa/client/res/cog.png")));
mnMain.add(mntmSettings);
JSeparator separator = new JSeparator();
mnMain.add(separator);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mntmExit.setIcon(new ImageIcon(Main.class.getResource("/net/lotusdev/medusa/client/res/door_open.png")));
mnMain.add(mntmExit);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(tabbedPane)
);
JPanel panel = new JPanel();
tabbedPane.addTab("Email Setup", new ImageIcon(Main.class.getResource("res/page_white_text.png")), panel, null);
JPanel panel_3 = new JPanel();
panel_3.setBorder(new TitledBorder(null, "Email Settings", TitledBorder.LEADING, TitledBorder.TOP, null, null));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(panel_3, GroupLayout.PREFERRED_SIZE, 306, Short.MAX_VALUE)
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
);
final JSpinner spinner_1 = new JSpinner();
JLabel lblTimeoutminutes = new JLabel("Timeout(minutes):");
final JSpinner spinner = new JSpinner();
JLabel lblSmtpPort = new JLabel("SMTP Port:");
JLabel lblSmtpHost = new JLabel("SMTP Host:");
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"smtp.gmail.com"}));
comboBox.setEditable(true);
passwordField = new JPasswordField();
JLabel lblPassword = new JLabel("Password:");
JLabel lblEmail = new JLabel("Email:");
textField = new JTextField();
textField.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Builder.setEmailUser(textField.getText());
Builder.setEmailPass(passwordField.getText());
Builder.setEmailHost(String.valueOf(comboBox.getSelectedItem()));
Builder.setEmailPort(String.valueOf(spinner.getValue()));
Builder.setTimeout((Integer)spinner_1.getValue());
Builder.writeConfig();
}
});
btnSave.setIcon(new ImageIcon(Main.class.getResource("/net/lotusdev/medusa/client/res/accept.png")));
GroupLayout gl_panel_3 = new GroupLayout(panel_3);
gl_panel_3.setHorizontalGroup(
gl_panel_3.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_3.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
.addComponent(btnSave, Alignment.TRAILING)
.addGroup(gl_panel_3.createSequentialGroup()
.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_3.createSequentialGroup()
.addComponent(lblSmtpPort, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addGap(10)
.addComponent(spinner, GroupLayout.PREFERRED_SIZE, 53, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
.addComponent(lblTimeoutminutes)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(spinner_1, GroupLayout.PREFERRED_SIZE, 53, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel_3.createSequentialGroup()
.addComponent(lblSmtpHost)
.addGap(10)
.addComponent(comboBox, 0, 209, Short.MAX_VALUE))
.addGroup(gl_panel_3.createSequentialGroup()
.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
.addComponent(lblPassword)
.addComponent(lblEmail))
.addGap(15)
.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
.addComponent(passwordField, GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
.addComponent(textField, GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE))))
.addContainerGap())))
);
gl_panel_3.setVerticalGroup(
gl_panel_3.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel_3.createSequentialGroup()
.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblEmail))
.addGap(6)
.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
.addComponent(lblPassword)
.addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_3.createSequentialGroup()
.addGap(9)
.addComponent(lblSmtpHost))
.addGroup(gl_panel_3.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_3.createSequentialGroup()
.addGap(3)
.addComponent(lblSmtpPort))
.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
.addComponent(spinner, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(spinner_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblTimeoutminutes)))
.addPreferredGap(ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addComponent(btnSave))
);
panel_3.setLayout(gl_panel_3);
panel.setLayout(gl_panel);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Build Stub", new ImageIcon(Main.class.getResource("res/application_edit.png")), panel_1, null);
JPanel panel_2 = new JPanel();
panel_2.setBorder(new TitledBorder(null, "Output", TitledBorder.LEADING, TitledBorder.TOP, null, null));
GroupLayout gl_panel_1 = new GroupLayout(panel_1);
gl_panel_1.setHorizontalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 306, Short.MAX_VALUE)
);
gl_panel_1.setVerticalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
);
JLabel lblLocation = new JLabel("Location:");
JLabel lblName = new JLabel("Name:");
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setColumns(10);
JButton button = new JButton("...");
JButton btnBuild = new JButton("Build");
btnBuild.setIcon(new ImageIcon(Main.class.getResource("/net/lotusdev/medusa/client/res/application_go.png")));
JButton btnFiles = new JButton("Files");
btnFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
EstimateClasses estClasses = new EstimateClasses();
estClasses.setVisible(true);
}
});
btnFiles.setIcon(new ImageIcon(Main.class.getResource("/net/lotusdev/medusa/client/res/page_white_stack.png")));
GroupLayout gl_panel_2 = new GroupLayout(panel_2);
gl_panel_2.setHorizontalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
.addComponent(lblName)
.addComponent(lblLocation))
.addGap(21)
.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addComponent(textField_3, GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button))
.addComponent(textField_2, GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE))
.addContainerGap())
.addGroup(Alignment.TRAILING, gl_panel_2.createSequentialGroup()
.addComponent(btnFiles)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnBuild))))
);
gl_panel_2.setVerticalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGap(3)
.addComponent(lblName)
.addGap(9)
.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
.addComponent(lblLocation)
.addComponent(textField_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(button)))
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 112, Short.MAX_VALUE)
.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
.addComponent(btnBuild)
.addComponent(btnFiles)))
);
panel_2.setLayout(gl_panel_2);
panel_1.setLayout(gl_panel_1);
contentPane.setLayout(gl_contentPane);
/**
* Set text of fields after being read drom config file.
*/
textField.setText(Builder.getEmailUser());
passwordField.setText(Builder.getEmailPass());
comboBox.setSelectedItem(String.valueOf(Builder.getEmailHost()));
//spinner.setValue(Integer.parseInt(Builder.getEmailPort()));
spinner_1.setValue((Integer)Builder.getTimeout());
JPanel panel_4 = new JPanel();
tabbedPane.addTab("Stub Settings", null, panel_4, null);
JScrollPane scrollPane = new JScrollPane();
final JPanel panel_5 = new JPanel(new CardLayout());
panel_5.setBorder(new TitledBorder(null, curTitle, TitledBorder.LEADING, TitledBorder.TOP, null, null));
GroupLayout gl_panel_4 = new GroupLayout(panel_4);
gl_panel_4.setHorizontalGroup(
gl_panel_4.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_4.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 136, GroupLayout.PREFERRED_SIZE)
.addGap(2)
.addComponent(panel_5, GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE))
);
gl_panel_4.setVerticalGroup(
gl_panel_4.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_4.createParallelGroup(Alignment.BASELINE)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 218, GroupLayout.PREFERRED_SIZE)
.addComponent(panel_5, GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE))
);
CustomTreeCellNodes.makeTreeIcons();
tree = new JTree();
tree.setShowsRootHandles(false);
tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Settings")));
for (int i = 0; i < CustomTreeCellNodes.getTreeIcons().size(); i++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)getTreeModel().getRoot();
node.add(new DefaultMutableTreeNode(CustomTreeCellNodes.getTreeIcons().get(i)));
}
expand();
final PanelEmail p_email = new PanelEmail();
final PanelTimeout p_timeout = new PanelTimeout();
tree.setCellRenderer(new CustomTreeCellRenderer());
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent arg0) {
try {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)arg0.getNewLeadSelectionPath().getLastPathComponent();
if (node != null) {
curTitle = node.toString();
panel_5.setBorder(new TitledBorder(null, curTitle, TitledBorder.LEADING, TitledBorder.TOP, null, null));
if(node.toString().equals("Email")) {
panel_5.add(p_email);
panel_5.remove(p_timeout);
}else if(node.toString().equals("Timeout")) {
panel_5.add(p_timeout);
panel_5.remove(p_email);
}
System.out.println(node.toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
scrollPane.setViewportView(tree);
panel_4.setLayout(gl_panel_4);
} | 5 |
@Override
public void writeToData(DataOut dataOut) throws IOException {
dataOut.writeInt(classes.size());
for(Class c : classes) {
dataOut.writeUTF(c.getName());
}
} | 1 |
@Override
public boolean parseField(String name, String value){
if (super.parseField(name, value)){
return true;
}
if (name != null && value != null){
PeripheralFieldHandler handler = EnumUtils.lookup(PeripheralFieldHandler.class, name);
if (handler != null){
return handler.handle(device, value);
} else{
return false;
}
}
return false;
} | 4 |
public K getMin(){
K minKey = null;
Double minValue = Double.valueOf(Double.MAX_VALUE);
for (Map.Entry<K, Double> entry : map.entrySet()){
//if this value is less than the minValue found so far
if (entry.getValue().compareTo(minValue)<0){
minValue = entry.getValue();
minKey = entry.getKey();
}
}
return minKey;
} | 2 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TracksInPlaylistsEntityPK that = (TracksInPlaylistsEntityPK) o;
if (playlistId != that.playlistId) return false;
if (trackId != that.trackId) return false;
return true;
} | 5 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Device)) return false;
Device device = (Device) o;
if (id != device.id) return false;
if (name != null ? !name.equals(device.name) : device.name != null) return false;
if (owner != null ? !owner.equals(device.owner) : device.owner != null) return false;
return true;
} | 7 |
public void repaint(Graphics g, int x, int y) {
painted.set(true);
Graphics2D g2d = (Graphics2D) g;
Composite previousComposite = g2d.getComposite();
int i = 0;
long timeBetween = System.currentTimeMillis() - lastLoop;
final Iterator<LogEntry> iterator = logEntries.iterator();
while (iterator.hasNext()) {
final LogEntry logEntry = iterator.next();
if (logEntry.alpha <= 0.0f) {
iterator.remove();
continue;
}
y += 15;
g.setColor(Color.BLACK);
g2d.setComposite(AlphaComposite.SrcOver.derive(logEntry.alpha));
String message = df.format(logEntry.timeSent) + " | " + logEntry.text;
g.drawString(message, x + 1, y + 1);
g.setColor(logEntry.color);
g.drawString(message, x, y);
if (i > capacity - 1 || System.currentTimeMillis() - logEntry.timeSent > MAX_LIFETIME) {
logEntry.alpha -= timeBetween * 0.0005;
}
i++;
}
g2d.setComposite(previousComposite);
lastLoop = System.currentTimeMillis();
} | 4 |
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Registration().setVisible(true);
}
});
} | 6 |
public void saveModel() {
try {
if (m_fileChooser == null) {
// i.e. after de-serialization
m_fileChooser =
new JFileChooser(new File(System.getProperty("user.dir")));
ExtensionFileFilter ef = new ExtensionFileFilter("model", "Serialized weka clusterer");
m_fileChooser.setFileFilter(ef);
}
int returnVal = m_fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File saveTo = m_fileChooser.getSelectedFile();
String fn = saveTo.getAbsolutePath();
if (!fn.endsWith(".model")) {
fn += ".model";
saveTo = new File(fn);
}
ObjectOutputStream os =
new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(saveTo)));
os.writeObject(m_Clusterer);
if (m_trainingSet != null) {
Instances header = new Instances(m_trainingSet, 0);
os.writeObject(header);
}
os.close();
if (m_log != null) {
m_log.logMessage("[Clusterer] Saved clusterer " + getCustomName());
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Clusterer.this,
"Problem saving clusterer.\n",
"Save Model",
JOptionPane.ERROR_MESSAGE);
if (m_log != null) {
m_log.logMessage("[Clusterer] Problem saving clusterer. "
+ getCustomName() + ex.getMessage());
}
}
} | 7 |
public void workWeek() {
for (int i=0; i<5; i++)
{
this.makeShake();
}
this.earnPaycheck();
this.setEffMult(1);
} | 1 |
public void increaseRope(int x , int y) {
if (ropelength < 125){
ropelength ++;
}
x += 1;
y += 2;
switch (ropelength) {
case 1: getWorld().addObject(rope, x, y); getWorld().addObject(ropeman, x, y+3); break;
case 25: y+= 2; getWorld().addObject(rope2, x, y); ropeman.setLocation(x, y+3); break;
case 50: y+= 4; getWorld().addObject(rope3, x, y); ropeman.setLocation(x, y+3); break;
case 75: y+= 6; getWorld().addObject(rope4, x, y); ropeman.setLocation(x, y+3); break;
case 100: y+= 8; getWorld().addObject(rope5, x, y); ropeman.setLocation(x, y+3); break;
case 125: y+= 10; getWorld().addObject(rope6, x, y); ropeman.setLocation(x, y+3); break;
}
} | 7 |
public Vector getInfo()
{
return v;
} | 0 |
public String[] getUserNames() {
ArrayList < Client > tclients = new ArrayList < Client > ();
tclients.addAll(clients);
for (int i = 0; i < channels.size(); i++) {
ArrayList < Client > clients = channels.get(i).getUsers();
for (Client c: clients) {
if (!(tclients.contains(c))) {
tclients.add(c);
}
}
}
String[] returnme = new String[tclients.size()];
for(int i = 0 ; i < tclients.size(); i ++){
returnme[i] = tclients.get(i).getName();
}
return returnme;
} | 4 |
private boolean editTypeWorkFrame(){
boolean ret = false;
String name;
int id;
if (jTableTypeWork.getSelectedRow() == -1 ){
// значит ничего не выбрали
SMS.message(this, "Вы ничего не выбрали для редактирования!");
return ret;
}
name = (String) jTableTypeWork.getValueAt(jTableTypeWork.getSelectedRow(), 1);
id = (int) jTableTypeWork.getValueAt(jTableTypeWork.getSelectedRow(), 0);
TypeWork type = new TypeWork(id, name);
JTextField text = new JTextField();
JComponent[] components = new JComponent[]{
new JLabel("Введите название типа работы"),
text
};
do {
text.setText(name);
boolean result = SMS.dialog(this, "Измените данные о типе работы", components);
if(result){
if(text.getText().trim().length() > 0){
try {
TypeWork newType = new TypeWork();
newType.setNameTypeWork(text.getText());
int code = type.updateTable(newType);
if(code == -1){
result = SMS.query(this, "Такое значение уже есть\nХотите еще раз ввести данные?");
if(result){
// запускаем занового цикл
continue;
} else {
// значит выходим из цикла
break;
}
} else if( code >= 0 ){
// все прошло успешно
ret = true;
break;
}
} catch (SQLException ex) {
SMS.error(this, ex.toString());
Logger.getLogger(TypeWorkInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
break;
}
} else {
SMS.message(this, "Вы ничего не ввели");
}
} else {
// Пользователь отменил выбор
break;
}
} while (true);
return ret;
} | 8 |
public boolean validMove(String world, int x, int y, int moveTileType, int currentTileType, int orgUID){
if ((lookup.invalidMoveCost != moveCost(moveTileType, orgUID)) && // If he has enough energy to move off current tile
(org.getEnergy(orgUID)>=moveCost(currentTileType, orgUID)) && // and the moveCost of the next tile is not the invalidCode.
(-1 == communicate.selectUIDByXAndYAndWorld(lookup.movementTableName, x, y, world)) &&// and there is no org at the location.
(!combat.isFighting(orgUID) && // and he isn't fighting. You can't move when you're fighting.
(!org.isLame(orgUID)))){ // and he isn't lame from leg HP ==0.
return true;
}
return false;
} | 5 |
public static IPv6Network getByAddress(String address, int mask) throws NetworkException {
if ((mask < 0) || (mask > 128)) {
throw new InvalidAddressException(String.format("'%d' is not a valid IPv6 mask.", mask));
}
try {
return new IPv6Network(new BigInteger(Inet6Address.getByName(address).getAddress()), BigInteger.valueOf(mask));
} catch (UnknownHostException ex) {
throw new InvalidAddressException(String.format("%s is not a valid address", address));
}
} | 3 |
public List<String> purge() {
Iterator<TaskItem<R,C>> items = iterator();
List<String> results = new ArrayList<String>();
while(items.hasNext()) {
TaskItem<R,C> item = items.next();
// Leave completed tasks for results reporting:
if(!item.future.isDone()) {
results.add("Cancelling " + item.task);
item.future.cancel(true); // May interrupt
items.remove();
}
}
return results;
} | 2 |
public static String encrypt(String input, String key){
int inputLength = input.length();
char[] out = new char[inputLength];
int code = key.hashCode();
Character[] mapping = randomizeArray(getMasterMapping(), code);
for(int i = 0; i < inputLength; i++){
char x = input.charAt(i);
if(x < 32 && x != 9 && x != 10 || x > 255 || x > 126 && x < 160){
throw new IllegalArgumentException("Illegal Input Character " + (int)x);
}
int y = convert(x);
char z = mapping[y];
out[i] = z;
}
return new String(out);
} | 7 |
public TreeLinkNode connectNextLine(TreeLinkNode first) {
TreeLinkNode nextPreHead = new TreeLinkNode(0);
TreeLinkNode next = nextPreHead;
while (first != null) {
if (first.left != null) {
next.next = first.left;
next = next.next;
}
if (first.right != null) {
next.next = first.right;
next = next.next;
}
first = first.next;
}
next.next = null;
return nextPreHead.next;
} | 3 |
private void doDecode() {
File file = null;
showMessage("uncompressing");
try {
int retval = ourChooser.showOpenDialog(null);
if (retval != JFileChooser.APPROVE_OPTION) {
return;
}
file = ourChooser.getSelectedFile();
String name = file.getName();
String uname = name;
if (name.endsWith(HUFF_SUFFIX)) {
uname = name.substring(0,name.length() - HUFF_SUFFIX.length()) + UNHUFF_SUFFIX;
}
else {
uname = name + UNHUFF_SUFFIX;
}
String newName = JOptionPane.showInputDialog(this,
"Name of uncompressed file", uname);
if (newName == null) {
return;
}
String path = file.getCanonicalPath();
int pos = path.lastIndexOf(name);
newName = path.substring(0, pos) + newName;
final File newFile = new File(newName);
ProgressMonitorInputStream temp = null;
if (myFast){
temp = getMonitorableStream(getFastByteReader(file),"uncompressing bits ...");
}
else {
temp = getMonitorableStream(file, "uncompressing bits...");
}
final ProgressMonitorInputStream stream = temp;
final ProgressMonitor progress = stream.getProgressMonitor();
final OutputStream out = new FileOutputStream(newFile);
Thread fileReaderThread = new Thread() {
public void run() {
try {
myModel.uncompress(stream, out);
} catch (IOException e) {
cleanUp(newFile);
HuffViewer.this.showError("could not uncompress\n "+e);
//e.printStackTrace();
}
if (progress.isCanceled()) {
cleanUp(newFile);
HuffViewer.this.showError("reading cancelled");
}
}
};
fileReaderThread.start();
} catch (FileNotFoundException e) {
showError("could not open " + file.getName());
e.printStackTrace();
} catch (IOException e) {
showError("IOException, uncompression halted from viewer");
e.printStackTrace();
}
} | 8 |
public CommunicationProtocol(InetAddress inetAddress, int port, UserManagement userManagement, String analyticsServerRef, String billingServerRef, Registry registry) {
this.inetAddress = inetAddress;
this.tcpPort = port;
this.userManagement = userManagement;
this.analyticsServerRef = analyticsServerRef;
this.billingServerRef = billingServerRef;
this.registry = registry;
try {
mClientHandler = (MClientHandler_RO) registry.lookup(analyticsServerRef);
} catch (AccessException e1) {
logger.error("Access to the registry denied");
} catch (RemoteException e1) {
logger.error("Failed to connect to the Analytics Server");
} catch (NotBoundException e1) {
logger.error("Analytics Server not bound to the registry");
}
try {
billingServerHandler = (BillingServer_RO) registry.lookup(billingServerRef);
this.billingServerLogin();
} catch (AccessException e1) {
logger.error("Access to the registry denied");
} catch (RemoteException e1) {
System.out.println("Failed to connect to the Billing Server");
} catch (NotBoundException e1) {
logger.error("Billing Server not bound. Ref:" + billingServerRef);
}
} | 6 |
protected Class loadClassByDelegation(String name)
throws ClassNotFoundException
{
/* The swing components must be loaded by a system
* class loader.
* javax.swing.UIManager loads a (concrete) subclass
* of LookAndFeel by a system class loader and cast
* an instance of the class to LookAndFeel for
* (maybe) a security reason. To avoid failure of
* type conversion, LookAndFeel must not be loaded
* by this class loader.
*/
Class c = null;
if (doDelegation)
if (name.startsWith("java.")
|| name.startsWith("javax.")
|| name.startsWith("sun.")
|| name.startsWith("com.sun.")
|| name.startsWith("org.w3c.")
|| name.startsWith("org.xml.")
|| notDelegated(name))
c = delegateToParent(name);
return c;
} | 8 |
public PogNode chooseNeighborWeighted(TreeQualifier qualifier, Random generator, double beta) {
Node editedNode = null;
boolean isAdded = false;
if (addableList.isEmpty() && removableList.isEmpty()) { // this is a null node; choose a node to add from the whole dataset
isAdded = true;
Set<Node> entireNodeList = qualifier.entireNodeList();
int chosenIndex = generator.nextInt(entireNodeList.size());
int i = 0;
for (Node n : entireNodeList) {
if (i++ == chosenIndex) {
editedNode = n;
break;
}
}
} else { // pick from the candidate set
// decide whether add or remove
if (generator.nextDouble() > beta && !addableList.isEmpty()) { // add a vertex to the subgraph
int chosenIndex = randomIndex(generator, addWeight);
isAdded = true;
editedNode = candidateArrayAdd[chosenIndex];
} else { // remove a vertex from the subgraph
int chosenIndex = randomIndex(generator, removeWeight);
editedNode = candidateArrayRemove[chosenIndex];
}
}
// create a node with the new infomation
PogNode q = null;
if (isAdded) {
q = recalcInfoAdded(editedNode, qualifier);
} else {
q = recalcInfoRemoved(editedNode, qualifier);
}
if (q != null) {
candidateEditedNode = editedNode;
}
return q;
} | 8 |
public static void insertSort2(int[] array, int index) {
System.out.println("index == " + index);
if (index > 1) {
insertSort2(array, index - 1);
}
int i = index - 1;
int key = array[index];
while (i >= 0 && array[i] > key) {
array[i + 1] = array[i];
i--;
}
if (i != index - 1) {
array[i + 1] = key;
}
} | 4 |
private String extrahiereRichtung(Befehlszeile befehlszeile)
{
// Ist der Befehl ein Shortcut?
// o,n,s,w
String richtung = translateShortcut(befehlszeile.getZeile());
if(richtung != null)
return richtung;
// Ist der Befehl eine lange Richtung ?
// gehe …
if(befehlszeile.beginntMit(TextVerwalter.BEFEHL_GEHEN)
&& befehlszeile.getGeparsteZeile().size() == 2)
{
richtung = befehlszeile.getGeparsteZeile().get(1);
// lange Richtung?
// gehe osten, …
if(isKorrekteRichtung(richtung))
{
return richtung;
}
// vllt. Shortcut?
//gehe o, …
richtung = translateShortcut(richtung);
if(richtung != null)
return richtung;
}
return null;
} | 5 |
private void calculateNext() {
addPoints(next_point, point_vector, next_point);
if (!isPointLegal(next_point)) {
addPoints(starting_point, starting_point_vector, starting_point);
clonePoints(starting_point, next_point);
}
} | 1 |
public static Configuration getConfiguration() {
return configuration;
} | 0 |
public String done ()
// count territory and return result string
// notifies BoardInterface
{
if (Pos.haschildren()) return null;
clearmarks();
getinformation();
int i, j;
int tb = 0, tw = 0, sb = 0, sw = 0;
P.getterritory();
for (i = 0; i < S; i++)
for (j = 0; j < S; j++)
{
if (P.territory(i, j) == 1 || P.territory(i, j) == -1)
{
markterritory(i, j, P.territory(i, j));
if (P.territory(i, j) > 0)
tb++;
else tw++;
}
else
{
if (P.color(i, j) > 0)
sb++;
else if (P.color(i, j) < 0) sw++;
}
}
String s = GF.resourceString("Chinese_count_") + "\n"
+ GF.resourceString("Black__") + (sb + tb)
+ GF.resourceString("__White__") + (sw + tw) + "\n"
+ GF.resourceString("Japanese_count_") + "\n"
+ GF.resourceString("Black__") + (Pw + tb)
+ GF.resourceString("__White__") + (Pb + tw);
showinformation();
copy();
if (Pos.node().main())
{
GF.result(tb, tw);
}
return s;
} | 9 |
public WindowMenuItem(String text, OutlinerDocument doc) {
super(text);
this.doc = doc;
group.add(this);
} | 0 |
@Test
public void resolve() {
int n = 2000000;
long sum = 0;
Primes.isPrime(n);
for (int p : Primes.primes) {
if (p < n) {
sum += p;
}
}
print(sum);
} | 2 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(sprung)
return super.okMessage(myHost,msg);
if(!super.okMessage(myHost,msg))
return false;
if((msg.amITarget(affected))
&&(!msg.amISource(invoker())))
{
if((msg.targetMinor()==CMMsg.TYP_ENTER)
||(msg.targetMinor()==CMMsg.TYP_LEAVE)
||(msg.targetMinor()==CMMsg.TYP_FLEE))
{
if(msg.targetMinor()==CMMsg.TYP_LEAVE)
return true;
spring(msg.source());
if(sprung)
return false;
}
}
return super.okMessage(myHost,msg);
} | 9 |
@Override
public String toString(){
Date d = new Date();
d.setTime(gameActiveMs);
String res = "";
res += "Game: " + gameName + "\n";
res += "Id: " + matchId + "\n";
res += "Mode: " + gameMode + "\n";
res += "Active: " + d.toString() + "\n";
d.setTime(gameStartMs);
res += "Start: " + d.toString() + "\n";
d.setTime(gameEndMs);
res += "End: " + d.toString() + "\n";
res += "Length: " + gameLength + "\n";
res += "dotaVersion: " + dotaVersion + "\n";
res += "Points: Sentinel: " + seScore + " Scourge: " + scScore + "\n";
res += "KD: Sentinel: " + seKill + " / " + seDeath + " Scourge: " + scKill + " / " + scDeath + "\n";
res += "winner: ";
switch(winner)
{
case 0:
res += "draw\n";
break;
case 1:
res += "sentinel\n";
break;
case -1:
res += "scourge\n";
break;
case -2:
res += "game aborted\n";
break;
case -3:
res += "no winner information\n";
break;
default:
res += "invalid winner value\n";
break;
}
res += "Sentinel\n";
for(int s : sentinel)
{
res += " " + s + "\n";
}
res += "Scourge\n";
for(int s : scourge)
{
res += " " + s + "\n";
}
res += "Number of players " + playerIds.size();
return res;
} | 7 |
private IDAReturnValue EIDAStar(State state, long stateId, int gScore, int threshold,
Cost cost, ArrayList<Action> solution) {
// Probes the transposition table.
if (transTable.containsKey(stateId)) {
TransEntry entry = transTable.get(stateId);
if (gScore > entry.gScore) {
return new IDAReturnValue(false, Integer.MAX_VALUE);
}
if (gScore == entry.gScore && threshold == entry.threshold) {
return new IDAReturnValue(false, Integer.MAX_VALUE);
}
}
TransEntry entry = new TransEntry(gScore, threshold);
transTable.put(stateId, entry);
// Applies the state.
state.setState(stateId);
// Is it a goal state?
if (state.isGoal()) {
return new IDAReturnValue(true, gScore);
}
// Generates successors.
ArrayList<Action> actions = new ArrayList<Action>();
state.getActions(actions);
nodesExpanded++;
int nextThreshold = Integer.MAX_VALUE;
for (Action action : actions) {
// g(x)
int distToNeighbour = state.getCost(action);
state.make(action);
int neighbourGScore = gScore + distToNeighbour;
long neighbourStateId = state.getStateID();
// h(x): Probes the transposition table for a H-score, if not found: Calculate it.
int neighbourHScore;
if (transTable.containsKey(neighbourStateId)) {
TransEntry neighbourEntry = transTable.get(neighbourStateId);
neighbourHScore = neighbourEntry.hScore;
} else {
neighbourHScore = heuristic.estimateCost(state); // state.getHeuristic(); // heuristic1.getHeuristic(state);
}
// f(x)
int neighbourFScore = neighbourGScore + neighbourHScore;
if (neighbourFScore <= threshold) {
// Calls the search function recursively.
IDAReturnValue ret = EIDAStar(
state, neighbourStateId, neighbourGScore, threshold, cost, solution);
if (ret.solved) {
solution.add(action);
cost.value += distToNeighbour;
return ret;
} else {
nextThreshold = Math.min(nextThreshold, ret.nextThreshold);
}
} else {
nextThreshold = Math.min(nextThreshold, neighbourFScore);
}
state.retract(action);
}
// Set the h(x) for this node in the transposition table.
entry.hScore = nextThreshold - gScore;
return new IDAReturnValue(false, nextThreshold);
} | 9 |
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VacationEntry other = (VacationEntry) obj;
if (days != other.days)
return false;
if (startDate == null)
{
if (other.startDate != null)
return false;
} else if (!startDate.equals(other.startDate))
return false;
return true;
} | 7 |
private static void sortBlock(File[] files, int start, int end, File[] mergeTemp) {
final int length = end - start + 1;
if (length < 8) {
for (int i = end; i > start; --i) {
for (int j = end; j > start; --j) {
if (compareFiles(files[j - 1], files[j]) > 0) {
final File temp = files[j];
files[j] = files[j-1];
files[j-1] = temp;
}
}
}
return;
}
final int mid = (start + end) / 2;
sortBlock(files, start, mid, mergeTemp);
sortBlock(files, mid + 1, end, mergeTemp);
int x = start;
int y = mid + 1;
for (int i = 0; i < length; ++i) {
if ((x > mid) || ((y <= end) && compareFiles(files[x], files[y]) > 0)) {
mergeTemp[i] = files[y++];
} else {
mergeTemp[i] = files[x++];
}
}
for (int i = 0; i < length; ++i) files[i + start] = mergeTemp[i];
} | 9 |
private void travelTree(TreeNode node, List<Integer> result) {
TreeNode left = node.left;
TreeNode right = node.right;
//travel left
if(null != left) travelTree(left, result);
//record
result.add(node.val);
//travel right
if(null != right) travelTree(right, result);
} | 2 |
public static int solution(final String s) {
// If it's empty then it's nested properly.
if (s.length() == 0) {
return 1;
}
// If not even then it can't be nested properly.
if (s.length() % 2 != 0) {
return 0;
}
char c;
Stack<Character> parentheses = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
parentheses.add(c);
} else { // Closing bracket
if (parentheses.empty() || !match(c, parentheses.pop())) {
return 0;
}
}
}
if (parentheses.empty()) {
return 1;
} else {
return 0;
}
} | 9 |
public StreetConfig(SSGlobals glob) throws FileNotFoundException
{
fGlobals = glob;
fStreets = new HashMap<String, StreetTemplate>();
try
{
parse();
}
catch (ParserConfigurationException e)
{
throw new FileNotFoundException("Die Strassen-Konfigurationsdatei konnte nicht gefunden werden");
}
catch (IOException e)
{
throw new FileNotFoundException("Die Strassen-Konfigurationsdatei konnte nicht gefunden werden");
}
catch (SAXException e)
{
throw new FileNotFoundException("Die Strassen-Konfigurationsdatei konnte nicht gefunden werden");
}
catch (JAXBException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} | 4 |
private static boolean isAssertionField(Exprent exprent, String classname, String key, boolean throwInIf) {
if (throwInIf) {
if (exprent.type == Exprent.EXPRENT_FUNCTION) {
FunctionExprent fparam = (FunctionExprent)exprent;
if (fparam.getFuncType() == FunctionExprent.FUNCTION_BOOL_NOT &&
fparam.getLstOperands().get(0).type == Exprent.EXPRENT_FIELD) {
FieldExprent fdparam = (FieldExprent)fparam.getLstOperands().get(0);
if (classname.equals(fdparam.getClassname())
&& key.equals(InterpreterUtil.makeUniqueKey(fdparam.getName(), fdparam.getDescriptor().descriptorString))) {
return true;
}
}
}
return false;
}
else {
if (exprent.type == Exprent.EXPRENT_FIELD) {
FieldExprent fdparam = (FieldExprent) exprent;
if (classname.equals(fdparam.getClassname())
&& key.equals(InterpreterUtil.makeUniqueKey(fdparam.getName(), fdparam.getDescriptor().descriptorString))) {
return true;
}
}
return false;
}
} | 9 |
public int getSellerType() {
return sellerType;
} | 0 |
public Cli()
{
console = new OSConsole("Batch Sequencer");
console.setCommandListener(this);
console.login();
} | 0 |
public static Integer getGirlToBoyRashiDistance(Rashi boyRashi, Rashi girlRashi) {
int boyNumber = boyRashi.ordinal() + 1;
int girlNumber = girlRashi.ordinal() + 1;
int distance = 0;
if (boyNumber > girlNumber) {
distance = boyNumber - (girlNumber - 1);
}
if (boyNumber < girlNumber) {
distance = (boyNumber + 13) - girlNumber;
}
if (boyNumber == girlNumber) {
distance = 1;
}
return distance;
} | 3 |
private int no_Between (ABObject o1, ABObject o2)
{
double minX = o1.getMaxX();
double maxX = o2.getMinX();
int no = 0;
for (int i = 0; i < shelters.size(); i++)
{
ABObject o = shelters.get(i);
double _minX = o.getMinX();
double _maxX = o.getMaxX();
if (_minX <= maxX && _minX >= minX && _maxX <= maxX && _maxX >= minX)
no++;
}
return no;
} | 5 |
private void start() throws FileNotFoundException, IOException, InterruptedException, ExecutionException {
BufferedReader brWatson = new BufferedReader(new FileReader(new File(this.inputWatson)));
String bufferedHeader = brWatson.readLine().substring(1);
for (int i = 0;;) {
List<SequenceEntry> list = new LinkedList<>();
try {
for (int j = 0; j < Globals.STEPS; j++) {
i++;
SequenceEntry seqEntry = parseFastaEntry(brWatson);
String tmp = seqEntry.header;
seqEntry.header = bufferedHeader;
bufferedHeader = tmp;
String parseFastaEntry = seqEntry.sequence;
if (parseFastaEntry.length() > 2 * Globals.CUT) {
parseFastaEntry = parseFastaEntry.substring(Globals.CUT, parseFastaEntry.length() - Globals.CUT);
seqEntry.sequence = parseFastaEntry;
if (seqEntry.sequence.length() >= Globals.MIN_LENGTH) {
list.add(seqEntry);
// list.addAll(Utils.splitRead(watsonS));
} else {
StatusUpdate.processLength();
}
} else {
StatusUpdate.processLength();
}
if (i % 10000 == 0) {
this.processResults();
}
}
synchronized (results) {
results.add(executor.submit(new FutureSequence(list)));
}
} catch (IllegalAccessError e) {
if (!list.isEmpty()) {
synchronized (results) {
results.add(executor.submit(new FutureSequence(list)));
}
}
// used to halt in case of EOF
break;
}
}
this.processResults();
this.saveConsensus();
executor.shutdown();
this.processResults();
this.resultsExecutor.shutdown();
} | 7 |
public static void main(String[] args) {
int i, n;
double x, y;
System.out.println("Derivada numerica con Polinomio de Lagrange "
+ "CON 2 o 3 PUNTOS CONOCIDOS");
do {
do {
System.out.println("Escriba el numero de puntos conocidos");
n = MyReadingMethods.readInt();
} while (n == 999999999);
} while (n > 3 || n < 1);
double a[][] = new double[n][2];
System.out.println("Vacíe su información");
for (i = 0; i < n; i++) {
do {
System.out.print("x" + i + " = ");
a[i][0] = MyReadingMethods.readDouble();
} while (a[i][0] == 999999.99);
do {
System.out.print("f(" + a[i][0] + ") = ");
a[i][1] = MyReadingMethods.readDouble();
} while (a[i][0] == 999999.99);
}
//Imprimir tabla con puntos conocidos
// for (i = 0; i < n; i++) {
// for (int j = 0; j < 2; j++) {
// System.out.printf("%.4f ", a[i][j]);
// }
// System.out.println("");
// }
do {
System.out.print("Punto en el que se desea evaluar la derivada: ");
x = MyReadingMethods.readDouble();
} while (x == 999999.99);
//segun puntos conocidos 2 ó 3 puntos conocidos solamente según mis notas
switch (n) {
case 2:
//L0'(x)f(x0)+L1'(x)f(x1) ; L0'(x) = 1/(x0-x1) ; L1'(x) = 1/(x1-x0)
y = (a[0][1] * (1 / (a[0][0] - a[1][0]))) + (a[1][1] * (1 / (a[1][0] - a[0][0])));
System.out.println("f'( " + x + ") = " + y);
break;
case 3:
//f(x0)L0'(x)+f(x1)L1'(x)+f(x2)L2'(x); L0'(x) = (2x-x2-x1)/(x0-x1)(x0-x2)
// L1'(x) = (2x-x0-x2)/(x1-x0)(x1-x2) ; L2'(x) = (2x-x0-x1)/(x2-x0)(x2-x1)
y = (a[0][1] * ((2 * x) - a[2][0] - a[1][0])) / ((a[0][0] - a[1][0]) * (a[0][0] - a[2][0]))
+ (a[1][1] * ((2 * x) - a[0][0] - a[2][0])) / ((a[1][0] - a[0][0]) * (a[1][0] - a[2][0]))
+ (a[2][1] * ((2 * x) - a[0][0] - a[1][0])) / ((a[2][0] - a[0][0]) * (a[2][0] - a[1][0]));
System.out.println("f'( " + x + ") = " + y);
break;
}
} | 9 |
public void setStatus(Boolean newStatus) throws IOException {
if (status==newStatus) return;
System.out.println("Switching "+channel+" to: "+(newStatus?"ON":"OFF"));
switch (channel) {
case 'A' : switch_a(newStatus); break;
case 'B' : switch_b(newStatus); break;
}
status=newStatus;
} | 4 |
private void deleteCase4(RBTreeNode<K,V> node) {
//If sibling's tree has longer black paths
if(nodeColor(node.parent) == Color.RED &&
nodeColor(node.sibling()) == Color.BLACK &&
nodeColor(node.sibling().left) == Color.BLACK &&
nodeColor(node.sibling().right) == Color.BLACK) {
//Color sibling red
node.sibling().color = Color.RED;
//And parent black
node.parent.color = Color.BLACK;
//This should make the black paths property true again
} else {
deleteCase5(node);
}
} | 4 |
static void SPCMacro (RG2ROM program, String destination)
throws IllegalArgumentException
{
int length = program.command.length; //May or may not fit in the available 60 lines of space.
final int x_base = 127;
final int y_base = 98; //97.5 teleports into the ground below the torches.
final int z_base = -21;
int X;
int Y;
int Z;
int updatesDone = 0; //Tracks number of changes made by the macro. The user must undo
//This many things to have the effect of removing the program.
char bin;
String unlit_torch = "121.5 58 73.5"; //57.5 drops you into the ground, below the torch.
String newLine = Settings.newLine; //Write doesn't include a newline. So these
//Are placed manually to separate commands.
try
{
FileWriter macro = new FileWriter (destination + ".txt");
// /t [X] [Y] [Z]
macro.write ("/output" + newLine); //Should be turning output off.
macro.write("/t " + x_base + ".5 " + y_base +" "+ z_base + ".5" + newLine);
macro.write("//pos1" + newLine);
macro.write("/t " + (x_base + 118) + ".5 " + y_base + ".5 " + (z_base + 65) + ".5 " + newLine);
macro.write("//pos2" + newLine);
macro.write("//replace 75 0" + newLine); //Turn all 1-bits (torches) to 0-bits (air)
macro.write("//replace 76 0" + newLine); //75 and 76 are redstone torches.
//Select a torch:
macro.write("/t " + unlit_torch + newLine); //On light; Should be unlit (computer off) when program is installed).
macro.write("//pos1" + newLine);
macro.write("//pos2" + newLine);
macro.write("//copy" + newLine);
Y = y_base; //Elevation never changes.
for (int command = 0; command < length; command++) //Iterate through commands.
{
X = x_base + (command*2); //Current X coordinate to write to.
for (byte bit = 0; bit < 33; bit++) //Iterate through bits.
{
Z = z_base + (bit*2); //Z coordinate of command[bit]
bin = program.command[command].getBit(bit);
if (bin == '1') //Only paste torches for 1's, 0's stay air.
{
updatesDone++; //One more paste that must be undone to remove the program.
macro.write("/t " + X + ".5 " + Y + ".5 " + Z + ".5" + newLine); //Teleport to X Y Z
macro.write("//paste" + newLine); //Paste unlit torch.
}
else if (bin != '0') //0 is only other valid binary value.
{
macro.write("/msg Error! Invalid program!");
macro.close(); //Close file before exiting.
throw new IllegalArgumentException (bin + " is non-binary. Cannot export.");
}
}
}
macro.write("/output" + newLine); //Re-establish output, for the following messages.
macro.write ("/msg Please only install programs when the computer is off." + newLine);
macro.write ("/msg RedGame program installed successfully." + newLine);
macro.write ("/msg To remove, undo " + updatesDone + " changes.");
macro.flush ();
macro.close ();
}
catch (IOException e)
{
ErrorLog.addError (e.getMessage() + " When saving macro file.");
}
} | 5 |
public void movimiento() {
int mov = (int) (Math.random() * (4 - 1 + 1) + 1);
// 1 es X positivo
// 2 es X negativo
// 3 es Y positivo
// 4 es Y negativoç
switch (mov) {
case 1:
if (x == Mundo.mundo_X - 1) {
x = 0;
} else {
x++;
}
break;
case 2:
if (x == 0) {
x = Mundo.mundo_X - 1;
} else {
x--;
}
break;
case 3:
if (y == Mundo.mundo_Y - 1) {
y = 0;
} else {
y++;
}
break;
case 4:
if (y == 0) {
y = Mundo.mundo_Y - 1;
} else {
y--;
}
break;
}
} | 8 |
public void visitLabel(final Label label) {
mv.visitLabel(label);
if (constructor && branches != null) {
List frame = (List) branches.get(label);
if (frame != null) {
stackFrame = frame;
branches.remove(label);
}
}
} | 3 |
private String[] loadConfig() {
String[] defaults = new String[] {
"ip=localhost", "port=9190", "heartbeat=1000", "pass=UNSET", "debug=false"
};
String[] data = new String[defaults.length];
try {
File folder = getDataFolder();
if(!folder.exists()) {
folder.mkdir();
}
File file = new File(folder, "config.txt");
if(!file.exists()) {
file.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(file));
for(int i = 0; i < defaults.length; i++) {
String l = br.readLine();
if(l == null || l.isEmpty()) {
data[i] = defaults[i].split("=")[1];
} else {
data[i] = l.split("=")[1];
defaults[i] = l;
}
}
br.close();
file.delete();
file.createNewFile();
PrintStream ps = new PrintStream(new FileOutputStream(file));
for(int i = 0; i < defaults.length; i++) {
ps.println(defaults[i]);
}
ps.close();
debugger = new Debugger(this, Boolean.valueOf(data[4]));
debugger.debug("Configuration file loaded.");
} catch(IOException e) {
e.printStackTrace();
}
return data;
} | 7 |
@Override
public void actionPerformed(ActionEvent arg0) {
String s = arg0.getActionCommand();// message from the clicked button
switch (s) {
case "Add New Employee":
addEmployee();
break;
case "View Current Employees":
case "Back to Employee List":
goToEmployeeListMenu();
break;
case "Save and Exit":
exit();
break;
case "Select Employee":
boolean employeeSelected = selectEmployee();
if (employeeSelected) {
goToManageMenu();
}// end if
break;
case "Return to Main Menu":
goToMainMenu();
break;
case "Remove Employee":
removeEmployee();
break;
case "Edit Employee":
editEmployee();
break;
default:
System.err.println("Fatal Error!");
System.exit(1);
}// end switch
}// end actionPerformed | 9 |
@Override
public void run()
{
while (true)
{
lock.lock();
Socket client;
try
{
client = socket.accept();
log.debug("new client: " + client.getInetAddress().toString());
handleConnection(client);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
await.awaitNanos(100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
ArrayList<Object> input = new ArrayList<Object>();
input.add("teset test test");
greetPacket.input = input;
mainSession.broadcast(greetPacket, mainSession.getClients().get(0));
}
} | 3 |
public GlassSword(){
this.name = Constants.GLASS_SWORD;
this.attackScore = 12;
this.attackSpeed = 14;
this.money = 410;
} | 0 |
public final void addBad(Opponent opp) {
bad[badPointer] = opp;
badPointer++;
if (badPointer == bad.length) {
badPointer = 0;
}
} | 1 |
public static Vector Half(Vector Vec, boolean X, boolean Y, boolean Z) {
if (X) {Vec.setX(Vec.getX()*0.5);}
if (Y) {Vec.setY(Vec.getY()*0.5);}
if (Z) {Vec.setZ(Vec.getZ()*0.5);}
return Vec;
} | 3 |
public void dumpRegion(String line) {
String parens = "{\010{}\010}<\010<>\010>[\010[]\010]`\010`'\010'"
.substring(options * 6, options * 6 + 6);
pw.print(parens.substring(0, 3));
Enumeration enum_ = childBPs.elements();
int cur = startPos;
BreakPoint child = (BreakPoint) enum_.nextElement();
if (child.startPos >= 0) {
pw.print(line.substring(cur, child.startPos));
child.dumpRegion(line);
cur = child.endPos;
}
while (enum_.hasMoreElements()) {
child = (BreakPoint) enum_.nextElement();
pw.print(line.substring(cur, child.breakPos));
pw.print("!\010!" + breakPenalty);
cur = child.breakPos;
if (child.startPos >= 0) {
pw.print(line.substring(child.breakPos, child.startPos));
child.dumpRegion(line);
cur = child.endPos;
}
}
pw.print(line.substring(cur, endPos));
pw.print(parens.substring(3));
} | 3 |
public boolean isMoving() {
return currAction == Action.MOVE || currAction == Action.MOVE_COMMITTED;
} | 1 |
public boolean hasChanged() {
if (!file.exists()) {
if (exists) {
exists = false;
return true;
}
return false;
}
if (!exists) {
exists = true;
this.timestamp = file.lastModified();
return true;
}
long current = file.lastModified();
if (current != timestamp) {
timestamp = current;
return true;
}
return false;
} | 4 |
public void put(int key,int value){
int hash = getHashCode(key);
if(elements[hash]==null){
elements[hash] = new LinkedNode(key,value);
}
else{
LinkedNode node = (LinkedNode)elements[hash];
if(node.put(key,value)==false) {
return;
}
elements[hash] = node;
}
counter++;
} | 2 |
public boolean outputFile(){
try {
this.outputFile = new File(outputFileName);
this.outputWritter = new BufferedWriter(new FileWriter(this.path + outputFile));
while (this.inputReader.ready()) {
String sLine = this.inputReader.readLine();
if (!sLine.equals(null) && sLine.length() >= 1) {
if (sLine.substring(0, 1).matches(regex)) {
outputWritter.write(sLine + "\n");
linesSaved++;
} else {
linesIgnored++;
}
}
}
System.out.println("Saved " + linesSaved + " lines");
System.out.println("Removed " + linesIgnored + " lines");
} catch (FileNotFoundException e) {
System.out.println("Files does not exist : "+this.path + inputFileName);
//e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if(this.inputReader!=null && this.outputWritter !=null){
this.inputReader.close();
this.outputWritter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
} | 9 |
public static BufferedImage buildHitmap(ArrayList<Entity> props) {
BufferedImage hitmap = new BufferedImage(800, 600, BufferedImage.TYPE_BYTE_BINARY);
PathQuad.size = new Dimension(800, 600);
Graphics2D g = hitmap.createGraphics();
for(int x = 0; x<props.size(); x++) {
if(props.get(x).isSolid())
g.fillRect((int)props.get(x).getBox().getX(), (int)props.get(x).getBox().getY(), (int)props.get(x).getBox().getWidth(), (int)props.get(x).getBox().getHeight());
}
g.dispose();
return hitmap;
} | 2 |
public static void writeStandardOutput() {
if (writingStandardOutput)
return;
try {
out.close();
}
catch (Exception e) {
}
outputFileName = null;
outputErrorCount = 0;
out = standardOutput;
writingStandardOutput = true;
} | 2 |
static int getDendrogramSize(int n) {
if (n < 2) {
return 0;
}
int cn = 2;
int cs = 50;
while (cn < n) {
cn++;
if (3 <= cn && cn <= 5) {
cs += 50;
}
if (6 <= cn && cn <= 10) {
cs += 30;
}
if (11 <= cn && cn <= 20) {
cs += 15;
}
}
return cs;
} | 8 |
public static void upload(){
readProjectDbInfo();
if(!Check.NULLCheck(projectName)||!Check.NULLCheck(dbconS)||!Check.NULLCheck(un)
||!Check.NULLCheck(pwd)||!Check.NULLCheck(data_db_name)||!Check.NULLCheck(channel))
return;
SFTPMultiThread.multiThreadUpload(projectName, new File(System.getProperty("user.dir") + File.separator + projectName),"/home//Pad-dbw");
SFTPMultiThread.multiThreadUpload(projectName+"-ods", new File(System.getProperty("user.dir") + File.separator + projectName+"-ods"),"/home//Pad-dbw");
} | 6 |
public static void main(String[] args) {
ObjectOutputStream objectWriter = null;
ObjectInputStream objectReader = null;
try {
objectWriter = new ObjectOutputStream(new FileOutputStream(
"student.dat"));
objectWriter.writeObject(new Student(1, "A", "a"));
objectWriter.writeObject(new Student(2, "B", "b"));
objectWriter.writeObject(new Student(3, "C", "c"));
objectWriter.writeObject(new Student(4, "D", "d"));
System.out.println("Printing list of students in the database:");
objectReader = new ObjectInputStream(new FileInputStream(
"student.dat"));
for (int i = 0; i < 4; i++) {
System.out.println(objectReader.readObject());
}
} catch (Exception e) {
} finally {
try {
objectReader.close();
objectWriter.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
} | 3 |
public void reload(List<String> list) {
setEnabled(false);
// Clear out all menu items
for (int i = getMenuComponentCount() - 1; i >= 0; i--) {
remove(0);
}
// Copy from Prefs into Menu
JMenuItem mi;
for (String f : list) {
if (f == null) { // Stop on first missing
break;
}
// Drop from list if file has been deleted.
if (new File(f).exists()) {
// Since at least one item valid, enable menu
setEnabled(true);
// And add to Menu
this.add(mi = new JMenuItem(f));
mi.addActionListener(recentOpener);
} else {
recentFileNames.remove(f);
}
}
} | 4 |
public int sendMultipleQueueMessage(int priority, int receiver, int context,
String content, List<Integer> queues) {
int status = -1;
if (messageBroker == null) {
log.error("There is no broker connecting to server");
} else {
if (messageSenderBroker == null) {
messageSenderBroker = messageBroker.createMessageSender();
}
Message msg = messageBroker.createMessage(priority, receiver, context, content);
try {
status = messageSenderBroker.send(msg, queues);
if (status < 0) {
log.error("Send message failed with status " + status);
}
} catch (ServerConnectionException e) {
log.error("No connection to server", e);
} catch (InvalidAuthenticationException e) {
log.error("Client not authenticated", e);
} catch (WrongResponseException e) {
log.error("Received wrong response from server.", e);
} catch (SendMessageException e) {
log.error("Could not send command to server.", e);
}
}
return status;
} | 7 |
public void loadConfiguration(){
File fichier_language = new File(getDataFolder() + File.separator + "Language.yml");
FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language);
Language.options().header("Supports unicode characters ! \n<3, [*], [**], [p], [v], [+], [++]");
Language.addDefault("Language.Prefix", "&4&l[&6&lOneInTheChamber&4&l]");
Language.addDefault("Language.Updater.Update_available", "&eUpdate available !! Type /oitc update to update the plugin.");
Language.addDefault("Language.Updater.Succesfully_update", "&eYou succesfully update the plugin ! Reload the server.");
Language.addDefault("Language.Updater.No_update_available", "&eThere is no update available ! You're good.");
Language.addDefault("Language.Updater.Error", "&eCouldn't update the plugin !");
Language.addDefault("Language.Scoreboard.Name", "&4&l>> &6&lLeaderboard &4&l<<");
Language.addDefault("Language.Stuff.Sword", "&6&lKNIFE");
Language.addDefault("Language.Stuff.Bow", "&3&lSNIPER");
Language.addDefault("Language.Stuff.Arrow", "&3&lAN AMMO");
Language.addDefault("Language.Stuff.Redstone", "&4&lLIVES");
Language.addDefault("Language.Stats.Start", "&2&l>>>>>> &4&l[&6&l%player's Stats&4&l] &2&l<<<<<<");
Language.addDefault("Language.Stats.Kills", " &4>>>>> &9Kills: &b%kills &4<<<<<");
Language.addDefault("Language.Stats.Wins", " &4>>>>> &9Wins: &b%wins &4<<<<<");
Language.addDefault("Language.Stats.Coins", " &4>>>>> &9Coins: &b%coins &4<<<<<");
Language.addDefault("Language.Stats.Played", " &4>>>>> &9Played: &b%played &4<<<<<");
Language.addDefault("Language.Stats.Not_found", "&cPlayer not found !");
Language.addDefault("Language.Stats.Never_play", "&cYou've never played to OITC !");
Language.addDefault("Language.Help.Menu", "&2&l>>>>>> &4&l[&6&lOne In The Chamber's Help&4&l] &2&l<<<<<<");
Language.addDefault("Language.Help.Update", " &4>>>>> &9&l/oitc update &bto update the plugin !");
Language.addDefault("Language.Help.Join", " &4>>>>> &9&l/oitc join <arena> &bto join an arena");
Language.addDefault("Language.Help.Lobby", " &4>>>>> &9&l/oitc lobby &bto join the lobby");
Language.addDefault("Language.Help.Leave", " &4>>>>> &9&l/oitc leave &bto leave an arena");
Language.addDefault("Language.Help.Stats", " &4>>>>> &9&l/oitc stats &bto look your skills");
Language.addDefault("Language.Help.Reload", " &4>>>>> &9&l/oitc reload &bto reload the plugin");
Language.addDefault("Language.Help.Stats_player", " &4>>>>> &9&l/oitc stats <player> &bto look the player's skills");
Language.addDefault("Language.Help.Setup.Lobby", " &4>>>>> &9&l/oitc setlobby &bto set the lobby");
Language.addDefault("Language.Help.Setup.Create", " &4>>>>> &9&l/oitc create <arena> &bto create an arena");
Language.addDefault("Language.Help.Setup.Delete", " &4>>>>> &9&l/oitc delete|remove <arena> &b to delete an arena");
Language.addDefault("Language.Help.Setup.Max_players", " &4>>>>> &9&l/oitc setmaxplayers <number> <arena> &bto set the maxplayers");
Language.addDefault("Language.Help.Setup.Min_players", " &4>>>>> &9&l/oitc setminplayers <number> <arena> &bto set the minplayers");
Language.addDefault("Language.Help.Setup.Add_spawn", " &4>>>>> &9&l/oitc addspawn <arena> &bto add a spawn");
Language.addDefault("Language.Help.Setup.Private_chat", " &4>>>>> &9&l/oitc setprivatechat <true|false> <arena> &bto set or not the private chat");
Language.addDefault("Language.Help.Setup.Start", " &4>>>>> &9&l/oitc setstart <arena> &bto set the start location");
Language.addDefault("Language.Help.Setup.Display_name", " &4>>>>> &9&l/oitc setdisplayname <arena> <display_name> &bto change the display name");
Language.addDefault("Language.Help.Setup.Type", " &4>>>>> &9&l/oitc settype <type> <arena> &bto set the type of an arena");
Language.addDefault("Language.Help.Setup.Lives", " &4>>>>> &9&l/oitc setlives <number> <arena> &bto set the lives of an arena");
Language.addDefault("Language.Help.Setup.Points", " &4>>>>> &9&l/oitc setpoints <number> <arena> &bto set the points of an arena");
Language.addDefault("Language.Help.Setup.Countdown", " &4>>>>> &9&l/oitc setcountdown <number> <arena> &bto set the countdown of an arena");
Language.addDefault("Language.Help.Setup.Active", " &4>>>>> &9&l/oitc active <arena> &bto active an arena");
Language.addDefault("Language.Help.Setup.Disactive", " &4>>>>> &9&l/oitc disactive <arena> &bto disactive an arena");
Language.addDefault("Language.Help.Admin.Stop", " &4>>>>> &9&l/oitc stop <arena> &bto stop an arena");
Language.addDefault("Language.Arena.Chat_format", "&2&l[&e&l%player&2&l] &a=> &b&l%message");
Language.addDefault("Language.Arena.Full", "&3The arena is full ! You can't join...");
Language.addDefault("Language.Arena.In_game", "&3The arena is in game ! You can't join...");
Language.addDefault("Language.Arena.Disable", "&3The arena is disactivate ! You can't join..");
Language.addDefault("Language.Arena.Not_in_game", "&3You're not in game ! You can't leave...");
Language.addDefault("Language.Arena.Already_in_game", "&3You are already in game !");
Language.addDefault("Language.Arena.Not_active", "&3This arena isn't active !");
Language.addDefault("Language.Arena.Join", "&e&l%player &3joined the arena ! &6%number/%max");
Language.addDefault("Language.Arena.StartsIn", "&3The game starts in &l%time &3seconds.");
Language.addDefault("Language.Arena.Not_enough_players_to_launch", "&3There is not enough players to launch the game !");
Language.addDefault("Language.Arena.Start", "&3The game started ! Good luck...");
Language.addDefault("Language.Arena.Broadcast_leave", "&e&l%player &3left the arena !");
Language.addDefault("Language.Arena.Leave", "&3You leave the arena !");
Language.addDefault("Language.Arena.Win", "&3&lYou win the game !");
Language.addDefault("Language.Arena.Broadcast_player_lost", "&e&l%player &3lost the game !");
Language.addDefault("Language.Arena.Broadcast_player_win", "&e&l%player &3win the game !");
Language.addDefault("Language.Arena.Player_lost", "&3You lost the game !");
Language.addDefault("Language.Arena.End", "&3End of the game !");
Language.addDefault("Language.Arena.Reload", "&3You reload the plugin !");
Language.addDefault("Language.Arena.Server_reload", "&3Reload ! You leave the arena...");
Language.addDefault("Language.Arena.Death_message", "&a&l%killer &3smashed &a&l%player &3!");
Language.set("Language.Signs.Name", null);
Language.addDefault("Language.Signs.Name_lives", "&4[&6&lOITC<3&4]");
Language.addDefault("Language.Signs.Name_points", "&4[&6&lOITC[**]&4]");
Language.set("Language.Signs.Arena", null);
Language.addDefault("Language.Signs.Arena_lives", "&0&l%arena<3");
Language.addDefault("Language.Signs.Arena_points", "&0&l%arena[**]");
Language.addDefault("Language.Signs.Joinable", "&a[Joinable]");
Language.addDefault("Language.Signs.InGame", "&8[InGame]");
Language.addDefault("Language.Signs.Starting", "&6[Starting]");
Language.addDefault("Language.Signs.Not_joinable", "&4[NotJoinable]");
Language.addDefault("Language.Signs.Number_in_arena", "&8%number/%maxplayers");
Language.addDefault("Language.Signs.Succesfully_set", "&3You succesfully set a join sign !");
Language.addDefault("Language.Signs.Missing_arena", "&cYou must insert an arena name in the line 2 !");
Language.addDefault("Language.Signs.Break", "&cYou've broken an OITC sign !");
Language.addDefault("Language.Signs.Must_to_be_sneak", "&cYou must to be sneaking if you want to destroy an OITC sign !");
Language.addDefault("Language.Error.Arena_does_not_exist", "&cThe arena &l%arena &cdoesn't exist !");
Language.addDefault("Language.Error.Not_enough_spawns", "&cNot enough spawns defined to join !");
Language.addDefault("Language.Error.No_start_location", "&cThe start location isn't set !");
Language.addDefault("Language.Error.Not_ready", "&cThe arena isn't ready to play !");
Language.addDefault("Language.Error.Not_permission", "&cYou don't have the permission !");
Language.addDefault("Language.Error.Lobby_is_not_set", "&cThe lobby isn't set !");
Language.addDefault("Language.Error.No_commands", "&3You can't use commands in a game ! ==> &l/oitc leave &3to leave the arena...");
Language.addDefault("Language.Error.Wrong_command", "&cWrong command ! Type /oitc to see all the commands !");
Language.addDefault("Language.Error.Not_enough_args", "&cNot enough arguments for this command !");
Language.addDefault("Language.Error.Bad_args", "&cBad type of argument !");
Language.addDefault("Language.Setup.Arena_succesfully_created", "&cThe arena &l%arena &chas been succesfully created !");
Language.addDefault("Language.Setup.Arena_succesfully_deleted", "&cThe arena &l%arena &chas been succesfully deleted !");
Language.addDefault("Language.Setup.Arena_already_exists", "&cThis arena &l%arena &calready exists !");
Language.addDefault("Language.Setup.Lobby_succesfully_set", "&cThe lobby has been succesfully set !");
Language.addDefault("Language.Setup.Display_name", "&cThe display name has been changed to &l%displayname &cfor the arena &l%arena &c!");
Language.addDefault("Language.Setup.Private_chat", "&cThe private chat has been set to &l%value &cfor the arena &l%arena &c!");
Language.addDefault("Language.Setup.Spawn_succesfully_added", "&cSpawn succesfully added for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Lives", "&cThe number of lives has been set for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Type", "&cThe type has been set for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Points", "&cThe number of points has been set for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Countdown", "&cThe countdown has been set for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Start_set", "&cThe start of the arena &l%arena &chas been succesfully set !");
Language.addDefault("Language.Setup.Max_players_succesfully_set", "&cMax players set for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Max_players_too_small", "&cMax players smaller than min players !");
Language.addDefault("Language.Setup.Min_players_succesfully_set", "&cMinimum players set for the arena &l%arena &c!");
Language.addDefault("Language.Setup.Min_players_too_big", "&cMin players bigger than max players !");
Language.addDefault("Language.Setup.Active", "&cYou active the arena &l%arena &c!");
Language.addDefault("Language.Setup.Disactive", "&cYou disactive the arena &l%arena &c!");
Language.addDefault("Language.Force.Stop", "&cYou stopped the arene %arena !");
Language.addDefault("Language.Force.Can_not_stop", "&cYou can't stop the arena %arena ! It isn't in game...");
Language.options().copyDefaults(true);
try {
Language.save(fichier_language);
} catch (IOException e) {
e.printStackTrace();
}
File fichier_lobby = new File(getDataFolder() + File.separator + "Lobby.yml");
FileConfiguration Lobby = YamlConfiguration.loadConfiguration(fichier_lobby);
if(!fichier_lobby.exists()){
Lobby.addDefault("Lobby.World", "");
Lobby.addDefault("Lobby.X", "");
Lobby.addDefault("Lobby.Y", "");
Lobby.addDefault("Lobby.Z", "");
Lobby.addDefault("Lobby.Yaw", "");
Lobby.addDefault("Lobby.Pitch", "");
Lobby.options().copyDefaults(true);
try {
Lobby.save(fichier_lobby);
} catch (IOException e) {
e.printStackTrace();
}
}
File dossier_players = new File(getDataFolder() + File.separator + "Players");
if(!dossier_players.exists()){
dossier_players.mkdir();
}
File dossier_arenas = new File(getDataFolder() + File.separator + "Arenas");
if(!dossier_arenas.exists()){
dossier_arenas.mkdir();
}
File fichier_signs = new File(getDataFolder() + File.separator + "Signs.yml");
YamlConfiguration signs = YamlConfiguration.loadConfiguration(fichier_signs);
if(!fichier_signs.exists()){
signs.set("Arenas", "");
try {
signs.save(fichier_signs);;
} catch (IOException e) {
e.printStackTrace();
}
}
} | 7 |
public static double asinh(double a) {
boolean negative = false;
if (a < 0) {
negative = true;
a = -a;
}
double absAsinh;
if (a > 0.167) {
absAsinh = FastMath.log(FastMath.sqrt(a * a + 1) + a);
} else {
final double a2 = a * a;
if (a > 0.097) {
absAsinh = a
* (1 - a2
* (F_1_3 - a2
* (F_1_5 - a2
* (F_1_7 - a2
* (F_1_9 - a2
* (F_1_11 - a2
* (F_1_13 - a2
* (F_1_15 - a2
* F_1_17
* F_15_16)
* F_13_14)
* F_11_12)
* F_9_10)
* F_7_8) * F_5_6)
* F_3_4) * F_1_2);
} else if (a > 0.036) {
absAsinh = a
* (1 - a2
* (F_1_3 - a2
* (F_1_5 - a2
* (F_1_7 - a2
* (F_1_9 - a2
* (F_1_11 - a2
* F_1_13
* F_11_12)
* F_9_10)
* F_7_8) * F_5_6)
* F_3_4) * F_1_2);
} else if (a > 0.0036) {
absAsinh = a
* (1 - a2
* (F_1_3 - a2
* (F_1_5 - a2
* (F_1_7 - a2 * F_1_9 * F_7_8)
* F_5_6) * F_3_4) * F_1_2);
} else {
absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2);
}
}
return negative ? -absAsinh : absAsinh;
} | 6 |
@Override
public void keyPressed(KeyEvent ke) {
if(ke.getKeyChar() == 'c') {
lastTool = curTool;
curTool = 2;
} else if(ke.getKeyChar() == 'l') {
lastTool = curTool;
curTool = 3;
} else if(ke.getKeyChar() == 'f') {
lastTool = curTool;
curTool = 1;
} else if(ke.getKeyChar() == 'd') {
lastTool = curTool;
curTool = 0;
}
if(ke.getKeyCode() == KeyEvent.VK_EQUALS) {
scale *= 2;
if(scale > 32) {
scale = 32;
}
tp.setScale(scale);
tp.repaint();
this.texturePane.revalidate();
} else if(ke.getKeyCode() == KeyEvent.VK_MINUS) {
scale /= 2;
if(scale < 1) {
scale = 1;
}
tp.setScale(scale);
tp.repaint();
this.texturePane.revalidate();
}
this.texturePane.getHorizontalScrollBar().setUnitIncrement(scale);
this.texturePane.getVerticalScrollBar().setUnitIncrement(scale);
this.setTool(curTool);
} | 8 |
public static void main(String[] args) {
int c = 0;
double check = 0;
outerloop:
for(int a = 1; a < 1000; a++)
{
for(int b = 1; b < 1000; b++)
{
check = Math.sqrt((a * a) + (b * b));
c = (int) Math.sqrt((a * a) + (b * b));
if(check == c)
{
if(a + b + c == 1000 && a < b && b < c)
{
System.out.println(a + " * " + b + " * " + c + " = " + (int) (a * b * c));
break outerloop;
}
}
}
}
} | 6 |
public static void main(String[] pArgs) {
try {
TableViewColumn[] columns =
{
new DefaultTableViewColumn(
"Name",
Row.class.getDeclaredMethod("getName", null),
Row.class.getDeclaredMethod("setName", new Class[] {String.class})),
new DefaultTableViewColumn(
"Description",
Row.class.getDeclaredMethod("getDescription", null),
Row.class.getDeclaredMethod("setDescription", new Class[] {String.class})),
new DefaultTableViewColumn(
"Number",
Row.class.getDeclaredMethod("getNumber", null),
Row.class.getDeclaredMethod("setNumber", new Class[] {Integer.class})),
new DefaultTableViewColumn(
"Data",
Row.class.getDeclaredMethod("getData", null),
Row.class.getDeclaredMethod("setData", new Class[] {String.class})),
new DefaultTableViewColumn(
"Create",
Row.class.getDeclaredMethod("getCreate", null),
Row.class.getDeclaredMethod("setCreate", new Class[] {Date.class}))
};
Row[] rows =
{
new Row("toto", "This is my toto", 1, "Hello", new Date(1000000000000L)),
new Row("ooo", "This is my ooo", 1, "999", new Date(1000000000000L)),
new Row("aaa", "This is my aaa", 1, "888", new Date(200000000000L)),
new Row("bbb", "This is my bbb", 1, "777", new Date(300000000000L)),
new Row("ccc", "This is my ccc", 1, "666", new Date(400000000000L)),
new Row("ddd", "This is my ddd", 1, "555", new Date(500000000000L)),
new Row("eee", "This is my eee", 1, "444", new Date(600000000000L)),
new Row("fff", "This is my fff", 1, "333", new Date(700000000000L)),
new Row("ggg", "This is my ggg", 1, "222", new Date(800000000000L)),
new Row("hhh", "This is my hhh", 1, "111", new Date(900000000000L))};
final DefaultTableViewModel model = new DefaultTableViewModel(columns, Arrays.asList(rows));
for (int i = 0 ; i < 20000 ; i++) {
model.addRow(new Row("" + 1, "This is my " + i, 1, "" + (20000 - i), new Date()));
}
JFrame frame = new JFrame();
final TableView view = new TableView(model);
view.setMakeIndex(true);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(view), BorderLayout.CENTER);
JPanel panelBtn = new JPanel();
JButton btnNew = new JButton("Add");
JButton btnRemove = new JButton("Remove");
btnNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent pEvent) {
List selection = view.getSelectedRowObjects();
model.addRow(new Row("New row", "This is s new row", 1, "Data of new row", new Date()));
view.addRowSelection(selection);
}
});
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent pEvent) {
List selection = view.getSelectedRowObjects();
model.removeRows(selection);
}
});
panelBtn.setLayout(new GridLayout(2, 1));
panelBtn.add(btnNew);
panelBtn.add(btnRemove);
frame.getContentPane().add(panelBtn, BorderLayout.EAST);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.validate();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
} | 2 |
public void setTrainNumber(TrainNumber value) {
this._trainNumber = value;
} | 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.