method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
61ac218a-da8b-4fa7-aa0f-a56c99089b9f | 5 | public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer,Integer> aux=new HashMap<>();
for(int i : nums){
Integer cnt=0;
if(aux.containsKey(i)) cnt=aux.get(i);
aux.put(i,++cnt);
}
PriorityQueue<Node> priorityQueue=new PriorityQueue<>();
for(Map.Entry<Integer,Integer> entry : aux.entrySet()){
priorityQueue.add(new Node(entry.getKey(),entry.getValue()));
if(priorityQueue.size()>k) priorityQueue.poll();
}
List<Integer> result=new ArrayList<>();
for(Node n : priorityQueue) result.add(n.i);
return result;
} |
12b7d2e2-cfd4-4b15-b409-c56a41225113 | 5 | public ArrayList<Device> findDeviceByPower(int minPower, int maxPower) throws LogicException{
if (minPower > maxPower) {
LOG.error("Wrong searching options");
throw new LogicException("ERROR Min value can not be bigger then Max value");
}
ArrayList<Device> foundDevices = new ArrayList<Device>();
for (Device device : devicesInHouse) {
if (device.getPower() >= minPower && device.getPower() <= maxPower) {
LOG.info(device + "has been found");
foundDevices.add(device);
}
}
if (foundDevices.isEmpty()) {
LOG.info("No Devices were found");
return foundDevices;
} else {
return foundDevices;
}
} |
f0ca57c8-a4a8-4dbe-8d26-0c0b93b26be1 | 0 | public EditorPane getEditorPane() {
return editorPane;
} |
20a26f2e-718e-4ee4-afad-a753a03ff605 | 1 | String dblfmt(double[] d) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < d.length - 1; i++) {
b.append(String.format(Locale.US, fformat, d[i]));
b.append(',');
}
b.append(String.format(Locale.US, fformat, d[d.length - 1]));
return b.toString();
} |
31bc086f-c127-4f8e-9285-756b8e3b1356 | 4 | boolean isNextToARobot(Robot r, int x, int y) {
synchronized (robots) {
for (Robot robot : robots)
if (robot != r && robot.getX() == x && robot.getY() == y)
return true;
return false;
}
} |
ba18b5ea-d5b6-4528-8b2a-ea65b78363ed | 3 | @Override
public void loadReader(String name, Reader reader)
throws LevelLoaderException {
filename = name;
try {
xmlreader.parse(new InputSource(reader));
}
catch (SAXException e) {
throw new LevelLoaderException(e);
}
catch (IOException e) {
throw new LevelLoaderException(e);
}
catch (NumberFormatException e) {
throw new LevelLoaderException(e);
}
} |
99dd7f91-caf6-45e4-89f8-fd825a9b72c8 | 4 | public Zone getZone(int x, int y) throws OutOfBoundsException{
if (x < 0 || x >= this.width || y < 0 || y >= this.height)
throw new OutOfBoundsException();
return this.zones[x][y];
} |
e094333e-e31d-4ecf-b4fe-60fc034c98f7 | 8 | int depthFirstCutValue(Edge edge, int count) {
Node n = getTreeTail(edge);
setTreeMin(n, count);
int cutvalue = 0;
int multiplier = (edge.target == n) ? 1 : -1;
EdgeList list;
list = n.outgoing;
Edge e;
for (int i = 0; i < list.size(); i++) {
e = list.getEdge(i);
if (e.tree && e != edge) {
count = depthFirstCutValue(e, count);
cutvalue += (e.cut - e.weight) * multiplier;
} else {
cutvalue -= e.weight * multiplier;
}
}
list = n.incoming;
for (int i = 0; i < list.size(); i++) {
e = list.getEdge(i);
if (e.tree && e != edge) {
count = depthFirstCutValue(e, count);
cutvalue -= (e.cut - e.weight) * multiplier;
} else {
cutvalue += e.weight * multiplier;
}
}
edge.cut = cutvalue;
if (cutvalue < 0)
spanningTree.add(edge);
setTreeMax(n, count);
return count + 1;
} |
61500f73-68ad-4d88-8ba9-cc2b8a5c4dcd | 0 | public static OthelloBoardBinary getInitialBoard(){
OthelloBoardBinary board = new OthelloBoardBinary();
// FOLLOWING BINARIES REPRESENT INITIAL BOARD CONDITION
board.binHasDisk = 0x00_00_00_18_18_00_00_00l;
board.binIsBlack = 0x00_00_00_08_10_00_00_00l;
board.isBattingFirstTurn = true;
return board;
} |
54f5df77-0348-4d86-b52a-527e17f24872 | 4 | private void reportPath(String title, Route path) {
I.add(""+title+": ") ;
if (path == null) I.add("No path.") ;
else {
I.add("Route length: "+path.path.length+"\n ") ;
int i = 0 ; for (Tile t : path.path) {
I.add(t.x+"|"+t.y+" ") ;
if (((++i % 10) == 0) && (i < path.path.length)) I.add("\n ");
}
}
I.add("\n") ;
} |
9e5e54c8-c79c-42ec-a12b-07969cb1fb6c | 5 | public final WaiprParser.stat_return stat() throws RecognitionException {
WaiprParser.stat_return retval = new WaiprParser.stat_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
ParserRuleReturnScope globalstat54 =null;
ParserRuleReturnScope localstat55 =null;
try {
// Waipr.g:46:6: ( globalstat | localstat )
int alt15=2;
int LA15_0 = input.LA(1);
if ( (LA15_0==14) ) {
alt15=1;
}
else if ( (LA15_0==ID) ) {
alt15=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 15, 0, input);
throw nvae;
}
switch (alt15) {
case 1 :
// Waipr.g:46:8: globalstat
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_globalstat_in_stat358);
globalstat54=globalstat();
state._fsp--;
adaptor.addChild(root_0, globalstat54.getTree());
}
break;
case 2 :
// Waipr.g:47:4: localstat
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_localstat_in_stat363);
localstat55=localstat();
state._fsp--;
adaptor.addChild(root_0, localstat55.getTree());
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} |
ac62957d-19c0-4dce-91d4-b2c535ce9879 | 0 | public static void g() throws MyException {
System.out.println("Throwing MyException from g()");
throw new MyException("Originated in g()");
} |
186f1bbd-31d8-4f92-9d97-c095d84b529e | 4 | private void refreshModel(DefaultListModel model) {
if (model.equals(guestModel)) {
ArrayList<Guest> guestList;
guestList = ctr.getGuestsFromDB();
guestModel.clear();
for (int i = 0; i < guestList.size(); i++) {
guestModel.addElement(guestList.get(i));
}
guestJList.setModel(guestModel);
guestJList2.setModel(guestModel);
}
if (model.equals(bookingDetailModel)) {
bookingDetailModel.clear();
ArrayList<Guest> roomGuestList;
roomGuestList = ctr.getBookingDetailsFromDB(ctr.getCurrentBooking());
for (int i = 0; i < roomGuestList.size(); i++) {
bookingDetailModel.addElement(roomGuestList.get(i));
}
bookingDetailsJList.setModel(bookingDetailModel);
}
} |
7691fdac-bbd3-4181-be72-7ece1ba30829 | 4 | public static Data data(String value)
{
Data data = null;
if (value.length() > 0)
{
if (value.charAt(0) == '[')
{
String content = value.substring(1, value.length() - 1);
try
{
int number = Integer.parseInt(content);
data = new Pointer(new Value(number));
}
catch (NumberFormatException e)
{
data = new Pointer(new RegisterAccess(content));
}
}
else
{
try
{
int number = Integer.parseInt(value);
data = new Value(number);
}
catch (NumberFormatException e)
{
data = new RegisterAccess(value);
}
}
}
return data;
} |
0b9445b3-5f64-47f4-9433-20b23d5ac924 | 3 | @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txCodigo = new javax.swing.JTextField();
txNome = new javax.swing.JTextField();
txEndereco = new javax.swing.JTextField();
txCidade = new javax.swing.JTextField();
txEstado = new javax.swing.JTextField();
PainelSuperior = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
PainelInferior = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
btSalvar = new javax.swing.JButton();
Deletar = new javax.swing.JButton();
jLabel12 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txRg = new javax.swing.JTextField();
txDataNascimento = new javax.swing.JFormattedTextField();
jLabel9 = new javax.swing.JLabel();
cbConvenio = new javax.swing.JComboBox();
txTelefone = new javax.swing.JFormattedTextField();
txCelular = new javax.swing.JFormattedTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Nome Completo.:");
jLabel2.setText("Codigo.:");
jLabel3.setText("Telefone.:");
jLabel4.setText("Celular.:");
jLabel5.setText("Endereço.:");
jLabel6.setText("Cidade.:");
jLabel7.setText("Estado.:");
txCodigo.setEditable(false);
txCodigo.setEnabled(false);
txNome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txNomeActionPerformed(evt);
}
});
PainelSuperior.setBackground(new java.awt.Color(0, 153, 153));
jLabel10.setText("Paciente");
javax.swing.GroupLayout PainelSuperiorLayout = new javax.swing.GroupLayout(PainelSuperior);
PainelSuperior.setLayout(PainelSuperiorLayout);
PainelSuperiorLayout.setHorizontalGroup(
PainelSuperiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PainelSuperiorLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
PainelSuperiorLayout.setVerticalGroup(
PainelSuperiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PainelSuperiorLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10)
.addContainerGap(75, Short.MAX_VALUE))
);
PainelInferior.setBackground(new java.awt.Color(0, 153, 153));
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/model/images/Java.png"))); // NOI18N
javax.swing.GroupLayout PainelInferiorLayout = new javax.swing.GroupLayout(PainelInferior);
PainelInferior.setLayout(PainelInferiorLayout);
PainelInferiorLayout.setHorizontalGroup(
PainelInferiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelInferiorLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11)
.addContainerGap())
);
PainelInferiorLayout.setVerticalGroup(
PainelInferiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelInferiorLayout.createSequentialGroup()
.addContainerGap(65, Short.MAX_VALUE)
.addComponent(jLabel11)
.addContainerGap())
);
btSalvar.setText("Salvar");
btSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSalvarActionPerformed(evt);
}
});
Deletar.setText("Deletar");
Deletar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeletarActionPerformed(evt);
}
});
jLabel12.setText("Data de nascimento.:");
jLabel8.setText("RG.:");
try {
txDataNascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jLabel9.setText("Convenio.:");
try {
txTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
try {
txCelular.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PainelSuperior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PainelInferior, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(241, 241, 241)
.addComponent(btSalvar)
.addGap(29, 29, 29)
.addComponent(Deletar))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txEndereco, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(txEstado))
.addGap(117, 117, 117)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel9)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(txCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(txNome, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txCelular, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel8)
.addComponent(jLabel12))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txRg, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(cbConvenio, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(139, 139, 139))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(PainelSuperior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel8)
.addComponent(txRg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel12)
.addComponent(txDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txCelular, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(cbConvenio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(txCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(txEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btSalvar)
.addComponent(Deletar))
.addGap(44, 44, 44)
.addComponent(PainelInferior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents |
783cc1af-2c1a-476c-9e66-da8b0f2c215c | 3 | private void readStateMove(State[] states, BufferedReader reader)
throws IOException {
for (int i = 0; i < states.length; i++) {
int x, y;
String[] tokens = reader.readLine().split("\\s+");
try {
x = Integer.parseInt(tokens[1]);
y = Integer.parseInt(tokens[2]);
} catch (NumberFormatException e) {
throw new ParseException("State " + (i + 1)
+ "'s position badly formatted.");
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException("State " + (i + 1)
+ "'s position string too short.");
}
states[i].getPoint().setLocation(x, y);
}
} |
3fc167e5-c06a-4cd4-bfab-81e784704842 | 7 | public void paintComponent(Graphics g) {
synchronized (LiveSystemCopyMutex) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillRect(0, 0, panelWidth, panelHeight);
List<Ship> ships = paintLS.ships;
PlayerShip hero = paintLS.hero;
List<Projectile> projectiles = paintLS.projectiles;
ArrayList<Dust> dust = paintLS.dust;
ArrayList<Star> stars = paintLS.stars;
int thisSystemWidth = paintLS.thisSystemWidth;
int thisSystemHeight = paintLS.thisSystemHeight;
// Draw stars and dust.
for (Star s : stars) {
g2d.setColor(s.color);
g2d.fillOval((int) (s.x + panelWidth / 2),
(int) (-(s.y) + panelHeight / 2), s.diam, s.diam);
}
for (Dust s : dust) {
g2d.setColor(s.color);
g2d.fillOval((int) (s.x + panelWidth / 2),
(int) (-(s.y) + panelHeight / 2), s.diam, s.diam);
}
// Draw ships and weapons.
AffineTransform origXform;
AffineTransform newXform;
int xRot;
int yRot;
int frameX;
int frameY;
for (Ship s : ships) {
origXform = g2d.getTransform();
newXform = (AffineTransform)(origXform.clone());
// The center of rotation is the position of the object in
// the panel.
xRot = ((int) s.x) + panelWidth / 2;
yRot = -((int) s.y) + panelHeight / 2;
newXform.rotate(-s.angle, xRot, yRot);
g2d.setTransform(newXform);
// Position at which to draw in the panel.
frameX = ((int) s.x) + panelWidth / 2
- s.origObjImg.getWidth(this)/2;
frameY = -((int) s.y) + panelHeight / 2
- s.origObjImg.getHeight(this)/2;
// Draw rotated image.
g2d.drawImage(s.origObjImg, frameX, frameY, this);
g2d.setTransform(origXform);
}
for (Projectile w : projectiles) {
g2d.setColor(Color.yellow);
g2d.fillOval((int) (w.x + panelWidth / 2 - w.diam / 2),
(int) (-(w.y) + panelHeight / 2 - w.diam / 2),
w.diam, w.diam);
}
if (hero.status == ShipStatus.ALIVE) {
// Position at which to draw in the panel.
frameX = ((int) hero.x) + panelWidth / 2
- hero.spriteWidth/2;
frameY = -((int) hero.y) + panelHeight / 2
- hero.spriteHeight/2;
// Draw image.
g2d.drawImage(hero.sprite, frameX, frameY, this);
} else if (hero.status == ShipStatus.DYING) {
origXform = g2d.getTransform();
newXform = (AffineTransform)(origXform.clone());
// The center of rotation is the position of the hero in
// the panel.
xRot = ((int) hero.x) + panelWidth/2;
yRot = -((int) hero.y) + panelHeight/2;
newXform.rotate(-hero.angle, xRot, yRot);
g2d.setTransform(newXform);
// Position at which to draw in the panel.
frameX = ((int) hero.x) + panelWidth / 2
- hero.origObjImg.getWidth(this)/2;
frameY = -((int) hero.y) + panelHeight / 2
- hero.origObjImg.getHeight(this)/2;
// Draw rotated image.
g2d.drawImage(hero.origObjImg, frameX, frameY, this);
g2d.setTransform(origXform);
}
// Paint sidebar.
g2d.setColor(Color.black);
g2d.fillRect(panelWidth, 0, sideMenuWidth, panelHeight);
g2d.setColor(new Color(0xFF808080));
g2d.fillRect(panelWidth, 0, hudDividerWidth, panelHeight);
// Paint minimap.
g2d.setColor(Color.red);
g2d.drawRect(panelWidth + hudDividerWidth + mapMargin - 1,
mapMargin - 1, mapWidth + 2, mapWidth + 2);
for (Ship s : ships) {
// This if statement is extra for later.
// if (s.isHostile)
g2d.setColor(Color.red);
// else
// g2d.setColor(Color.green);
g2d.fillOval(((int) (s.x * (double) mapWidth / (double) thisSystemWidth) + (mapWidth / 2) + panelWidth + mapMargin + hudDividerWidth) - 1,
-((int) (s.y * (double) mapWidth / (double) thisSystemHeight)) + (mapWidth / 2) + mapMargin - 1,
3, 3);
}
g2d.setColor(Color.blue);
g2d.fillOval((int) (hero.x * (double) mapWidth / (double) thisSystemWidth) + (mapWidth / 2) + panelWidth + mapMargin + hudDividerWidth - 1,
-((int) (hero.y * (double) mapWidth / (double) thisSystemHeight)) + (mapWidth / 2) + mapMargin - 1,
3, 3);
// Paint rectangle around visible field on minimap.
g2d.setColor(new Color(0x00C000));
g2d.drawRect((int) ((-panelWidth / 2) * (double) mapWidth / (double) thisSystemWidth) + (mapWidth / 2) + panelWidth + mapMargin + hudDividerWidth, -((int) ((panelHeight / 2) * (double) mapWidth / (double) thisSystemHeight)) + (mapWidth / 2) + mapMargin, (int) (panelWidth * (double) mapWidth / (double) thisSystemWidth), (int) (panelHeight * (double) mapWidth / (double) thisSystemHeight));
// Paint health bar.
g2d.setColor(new Color(0x3D75B8));
g2d.fillRect(panelWidth + hudDividerWidth + mapMargin - 1,
mapMargin + mapWidth + 5,
(mapWidth + 3) * hero.structInteg / hero.maxStructInteg,
20);
}
} |
93fcaced-0aff-4298-8fc9-4a3811d895be | 7 | public Main(final File file) {
try {
jmdns = JmDNS.create();
} catch (IOException e1) {
e1.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
mainFrame = new MainGUI();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
if (file != null && file.canRead()) {
mainFrame.actionOpenOld(file);
}
}
});
} |
e0b5fa5c-62f6-4d82-b82d-7bb303f84dbd | 0 | protected void onRemoveChannelBan(String channel, String sourceNick, String sourceLogin, String sourceHostname, String hostmask) {} |
91341700-1883-415f-8a77-3143f2339bdb | 1 | public void removeOnetimeLocals() {
StructuredBlock[] subBlocks = getSubBlocks();
for (int i = 0; i < subBlocks.length; i++)
subBlocks[i].removeOnetimeLocals();
} |
e22b09f5-be0f-40fe-b41d-34a420555ac5 | 8 | private void calculate() throws Exception {
//Get B
Matrix diagonalizedMatrix = matrix.transpose().copy().times(matrix.copy()).copy();
//Diagonalize B
EigenvalueDecomposition ed = new EigenvalueDecomposition(diagonalizedMatrix);
//Get eigenvalues and sort them into ArrayLists
double[] eigenValues = ed.getRealEigenvalues();
ArrayList<Double> unsortedEigenValues = new ArrayList<Double>();
for (int i = 0 ; i < eigenValues.length ; i++)
unsortedEigenValues.add(eigenValues[i]);
//Get eigenvectors
ArrayList<Matrix> unsortedEigenVectors = getColumns(ed.getV().copy());
//Romove the non-strictly-positive eigenvalues and their corresponding eigenvectors
for (int i = 0 ; i < unsortedEigenValues.size() ; i++) {
if (unsortedEigenValues.get(i) <= 0) {
unsortedEigenValues.remove(i);
unsortedEigenVectors.remove(i);
}
}
//Put the ArrayLists into a TreeMap
Comparator<Double> c = Collections.reverseOrder();
TreeMap<Double , Matrix> sortedMap = new TreeMap<Double , Matrix>(c);
for (int i = 0 ; i < unsortedEigenValues.size() ; i++)
sortedMap.put(Double.valueOf(unsortedEigenValues.get(i)) , unsortedEigenVectors.get(i).copy());
//Retrieve sorted eigenvalues and add them square-rooted to d
Iterator<Double> evalues = sortedMap.keySet().iterator();
while (evalues.hasNext()) {
double evalue = evalues.next().doubleValue();
d.add(Double.valueOf(Math.sqrt(evalue)));
}
//Retrieve sorted eigenvectors and add them unit-vectored to u
Iterator<Matrix> evectors = sortedMap.values().iterator();
while (evectors.hasNext()) {
Matrix evector = evectors.next().copy();
u.add(getUnitMatrix(evector).copy());
}
//Set v, d and u
Matrix uCombined = combineColumns(u).copy();
Matrix dCombined = getDiagonalizedMatrix(d).copy();
Matrix vCombined = matrix.copy().times(uCombined).copy().times(dCombined.inverse().copy()).copy();
v = getColumns(vCombined);
//Check if rank exceeds d's dimension
if (rank > d.size())
throw new Exception("Rank " + rank + " is higher than the maximum number of eigenvalues "
+ d.size() + "!");
//Get ranked matrix
for (int i = 0 ; i < (rank - 1) ; i++) {
Matrix currentRanked = v.get(i).copy().times(u.get(i).transpose().copy().times(d.get(i).doubleValue()));
rankedMatrix = rankedMatrix.plus(currentRanked).copy();
}
} |
148d8bbb-1d96-4418-a09d-4175eb440d49 | 9 | public static String[] convertUserInput(String input) {
assertNotNull("User input is null", input);
int index;
String temp1, temp2;
// preprocess of the input string to ease the progress of detecting
// deadline indicators which are "due at" and "due on"
if (input.contains(StringFormat.DUE_INDICATOR)) {
index = input.indexOf(StringFormat.DUE_INDICATOR);
temp1 = input.substring(index + 4, index + 6);
temp2 = input.substring(index + 6);
input = input.substring(0, index + 3);
if (temp1.equals(StringFormat.ON_INDICATOR)) {
input = input.concat(StringFormat.ON_INDICATOR);
} else {
input = input.concat(StringFormat.AT_INDICATOR);
}
input = input.concat(temp2);
}
String[] arg = input.trim().split(StringFormat.SPACE_INDICATOR);
String[] parsedInput;
String userAction = arg[0].toLowerCase(); // arg[0] stores the action of
// the user
switch (userAction) {
case StringFormat.ADD:
parsedInput = handleAddInput(arg);
break;
case StringFormat.DELETE:
parsedInput = handleDeleteInput(arg);
break;
case StringFormat.UPDATE:
parsedInput = handleUpdateInput(arg);
break;
case StringFormat.SORT:
parsedInput = handleSortInput(arg);
break;
case StringFormat.SEARCH:
parsedInput = handleSearchInput(arg);
break;
case StringFormat.DONE:
parsedInput = handleDoneInput(arg);
break;
case StringFormat.DISPLAY:
parsedInput = handleDisplayInput(arg);
break;
default:
parsedInput = new String[1];
parsedInput[0] = arg[0];
}
return parsedInput;
} |
cb359e3d-2b38-4295-807e-b0faed59b73b | 7 | public boolean generate(World par1World, Random par2Random, int par3, int par4, int par5)
{
if (par1World.getBlockMaterial(par3, par4, par5) != Material.water)
{
return false;
}
else
{
int var6 = par2Random.nextInt(this.radius - 2) + 2;
byte var7 = 2;
for (int var8 = par3 - var6; var8 <= par3 + var6; ++var8)
{
for (int var9 = par5 - var6; var9 <= par5 + var6; ++var9)
{
int var10 = var8 - par3;
int var11 = var9 - par5;
if (var10 * var10 + var11 * var11 <= var6 * var6)
{
for (int var12 = par4 - var7; var12 <= par4 + var7; ++var12)
{
int var13 = par1World.getBlockId(var8, var12, var9);
if (var13 == Block.dirt.blockID || var13 == Block.grass.blockID)
{
par1World.setBlock(var8, var12, var9, this.sandID);
}
}
}
}
}
return true;
}
} |
67bb3d47-8155-46cc-9f93-3ba03cfbc777 | 6 | @Override
public void valueUpdated(Setting s, Value v) {
if (s.getName().equals(Trigger)) {
try {
boolean b = v.getBoolean();
if (trigger_ == null && b) {
trigger_ = addInput(Trigger, ValueType.VOID);
trigger_.addListener(this);
} else if (trigger_ != null && !b) {
trigger_.removeListener(this);
removeInput(trigger_);
trigger_ = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
super.valueUpdated(s, v);
} |
34cd45df-5fcb-461b-ac80-9758d2734f0b | 6 | private boolean readHyphenatedWordBackwards()
{
boolean hadHyphen = false;
ArrayList<Character> saved = new ArrayList<Character>();
// check for page numbers
char token;
if ( readArabicPageBackwards()||readRomanPageBackwards() )
{
// remove page number
char last = undo.get(undo.size()-1);
undo.clear();
token = last;
}
else
token = prevChar();
saved.add(token);
if ( token=='-' )
{
token = prevChar();
saved.add(token);
hadHyphen = true;
}
while ( undo.size()>0 )
saved.add(undo.remove(0));
while (saved.size()>0 )
unpush( saved.remove(saved.size()-1) );
// token is definitely not a newline
return hadHyphen && Character.isLetter(token);
} |
c13078e0-5fbd-4da1-ac2f-ad272fa7b449 | 9 | private void writeEncoded(String str)
{
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 0x0A:
this.writer.print(c);
break;
case '<':
this.writer.print("<");
break;
case '>':
this.writer.print(">");
break;
case '&':
this.writer.print("&");
break;
case '\'':
this.writer.print("'");
break;
case '"':
this.writer.print(""");
break;
default:
if ((c < ' ') || (c > 0x7E)) {
this.writer.print("&#x");
this.writer.print(Integer.toString(c, 16));
this.writer.print(';');
} else {
this.writer.print(c);
}
}
}
} |
3dfe4f60-9ab7-4fb3-9eeb-f4203432f6c5 | 7 | private String getIPAddress() {
String ip = null;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp()
|| !iface.isPointToPoint()) {
continue;
}
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement().getHostAddress();
if (ip.matches("[0-9.]+")) {
return ip;
}
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return ip;
} |
749b37fe-e76e-4468-a7c5-012b3496a246 | 6 | public static Map<String,String> updateNamespaces( Object xmlPart, Map<String,String> previousNsAbbreviations ) {
if( !(xmlPart instanceof XMLOpenTag) ) return previousNsAbbreviations;
XMLOpenTag openTag = (XMLOpenTag)xmlPart;
Map<String,String> newNsAbbreviations = previousNsAbbreviations;
for( Iterator<String> i=openTag.attributes.keySet().iterator(); i.hasNext(); ) {
String attrKey = i.next();
String attrValue = openTag.attributes.get(attrKey);
if( "xmlns".equals(attrKey) ) {
if( newNsAbbreviations == previousNsAbbreviations ) newNsAbbreviations = new HashMap<String,String>(previousNsAbbreviations);
newNsAbbreviations.put( "", attrValue );
} else if( attrKey.startsWith("xmlns:") ) {
if( newNsAbbreviations == previousNsAbbreviations ) newNsAbbreviations = new HashMap<String,String>(previousNsAbbreviations);
newNsAbbreviations.put( attrKey.substring(6), attrValue );
}
}
return newNsAbbreviations;
} |
57d04e17-6e4b-4f98-84f9-b4f598180446 | 0 | public String getCountry() {
return country;
} |
acd96137-098c-4ea1-a245-ee861fb93c0f | 3 | public boolean contains(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = head;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x))
return true;
i = (i + 1) & mask;
}
return false;
} |
ff8ea982-13e5-40b9-a1e4-dbef9bc295ff | 2 | public void insert(E element) {
heap.insert(element);
int i = heapSize;
while (i > 0 && heap.get(parent(i)).compareTo(element) > 0) {
swapElementsByIndex(i, parent(i));
i = parent(i);
}
heap.set(i, element);
heapSize++;
} |
38be3f63-74aa-45aa-bb59-5a0e5dcab232 | 4 | double heuristicEstimation(int i, int j) throws Exception {
if (BitmapGraph.this.destI_pos == -1 || BitmapGraph.this.destJ_pos == -1) {
throw new Exception("heuristicEstimation failed! End point is not found!!");
}
//return 15*Math.sqrt(pow2(BitmapGraph.this.destI_pos - i) + pow2(BitmapGraph.this.destJ_pos - j));
//return 10*Math.abs(BitmapGraph.this.destI_pos - i) + Math.abs(BitmapGraph.this.destJ_pos - j);
int distanceX = Math.abs(BitmapGraph.this.destI_pos - i);
int distanceY = Math.abs(BitmapGraph.this.destJ_pos - j);
int max = (distanceX > distanceY ? distanceX : distanceY);
int min = (distanceX > distanceY ? distanceY : distanceX);
return 15*min + 10*(max-min);
} |
5b939782-abed-4713-9ce4-1427169dad12 | 5 | public static boolean createAssignExpression(InstructionContainer ic,
StructuredBlock last) {
/*
* Situation: sequBlock: dup_X(lvalue_count) store(POP) = POP
*/
SequentialBlock sequBlock = (SequentialBlock) last.outer;
StoreInstruction store = (StoreInstruction) ic.getInstruction();
if (sequBlock.subBlocks[0] instanceof SpecialBlock
&& store.isFreeOperator()) {
Expression lvalue = store.getSubExpressions()[0];
SpecialBlock dup = (SpecialBlock) sequBlock.subBlocks[0];
if (dup.type != SpecialBlock.DUP
|| dup.depth != lvalue.getFreeOperandCount()
|| dup.count != lvalue.getType().stackSize())
return false;
dup.removeBlock();
store.makeNonVoid();
return true;
}
return false;
} |
3d05b3fa-e84d-4bb7-9083-8fa0c1d4e0de | 0 | public PWWindow(PermWriter project) {
this.project = project;
this.setTitle("PermWriter");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new GridBagLayout());
this.setSize(750, 475);
} |
0d775a95-27ca-4910-930b-4d6f7aeb0fca | 3 | public boolean hasSingleFinalState(Automaton automaton) {
State[] finalStates = automaton.getFinalStates();
if (finalStates.length != 1) {
// System.err.println("There is not exactly one final state!");
return false;
}
State finalState = finalStates[0];
Transition[] transitions = automaton.getTransitionsToState(finalState);
for (int k = 0; k < transitions.length; k++) {
PDATransition trans = (PDATransition) transitions[k];
String toPop = trans.getStringToPop();
if (!(toPop.substring(toPop.length() - 1)).equals(BOTTOM_OF_STACK)) {
// System.err.println("Bad transition to final state! "+trans);
// System.err.println(toPop.substring(toPop.length()-1));
return false;
}
}
return true;
} |
3fcaa61e-4867-44e5-bc1c-b7bdefff8c98 | 4 | public static List<Mouse> loadMice()
{
LinkedList<Mouse> mouseList = new LinkedList<>();
try (BufferedReader savedMice = new BufferedReader(new FileReader(
"mice.list")))
{
String mouseString;
while ((mouseString = savedMice.readLine()) != null)
{
if (mouseString.isEmpty())
{
continue;
}
Mouse mouse = Mouse.loadMouseString(mouseString);
if (mouse != null)
{
mouseList.add(mouse);
}
}
} catch (IOException e)
{
// Save File not Found
}
return mouseList;
} |
468ac8af-8083-4ebe-b7bf-eed564640516 | 5 | public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e))
{
int x = (int)e.getPoint().getX();
int y = (int)e.getPoint().getY();
ActionJouer action = null;
if (x > 0 && x < 300 && y > 0 && y < 300) {
action = new ActionJouer(x/100, y/100);
m_view.sendActionToController(action);
}
}
} |
d8dc1604-2871-496a-a517-229c599aa36d | 3 | private int clearAnswer() throws Exception
{
int n = 0;
while(n < this.MAX_TRIES && this.sendClearCommand() != 1)
{
if ( n > this.MAX_TRIES)
throw new Exception("Достигнут максимальный лимит попыток");
n += 1;
}
return 0;
} |
e3273bbd-4a37-462b-a3b0-c022f55c76cb | 0 | @Override
public void setValue(Object o) {
throw new UnsupportedOperationException("set replaygain not yet supported");
} |
5c0438a4-425a-43e0-a718-298959e06453 | 3 | private NoeudArbre recherchePrioriteList(double priorite) {
NoeudArbre result = NIL;
int i = 0;
while (result == NIL && i < listNoeudArbres.size()) {
if (listNoeudArbres.get(i).priorite == priorite) {
result = listNoeudArbres.get(i);
}
i++;
}
return result;
} |
be14254a-43b4-44ba-b09d-c936381175d3 | 0 | public CheckResultMessage pass(String message) {
return new CheckResultMessage(message);
} |
16ae1b8b-d9e7-4eeb-a53c-041ac0f44f15 | 6 | private int pairIndex(int ii, int jj){
int ret = -1;
int i = 0;
boolean test = true;
while(test){
if(this.pairIndices[i][0]==ii && this.pairIndices[i][1]==jj){
ret = i;
test = false;
}
else{
if(this.pairIndices[i][0]==jj && this.pairIndices[i][1]==ii){
ret = i;
test = false;
}
else{
i++;
if(i>=this.nComparisons){
throw new IllegalArgumentException("No index found " + ii + " and " + jj);
}
}
}
}
return ret;
} |
c9acd1a8-5506-4e04-8590-83f126f4a303 | 7 | public void tick()
{
super.tick();
if(this.fluidIn != null && this.fluidIn.getName().equals("water") && !hasAchievement(AchievementList.touchWater))
{
this.toggleAchievement(AchievementList.touchWater);
}
if(getHeldItem() != null)
{
getHeldItem().update(this, x, y, world);
}
if(this.inv.containsItem(Block.torch.getItem().id) && this.fluidIn == null)
{
if(x >= 0)
Block.torch.onWorldUpdate((int) (x / Block.BLOCK_WIDTH), (int) (y / Block.BLOCK_HEIGHT) + 1, world);
else
Block.torch.onWorldUpdate((int) (x / Block.BLOCK_WIDTH) - 1, (int) (y / Block.BLOCK_HEIGHT) + 1, world);
}
} |
49bfc6c9-f291-4041-b045-94b1bd2dbef9 | 2 | private static Item findClosestMatch(String input){
Levenshtein compare = new Levenshtein();
float max = 0.0f;
float comp;
Item maxitm = null;
for(Item item : items){
comp = compare.getSimilarity(input, item.name);
if(comp > max){
max = comp;
maxitm = item;
}
}
return maxitm;
} |
de661eb6-78b2-4f6d-b7af-eefef2ae1d56 | 1 | public static void main(String[] args) {
List<Interval> result = new ArrayList<Interval>();
Interval a = new Interval(1,5);
Interval b = new Interval(6,8);
result.add(a);
result = new Insert_Interval().insert(result, b);
for(int i = 0 ; i< result.size();i++)
System.out.println(result.get(i).toString());
} |
848ce6c2-063e-4d90-a954-fd9f46d2f36d | 7 | protected boolean isLegalActionTiles(GameContext.PlayerView context,
Set<Tile> tiles) {
PlayerLocation location = context.getMyLocation();
if (!meetPrecondition(context)) {
return false;
}
int legalTilesSize = getActionTilesSize();
if (legalTilesSize > 0
&& (tiles == null || tiles.size() != legalTilesSize)) {
return false;
}
Set<Tile> legalTilesRange = getActionTilesRange(context, location);
if (tiles != null && legalTilesRange != null
&& !legalTilesRange.containsAll(tiles)) {
return false;
}
boolean legal = isLegalActionWithPreconition(context, tiles);
return legal;
} |
41d0afe6-656c-45ef-b510-3d9112e22dc8 | 4 | public void update(){
if(beginningAnimation){
AffineTransform transform = new AffineTransform();
transform.translate(WIDTH/2 - scaleFirst*WIDTH/2, HEIGHT/2 - scaleFirst*HEIGHT/2);
transform.scale(scaleFirst,scaleFirst);
Graphics2D g2d = (Graphics2D)beginningImage.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setColor(new Color(0,0,0,0));
g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.drawImage(tileImage, transform, null);
scaleFirst += 0.1;
g2d.dispose();
if(scaleFirst >= 1)beginningAnimation = false;
}
else if(combineAnimation){
AffineTransform transform = new AffineTransform();
transform.translate(WIDTH/2 - scaleCombine*WIDTH/2, HEIGHT/2 - scaleCombine*HEIGHT/2);
transform.scale(scaleCombine,scaleCombine);
Graphics2D g2d = (Graphics2D)combineImage.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setColor(new Color(0,0,0,0));
g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.drawImage(tileImage, transform, null);
scaleCombine -= 0.05;
g2d.dispose();
if(scaleCombine <= 1)combineAnimation = false;
}
} |
ee05d801-0a3e-4420-bf25-b0df2a349c5b | 6 | public static boolean Substring(String s1, String s2) {
boolean is_substring = true;
if (s2.length() > s1.length()) {
return false;
}
char[] input = s1.toCharArray();
char[] sub = s2.toCharArray();
for (int i = 0; i < input.length; i++) {
if (input[i] == sub[0] && (input.length - i > sub.length)) {
int temp = i + 1;
for (int j = 1; j < sub.length; j++) {
if (input[temp] == sub[j]) {
is_substring = true;
} else {
is_substring = false;
}
temp++;
}
}
}
return is_substring;
} |
e48b26c6-6088-4037-9409-607a4115b0cd | 0 | public void setPostition(int[] newPos) {
this.position = newPos;
} |
2628592f-c464-4812-95c2-f6feb8024ed3 | 9 | public static int computeStorageClass (int tag)
{
switch (tag)
{
case T_BOOLEAN: case T_CHAR: case T_BYTE:
case T_SHORT: case T_INT:
return SC_INT;
case T_ARRAY: case T_CLASS:
case T_ADDR: case T_NULL:
return SC_ADDR;
default:
return tag;
}
} |
59704096-e6dd-4239-b54d-6bf96988ce25 | 6 | public static void tag(String catalogFile, String tagFile) {
ObjectOutputStream tagOutput = null;
try {
FileOutputStream fos = new FileOutputStream(tagFile);
BufferedOutputStream bos = new BufferedOutputStream(fos, 4096*4);
tagOutput = new ObjectOutputStream(bos);
}
catch(IOException e) {
System.out.println("Problem openning tagFile: " + e);
}
ArrayList allFiles = null;
try {
FileInputStream fis = new FileInputStream(catalogFile);
BufferedInputStream bis = new BufferedInputStream(fis, 4096*4);
ObjectInputStream ois = new ObjectInputStream(bis);
allFiles = (ArrayList) ois.readObject();
ois.close();
}
catch(IOException e) {
System.out.println("Problem openning catalogFile: " + e);
return;
}
catch(ClassNotFoundException e) {
System.out.println("Problem reading catalog from ["+catalogFile+"]: " + e);
return;
}
System.out.println("Found " + allFiles.size() + " PDF files to tag");
long then = 0;
for(int i = 0; i < allFiles.size(); i++) {
File file = (File) allFiles.get(i);
String path = file.getAbsolutePath();
long now = System.currentTimeMillis();
if ((now - then) >= 5000L) {
then = now;
System.out.println("Commencing tagging file " + (i+1) + " of " + allFiles.size());
System.out.println(path);
}
//long before = System.currentTimeMillis();
tagPdf(path);
//long after = System.currentTimeMillis();
//System.out.println("Duration: " + (after-before));
System.out.println("Used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
}
System.out.println("Finished tagging " + allFiles.size() + " PDF files");
//if (true) return;
try {
TagState state = Tagger.getTagState();
tagOutput.writeObject(state);
tagOutput.flush();
tagOutput.close();
}
catch(IOException e) {
System.out.println("Problem saving tags: " + e);
}
} |
61a3b67d-fdba-461e-b5e1-fa7d89e8135e | 6 | private void updateSpelprojektInPanel() {
tfSpelprojectSearch.setEnabled(false);
PanelHelper.cleanPanel(spelprojectHolderPanel); // do some cleanup before
ArrayList<String> matches = fetchMatchingSpelproject();
if (!matches.isEmpty()) {
for (String st : matches) {
HashMap<String, String> hm = fetchSpelprojektInfo(st);
if (hm != null) {
PanelHelper.addPanelToPanel(new SpelprojektPanelViewbox(hm.get("SID"), hm.get("BETECKNING"), hm.get("RELEASEDATUM"), hm.get("STARTDATUM")), spelprojectHolderPanel, 150, 120);
} else {
JPanel panel = new JPanel();
panel.add(new JLabel("Something went wrong with your search"));
panel.setVisible(true);
PanelHelper.addPanelToPanel(panel, spelprojectHolderPanel, 500, 200);
}
}
Dimension d = spelprojectHolderPanel.getPreferredSize(); //set the scroll to the right size
int count = matches.size();
int height = count * 125 / 3;
if (count % 3 != 0) {
if (count % 3 == 1) {
height += 88;
}
if (count % 3 == 2) {
height += 44;
}
}
d.setSize(500, height); //sets the size of the panel to the right preferred size
spelprojectHolderPanel.setPreferredSize(d);
} else { // we found nothing that matched
JPanel panel = new JPanel();
panel.add(new JLabel("None matched your search, try to make your search more generic"));
panel.setVisible(true);
PanelHelper.addPanelToPanel(panel, spelprojectHolderPanel, 500, 200);
Dimension d = spelprojectHolderPanel.getPreferredSize();
d.setSize(500, 100);
spelprojectHolderPanel.setPreferredSize(d);
}
tfSpelprojectSearch.setEnabled(true);
} |
9c3e8b4f-3895-41bd-bc7e-5d43b45e5425 | 2 | public int compareTo(Element element)
{
int myCharge = this.getCharge(getName(), protons);
int otherCharge = element.getCharge();
if (myCharge == otherCharge)
return 0;
else if (myCharge > otherCharge)
return 1;
else
return -1;
} |
ffca1227-224e-42e1-9806-6174b64cbab2 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Company)) {
return false;
}
Company other = (Company) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
d5055bf6-f2a9-40e9-9358-5ac595094b67 | 2 | protected void setCod(String cod) throws Exception{
if(cod.length()<5 || cod.length()>20){
throw new Exception("El codigo tiene que tener minimo 5 caracteres y menos de 20 caracteres.");
}else{
this.cod = cod;
}
} |
c1107423-2d0a-4cc8-94a7-bf3c0206b600 | 2 | public static ErrorLogs parameterLogs(String supMsg, String confMsg){
ErrorLogs logs = new ErrorLogs();
String parameterError = "Parameter Input Error: ";
String parameterRange = " Must be between 0.0 and 1.0, inclusively";
if (!supMsg.equals("")) {
logs.getErrorMsgs().add(
parameterError + " Min Support Level is " + supMsg
+ parameterRange);
}
if (!confMsg.equals("")) {
logs.getErrorMsgs().add(
parameterError + " Min Confidence Level is " + confMsg
+ parameterRange);
}
return logs;
} |
b8d8c1f8-de4a-4499-bfd7-d52ae7ac9589 | 2 | public static void roverChange(){
rover = head;
while(rover!=null){
if(rover.img.endsWith(".jpeg")){
String holder = rover.img;
String temp = changeExtension(holder);
System.out.println(temp);
rover.img = temp;
}
rover = rover.next;
}
} |
ba55f99a-7798-45a7-96dc-513271244412 | 6 | void hitmiss(int xe, int ye, int [][] pixel2, int [][]pixel, int [] lut){
int x, y;
// considers the pixels outside image to be 0 (not set)
for (x=1; x<xe-1; x++) {
for (y=1; y<ye-1; y++) {
pixel[x][y]+= lut[(
pixel2[x-1][y-1] +
pixel2[x ][y-1] * 2 +
pixel2[x+1][y-1] * 4 +
pixel2[x-1][y ] * 8 +
pixel2[x ][y ] * 16 +
pixel2[x+1][y ] * 32 +
pixel2[x-1][y+1] * 64 +
pixel2[x ][y+1] * 128 +
pixel2[x+1][y+1] * 256)];
}
}
y=0;
for (x=1; x<xe-1; x++) {
//upper row
pixel[x][y]+= lut[(
pixel2[x-1][y ] * 8 +
pixel2[x ][y ] * 16 +
pixel2[x+1][y ] * 32 +
pixel2[x-1][y+1] * 64 +
pixel2[x ][y+1] * 128 +
pixel2[x+1][y+1] * 256)];
}
y=ye-1;
for (x=1; x<xe-1; x++) {
//lower row
pixel[x][y]+= lut[(
pixel2[x-1][y-1] +
pixel2[x ][y-1] * 2 +
pixel2[x+1][y-1] * 4 +
pixel2[x-1][y ] * 8 +
pixel2[x ][y ] * 16 +
pixel2[x+1][y ] * 32)];
}
x=0;
for (y=1; y<ye-1; y++) {
//left column
pixel[x][y]+= lut[(
pixel2[x ][y-1] * 2 +
pixel2[x+1][y-1] * 4 +
pixel2[x ][y ] * 16 +
pixel2[x+1][y ] * 32 +
pixel2[x ][y+1] * 128 +
pixel2[x+1][y+1] * 256)];
}
x=xe-1;
for (y=1; y<ye-1; y++) {
//right column
pixel[x][y]+= lut[(
pixel2[x-1][y-1] +
pixel2[x ][y-1] * 2 +
pixel2[x-1][y ] * 8 +
pixel2[x ][y ] * 16 +
pixel2[x-1][y+1] * 64 +
pixel2[x ][y+1] * 128)];
}
x=0; //upper left corner
y=0;
pixel[x][y]+= lut[(pixel2[x][y] * 16 + pixel2[x+1][y] * 32 + pixel2[x][y+1] * 128 + pixel2[x+1][y+1] * 256)];
x=xe-1; //upper right corner
//y=0;
pixel[x][y]+= lut[(pixel2[x-1][y] * 8 + pixel2[x][y] * 16 + pixel2[x-1][y+1] * 64 + pixel2[x][y+1] * 128)];
x=0; //lower left corner
y=ye-1;
pixel[x][y]+= lut[(pixel2[x][y-1] * 2 + pixel2[x+1][y-1] * 4 + pixel2[x][y] * 16 + pixel2[x+1][y] * 32)];
x=xe-1; //lower right corner
y=ye-1;
pixel[x][y]+= lut[(pixel2[x-1][y-1] + pixel2[x][y-1] * 2 + pixel2[x-1][y] * 8 + pixel2[x ][y] * 16)];
} |
d513d6ce-b3ff-4d7b-a290-1d881375a9ef | 2 | public static List<TaskWorker> configRunners(DeployConfig config, String taskId, boolean undo) {
List<TaskWorker> result = new ArrayList<TaskWorker>();
boolean flag = true;
Task task = config.getTasks().getTaskById(taskId);
List<Server> servers = parseServers(config, task.getTargetServer());
List<String> dbNames = parseDbNames(task.getTargetDatabase());
List<String> sqls = parseSqls(task.getSqls(), undo);
for (Server server : servers) {
for (String dbName : dbNames) {
result.add(new TaskWorker(server, dbName, sqls));
}
}
return result;
} |
88272ccd-3470-456d-818a-f7c48ed24f86 | 7 | @Override
public void buttonPressed(ClickableComponent button) {
if (button instanceof LevelButton) {
LevelButton lb = (LevelButton) button;
TitleMenu.level = levels.get(lb.getId());
if (activeButton != null && activeButton != lb) {
activeButton.setActive(false);
}
activeButton = lb;
}
else if (button == previousPageButton && hasPreviousPage()) {
goToPage(currentPage - 1);
}
else if (button == nextPageButton && hasNextPage()) {
goToPage(currentPage + 1);
}
} |
6ca3a07a-7487-4e75-92ed-3f6a1dc7829a | 6 | @EventHandler
public void GiantFastDigging(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getGiantConfig().getDouble("Giant.FastDigging.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getGiantConfig().getBoolean("Giant.FastDigging.Enabled", true) && damager instanceof Giant && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getGiantConfig().getInt("Giant.FastDigging.Time"), plugin.getGiantConfig().getInt("Giant.FastDigging.Power")));
}
} |
c8081981-c909-496c-8cf5-7cdff02cd0af | 2 | public final Customer getCustomer(String custID) {
Customer customer = null;
for (Customer c : customers) {
if (custID.equals(c.getCustID())) {
customer = c;
break;
}
}
return customer;
} |
9b57c1fa-f50d-436e-97cb-de7893910465 | 2 | protected final String getCommand() throws MenuException{
// Scanner inFile = Memorygame.getInputFile();
Scanner inFile = new Scanner(System.in);
String command;
boolean valid = false;
do {
command = inFile.nextLine();
command = command.trim().toUpperCase();
valid = validCommand(command);
if (!validCommand(command)) {
throw new MenuException(ErrorType.ERROR3.getMessage());
//continue;
}
return command;
} while (!valid);
} |
6c980c9f-18cf-4bbb-8357-7231bba058e9 | 2 | private void formUserList(SessionRequestContent request) throws ServletLogicException {
Criteria criteria = new Criteria();
User user = (User) request.getSessionAttribute(JSP_USER);
if (user != null) {
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
criteria.addParam(DAO_ROLE_NAME, type);
} else {
criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE));
}
try {
AbstractLogic userLogic = LogicFactory.getInctance(LogicType.USERLOGIC);
List<User> users = userLogic.doGetEntity(criteria);
request.setSessionAttribute(JSP_USER_LIST, users);
} catch (TechnicalException ex) {
throw new ServletLogicException(ex.getMessage(), ex);
}
} |
fd2f074e-cb7e-4e82-80d0-dd5d86ea0d30 | 1 | public boolean isCellEditable(int row, int column) {
if (!finalEdit)
return super.isCellEditable(row, column);
column = convertColumnIndexToModel(column);
return cellEditors[row][column] != null;
} |
36b64eab-1277-4c9f-a4bf-81dcbfad00e1 | 7 | public static Slot lookupVisibleSlot(Stella_Class renamed_Class, Stella_Object slotName) {
{ Slot slot = null;
String slotnamestring = null;
Module module = ((Module)(Stella.$MODULE$.get()));
{ Surrogate testValue000 = Stella_Object.safePrimaryType(slotName);
if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol slotName000 = ((Symbol)(slotName));
slot = Stella_Class.lookupSlot(renamed_Class, slotName000);
if (slot != null) {
return (slot);
}
slotnamestring = slotName000.symbolName;
module = ((Module)(slotName000.homeContext));
}
}
else if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate slotName000 = ((Surrogate)(slotName));
slotnamestring = slotName000.symbolName;
module = ((Module)(slotName000.homeContext));
}
}
else if (Surrogate.subtypeOfKeywordP(testValue000)) {
{ Keyword slotName000 = ((Keyword)(slotName));
slotnamestring = slotName000.symbolName;
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper slotName000 = ((StringWrapper)(slotName));
slotnamestring = slotName000.wrapperValue;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("Illegal slot name: `" + slotName + "'");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
{ Symbol symbol = null;
Cons iter000 = Stella.lookupVisibleSymbolsInModule(slotnamestring, module, true);
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
symbol = ((Symbol)(iter000.value));
slot = Stella_Class.lookupSlot(renamed_Class, symbol);
if (slot != null) {
return (slot);
}
}
}
return (null);
}
} |
8bb41dd2-6afe-47e8-93a8-8addade7a92d | 8 | private List<FactoryPoint<?>> findAllFactoryPoints(final List<Member> allMembers, final List<Method> allMethods,
final BeanKey factoryBean, final TypeMap typeMap) {
final List<FactoryPoint<?>> factoryPoints = new ArrayList<FactoryPoint<?>>();
for (final Member member : allMembers) {
if (member instanceof Method) {
final Method method = (Method) member;
if (methodIsFactoryPoint(method) && !reflectionUtils.isOverridden(method, allMethods)) {
failIfInjectionPoint(method);
final FactoryPointMethod<?> factoryPointMethod = createFactoryPointMethod(method, factoryBean, typeMap);
factoryPoints.add(factoryPointMethod);
}
}
}
return factoryPoints;
} |
888f6619-b414-4222-b512-5f6e33545c25 | 1 | public Value naryOperation(final AbstractInsnNode insn, final List values) {
int size;
if (insn.getOpcode() == MULTIANEWARRAY) {
size = 1;
} else {
size = Type.getReturnType(((MethodInsnNode) insn).desc).getSize();
}
return new SourceValue(size, insn);
} |
bd3ed33d-8601-48f2-bd9f-eeb0dc86ca9f | 0 | public void setFunEstado(String funEstado) {
this.funEstado = funEstado;
} |
d5cf6c8c-3379-4cf6-bb43-52bf6bd43103 | 2 | public void visitTableSwitchInsn(
final int min,
final int max,
final Label dflt,
final Label[] labels)
{
buf.setLength(0);
buf.append(tab2).append("TABLESWITCH\n");
for (int i = 0; i < labels.length; ++i) {
buf.append(tab3).append(min + i).append(": ");
appendLabel(labels[i]);
buf.append('\n');
}
buf.append(tab3).append("default: ");
appendLabel(dflt);
buf.append('\n');
text.add(buf.toString());
if (mv != null) {
mv.visitTableSwitchInsn(min, max, dflt, labels);
}
} |
271d55cf-c568-48e9-a538-e421a628c698 | 1 | protected void stopPlayer() throws JavaLayerException
{
if (player!=null)
{
player.close();
player = null;
playerThread = null;
}
} |
143b07e0-3563-44a9-8bd0-5b23fbf8e5c5 | 3 | @SuppressWarnings("deprecation")
public ConfigAccessor(JavaPlugin plugin, String fileName) {
if (plugin == null) {
throw new IllegalArgumentException("plugin cannot be null");
}
if (!plugin.isInitialized()) {
throw new IllegalArgumentException("plugin must be initialized");
}
this.plugin = plugin;
this.fileName = fileName;
File dataFolder = plugin.getDataFolder();
if (dataFolder == null) {
throw new IllegalStateException();
}
configFile = new File(plugin.getDataFolder(), fileName);
} |
6463eeda-7ecb-414b-8a9e-233e7de31108 | 7 | public void declareSplitWinnings(int dealer, int player, int split) {
int winnings = 0;
if (playerHand.blackJack()) {
winnings += playerHand.getBet() + (playerHand.getBet() * 3) / 2;
} else if (player > dealer) {
winnings += playerHand.getBet() * 2;
} else if (player == dealer) {
winnings += playerHand.getBet();
}
if (splitHand.blackJack()) {
winnings += splitHand.getBet() + (splitHand.getBet() * 3) / 2;
} else if (split > dealer) {
winnings += splitHand.getBet() * 2;
} else if (split == dealer) {
winnings += splitHand.getBet();
}
if (winnings > 0) {
payWinnings(winnings);
ui.gameOver("YOU WON " + winnings + "€");
} else {
ui.gameOver("DEALER WINS");
}
} |
7d78015a-9293-41f3-9df8-d5f5c39d9574 | 1 | protected static BigDecimal parseBigDecimal(final Object obj, final String type) throws ParseException {
final BigDecimal result;
try {
result = new BigDecimal(obj.toString());
} catch (NumberFormatException nfe) {
throw new ParseException(obj + " is not a valid " + type + ".");
}
return result;
} |
f0dd1034-8c41-4980-9a8d-3d36e9e5b08e | 1 | public Set<String> copySet(Set<String> set) {
Set<String> out = new HashSet<String>();
for (String elem : set) {
out.add(elem);
}
return out;
} |
eeae3dc2-d4ab-42ca-8bd6-d329fb9f9d96 | 8 | private void createInterface() {
boolean b = true;
for (int i = 0; i < model.getTabellone().length; i++) {
for (int j = 0; j < model.getTabellone()[i].length; j++) {
Cell cell = new Cell(i, j);
if (b) {
cell.setImage(whiteCell.getImage());
} else {
cell.setImage(blackCell.getImage());
}
b = !b;
cell.setBorder(null);
ImageIcon icon = null;
if (model.getTabellone()[i][j] != 0) {
if (model.getTabellone()[i][j] == 1) {
icon = blackDama;
}
if (model.getTabellone()[i][j] == 2) {
icon = whiteDama;
}
if (model.getTabellone()[i][j] == 3) {
icon = blackDamone;
}
if (model.getTabellone()[i][j] == 4) {
icon = whiteDamone;
}
Pedina button = new Pedina(icon, this);
cell.add(button);
}
cell.addActionListener(this);
pannello.add(cell);
}
b = !b;
}
} |
2a1a7b4f-cef5-4270-99e9-a8aa1941bac3 | 9 | public EditorTab() {
this.setLayout(new BorderLayout());
this.list.setCellRenderer(this.renderer);
this.list.setTransferHandler(new BytecodeEditorTransferHandler(this));
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.registerComponent(this.list);
this.add(this.label, BorderLayout.NORTH);
this.add(this.editorScrollPane, BorderLayout.CENTER);
this.list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
splitSynchronize();
}
});
this.list.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
if (me.getClickCount() == 2
&& me.getButton() == MouseEvent.BUTTON1) {
modifyRow();
} else if (me.getButton() == MouseEvent.BUTTON3) {
Object obj = list.getSelectedValue();
if (obj instanceof CodeRow) {
EditorTab.this.codeContextMenu.show(
EditorTab.this.list, me.getPoint().x, me
.getPoint().y);
} else if (obj instanceof LabelRow) {
EditorTab.this.labelContextMenu.show(
EditorTab.this.list, me.getPoint().x, me
.getPoint().y);
} else if (obj instanceof MethodDefRow) {
EditorTab.this.methodContextMenu.show(
EditorTab.this.list, me.getPoint().x, me
.getPoint().y);
} else if (obj instanceof FieldDefRow) {
EditorTab.this.fieldContextMenu.show(
EditorTab.this.list, me.getPoint().x, me
.getPoint().y);
} else if (obj instanceof ImportDefRow) {
EditorTab.this.importContextMenu.show(
EditorTab.this.list, me.getPoint().x, me
.getPoint().y);
} else if (obj instanceof ClassDefRow) {
EditorTab.this.classContextMenu.show(
EditorTab.this.list, me.getPoint().x, me
.getPoint().y);
}
}
}
});
createContextMenus();
} |
cb714484-b814-4dbd-b4c6-a4cd5277124d | 0 | public RedeclarationError(Symbol sym)
{
super("Symbol " + sym + " being redeclared.");
} |
ac8bb7ad-d19a-478a-98aa-6f623561125a | 7 | @Override
public void run() {
HashMap<String, String> args = msg.getArgs();
String ip = socket.getInetAddress().toString();
String username = args.get("username");
String password_ = args.get("password");
DebugLog.log("login", username);
String password = null;
try {
password = DaoFactory.creatIdentificationDao().queryPasswordByUsername(username);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
IMessage newMsg = new IMessage(IMessage.MSG_RESPOND);
int result = 0;
if (password!=null) {
DebugLog.log("password", password);
if (password.equals(password_)) {
User user = new User(username, ip);
user.setState(User.STATE_ONLINE);
try {
result = DaoFactory.creatUserDao().updateUser(user);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (result==1) {
newMsg.addArgs("code",IMessage.OK);
newMsg.addArgs("content", "login successfully!");
}else {
newMsg.addArgs("code", IMessage.ERROE);
newMsg.addArgs("content", "error");
}
}else {
newMsg.addArgs("code", IMessage.ERROE);
newMsg.addArgs("content", "error");
}
sendMessage(newMsg);
} |
e3cc5633-df38-48d5-9b52-f9a0e796d2d5 | 2 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
try {
long id = Long.parseLong(jTextField1.getText());
long tel = Long.parseLong(jTextField5.getText());
String nome = jTextField2.getText();
String end = jTextField3.getText();
String email = jTextField4.getText();
if (f.buscarCliente(id) instanceof ClienteFisico) {
f.alterarCliente(new ClienteFisico(id, nome, end, email, tel));
} else {
f.alterarCliente(new ClienteJuridico(id, nome, end, email, tel));
}
JOptionPane.showMessageDialog(null, "Alterado com sucesso!");
dispose();
} catch (Exception e) {
}
}//GEN-LAST:event_jButton2ActionPerformed |
17c9b1f5-0668-44a9-b249-714093978066 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final List<Ability> offensiveAffects=returnOffensiveAffects(mob,target);
if((success)&&(offensiveAffects.size()>0))
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> feel(s) lightly touched."):L("^S<S-NAME> @x1 to deliver a light unbinding touch to <T-NAMESELF>.^?",prayForWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
if(!CMLib.flags().isStillAffectedBy(target,offensiveAffects,false))
target.tell(L("You feel less constricted!"));
}
}
else
this.beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} |
f9571c81-37a8-4335-9e65-8944639f4123 | 8 | private void checkCollision()
{
for (int i = 0; i < traps.size(); i ++) {
Trap t = traps.get(i);
if (t.functioning) {
double distance = player.pos.x - t.pos.x;
if (distance < 10 && distance > - 5) {
if (player.state != Player.STATE.JUMPING || (player.state == Player.STATE.JUMPING && (player.getJumpPhase() < 2 || player.getJumpPhase() > 10))) {
System.out.println("Collision");
t.functioning = false;
t.rotationSpeed = (Math.random() - 0.5) / 2;
t.vel.x = player.vel.x * 1.4 * (Math.random() * 0.4 + 1);
t.vel.y = - player.vel.x * Math.random();
// Slow down player
player.vel.x *= 0.8;
}
}
}
}
} |
dfa6fe31-c965-4af7-9496-cb89f0f93412 | 7 | public void compFinalResult() {
do {
iStage++;
compAllocation();
if (compDistribution()) {
/* deadline can not be satisfied */
if (!bDeadline) {
System.out.println("THE DEADLINE CAN NOT BE SATISFIED!");
return;
} else {
System.out.println("\nNEW ROUND WITHOUT CHECKING:");
dEval = 1;
}
} else {
compExecTime();
}
// System.out.println("Evaluation Value =========="+dEval);
} while (dEval > 0);
// while (evaluateResults());
// System.out.println("==================Distribution=====================");
for (int i = 0; i < iClass; i++) {
// System.out.print("FinalDistribution[" + i + "] ");
for (int j = 0; j < iSite; j++) {
dmDist[i][j] = Math.round(dmDist[i][j]);
// System.out.print(dmDistribution[i][j] + ",");
}
// System.out.println();
}
// System.out.println("==================Allocation=====================");
for (int i = 0; i < iClass; i++) {
System.out.print("FinalAllocation[" + i + "] ");
for (int j = 0; j < iSite; j++) {
dmAlloc[i][j] = Math.round(dmAlloc[i][j]);
// System.out.print(dmAllocation[i][j] + ",");
}
// System.out.println();
}
// System.out.println("Stage = " + iStage);
} |
b299a697-2a85-4bf7-8433-d391ed6a6161 | 7 | public static String BigIntMultDif(String a, String b, int intLevel) {
int k1 = a.length();
int k2 = b.length();
StringBuffer strLevel = new StringBuffer("\n");
for (int i = 0; i < intLevel; i++) {
strLevel.append(" ");
}
if (k1 < 4 && k2 < 4) {
int intA = Integer.parseInt(a);
int intB = Integer.parseInt(b);
int intR = intA * intB;
strProcess.append(strLevel).append(a).append(" * ").append(b).append(" = ").append(intR);
return String.valueOf(intR);
}
if (k1 > k2) {
return BigIntMultDif(b, a, intLevel);
} else if (k1 == k2) {
return BigIntMultSame(a, b, intLevel);
}
BigInteger p = BigInteger.ZERO;
BigInteger r = p;
int i = 0;
strProcess.append(strLevel).append(a).append(" * ").append(b).append(" = ");
for (; i < k2 - k1; i += k1) {
String bi = b.substring(i, i + k1);
strProcess.append(a).append("*").append(bi).append("*10^").append(k2 - k1 - i).append("+");
}
String bi = b.substring(i);
strProcess.append(a).append("*").append(bi);
for (i=0; i < k2 - k1; i += k1) {
String bt = b.substring(i, i + k1);
r = p.add(new BigInteger(BigIntMultSame(a, bt, intLevel+1) + cover(k2 - k1 - i)));
p = r;
}
r = p.add(new BigInteger(BigIntMultDif(a, bi, intLevel+1)));
strProcess.append(strLevel).append(" =").append(r);
return r.toString();
} |
eb02fea0-f9b3-4978-aad3-19c5a53eb78e | 3 | @Override
public TestResult test(String input, Integer... args) {
if( !String.class.equals(input.getClass()) ){
throw new IllegalArgumentException("Parameter 'input' ONLY support 'String' type.");
}
final int length = input.length();
final int minLength = args[0];
final int maxLength = args[1];
boolean passed = (length >= minLength && length <= maxLength);
String message = passed ? null : String.format(messageT, minLength,maxLength);
return new TestResult(passed, message);
} |
63fdcc85-8a56-4a25-9178-04babf25362e | 8 | public int compareChromoName(Interval interval) {
Chromosome i2 = (Chromosome) interval;
// Both of them are non-numeric: Compare as string
if ((chromosomeNum == 0) && (i2.chromosomeNum == 0)) return id.compareTo(i2.id);
// One of them is a number? => the number goes first
if ((chromosomeNum != 0) && (i2.chromosomeNum == 0)) return -1;
if ((chromosomeNum == 0) && (i2.chromosomeNum != 0)) return 1;
// Use numeric comparison
if (chromosomeNum - i2.chromosomeNum < 0) return -1;
if (chromosomeNum - i2.chromosomeNum > 0) return 1;
return 0;
} |
3729accf-35dc-44ae-aafe-01e43e3e32e6 | 3 | public boolean escribirCliente (int i,CCliente cliente){
if(i>=0 && i<= nregs){
try{//uso try porque puede generar errores
fes.seek(i*tam); //situamos el puntero en la posición que me indica i (será nregs*tamaño de cada registro)
fes.writeUTF(cliente.getDNI());
fes.writeUTF(cliente.getNombre());
fes.writeUTF(cliente.getCuenta());
return true;
}
catch (IOException e){//tratamiento del error
Pantalla.muestra("Imposible escribir el registro");
}
}else{//No intentaría escribirlo, por eso no es necesario tratarlo como error.
Pantalla.muestra("Registro excedido");
}
return false;
} |
6cd60683-0445-4437-ace6-6f327be36d16 | 3 | public synchronized Connection get() throws DataException {
// ensure we haven't used too many connections
if (usedConnections.size() >= MAX_CONNECTIONS) {
throw new DataException("The database connection pool is out of connections -- a maximum number of " + MAX_CONNECTIONS);
}//if
try {
// do we have enough connections to assign one out?
if (freeConnections.size() == 0) {
freeConnections.add(createConnection());
}
// return the first free connection
Connection conn = freeConnections.remove(0);
usedConnections.add(conn);
//Logger.global.info("Gave out a connection from the pool. Free size is now: " + freeConnections.size() + "/" + (freeConnections.size() + usedConnections.size()));
return conn;
}catch (Exception e) {
throw new DataException("An error occurred while retrieving a database connection from the pool", e);
}
}//get |
1f7cfd82-081a-43d1-be26-7fdcd2d0ae9d | 7 | public void onReceivePushSolution(RepairSolution solution) {
logger_.info("Solution for path {} received.", solution.failedPath);
// Update routing table.
for (PeerReference ref : solution.failedHosts) {
Host failedHost = Deserializer.deserializeHost(ref);
logger_.debug("Removing failed host {}:{}", failedHost, failedHost.getPort());
routingTable_.removeReference(failedHost);
registry_.removeIssue(failedHost.getUUID());
}
for (PeerReference ref : solution.updatedHosts) {
Host updatedHost = Deserializer.deserializeHost(ref);
logger_.debug("Updating host {}:{}", updatedHost, updatedHost.getPort());
routingTable_.removeReference(updatedHost);
routingTable_.addReference(0, updatedHost);
//routingTable_.updateReference(updatedHost);
}
routingTable_.refresh(maxRef_);
logger_.debug("Routing table updated.");
if (solution.levelPrefix.compareTo(routingTable_.getLocalhost().getHostPath().toString()) == 0) {
// sanity included...
logger_.debug("Broadcasting cannot proceed. {} is the final point.", solution.levelPrefix);
return;
}
// Continue solution broadcasting.
PGridPath levelPrefix = new PGridPath(solution.levelPrefix);
PGridPath localPath = routingTable_.getLocalhost().getHostPath();
logger_.debug("Common with level prefix '{}': {}", levelPrefix, localPath.commonPrefix(levelPrefix));
int startLevel = localPath.commonPrefix(levelPrefix).length();
logger_.debug("Starting from level {}", startLevel);
for (int i = startLevel; i < localPath.length(); i++) {
logger_.debug("Informing level {} ({})", i, localPath.subPath(0, i));
Random r = new Random(System.currentTimeMillis());
Host[] level = routingTable_.getLevelArray(i);
int nextInt = r.nextInt(level.length + 1);
nextInt = nextInt <= 0 ? 0 : nextInt - 1;
Host host = level[nextInt];
PGridPath responsibility = new PGridPath(localPath.subPath(0, i));
responsibility.revertAndAppend(localPath.value(i));
solution.levelPrefix = responsibility.toString();
try {
logger_.info("{}:{} is responsible for subtree {}",
new Object[]{host, host.getPort(), responsibility});
RepairHandle repairHandle = getRemoteHandle(host);
repairHandle.pushSolution(solution);
} catch (CommunicationException e) {
// Ignore the failure. The broadcasting becomes really
// complicated if a new repair session will start. What
// will happen with all the host that already got the
// solution?
logger_.debug("{}:{} is not reachable.", host, host.getPort());
}
if (i >= localPath.length()) {
logger_.error("From {} to {} ({})", new Object[]{startLevel, localPath.length(), i});
System.exit(i);
}
}
} |
2d9ea648-17ef-46b9-9c96-3169b8de55ac | 6 | public static TreeNode commonAncestor(TreeNode root, int childOne, int childTwo) {
if (root == null)
return null;
if (childOne == root.value || childTwo == root.value)
return root;
TreeNode left = commonAncestor(root.left, childOne, childTwo);
TreeNode right = commonAncestor(root.right, childOne, childTwo);
if (left != null && right != null)
return root;
return left == null ? right : left;
} |
cb643644-0d31-4bc9-91da-f064dad9701a | 7 | @Override
public boolean equals(Object other){
if(other instanceof HttpResponse){
HttpResponse otherResponse = (HttpResponse) other;
if(header == null)
return statusCode == otherResponse.statusCode &&
body.equals(otherResponse.body);
if(body == null)
return statusCode == otherResponse.statusCode &&
header.equals(otherResponse.header);
else
return statusCode == otherResponse.statusCode &&
header.equals(otherResponse.header) &&
body.equals(otherResponse.body);
}
return false;
} |
0160c182-f82e-4bbf-8fde-0752e9564fd8 | 9 | public static List<String> generateAllSentencesWithAllDefinitions(GRESCTask task) {
List<String> pSentences = new ArrayList<String>();
List<GRESCOption> options = task.getOptions().get(0);
for (GRESCOption option : options) {
String sentence = task.getSentence().replaceAll("%s", "\\(%s\\)");
String formattedSentence = String.format(sentence, option.getBlanks().toArray());
List<String> singleWord = new ArrayList<String>();
List<String> blank = new ArrayList<String>();
List<String> allWord = new ArrayList<String>();
// dictionary look up
for (String token : option.getBlanks()) {
if (!SparkUtils.isPhrase(token)) {
// it is a word
allWord.add("%s");
singleWord.add(token);
blank.add(token);
} else {
// it is a phrase
System.out.println(token);
allWord.add(token);
}
}
if (singleWord.size() > 0) {
String dictSentence = String.format(sentence, allWord.toArray());
List<List<String>> singleWordDefinitions = new ArrayList<List<String>>();
// iterate the single word list and look up all single word using Pearson Dictionary
for (int i = 0; i < singleWord.size(); i++) {
PearsonHeadwordRequest request = new PearsonHeadwordRequest();
request.setHeadWord(singleWord.get(i));
try {
PearsonHeadwordResponse response = PearsonDictionary.getDictionary().lookupDictionary(request);
if (response != null) {
response.response(response.getJsonResponse());
List<PearsonDictionaryEntry> entries = response.getEntries();
singleWordDefinitions.add(PearsonDictionary.getDictionary().getAllDefinitions(entries));
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
singleWordDefinitions.get(i).add(singleWord.get(i));
}
// enumerate all possible combinations of the single word definitions
List<List<String>> enumerations = SparkUtils.enumerate(singleWordDefinitions);
for (List<String> ems : enumerations) {
StringBuilder dictFormattedSentence = new StringBuilder();
dictFormattedSentence.append(option.getOptionId());
dictFormattedSentence.append(":");
dictFormattedSentence.append(String.format(dictSentence, ems.toArray()));
pSentences.add(dictFormattedSentence.toString());
}
} else {
pSentences.add(formattedSentence);
}
}
return pSentences;
} |
c8c1b67d-708d-4b17-9fb4-fad74be74ad8 | 9 | @Override protected boolean canFigureMove(Point x, Point Abs) {
if ((x.x==1*getFI() || (x.x == 2*getFI() && isFirstMove)) && x.y == 0)
if (!C.isFigure(Abs) && x.x == 1*getFI() || !C.isFigure(Abs) &&
!C.isFigure(new Point(Abs.x-getFI(),Abs.y)) && x.x == 2*getFI())
return true;
return false;} |
8c93490b-3ceb-424c-8d0c-fef16faa12cb | 2 | @Override
public void paint(Graphics g) {
Dimension currentSize = getSize();
Dimension maximumSize = getMaximumSize();
if (currentSize.width > maximumSize.width || currentSize.height > maximumSize.height) {
currentSize.width = Math.min(maximumSize.width, currentSize.width);
currentSize.height = Math.min(maximumSize.height, currentSize.height);
Point p = getLocation();
p.setLocation(Math.max(p.x, 0), Math.max(p.y, 0));
setSize(currentSize);
setLocation(p);
}
super.paint(g);
// g.drawImage(ImageLoader.getInstance().loadMainFrameOverlay(), 9, 32, null);
} |
271e37e0-03ec-47c9-9da7-31dd4ac0d220 | 0 | public static UDPChat getInstance()
{
return instance;
} |
a4dcae60-58f5-444f-abc5-8b011b01d8ff | 9 | @Override
public void run() {
if (state == GameState.Running) {
while (true) {
robot.update();
if (robot.isJumped()) {
currentSprite = characterJumped;
} else if (robot.isJumped() == false
&& robot.isDucked() == false) {
currentSprite = anim.getImage();
}
ArrayList<Projectile> projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
if (p.isVisible() == true) {
p.update();
} else {
projectiles.remove(i);
}
}
updateTiles();
hb.update();
hb2.update();
bg1.update();
bg2.update();
animate();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (robot.getCenterY() > 500) {
state = GameState.Dead;
}
}
}
} |
63518f12-1eb7-467f-8693-ad7944fd4c9c | 8 | @Override
public Parameter getParameter(final int parameterIndex) {
Parameter parameter;
switch (parameterIndex) {
case 0:
parameter = effect1On;
break;
case 1:
parameter = effect2On;
break;
case 2:
parameter = chorusOn;
break;
case 3:
parameter = delayOn;
break;
case 4:
parameter = reverbOn;
break;
case 5:
parameter = eqOn;
break;
case 6:
parameter = gainOn;
break;
case 7:
parameter = insertOn;
break;
default:
parameter = null;
}
return parameter;
} |
48323098-1e3d-40aa-8461-7323095670c8 | 2 | @EventHandler(priority = EventPriority.NORMAL)
public void onEntityDeath(EntityDeathEvent event) {
if (event.getEntityType() == EntityType.PLAYER) {
Player player = (Player) event.getEntity();
RemovePlayer(player);
}
if (event instanceof PlayerDeathEvent) {
PlayerDeathEvent e = (PlayerDeathEvent) event;
e.setDeathMessage(null);
}
} |
6a824ed2-965a-4b1a-8ce9-b1ebf8d43735 | 7 | public static int lengthOfLongestSubstring(String s) {
if(s.equals("")) {
return 0;
}
HashMap<String, Integer> table = new HashMap<String, Integer>();
int tmpLen = 0;
int maxLen = 0;
int start = 1;
String[] subStrings = s.split("");
int len = subStrings.length;
for(int i=0;i<len;i++) {
if(!subStrings[i].equals("")) {
if(!table.containsKey(subStrings[i])) {
tmpLen++;
table.put(subStrings[i], i);
}else {
if(tmpLen > maxLen) {
maxLen = tmpLen;
}
int index = table.get(subStrings[i]);
tmpLen = tmpLen - (index-start);
for(int j=start;j<=index;j++) {
table.remove(subStrings[j]);
}
table.put(subStrings[i], i);
start = index+1;
}
}
}
if(tmpLen > maxLen) {
maxLen = tmpLen;
}
return maxLen;
} |
ed9cbef6-62d9-4f5e-b79c-6bb88aae2493 | 8 | public void run() {
InetAddress group = null;
try {
group = InetAddress.getByName(multicast);
} catch (UnknownHostException e) {
e.printStackTrace();
}
//create Multicast socket to to pretending group
MulticastSocket s = null;
try {
s = new MulticastSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
if (group != null && s != null) try {
s.joinGroup(group);
} catch (IOException e) {
e.printStackTrace();
}
int count = 0;
while(true) {
try {
String msg = (String)" <?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<data>\n" +
" <header>\n" +
" <name>adresgegevens</name>\n" +
" <type>PERIODIC</type>\n" +
" </header>\n" +
" <payload>\n" +
" <item name='straat' value='Jansteenstraat' type='text' />\n" +
" <item name='postcode' value='9734BC' type='text' />\n" +
" <item name='huisnummer' value='28c' type='text' />\n" +
" <item name='stad' value='Groningen' type='text' />\n" +
" </payload>\n" +
"</data>\n";
byte[] b = msg.getBytes();
DatagramPacket dp = new DatagramPacket(b , b.length , group , port);
try {
s.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(250);
} catch (InterruptedException e) { e.printStackTrace();}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.