text stringlengths 14 410k | label int32 0 9 |
|---|---|
private boolean salvarXml() throws IOException{
boolean status;
File f = new File("xmls/", renavam+".xml");
if(f.exists())
f.delete();
status = f.createNewFile();
FileWriter x = new FileWriter(f, true);
x.write("<?xml version = \"1.0\" encoding=\"UTF-8\"?>\n" + conteudo);
x.close();
return status;
} | 1 |
public void testWithEndMillis_long2() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
try {
test.withEndMillis(TEST_TIME1 - 1);
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
public OTUltra(Main_Window caller, String reader_port) {
super(caller, reader_port);
myself = this;
this.caller = get_caller();
this.m_port = get_port();
connected = false;
processed = 0;
expected = 0;
Logger("Ultra opening !");
serial = new SerialIF(this.caller, myself, m_port, 0); //Configure serial in ascii mode
if(serial != null){
if(serial.connect()){
caller.mylog("Port <"+m_port+"> connected");
if(serial.initIOStream()) {
serial.initListener();
this.connectToDevice(); //Try to obtain an answer from meter (serial_id)
timer(2000);
if(state == 0) {
//Meter does'nt answer : Probably due to wake up ! redo command
this.connectToDevice();
}
}
}
}
} //Constructor end ////////////////////////////////// | 4 |
public InputStream getThumbnailInputStream() {
if(playlist!=null)
return super.getThumbnailInputStream();
String url="";
if(album!=null)
url=album.getCoverURL();
if(artist!=null)
url=artist.getCoverURL();
if(url.length()==0)
return super.getThumbnailInputStream();
try {
return downloadAndSend(url,true);
}
catch (Exception e) {
return super.getThumbnailInputStream();
}
} | 5 |
public ArrayList<Vehicle> VehiclesForFranchise( int FranID)
throws UnauthorizedUserException, BadConnectionException, DoubleEntryException
{
/* Variable Section Start */
/* Database and Query Preperation */
PreparedStatement statment = null;
ResultSet results = null;
String statString = "SELECT * FROM vehicle WHERE FranchiseNumber = ?";
/* Return Parameter */
ArrayList<Vehicle> BPList = new ArrayList<Vehicle>();
/* Variable Section Stop */
/* TRY BLOCK START */
try
{
/* Preparing Statment Section Start */
statment = con.prepareStatement(statString);
statment.setInt(1, FranID);
/* Preparing Statment Section Stop */
/* Query Section Start */
results = statment.executeQuery();
/* Query Section Stop */
/* Metadata Section Start*/
//ResultSetMetaData metaData = results.getMetaData();
/* Metadata Section Start*/
/* List Prepare Section Start */
while (results.next())
{
Vehicle temp = new Vehicle();
//rs.getBigDecimal("AMOUNT")
temp.setCapacity(results.getInt("Capacity"));
temp.setCondition(results.getString("VCondition"));
temp.setFranchiseNumber(results.getInt("FranchiseNumber"));
temp.setMake(results.getString("Make"));
temp.setMileage(results.getInt("Mileage"));
temp.setModel(results.getString("Model"));
temp.setRate(results.getDouble("RentalPrice"));
temp.setTablet(results.getString("Tablet"));
temp.setVehicleID(results.getInt("VehicleID"));
temp.setVin(results.getString("VIN"));
temp.setYear(results.getInt("Year"));
BPList.add(temp);
}
/* List Prepare Section Stop */
}
catch(SQLException sqlE)
{
if(sqlE.getErrorCode() == 1142)
throw(new UnauthorizedUserException("AccessDenied"));
else if(sqlE.getErrorCode() == 1062)
throw(new DoubleEntryException("DoubleEntry"));
else
throw(new BadConnectionException("BadConnection"));
}
finally
{
try
{
if (results != null) results.close();
}
catch (Exception e) {};
try
{
if (statment != null) statment.close();
}
catch (Exception e) {};
}
/* TRY BLOCK STOP*/
/* Return to Buisness Section Start */
return BPList;
/* Return to Buisness Section Start */
} | 8 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((elseIfs == null) ? 0 : elseIfs.hashCode());
result = prime * result + ((exp1 == null) ? 0 : exp1.hashCode());
result = prime * result + ((stateSeq1 == null) ? 0 : stateSeq1.hashCode());
result = prime * result + ((stateSeq2 == null) ? 0 : stateSeq2.hashCode());
return result;
} | 4 |
public void keyPressed(int k) {
switch(k){
case KeyEvent.VK_ENTER:
select();
break;
case KeyEvent.VK_UP:
currentChoice--;
if (currentChoice == -1){
currentChoice = options.length - 1;
}
break;
case KeyEvent.VK_DOWN:
currentChoice++;
if (currentChoice == options.length){
currentChoice = 0;
}
break;
}
} | 5 |
public void volcarDatos(ArrayList<Libros> libros){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
while(model.getRowCount()>0)model.removeRow(0);
for(Libros l : libros){
Object[] fila = {
l.getCodigolibro(),
l.getNombrelibro(),
l.getTitulolibro(),
l.getAutorlibro(),
l.getCantidad(),
l.getPrestados(),
l
};
model.addRow(fila);
}
} | 2 |
@Override
public void actionPerformed(ActionEvent ae) {
String comando = ae.getActionCommand();
switch (comando) {
case "Depositar":
if (!Base.hasConnection()) {
Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/quiniela", "tecpro", "tecpro");
}
List<Caja> cajas = Caja.findAll();
int id_caja = cajas.get(cajas.size() - 1).getInteger("id");
if (depM.motivoDepoMan.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(depM, "Error: Falta especificar motivo");
} else {
if (Double.valueOf(depM.montoDepoMan.getText()) > 0) {
String motivo = depM.motivoDepoMan.getText();
BigDecimal monto = new BigDecimal((depM.montoDepoMan.getText()));
abmTrans.altaTransaccion(motivo, "Dep. Man", monto, 1, id_caja, Quiniela.id_usuario);
cc.cargarTransacciones();
depM.dispose();
} else {
JOptionPane.showMessageDialog(depM, "El depósito no puede ser negativo");
}
}
if (Base.hasConnection()) {
Base.close();
}
break;
case "Cancelar":
depM.dispose();
break;
}
} | 6 |
private ParkManage(){
} | 0 |
public void mouseClicked(MouseEvent e) {
//if the mouse was left clicked on
//the node then
if (m_clickAvailable) {
//determine if the click was on a node or not
int s = -1;
for (int noa = 0; noa < m_numNodes;noa++) {
if (m_nodes[noa].m_quad == 18) {
//then is on the screen
calcScreenCoords(noa);
if (e.getX() <= m_nodes[noa].m_center + m_nodes[noa].m_side
&& e.getX()
>= m_nodes[noa].m_center - m_nodes[noa].m_side &&
e.getY() >= m_nodes[noa].m_top && e.getY()
<= m_nodes[noa].m_top + m_nodes[noa].m_height) {
//then it is this node that the mouse was clicked on
s = noa;
}
m_nodes[noa].m_top = 32000;
}
}
m_focusNode = s;
if (m_focusNode != -1) {
if (m_listener != null) {
//then set this to be the selected node for editing
actionPerformed(new ActionEvent(this, 32000, "Create Child Nodes"));
}
else {
//then open a visualize to display this nodes instances if possible
actionPerformed(new ActionEvent(this, 32000, "Visualize The Node"));
}
}
}
} | 9 |
public void setCoordTransform(AffineTransform coordTransform) {
this.coordTransform = coordTransform;
} | 0 |
public boolean equals(Object par1Obj)
{
if (!(par1Obj instanceof NBTBase))
{
return false;
}
NBTBase nbtbase = (NBTBase)par1Obj;
if (getId() != nbtbase.getId())
{
return false;
}
if (name == null && nbtbase.name != null || name != null && nbtbase.name == null)
{
return false;
}
return name == null || name.equals(nbtbase.name);
} | 7 |
protected void processRuleBlock(String block, Engine engine) throws Exception {
BufferedReader reader = new BufferedReader(new StringReader(block));
String line;
RuleBlock ruleBlock = new RuleBlock();
engine.addRuleBlock(ruleBlock);
while ((line = reader.readLine()) != null) {
Op.Pair<String, String> keyValue = parseKeyValue(line, ':');
if ("RuleBlock".equals(keyValue.first)) {
ruleBlock.setName(keyValue.second);
} else if ("enabled".equals(keyValue.first)) {
ruleBlock.setEnabled(parseBoolean(keyValue.second));
} else if ("conjunction".equals(keyValue.first)) {
ruleBlock.setConjunction(parseTNorm(keyValue.second));
} else if ("disjunction".equals(keyValue.first)) {
ruleBlock.setDisjunction(parseSNorm(keyValue.second));
} else if ("activation".equals(keyValue.first)) {
ruleBlock.setActivation(parseTNorm(keyValue.second));
} else if ("rule".equals(keyValue.first)) {
ruleBlock.addRule(Rule.parse(keyValue.second, engine));
} else {
throw new RuntimeException("[import error] "
+ "key <" + keyValue.first + "> " + "not recognized in pair <"
+ Op.join(":", keyValue.first, keyValue.second) + ">");
}
}
reader.close();
} | 7 |
@Override
public boolean execute(CommandSender sender, String identifier,
String[] args) {
String titleName = args[1];
String titleId = args[0];
if (sender instanceof Player) {
try {
if (DBManager.idExist(titleId)) {
sender.sendMessage("This id already exist.");
return false;
}
if (DBManager.titleExists(titleName)) {
sender.sendMessage("This title already exist.");
return false;
}
if (DBManager.createTitle(titleId, titleName)) {
sender.sendMessage(FontFormat.translateString("The title "
+ titleName + "&r was created."));
return true;
} else {
sender.sendMessage("There was an error creating the title.");
}
} catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE,
"Error executing Title Create command.", ex);
return false;
}
return false;
}
sender.sendMessage("Only players can use this command");
return false;
} | 5 |
private MineOS(){} | 0 |
private void setQuorums()
{
HashMap<FileServerInfo, Integer> servers = new HashMap<FileServerInfo, Integer>();
for(FileServerInfo f : serverIdentifier.values())
{
servers.put(f, (int) f.getUsage());
}
servers = (HashMap<FileServerInfo, Integer>) sortByComparator(servers);
int quorumSize = Math.round(servers.size()/2)+1;
readQuorum = new ConcurrentHashMap<Integer, FileServerInfo>();
writeQuorum = new ConcurrentHashMap<Integer, FileServerInfo>();
int x = 0;
for(FileServerInfo i : servers.keySet())
{
if(x < quorumSize)
{
readQuorum.put(i.getPort(), i);
x++;
}
else
{
break;
}
}
x = 0;
for(FileServerInfo i : servers.keySet())
{
if(x < quorumSize)
{
writeQuorum.put(i.getPort(), i);
x++;
}
else
{
break;
}
}
} | 5 |
private boolean saveAll(UserScore userScore) throws SQLException {
PreparedStatement insertUserStmt = null;
PreparedStatement selectStmt = null;
PreparedStatement insertScoreStmt = null;
int result = 0;
try {
int playerId = getPlayerById(userScore.getUserName());
if (playerId == 0) {
insertUserStmt = getConnection().prepareStatement("insert into player(username) values(?)");
insertUserStmt.setString(1, userScore.getUserName());
result = insertUserStmt.executeUpdate();
if (result == 0) {
return false;
}
selectStmt = getConnection().prepareStatement("select last_insert_rowid()");
playerId = selectStmt.executeQuery().getInt(1);
}
insertScoreStmt = getConnection().prepareStatement("insert into score(player_id, score, play_date) values(?,?,?)");
insertScoreStmt.setInt(1, playerId);
insertScoreStmt.setInt(2, userScore.getScore());
insertScoreStmt.setLong(3, new Date().getTime());
result = insertScoreStmt.executeUpdate();
if (result == 0) {
return false;
}
return true;
} finally {
if (selectStmt != null) {
selectStmt.close();
}
if (insertScoreStmt != null) {
insertScoreStmt.close();
}
if (insertUserStmt != null) {
insertUserStmt.close();
}
}
} | 6 |
@Override
public MultiLabelOutput inferenceProcedure(Instance instance)
throws Exception {
Instance tempInstance = DataUtils.createInstance(instance,
instance.weight(), instance.toDoubleArray());
Comparator<LabelCombinationExtended> probabilityComparator = new Comparator<LabelCombinationExtended>() {
public int compare(LabelCombinationExtended left, LabelCombinationExtended right) {
double probabilityLeft = left.getP();
double probabilityRight = right.getP();
if (probabilityLeft > probabilityRight) {
return -1;
} else if (probabilityRight > probabilityLeft) {
return +1;
} else { // equal
return 0;
}
}
};
PriorityQueue<LabelCombinationExtended> queue = new PriorityQueue<LabelCombinationExtended>(
this.numLabels, probabilityComparator);
queue.add(new LabelCombinationExtended(this.numLabels, tempInstance, this));
PriorityQueue<LabelCombinationExtended> unsurvived = new PriorityQueue<LabelCombinationExtended>(
this.numLabels, probabilityComparator);
// double max = minMode;
LabelCombinationExtended best = null;
while (!queue.isEmpty()) {
LabelCombinationExtended current = queue.poll();
best = current;
if (best.getCurrentLabel() == this.numLabels) {
unsurvived.clear(); // the optimal solution has been found
break;
}
Instance currentInstance = current.getInstance();
int i = current.getCurrentLabel();
double p = this.ensemble[i].distributionForInstance(currentInstance)[1];
LabelCombinationExtended left = new LabelCombinationExtended(current);
left.setNextLabel(0, 1 - p);
boolean leftAdded = addToQueue(queue, left);
LabelCombinationExtended right = new LabelCombinationExtended(current);
right.setNextLabel(1, p);
boolean rightAdded = addToQueue(queue, right);
if (!leftAdded && !rightAdded) {
unsurvived.add(current);
}
}
this.max = 0.0;
while (!unsurvived.isEmpty()) { // search for approximate solution
LabelCombinationExtended greedy = unsurvived.poll();
if (greedy.getP() <= this.max)
break;
greedy = greedyApproximation(greedy, this.max);
if (greedy.getP() > this.max) {
best = greedy;
max = best.getP();
}
}
MultiLabelOutput result = new MultiLabelOutput(
booleansFromDoubles(best.getCombination()));
return result;
} | 9 |
public boolean valid() {
if (! super.valid()) return false ;
if (driven != null) {
if (driven.destroyed()) return false ;
if (! driven.canPilot(actor)) return false ;
}
//
// TODO: Put the passenger-delivery schtick into a different class. It's
// making a mess of things here.
if (passenger != null) return true ;
if (stage < STAGE_RETURN && available(actor).length == 0) {
if (driven != null) { stage = STAGE_RETURN ; return true ; }
///I.say("Nothing available!") ;
return false ;
}
return true ;
} | 8 |
public int[] createTileArray2(int numTiles)
{
arrTiles = new int[numTiles];
arrTilesCount = new int[numTiles];
int halfTiles = numTiles / 2;
int c = 0;
try
{
// First set of tiles
for (int n = 0; n < (halfTiles); n++)
{
arrTiles[n] = randomTile2(halfTiles);
}
// Second set of tiles, using the first set as the source: X / Chiasmus style... Meet in the middle!
int x = 0;
for (int o = (numTiles - 1); o >= halfTiles; o--)
{
arrTiles[o] = arrTiles[x];
x++;
}
}
catch (Exception x)
{
System.out.println("Error: " + x + "\n");
}
return (arrTiles);
} | 3 |
public int doSalary(int sal){
if(this.salary != null)
return this.salary.doSalary(sal);
return sal;
} | 1 |
public static boolean isValid(String content){
if(content != null && !content.isEmpty() && !content.equals("") && !content.equals("[false]") && !content.equals("null") && content.length() != 0 && content.length() < 500){
return true;
} else {
return false;
}
} | 7 |
@EventHandler
public void EnderDragonSpeed(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.getEnderDragonConfig().getDouble("EnderDragon.Speed.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.Speed.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getEnderDragonConfig().getInt("EnderDragon.Speed.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Speed.Power")));
}
} | 6 |
public static void main (String args[]) throws Exception
{
String hostname = HOSTNAME;
int port = PORT;
int timeToSleep = TIME_TO_SLEEP;
if(args.length > 0) {
List<String> argList = Arrays.asList(args);
if(argList.contains("-h")) {
int indexOf = argList.indexOf("-h");
hostname = argList.get(indexOf + 1);
}
if(argList.contains("-t")) {
int indexOf = argList.indexOf("-t");
timeToSleep = Integer.valueOf( argList.get(indexOf + 1) ) * 1000;
}
if(argList.contains("-p")) {
int indexOf = argList.indexOf("-p");
port = Integer.valueOf( argList.get(indexOf + 1) );
}
}
InetSocketAddress socketAddress = new InetSocketAddress(hostname, port);
HttpServer server = HttpServer.create(socketAddress, 0);
server.createContext("/", new RequestHandler(new MiniGameRequestReceiverFactory()));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
try
{
Thread.sleep(timeToSleep);
}
catch (InterruptedException e)
{
}
server.stop(10);
} | 5 |
public static List<Mensalidade> getListaMensalidadeEmAberto(String nome, Date data){
List<Mensalidade> lista = new ArrayList();
Connection conn = Conexao.getConexao();
PreparedStatement stmt = null;
ResultSet rs = null;
Mensalidade mens = null;
try {
String sql = "Select C.Codigo, C.Nome, P.Valor from Clientes C, Planos P " +
"where P.Codigo = C.Plano and C.DataCadastro <= ?";
if (nome != null) {
sql += " and C.Nome like '%" + nome + "%'";
}
if (data != null) {
sql += " and (not C.Codigo in (Select M.Cliente from MensalidadesPagas M " +
" where M.DataRef = ?))";
//" where Extract(Month from M.DataRef) = Extract(Month from ?) and " +
//" Extract(Year from M.DataRef) = Extract(Year from ?)))";
}
sql += " Order by C.Nome";
stmt = conn.prepareStatement(sql);
if (data != null) {
stmt.setDate(1, new java.sql.Date(data.getTime()));
stmt.setDate(2, new java.sql.Date(data.getTime()));
//stmt.setDate(3, new java.sql.Date(data.getTime()));
}
rs = stmt.executeQuery();
while (rs.next()) {
mens = new Mensalidade();
mens.setCodigo(rs.getInt("Codigo"));
mens.setCliente(ClienteDAO.getCliente(rs.getInt("codigo")));
mens.setValorpago(rs.getDouble("Valor"));
lista.add(mens);
}
} catch (SQLException e) {
System.out.println("ERRO: " + e.getMessage());
} finally {
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
System.out.println("ERRO: " + e.getMessage());
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("ERRO: " + e.getMessage());
}
}
}
return lista;
} | 9 |
public void setMinus(TMinus node)
{
if(this._minus_ != null)
{
this._minus_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._minus_ = node;
} | 3 |
public String[] ReadTargetPHPFileData() {
String[] FaultTypeOperators = null;
int count = 0;
Statement s = null;
ResultSet rs = null;
// Adapted from http://developers.sun.com/docs/javadb/10.2.2/ref/rrefclob.html
try {
if ((conn = setConn()) != null) {
System.out.println("Connected to database " + getDatabaseName());
} else {
throw new Exception("Not connected to database " + getDatabaseName());
}
conn.setAutoCommit(false);
// Test to see if the Target PHP file is already in the DB
s = conn.createStatement();
rs = s.executeQuery("SELECT COUNT(*) FROM TARGET_PHP_FILES"); // get the result
rs.next();
count = rs.getInt(1);
rs.close();
s.close();
FaultTypeOperators = new String[count + 1];
FaultTypeOperators[0] = "null";
// Test to see if the Target PHP file is already in the DB
s = conn.createStatement();
rs = s.executeQuery("SELECT PATH FROM TARGET_PHP_FILES"); // get the result
while (rs.next()) {
// Open matches log file.
FaultTypeOperators[rs.getRow()] = rs.getString(1);
}
rs.close();
conn.commit();
conn.close();
} catch (Throwable e) {
System.out.println("exception thrown:");
if (e instanceof SQLException) {
printSQLError((SQLException) e);
} else {
e.printStackTrace();
}
}
return FaultTypeOperators;
} | 4 |
@Override
public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException {
List paramList1 = new ArrayList<>();
List paramList2 = new ArrayList<>();
StringBuilder sb = new StringBuilder(UPDATE_QUERY);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_TOURIST_FNAME, DB_TOURIST_FNAME, criteria, paramList1, sb, COMMA);
Appender.append(DAO_TOURIST_MNAME, DB_TOURIST_MNAME, criteria, paramList1, sb, COMMA);
Appender.append(DAO_TOURIST_LNAME, DB_TOURIST_LNAME, criteria, paramList1, sb, COMMA);
Appender.append(DAO_TOURIST_BIRTH, DB_TOURIST_BIRTH, criteria, paramList1, sb, COMMA);
Appender.append(DAO_TOURIST_PASSPORT, DB_TOURIST_PASSPORT, criteria, paramList1, sb, COMMA);
Appender.append(DAO_TOURIST_STATUS, DB_TOURIST_STATUS, criteria, paramList1, sb, COMMA);
sb.append(WHERE);
Appender.append(DAO_ID_TOURIST, DB_TOURIST_ID_TOURIST, beans, paramList2, sb, AND);
Appender.append(DAO_ID_ORDER, DB_TOURIST_ID_ORDER, beans, paramList2, sb, AND);
Appender.append(DAO_TOURIST_FNAME, DB_TOURIST_FNAME, beans, paramList2, sb, AND);
Appender.append(DAO_TOURIST_MNAME, DB_TOURIST_MNAME, beans, paramList2, sb, AND);
Appender.append(DAO_TOURIST_LNAME, DB_TOURIST_LNAME, beans, paramList2, sb, AND);
Appender.append(DAO_TOURIST_BIRTH, DB_TOURIST_BIRTH, beans, paramList2, sb, AND);
Appender.append(DAO_TOURIST_PASSPORT, DB_TOURIST_PASSPORT, beans, paramList2, sb, AND);
Appender.append(DAO_TOURIST_STATUS, DB_TOURIST_STATUS, beans, paramList2, sb, AND);
return sb.toString();
}
}.mapQuery();
paramList1.addAll(paramList2);
try {
return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn);
} catch (DaoException ex) {
throw new DaoQueryException(ERR_TOURIST_UPDATE, ex);
}
} | 1 |
private List<String> createCommand() throws MojoExecutionException {
List<String> cmd = new ArrayList<String>();
cmd.add(getCommandPath("createdb"));
if (host != null) {
cmd.add("-h");
cmd.add(host);
}
if (port != null) {
cmd.add("-p");
cmd.add(port.toString());
}
if (username != null) {
cmd.add("-U");
cmd.add(username);
}
if (template != null) {
cmd.add("-T");
cmd.add(template);
}
if (noPassword) {
cmd.add("--no-password");
}
cmd.add(databaseName);
if (description != null) {
cmd.add(description);
}
return cmd;
} | 6 |
@Override
public PreparedStatement prepare(String query) {
//Connection connection = null;
PreparedStatement ps = null;
try
{
//connection = open();
ps = connection.prepareStatement(query);
return ps;
} catch(SQLException e) {
if(!e.toString().contains("not return ResultSet"))
this.writeError("Error in SQL prepare() query: " + e.getMessage(), false);
}
return ps;
} | 2 |
public static Node getNormalizedNode(String normalized){
if (normalized == "01"){
return new Node("NOTYPE",0);
}
else {
Node resultat = new Node("NOTYPE",0);
ArrayList<String> filsName = new ArrayList<String>();
int cut = 0;
int debutCut = 0, finCut = 0;
for (int i = 1; i<normalized.length(); i++){
int cutBefore = cut;
if (normalized.charAt(i) == '0')
cut++;
else
cut--;
if (cut == 1 && cutBefore == 0)
debutCut = i;
else if (cut == 0 && cutBefore == 1){
finCut = i;
filsName.add(normalized.substring(debutCut, finCut+1));
}
}
for (String son : filsName){
resultat.addFils(ToolNode.getNormalizedNode(son));
}
return resultat;
}
} | 8 |
private void selectSQLiteData() {
if (m_sqlTable == null) {
return;
}
ResultSet selectAll = m_sqlTable.select("*");
if (selectAll == null || countResults(selectAll) != 3) {
log("selectSQLiteData selectAll Failed!");
}
ResultSet selectSam = m_sqlTable.select("*", "name='SAM'");
if (selectSam == null || countResults(selectSam) != 1) {
log("selectSQLiteData selectSam Failed!");
}
log("selectSQLiteData Passed");
} | 5 |
private JTreeNode<T> convertList( JTreeNode<T> current, boolean isLeft){
if(current == null){
return null;
}
JTreeNode<T> left = convertList(current.getLeftNode(), true);
JTreeNode<T> right = convertList(current.getRightNode(), false);
if(left!=null && right==null){
left.setRightNode(current);
current.setLeftNode(left);
return current;
}
if(left==null && right!=null) {
current.setRightNode(right);
right.setLeftNode(current);
return current;
}
if(left!=null && right!=null){
left.setRightNode(current);
current.setLeftNode(left);
current.setRightNode(right);
right.setLeftNode(current);
if(isLeft) {
return right;
}
return left;
}
return current;
} | 8 |
public static void main(String[] args) {
Integer philosophersAmount = 5;
Integer hungryAmount = 2;
Integer chairAmount = 5;
Integer runtime = 30; //in s
Table tisch = new Table(chairAmount);
List<Philosopher> philosophers = new ArrayList<Philosopher>();
List<Thread> philosopherThreads = new ArrayList<Thread>();
for (int i = 0; i < philosophersAmount; i++) {
Philosopher philosopher = new Philosopher(tisch, false);
philosopherThreads.add(new Thread(philosopher));
philosophers.add(philosopher);
}
for (int i = 0; i < hungryAmount; i++) {
Philosopher philosoph = new Philosopher(tisch, true);
philosopherThreads.add(new Thread(philosoph));
philosophers.add(philosoph);
}
Thread inspectorThread = new Thread(new Inspector(philosophers));
inspectorThread.start();
for (Thread t : philosopherThreads) {
t.start();
}
try {
Thread.sleep(1000 * runtime);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (Philosopher p : philosophers) {
p.printStats();
}
for (Thread t : philosopherThreads) {
t.stop();
}
inspectorThread.stop();
} | 6 |
public void sendFile(String localFileName, String fileOnServer) throws IOException {
File file = new File(rootFolder, localFileName);
if(! file.exists()) {
throw new FileNotFoundException("File " + localFileName + " not found in the root folder " + rootFolder.getAbsolutePath());
}
if(file.isDirectory()) {
throw new IOException("Writing whole folders isn't supported. Please send each file individually.");
}
try(DatagramSocket clientSocket = new DatagramSocket()) {
Sender sender = new Sender(clientSocket, GlobalConfig.TFTP_CONTROL_PORT, serverAddress);
sender.sendObject(new WRQ(fileOnServer));
byte[] buff = new byte[256];
DatagramPacket datagram = new DatagramPacket(buff, buff.length);
clientSocket.setSoTimeout(GlobalConfig.TIMEOUT_MS);
try {
clientSocket.receive(datagram);
}
catch(SocketTimeoutException e) {
throw new SocketTimeoutException("Server didn't respond to our request to write "
+ localFileName + " as " + fileOnServer + " in time.");
}
Object response = ObjectUtil.extractFromDatagram(datagram);
if(response instanceof ERR) {
ERR err = (ERR)response;
if(err.errorCode == ERR.FILE_ALREADY_EXISTS) {
throw new FileAlreadyExistsException("Cannot write to server: " + err.message);
}
else {
throw new IOException("Cannot write to server: " + err.message);
}
}
else if(response instanceof ACK) {
Logger.log("Got the green light to write to the server!");
try(Scanner s = new Scanner(file)) {
s.useDelimiter("\\Z");
String textContents = s.next();
byte[] fileBytes = textContents.getBytes();
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
int dataLinkPort = datagram.getPort();
Logger.log("Sending file to server @ port " + dataLinkPort);
Sender fileSender = new Sender(clientSocket, dataLinkPort, serverAddress);
try {
FileSender.sendFile(fileBytes, fileSender);
} catch(IOException e) {
throw new IOException("Failed to send file to server: " + e.getMessage());
}
}
Logger.log("Done sending.");
}
}
} | 8 |
public boolean move(String input) {
// logically what is happening is this variable starts out false,
// gets changed to true if the player moved successfully, then is
// send back and it tells the program if the player has moved or not.
boolean moved = false;
switch (input) {
case "north":
moved = player.move(Direction.NORTH);
break;
case "south":
moved = player.move(Direction.SOUTH);
break;
case "west":
moved = player.move(Direction.WEST);
break;
case "east":
moved = player.move(Direction.EAST);
break;
case "up":
moved = player.move(Direction.UP);
break;
case "down":
moved = player.move(Direction.DOWN);
break;
}
return moved;
} | 6 |
public void chargerLivraisons(String adresse)
{
this.vueAppli.afficherCurseurAttente();
try
{
if (this.itineraireInitial != null)
{
ParserXML livraisonParser= new ParserXML(adresse,TypeFichier.LIVRAISONS);
Pair<NoeudItineraire,ArrayList<PlageHoraire> > dataLIvr =
livraisonParser.genererLivraisonsDepuisXML(this.itineraireInitial.getPlan().getNoeuds());
this.itineraireInitial.setPlagesHoraire(dataLIvr.getSecond());
this.itineraireInitial.setEntrepot(dataLIvr.getFirst());
this.itineraireInitial.setEtat(EtatItineraire.NON_CALCULE);
/********* AJOUT QL ***********/
this.vueAppli.resetDessin();
this.gestItineraire.reset();
this.gestItineraire.supprimerItineraire(this.itineraireInitial);
Plan plan = this.itineraireInitial.getPlan();
NoeudItineraire entrepot = this.itineraireInitial.getEntrepot();
List<PlageHoraire> plagesHoraireInitiales = this.itineraireInitial.getPlagesHoraire();
PlageHoraire plageHoraireInitiale = plagesHoraireInitiales.get(0);
AffectationLivraison.affecter(this.gestItineraire, plan, entrepot, plageHoraireInitiale);
HashMap<Integer, Itineraire> itineraires = this.gestItineraire.getItineraires();
Set<Map.Entry<Integer, Itineraire>> set = itineraires.entrySet();
for(Map.Entry<Integer, Itineraire> entry : set)
{
Itineraire itineraire = entry.getValue();
int i = 0;
System.out.println("Itineraire " + itineraire.getItineraireId());
for(Livraison liv : itineraire.getPlagesHoraire().get(0).getAllLivraison())
{
System.out.println("Poids de la livraison " + i + " : " + liv.getPoids());
i++;
}
System.out.println();
}
/********** AJOUT QL **********/
this.historique.viderHistorique();
this.vueAppli.rafraichir();
// this.vueAppli.afficherMessageInfo(Constantes.CHARGEMENT_LIVRAISONS_REUSSI);
}
}
catch (XmlParserException e)
{
e.printStackTrace();
//this.vueAppli.afficherMessageErreur(Constantes.CHARGEMENT_ITINERAIRE_IMPOSSIBLE);
// this.vueAppli.afficherMessageErreur(e.getMsgUtilisateur());
//this.vueAppli.afficherMessageErreur(e.getMsgUtilisateur());
}
this.vueAppli.afficherCurseurNormal();
} | 4 |
@Override
public void documentRemoved(DocumentRepositoryEvent e) {} | 0 |
public int getSoundNarration()
{
return soundNarration;
} | 0 |
private String munecoBasico(){
String muneco = "";
if(intentos == 5){
muneco = muneco + " O ";
}
if(intentos == 4){
muneco = muneco + " O <BR>"+
" / <BR>";
}
if(intentos == 3){
muneco = muneco + " O <BR>"+
" /| <BR>";
}
if(intentos == 2){
muneco = muneco + " O <BR>"+
" /|\\ <BR>";
}
if(intentos == 1){
muneco = muneco + " O <BR>"+
" /|\\ <BR>"+
" / ";
}
if(intentos == 0){
muneco = muneco + " O <BR>"+
" /|\\ <BR>"+
" / \\ ";
}
return muneco;
} | 6 |
public static void info(String msg){
if(Settings.debug) System.out.println(info+" "+msg.trim());
} | 1 |
private void writeChars( int db, int ln, String sc )
{
RandomAccessFile f = ( db==0 ? fdbf : db==1 ? ffpt : fcdx );
int l = sc.length();
int ml = Math.min(ln,l);
try { f.writeBytes( (l==ml ? sc : sc.substring(0,ml)) ); }
catch (IOException e) { e.printStackTrace(); }
if(ln>l)
{
String s = new String(new char[ln-l]).replace("\0", " ");
try { f.writeBytes(s); } catch (IOException e) { e.printStackTrace(); }
}
} | 6 |
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (!localName.equals(BuilderProperties.getString("root_element"))) { //$NON-NLS-1$
if (parserFactory.hasDevice(localName)) {
devices.add(currentParser.getDevice());
currentParser = null;
}
}
} | 2 |
public static void checkAutoBroadcastConfigYAML() {
File file = new File(path + "AutoBroadcast/config.yml");
if(!file.exists()) {
try {
file.createNewFile();
FileConfiguration f = YamlConfiguration.loadConfiguration(file);
f.set("Interval.Hours", 0);
f.set("Interval.Minutes", 0);
f.set("Interval.Seconds", 20);
f.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
} | 2 |
public String addIngredient() {
if (ingredient != null) {
try {
restClientBean.getIngredientClient().createIngredient(ingredient);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ProductBrand other = (ProductBrand) obj;
if (!Objects.equals(this.szBrandId, other.szBrandId)) {
return false;
}
return true;
} | 3 |
@Override
public void doAction(Player player, Grid grid) throws InvalidActionException {
if (player.getRemainingTurns() <= 0)
throw new InvalidActionException("The player has no turns left!");
Position currentPos = player.getPosition();
Position newPos = new Position(currentPos.getxCoordinate(), currentPos.getyCoordinate() + 1);
if (!canMoveToPosition(player, grid, newPos))
throw new InvalidActionException("The player can't move to the desired position!");
player.setPosition(newPos);
player.getLightTrail().addPosition(currentPos);
player.decrementTurn();
} | 2 |
@Test
public void testQueryOrder() throws FileNotFoundException{;
int count = 0;
for (Player p : myGame.getPlayers()){
if (count == 0){
assertEquals(p.getName(), "Test name");
count++;
}
else if (count == 1){
assertEquals(p.getName(), "Elessar Telcontal");
count++;
}
else if (count == 2){
assertEquals(p.getName(), "Gandalf Grey");
count++;
}
else if (count == 3){
assertEquals(p.getName(), "Gollum Trahald");
count++;
}
else if (count == 4){
assertEquals(p.getName(), "Samwise Gamgee");
count++;
}
else if (count == 5){
assertEquals(p.getName(), "Frodo Baggins");
count++;
}
}
} | 7 |
public static long parseTimeInterval(String str) {
try {
int len = str.length();
char suffix = str.charAt(len - 1);
String numstr;
long mult = 1;
if (Character.isDigit(suffix)) {
numstr = str;
} else {
numstr = str.substring(0, len - 1);
switch (Character.toUpperCase(suffix)) {
case 'S':
mult = Constants.SECOND;
break;
case 'M':
mult = Constants.MINUTE;
break;
case 'H':
mult = Constants.HOUR;
break;
case 'D':
mult = Constants.DAY;
break;
case 'W':
mult = Constants.WEEK;
break;
default:
throw new NumberFormatException("Illegal time interval suffix");
}
}
return Long.parseLong(numstr) * mult;
} catch (IndexOutOfBoundsException e) {
throw new NumberFormatException("empty string");
}
} | 7 |
public final void reset() {
this.taskPool.addTask(new Runnable() {
@Override
final public void run() {
for (final DropTargetContainer<?, ?, ?> target : AbcMapPlugin.this.targets) {
target.clearTargets();
}
}
});
this.trackMap.clear();
this.instrumentToTrack.clear();
} | 4 |
public String getFoundKey(){
return _key + "Found?";
} | 0 |
private void updatePropertyEditor_selected() {
HashSet<Vertex> selectedVertices = spm.getSelectedVertices();
HashSet<Edge> selectedEdges = spm.getSelectedEdges();
int numOfSelectedVertices = selectedVertices.size();
int numOfSelectedEdges = selectedEdges.size();
//if there was only 1 selected vertex(edge) show the classic editor for it
if (numOfSelectedVertices + numOfSelectedEdges == 1) {
if (numOfSelectedVertices == 1) {
setTarget(new VertexNotifiableAttrSet(selectedVertices.iterator().next()));
viewer = vertexView;
} else {
setTarget(new EdgeNotifiableAttrSet(selectedEdges.iterator().next()));
viewer = edgeView;
}
} else {
viewer = selectView;
iChangedTheAttribute = true;
TimeLimitedNotifiableAttrSet retAtrs = new TimeLimitedNotifiableAttrSet(new AttributeSetImpl());
retAtrs.removeAttributeListener(this);
//adding each Vertex/Edge attribute to selectionAttributes
int i = 0;
retAtrs.put("Vertices", numOfSelectedVertices);
selectView.setEditable("Vertices", false);
selectView.setIndex("Vertices", i++);
for (Vertex v : selectedVertices) {
if (i < 500) {
AttributeSet vAtrs = new VertexAttrSet(v);
vertexView.setAttribute(vAtrs);
for (String atrName : vertexView.getNames()) {
String key = vertexAtrName(atrName);
insertAttributeToSelectionAtrs(retAtrs, key, vAtrs, atrName);
selectView.setDisplayName(key, atrName);
selectView.setIndex(key, i++);
}
}
}
retAtrs.put(" ", "");
selectView.setEditable(" ", false);
retAtrs.put("Edges", numOfSelectedEdges);
selectView.setIndex(" ", i++);
selectView.setIndex("Edges", i++);
selectView.setEditable("Edges", false);
for (Edge e : selectedEdges) {
if (i < 1000) {
AttributeSet eAtrs = new EdgeAttrSet(e);
for (String atrName : ((Set<String>)eAtrs.getAttrs().keySet())) {
String key = edgeAtrName(atrName);
insertAttributeToSelectionAtrs(retAtrs, key, eAtrs, atrName);
selectView.setDisplayName(key, atrName);
selectView.setIndex(key, i++);
}
}
}
selectView.setVisible("v" + VertexAttrSet.LOCATION, false);
selectView.setVisible("v" + VertexAttrSet.SELECTED, false);
selectView.setEditor("v" + VertexAttrSet.BORDER, new GStrokeEditor() {
public Object[] getValues() {
return new GStroke[]{
GStroke.empty,
simple,
solid,
strong,
dashed,
dotted,
dashed_dotted,
dashed_dotted_dotted,
dashed_dashed_dotted
};
}
});
selectView.setEditor("v" + VertexAttrSet.COLOR, new GMergedColorEditor());
selectView.setrenderer("v" + VertexAttrSet.COLOR, new GMergedColorRenderer());
selectView.setEditor("e" + VertexAttrSet.COLOR, new GMergedColorEditor());
selectView.setrenderer("e" + VertexAttrSet.COLOR, new GMergedColorRenderer());
viewer = selectView;
retAtrs.addAttributeListener(this);
// updateSelectView();
iChangedTheAttribute = false;
setTarget(retAtrs);
}
} | 8 |
private void queryForTileBars(){
//TODO: BUGS EVERYWHERE IF THIS ISN'T RESET TOOK ME 5 HOURS TO FIGURE THIS OUT
selectedChapters = new ArrayList<>();
for(int i = 0;i < repository.size();i++){
selectedChapters.add(new ArrayList<Integer>());
}
//Reset all buttons text to the Magnify text.
for(int i = 0;i < magnifyRevertButtons.size();i++){
magnifyRevertButtons.get(i).setText("Magnify");
}
//Clear all old tilebars.
for(int i = 0;i < tileBarViews.size();i++){
if(tileBarViews.get(i) != null){
tileBarPanels.get(i).remove(tileBarViews.get(i));
}
}
tileBarViews.clear();
//Get the text from the query fields.
getTextFromFields();
//Update Tilebars.
for(int i = 0;i < repository.size();i++){
tileBarViews.add(new TileBarView(repository.get(i), i, thisInstance, USE_CHAPTER_FREQUENCY_COLORING, coloringMode, 20, 20, redQueryList.get(i), greenQueryList.get(i), blueQueryList.get(i), redQueryStrings.get(i), greenQueryStrings.get(i), blueQueryStrings.get(i)));
}
String buildTileBarString = "";
for(int i = 0;i < tileBarViews.size();i++){
buildTileBarString += "Title: "+repository.get(i).getTitle() +"\nAuthor: "+repository.get(i).getAuthor()+"\n";
buildTileBarString += tileBarViews.get(i).getTextInformation()+"\n\n";
}
displayTextTileBar.setText(buildTileBarString);
updateTileBarInterface();
} | 6 |
public Onderwerp(final logic.Onderwerp onderwerp, final Spel spel) {
setOpaque(false);
setBorder(null);
setLayout(new MigLayout("", "[123px:176.00,grow,fill]", "[40.00][100px:149.00:100px,grow,fill]"));
try {
JLabel lblSteden = new JLabel(onderwerp.getNaam());
lblSteden.setHorizontalAlignment(SwingConstants.CENTER);
lblSteden.setFont(new Font("Dialog", Font.PLAIN, 15));
add(lblSteden, "cell 0 0,growx");
// Dat je op het plaatje kan klikken
ImagePanel image = new ImagePanel(onderwerp.getPlaatje());
image.setBorder(new LineBorder(new Color(0, 0, 0)));
image.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
spel.setOnderwerp(onderwerp);
spel.openPanel(new SpeelScherm(spel));
}
});
add(image, "cell 0 1,alignx center,aligny center");
image.setAutoResize(true);
} catch (IOException e) {
e.printStackTrace();
// TODO doet iets hiermee
}
} | 1 |
public static String wrapper(String data){
return "<html>"+
head()+
"<body>"+
"<table id=\"hor-minimalist-b\">"+
thead()+
data+
"</table>"+
"</body>"+
"</html>";
} | 0 |
public MoveTest() {
} | 0 |
private void profile(String hostname, String jobId, boolean needMetrics, int sampleMapperNum, int sampleReducerNum) {
SingleJobProfiler profiler = new SingleJobProfiler(hostname, jobId, needMetrics, sampleMapperNum, sampleReducerNum);
job = profiler.profile();
finishedConf = job.getJobConfiguration();
newConf = finishedConf.copyConfiguration();
isXmxChanged = false;
isXmsChanged = false;
isSplitSizeChanged = false;
isMapperConfChanged = false;
isReducerConfChanged = false;
// judge whether mapper and reducer data-model estimators is needed
for(Entry<String, String> entry : conf.getAllConfs()) {
String key = entry.getKey();
String value = entry.getValue();
if(key.equals("mapred.child.java.opts")) {
int start = value.indexOf("-Xmx") + 4;
int end = value.indexOf('m', start);
int xmx = Integer.parseInt(value.substring(start, end)); //4000;
start = value.indexOf("-Xms") + 4;
end = value.indexOf('m', start);
int xms = Integer.parseInt(value.substring(start, end)); //1000;
if(finishedConf.isXmxChanged(xmx))
isXmxChanged = true;
if(finishedConf.isXmsChanged(xms))
isXmsChanged = true;
}
if(key.equals("split.size") && finishedConf.isSpliSizeChanged(value))
isSplitSizeChanged = true;
if(finishedConf.isMapperConfChanged(key, value))
isMapperConfChanged = true;
if(finishedConf.isReducerConfChanged(key, value))
isReducerConfChanged = true;
newConf.set(entry.getKey(), entry.getValue());
}
} | 8 |
private void extractFileContent() throws Exception{
int first_frame, num_frames, looping_frames, frames_per_second; //data from file
int end_frame;
String description = "";
for( int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.trim();
if( line.length() == 0) continue;
if( line.startsWith("//")) continue;
String tokens[] = line.split("\t");
// System.out.println(parts.length);
if( tokens.length >= 4){
try{
// get frame-data
first_frame = Integer.parseInt(tokens[0]);
num_frames = Integer.parseInt(tokens[1]);
looping_frames = Integer.parseInt(tokens[2]);
frames_per_second = Integer.parseInt(tokens[3]);
end_frame = first_frame + num_frames; //TODO: set the first frame of next animation
// get description
for(int j = 4; j < tokens.length; j++ ){
tokens[j] = tokens[j].trim();
if( tokens[j].length() == 0) continue;
if( tokens[j].startsWith("//")){
tokens[j] = tokens[j].replaceAll("[/]", "");
tokens[j] = tokens[j].trim();
description = tokens[j];
}
}
// build new animation from data
Q3_Animation anim = new Q3_Animation
(
first_frame,
num_frames,
looping_frames,
frames_per_second,
description,
end_frame
);
// add animation to list
animations.add(anim);
} catch (NumberFormatException e){
e.printStackTrace();
}
}
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variable other = (Variable) obj;
if (rang != other.rang)
return false;
return true;
} | 4 |
public void testRemoveAllTCollection() {
int element_count = 20;
TIntList other = new TIntLinkedList();
for ( int i = 0; i < element_count; i++ ) {
other.add( i );
}
TIntList list = new TIntLinkedList( 20 );
for ( int i = 0; i < element_count; i++ ) {
list.add( i );
}
assertEquals( element_count, list.size() );
assertEquals( element_count, other.size() );
assertTrue( list.removeAll( list ) );
assertEquals( 0, list.size() );
assertTrue( list.isEmpty() );
// Reset the list
list = new TIntLinkedList( 20 );
for ( int i = 0; i < element_count; i++ ) {
list.add( i );
}
assertTrue( list.removeAll( other ) );
assertEquals( 0, list.size() );
assertTrue( list.isEmpty() );
for ( int i = 0; i < list.size(); i++ ) {
assertEquals( i , list.get( i ) );
}
// Reset the list
list = new TIntLinkedList( 20 );
for ( int i = 0; i < element_count; i++ ) {
list.add( i );
}
other.remove( 0 );
other.remove( 5 );
other.remove( 10 );
other.remove( 15 );
assertTrue( list.removeAll( other ) );
int expected = 4;
assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list ,
expected, list.size() );
for ( int i = 0; i < list.size(); i++ ) {
expected = i * 5;
assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list,
expected , list.get( i ) );
}
} | 6 |
private ListNode findMid(ListNode head){
ListNode oneStep = head;
ListNode twoStep = head;
while(oneStep.next != null && twoStep.next != null && twoStep.next.next != null){
twoStep = twoStep.next;
if(twoStep == null){
break;
}
twoStep = twoStep.next;
oneStep = oneStep.next;
}
return oneStep;
} | 4 |
public void jump() {
if (jumped == true && jumpLimit == false) {
speedY += JUMPSPEED2;
jumpLimit = true;
}
if (jumped == false) {
speedY = JUMPSPEED;
jumped = true;
}
} | 3 |
private void hybrid(int ch, int gr)
{
int bt;
int sb18;
gr_info_s gr_info = (si.ch[ch].gr[gr]);
float[] tsOut;
float[][] prvblk;
for(sb18=0;sb18<576;sb18+=18)
{
bt = ((gr_info.window_switching_flag !=0 ) && (gr_info.mixed_block_flag !=0) &&
(sb18 < 36)) ? 0 : gr_info.block_type;
tsOut = out_1d;
// Modif E.B 02/22/99
for (int cc = 0;cc<18;cc++)
tsOutCopy[cc] = tsOut[cc+sb18];
inv_mdct(tsOutCopy, rawout, bt);
for (int cc = 0;cc<18;cc++)
tsOut[cc+sb18] = tsOutCopy[cc];
// Fin Modif
// overlap addition
prvblk = prevblck;
tsOut[0 + sb18] = rawout[0] + prvblk[ch][sb18 + 0];
prvblk[ch][sb18 + 0] = rawout[18];
tsOut[1 + sb18] = rawout[1] + prvblk[ch][sb18 + 1];
prvblk[ch][sb18 + 1] = rawout[19];
tsOut[2 + sb18] = rawout[2] + prvblk[ch][sb18 + 2];
prvblk[ch][sb18 + 2] = rawout[20];
tsOut[3 + sb18] = rawout[3] + prvblk[ch][sb18 + 3];
prvblk[ch][sb18 + 3] = rawout[21];
tsOut[4 + sb18] = rawout[4] + prvblk[ch][sb18 + 4];
prvblk[ch][sb18 + 4] = rawout[22];
tsOut[5 + sb18] = rawout[5] + prvblk[ch][sb18 + 5];
prvblk[ch][sb18 + 5] = rawout[23];
tsOut[6 + sb18] = rawout[6] + prvblk[ch][sb18 + 6];
prvblk[ch][sb18 + 6] = rawout[24];
tsOut[7 + sb18] = rawout[7] + prvblk[ch][sb18 + 7];
prvblk[ch][sb18 + 7] = rawout[25];
tsOut[8 + sb18] = rawout[8] + prvblk[ch][sb18 + 8];
prvblk[ch][sb18 + 8] = rawout[26];
tsOut[9 + sb18] = rawout[9] + prvblk[ch][sb18 + 9];
prvblk[ch][sb18 + 9] = rawout[27];
tsOut[10 + sb18] = rawout[10] + prvblk[ch][sb18 + 10];
prvblk[ch][sb18 + 10] = rawout[28];
tsOut[11 + sb18] = rawout[11] + prvblk[ch][sb18 + 11];
prvblk[ch][sb18 + 11] = rawout[29];
tsOut[12 + sb18] = rawout[12] + prvblk[ch][sb18 + 12];
prvblk[ch][sb18 + 12] = rawout[30];
tsOut[13 + sb18] = rawout[13] + prvblk[ch][sb18 + 13];
prvblk[ch][sb18 + 13] = rawout[31];
tsOut[14 + sb18] = rawout[14] + prvblk[ch][sb18 + 14];
prvblk[ch][sb18 + 14] = rawout[32];
tsOut[15 + sb18] = rawout[15] + prvblk[ch][sb18 + 15];
prvblk[ch][sb18 + 15] = rawout[33];
tsOut[16 + sb18] = rawout[16] + prvblk[ch][sb18 + 16];
prvblk[ch][sb18 + 16] = rawout[34];
tsOut[17 + sb18] = rawout[17] + prvblk[ch][sb18 + 17];
prvblk[ch][sb18 + 17] = rawout[35];
}
} | 6 |
public Point move( String move ) {
Point moveCoords = new Point();
switch( move ) {
case "NORTH":
moveCoords.x = 0;
moveCoords.y = -1;
break;
case "EAST":
moveCoords.x = 1;
moveCoords.y = 0;
break;
case "SOUTH":
moveCoords.x = 0;
moveCoords.y = 1;
break;
case "WEST":
moveCoords.x = -1;
moveCoords.y = 0;
break;
case "WAIT":
moveCoords.x = 0;
moveCoords.y = 0;
break;
default:
break;
}
return moveCoords;
} | 5 |
private void fillBoxes() {
for (int i = -20; i <= 20; i++) {
cmbYear.addItem(calendar.get(Calendar.YEAR) + i);
}
for (int j = 1; j <= 12; j++) {
cmbMonth.addItem(j);
}
cmbYear.setSelectedItem(year);
cmbMonth.setSelectedItem(month);
cmbYear.addItemListener(changeListener);
cmbMonth.addItemListener(changeListener);
} | 2 |
@FXML
protected void doubleClickPlaySelectedSong(MouseEvent mouseEvent) throws Exception {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
playSong();
}
//todo list index change
}
} | 2 |
public boolean equals(Object o) {
Association other = (Association) o;
return (this.PID.equals(other.PID) && this.QID.equals(other.QID))
|| (this.PID.equals(other.QID) && this.QID.equals(other.PID));
} | 3 |
private void cmbBoxAgeLimitActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cmbBoxAgeLimitActionPerformed
{//GEN-HEADEREND:event_cmbBoxAgeLimitActionPerformed
switch (cmbBoxAgeLimit.getSelectedIndex())
{
case 0:
switchLimitation = 0;
break;
case 1:
switchLimitation = 10;
break;
case 2:
switchLimitation = 12;
break;
case 3:
switchLimitation = 14;
break;
case 4:
switchLimitation = 16;
break;
case 5:
switchLimitation = 18;
break;
case 6:
switchLimitation = 100;
break;
}
try
{
search();
}
catch (Exception ex)
{
Logger.getLogger(RankingGui.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_cmbBoxAgeLimitActionPerformed | 8 |
public ArrayList<Boolean> solve()
{
double iterations = Math.pow(2,varCount); //2^varCount
double start = System.currentTimeMillis();
int tenth = (int) iterations/10;
for(int i = 0; i<(iterations);i++)
{
if(i%tenth == 0)
{
System.out.println(System.currentTimeMillis()- start);
}
ArrayList<Boolean> currentList = intToBooList(i);
if(formula.satisfies(currentList))
{
System.out.println(currentList);
return currentList;
}
}
System.out.println("No Match");
return null;
} | 3 |
public static void setLookAndFeel(){
try {
// Set System L&F
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (UnsupportedLookAndFeelException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
catch (InstantiationException e) {
// handle exception
}
catch (IllegalAccessException e) {
// handle exception
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
City other = (City) obj;
if (cityName == null) {
if (other.cityName != null)
return false;
} else if (!cityName.equals(other.cityName))
return false;
return true;
} | 6 |
public void actionPerformed(ActionEvent e) {
if (sound != null) {
sound.play();
}
} | 1 |
void flip() {
System.out.println("Flip trangle");
} | 0 |
public static void main(String[] args) throws InterruptedException {
MailUtil.sendMailSynchron("test", "这是一个测试", "289048093@qq.com",true);
Thread.sleep(5000);
} | 0 |
@Override
public void handleAttribute(final char[] buffer, final int nameOffset, final int nameLen,
final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen,
final int operatorLine, final int operatorCol, final int valueContentOffset,
final int valueContentLen, final int valueOuterOffset, final int valueOuterLen,
final int valueLine, final int valueCol) throws ParseException {
getNext().handleInnerWhiteSpace(
SIZE_ONE_WHITE_SPACE, 0, SIZE_ONE_WHITE_SPACE.length,
this.pendingEventLine, this.pendingEventCol);
final boolean isMinimizableBooleanAttribute =
this.minimizeMode.minimizeBooleanAttributes &&
isBooleanAttribute(buffer, nameOffset, nameLen) &&
TextUtil.equals(false, buffer, nameOffset, nameLen, buffer, valueContentOffset, valueContentLen);
if (isMinimizableBooleanAttribute) {
// If it is a minimizable boolean, no need to go any further
getNext().handleAttribute(
buffer,
nameOffset, nameLen, nameLine, nameCol,
0, 0, operatorLine, operatorCol,
0, 0, 0, 0, operatorLen, operatorCol
);
return;
}
final boolean canRemoveAttributeQuotes =
this.minimizeMode.unquoteAttributes &&
canAttributeValueBeUnquoted(buffer, valueContentOffset, valueContentLen, valueOuterOffset, valueOuterLen);
if (operatorLen <= 1 && !canRemoveAttributeQuotes) {
// Operator is already minimal enough, so we don't need to use our attribute-minimizing buffer
getNext().handleAttribute(buffer, nameOffset, nameLen, nameLine, nameCol, operatorOffset,
operatorLen, operatorLine, operatorCol, valueContentOffset, valueContentLen,
valueOuterOffset, valueOuterLen, valueLine, valueCol);
} else {
final int requiredLen = nameLen + 1 /* new operator len */ + valueOuterLen;
if (this.internalBuffer.length < requiredLen) {
this.internalBuffer = new char[requiredLen];
}
System.arraycopy(buffer, nameOffset, this.internalBuffer, 0, nameLen);
System.arraycopy(ATTRIBUTE_OPERATOR, 0, this.internalBuffer, nameLen, ATTRIBUTE_OPERATOR.length);
if (canRemoveAttributeQuotes) {
System.arraycopy(buffer, valueContentOffset, this.internalBuffer, nameLen + ATTRIBUTE_OPERATOR.length, valueContentLen);
getNext().handleAttribute(
this.internalBuffer,
0, nameLen, nameLine, nameCol,
nameLen, ATTRIBUTE_OPERATOR.length, operatorLine, operatorCol,
nameLen + ATTRIBUTE_OPERATOR.length, valueContentLen,
nameLen + ATTRIBUTE_OPERATOR.length, valueContentLen,
valueLine, valueCol);
} else {
System.arraycopy(buffer, valueOuterOffset, this.internalBuffer, nameLen + ATTRIBUTE_OPERATOR.length, valueOuterLen);
getNext().handleAttribute(
this.internalBuffer,
0, nameLen, nameLine, nameCol,
nameLen, ATTRIBUTE_OPERATOR.length, operatorLine, operatorCol,
nameLen + ATTRIBUTE_OPERATOR.length + (valueOuterOffset - valueContentOffset), valueContentLen,
nameLen + ATTRIBUTE_OPERATOR.length, valueOuterLen,
valueLine, valueCol);
}
}
} | 8 |
private void factor() {
int n = LU.numRows();
// Internal CRS matrix storage
int[] colind = LU.getColumnIndices();
int[] rowptr = LU.getRowPointers();
double[] data = LU.getData();
// Find the indices to the diagonal entries
int[] diagind = findDiagonalIndices(n, colind, rowptr);
// Go down along the main diagonal
for (int k = 1; k < n; ++k)
for (int i = rowptr[k]; i < diagind[k]; ++i) {
// Get the current diagonal entry
int index = colind[i];
double LUii = data[diagind[index]];
if (LUii == 0)
throw new RuntimeException("Zero pivot encountered on row "
+ (i + 1) + " during ILU process");
// Elimination factor
double LUki = (data[i] /= LUii);
// Traverse the sparse row i, reducing on row k
for (int j = diagind[index] + 1, l = rowptr[k] + 1; j < rowptr[index + 1]; ++j) {
while (l < rowptr[k + 1] && colind[l] < colind[j])
l++;
if (colind[l] == colind[j])
data[l] -= LUki * data[j];
}
}
L = new UnitLowerCompRowMatrix(LU, diagind);
U = new UpperCompRowMatrix(LU, diagind);
} | 7 |
public static void initView(JToolBar toolbar,
final BuilderController controller) {
toolbar.add(new JButton(new TooltipAction("Hint",
"Adds one transition.") {
public void actionPerformed(ActionEvent e) {
controller.hint();
}
}));
toolbar.add(new JButton(new TooltipAction("Complete",
"Adds all transitions.") {
public void actionPerformed(ActionEvent e) {
controller.complete();
}
}));
toolbar.add(new JButton(new TooltipAction("Done?",
"Checks if the automaton is done.") {
public void actionPerformed(ActionEvent e) {
controller.done();
}
}));
} | 0 |
public ChoiceQuest()
{
super(QuestType.CHOICEQUEST);
goTo="";
} | 0 |
public ClientHanldler(Socket client) {
this.client = client;
} | 0 |
public NickAlreadyInUseException(String e) {
super(e);
} | 0 |
private boolean searchDownForNextSupersetNode( Node node, K key, Object[] ret ) {
while( true ) {
// Descend left subtree if it might have superset node.
if( node.mLeft != null && mComp.compareMaxes( key, node.mLeft.mMaxStop.mKey ) <= 0 ) {
node = node.mLeft;
continue;
}
// Check if current node contains mKey.
int c = mComp.compareMins( key, node.mKey );
if( c >= 0 && mComp.compareMaxes( key, node.mKey ) <= 0 ) {
ret[0] = node;
return true;
}
// Descend right subtree if it might have a superset node.
if( node.mRight != null && c >= 0 && mComp.compareMaxes( key, node.mRight.mMaxStop.mKey ) <= 0 ) {
node = node.mRight;
continue;
}
// Request upward search from current node.
ret[0] = node;
return false;
}
} | 8 |
private BattleSelector newBattleSelector(List<BotList> initialBattles,
final ChallengeConfig challenge, final String challenger,
final Map<String, ScoreError> errorMap) {
final LinkedList<BotList> battleList = Lists.newLinkedList(initialBattles);
return new BattleSelector() {
@Override
public BotList nextBotList() {
if (!battleList.isEmpty()) {
return battleList.remove();
};
int minBattles = getMinBattles(errorMap);
double randomBattleChance =
SMART_BATTLE_RANDOM_RATE / power(2, minBattles - 2);
String nextBotListString = null;
if (Math.random() < randomBattleChance) {
List<String> minBotLists = Lists.newArrayList();
for (Map.Entry<String, ScoreError> entry : errorMap.entrySet()) {
if (entry.getValue().numBattles == minBattles) {
minBotLists.add(entry.getKey());
}
}
nextBotListString =
minBotLists.get((int) Math.random() * minBotLists.size());
} else {
double bestGain = Double.NEGATIVE_INFINITY;
for (Map.Entry<String, ScoreError> entry : errorMap.entrySet()) {
String botListString = entry.getKey();
if (challenge.allReferenceBots.size() <= _config.threads
|| !_runningBotLists.contains(botListString)) {
double accuracyGain = entry.getValue().getAccuracyGainRate();
if (accuracyGain > bestGain) {
bestGain = accuracyGain;
nextBotListString = botListString;
}
}
}
}
if (nextBotListString == null) {
throw new RuntimeException("Failed to select a battle!");
}
_runningBotLists.add(nextBotListString);
List<String> nextBotList =
Lists.newArrayList(nextBotListString.split(","));
nextBotList.add(challenger);
return new BotList(nextBotList);
}
};
} | 9 |
@Override
public void mark(int boardPosition, Cell[] cellBoard, int rows, int columns) throws IllegalMark {
//Find the row.
int boardPositionRow = boardPosition / columns;
//Find the column.
int boardPositionColumn = boardPosition % columns;
//Position to mark.
int positionToMark = boardPosition;
if (boardPositionRow -2 >=0){
//Left side.
if(boardPositionColumn -1 >= 0){
positionToMark = (boardPositionRow -2) * columns + boardPositionColumn -1;
mark(boardPosition,positionToMark, cellBoard);
}
if(boardPositionColumn +1 < columns){
positionToMark = (boardPositionRow -2) * columns + boardPositionColumn +1;
mark(boardPosition,positionToMark, cellBoard);
}
}
} | 3 |
public static Picture readPictureFromTga(String path) throws Exception {
File f = new File(path);
if (!f.exists()) {
throw new IllegalArgumentException("File at " + path + " does not exist. " + f.getAbsolutePath());
}
FileInputStream in = new FileInputStream(f);
int[] header = new int[18];
for (int i = 0; i < header.length; i++) {
header[i] = in.read();
}
if (header[2] != 2 || header[16] != 24 || header[8] != 0
|| header[9] != 0 || header[10] != 0 || header[11] != 0) {
throw new IllegalArgumentException("Unsupported TGA-format. Use uncompressed RGB's.");
}
int width = header[12] | (header[13] << 8);
int height = header[14] | (header[15] << 8);
int[] data = new int[width * height * 3];
for (int i = 0; i < data.length; i += 3) {
data[i + 2] = in.read();
data[i + 1] = in.read();
data[i] = in.read();
}
return new Picture(data, width, height);
} | 9 |
public Pedido insertar(Pedido pedido) throws DAOExcepcion {
System.out.println("PedidoDAO: insertar()");
String query = "INSERT INTO pedido (id_usuario,fecha,estado,total) VALUES (?,?,?,?)";
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = ConexionDB.obtenerConexion();
con.setAutoCommit(false);
stmt = con.prepareStatement(query);
stmt.setString(1, pedido.getIdUsuario());
stmt.setString(2, pedido.getFecha());
stmt.setString(3, pedido.getEstado());
stmt.setDouble(4, pedido.getTotal());
int i = stmt.executeUpdate();
if (i != 1) {
throw new SQLException("No se pudo insertar");
}
int idp = 0;
query = "SELECT LAST_INSERT_ID()";
stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
if (rs.next()) {
idp = rs.getInt(1);
}
pedido.setIdPedido(idp);
for (DetallePedido ped : pedido.getDetalles()) {
query = "INSERT INTO detalle_pedido(id_pedido, id_producto, precio, cantidad) VALUES (?,?,?,?)";
stmt = con.prepareStatement(query);
stmt.setInt(1, idp);
stmt.setInt(2, ped.getIdProducto());
stmt.setDouble(3, ped.getPrecio());
stmt.setInt(4, ped.getCantidad());
int u = stmt.executeUpdate();
if (u != 1) {
throw new SQLException("No se pudo insertar");
}
int idd = 0;
query = "SELECT LAST_INSERT_ID()";
stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
if (rs.next()) {
idd = rs.getInt(1);
}
ped.setIdDetallePedido(idd);
}
con.commit();
} catch (SQLException e) {
try {
con.rollback();
} catch (SQLException e1) {
throw new DAOExcepcion(e.getMessage());
}
System.err.println(e.getMessage());
throw new DAOExcepcion(e.getMessage());
} finally {
try {
con.setAutoCommit(true);
} catch (SQLException e) {
throw new DAOExcepcion(e.getMessage());
}
this.cerrarResultSet(rs);
this.cerrarStatement(stmt);
this.cerrarConexion(con);
}
return pedido;
} | 8 |
void mouseWheel(long time, int rotation, int modifiers) {
if (!viewer.getAwtComponent().hasFocus())
return; // XIE
hoverOff();
timeCurrent = time;
// Logger.debug("mouseWheel time:" + time + " rotation:" + rotation + " modifiers:" + modifiers);
if (rotation == 0)
return;
if ((modifiers & BUTTON_MODIFIER_MASK) == 0) {
if (viewer.getNavigationMode()) { // XIE
viewer.zoomBy(rotation > 0 ? 5 : -5);
}
else {
float zoomLevel = viewer.getZoomPercentSetting() / 100f;
if (rotation > 0) {
while (--rotation >= 0)
zoomLevel *= wheelClickFractionUp;
}
else {
while (++rotation <= 0)
zoomLevel *= wheelClickFractionDown;
}
viewer.zoomToPercent(zoomLevel * 100 + 0.5f);
}
}
} | 8 |
public void draw(){
background(255);
fill(0);
for(int i = 0; i < 5; i++){
threads[(int) alpha[i]].draw();
if(threads[i].getLinha().getAlpha() == 0){
nextLine();
System.out.println("AQUI");
}
}
} | 2 |
@Override
public double predict(int userID, int movieID) {
double rating = 0;
ArrayList<Double> sim = new ArrayList<Double>();
ArrayList<Double> rat = new ArrayList<Double>();
ArrayList<Double> avg = new ArrayList<Double>();
HashMap<Integer, Double> tempHashMap = similarities.get(userID);
//Fill the arrays
for (Map.Entry<Integer, Double> user2ID : tempHashMap.entrySet()) {
if (userMovieRatings.get(user2ID.getKey()).get(movieID) == null) {
} else {
sim.add(user2ID.getValue());
rat.add(userMovieRatings.get(user2ID.getKey()).get(movieID));
avg.add(averageRatings.get(user2ID.getKey()));
}
}
//Calculate the prediction with the chosen algorithm
if (pMetric.toLowerCase().equals("weightedsum")) {
rating = PredictionCalculator.calculateWeightedSum(sim, rat);
} else if (pMetric.toLowerCase().equals("adjustedsum")) {
rating = PredictionCalculator.calculateAdjustedSum(averageRatings.get(userID), avg, rat);
} else if (pMetric.toLowerCase().equals("adjustedweightedsum")) {
rating = PredictionCalculator.calculateAdjustedWeightedSum(averageRatings.get(userID), avg, rat, sim);
}
if (rating == 0)
return averageRatings.get(userID);
return rating;
} | 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Bot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Bot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Bot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Bot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Bot().setVisible(true);
}
});
} | 6 |
private void jbRechercheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRechercheActionPerformed
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
JOptionPane jOErreur = new JOptionPane("Driver non trouvé " + ex.getMessage());
}
Connection connexion = null;
try {
connexion = DriverManager.getConnection(sqlConnexion);
} catch (SQLException ex) {
JOptionPane jOErreur = new JOptionPane("Erreur de connexion a la base" + ex.getMessage());
}
Statement stmt = null;
try {
stmt = connexion.createStatement();
} catch (SQLException ex) {
JOptionPane jOErreur = new JOptionPane("Erreur Compte Utilisateur");
}
ResultSet rs = null;
try {
String auteurNom = "";
Vector tables = new Vector();
if (jtfNomAuteur.getText().equals("")){
rs = stmt.executeQuery("SELECT * from auteur where auteur_actif = 1");
}else{
auteurNom = jtfNomAuteur.getText();
rs = stmt.executeQuery("SELECT * FROM auteur where auteur_actif = 1 AND auteur_nom LIKE '%" + auteurNom + "%' ORDER BY auteur_nom");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
while (rs.next()) {
Vector listeNomAuteur = new Vector();
Auteur auteur = new Auteur (rs.getString("auteur_nom"), rs.getString("auteur_prenom"),
sdf.parse(rs.getString("auteur_date_naissance")));
// if (rs.getString("auteur_date_deces").equals("")){
// }else{
// auteur.setDateDAuteur(sdf.parse(rs.getString("auteur_date_deces")));
// }
listeNomAuteur.add(auteur.getNomAuteur());
listeNomAuteur.add(auteur.getPrenomAuteur());
listeNomAuteur.add(sdf.format(auteur.getDateNAuteur()));
tables.add(listeNomAuteur);
}
Vector titre = new Vector();
titre.add("Nom");
titre.add("prenom");
titre.add("Date de naissance");
// titres.add("Date de deces");
DefaultTableModel tm = new DefaultTableModel(tables, titre) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
jtlListeAuteur.setModel(tm);
} catch (SQLException ex) {
JOptionPane joErreur = new JOptionPane("Erreur saisie "+ex.getMessage());
} catch (ParseException ex) {
JOptionPane jOErreur = new JOptionPane("Erreur de conversion de date" + ex.getMessage());
}
try {
rs.close();
stmt.close();
} catch (SQLException ex) {
JOptionPane joErreur = new JOptionPane("erreur base de donnees" +ex.getMessage());
}
try {
connexion.close();
} catch (SQLException ex) {
JOptionPane joErreur = new JOptionPane("erreur Base de Donness" +ex.getMessage());
}
}//GEN-LAST:event_jbRechercheActionPerformed | 9 |
public void update() {
player.update();
player.checkAttack(enemies);
player.checkCoins(coins);
finish.update();
finish.checkGrab(player);
bg.setPosition(tileMap.getx(), 0);
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety());
if(player.isDead()){
player.setPosition(100, 500);
player.reset();
//restart();
player.revive();
}
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
e.update();
if(player.isDrunk()){
e.kill();
}
if(e.isDead()){
enemies.remove(i);
e.addScore(Level2State.score);
i--;
}
}
for(int i = 0; i < coins.size(); i++){
Coin c = coins.get(i);
c.update();
if(c.shouldRemove()){
coins.remove(i);
c.addScore();
i--;
}
}
} | 6 |
private void addMTWCs(MTWData data, int x, int y, int dx, int dy) {
// Create set of tuples with coordinates - with annoying syntax
Set<Tuple<Integer, Integer>> set = new HashSet<Tuple<Integer, Integer>>();
// Trace in the given direction and it's opposite direction
Tuple<Integer, Integer> first = traceDirection(set, data.board, data.player, x, y, dx, dy);
Tuple<Integer, Integer> second = traceDirection(set, data.board, data.player, x - dx, y - dx, -dx, -dy);
// Add to heuristic data if not empty and the WC is large enough to give a win
if (!set.isEmpty() && first._1 + first._2 + second._1 + second._2 > 3) {
int mTW = 4 - first._1 + second._1;
if (data.player == playerID) {
data.mTWCFP1.add(set);
if (mTW < data.mTW1) data.mTW1 = mTW;
}
else {
data.mTWCFP2.add(set);
if (mTW < data.mTW2) data.mTW2 = mTW;
}
}
} | 5 |
private void get(Player cmdSender, String... args) {
for (String arg : args)
switch (arg) {
case CMD_ARG_GETOPS:
cmdSender.chat("List of Operators:");
for (OfflinePlayer player : getServer().getOperators())
cmdSender.chat(player.getName());
break;
case CMD_ARG_GETBANS:
cmdSender.chat("List of Banned Players:");
for (OfflinePlayer player : getServer().getBannedPlayers())
cmdSender.chat(player.getName());
break;
case CMD_ARG_GETBANNEDIPS:
cmdSender.chat("List of Banned IPs:");
for (String ip : getServer().getIPBans())
cmdSender.chat(ip);
break;
case CMD_ARG_GETPLUGINS:
cmdSender.chat("List of Plugins:");
for (Plugin plugin : getServer().getPluginManager().getPlugins())
cmdSender.chat(plugin.getName());
break;
default:
break;
}
} | 9 |
@RequestMapping("salvarProduto")
public ModelAndView salvarProduto(Produto produto,
@RequestParam(value = "grupoDoProduto") String[] grupoDoProduto,
@RequestParam(value = "temaDoProduto") String[] temaDoProduto,
HttpServletRequest request) {
ModelAndView mav = new ModelAndView("redirect:admin");
if (adminController.isLogado()) {
feedbacks.clear();
if (produto.valido(feedbacks)) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("arquivo");
applyCategorias(produto, grupoDoProduto, temaDoProduto);
if (produto.getId() != 0) {
alterarProduto(produto, file);
} else {
inserirProduto(produto, file);
}
this.produto = produto;
}
mav.setViewName("redirect:cadastroDeProduto");
}
finaliza(mav);
return mav;
} | 3 |
void insert(RedBlackNode z)
{
RedBlackNode y = nil;
RedBlackNode x = root;
while(x != nil)
{
y = x;
if(z.key.compareTo(x.key) < 0)
x = x.left;
else
x = x.right;
}
z.parent = y;
if(y == nil)
root = z;
else if(z.key.compareTo(y.key) < 0)
y.left = z;
else
y.right = z;
z.left = nil;
z.right = nil;
z.color = RED;
insertFixUP(z);
} | 4 |
private void waitForThread() {
if ((this.thread != null) && this.thread.isAlive()) {
try {
this.thread.join();
} catch (final InterruptedException e) {
plugin.getLogger().log(Level.SEVERE, null, e);
}
}
} | 3 |
public void listPlugins(CommandSender sender, String[] args) {
if (args.length > 1) {
sender.sendMessage(pre + red + tooMany);
return;
}
StringBuilder list = new StringBuilder();
List<String> pluginList = new ArrayList<String>();
for (Plugin pl : Bukkit.getServer().getPluginManager().getPlugins()) {
String plName = "";
plName += pl.isEnabled() ? green : red;
plName += pl.getDescription().getName();
pluginList.add(plName);
}
Collections.sort(pluginList, String.CASE_INSENSITIVE_ORDER);
for (String plName : pluginList) {
if (list.length() > 0) {
list.append(white + ", ");
}
list.append(plName);
}
sender.sendMessage(pre + gray + "Plugins: " + list);
} | 5 |
public ViewUserLogin()
{
setTitle("Login");
setLayout(new GridLayout(3,2));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
u=new JLabel("Username");
p=new JLabel("Password");
uname=new JTextField(20);
pass=new JPasswordField(20);
login=new JButton("Login");
cancel=new JButton("Cancel");
add(u);
add(uname);
add(p);
add(pass);
add(login);
add(cancel);
uname.requestFocus();
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
System.exit(0);
}
});
login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
String un=uname.getText();
String pa=new String(pass.getPassword());
ClientWebService auth = new ClientWebService();
Boolean isAuth = false;
try {
isAuth = auth.login(un, pa);
} catch (SOAPException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
JOptionPane.showMessageDialog( null, "Serveur inaccessible",
"GamePlayerXML", JOptionPane.INFORMATION_MESSAGE);
}
if(isAuth)
{
//On r�cup�re l'instance de la classe user et on lui d�finit le login du user
//Qui se connecte
String login = un;
User user = User.getInstance();
user.setLogin(login);
dispose();
ViewMainMenu vmm = new ViewMainMenu();
ModelMainMenu mmm = new ModelMainMenu();
ControllerMainMenu cmm = new ControllerMainMenu(vmm, mmm);
}
else
{
JOptionPane.showMessageDialog( null, "Login et/ou mot de passe incorrects",
"GamePlayerXML", JOptionPane.INFORMATION_MESSAGE);
}
}
});
KeyAdapter k=new KeyAdapter(){
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode()==KeyEvent.VK_ENTER)
login.doClick();
}
};
pass.addKeyListener(k);
uname.addKeyListener(k);
pack();
setLocationRelativeTo(null);
} | 3 |
public static void loadAccounts() {
try {
accounts.clear();
File accountsFile = new File(Configuration.ACCOUNTS_DIR + File.separator + "Accounts.txt");
if (!accountsFile.exists()) {
accountsFile.createNewFile();
return;
}
StringBuilder fileContents = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(accountsFile));
String line;
while ((line = br.readLine()) != null) {
fileContents.append(line);
}
br.close();
String[] rawAccs = fileContents.toString().split(";");
if (rawAccs[0].length() > 0) {
for (String acc : rawAccs) {
String[] split = acc.split(":");
accounts.add(new Account(split[0], split[1], split[2], split[3]));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.