text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
public void keyTyped(KeyEvent event) {
char ch = event.getKeyChar();
if (ch == '\n' || ch == '\r') {
if (canOpenSelection()) {
openSelection();
}
event.consume();
} else if (ch == '\b' || ch == KeyEvent.VK_DELETE) {
if (canDeleteSelection()) {
deleteSelection();
}
event.consume();
}
}
| 6 |
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}
int length = board[0].length - 1;
int height = board.length - 1;
for (int i = 0; i < length; i++) {
fill(board, 0, i);
fill(board, height, length - i);
}
for (int j = 0; j < height; j++) {
fill(board, j, length);
fill(board, height - j, 0);
}
for (int i = 0; i <= height; i++) {
for (int j = 0; j <= length; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == 'D') {
board[i][j] = 'O';
}
}
}
}
| 9 |
@Override
public Program mutate(Program program) throws InvalidProgramException {
if (!(program instanceof ProgramImpl)) {
throw new InvalidProgramException();
}
Random randomGenerator = new Random();
ProgramImpl program1 = (ProgramImpl) program.clone();
List<Reaction> reactions = program1.getReactions();
Double kineticRate = randomGenerator.nextDouble();
Reaction newReaction = null;
int attempts = 0;
do {
newReaction = new Reaction(ruleRepository.getRandomRule(),
kineticRate);
attempts++;
} while (reactions.contains(newReaction) && attempts < ruleRepository.getNumberOfRules() * 2);
if (!reactions.contains(newReaction)) {
program1.addReaction(newReaction);
}
return program1;
}
| 4 |
public String update(String string, String string2) {
// TODO Auto-generated method stub
for (int i = 0; i < clientObj.length; i++) {
if((clientObj[i].getPassword()).equals(string)){
clientObj[i].setEmail(string2);
return clientObj[i].getEmail();
}
}
return null;
}
| 2 |
public OptionsPanel(Handler handler, boolean optioncollapsed, int random) {
super();
if(random == 0) color = "_green";
else if(random == 1) color = "_blue";
else color = "_orange";
this.setLayout(new MigLayout("fill"));
this.setBackground(Color.black);
JPanel titlePanel = new JPanel(new MigLayout("fill"));
JPanel optionPanel = new JPanel(new MigLayout("fill"));
JLabel optionText = new JLabel("Options");
JLabel optionToggleImage = new JLabel(optioncollapsed ? makeImageIcon("/images/fold_up" + color + ".png") :
makeImageIcon("/images/fold_down" + color + ".png"));
optionToggleImage.setToolTipText(optioncollapsed ? "show options" : "hide options");
JCheckBox liveDecode = new JCheckBox("Live Decode");
JCheckBox alwaysOnTop = new JCheckBox("Always on top");
optionText.setBackground(Color.black);
optionToggleImage.setBackground(Color.black);
liveDecode.setBackground(Color.black);
alwaysOnTop.setBackground(Color.black);
optionText.setForeground(GUI3.guiColor);
optionToggleImage.setForeground(GUI3.guiColor);
liveDecode.setForeground(GUI3.guiColor);
alwaysOnTop.setForeground(GUI3.guiColor);
optionText.setFont(GUI3.INGRESS_FONT);
optionToggleImage.setFont(GUI3.INGRESS_FONT);
liveDecode.setFont(GUI3.INGRESS_FONT);
alwaysOnTop.setFont(GUI3.INGRESS_FONT);
titlePanel.setBackground(Color.black);
optionPanel.setBackground(Color.black);
optionToggleImage.setName("optionToggle");
optionToggleImage.addMouseListener(handler);
setName("optionToggle");
addMouseListener(handler);
titlePanel.setBorder(new LineBorder(GUI3.guiColor, 1));
optionPanel.setBorder(new LineBorder(GUI3.guiColor, 1));
titlePanel.add(optionText, "growx, push");
titlePanel.add(optionToggleImage);
if(handler.isLiveDecode()) liveDecode.setSelected(true);
if(handler.isAlwaysOnTop()) alwaysOnTop.setSelected(true);
liveDecode.setActionCommand("liveDecode");
liveDecode.addActionListener(handler);
alwaysOnTop.setActionCommand("alwaysOnTop");
alwaysOnTop.addActionListener(handler);
optionPanel.add(liveDecode, "wrap");
optionPanel.add(alwaysOnTop);
add(titlePanel, "growx, wrap");
if(!optioncollapsed) add(optionPanel, "growx, growy, push");
}
| 7 |
public void AllPairsShortestPath(int[][] matrix) {
int numberVertices = matrix.length;
// create new storage container for path and weight information
pathWeights = new int[numberVertices][numberVertices];
// Initialise containers;
for (int i = 0; i < numberVertices; i++) {
for (int j = 0; j < numberVertices; j++) {
// If no direct path, set weight to Infinity.
pathWeights[i][j] = matrix[i][j] > 0 ? matrix[i][j] : Integer.MAX_VALUE;
if(i == j){
pathWeights[i][j] = 0;
}
}
}
// Main loop.
for (int k = 0; k < numberVertices; k++) {
for (int i = 0; i < numberVertices; i++) {
for (int j = 0; j < numberVertices; j++) {
// Cast these to long to avoid overflow!
if ((long)pathWeights[i][j] > (long)pathWeights[i][k] + (long)pathWeights[k][j]) {
// Store new min weight
pathWeights[i][j] = pathWeights[i][k] + pathWeights[k][j];
}
}
}
}
}
| 8 |
public boolean matches(String word) {
if (word.length() != string.length()) {
return false;
}
for (int i=0; i<word.length(); i++) {
if (string.charAt(i) != ANY_CHAR && string.charAt(i) != word.charAt(i)) {
return false;
}
}
return true;
}
| 4 |
public void tilesetLaden(BufferedImage set){
tiles = new ArrayList<Tile>();
int Anzahl_x = set.getWidth()/32;
int Anzahl_y = set.getHeight()/32;
for(int x=0;x<Anzahl_x;x++){
for(int y=0;y<Anzahl_y;y++){
Tile t = new Tile((set.getSubimage(x*32, y*32, 32, 32)));
/*index
* 0 gras
* 1 sand
* 2 busch
* 3 stein
* 4 wasser
* */
tiles.add(t);
// if zb stein dann istBegehbar=false
}
}
}
| 2 |
public static Integer[][] crossover(Integer[] parent1, Integer[] parent2)
{
Integer[] child1 = new Integer[matrixSize] ;
Integer[] child2 = new Integer[matrixSize] ;
Integer[][] result = new Integer[2][matrixSize] ;
int i = 0, parent1Pos = 0, parent2Pos = 0 ;
setupArray(child1) ;
setupArray(child2) ;
while(i < matrixSize) {
if(Arrays.binarySearch(child1, parent1[parent1Pos]) < 0) {
child1[i] = parent1[parent1Pos] ;
i++ ;
}
parent1Pos++ ;
if(Arrays.binarySearch(child1, parent2[i]) < 0) {
child1[i] = parent2[parent2Pos] ;
i++ ;
}
parent2Pos++ ;
}
result[0] = child1 ;
//reset counter variables for reuse
i = 0 ; parent1Pos = 0 ; parent2Pos = 0 ;
while(i < matrixSize) {
if(Arrays.binarySearch(child2, parent2[parent2Pos]) < 0) {
child2[i] = parent2[parent2Pos] ;
i++ ;
}
parent2Pos++ ;
if(Arrays.binarySearch(child2, parent1[i]) < 0) {
child2[i] = parent1[parent1Pos] ;
i++ ;
}
parent1Pos++ ;
}
result[1] = child2 ;
return result ;
}
| 6 |
public void put(long key, E value) {
int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i >= 0) {
mValues[i] = value;
} else {
i = ~i;
if (i < mSize && mValues[i] == DELETED) {
mKeys[i] = key;
mValues[i] = value;
return;
}
if (mGarbage && mSize >= mKeys.length) {
gc();
// Search again because indices may have changed.
i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
}
if (mSize >= mKeys.length) {
int n = mSize + 1;
long[] nkeys = new long[n];
Object[] nvalues = new Object[n];
// Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
mKeys = nkeys;
mValues = nvalues;
}
if (mSize - i != 0) {
// Log.e("SparseArray", "move " + (mSize - i));
System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
}
mKeys[i] = key;
mValues[i] = value;
mSize++;
}
}
| 7 |
public static void defineEnemies(int level){
enemyDim.clear();
enemyDim.put("skeleton", new int[]{26, 46});
try {
skeleton.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/Skeleton1.png")));
skeleton.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/Skeleton2.png")));
skeleton.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/Skeleton3.png")));
skeleton.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/Skeleton4.png")));
skeletonF.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/SkeletonF1.png")));
skeletonF.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/SkeletonF2.png")));
skeletonF.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/SkeletonF3.png")));
skeletonF.add(ImageIO.read(CharacterManager.class.getClassLoader().getResourceAsStream("images/SkeletonF4.png")));
enemySprites.put("skeleton", skeleton);
enemySpritesF.put("skeleton", skeletonF);
}
catch (IOException e){
e.printStackTrace();
}
createEnemy(posRel(0, 1, 3), PlatformManager.floors.get(0).y, "skeleton", 1);
createEnemy(posRel(1, 1, 2), PlatformManager.floors.get(1).y, "skeleton", 1);
}
| 1 |
private void loadGUIFromOperator() {
String code = operator.getCode();
String filialCode = operator.getFilialCode();
String firstName = operator.getFirstName();
String surName = operator.getSurName();
String parentName = operator.getParentName();
String password = operator.getPassword();
Boolean controler = operator.isControler();
Boolean admin = operator.isAdmin();
Boolean enabled = operator.isEnabled();
// текстовые поля
if (code != null) {
codeTextField.setText(code);
} else {
codeTextField.setText("");
}
// текстовые поля
if (filialCode != null) {
filialCodeTextField.setText(filialCode);
} else {
filialCodeTextField.setText("");
}
// текстовые поля
if (firstName != null) {
firstNameTextField.setText(firstName);
} else {
firstNameTextField.setText("");
}
if (surName != null) {
surNameTextField.setText(surName);
} else {
surNameTextField.setText("");
}
if (parentName != null) {
parentNameTextField.setText(parentName);
} else {
parentNameTextField.setText("");
}
if (password != null) {
passwordTextField.setText(password);
} else {
passwordTextField.setText("");
}
// логические поля
if (controler != null) {
controlerCheckBox.setSelected(controler);
} else {
controlerCheckBox.setSelected(false);
}
if (admin != null) {
adminCheckBox.setSelected(admin);
} else {
adminCheckBox.setSelected(false);
}
if (enabled != null) {
enabledCheckBox.setSelected(enabled);
} else {
adminCheckBox.setSelected(true);
}
}
| 9 |
@Override
public void deserialize(Buffer buf) {
id = buf.readShort();
if (id < 0)
throw new RuntimeException("Forbidden value on id = " + id + ", it doesn't respect the following condition : id < 0");
finishedlevel = buf.readShort();
if (finishedlevel < 0 || finishedlevel > 200)
throw new RuntimeException("Forbidden value on finishedlevel = " + finishedlevel + ", it doesn't respect the following condition : finishedlevel < 0 || finishedlevel > 200");
}
| 3 |
@Override
protected List<CharPoint> getNeighbors(CharPoint field) {
List<CharPoint> neighbors = new ArrayList<CharPoint>(this.neighbors.length);
int x = field.getX();
int y = field.getY();
for (int xx = x - 1; xx <= x + 1; xx++) {
for (int yy = y - 1; yy <= y + 1; yy++) {
if (xx == x && yy == y)
continue;
if (xx < 0 || yy < 0)
continue;
if (xx >= width || yy >= height)
continue;
neighbors.add(this.points[xx][yy]);
}
}
return neighbors;
}
| 8 |
public ChatChannel[] getAllChatChannels(){
ChatChannel channels[] = null;
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String url = "jdbc:derby:" + DBName;
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sqlStatement = "SELECT channelID, cctype AS channelType, channelName "
+ "FROM CHATCHANNELS, CHATCHANNELTYPES WHERE cctid = chatchannels.channelType "
+ "AND (chatchannels.channelType = (SELECT CCTID FROM chatchannelTypes WHERE cctype = 'permanent') "
+ "OR chatchannels.channelType = (SELECT CCTID FROM chatchannelTypes WHERE cctype = 'custom'))";
ResultSet rs = statement.executeQuery(sqlStatement);
ArrayList<ChatChannel> alstChannels = new ArrayList<>();
while(rs.next()){
ChatChannel channel = new ChatChannel(rs.getInt("channelID"), rs.getString("channelType"), rs.getString("channelName"));
alstChannels.add(channel);
}
channels = alstChannels.toArray(new ChatChannel[0]);
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return channels;
}
| 2 |
public int accessMemVictimCache(int smpIndexFrom, int numCPUFrom, int smpIndexTo, int numCPUTo, int cacheIndex, int startTime){
int n = getNumberSyncObjectsUntil(smpIndexTo);
SMPNodeConfig smpNodeCfg=Configuration.getInstance().smpNodeConfigs.get(smpIndexTo);
n+=1+smpNodeCfg.cacheConfigsPT.size();
if(smpNodeCfg.hasRemoteCache()){
n++;
}
for(int j = 0;j<smpNodeCfg.cacheConfigsPT.size();j++){
if(smpNodeCfg.cacheConfigsPT.get(j).hasVictimCache()){
n++;
}
}
for(int i = 0;i<smpNodeCfg.cpuCachesToPT.size();i++){
if(smpNodeCfg.cpuCachesToPT.get(i).hasExclusiveCache()){
n++;
}
}
for(int j = 0;j<smpNodeCfg.getIndexInMemCacheCfgs(numCPUTo, cacheIndex);j++){
n++;
if(smpNodeCfg.cacheConfigsMem.get(j).hasVictimCache()){
n++;
}
}
n++;
return access(n,smpIndexFrom,numCPUFrom, startTime);
}
| 7 |
public Main_Window() {
// TODO Auto-generated constructor stub
final JFrame main_frame = new JFrame("stt");
main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane content = new JScrollPane();
//content.setLayout(new FlowLayout());
main_frame.add(content);
source_code.setBorder(BorderFactory.createLineBorder(Color.BLUE));
source_code.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent arg0) {
if (arg0.getModifiers() == 2 && arg0.getKeyChar() == 10) {// 2
// ->ctrl_mod
// 10->
// Enter_key_code
run_compile(source_code.getText());
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyPressed(KeyEvent arg0) {
}
});
content.add(source_code);
start_button = new JButton("Run");
start_button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String src_code = source_code.getText();
program.main(src_code);
run_compile(src_code);
}
});
start_button.setSize(10, 10);
content.add(start_button);
JButton start_debug = new JButton("Step_into");
start_debug.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String src_code = source_code.getText();
start_button.setEnabled(false);
if(cur_pos==-1){
program.main(src_code);
cur_pos=0;
}
run_debug(src_code);
}
});
start_debug.setSize(10, 10);
content.add(start_debug);
JButton openFile = new JButton("Open");
openFile.addActionListener(new OpenFileListener());
content.add(openFile);
main_frame.pack();
main_frame.setVisible(true);
source_code.setText("+++[>++[!-]<-]!");
}
| 3 |
public int compareTo(Point o) {
if (getX() < o.getX()) {
return -1;
} else if ((getX() == o.getX()) && (getY() == o.getY())) {
return 0;
} else if ((getX() == o.getX()) && (getY() < o.getY())) {
return -1;
}
return 1;
}
| 5 |
private void calculerHeuresLivraison() throws HorsPlageException {
int tempsSecondes;
List<Troncon> listTroncons;
PlageHoraire plage = null;
Calendar heureDebut = Calendar.getInstance();
double vitesseKmH=0;
for(Chemin chemin : this.getCheminsResultats()) {
listTroncons = chemin.getTroncons();
tempsSecondes = 0;
int metres = 0;
for(Troncon troncon : listTroncons) {
vitesseKmH = ((troncon.getVitesse()*10)/3.6);
tempsSecondes += (troncon.getLongueurMetre()/(vitesseKmH));
metres+=troncon.getLongueurMetre();
}
Noeud noeudDest = zone.getNoeudById(chemin.getDestination().getIdNoeud());
if(noeudDest.getId() != zone.getEntrepot().getId()){
Livraison livraisonDest = (Livraison) noeudDest;
if(plage == null){
plage = livraisonDest.getPlage();
heureDebut.setTime(plage.getHeureDebut());
}
heureDebut.add(Calendar.SECOND, tempsSecondes);
if (heureDebut.getTime().after(livraisonDest.getPlage().getHeureFin())){
livraisonDest.setEtatLivraison(EtatNoeud.NON_LIVRE);
throw new HorsPlageException(livraisonDest);
} else if (heureDebut.getTime().before((livraisonDest.getPlage().getHeureDebut()))) {
heureDebut.setTime(livraisonDest.getPlage().getHeureDebut());
}
livraisonDest.setHeureLivraison(heureDebut.getTime());
heureDebut.add(Calendar.MINUTE, Livraison.TPS_LIVRAISON_MIN);
}
}
}
| 6 |
public StackFrame()
{
// first create the buttons and widgets to put on the frame
pushButton = new JButton("Push Item");
popButton = new JButton("Pop Item");
peekButton = new JButton("Peek At Stack");
showButton = new JButton("Show Stack");
sizeButton = new JButton("Show Stack Size");
spaceButton = new JButton("Show Stack Space");
stackButton = new JButton("Switch Stacks");
clearButton = new JButton("Clear Stack");
field = new JTextField(50);
area = new JTextArea(10,50);
field.setText("Current stack: stackA");
stackA = new StackAImpl<String>();
stackL = new StackLImpl<String>();
isStackA=true;
buttonPanel1 = new JPanel(); // used to keep the buttons together
buttonPanel2 = new JPanel();
//
this.setTitle("Stack Testing");
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(buttonPanel1);
this.getContentPane().add(buttonPanel2);
this.getContentPane().add(field);
this.getContentPane().add(area);
buttonPanel1.add(pushButton);
buttonPanel1.add(popButton);
buttonPanel1.add(peekButton);
buttonPanel1.add(showButton);
buttonPanel2.add(sizeButton);
buttonPanel2.add(spaceButton);
buttonPanel2.add(stackButton);
buttonPanel2.add(clearButton);
area.setEditable(false); // its now UNchangeable
/* action listener: push button */
pushButton.addActionListener( new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
doPush();
}
} );
/* action listener: pop button */
popButton.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
String poppedItem = "";
if(isStackA)
{
poppedItem = stackA.pop();
area.setText("pop successful!\n" +
"Here's what was popped from stackA: " + poppedItem + "\n\n" +
"Here are the current contents of stackA:\n" + stackL);
}
else
{
poppedItem = stackL.pop();
area.setText("pop successful!\n" +
"Here's what was popped from stackL: " + poppedItem + "\n\n" +
"Here are the current contents of stackL:\n" + stackL);
}
}
} );
/* action listener: peek button */
peekButton.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
String peekItem = "";
if(isStackA)
{
peekItem = stackA.peek();
area.setText("Here's the item on the top of stackA: " + peekItem);
}
else
{
peekItem = stackL.peek();
area.setText("Here's the item on the top of stackL: " + peekItem);
}
}
} );
/* action listener: stack button */
stackButton.addActionListener( new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
isStackA = !isStackA;
if(isStackA)
{
field.setText("Current stack: stackA");
area.setText("Here are the current contents of stackA:\n" + stackA);
}
else
{
field.setText("Current stack: stackL");
area.setText("Here are the current contents of stackL:\n" + stackL);
}
}
} );
/* action listener: show button */
showButton.addActionListener( new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
if(isStackA)
area.setText("Here are the current contents of stackA:\n" + stackA);
else
area.setText("Here are the current contents of stackL:\n" + stackL);
}
} );
/* action listener: size button */
sizeButton.addActionListener( new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
if(isStackA)
area.setText("Here's the current size of stackA: " + stackA.size() +
" items");
else
area.setText("Here's the current size of stackL: " + stackL.size() +
" items");
}
} );
/* action listener: space button */
spaceButton.addActionListener( new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
if(isStackA)
{
if(!stackA.isFull())
area.setText("stackA has room for " + (5 - stackA.size()) +
" more items.");
else
area.setText("stackA is already full.");
}
else
{
if(!stackL.isFull())
area.setText("stackL has room for " + (5 - stackL.size()) +
" more items.");
else
area.setText("stackL is already full.");
}
}
} );
/* action listener: clear button */
clearButton.addActionListener( new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
if(isStackA)
{
stackA.clear();
area.setText("clear successful!\n" + stackA);
}
else
{
stackL.clear();
area.setText("clear successful!\n" + stackL);
}
}
} );
}// end of constructor
| 9 |
public boolean isAnyKindOfOfficer(Law laws, MOB M)
{
if((M.isMonster())
&&(M.location()!=null)
&&(CMLib.flags().isMobile(M)))
{
if((laws.officerNames().size()<=0)
||(laws.officerNames().get(0).equals("@")))
return false;
for(int i=0;i<laws.officerNames().size();i++)
{
if((CMLib.english().containsString(M.displayText(),laws.officerNames().get(i))
||(CMLib.english().containsString(M.Name(),laws.officerNames().get(i)))))
return true;
}
}
return false;
}
| 8 |
public double getVitality() {
return vitality;
}
| 0 |
public void setTool(int tool) {
hp.setTool(tool);
if(tool == 0) {
pencil.setSelected(true);
} else if(tool == 1) {
fill.setSelected(true);
} else if(tool == 2) {
chooser.setSelected(true);
} else if(tool == 3) {
line.setSelected(true);
}
curTool = tool;
}
| 4 |
public String readUntil(char c) throws IOException {
if (lookaheadChar == UNDEFINED) {
lookaheadChar = super.read();
}
line.clear(); // reuse
while (lookaheadChar != c && lookaheadChar != END_OF_STREAM) {
line.append((char) lookaheadChar);
if (lookaheadChar == '\n') {
lineCounter++;
}
lastChar = lookaheadChar;
lookaheadChar = super.read();
}
return line.toString();
}
| 4 |
public tile searchMap(TriPoint t){
tile Tile = new tile(t);
for(int i = 0; i < tiles.size(); i++){
Tile = tiles.get(i);
if(t.x == Tile.coords.x){
if(t.y == Tile.coords.y){
return Tile;
}
}
}
return null;
}
| 3 |
protected void end() {}
| 0 |
static void destroy() {
while (! queue.isEmpty()) {
try {
ProxyConnection conn = queue.take();
if (conn != null && conn.isValid(DB_ISVALID_TIMEOUT)) {
conn.reallyClose();
}
} catch (InterruptedException | SQLException ex) {
LOGGER.error("Error in closing and destroying pool connections.", ex);
}
}
}
| 4 |
public void setLines(ArrayList<PathItem> lines) {
this.lines = lines;
}
| 0 |
public boolean export(String filename){
try {
StringBuilder sb = new StringBuilder();
sb.append(frozen).append('\n');
int i = layers.size();
for (Node[] layer: layers){
//Account for bias weights
int layer_size = layer.length;
if (--i != 0) layer_size--;
sb.append(layer_size).append('\t');
}
sb.append('\n');
for (Node[] layer: layers){
for (Node n: layer){
for (Double weight: n.weights)
sb.append(weight).append('\t');
sb.append('\n');
}
}
try (FileWriter x = new FileWriter(new File(filename))) {
x.write(sb.toString());
}
return true;
} catch (IOException ex) {
System.out.println(ex.getMessage());
return false;
}
}
| 6 |
private static int decode4to3(
final byte[] source, final int srcOffset,
final byte[] destination, final int destOffset, final int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
final byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
final int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
final int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
final int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes
| 8 |
public ConfigGetDb(String fileName)
{
FileInputStream inputFile = null;
try
{
inputFile = new FileInputStream(fileName);
} catch (FileNotFoundException e)
{
System.out.println(fileName + ":" + e);
e.printStackTrace();
}
Properties props = new Properties();
InputStream in = new BufferedInputStream(inputFile);
try
{
props.load(in);
this.url = props.getProperty("url");
this.driver = props.getProperty("driver");
this.user = props.getProperty("user");
this.password = props.getProperty("password");
this.execSql = props.getProperty("sql");
} catch (IOException e)
{
System.out.println(fileName + ":" + e);
e.printStackTrace();
}
}
| 2 |
@Override
protected void readCacheSelf(Element e) throws ProblemsReadingDocumentException {
for (String key: Arrays.asList(XMLCacheDataKeys)) {
String value = e.getAttributeValue(key);
if (value==null)
value = ""; // keep existing value of same name if possible
setProperty(key,value);
}
}
| 2 |
public static String checkForCacheUpdates(boolean verbose, String currentVersion, JSONObject versionsConfig) {
if (Util.versionIsEquivalentOrNewer(currentVersion, versionsConfig.get("latestcache").toString())) {
//Jump out if the launcher is up to date
Logger.info("Updater.checkForCacheUpdates", "Cache is up to date!");
return null;
} else {
Logger.info("Updater.checkForCacheUpdates", "Updates were found!");
//Init message variable
String message = "";
//Init update queue stack
Stack<String> updateQueue = new Stack();
//Build a list of versions to install and the update messages
for (Object updateObj : (JSONArray)versionsConfig.get("cacheversions")) {
JSONObject update = (JSONObject)updateObj;
if (update.get("name").toString().equals(currentVersion)) {
//Break out of loop if the current version is reached
break;
} else {
//Add to queue
updateQueue.push(update.get("name").toString());
//Append to message
message += "Update " + update.get("name").toString() + ":\n";
for (Object messagesObj : (JSONArray)update.get("messages")) {
message += messagesObj.toString() + "\n";
}
message += "\n";
}
}
//Show the update dialog
GlobalDialogs.showUpdateNotification(message, "cache");
//Wait for the dialog result
while (DialogResult == -1);
int updateDialogResult = DialogResult;
DialogResult = -1;
if (updateDialogResult == 1) {
//Update!
if (doCacheUpdate(updateQueue, versionsConfig)) {
return versionsConfig.get("latestcache").toString();
} else {
return null;
}
} else {
return null;
}
}
}
| 7 |
public void dumpInstruction(TabbedPrintWriter writer)
throws java.io.IOException {
boolean needBrace = thenBlock.needsBraces();
writer.print("if (");
cond.dumpExpression(writer.EXPL_PAREN, writer);
writer.print(")");
if (needBrace)
writer.openBrace();
else
writer.println();
writer.tab();
thenBlock.dumpSource(writer);
writer.untab();
if (elseBlock != null) {
if (needBrace)
writer.closeBraceContinue();
if (elseBlock instanceof IfThenElseBlock
&& (elseBlock.declare == null || elseBlock.declare
.isEmpty())) {
needBrace = false;
writer.print("else ");
elseBlock.dumpSource(writer);
} else {
needBrace = elseBlock.needsBraces();
writer.print("else");
if (needBrace)
writer.openBrace();
else
writer.println();
writer.tab();
elseBlock.dumpSource(writer);
writer.untab();
}
}
if (needBrace)
writer.closeBrace();
}
| 8 |
public static void main(String[] args)
{
String str = null;
System.out.println(str.length());
}
| 0 |
public void resizeMap(int newWidth, int newHeight, int widthOffset, int heightOffset) {
setMapWidth(newWidth);
setMapHeight(newHeight);
HashMap<Point, Tile> newMap = new HashMap<Point, Tile>();
for (Point p : tileMap.keySet()) {
Tile t = tileMap.get(p);
short newX = (short) (p.getX() + widthOffset);
short newY = (short) (p.getY() + heightOffset);
if (newX >= 0 && newX < getMapWidth() && newY >= 0 && newY < getMapHeight()) {
t.setX(newX);
t.setY(newY);
newMap.put(new Point(newX, newY), t);
}
}
tileMap = newMap;
changes = true;
}
| 5 |
@After
public void tearDown() {
try
{
AqWsFactory.close(clientProxy);
}
catch(Exception ex)
{
fail("tearDown failed: " + ex.toString());
}
}
| 1 |
@Override
protected void onKick(String channel, String kickerNick, String kickerLogin, String kickerHostname, String recipientNick, String reason)
{
super.onKick(channel, kickerNick, kickerLogin, kickerHostname, recipientNick, reason);
int targettab = 0;
int i = 0;
while(true)
{
try
{
if(Main.gui.tabs.get(i).title.equalsIgnoreCase(channel) || Main.gui.tabs.get(i).title.substring(1).equalsIgnoreCase(channel))
{
targettab = i;
break;
}
else
{
i++;
}
}
catch(Exception e)
{
break;
}
}
Main.gui.tabs.get(targettab).addMessage(recipientNick + " has been kicked from " + channel + " by " + kickerNick + " [" + reason + "]");
Main.gui.tabs.get(targettab).onUpdate();
}
| 4 |
public void buildTrie(Set<String> col) {
for (String str : col) {
Trie[] trieArray = sons;
for (int i = 0; i < str.length(); ++i) {
Trie tmpTrie;
if (trieArray[str.charAt(i) - 'a'] == null) {
tmpTrie = new Trie();
tmpTrie.ch = str.charAt(i);
trieArray[str.charAt(i) - 'a'] = tmpTrie;
}
tmpTrie = trieArray[str.charAt(i) - 'a'];
if (i == str.length() - 1) {
tmpTrie.finish = true;
}
trieArray = tmpTrie.sons;
}
}
return;
}
| 4 |
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
| 2 |
public void setIdSolicitud(int idSolicitud) {
this.idSolicitud = idSolicitud;
}
| 0 |
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
| 0 |
public boolean CanBePickedUp(Item item) {
switch (direction) {
case DIR_UP:
if (mazeHeight == 1) {
return false;
}
mazeHeight--;
break;
case DIR_DOWN:
mazeHeight++;
break;
case DIR_LEFT:
if (mazeWidth == 1) {
return false;
}
mazeWidth--;
break;
case DIR_RIGHT:
mazeWidth++;
break;
}
TextBox tb = room.textBoxes.elementAt(1);
tb.textString = mazeWidth + "x" + mazeHeight;
tb.x = (560 - 12 * tb.textString.length()) / 2;
return false;
}
| 6 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
| 6 |
* @return a List of the matching meetings
*
*/
private List<Meeting> listForContact(Set<Meeting> meetingSet, Contact contact)
{
List<Meeting> list = new ArrayList<Meeting>();
for(Meeting meeting : meetingSet)
{
if(meeting.getContacts().contains(contact))
{
list.add(meeting);
}
}
return list;
}
| 2 |
public void drawCoordinateSystem(Graphics g) {
g.setColor(Color.lightGray);
g.drawLine(0, startY, PLOT_WIDTH, startY);
g.drawLine(startX, 0, startX, PLOT_HEIGHT);
for (int x = startX - (int) zoom; x > zoom; x -= (int) zoom) {
String num = "" + (x - startX) / (int) zoom;
g.drawString(num, x, startY);
}
for (int x = startX; x < PLOT_WIDTH - zoom; x += (int) zoom) {
String num = "" + (x - startX) / (int) zoom;
g.drawString(num, x, startY);
}
for (int y = startY - (int) zoom; y > zoom; y -= (int) zoom) {
String num = "" + (startY - y) / (int) zoom;
if (!num.equals("0"))
g.drawString(num, startX, y);
}
for (int y = startY; y < PLOT_HEIGHT - zoom; y += (int) zoom) {
String num = "" + (startY - y) / (int) zoom;
if (!num.equals("0"))
g.drawString(num, startX, y);
}
}
| 6 |
public MixinProxy(TwoTuple<Object, Class<?>>... pairs) {
delegatesByMethod = new HashMap<String, Object>();
for(TwoTuple<Object, Class<?>> pair : pairs) {
for(Method method : pair.second.getMethods()) {
String methodName = method.getName();
// The first interface in the map
// implements the method.
if(!delegatesByMethod.containsKey(methodName)) {
delegatesByMethod.put(methodName, pair.first);
}
}
}
}
| 5 |
public static boolean isField(Member m) {
return (m instanceof Field) || ((m instanceof LocalField)
&& !(m instanceof LocalMethod));
};
| 2 |
public static void main(String [] args){
buildOptions();
buildUI();
//scoreBoard.setHighScore(0);
//scoreBoard.setHighScore(0);
while(true) {
if(theRedButton ) {
score = 0;
wins = 0;
streak = true;
optionsDone = false;
theRedButton = false;
}
if(optionsDone && streak) {
setupGame();
centerFrame(frame);
Options.setVisible(false);
frame.setVisible(true);
gameLoop();
showWinner();
} else if (optionsDone && !streak) {
//high score thing
//HighScore is called to work here
if(scoreBoard.handleScore(score)) {
JOptionPane.showMessageDialog(frame, "Good job! You set the high score!");
}
int selection = JOptionPane.showConfirmDialog(
frame,
"Would you like to play again?",
"Game Over",
JOptionPane.YES_NO_OPTION);
if(selection == JOptionPane.NO_OPTION)
System.exit(0);
score = 0;
streak = true;
} else {
frame.setVisible(false);
Options.setVisible(true);
}
}
}
| 8 |
@SuppressWarnings("static-method")
protected String getData(Row row, Column column, boolean nullOK) {
if (row != null) {
String text = row.getDataAsText(column);
return text == null ? nullOK ? null : "" : text; //$NON-NLS-1$
}
return column.toString();
}
| 3 |
public static void main(String[] args){
try{
BufferedReader in=null;
if(args.length>0){
in = new BufferedReader(new FileReader(args[0]));
}
else{
in = new BufferedReader(new InputStreamReader(System.in));
}
ArrayList<String> input = new ArrayList<String>();
String inp = in.readLine();
while(inp!=null){
input.add(inp);
inp=in.readLine();
}
int[][] nabomatrise = new int[input.size()][input.size()];
for(int i=0; i<nabomatrise.length;i++){
Arrays.fill(nabomatrise[i], INF);
}
StringTokenizer st;
for(int i=0;i<input.size();i++){
st = new StringTokenizer((String)input.get(i));
while(st.hasMoreTokens()){
String[] oneEdge = st.nextToken().split(":");
nabomatrise[i][Integer.parseInt(oneEdge[0])]=Integer.parseInt(oneEdge[1]);
}
}
System.out.println(mst(nabomatrise));
}
catch(Exception e){
e.printStackTrace();
}
}
| 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuPrincipal.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() {
final MenuPrincipal menu = new MenuPrincipal();
menu.setVisible(true);
menu.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
| 6 |
public Optgroup(HtmlMidNode parent, HtmlAttributeToken[] attrs){
super(parent, attrs);
for(HtmlAttributeToken attr:attrs){
String v = attr.getAttrValue();
switch(attr.getAttrName()){
case "disabled":
disabled = Disabled.parse(this, v);
break;
case "label":
label = Label.parse(this, v);
break;
}
}
}
| 3 |
public void closure(Production p){
System.out.println("------------------------- Closure " + p.toString()+ " ------------------------------");
State s = new State();
List<Production> prList = new ArrayList<>();
prList.add(p);
for(int i = 0; i < prList.size(); i++){
Production prod = prList.get(i);
String elem="";
if( !prod.is_dot_last()){
elem = prList.get(i).getElementAfterDot();
}
if( !prod.is_dot_last() && !isTerminal(elem)){
if( p.left.equals("ASS") && p.dot == 2 && i == 2){
String bla;
bla = "das";
}
List<Production> l = getProductionsByLeft(prod.getElementAfterDot());
for ( Production p1: l){
if( !prList.contains(p1)){
prList.add(p1);
}
}
}
}
// prList is expanded list
s.productions.addAll(prList);
states.add(s);
}
| 9 |
public static boolean isPrime(int i) {
if (i < 2) {
return false;
} else if (i % 2 == 0 && i != 2) {
return false;
} else {
for (int j = 3; j <= Math.sqrt(i); j = j + 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
}
| 5 |
@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
if (kirjaudutaankoUlos(request)) {
kirjauduUlos(request, response);
} else if (onkoKirjautunut(request, response)) {
try {
if (Varaus.haeAjatAsiakasIdlla(getKayttaja().getId()).isEmpty()) {
request.setAttribute("varauksenTila", "Sinulla ei ole ajanvarauksia.");
} else {
if (napinPainallus("peruaika", request)) {
int id = haePeruttavanAjanId(request);
Varaus.peruAika(id);
Oirekuvaus.poistaOirekuvaus(id);
request.setAttribute("varauksenTila", "Varaus peruttu onnistuneesti.");
}
try {
List<Varaus> ajat = Varaus.haeAjatAsiakasIdlla(getKayttaja().getId());
List<Oirekuvaus> oirekuvaukset = new ArrayList<Oirekuvaus>();
for (Varaus v : ajat) {
Oirekuvaus o = Oirekuvaus.haeOirekuvausVarausIdlla(v.getId());
oirekuvaukset.add(o);
}
haeVaraustieto(request);
muunnaPaivamaaratSuomalaisiksi(request, ajat);
request.setAttribute("varaukset", ajat);
request.setAttribute("oirekuvaukset", oirekuvaukset);
} catch (Exception e) {
naytaVirheSivu("Varausten hakeminen epäonnistui.", request, response);
}
}
} catch (NamingException e) {
} catch (SQLException e) {
}
avaaSivunakyma(request, response, "omatvaraukset", "viikkoaikataulu", "hoito-ohjeet", "web/omatVaraukset.jsp");
}
}
| 8 |
public void displayStory() {
for (String[] akt : fressakte) {
Leckerbissen l1 = find(akt[0]);
Leckerbissen l2 = find(akt[1]);
if (l1 == null || l2 == null) {
System.err.println("Fressakt konnte nicht ausgeführt werden: " + akt[0] + " frisst " + akt[1]);
}
if (!(l1 instanceof Fisch)) {
System.err.println("Fressakteur ist kein Fisch: " + l1.getName());
continue;
}
Fisch fisch = (Fisch) l1;
System.out.println(l1.getName() + " versucht " + l2.getName() + " zu fressen...");
try {
fisch.fressen(l2);
System.out.println(fisch.getName() + " hat " + l2.getName() + " gefressen!");
} catch (MuellException e) {
e.printStackTrace();
System.out.println(l1.getName() + " kann keinen Müll verdauen.");
} catch (SchmecktNichtException e) {
e.printStackTrace();
System.out.println(l1.getName() + "'s Überzeugung hat den Fressakt verhindert.");
} catch (SattException e) {
e.printStackTrace();
System.out.println(l1.getName() + " möchte nichts mehr essen.");
} catch (EatYourFriendException e) {
e.printStackTrace();
System.out.println(l1.getName() + " frisst keine Freunde.");
}
}
}
| 8 |
private void setUpGeneralGraphData() {
bars = setUpBars(Database.statistics.get(categoryId).histogram);
for (Entry<Float, float[][]> allData : Database.DB_ARRAY.entrySet()) {
// get all company data (all 87 pts) for each collected set
timeSeriesCompayData.put(allData.getKey(), allData.getValue()[id]);//
}
timePath = makePathFromData(
makeListFromPointInArray(timeSeriesCompayData, categoryId),
INDIVIDUAL);
setMinMaxHistogramHighlight();
}
| 1 |
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(FormDatosInicioTurno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormDatosInicioTurno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormDatosInicioTurno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormDatosInicioTurno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FormDatosInicioTurno dialog = new FormDatosInicioTurno(new javax.swing.JFrame(), true, tipo);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
| 6 |
public void fillIt() {
while (index != -1) {
cur = pixels[index];
--index;
if (cur.y + 1 < bim.getHeight()
&& bim.getRGB(cur.x, cur.y + 1) == old) {
bim.setRGB(cur.x, cur.y + 1, fill);
++index;
pixels[index] = new Point(cur.x, cur.y + 1);
}
if (cur.y - 1 >= 0 && bim.getRGB(cur.x, cur.y - 1) == old) {
bim.setRGB(cur.x, cur.y - 1, fill);
++index;
pixels[index] = new Point(cur.x, cur.y - 1);
}
if (cur.x + 1 < bim.getWidth()
&& bim.getRGB(cur.x + 1, cur.y) == old) {
bim.setRGB(cur.x + 1, cur.y, fill);
++index;
pixels[index] = new Point(cur.x + 1, cur.y);
}
if (cur.x - 1 >= 0 && bim.getRGB(cur.x - 1, cur.y) == old) {
bim.setRGB(cur.x - 1, cur.y, fill);
++index;
pixels[index] = new Point(cur.x - 1, cur.y);
}
}
bim.flush();
}
| 9 |
public void exitGroup()
{
Object root = model.getRoot();
Object current = getCurrentRoot();
if (current != null)
{
Object next = model.getParent(current);
// Finds the next valid root in the hierarchy
while (next != root && !isValidRoot(next)
&& model.getParent(next) != root)
{
next = model.getParent(next);
}
// Clears the current root if the new root is
// the model's root or one of the layers.
if (next == root || model.getParent(next) == root)
{
view.setCurrentRoot(null);
}
else
{
view.setCurrentRoot(next);
}
mxCellState state = view.getState(current);
// Selects the previous root in the graph
if (state != null)
{
setSelectionCell(current);
}
}
}
| 7 |
public JPanelMainFrameHeader() {
super();
try {
GUIImageLoader imgLdr = new GUIImageLoader();
biHeader = imgLdr.loadBufferedImage(GUIImageLoader.GREEN_MAINFRAME_HEADER);
} catch (Exception e) {
e.printStackTrace();
}
}
| 1 |
public static void saveLifestone(String bWorld, int bX, int bY, int bZ) throws SQLException {// Block
// block
String table = Config.sqlPrefix + "Lifestones";
Connection con = getConnection();
PreparedStatement statement = null;
int success = 0;
String query = "select * from " + table + " where `world` LIKE ? AND `x` LIKE ? AND `y` LIKE ? AND `z` LIKE ? ";
statement = con.prepareStatement(query);
statement.setString(1, bWorld);
statement.setInt(2, bX);
statement.setInt(3, bY);
statement.setInt(4, bZ);
ResultSet result = statement.executeQuery();
while (result.next()) {
success = 1;
break;
}
statement.close();
if (success > 0) {
// System.out.println("mysql Lifestone already in DB!");
return;
}
if (success == 0) {
query = "INSERT INTO `" + table + "` (`world`, `x`, `y`, `z`) VALUES (?, ?, ?, ?);";
statement = con.prepareStatement(query);
statement.setString(1, bWorld);
statement.setInt(2, bX);
statement.setInt(3, bY);
statement.setInt(4, bZ);
success = statement.executeUpdate();
statement.close();
con.close();
}
con.close();
}
| 3 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String folderPath=null;
String fileName=null;
Writer writer=response.getWriter();
List<FileItem> items;
System.out.println("In FilesReciveServlet");
try {
System.out.println("inside try");
items=new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : items) {
if(item.isFormField()){
System.out.println("if block");
}
else
{
System.out.println("else block");
String fieldname=item.getString();
// System.out.println("fieldname"+fieldname);
if(fieldname.equals("uploadFIle"));
fileName=FilenameUtils.getName(item.getName());
System.out.println("fileName:"+fileName);
java.io.InputStream filecontent=item.getInputStream();
File f=new File(PATH+"/"+fileName);
if(!f.exists())
{
f.createNewFile();
}
OutputStream out=new FileOutputStream(f);
byte buf[] =new byte[1024];
int len;
while((len=filecontent.read(buf))>0)
out.write(buf,0,len);
out.close();filecontent.close();
AdbCommandUtil adbConn=new AdbCommandUtil();
adbConn.commandpushFile(fileName);
//Thread.sleep(3000);
}
}
} catch (FileUploadException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (FileAlreadyExistsException e) {
e.printStackTrace();
// TODO: handle exception
}
catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: handle exception
}
catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
| 9 |
private boolean checkCondition(Map<String, String> conditionMap,
List<ConditionBean> list) {
boolean flag = true;
for (ConditionBean conditionBean : list) {
if (conditionMap.containsKey(conditionBean.getId())
&& conditionBean.getValue().equals(ALL)) {
continue;
}
if (!conditionMap.containsKey(conditionBean.getId())) {
flag = false;
}
if (conditionMap.containsKey(conditionBean.getId())
&& !this.isSame(conditionMap, conditionBean)) {
flag = false;
}
}
return flag;
}
| 6 |
@Override
public void keyPressed(KeyEvent e)
{
map.keyPressed(e);
switch (e.getKeyCode())
{
// Floor changes. Not handled here, but tracked for re-painting:
case KeyEvent.VK_PAGE_UP:
case KeyEvent.VK_PAGE_DOWN:
break;
// Plus (or equals without shift) will zoom in
case KeyEvent.VK_PLUS:
case KeyEvent.VK_EQUALS:
case KeyEvent.VK_ADD:
if (scale < 64)
{
scale = scale * 2;
load_and_scale_images();
}
break;
// Minus will zoom out
case KeyEvent.VK_MINUS:
case KeyEvent.VK_SUBTRACT:
if (scale > 8)
{
scale = scale / 2;
load_and_scale_images();
}
break;
// All other keys do not have global drawing effects
default:
fullPaint = false;
}
repaint();
}
| 9 |
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jEditorPane1 = new javax.swing.JEditorPane();
modificarFrame = new javax.swing.JFrame();
nombre = new javax.swing.JTextField();
apellidos = new javax.swing.JTextField();
apodo = new javax.swing.JTextField();
especial = new javax.swing.JCheckBox();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
btnModificar = new javax.swing.JButton();
idLabel = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
ver = new javax.swing.JFrame();
nombre1 = new javax.swing.JTextField();
apellidos1 = new javax.swing.JTextField();
apodo1 = new javax.swing.JTextField();
especial1 = new javax.swing.JCheckBox();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
btnModificar1 = new javax.swing.JButton();
idLabel1 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
nuevo = new javax.swing.JFrame();
nombreN = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
apellidosN = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
apodoN = new javax.swing.JTextField();
especialN = new javax.swing.JCheckBox();
btnNuevo = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jLabel17 = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
buscar = new javax.swing.JFrame();
jScrollPane2 = new javax.swing.JScrollPane();
tablaBuscar = new javax.swing.JTable();
espere = new javax.swing.JDialog();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tabla = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
textBuscar = new javax.swing.JTextField();
btnBuscar = new javax.swing.JButton();
jLabel18 = new javax.swing.JLabel();
RNombre = new javax.swing.JRadioButton();
RApellidos = new javax.swing.JRadioButton();
RApodo = new javax.swing.JRadioButton();
RNumero = new javax.swing.JRadioButton();
jSeparator4 = new javax.swing.JSeparator();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jLabel2.setText("holas");
jLabel3.setText("jLabel3");
jScrollPane3.setViewportView(jEditorPane1);
modificarFrame.setName("modificar"); // NOI18N
nombre.setText("jTextField1");
nombre.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nombreActionPerformed(evt);
}
});
apellidos.setText("jTextField1");
apodo.setText("jTextField1");
especial.setText("Especial");
especial.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
especialActionPerformed(evt);
}
});
jLabel4.setText("Nombre");
jLabel5.setText("Apellidos");
jLabel6.setText("Apodo");
jButton2.setText("Cancelar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
btnModificar.setText("Guardar");
btnModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnModificarActionPerformed(evt);
}
});
idLabel.setText("jLabel7");
jLabel7.setText("Número");
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel8.setText("Ver | Modificar Cliente");
javax.swing.GroupLayout modificarFrameLayout = new javax.swing.GroupLayout(modificarFrame.getContentPane());
modificarFrame.getContentPane().setLayout(modificarFrameLayout);
modificarFrameLayout.setHorizontalGroup(
modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, modificarFrameLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addGroup(modificarFrameLayout.createSequentialGroup()
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(modificarFrameLayout.createSequentialGroup()
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(47, 47, 47))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, modificarFrameLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnModificar)
.addGap(18, 18, 18)))
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(especial)
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(modificarFrameLayout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(18, 18, 18)
.addComponent(idLabel))
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nombre)
.addComponent(apellidos)
.addComponent(apodo, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addContainerGap())
);
modificarFrameLayout.setVerticalGroup(
modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, modificarFrameLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(idLabel)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addGroup(modificarFrameLayout.createSequentialGroup()
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(modificarFrameLayout.createSequentialGroup()
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apellidos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(especial)
.addGap(18, 18, 18)
.addGroup(modificarFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(btnModificar))
.addGap(81, 81, 81))
);
ver.setName("modificar"); // NOI18N
nombre1.setText("jTextField1");
nombre1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nombre1ActionPerformed(evt);
}
});
apellidos1.setText("jTextField1");
apodo1.setText("jTextField1");
especial1.setText("Especial");
especial1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
especial1ActionPerformed(evt);
}
});
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel9.setText("Nombre");
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel10.setText("Apellidos");
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel11.setText("Apodo");
jButton4.setText("Cancelar");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
btnModificar1.setText("Guardar");
btnModificar1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnModificar1ActionPerformed(evt);
}
});
idLabel1.setText("jLabel7");
jLabel12.setText("Número");
jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel13.setText("Modificar Cliente");
javax.swing.GroupLayout verLayout = new javax.swing.GroupLayout(ver.getContentPane());
ver.getContentPane().setLayout(verLayout);
verLayout.setHorizontalGroup(
verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, verLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)
.addGroup(verLayout.createSequentialGroup()
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(verLayout.createSequentialGroup()
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(jLabel11))
.addGap(47, 47, 47))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, verLayout.createSequentialGroup()
.addComponent(btnModificar1)
.addGap(18, 18, 18)))
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton4)
.addComponent(especial1)
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(verLayout.createSequentialGroup()
.addComponent(jLabel12)
.addGap(18, 18, 18)
.addComponent(idLabel1))
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nombre1)
.addComponent(apellidos1)
.addComponent(apodo1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addContainerGap())
);
verLayout.setVerticalGroup(
verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, verLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(idLabel1)
.addComponent(jLabel12))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel11)
.addGroup(verLayout.createSequentialGroup()
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(verLayout.createSequentialGroup()
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(nombre1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apellidos1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel10))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apodo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(especial1)
.addGap(18, 18, 18)
.addGroup(verLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(btnModificar1))
.addGap(81, 81, 81))
);
jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel14.setText("Nombre");
jLabel15.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel15.setText("Apellidos");
jLabel16.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel16.setText("Apodo");
especialN.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
especialN.setText("Especial");
btnNuevo.setText("Guardar");
btnNuevo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNuevoActionPerformed(evt);
}
});
jButton7.setText("Cancelar");
jLabel17.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel17.setText("Añadir nuevo cliente");
javax.swing.GroupLayout nuevoLayout = new javax.swing.GroupLayout(nuevo.getContentPane());
nuevo.getContentPane().setLayout(nuevoLayout);
nuevoLayout.setHorizontalGroup(
nuevoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, nuevoLayout.createSequentialGroup()
.addContainerGap(42, Short.MAX_VALUE)
.addGroup(nuevoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel17)
.addComponent(especialN)
.addComponent(jLabel16)
.addComponent(jLabel15)
.addComponent(jLabel14)
.addComponent(apellidosN)
.addComponent(nombreN)
.addComponent(apodoN, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
.addGroup(nuevoLayout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(btnNuevo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton7))
.addComponent(jSeparator3))
.addGap(27, 27, 27))
);
nuevoLayout.setVerticalGroup(
nuevoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, nuevoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nombreN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apellidosN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apodoN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(especialN)
.addGap(18, 18, 18)
.addGroup(nuevoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnNuevo)
.addComponent(jButton7))
.addGap(47, 47, 47))
);
tablaBuscar.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"", "Id", "Nombre", "Apellidos", "Apodo", "Especial"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane2.setViewportView(tablaBuscar);
javax.swing.GroupLayout buscarLayout = new javax.swing.GroupLayout(buscar.getContentPane());
buscar.getContentPane().setLayout(buscarLayout);
buscarLayout.setHorizontalGroup(
buscarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buscarLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
.addContainerGap())
);
buscarLayout.setVerticalGroup(
buscarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buscarLayout.createSequentialGroup()
.addContainerGap(14, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jLabel1.setText("espere...");
javax.swing.GroupLayout espereLayout = new javax.swing.GroupLayout(espere.getContentPane());
espere.getContentPane().setLayout(espereLayout);
espereLayout.setHorizontalGroup(
espereLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(espereLayout.createSequentialGroup()
.addGap(176, 176, 176)
.addComponent(jLabel1)
.addContainerGap(197, Short.MAX_VALUE))
);
espereLayout.setVerticalGroup(
espereLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(espereLayout.createSequentialGroup()
.addGap(143, 143, 143)
.addComponent(jLabel1)
.addContainerGap(168, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tabla.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"", "Id", "Nombre", "Apellidos", "Apodo", "Especial"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
true, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tabla.getTableHeader().setReorderingAllowed(false);
tabla.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablaMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tabla);
jButton1.setText("Editar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton3.setText("Nuevo");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton5.setText("Ver");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
btnBuscar.setText("Buscar");
btnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarActionPerformed(evt);
}
});
jLabel18.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel18.setText("Buscar");
RNombre.setText("Nombre");
RApellidos.setText("Apellidos");
RApodo.setText("Apodo");
RNumero.setText("Numero");
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jSeparator4, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(RNombre)
.addGap(18, 18, 18)
.addComponent(RApellidos)
.addGap(18, 18, 18)
.addComponent(RApodo)
.addGap(24, 24, 24)
.addComponent(RNumero))
.addComponent(textBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(22, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel18)
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnBuscar))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(RNombre)
.addComponent(RApellidos)
.addComponent(RApodo)
.addComponent(RNumero))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| 0 |
public void testConstructor_ObjectStringEx2() throws Throwable {
try {
new MonthDay("T10:20:30.040+14:00");
fail();
} catch (IllegalArgumentException ex) {
// expected
}
}
| 1 |
public int[] getTouchingVoxel( int x, int y, int z ) throws UnsupportedOperationException
{
switch ( this )
{
case LEFT:
return new int[] { x - 1, y, z };
case RIGHT:
return new int[] { x + 1, y, z };
case BOTTOM:
return new int[] { x, y - 1, z };
case TOP:
return new int[] { x, y + 1, z };
case BACK:
return new int[] { x, y, z + 1 };
case FRONT:
return new int[] { x, y, z - 1 };
}
throw new UnsupportedOperationException( "Something's wrong about this face; index: " + value );
}
| 6 |
public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectFloatMap ) ) {
return false;
}
TObjectFloatMap that = ( TObjectFloatMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectFloatIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
float value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
| 8 |
public NSDictionary createDay(Date date,
String name,
List<NSDictionary> events){
NSDictionary day = new NSDictionary();
day.put("date", date);
day.put("name", name);
Integer i = 0;
for (NSDictionary nsd: events){
day.put("events" + Integer.toString(i), nsd);
i++;
}
return day;
}
| 1 |
public void setSocketOption(byte option, int value) throws IllegalArgumentException, IOException {
switch(option){
case SocketConnection.DELAY:
socket.setTcpNoDelay(option == 0);
break;
case SocketConnection.KEEPALIVE:
socket.setKeepAlive(option != 0);
break;
case SocketConnection.LINGER:
socket.setSoLinger(value != 0, value);
break;
case SocketConnection.RCVBUF:
socket.setReceiveBufferSize(value);
break;
case SocketConnection.SNDBUF:
socket.setSendBufferSize(value);
break;
default:
throw new IllegalArgumentException();
}
}
| 5 |
@Override
public void e(float sideMot, float forMot) {
if (this.passenger == null || !(this.passenger instanceof EntityHuman)) {
super.e(sideMot, forMot);
this.W = 0.5F; // Make sure the entity can walk over half slabs,
// instead of jumping
return;
}
EntityHuman human = (EntityHuman) this.passenger;
if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) {
// Same as before
super.e(sideMot, forMot);
this.W = 0.5F;
return;
}
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
// Set the entity's pitch, yaw, head rotation etc.
this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166
this.aO = this.aM = this.yaw;
this.W = 1.0F; // The custom entity will now automatically climb up 1
// high blocks
sideMot = ((EntityLiving) this.passenger).bd * 0.5F;
forMot = ((EntityLiving) this.passenger).be;
if (forMot <= 0.0F) {
forMot *= 0.25F; // Make backwards slower
}
sideMot *= 0.75F; // Also make sideways slower
float speed = 0.35F; // 0.2 is the default entity speed. I made it
// slightly faster so that riding is better than
// walking
this.i(speed); // Apply the speed
super.e(sideMot, forMot); // Apply the motion to the entity
try {
Field jump = null;
jump = EntityLiving.class.getDeclaredField("bc");
jump.setAccessible(true);
if (jump != null && this.onGround) { // Wouldn't want it jumping
// while
// on the ground would we?
if (jump.getBoolean(this.passenger)) {
double jumpHeight = 0.5D;
this.motY = jumpHeight; // Used all the time in NMS for
// entity jumping
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
| 8 |
private void createRooms() {
HashSet<String> roomPaths;
try {
roomPaths = KvReader.getKvFiles("./rooms");
} catch (IOException e){
e.printStackTrace(System.err);
return;
}
for (String s : roomPaths) {
HashMap<String, String> roomAttributes = KvReader.readFile(s);
if (roomAttributes.get("riddle") == null) {
rooms.put(roomAttributes.remove("id"), new Room(this, roomAttributes));
} else {
rooms.put(roomAttributes.remove("id"), new SpecialRoom(this, roomAttributes));
}
}
currentRoom = "Empty Room 1";
}
| 3 |
private void jMsgRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMsgRActionPerformed
jTable1.getColumnModel().getColumn(0).setCellRenderer(new CustomCellRender_Message());
jTable1.setModel(modele);
jTable1.setAutoCreateRowSorter(true);
Color c = new Color(63,70,73);
TableRowSorter<TableModel> sorter = new TableRowSorter<>(jTable1.getModel());
jScrollPane1.setBorder(null);
jTable1.setRowSorter(sorter);
jTable1.setFillsViewportHeight(true);
jTable1.setShowHorizontalLines(false);
jTable1.setShowVerticalLines(true);
JTableHeader header = jTable1.getTableHeader();
Color bgcolor = new Color(45,47,49);
Color focolor = new Color(244,244,244);
header.setBackground(bgcolor);
header.setForeground(focolor);
header.setBorder(null);
getContentPane().setBackground(c);
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
TableColumn AlignementCol;
for(int i = 0; i < modele.getColumnCount(); i++)
{
AlignementCol= jTable1.getColumnModel().getColumn(i);
AlignementCol.setCellRenderer(renderer);
}
for(int i = 0; i < modele.getColumnCount(); i++)
{
TableColumn column = jTable1.getColumnModel().getColumn(i);
column.setHeaderRenderer(new CustomCellRender());
}
//end set header border:disabled
Color HeaderColorBackground = new Color(34,168,108);
header.setBackground(HeaderColorBackground);
}//GEN-LAST:event_jMsgRActionPerformed
| 2 |
@Override
public String toString() {
return "Chunck at "+xPos+" "+zPos+" in "+parent.toString();
}
| 0 |
private static void printEllipsisRow(int width, int printWidth,
int startX) {
System.out.print("|");
if (startX > 0) // Print an extra column of "..."s at the beginning.
System.out.print("...,");
for (int x = 0; x < printWidth; x++)
System.out.print(" ... ");
if (printWidth < width) // Print an extra column of "..."s at the end.
System.out.print("...");
System.out.println("|");
}
| 3 |
public boolean evaluateDarkCheckmate(Chessboard boardToCheck)
{
Chessboard chessboardCopy = new Chessboard(boardToCheck);
Tile[][] tileBoardCopy = chessboardCopy.getBoard();
boolean isInCheckmate = false;
ArrayList<Piece> offendingPieces = new ArrayList<>();
ArrayList<Location> safeAreas = new ArrayList<>();
Piece darkKing = getDarkKing(tileBoardCopy, false);
Location darkKingLoc = darkKing.getLocation();
// ArrayList<Location> darkKingMoves;
for(int i = 0; i < BOARD_LENGTH; i++)
{
for(int j = 0; j < BOARD_LENGTH; j++)
{
if(tileBoardCopy[i][j].getPiece() != null)
{
Piece currentOffendingPiece = tileBoardCopy[i][j].getPiece();
if(evaluateDarkCheck(board))
{
//If offending piece is not same color as light king
if(currentOffendingPiece.isPieceWhite() != darkKing.isPieceWhite())
{
offendingPieces.add(currentOffendingPiece);
//Loop through array and for each location, if offending piece can't move there
//See if king can move there
//If not, checkmate
for(Piece p : offendingPieces)
{
Location potentialSafeArea = new Location(i, j);
if(chessboardCopy.testMovePiece(p.getLocation(), potentialSafeArea, tileBoardCopy))
{
safeAreas.add(potentialSafeArea);
}
}
for(Location l : safeAreas)
{
if(chessboardCopy.testMovePiece(darkKingLoc, l, tileBoardCopy))
{
System.out.println("KING IS SAFE FOR NOW");
isInCheckmate = false;
}
else
{
System.out.println("GAME OVER MAN");
isInCheckmate = true;
}
}
}
}
}
}
}
return isInCheckmate;
}
| 9 |
public Select cache(Boolean cache) {
if (cache == null) {
this.cache = null;
return this;
}
if (cache)
this.cache = Cache.SQL_CACHE;
else if (!cache)
this.cache = Cache.SQL_NO_CACHE;
return this;
}
| 3 |
public HysteresisThresholdDialog(final Panel panel){
setTitle("Hysteresis Threshold");
setBounds(1, 1, 250, 220);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width/3 - getWidth()/3, size.height/3 - getHeight()/3);
this.setResizable(false);
setLayout(null);
JPanel pan1 = new JPanel();
pan1.setBorder(BorderFactory.createTitledBorder("Lower threshold"));
pan1.setBounds(0, 0, 250, 70);
JPanel pan2 = new JPanel();
pan2.setBorder(BorderFactory.createTitledBorder("Upper threshold"));
pan2.setBounds(0, 70, 250, 70);
JLabel coordLabel1 = new JLabel("Value = ");
final JTextField lowerThresholdTextField = new JTextField("");
lowerThresholdTextField.setColumns(3);
JLabel colorLabel = new JLabel("Value = ");
final JTextField higherThresholdTextField = new JTextField("");
higherThresholdTextField.setColumns(3);
higherThresholdTextField.setAlignmentX(LEFT_ALIGNMENT);
JButton okButton = new JButton("OK");
okButton.setSize(250, 40);
okButton.setBounds(0, 140, 250, 60);
okButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
double lowerThreshold = 0;
double upperThreshold = 0;
try{
lowerThreshold = Double.valueOf(lowerThresholdTextField.getText());
upperThreshold = Double.valueOf(higherThresholdTextField.getText());
if (upperThreshold < lowerThreshold) {
throw new NumberFormatException();
}
} catch(NumberFormatException ex){
new MessageFrame("Invalid values");
return;
}
panel.setImage(ThresholdUtils.hysteresis(panel.getImage(), lowerThreshold, upperThreshold));
panel.repaint();
dispose();
}
});
pan1.add(coordLabel1);
pan1.add(lowerThresholdTextField);
pan2.add(colorLabel);
pan2.add(higherThresholdTextField);
this.add(pan1);
this.add(pan2);
this.add(okButton);
};
| 2 |
public static void save(String filename) {
File file = new File(filename);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
// png files
if (suffix.toLowerCase().equals("png")) {
try { ImageIO.write(onscreenImage, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
// need to change from ARGB to RGB for jpeg
// reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
else if (suffix.toLowerCase().equals("jpg")) {
WritableRaster raster = onscreenImage.getRaster();
WritableRaster newRaster;
newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
cm.getRedMask(),
cm.getGreenMask(),
cm.getBlueMask());
BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
try { ImageIO.write(rgbBuffer, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
else {
System.out.println("Invalid image file type: " + suffix);
}
}
| 4 |
public static void writeLargeFile(){
(new Thread() {
public void run() {
for (int i = 1; i <= 10; i++) {
StringBuffer sb = new StringBuffer();
for (int j = 0; j < 100000; j++) {
sb.append("chris");
}
FileProcess.write("demo" + i + ".txt", sb.toString());
}
}
}).start();
}
| 2 |
public static void main(String[] args) {
Cube cube;
if (args.length <= 0) {
cube = new Cube("input/valid_input1.txt");
} else {
cube = new Cube(args[0]);
}
Boolean validCube = Cube.verifyCube(cube.state);
if (validCube) {
boolean verbose = false;
if (args.length > 1) {
verbose = Boolean.parseBoolean(args[1]);
}
String result = IDAStar.performIDAStar(cube.state, verbose);
System.out.println(result);
} else {
System.out.println("This cube is not valid");
}
}
| 3 |
@Override
public void keyReleased(KeyEvent arg0) {
int code = arg0.getKeyCode();
if(code < 0 || code >= keys.length)return;
keys[code] = false;
}
| 2 |
public GlyphText addText(String cid, String unicode, float x, float y, float width) {
// keep track of the text total bound, important for shapes painting.
// IMPORTANT: where working in Java Coordinates with any of the Font bounds
float w = width;//(float)stringBounds.getWidth();
float h = (float) (font.getAscent() + font.getDescent());
if (h <= 0.0f) {
h = (float) (font.getMaxCharBounds().getHeight());
}
if (w <= 0.0f) {
w = (float) font.getMaxCharBounds().getWidth();
}
// zero height will not intersect with clip rectangle
// todo: test if this can occur, might be legacy code from old bug...
if (h <= 0.0f) {
h = 1.0f;
}
if (w <= 0.0f) {
w = 1.0f;
}
Rectangle2D.Float glyphBounds =
new Rectangle2D.Float(x, y - (float) font.getAscent(), w, h);
// add bounds to total text bounds.
bounds.add(glyphBounds);
// create glyph and normalize bounds.
GlyphText glyphText =
new GlyphText(x, y, glyphBounds, cid, unicode);
glyphText.normalizeToUserSpace(graphicStateTransform);
glyphTexts.add(glyphText);
return glyphText;
}
| 4 |
private void newServer() {
// status
BTServerStateListener serverStateListener = new BTServerStateListenerImpl(
serverUI);
// recv
BTObservableHandlerListenerImpl handlerListener = new BTObservableHandlerListenerImpl(
serverUI);
BTObservableHandlerFactory handlerFactory = new BTObservableHandlerFactory(
handlerListener);
bt_server = new BTServer(handlerFactory, serverUI.getBluetoothService());
bt_server.getBTServerState().addListener(serverStateListener);
try {
bt_server.init();
bt_server.listen();
} catch (ServerAlreadyStartedException e) {
e.printStackTrace();
serverUI.addStatus(e.getMessage());
}
}
| 1 |
public double getFruitProbs(int pos, int fruits, int score)
{
double prob = 0.0, innerprob, curprob;
if(pos == length - 1)
{
if(fruits <= distribution[pos] && score == fruits)
prob = 1.0;
}
else
{
for(int i = 0, s = 0; (i <= fruits) && (s <= score) && (i <= distribution[pos]); i++, s = s + (length - pos))
{
if(fruits - i <= (numfruits * choicesleft) - distsum[pos])
{
if(fruitproblist[pos + 1][fruits - i][score - s] < -0.1)
{
innerprob = getFruitProbs(pos + 1, fruits - i, score - s);
fruitproblist[pos + 1][fruits - i][score - s] = innerprob;
}
else
innerprob = fruitproblist[pos + 1][fruits - i][score - s];
curprob = combinationlist[distribution[pos]][i] * combinationlist[(numfruits * choicesleft) - distsum[pos]][fruits - i] / combinationlist[(numfruits * choicesleft) - distsum[pos] + distribution[pos]][fruits];
prob += curprob * innerprob;
}
}
}
return prob;
}
| 8 |
private Node putRoot(Node x, Key key, Value value)
throws DuplicateKeyException {
if (x == null)
return new Node(key, value, 1);
int cmp = key.compareTo(x.key);
if (cmp == 0)
throw new DuplicateKeyException();
else if (cmp < 0) {
x.left = putRoot(x.left, key, value);
x = rotateRight(x);
} else if (cmp > 0) {
x.right = putRoot(x.right, key, value);
x = rotateLeft(x);
}
x.count = 1 + size(x.left) + size(x.right);
return x;
}
| 4 |
public void update(long delta) {
time += delta;
if (time > nextFruitTime && !stopped) {
nextFruitTime = rate.getTime();
time = 0;
Transform3D t3dOffset = new Transform3D();
int x = rand.nextInt(xGridCount);
int y = rand.nextInt(yGridCount);
t3dOffset.setTranslation(new Vector3d(xgrid[x][y], ygrid[x][y], 0.25));
Fruit fruit = factory.getFruit();
fruit.setCollisionListner(runner);
fruit.setTranslation(t3dOffset);
BranchGroup bg = new BranchGroup();
bg.setCapability(TransformGroup.ENABLE_COLLISION_REPORTING);
bg.setCapability(TransformGroup.ENABLE_PICK_REPORTING);
bg.setCapability(BranchGroup.ALLOW_DETACH);
detector = new CollisionDetector(bg);
bg.addChild(fruit.getFallingAnimation());
bg.addChild(detector);
fruit.registerWithShaker(shaker);
fruit.setBranchGroup(bg);
fruit.regisetWithCollisionDetector(detector);
// Shadow
BranchGroup shadowBg = new BranchGroup();
shadowBg.setCapability(BranchGroup.ALLOW_DETACH);
SphereObject s = new SphereObject(0.01f);
FakeShadow fs = new FakeShadow((GeometryArray) s.getGeometry(), new Color3f(0.2f, 0.2f, 0.2f));
Transform3D fruitShadowT3D = new Transform3D();
fruitShadowT3D.setTranslation(new Vector3d(xgrid[x][y], ygrid[x][y], 0.001));
fruitShadowT3D.setRotation(new AxisAngle4d(1.0, 0.0, 0.0, Math.PI/2));
fs.getTransformGroup().setTransform(fruitShadowT3D);
shadowBg.addChild(fs);
fruit.addShadow(shadowBg);
runner.addFruit(bg);
runner.addShadow(shadowBg);
fruits.add(fruit);
}
for(Iterator<Fruit> it = fruits.iterator(); it.hasNext(); )
{
Fruit fruit = it.next();
fruit.update();
if(fruit.getDeleteFruit())
{
BranchGroup b = fruit.getBranchGroup();
BranchGroup shadowBg = fruit.getShadow();
it.remove();
runner.removeFruit(b);
runner.removeShadow(shadowBg);
}
}
}
| 4 |
public Map<String, String> userJobList(int uid) {
Map<String, String> jobList = new HashMap<String, String>();
// fetch related data from database
String sql = "select u_clubs,u_clubs_level from user where uid=" + uid;
// parse the data
Map<?, ?> map = (Map<?, ?>) (Object) querySql(sql).get(0);
String clubData = map.get("u_clubs").toString();
String jobData = map.get("u_clubs_level").toString();
if (clubData.equals("") || jobData.equals("")) // well, in case...
{ System.out.println("NULL");return null;}
System.out.println("clubData:" + clubData);
int[] clubs = format.transformString2IntegerArray(clubData, ",");
int[] jobs = format.transformString2IntegerArray(jobData, ","); // ATTENTION: mutilated job is not ready
for (int i=0; i<clubs.length; i++) {
// fetch different clubs' title
sql = "select club.cid,job.jo_name" +
" from club inner join job on job.joid=" + jobs[i] + " where club.cid=" + clubs[i];
map = (Map<?, ?>) (Object) querySql(sql).get(0);
// push in
jobList.put(map.get("cid").toString(), map.get("jo_name").toString());
}
return jobList;
}
| 9 |
private static PrinterResolution extractFromResolutionString(String buffer) {
if (buffer != null && buffer.length() > 0) {
int sep = buffer.indexOf('x');
int x;
int y;
if (sep != -1 && sep < buffer.length() - 1) {
x = Numbers.getInteger(buffer.substring(0, sep), 0);
y = Numbers.getInteger(buffer.substring(sep + 1), 0);
} else {
x = Numbers.getInteger(buffer, 0);
y = x;
}
if (x < 1 || y < 1) {
return null;
}
return new PrinterResolution(x, y, 1);
}
return null;
}
| 6 |
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int a = e.getWheelRotation();
if (a < 0) {
for(int i = 0; i < -a; i++) {
keys[KeyEvent.VK_UP] = true;
updateStatus();
keys[KeyEvent.VK_UP] = false;
}
}
else if (a > 0) {
for(int i = 0; i < a; i++) {
keys[KeyEvent.VK_DOWN] = true;
updateStatus();
keys[KeyEvent.VK_DOWN] = false;
}
}
}
| 4 |
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
if (args.length==0) {
String[] text = new String[] {
"§a§lJoin a team",
"§9§lBLUE §8- §e§l"+Blue.getSize(),
"§a§lGREEN §8- §e§l"+ Green.getSize(),
"§e§lYELLOW §8- §e§l"+ Yellow.getSize(),
"§c§lRED §8- §e§l"+ Red.getSize()
};
sender.sendMessage(text);
return true;
} else {
String team = args[0];
if (!(sender instanceof Player)) {
sender.sendMessage(Core.getPrefix()+"§4You cannot join a team unless you are a player!");
return true;
}
Player player = (Player) sender;
if (team.equalsIgnoreCase("blue")) {
Team.addMember(player);
player.sendMessage(Core.getPrefix()+"§6You joined §9§lBLUE§6.");
return true;
} else if (team.equalsIgnoreCase("green")) {
return true;
} else if (team.equalsIgnoreCase("yellow")) {
return true;
} else if (team.equalsIgnoreCase("red")) {
return true;
} else {
sender.sendMessage(Core.getPrefix()+"§4Unknown team. Do §c/join §4for a list of teams.");
return true;
}
}
}
| 6 |
public void stopDecryptingHands() {
try {
decryptSub.remove();
decryptionCount = 0;
} catch (Exception e) {
// do nothing
}
decryptSub = null;
}
| 1 |
private static DataSet[][][] aggregateTraces(String[] nodeClasses,
String[] approaches, String[] metrics) {
DataSet[][][] allData = new DataSet[nodeClasses.length][approaches.length][metrics.length];
for(int i = 0; i < nodeClasses.length; i++) {
// VirtuaTraces
String[] virtuaTracesBaseDirs = {
"/media/embs/Data/VirtuaSimulationOptFIVNMPs/",
"/media/embs/Data/VirtuaSimulationSharingNodesOptFIVNMPs"
};
for(int a = 0; a < virtuaTracesBaseDirs.length; a++) {
File baseDir = new File(virtuaTracesBaseDirs[a]);
DataSet[] metricsData = new DataSet[metrics.length];
for(int x = 0; x < metricsData.length; x++) {
metricsData[x] = new DataSet();
}
for(int j = 0; j < 30; j++) {
VirtuaSimulatorTraceReader reader = new VirtuaSimulatorTraceReader();
reader.readTrace(baseDir.getAbsolutePath() + "/eu_" +
nodeClasses[i] + "_" + j + "_prob_simulation.txt");
for(int k = 0; k < metrics.length; k++) {
metricsData[k].addValue((Double) reader.get(metrics[k]));
}
}
allData[i][a] = metricsData;
}
// ViNETraces
String[] approachesNames = { "HRA", "HRASharingNodes", "", ".dvine" };
for(int a = 2; a < approachesNames.length; a++) {
String approach = approachesNames[a];
File baseDir = new File("/media/embs/Data/OptFIVNMP_Instances_ViNE_format/" +
nodeClasses[i]);
DataSet[] metricsData = new DataSet[metrics.length];
for(int x = 0; x < metricsData.length; x++) {
metricsData[x] = new DataSet();
}
for(int j = 0; j < 30; j++) {
ViNEYardTraceReader reader = new ViNEYardTraceReader();
String s = baseDir.getAbsolutePath() + "/eu_" + nodeClasses[i] + "_" +
j + "_prob/";
reader.readTrace(s + "MySimINFOCOM2009" + approach + ".out",
s + "time" + approach + ".out");
reader.readMappings(s + "sub.txt", s + "requests",
s + "mappings" + approach + ".out");
for(int k = 0; k < metrics.length; k++) {
metricsData[k].addValue((Double) reader.get(metrics[k]));
}
}
allData[i][a] = metricsData;
}
}
return allData;
}
| 9 |
public void play(Channel c) {
if (!active(GET, XXX)) {
if (toLoop)
toPlay = true;
return;
}
if (channel != c) {
channel = c;
channel.close();
}
// change the state of this source to not stopped and not paused:
stopped(SET, false);
paused(SET, false);
}
| 3 |
private static void playres(Resource res) {
Collection<Resource.Audio> clips = res.layers(Resource.audio);
int s = (int)(Math.random() * clips.size());
Resource.Audio clip = null;
for(Resource.Audio cp : clips) {
clip = cp;
if(--s < 0)
break;
}
play(clip.clip);
}
| 2 |
public static DelayCodeEnum fromValue(String v) {
for (DelayCodeEnum c: DelayCodeEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
| 2 |
ArrayList<Stack<String>> join(boolean[][] res, int begin, String s,
HashMap<Integer, ArrayList<Stack<String>>> dp) {
int n = s.length();
ArrayList<Stack<String>> resArr = new ArrayList<Stack<String>>();
if (begin == n) {
resArr.add(new Stack<String>());
return resArr;
}
if (dp.containsKey(begin))
return dp.get(begin);
for (int i = begin; i < n; i++) {
if (res[begin][i]) {
ArrayList<Stack<String>> arr = join(res, i + 1, s, dp);
String str = s.substring(begin, i + 1);
for (Stack<String> sta : arr) {
Stack<String> tmp = (Stack<String>) sta.clone();
tmp.push(str);
resArr.add(tmp);
}
}
}
dp.put(begin, resArr);
return resArr;
}
| 5 |
private void calculateBalance(){
int[] rowWeights = ((CargoLifter) getWorld()).getRowWeights();
int weightTop = 0;
int weightBottom = 0;
weightDifference = 0;
for(int i = 0; i < rowWeights.length / 2; i++)
weightTop += rowWeights[i];
for(int i = rowWeights.length / 2; i < rowWeights.length; i++)
weightBottom += rowWeights[i];
weightDifference = weightTop - weightBottom;
if(weightDifference >= MAX_DIF || weightDifference <= (-MAX_DIF))
((CargoLifter) getWorld()).loseGame();
}
| 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.