method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
83a6fd42-f0bb-493f-9837-71c59bae64b5
| 1
|
protected void addDebito(double acrecimo)throws ExceptionPessoa{
if(acrecimo >0){
this.debito += acrecimo;
}else{
throw new ExceptionPessoa("Tentativa de adocionar d��bito com valor negativo");
}
}
|
77692242-5d75-449f-84bb-f223bb7bb65d
| 3
|
public void setDifficulty(Difficulty diff) {
difficulty = diff;
// Remove check from all menu items.
menuGameDiffEasy.setSelected(false);
menuGameDiffMedium.setSelected(false);
menuGameDiffHard.setSelected(false);
// Check appropriate menu item.
switch (diff) {
case EASY: menuGameDiffEasy.setSelected(true); break;
case MEDIUM: menuGameDiffMedium.setSelected(true); break;
case HARD: menuGameDiffHard.setSelected(true); break;
}
}
|
2c7ac0d6-c09c-45b3-b73f-13b09649a05f
| 0
|
public MultipleBruteParseAction(GrammarEnvironment environment) {
super("Multiple Brute Force Parse", null);
this.environment = environment;
this.frame = Universe.frameForEnvironment(environment);
}
|
d3b8fd48-0d65-4957-99a7-cede0f294bdd
| 2
|
public void add_bits (int bitstring, int length)
{
int bitmask = 1 << (length - 1);
do
if (((crc & 0x8000) == 0) ^ ((bitstring & bitmask) == 0 ))
{
crc <<= 1;
crc ^= polynomial;
}
else
crc <<= 1;
while ((bitmask >>>= 1) != 0);
}
|
172cf774-babc-40d5-b2c6-d7ebcc4708d1
| 1
|
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("filtroAutenticacion:DoAfterProcessing");
}
// Write code here to process the request and/or response after
// the rest of the filter chain is invoked.
// For example, a logging filter might log the attributes on the
// request object after the request has been processed.
/*
for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
Object value = request.getAttribute(name);
log("attribute: " + name + "=" + value.toString());
}
*/
// For example, a filter might append something to the response.
/*
PrintWriter respOut = new PrintWriter(response.getWriter());
respOut.println("<P><B>This has been appended by an intrusive filter.</B>");
*/
}
|
ab9c3eba-cd0a-46c9-b4bb-b6e96183cbc3
| 4
|
public boolean hasUnitLeft(Player player) {
for (int i = 0; i < this.unitList.length; i++) {
for (int j = 0; j < this.unitList.length; j++) {
if (this.unitList[i][j] != null) {
if (this.unitList[i][j].getName().equals(player.getFaction().getName())) {
return true;
}
}
}
}
return false;
}
|
823a8813-3168-4aed-817b-d497ae42cf14
| 1
|
public String scriptDownload(String appKey, String userKey, String testId) {
try {
appKey = URLEncoder.encode(appKey, "UTF-8");
userKey = URLEncoder.encode(userKey, "UTF-8");
testId = URLEncoder.encode(testId, "UTF-8");
} catch (UnsupportedEncodingException e) {
BmLog.error(e);
}
return String.format("%s/api/rest/blazemeter/testScriptDownload/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId);
}
|
92467caf-27d5-4891-b833-5d7596dd5219
| 4
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
logger.error(ex.getMessage());
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
try {
new App().setVisible(true);
} catch (Throwable ex) {
logger.error(ex.getMessage());
}
});
}
|
c4b8b0a6-4103-4f8b-96ea-fb01fdb18685
| 7
|
private static boolean goodWord(String s){
if(s.contains("-")){
return false;
}else if(s.contains("'")){
return false;
}else if(s.contains(" ")){
return false;
}else if(s.contains(".")){
return false;
}else if(s.contains("fuck")){
return false;
}else if(s.contains("shit")){
return false;
}else if(s.contains("crap")){
return false;
}else{
return true;
}
}
|
686347a7-19f1-4436-b719-131582e218c6
| 3
|
public static void main(String[] args) throws Exception {
for(int c=0; c<2; c++) {
long lall = 0, tall = 0;
for(File f : new File("resources/testdata/").listFiles()) {
RandomAccessFile raf = new RandomAccessFile(f, "r");
byte[] data = new byte[(int) raf.length()];
raf.readFully(data);
Buffer compressed = SnappyCompressor.compress(data);
long l = 0;
Buffer b = new Buffer();
int iterations = 4000;
long t0 = System.nanoTime();
for(int i=0; i<iterations; i++) {
l += SnappyDecompressor.decompress(compressed, b).getLength();
}
long t1 = System.nanoTime();
lall += l;
tall += (t1-t0);
System.out.println(f.getName() + ": " + String.format("%.2f", (l * 1000000000. / (t1-t0))/(1024*1024)));
}
System.out.println("all: " + String.format("%.2f", (lall * 1000000000. / (tall))/(1024*1024)));
System.out.println();
}
}
|
2ee7b3cc-90b0-4c6f-aa13-351eb39a9521
| 2
|
protected void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession(true);
HashMap<Product,Integer> map = (HashMap<Product,Integer>)session.getAttribute("cart");
int uid = (int)((User)session.getAttribute("currentSessionUser")).getId();
List<Order> cart;
try {
cart = OrderDAO.list(uid);
if (cart.size() != 0)
req.setAttribute("cart", cart);
} catch (SQLException e) {
e.printStackTrace();
res.sendRedirect("products");
}
//if ((map) != null) {
/*try {
List<Product> prods = ProductDAO.list(-1);
for (Map.Entry<Product, Integer> entry : map.entrySet()) {
if (prods.contains(entry.getKey())) {
prods.
}
map.put(ProductDAO.find("id", (int)(entry.getKey().getId())), map.remove(entry.getKey()));
}
} catch (SQLException e) {}*/
//session.setAttribute("cart", map);
//}
req.getRequestDispatcher("buyCart.jsp").forward(req, res);
}
|
6eb6bea8-3638-4f97-8c49-8431f2885f47
| 7
|
static Handler remove(Handler h, Label start, Label end) {
if (h == null) {
return null;
} else {
h.next = remove(h.next, start, end);
}
int hstart = h.start.position;
int hend = h.end.position;
int s = start.position;
int e = end == null ? Integer.MAX_VALUE : end.position;
// if [hstart,hend[ and [s,e[ intervals intersect...
if (s < hend && e > hstart) {
if (s <= hstart) {
if (e >= hend) {
// [hstart,hend[ fully included in [s,e[, h removed
h = h.next;
} else {
// [hstart,hend[ minus [s,e[ = [e,hend[
h.start = end;
}
} else if (e >= hend) {
// [hstart,hend[ minus [s,e[ = [hstart,s[
h.end = start;
} else {
// [hstart,hend[ minus [s,e[ = [hstart,s[ + [e,hend[
Handler g = new Handler();
g.start = end;
g.end = h.end;
g.handler = h.handler;
g.desc = h.desc;
g.type = h.type;
g.next = h.next;
h.end = start;
h.next = g;
}
}
return h;
}
|
15cab20d-dbee-4209-8f40-d9b86aa058ae
| 6
|
public void drawAATrapezoid(float line0, float line1, float x0, float x1, float x2, float x3 ) {
for (int y = line0 < 0 ? 0 : (int)Math.round(line0); y < (int)Math.round(line1) && y < h; ++y) {
int lx0 = (int)(x0 + (y + 0.5f - line0) * (x2 - x0) / (line1 - line0));
int lx1 = (int)(x1 + (y + 0.5f - line0) * (x3 - x1) / (line1 - line0));
if( lx0 < 0 ) lx0 = 0;
if( lx1 >= w ) lx1 = w;
for( int i = y * w + lx0, i1 = y * w + lx1; i < i1; ++i ) {
this.r[i] = drawR;
this.g[i] = drawG;
this.b[i] = drawB;
}
}
}
|
4aab74d6-2173-4a2b-a9d5-5ca4cd61febf
| 9
|
public void inicializarTransformador() {
String inicializar = inicializarTiposTransformador();
if (puntoLuz.getTransformador() == null) {
puntoLuz.setTransformador(new Transformador());
puntoLuz.getTransformador().setFabricante(new Fabricante());
puntoLuz.getTransformador().setTipoTransformador(new TipoTransformador());
puntoLuz.getTransformador().setTipoConexionTransformador(new TipoConexionTransformador());
puntoLuz.getTransformador().setFase(new Fase());
puntoLuz.getTransformador().setFrecuencia(new Frecuencia());
puntoLuz.getTransformador().setPotencia(new Potencia());
puntoLuz.getTransformador().setVoltajeAlta(new Voltaje());
puntoLuz.getTransformador().setVoltajeBaja(new Voltaje());
} else {
if (puntoLuz.getTransformador().getTipoTransformador() == null) {
puntoLuz.getTransformador().setTipoTransformador(new TipoTransformador());
}
if (puntoLuz.getTransformador().getFabricante() == null) {
puntoLuz.getTransformador().setFabricante(new Fabricante());
}
if (puntoLuz.getTransformador().getFrecuencia() == null) {
puntoLuz.getTransformador().setFrecuencia(new Frecuencia());
}
if (puntoLuz.getTransformador().getFase() == null) {
puntoLuz.getTransformador().setFase(new Fase());
}
if (puntoLuz.getTransformador().getTipoConexionTransformador() == null) {
puntoLuz.getTransformador().setTipoConexionTransformador(new TipoConexionTransformador());
}
if (puntoLuz.getTransformador().getVoltajeAlta() == null) {
puntoLuz.getTransformador().setVoltajeAlta(new Voltaje());
}
if (puntoLuz.getTransformador().getVoltajeBaja() == null) {
puntoLuz.getTransformador().setVoltajeBaja(new Voltaje());
}
if (puntoLuz.getTransformador().getPotencia() == null) {
puntoLuz.getTransformador().setPotencia(new Potencia());
}
}
}
|
ce29a7af-f692-4a2f-9d9e-d23216fb82f3
| 2
|
public static String[] searchProduct(Integer ID) {
Database db = dbconnect();
String [] Array = null;
try {
String query = ("SELECT * FROM product WHERE PID = ?");
db.prepare(query);
db.bind_param(1, ID.toString());
ResultSet rs = db.executeQuery();
while(rs.next()) {
Array = new String[]{rs.getString(rs.getMetaData().getColumnName(2)),
rs.getString(rs.getMetaData().getColumnName(3))};
}
db.close();
} catch (SQLException e) {
Error_Frame.Error(e.toString());
}
return Array;
}
|
e710f2a2-83eb-4672-b94a-6e30481c1d44
| 3
|
public static ArrayList<Item> generateContents(int containerSize, int density){
ArrayList<Item> returnlist = new ArrayList<Item>();
Random rand = new Random(System.currentTimeMillis());
if (possibilities.isEmpty()) {
makePossibilities();
}
for (int x = 0; x < containerSize; x++){
if (rand.nextInt(100) <= density){
returnlist.add(getRandomItem(rand));
} else {
returnlist.add(null);
}
}
return returnlist;
}
|
7358796a-fc8e-4592-9ca8-12f882979ee3
| 5
|
protected void validateInterval(int start, int end)
{
if (end < start)
throw new RuntimeException("Wrong interval: end < start");
// Console.Out.WriteLine("Checking interval "+start+" - " +end +" on "+name);
if (start < 0 || start > fileSize)
throw new RuntimeException("Wrong interval: start out of bounds");
if (end < 0 || end > fileSize)
throw new RuntimeException("Wrong interval: end out of bounds");
}
|
988bab98-3fe4-41ee-a725-ca638a033af2
| 4
|
public void AddPHPFileToDatabase(DatabaseAccess JavaDBAccess, String host, String url, int port, String FileURL) {
File PHPFile; //The PHP file where we want to inject the vulnerabilities
String filename = "." + File.separator;
Connection conn = null;
JFileChooser fc = new JFileChooser(new File(filename));
fc.setDialogTitle("Open VulnOpXSSAttacks.xml program to get its location");
class MyFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
String filename = file.getName();
return filename.endsWith(".php");
}
public String getDescription() {
return "*.php";
}
}
// fc.addChoosableFileFilter(new MyFilter());
// Show open dialog; this method does not return until the dialog is closed
int returnVal = fc.showOpenDialog(new JFrame());
if (returnVal == JFileChooser.APPROVE_OPTION) {
// System.out.println("You chose to open this file: " + fc.getSelectedFile().getName());
PHPFile = fc.getSelectedFile();
try {
if ((conn = JavaDBAccess.setConn()) != null) {
System.out.println("Connected to database " + JavaDBAccess.getDatabaseName());
} else {
throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName());
}
JavaDBAccess.ReadFile2DB(PHPFile, host, url, FileURL, JavaDBAccess, true);
} catch (Throwable e) {
System.out.println("exception thrown:");
if (e instanceof SQLException) {
JavaDBAccess.printSQLError((SQLException) e);
} else {
e.printStackTrace();
}
}
// PHPFileTextClean = ReadFile(PHPFile);
} else {
// System.out.println("You chose not to open file");
}
}
|
a4ca7cc0-3ec8-498b-b9fd-1ea40df9346c
| 2
|
private void gameOverEvent(GameEvent gameEvent) {
gameEvent.sourceGame = this.name;
for (GameListener listener : gameListeners) {
if (listener == null)
continue;
listener.onGameEnd(gameEvent);
}
}
|
4d605e28-0a6a-484d-b6e4-9fd5e733fc10
| 2
|
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if(e.getWheelRotation()<0)
{
zoomIn();
}
else if(e.getWheelRotation()>0)
{
zoomOut();
}
}
|
a8c668c2-e16a-4105-ad1e-a53fb60635f6
| 3
|
public VentanaAgregar(){
this.config();
enviar = new JButton("Enviar");
nombre =new JLabel("Nombre: ");
direccion = new JLabel("Direccion: ");
fechaNacimiento = new JLabel("Fecha Nacimiento: ");
nombre_ = new JTextField();
direccion_ = new JTextField();
fechaNacimiento_ = new JTextField();
nombre.setBounds(10, 20, 200, 20);
direccion.setBounds(10, 50, 200, 20);
fechaNacimiento.setBounds(10, 80, 200, 20);
nombre_.setBounds(210, 20, 200, 20);
direccion_.setBounds(210, 50, 200, 20);
fechaNacimiento_.setBounds(210, 80, 200, 20);
panelNumeros = new Panel("Numeros");
panelNumeros.setBounds(50, 100, 300, 200);
panelCorreos = new Panel("Correos");
panelCorreos.setBounds(50, 300, 300, 200);
enviar.setBounds(370, 400, 100, 20);
super.add(nombre);
super.add(direccion);
super.add(fechaNacimiento);
super.add(nombre_);
super.add(direccion_);
super.add(fechaNacimiento_);
super.add(panelNumeros);
super.add(panelCorreos);
super.add(enviar);
enviar.setEnabled(true);
enviar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//System.out.println(panelNumeros.getNumeros());
//System.out.println(panelCorreos.getCorreos());
//panelCorreos = new Panel("Numeros");
//panelCorreos = new Panel("Correos");
/*limpiarTabla(panelNumeros.mt);
limpiarTabla(panelCorreos.mt);
panelNumeros.setNumeros();
panelCorreos.setCorreos(null);
*/
if(!nombre_.getText().equals("") && !direccion_.getText().equals("") && !fechaNacimiento_.getText().equals("")){
enviar.setEnabled(false);
nombre_.setEnabled(false);
direccion_.setEnabled(false);
fechaNacimiento_.setEnabled(false);
panelCorreos.boton.setEnabled(false);
panelNumeros.boton.setEnabled(false);
persona = new Persona(nombre_.getText(), direccion_.getText(), fechaNacimiento_.getText(), panelCorreos.getCorreos(), panelNumeros.getNumeros());
//System.out.println(persona);
JOptionPane.showMessageDialog(null,"Se ah agregado, cierre ahora la ventana");
}
}
});
}
|
b9706d06-79d0-469d-b8d9-276b5712faff
| 0
|
public String getPiloteJdbc() {
return piloteJdbc;
}
|
fa4121b3-649c-4224-956a-df28ea0c9231
| 0
|
public int getFileSize() {
return fileSize;
}
|
aa72f969-74e8-4b23-9691-f010a9f819b5
| 7
|
public String convert1(String s, int numRows) {
if(s.isEmpty()) {
return "";
}
if(s.length() <= numRows) {
return s;
}
StringBuilder sb = new StringBuilder(s.length());
for(int i = 0; i < numRows; i++) {
if(i%2 == 0) {
int j = i;
while(j < s.length()) {
sb.append(s.charAt(j));
j += (numRows + numRows/2);
}
}else {
int j = i;
while(j < s.length()) {
sb.append(s.charAt(j));
int next = j + (numRows - (i + 1)) + numRows/2;
if(next < s.length()) {
sb.append(s.charAt(next));
}
j += (numRows + numRows/2);
}
}
}
return sb.toString();
}
|
066126b2-e849-49d2-a333-6b85cc58e79b
| 9
|
public Credentials(String name, String pass, String path) {
this.name = null;
this.pass = null;
// the user provided in on command line
if (name != null) {
this.name = name;
if (pass != null) {
this.pass = pass;
return;
}
}
// get the missing credentials from a file
PasswordFile passwordFile = new PasswordFile(path);
passwordFile.loadCredentials();
if (this.name != null) {
if (passwordFile.getName() != null) {
if (!passwordFile.getName().equals(this.name)) {
System.out.println("Name entered on command line does not match the name in the config file.");
return;
}
}
} else {
this.name = passwordFile.getName();
}
if (this.pass == null) {
this.pass = passwordFile.getPass();
}
// the last resort, show interactive dialog
if (this.name == null || this.pass == null) {
PasswordDialog passwordDialog = new PasswordDialog();
if (passwordDialog.showDialog(this.name)) {
this.name = passwordDialog.getName();
this.pass = passwordDialog.getPass();
}
}
}
|
e2f693ac-7996-4a57-b24f-75cdf81cf723
| 4
|
private List<String> loadNoDeleteFiles(JsonObject configContent) {
List<String> noDeleteFiles = new ArrayList<String>();
if (configContent != null) {
JsonArray array = configContent.getAsJsonArray("no_delete");
if (array != null) {
for (JsonElement elem : array) {
if (elem instanceof JsonPrimitive) {
noDeleteFiles.add(((JsonPrimitive) elem).getAsString());
}
}
}
}
return noDeleteFiles;
}
|
0f473082-3ef5-4518-b43b-355724a8bc2f
| 9
|
private void prepararIteracion() {
/*
* Asignar tareas a los procesadores.
*/
for (Integer prioridadActual : this.tareasListasPorPrioridad.keySet()) {
Iterator<Tarea> it = this.tareasListasPorPrioridad.get(
prioridadActual).iterator();
while (it.hasNext()) {
Tarea tarea = it.next();
boolean tareaAsignada = false;
List<Procesador> procesadoresLibres = getProcesadoresLibres();
Iterator<Procesador> itProcesadoresLibres = procesadoresLibres
.iterator();
while (itProcesadoresLibres.hasNext()) {
Procesador procesadorLibre = itProcesadoresLibres.next();
if (procesadorLibre.setTarea(tarea)) {
this.tareasListas.remove(tarea);
tareaAsignada = true;
it.remove();
break;
}
}
if (!tareaAsignada) {
for (Procesador procesador : this.procesadores) {
// Cambio de contexto:
Tarea tareaDelProcesador = procesador.getTarea();
if (tareaDelProcesador != null
&& tareaDelProcesador.getPrioridad() > tarea
.getPrioridad()) {
this.tareasListasPorPrioridad.get(
tareaDelProcesador.getPrioridad()).add(
tareaDelProcesador);
this.tareasListas.add(tareaDelProcesador);
if (procesador.setTarea(tarea)) {
System.out.println(Global.getInstance()
.getTiempo()
+ 1
+ " Cambio de contexto:");
it.remove();
this.tareasListas.remove(tarea);
}
break;
}
}
}
}
}
}
|
40f4553c-1534-4149-8f33-09fc60386eb2
| 9
|
public String toString() {
String s = "";
for (int i = 0; i < dungeon.size(); i++) {
for (int j = 0; j < dungeon.size(); j++) {
Site site = new Site(i, j);
if (rogueSite.equals(monsterSite) && (rogueSite.equals(site))) s += "* ";
else if (rogueSite.equals(site)) s += ROGUE + " ";
else if (monsterSite.equals(site)) s += monsterDisp + " ";
else if (dungeon.isRoom(site)) s += ". ";
else if (dungeon.isCorridor(site)) s += "+ ";
else if (dungeon.isWall(site)) s += " ";
}
s += NEWLINE;
}
return s;
}
|
e53f1d15-8697-4fdd-b6cc-ea329f8427b7
| 3
|
public PlayerSave loadMythgame(String playerName, String playerPass)
{
boolean exists = (new File("./savedGames/"+playerName+".dat")).exists();
PlayerSave tempPlayer;
try { if(exists || mythRetry == 3){
ObjectInputStream in = new ObjectInputStream(new FileInputStream("./savedGames/"+playerName+".dat"));
tempPlayer = (PlayerSave)in.readObject();
in.close();
System.out.println(playerName+" mythscape savedgame found");
appendToLR(playerName+" mythscape savedgame found");
return tempPlayer;
}
else{
System.out.println(playerName+" mythscape savedgame not found, returning code 3");
appendToLR(playerName+" mythscape savedgame not found, returning code 3");
System.out.println(playerName+" retrying to load mythscape savegame");
appendToLR(playerName+" retrying to load mythscape savegame");
mythRetry += 1;
}
}
catch(Exception e){
return null;
}
return null;
}
|
5d160f49-2031-43e2-a9e5-ecde70bd056f
| 1
|
public void stem()
{ k = i - 1;
if (k > 1) { step1(); step2(); step3(); step4(); step5(); step6(); }
i_end = k+1; i = 0;
}
|
7b30e27b-ff23-470e-88f9-5075d2b37a99
| 9
|
final public void columnAndAlias() throws ParseException {
/*@bgen(jjtree) columnAndAlias */
SimpleNode jjtn000 = new SimpleNode(JJTCOLUMNANDALIAS);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtn000.jjtSetFirstToken(getToken(1));
try {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case STRING:
jj_consume_token(STRING);
break;
case MUL:
jj_consume_token(MUL);
break;
default:
jj_la1[2] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 67:
jj_consume_token(67);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case STRING:
jj_consume_token(STRING);
break;
case MUL:
jj_consume_token(MUL);
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
jj_la1[4] = jj_gen;
;
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtn000.jjtSetLastToken(getToken(0));
}
}
}
|
0448a00a-d658-4a30-a618-889c39f7553f
| 4
|
static public byte[] decode(byte[] in)
{
String out = new String(""); //We'll use a string so we don't need any expanding arrays
int bits, tbits;
HuffmanNode tmp;
if(unsigned(in[0]) == 0xFF)
{
return Arrays.copyOfRange(in, 1, in.length);
}
tbits = (in.length-1)*8 - unsigned(in[0]);
bits = 0;
in = Arrays.copyOfRange(in, 1, in.length);
while(bits < tbits)
{
tmp = huffTree;
do
{
if(getBit(in, bits))
tmp = tmp.one;
else
tmp = tmp.zero;
bits++;
}
while(tmp.zero != null);
char[] outTmp = {tmp.val};
out += new String(outTmp);
}
return out.getBytes();
}
|
64bcfda0-92df-4fcb-923a-b56bccf891d7
| 0
|
public static void setTipoFunc(String tipoFunc) {
Funcionario.tipoFunc = tipoFunc;
}
|
02553ff4-f626-4fc8-bd65-1d26276e0ecd
| 3
|
private void paste() {
try {
switch(style) {
case INTEGERS:
text += Integer.parseInt((String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor));
break;
default:
text += (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
break;
}
} catch (NumberFormatException e) {
} catch (IOException | HeadlessException | UnsupportedFlavorException e) {
e.printStackTrace();
}
}
|
7a5fc3dc-a0ec-470c-8929-1df6825c9a18
| 1
|
public static void initializeDataBaseSimulator(String fileName) throws Exception
{
DBSIMULATOR = new HashMap<String, DataPoint>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line="";
while((line=reader.readLine())!=null)
{
DataPoint current = new DataPoint(line);
DBSIMULATOR.put(current.getID(),current);
}
}
|
598a4bca-dbd7-4809-b236-3677ddbbeee7
| 0
|
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
|
d2319c4b-c364-452b-9aed-bfefd76d0162
| 9
|
public void paintTrack(Graphics g) {
boolean leftToRight = JTattooUtilities.isLeftToRight(slider);
g.translate(trackRect.x, trackRect.y);
int overhang = 4;
int trackLeft = 0;
int trackTop = 0;
int trackRight = 0;
int trackBottom = 0;
if (slider.getOrientation() == JSlider.HORIZONTAL) {
trackBottom = (trackRect.height - 1) - overhang;
trackTop = trackBottom - (getTrackWidth() - 1);
trackRight = trackRect.width - 1;
} else {
if (leftToRight) {
trackLeft = (trackRect.width - overhang) - getTrackWidth();
trackRight = (trackRect.width - overhang) - 1;
} else {
trackLeft = overhang;
trackRight = overhang + getTrackWidth() - 1;
}
trackBottom = trackRect.height - 1;
}
g.setColor(AbstractLookAndFeel.getFrameColor());
g.drawRect(trackLeft, trackTop, (trackRight - trackLeft) - 1, (trackBottom - trackTop) - 1);
int middleOfThumb = 0;
int fillTop = 0;
int fillLeft = 0;
int fillBottom = 0;
int fillRight = 0;
if (slider.getOrientation() == JSlider.HORIZONTAL) {
middleOfThumb = thumbRect.x + (thumbRect.width / 2);
middleOfThumb -= trackRect.x;
fillTop = trackTop + 1;
fillBottom = trackBottom - 2;
if (!drawInverted()) {
fillLeft = trackLeft + 1;
fillRight = middleOfThumb;
} else {
fillLeft = middleOfThumb;
fillRight = trackRight - 2;
}
Color colors[] = null;
if (!JTattooUtilities.isActive(slider)) {
colors = AbstractLookAndFeel.getTheme().getInActiveColors();
} else {
if (slider.isEnabled()) {
colors = AbstractLookAndFeel.getTheme().getSliderColors();
} else {
colors = AbstractLookAndFeel.getTheme().getDisabledColors();
}
}
JTattooUtilities.fillHorGradient(g, colors, fillLeft + 2, fillTop + 2, fillRight - fillLeft - 2, fillBottom - fillTop - 2);
Color cHi = ColorHelper.darker(colors[colors.length - 1], 5);
Color cLo = ColorHelper.darker(colors[colors.length - 1], 10);
JTattooUtilities.draw3DBorder(g, cHi, cLo, fillLeft + 1, fillTop + 1, fillRight - fillLeft - 1, fillBottom - fillTop - 1);
} else {
middleOfThumb = thumbRect.y + (thumbRect.height / 2);
middleOfThumb -= trackRect.y;
fillLeft = trackLeft + 1;
fillRight = trackRight - 2;
if (!drawInverted()) {
fillTop = middleOfThumb;
fillBottom = trackBottom - 2;
} else {
fillTop = trackTop + 1;
fillBottom = middleOfThumb;
}
Color colors[] = null;
if (!JTattooUtilities.isActive(slider)) {
colors = AbstractLookAndFeel.getTheme().getInActiveColors();
} else {
if (slider.isEnabled()) {
colors = AbstractLookAndFeel.getTheme().getSliderColors();
} else {
colors = AbstractLookAndFeel.getTheme().getDisabledColors();
}
}
JTattooUtilities.fillVerGradient(g, colors, fillLeft + 2, fillTop + 2, fillRight - fillLeft - 2, fillBottom - fillTop - 2);
Color cHi = ColorHelper.darker(colors[colors.length - 1], 5);
Color cLo = ColorHelper.darker(colors[colors.length - 1], 10);
JTattooUtilities.draw3DBorder(g, cHi, cLo, fillLeft + 1, fillTop + 1, fillRight - fillLeft - 1, fillBottom - fillTop - 1);
}
g.translate(-trackRect.x, -trackRect.y);
}
|
4825fc5f-09b3-42a1-9aee-5f881635301e
| 7
|
public boolean isOfTypes(Class<?>... classes) {
if (classes.length != size)
return false;
for (int i = 0; i < size; i++) {
if (items[i] == null)
continue;
String inTuple = box(items[i].getClass().toString()
.replaceAll("java.lang.", "").replaceAll("class", "")
.replaceAll(" ", ""));
String inClass = box(classes[i].toString()
.replaceAll("java.lang.", "").replaceAll("class", "")
.replaceAll(" ", ""));
if (!inTuple.equalsIgnoreCase(inClass)
&& !(items[i].getClass().isAssignableFrom(classes[i]) || classes[i]
.isAssignableFrom(items[i].getClass())))
return false;
}
return true;
}
|
e8a1d3ad-ee8e-46b4-af1f-5c4ef653e233
| 7
|
public T predecessor(T data) {
if (this.isEmpty())
return null;
if (this.getData().compareTo(data) < 0) {
if (this.getRight() == null)
return null;
T tmp;
if ((tmp = this.getRight().predecessor(data)) == null)
return this.getData();
return tmp;
}
if (this.getData().compareTo(data) > 0) {
if (this.getLeft() == null)
return null;
return this.getLeft().predecessor(data);
}
if (this.getLeft() == null)
return null;
return this.getLeft().searchMax();
}
|
192f88f4-c271-4ce2-9a84-fde1208ed264
| 8
|
@Override
public RemoteClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject object = (JsonObject) json;
String name = null;
String doc = null;
boolean abstractValue = false;
TypeRef extendsValue = null;
Method constructor = null;
List<Method> methods = new ArrayList<Method>();
List<Property> properties = new ArrayList<Property>();
List<TypeRef> events = new ArrayList<TypeRef>();
if (object.get("name") != null) {
name = object.get("name").getAsString();
}
if (object.get("doc") != null) {
doc = object.get("doc").getAsString();
}
if (object.get("abstract") != null) {
abstractValue = object.get("abstract").getAsBoolean();
}
if (object.get("extends") != null) {
extendsValue = context.deserialize(object.get("extends"), TypeRef.class);
}
if (object.get("constructor") != null) {
constructor = context.deserialize(object.get("constructor"), new TypeToken<Method>() {
}.getType());
}
if (object.get("methods") != null) {
methods = context.deserialize(object.get("methods"), new TypeToken<List<Method>>() {
}.getType());
}
if (object.get("properties") != null) {
properties = context.deserialize(object.get("properties"), new TypeToken<List<Property>>() {
}.getType());
}
if (object.get("events") != null) {
events = context.deserialize(object.get("events"), new TypeToken<List<TypeRef>>() {
}.getType());
}
RemoteClass remoteClass = new RemoteClass(name, doc, extendsValue, constructor, methods,
properties, events);
remoteClass.setAbstract(abstractValue);
return remoteClass;
}
|
59afee9f-743a-4244-a12c-2fdf27479078
| 9
|
@Override
protected void paintComponent(Graphics g) {
//Clears the window so it can be updated
super.paintComponent(g);
//Paints the updated image(s) inside of the window
ImageIcon icon1 = new ImageIcon(GetBlackjackTable.class.getResource("/DragonBoard.jpg"));
Image background = icon1.getImage();
ImageIcon icon2 = new ImageIcon(GetBlackjackTable.class.getResource("/Face Down.png"));
Image facedown = icon2.getImage();
g.drawImage(background, 0, 0, 900, 600, this);
//Draws the players' cards on the screen
for (int i = 0; i < playerCards.length; i++) {
for (int j = 0; j < playerCards[0].length; j++) {
for (int k = 0; k < playerCards[0][0].length; k++) {
g.drawImage(playerCards[i][j][k], 10 + 300 * i + 30 * k, 350 + 70 * j, 49, 65, this);
}
}
}
//Draws the dealer's cards on the screen
for (int i = 0; i < dealerCards.length; i++) {
if (dealerInitialized) {
if (dealer.getHand().sizeOfHand() == 2) {
if (i == 0)
g.drawImage(dealerCards[i], 170, 120, 49, 65, this);
else if (i == 1)
g.drawImage(facedown, 170 + 30 * i, 120, 49, 65, this);
}
}
else if (dealerCards[i] != null)
g.drawImage(dealerCards[i], 170 + 30 * i, 120, 49, 65, this);
}
}
|
585b82bf-c52d-4407-8780-158841a7cc02
| 4
|
public Set<T> getSet(int i)
{ Set<T> res=null;
if(this.size()<=i)
{ return this;
}
else
{ for(Set<T> p=this;p!=null;p=p.next)
{ if(i>0)
{ if(res==null)
{ res=new Set(p.a,null);
}
else
{ res=res.ins(p.a);
}
i--;
}
else
{ break;
}
}
return res;
}
}
|
2f39eea3-f291-4e3a-bdd9-1a7f0fe12b20
| 1
|
public void closeWriter() {
try {
this.writer.flush();
this.writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
a2efcc8b-e6d3-4b3b-ac85-d728bdfceef1
| 0
|
@Override
public void onError(ModelNotification notification) {
setChanged();
notifyObservers(notification);
errorsWhileStarting = true;
stopServer();
}
|
17208f50-30ae-4da4-940a-b31ac3504362
| 4
|
public void buttonBuscarResultados() {
destinoDAO = new DestinoDAO();
paisDAO = new PaisDAO();
listaDestinosAproximados = new ArrayList<>();
List<Destino> listaDestinosRetornados = destinoDAO.listar();
BigDecimal doubleArredondado = null;
boolean achouCompativel = true;
String nomeLocal = "";
int[] listaIDCombosView = new int[5];
listaIDCombosView [0] = selecionaDestinoView.getjComboBoxTipo().getSelectedIndex() + 1;
listaIDCombosView [1] = selecionaDestinoView.getjComboBoxAtividade().getSelectedIndex() + 1 ;
listaIDCombosView [2] = paisDAO.idPaisCombo(selecionaDestinoView.getjComboBoxPais().getSelectedItem().toString());
listaIDCombosView [3] = selecionaDestinoView.getjComboBoxInfraestrutura().getSelectedIndex() + 1;
listaIDCombosView [4] = selecionaDestinoView.getjComboBoxCaracteristica().getSelectedIndex() + 1;
if(listaDestinosRetornados.isEmpty()) {
JOptionPane.showMessageDialog(null, "Nenhum destino cadastrado no sistema.\nVá para 'Gestão de Desinos' e cadastre ao menos um.");
} else {
int[] listaIDBD = new int[5];
for(Destino destinoComparado : listaDestinosRetornados) {
listaIDBD[0] = destinoComparado.getIdTipo();
listaIDBD[1] = destinoComparado.getIdAtividade();
listaIDBD[2] = destinoComparado.getIdPais();
listaIDBD[3] = destinoComparado.getIdInfrestrutura();
listaIDBD[4] = destinoComparado.getIdCaracteristica();
if(Arrays.equals(listaIDCombosView, listaIDBD)) {
nomeLocal = destinoComparado.getNomeDestino();
achouCompativel = true;
} else {
for(int i = 0; i<=4; i++) {
double proximidadeModular = Math.abs((listaIDBD[i]-listaIDCombosView[i])*(i+1));
double proximidadePercentual = (((1/(proximidadeModular+1))*((5-i)*(100/15))));//15 é a soma dos pesos das variáveis (tipo local, atividade...) escolhidas
doubleArredondado = new BigDecimal(proximidadePercentual).setScale(1, RoundingMode.DOWN);
somatorioProximidadeModular = somatorioProximidadeModular + proximidadeModular;
somatorioProximidadePercentual = somatorioProximidadePercentual + doubleArredondado.doubleValue();
}
destinoAproximado = new DestinoAproximado();
destinoAproximado.setNomeDestinoAproximado(destinoComparado.getNomeDestino());
destinoAproximado.setProximidadeModular(somatorioProximidadeModular);
destinoAproximado.setProximidadePercentual(somatorioProximidadePercentual);
listaDestinosAproximados.add(destinoAproximado);
somatorioProximidadeModular = 0;
somatorioProximidadePercentual = 0;
achouCompativel = false;
}
}
}
achouCompativel(achouCompativel, nomeLocal);
}
|
a1b4f456-a26a-4201-b25b-95b7ebd26603
| 4
|
public String getRelationship(){
String relationshipStatus = new String();
if(love<-5){
relationshipStatus = "an enemy";
}
else if(love<-1){
relationshipStatus = "a nuisance";
}
else if(love<1){
relationshipStatus = "a person";
}
else if(love<5){
relationshipStatus = "an acquaintance";
}
else{
relationshipStatus = "a friend";
}
return(thisName + " considers " + otherName + " to be " + relationshipStatus + ".");
}
|
19458886-3bd0-4a33-a468-81c8fd74d9ca
| 1
|
public void weeklyBonus(Player player)
{
if (color == player.getColor()) {
type.weeklyBonus(player);
}
}
|
ec19b67b-77ff-4b94-a064-3dfd336fb202
| 0
|
public boolean isEmpty() {
return first == null;
}
|
72687953-c072-44b7-8247-52756a62efff
| 8
|
public mxRectangle getCellContainmentArea(Object cell)
{
if (cell != null && !model.isEdge(cell))
{
Object parent = model.getParent(cell);
if (parent == getDefaultParent() || parent == getCurrentRoot())
{
return getMaximumGraphBounds();
}
else if (parent != null && parent != getDefaultParent())
{
mxGeometry g = model.getGeometry(parent);
if (g != null)
{
double x = 0;
double y = 0;
double w = g.getWidth();
double h = g.getHeight();
if (isSwimlane(parent))
{
mxRectangle size = getStartSize(parent);
x = size.getWidth();
w -= size.getWidth();
y = size.getHeight();
h -= size.getHeight();
}
return new mxRectangle(x, y, w, h);
}
}
}
return null;
}
|
bd905f8f-5845-4dd0-8699-affafde5ed3f
| 0
|
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("SHS BankServlet: doPost()");
processRequest(request, response);
}
|
86d138a7-f9f0-4e32-8ffe-a95e50d584ed
| 1
|
double[] randomSample() {
double[] sample = new double[n];
for (int i = 0; i < n; i++) {
sample[i] = (lowBound[i] + generator.nextDouble() * (upBound[i] - lowBound[i]));
}
return sample;
}
|
914999f4-047a-4b9f-be3c-76b1c00cd147
| 6
|
public void mouseDragged(MouseEvent me)
{
// if out of range, don't even look at it
if (me.getX() < 0 || me.getX() > squareSize * cols || me.getY() < 0
|| me.getY() > squareSize * rows)
return;
int x = me.getX() - 1, y = me.getY() - 1;
if (x < squareSize * cols)
{
// if in area with colors set color to clicked on one
int newCol = (x / (this.squareSize)) + (y / this.squareSize) * cols;
// System.out.println("Selected color #" + newCol);
if (newCol < pal.length)
this.setSelectedColorIndex(newCol);
}
}
|
75c17f6e-9bbb-40ba-a36f-c75a11e03ebf
| 7
|
public void setWapSignalFromString(String s)
{
if (s == null)
{
wapSignal = WAP_SIGNAL_MEDIUM;
return;
}
s = s.trim();
if (s.equalsIgnoreCase("none"))
{
wapSignal = WAP_SIGNAL_NONE;
}
else if (s.equalsIgnoreCase("low"))
{
wapSignal = WAP_SIGNAL_LOW;
}
else if ((s.equalsIgnoreCase("medium")) || (s.equals("")))
{
wapSignal = WAP_SIGNAL_MEDIUM;
}
else if (s.equalsIgnoreCase("high"))
{
wapSignal = WAP_SIGNAL_HIGH;
}
else if (s.equalsIgnoreCase("delete"))
{
wapSignal = WAP_SIGNAL_DELETE;
}
else
{
throw new RuntimeException("Cannot determine WAP signal to use");
}
}
|
4faad010-32df-4c02-9c0a-abac4e726350
| 2
|
private void initializeView()
{
this.setOpaque(true);
this.setLayout(new BorderLayout());
resourcePanel = new JPanel();
resourcePanel.setLayout(new BoxLayout(resourcePanel, BoxLayout.Y_AXIS));
resourcePanel.setBackground(Color.WHITE);
for(ResourceBarElement type : resourceElementList)
{
resourcePanel.add(resources.get(type).asJComponent());
}
this.add(resourcePanel, BorderLayout.CENTER);
JPanel discardButtonPanel = new JPanel();
discardButtonPanel.setBackground(Color.WHITE);
if(TESTING)
{
testButton = new JButton("Enable");
testButton.addActionListener(actionListener);
discardButtonPanel.add(testButton);
}
this.setBackground(Color.WHITE);
this.add(discardButtonPanel, BorderLayout.SOUTH);
}
|
34066db6-7990-4fd5-a486-0b899055ce53
| 1
|
public boolean replaceSubBlock(StructuredBlock oldBlock,
StructuredBlock newBlock) {
if (innerBlock == oldBlock)
innerBlock = newBlock;
else
return false;
return true;
}
|
5e0139db-7eac-4795-8d33-62d3e40eecec
| 2
|
public void gotfocus() {
if (focusctl && (focused != null)) {
focused.hasfocus = true;
focused.gotfocus();
}
}
|
1d427294-c952-4caa-a128-fe4c7f37e8ed
| 5
|
public boolean isComplete()
{
try
{
boolean emptyFields = false;
String name = nameField.getText();
String magneticHeading = magneticHeadingField.getText();
//String altitude = altitudeField.getText();
nameField.setBackground(Color.WHITE);
magneticHeadingField.setBackground(Color.WHITE);
//altitudeField.setBackground(Color.WHITE);
if(name.isEmpty())
{
nameField.setBackground(Color.PINK);
emptyFields = true;
}
if(magneticHeading.isEmpty())
{
magneticHeadingField.setBackground(Color.PINK);
emptyFields = true;
}
/*if(altitude.isEmpty())
{
altitudeField.setBackground(Color.PINK);
emptyFields = true;
}*/
if (emptyFields){
throw new Exception("");
}
Float.parseFloat(magneticHeading);
//Float.parseFloat(altitude);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(rootPane, "Please input correct numerical values", "Error", JOptionPane.INFORMATION_MESSAGE);
//ew = new ErrWindow("Please input correct numerical values");
return false;
}catch(Exception e){
JOptionPane.showMessageDialog(rootPane, "Please complete all required fields\n" + e.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
//ew = new ErrWindow("Please complete all required fields\n" + e.getMessage());
return false;
}
return true;
}
|
7ec1feec-16ea-4b0f-bd60-584535ee045d
| 0
|
public int getType() {return this.type;}
|
d43ef975-5230-4384-ac00-2460d7376f17
| 0
|
public byte[] getBytes() {
return this.data.array();
}
|
12a9e752-0b16-435e-964e-5bdec222599e
| 7
|
@Override
public void run() {
log.warn("The creation of Linux shell-scripts is an untested feature and not supported!");
if (targetScriptFolder== null)targetScriptFolder = new File(".");
if (runsh == null) runsh = new File("run.sh");
if (!runsh.isFile()) {
log.error("run.sh searched at " + runsh.getAbsolutePath() + " does not point to a valid file. Please specify a valid file location using the runsh=<> command line parameter");
return;
}
if (!runsh.canRead()) {
log.error("run.sh located at " + runsh + " cannot be read. Please check file permissions.");
return;
}
log.info("About to scan package " + packagename + " for classes implementing Runnable...");
List<Class<? extends Runnable>> classes = getClassesInPackage(packagename, log);
for (Class<? extends Runnable> c : classes) {
String scriptname = c.getCanonicalName().replaceAll("\\.", "_") + ".sh";
log.info("Creating script for class " + c.getCanonicalName() + " in as " + scriptname + " in directory " + targetScriptFolder.getAbsolutePath());
copy(log, runsh, new File(targetScriptFolder, scriptname), c.getCanonicalName());
// System.out.println("Found: " + c.getCanonicalName());
}
}
|
f0a516f7-5309-4f66-b2c0-6f8ea6f075a2
| 2
|
public void testPropertySetDayOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfYear().setCopy(12);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-01-12T00:00:00.000Z", copy.toString());
try {
test.dayOfYear().setCopy(367);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.dayOfYear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
|
94feb5d3-623e-44e6-8038-5cfa632fe428
| 7
|
private static void recursivelyCatalogPDFs(java.util.ArrayList<File> allFiles, File directory) {
File[] children = directory.listFiles();
if(children != null && children.length > 0) {
java.util.ArrayList<File> directories = new java.util.ArrayList<File>(children.length);
java.util.ArrayList<File> files = new java.util.ArrayList<File>(children.length);
for(int i = 0; i < children.length; i++) {
if(children[i].isDirectory()) {
String name = children[i].getName();
if (!name.startsWith(".")) {
directories.add(children[i]);
}
}
else if(children[i].isFile()) {
addFileIfIsPDF(files, children[i]);
}
}
Collections.sort(directories);
Collections.sort(files);
for(int i = 0; i < directories.size(); i++) {
//System.out.println("Directory: " + directories.get(i));
recursivelyCatalogPDFs(allFiles, (File) directories.get(i));
}
allFiles.addAll(files);
}
}
|
77893a4d-ad61-416e-8c01-7553c6263796
| 4
|
public boolean insertSkillScore(String employeeId, String skillName,
int ratingId) {
String sql = INSERT_SKILL_SCORE;
Connection connection = new DbConnection().getConnection();
PreparedStatement preparedStatement = null;
boolean flag = false;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, employeeId);
preparedStatement.setInt(2, CommonUtil.getSkillId(skillName));
preparedStatement.setInt(3, ratingId);
preparedStatement.executeUpdate();
flag = true;
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
} finally {
try {
if (connection != null)
connection.close();
if (preparedStatement != null)
preparedStatement.close();
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
}
}
return flag;
}
|
df809df2-66c9-48a0-9f16-6b606e00fdc4
| 2
|
@Override
public List<Country> load(Criteria criteria, GenericLoadQuery loadGeneric, Connection conn) throws DaoQueryException {
int pageSize = 50;
List paramList = new ArrayList<>();
StringBuilder sb = new StringBuilder(WHERE);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_ID_COUNTRY, DB_COUNTRY_ID_COUNTRY, criteria, paramList, sb, AND);
Appender.append(DAO_COUNTRY_NAME, DB_COUNTRY_NAME, criteria, paramList, sb, AND);
Appender.append(DAO_COUNTRY_STATUS, DB_COUNTRY_STATUS, criteria, paramList, sb, AND);
Appender.append(DAO_COUNTRY_PICTURE, DB_COUNTRY_PICTURE, criteria, paramList, sb, AND);
Appender.append(DAO_ID_DESCRIPTION, DB_COUNTRY_ID_DESCRIPTION, criteria, paramList, sb, AND);
if (paramList.isEmpty()) {
return LOAD_QUERY;
} else {
return sb.insert(0, LOAD_QUERY).toString();
}
}
}.mapQuery();
try {
return loadGeneric.sendQuery(queryStr, paramList.toArray(), pageSize, conn, (ResultSet rs, int rowNum) -> {
Country bean = new Country();
bean.setIdCountry(rs.getInt(DB_COUNTRY_ID_COUNTRY));
bean.setName(rs.getString(DB_COUNTRY_NAME));
bean.setStatus(rs.getShort(DB_COUNTRY_STATUS));
bean.setPicture(rs.getString(DB_COUNTRY_PICTURE));
bean.setDescription(new Description(rs.getInt(DB_COUNTRY_ID_DESCRIPTION)));
return bean;
});
} catch (DaoException ex) {
throw new DaoQueryException(ERR_COUNTRY_LOAD, ex);
}
}
|
5f872988-5daa-4771-980a-bc4eafa1076d
| 0
|
public int getSequence_Id() {
return sequence_Id;
}
|
b1673279-5196-4396-98da-13108ab066c7
| 0
|
public GUITreeComponentRegistry() {}
|
56257fb9-0edc-4218-a691-91765f265ec3
| 3
|
private ConnectionableCapability getSourceCapability( int x, int y ){
float bestScore = 1.0f;
ConnectionableCapability result = null;
ConnectionFlavor flavor = factory.getFlavor();
for( ConnectionableCapability capability : site.getCapabilities() ){
if( capability.isSource( flavor )){
float score = capability.containsConnectionable( x, y );
if( score >= bestScore ){
bestScore = score;
result = capability;
}
}
}
return result;
}
|
223d062f-543b-4570-8b45-0dbc602b24f8
| 5
|
public Screen respondToUserInputClick(MouseEvent mouse) {
int mx = mouse.getX();
int my = mouse.getY();
if(connectButton.intersects(mx, my)) {
if(!isHost) {
return new MultiplayerGame(Pong.ipText.getText(), Integer.parseInt(Pong.connectPortText.getText()), winScore);
}
else
Pong.ipText.setText("You are host");
}
if(hostButton.intersects(mx, my)) {
if(Pong.hostPortText.getText().equals(""))
System.out.println("Please enter a valid port");
else
return new MultiplayerGame(Integer.parseInt(Pong.hostPortText.getText()), winScore);
}
if(multiToMainButton.intersects(mx, my))
return new MainMenu(screenSize);
return this;
}
|
91bdd8b0-c158-40f1-bde4-681c448b8e33
| 0
|
@Test
public void testGetSumm() {
System.out.println("getSum");
assertEquals(12.0, new Tetrahedron(1.5,2,3.5,12).getSum(), 0.00001);
}
|
a9bf04bf-aa8c-4a6e-8eac-3893bf923dbc
| 0
|
public LSystem getLSystem() {
return input.getLSystem();
}
|
b1a04f44-1af1-4102-8e05-63ee32ecac3a
| 2
|
public String findString(String key, String value, String find) {
for (int i = 0; i < lines.size(); i++) {
Line line = new Line(lines.get(i));
if (line.getString(key).equals(value)) {
return line.getString(find);
}
}
return null;
}
|
df9a5078-1f1c-4c2c-a818-e41d88921d70
| 8
|
public void paintComponent(Graphics g){
expertamd.setFont(normal);
experenv.setFont(normal);
Series.setFont(normal);
ExactName.setFont(normal);
PoolInfo.setFont(normal);
CoinCalc.setFont(normal);
ExpertModeCheckBox.setFont(normal);
Walletaddress.setFont(normal);
StartMining.setFont(normal);
ExperModeField.setFont(normal);
g.drawImage(ResourceLoader.ImageLoad("/background.png"), 0, 0, null);
g.drawImage(ResourceLoader.ImageLoad("/xminer_logo_neoscrypt.png"),321,50,null);
g.drawImage(ResourceLoader.ImageLoad("/input_bar.png"),241, 256,null);
g.drawImage(ResourceLoader.ImageLoad("/status_text_bg3.png"),53,36,null);
g.drawImage(ResourceLoader.ImageLoad("/status_text_bg3.png"),53,106,null);
g.drawString(version,735,500);
g.setFont(ftdefault);
if(ExpertModeCheckBox.isSelected() == true){
g.drawImage(ResourceLoader.ImageLoad("/status_text_bg4.png"),56,200,null);
}
if(OtherStuff.pFTCPriceinUSDisPulled == true){
g.drawString(OtherStuff.pFTCPriceinUSD, 575, 400);
}else{
g.drawString("Fetching USD Price...", 570, 400);
}
if(OtherStuff.pFTCDiff != null && OtherStuff.pFTCDiff != "null"){
g.drawString(OtherStuff.pFTCDiff, 575, 430);
}else{
g.drawString("Fetching difficulty...", 570, 430);
}
if(ExactWalletAddress == true)
{
g.drawImage(ResourceLoader.ImageLoad("/icontrue.png"), 180, 255, 35, 35, null);
}
else if(ExactWalletAddress == false)
{
g.drawImage(ResourceLoader.ImageLoad("/iconfalse.png"), 180, 255, 35, 35, null);
}
if(ExactNameRight == true)
{
g.drawImage(ResourceLoader.ImageLoad("/icontrue.png"), 10, 105, 35, 35, null);
}
else if(ExactNameRight == false)
{
g.drawImage(ResourceLoader.ImageLoad("/iconfalse.png"), 10, 105, 35, 35, null);
}
}
|
9036dcd0-6a34-48c9-bb3c-355018aa9f67
| 0
|
@Override public void sign(String apikey) {
this.apikey = apikey;
}
|
712ee5c0-6f60-4223-b2a3-06a790bc76b1
| 4
|
public static void insertPerson(PersonBean person){
PreparedStatement pst = null;
Connection conn=null;
boolean result = false;
try {
conn=ConnectionPool.getConnectionFromPool();
pst = conn
.prepareStatement("INSERT INTO PERSON (FNAME, LNAME, ADDRESS, USERID, PASSWORD, TYPE) "
+ "VALUES (?,?,?,?,SHA1(?),?)");
pst.setString(1, person.getFname());
pst.setString(2, person.getLname());
pst.setString(3, person.getAddress());
pst.setString(4, person.getUserid());
pst.setString(5, person.getPassword());
pst.setString(6, person.getType());
result = pst.execute();
}catch (Exception e) {
System.out.println(e);
} finally {
if(conn!=null){
ConnectionPool.addConnectionBackToPool(conn);
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
22ad3820-486e-4abf-a0b2-947e05996cf4
| 9
|
public static void saveScores(int score) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(
"F:/LearnMusic!/bin/hayden/scores.txt"));
int counter = 0;
boolean condition = false;
String scores[] = new String[100];
String temp = "";
while (temp != null) {
scores[counter] = reader.readLine();
temp = scores[counter];
counter++;
}
//checks if the user scores beats their highscire
for (int i = 0; i < counter-1; i = i + 3) {
//if score is greater, it replaces high score
if (scores[i].equals(username) && Integer.parseInt(scores[i+2]) < score){
scores[i + 1] = String.valueOf(score);
scores[i + 2] = String.valueOf(score);
highscore = scores[i+2];
condition = true;
}
else if (scores[i].equals(username) && Integer.parseInt(scores[i+2]) > score){
scores[i+1] = String.valueOf(score);
highscore = scores[i+2];
condition = true;
}
}
//writes the existing user scores onto the text file
BufferedWriter writer = new BufferedWriter(new FileWriter(
"F:/LearnMusic!/bin/hayden/scores.txt"));
for(int j = 0; j < counter-1; j++){
writer.write(scores[j]);
writer.newLine();
}
//writes a new user's score onto the text file
if(condition == false){
scores[counter+1] = username;
scores[counter+2] = String.valueOf(score);
scores[counter+3] = String.valueOf(score);
for(int i = 1; i < 4 ; i++)
{
writer.write(scores[counter + i]);
writer.newLine();
}
}
writer.close();
}
|
f762c540-cffe-49fb-bea4-e4063a01c8bb
| 8
|
public static void main(String[] args) {
try { test1(); }
catch (Exception e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
try { test2(); }
catch (Exception e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
try { test3(); }
catch (Exception e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
try { test4(); }
catch (Exception e) { e.printStackTrace(); }
StdOut.println("--------------------------------");
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
double[] c = new double[N];
double[] b = new double[M];
double[][] A = new double[M][N];
for (int j = 0; j < N; j++)
c[j] = StdRandom.uniform(1000);
for (int i = 0; i < M; i++)
b[i] = StdRandom.uniform(1000);
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
A[i][j] = StdRandom.uniform(100);
Simplex lp = new Simplex(A, b, c);
StdOut.println(lp.value());
}
|
782e399c-8f55-42f9-9ef6-e2098576d53e
| 0
|
public void setBlogContentLable(String blogContentLable) {
this.blogContentLable = blogContentLable;
}
|
f186e090-de22-43e8-a9ce-7f62353860cf
| 3
|
private static void addNeighbours(LinkedList<Vertex> unobstructed)
{
if (src.getClass() != Point.class) return;
Point p = (Point)src;
if (p.getLeft().isVertex())
unobstructed.add(p.getLeft());
if (p.getRight().isVertex())
unobstructed.add(p.getRight());
}
|
4f90c53a-f40d-4dfe-aa22-26cae5712d74
| 7
|
@Override
public Void doInBackground() {
progressBar.setVisible(true);
loginScreen.repaint();
BackendInterface backend= new Backend(); //Variable to communicate with Model merely for modification and retrieval of information.
try {
backend= backend.readUser();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} //Loading program
ControlInterface control = new Control(backend); //Variable to communicate with Control and perform all logic and data processes.
Hashtable<String,User> users = new Hashtable<String,User>();
String user;
boolean done = false;
users= control.getUsers();
if(users.size()<0){
progressBar.setVisible(false);
loginScreen.repaint();
}
try{
user = usernameT.getText();
done = control.logIn(user);
if(user.equalsIgnoreCase("admin")){
admin = new AdminScreen(backend,loginScreen);
adminLoaded=true;
}
else if(!done){
userLoaded=false;
}
else{
String userName = control.getUser().getFullName();
String[] name = new String[2];
name = userName.split(" ");
sesion = new AlbumsScreen(name[0],control,backend,loginScreen);
userLoaded=true;
}
}
catch(Exception exp){
System.out.println("Please input the username, try again..."+exp);
}
return null;
}
|
6b0f4d9e-f1b4-4737-8ad6-b1c9c42114ff
| 1
|
void makeParseUneditable() {
editable = false;
try {
parseTable.getCellEditor().stopCellEditing();
} catch (NullPointerException e) {
}
}
|
8530208b-4784-4f8a-901e-c120c23ae629
| 3
|
public static Image contrast(Image original, int r1, int r2, int s1, int s2) {
if (original == null) {
return null;
}
Image img = original.shallowClone();
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
double red = contrastValue(original.getPixel(x, y, RED), r1,
r2, s1, s2);
double green = contrastValue(original.getPixel(x, y, GREEN),
r1, r2, s1, s2);
double blue = contrastValue(original.getPixel(x, y, BLUE), r1,
r2, s1, s2);
img.setPixel(x, y, RED, red);
img.setPixel(x, y, GREEN, green);
img.setPixel(x, y, BLUE, blue);
}
}
return img;
}
|
59996a66-34ba-470c-a7a2-b1f13be4aac9
| 3
|
public JSONWriter array() throws JSONException {
if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
this.push(null);
this.append("[");
this.comma = false;
return this;
}
throw new JSONException("Misplaced array.");
}
|
81275043-4cff-418d-8f08-a5f7a824aa7a
| 2
|
public TWLInputForwarder(GUI gui, Input input) {
if (gui == null) {
throw new NullPointerException("gui");
}
if (input == null) {
throw new NullPointerException("input");
}
this.gui = gui;
this.input = input;
}
|
1bdc34fa-67cd-4c7c-a06e-509c1d0cc276
| 7
|
public static int svm_check_probability_model(svm_model model) {
if (((model.param.svm_type == svm_parameter.C_SVC || model.param.svm_type == svm_parameter.NU_SVC)
&& model.probA != null && model.probB != null)
|| ((model.param.svm_type == svm_parameter.EPSILON_SVR || model.param.svm_type == svm_parameter.NU_SVR)
&& model.probA != null)) {
return 1;
} else {
return 0;
}
}
|
ff0b349d-4932-4ae6-b28b-e3e85ae9b7e9
| 4
|
public static void addBillItem(int billID, int medicineID, int quantity) {
String query = "SELECT ifnull(count(*),0) as count "
+ "FROM `billItem` "
+ "WHERE `billItem`.`billId` = '%d' "
+ "AND `billItem`.`medicineId` = '%d';";
int exists = 0;
ResultSet rs;
DBA dba = Helper.getDBA();
try {
rs = dba.executeQuery(String.format(query, billID, medicineID));
if (rs != null) {
while (rs.next()) {
exists = rs.getInt("count");
}
rs.close();
}
dba.closeConnections();
} catch (SQLException sqlEx) {
dba.closeConnections();
}
if (exists > 0) {
BillItem billItem = new BillItem();
billItem.findBillItem(billID, medicineID);
quantity += billItem.getQuanitity();
updateBillItem(billID, medicineID, quantity);
} else {
createBillItem(billID, medicineID, quantity);
}
}
|
ff75dffe-7c24-43ef-9bbe-d58830fd13bf
| 8
|
public void renderMob(int xp, int yp, Sprite sprite)
{
xp -= xOffset;
yp -= yOffset;
for(int y = 0; y < sprite.SIZE; y++)
{
int ya = y + yp;
for(int x = 0; x < sprite.SIZE; x++)
{
int xa = x + xp;
if(xa < -sprite.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite.pixels[x + y * sprite.SIZE];
if(col != 0xffffff)
{
pixels[xa + ya * width] = col;
}
}
}
}
|
3c1b444b-0823-46ef-8537-7657105ae773
| 4
|
@Override
/**
* This method will be used by the table component to get
* value of a given cell at [row, column]
*/
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
Language language = languages.get(rowIndex);
switch (columnIndex) {
case COLUMN_NAME:
value = language.getName();
break;
case COLUMN_FILE_EXTENSION:
value = language.getFileExtension();
break;
case COLUMN_CMD_COMPILE:
value = language.getCmdCompile();
break;
case COLUMN_CMD_EXECUTE:
value = language.getCmdExecute();
break;
}
return value;
}
|
f1e8ba02-5be1-4192-8385-c066197babd1
| 2
|
public String obtenTabla(String busqueda) {
ArrayList<Equipo> lista = bd.buscaEquipo(Integer.parseInt(busqueda));
if (lista.size() == 0) {
return "<label id=\"errorBusqueda\" class=\"errorFormulario\">No se encontraron equipos</label>";
}
String tablaIn = "<table style=\"width:100%\" id=\"tablaResultado\">";
String tablaFin = "</table>";
String tr1 = "<tr>";
String tr2 = "</tr>";
String td1 = "<td>";
String td2 = "</td>";
String boton = "<button onclick=\"muestraFormulario()\" class=\"button\">Actualizar</button>";
String tabla = "";
tabla += tablaIn;
tabla += "<tr> <th>Clave Activo Fijo</th> <th> Num. inventario </th> <th>Serie</th>"
+ "<th>Marca</th> <th>Tipo Activo</th> <th>Selección</th> </tr>";
for (Equipo elem : lista) {
tabla += tr1;
tabla += td1;
tabla += String.valueOf(elem.getClave_activo_fijo());
tabla += td2;
tabla += td1;
tabla += String.valueOf(elem.getNum_inv_unam());
tabla += td2;
tabla += td1;
tabla += elem.getSerie();
tabla += td2;
tabla += td1;
tabla += elem.getClave_marcar();
tabla += td2;
tabla += td1;
tabla += elem.getClave_tipo();
tabla += td2;
tabla += td1;
tabla += "<input type=\"radio\" value=\"" + elem.getId_equipo() + "\" name=\"seleccion\" id=\"seleccion\"/>";
tabla += td2;
tabla += tr2;
}
tabla += tablaFin;
tabla += boton;
return tabla;
}
|
287a976e-6c20-44e4-bacb-e4ffc2d2e1c0
| 1
|
private void comboBox1ItemStateChanged(ItemEvent e) {
// TODO add your code here
if (comboBox1.getSelectedIndex()==0)
{
textField1.setText("[-0.5; 0.5] max");
}
else
{
textField1.setText("[-0.2; 0.95] max");
}
}
|
4a522cca-7214-41ad-bc85-971027547241
| 0
|
public void setPriority(Priority priority) {
this.priority = priority;
}
|
ddbeb366-d505-410a-ae06-a33df3f15b21
| 1
|
public void Forward(double value){
if (!forward){
start_pos = gyro[0];
}
forward = true;
speed = 1.2*value;
}
|
4df9dd7b-d6b2-4bb3-b4cb-fabcf4a8aec3
| 0
|
public void testAddMonth() {
Date date = DateUtils.addMonth(testDate, 1);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
assertEquals(Calendar.OCTOBER, calendar.get(Calendar.MONTH));
date = DateUtils.addMonth(testDate, 4);
calendar.setTime(date);
assertEquals(Calendar.JANUARY, calendar.get(Calendar.MONTH));
assertEquals(2013, calendar.get(Calendar.YEAR));
}
|
9415dd2f-e3b9-4794-bd59-3c3bdcd60968
| 9
|
private void followEdge(final int _x, final int _y, final BufferedImage _bi) {
_bi.setRGB(_x, _y, rgb_border);
for (int dX = 1; dX <= 1; dX++) {
for (int dY = 1; dY <= 1; dY++) {
if (!(dX == dY && dY == 1)) {
int x = _x + dX;
int y = _y + dY;
if (x >= 0 && y >= 0 && x < _bi.getWidth() && y < _bi.getHeight()) {
if (_bi.getRGB(x, y) == rgb_potential) {
followEdge(x, y, _bi);
}
}
}
}
}
}
|
c2b8cc19-a109-494b-8eb3-6392b31c4a07
| 7
|
void shootOnDos() {
for (Entity e : DOServer.entities)
if (e instanceof Dos)
if (attackTimeout <= 0 && e.x > x - 500
&& e.x < x + 500 && e.y > y - 500
&& e.y < y + 500) {
DOServer.entities.add(new Meatball(x, y, e.x, e.y));
attackTimeout = ATTACK_DELAY;
return;
}
}
|
7b3e318a-04bb-4bcc-8e74-f0c8feeab9ee
| 5
|
public int posWalkForwards(int begin_pos, int end_pos, double tmr,
int end_time,int standstill_pos,int standstill_time,int standstill_count){
if (tmr < standstill_time) {
double step = (standstill_pos - begin_pos)/(double)standstill_time;
return begin_pos + (int)(tmr*step);
} else if (tmr>=standstill_time&&tmr<standstill_time+standstill_count){
return standstill_pos;
} else if (tmr >= standstill_time+standstill_count && tmr < end_time) {
int beg2_time = standstill_time + standstill_count;
double step=(end_pos-standstill_pos)/(double)(end_time - beg2_time);
return standstill_pos + (int)((tmr-beg2_time) * step);
} else {
return end_pos;
}
}
|
8b2dae08-485f-4a82-bd53-cf00493fe466
| 1
|
private void refreshEditData () {
JList<River> jList = (JList<River>) riverList;
River selRiver = (River) jList.getSelectedValue();
if (selRiver == null)
return;
riverNameField.setText(selRiver.getRiverName());
fromNameField.setText(selRiver.getTripFrom());
toNameField.setText(selRiver.getTripTo());
lengthField.setText (Integer.toString(selRiver.getTripLength()));
defaultGroupSizeField.setText(Integer.toString(selRiver.getDefaultGroupSize()));
distanceField.setText (Integer.toString(selRiver.getDistanceToStart ()));
wwLevelField.setText(selRiver.getWwLevel());
wwTopLevelCombo.setSelectedIndex(selRiver.getWwTopLevel()-1);
minWaterLevelField.setText(Integer.toString(selRiver.getMinWaterLevel()));
maxWaterLevelField.setText(Integer.toString(selRiver.getMaxWaterLevel()));
unitOfWaterLevelCombo.setSelectedItem(selRiver.getUnitOfWaterLevel());
minWaterLevelUnitField.setText (selRiver.getUnitOfWaterLevel());
maxWaterLevelUnitField.setText (selRiver.getUnitOfWaterLevel());
commentText.setText(selRiver.getComment());
isFavoured.setSelected(selRiver.getIsFavoured());
}
|
c84cbbb6-4f07-4691-9ebd-cd2169640dc5
| 2
|
private int seeders() {
int count = 0;
for (TrackedPeer peer : this.peers.values()) {
if (peer.isCompleted()) {
count++;
}
}
return count;
}
|
809608fc-7620-4bdd-ad7f-abd345ef64bb
| 5
|
public static boolean downloadSSH(InetAddress ip, boolean toVM, String sessionid, String outputFolder){
try {
JSch jsch = new JSch();
Session session;
if (toVM) {
session = jsch.getSession("root", ip.getHostAddress(), 22);
} else {
session = jsch
.getSession(DefaultNetworkVariables.DAS4_USERNAME, ip.getHostAddress(), 22);
session.setPassword(DefaultNetworkVariables.DAS4_PASSWORD);
}
jsch.addIdentity("~/.ssh/id_dsa");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
PipedInputStream pis = new PipedInputStream();
PipedOutputStream fwdOutput = new PipedOutputStream(pis);
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream fwdInput = new PipedInputStream(pos);
Channel channel = session.getStreamForwarder(ip.getHostAddress(), DefaultNetworkVariables.DEFAULT_FTP_PORT);
channel.setInputStream(pis);
channel.setOutputStream(pos);
channel.connect(1000);
boolean success = download(fwdInput,fwdOutput,sessionid,outputFolder);
while (!channel.isClosed())
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
channel.disconnect();
return success;
} catch (IOException e) {
return false;
} catch (JSchException e1) {
return false;
}
}
|
011755b4-7fb0-4b3f-ae09-e17ac970ddba
| 6
|
@EventHandler
public void onCuboidFind(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player player = event.getPlayer();
User user = EdgeCoreAPI.userAPI().getUser(player.getName());
if (user != null && CuboidHandler.getInstance().isSearching(player.getName()) && event.getItem() != null) {
Material material = event.getItem().getType();
String userLang = user.getLanguage();
if (material == WorldManager.getInstance().getFindItem()) {
Cuboid cuboid = Cuboid.getCuboid(event.getClickedBlock().getLocation());
if (cuboid == null) {
event.setCancelled(true);
player.sendMessage(lang.getColoredMessage(user.getLanguage(), "cuboid_find_nocuboid"));
return;
}
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_title").replace("[0]", cuboid.getName()));
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_name").replace("[0]", cuboid.getName()));
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_type").replace("[0]", CuboidType.getType(cuboid.getCuboidType()).name()));
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_owner").replace("[0]", cuboid.getOwner().getName()));
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_center").replace("[0]", cuboid.getCenter().getBlockX() + "")
.replace("[1]", cuboid.getCenter().getBlockY() + "")
.replace("[2]", cuboid.getCenter().getBlockZ() + ""));
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_blocks").replace("[0]", cuboid.getArea() + "").replace("[1]", cuboid.getVolume() + ""));
player.sendMessage(lang.getColoredMessage(userLang, "admin_cuboid_info_participants").replace("[0]", cuboid.getParticipants().size() + ""));
}
}
}
}
|
48ecadd7-20f4-48be-91ab-66815987703a
| 4
|
private void setupEventListener() {
captureMenuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK));
newImageMenuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
openMenuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
saveMenuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
exitMenuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK));
captureMenuItem.addActionListener(e -> {
createScreenCapture();
});
newImageMenuItem.addActionListener(e -> {
newImage();
});
openMenuItem.addActionListener(e -> {
openImage();
});
saveMenuItem.addActionListener(e -> {
mainFrame.saveImageOfSelectedFrame();
});
saveAsMenuItem.addActionListener(e -> {
mainFrame.saveImageAsFileOfSelectedFrame();
});
saveAllMenuItem.addActionListener(e -> {
mainFrame.forEachInternalFrame(MainFrame.SAVE_ALL);
});
exitMenuItem.addActionListener(e -> {
mainFrame.checkUnsavedImages();
if (mainFrame.noInternalFrame()) {
System.exit(0);
}
});
widthSpinner.addChangeListener(e -> {
if (((Integer) widthSpinner.getValue()) <= 0) {
widthSpinner.setValue(1);
}
});
heightSpinner.addChangeListener(e -> {
if (((Integer) heightSpinner.getValue()) <= 0) {
heightSpinner.setValue(1);
}
});
backgroundColorBox.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Color color = JColorChooser.showDialog(null, "Color information", backgroundColorBox.getColor());
if (color != null) {
backgroundColorBox.setColor(color);
backgroundColorBox.repaint();
}
}
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.