method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
0f59f6cc-e845-4576-b706-2344f3a9ca27 | 1 | public int[] getSelectedIndexes() {
int[] array = new int[getCount()];
int i = 0;
int index = firstSelectedIndex();
while (index != -1) {
array[i++] = index;
index = nextSelectedIndex(index + 1);
}
return array;
} |
f06d13d5-1daf-44cf-9d67-54ab7d910f26 | 9 | @Override
public String Imprimir_det_proceso(String iddgp, String idrp, String iddep) {
String cadena = "";
try {
this.conn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE);
String sql = "SELECT f.de_pasos, "
+ " f.nu_pasos ,s.es_autorizacion, rhfu_count_aut_dgp ('" + iddgp + "') as count_aut,rhfu_detalle_puesto_aut ('" + idrp + "',f.id_pasos,'" + iddep.trim() + "') as puesto_aut "
+ "FROM "
+ " (SELECT p.id_pasos, "
+ " p.id_proceso, "
+ " rp.id_detalle_req_proceso, "
+ " p.de_pasos, "
+ " p.nu_pasos, "
+ " p.co_pasos, "
+ " pro.no_proceso, "
+ " rp.id_direccion, "
+ " rp.id_departamento, "
+ " rp.id_requerimiento "
+ " FROM rhtc_pasos p , "
+ " rhtv_proceso pro, "
+ " rhtr_detalle_req_proceso rp "
+ " WHERE pro.id_proceso = p.id_proceso "
+ " AND rp.id_proceso = pro.id_proceso "
+ " AND rp.ES_REQ_PROCESO='1' "
+ " AND p.ES_PASOS ='1' "
+ " ) f "
+ "LEFT OUTER JOIN "
+ " (SELECT pu.NO_PUESTO, "
+ " du.NO_USUARIO, "
+ " a.co_pasos, "
+ " a.DE_PASOS, "
+ " a.es_autorizacion, "
+ " a.fe_creacion, "
+ " a.id_autorizacion, "
+ " a.id_departamento, "
+ " a.id_detalle_pasos, "
+ " a.id_detalle_req_proceso, "
+ " a.id_dgp, "
+ " a.id_direccion, "
+ " a.id_pasos, "
+ " a.id_proceso, "
+ " a.id_puesto, "
+ " a.id_requerimiento, "
+ " a.no_proceso, "
+ " a.nu_pasos, "
+ " a.us_creacion , "
+ " dt.AP_PATERNO, "
+ " dt.AP_MATERNO, "
+ " dt.NO_TRABAJADOR, "
+ " dgp.CA_SUELDO, "
+ " du.AP_PATERNO AS us_ap_p, "
+ " du.AP_MATERNO AS us_ap_mat , "
+ " du.NO_TRABAJADOR AS us_no_tr, "
+ " du.NO_PUESTO AS us_no_puesto, "
+ " du.NO_AREA AS us_no_area, "
+ " du.NO_DEP AS us_no_dep "
+ " FROM "
+ " (SELECT a.id_detalle_req_proceso, "
+ " a.id_dgp, "
+ " a.id_pasos, "
+ " d.id_proceso, "
+ " d.id_detalle_pasos , "
+ " d.DE_PASOS, "
+ " d.NU_PASOS, "
+ " d.CO_PASOS , "
+ " d.no_proceso , "
+ " d.id_puesto, "
+ " d.id_direccion, "
+ " d.id_departamento , "
+ " d.id_requerimiento , "
+ " a.id_autorizacion, "
+ " a.fe_creacion, "
+ " a.es_autorizacion, "
+ " a.us_creacion "
+ " FROM "
+ " (SELECT * FROM rhvd_req_paso_pu "
+ " ) d "
+ " LEFT OUTER JOIN rhtv_autorizacion a "
+ " ON ( a.id_pasos =d.id_pasos "
+ " AND d.id_pasos =a.id_pasos "
+ " AND d.id_puesto =a.id_puesto "
+ " AND d.id_detalle_req_proceso=a.id_detalle_req_proceso) "
+ " ) a , "
+ " rhtm_dgp dgp , "
+ " rhtm_trabajador dt , "
+ " rhvd_usuario du , "
+ " rhvd_puesto_direccion pu "
+ " WHERE dgp.id_dgp =a.id_dgp "
+ " AND dt.id_trabajador = dgp.id_trabajador "
+ " AND du.id_usuario =a.us_creacion "
+ " AND dgp.id_puesto =pu.id_puesto "
+ " AND dgp.id_dgp ='" + iddgp + "' "
+ " ) s ON ( s.ID_DETALLE_REQ_PROCESO=f.ID_DETALLE_REQ_PROCESO "
+ "AND f.id_pasos =s.id_pasos ) "
+ "WHERE f.ID_DETALLE_REQ_PROCESO ='" + idrp + "' "
+ "ORDER BY to_number(SUBSTR(f.nu_pasos,2,LENGTH(f.nu_pasos))) ASC";
ResultSet rs = this.conn.query(sql);
int i = 0;
while (rs.next()) {
i++;
if (rs.getString("es_autorizacion") != null) {
if (rs.getString("es_autorizacion").equals("1")) {
if (i == 1) {
cadena = cadena
+ " <div class=\"new-circle done\" rel=\"popover-hover\" data-placement=\"top\" data-original-title=\"" + rs.getString("de_pasos") + "\" data-content=\""
+ rs.getString("puesto_aut") + "\" data-html=\"true\">"
+ "<span class=\"new-label\">✔</span>"
+ "<span class=\"new-title\">" + rs.getString("nu_pasos") + "</span> "
+ "</div>";
} else {
cadena = cadena
+ " <span class=\"new-bar done\"></span> "
+ "<div class=\"new-circle done\" rel=\"popover-hover\" data-placement=\"top\" data-original-title=\"" + rs.getString("de_pasos") + "\" data-content=\"" + rs.getString("puesto_aut") + " \" data-html=\"true\">"
+ "<span class=\"new-label\">✔</span>"
+ "<span class=\"new-title\">" + rs.getString("nu_pasos") + "</span>"
+ " </div>";
}
}
if (rs.getString("es_autorizacion").equals("2")) {
cadena = cadena
+ " <span class=\"new-bar done\"></span> "
+ "<div class=\"new-circle rechazo\" rel=\"popover-hover\" data-placement=\"top\" data-original-title=\"" + rs.getString("de_pasos") + "\" data-content=\" " + rs.getString("puesto_aut") + " \" data-html=\"true\">"
+ "<span style='color:white; font:bold;' class=\"new-label fa fa-warning\"></span>"
+ "<span class=\"new-title\">" + rs.getString("nu_pasos") + "</span>"
+ " </div>";
}
} else if (rs.getInt("count_aut") + 1 == i) {
//if (false) {
cadena = cadena
+ " <span class=\"new-bar active\"></span> "
+ "<div class=\"new-circle active\" rel=\"popover-hover\" data-placement=\"top\" data-original-title=\"" + rs.getString("de_pasos") + "\" data-content=\"" + rs.getString("puesto_aut") + " \" data-html=\"true\">"
+ "<span class=\"new-label fa fa-inbox\"></span>"
+ "<span class=\"new-title\">" + rs.getString("nu_pasos") + "</span>"
+ " </div>";
} else {
cadena = cadena
+ " <span class=\"new-bar \"></span> "
+ "<div class=\"new-circle\" rel=\"popover-hover\" data-placement=\"top\" data-original-title=\"" + rs.getString("de_pasos") + "\" data-content=\"" + rs.getString("puesto_aut") + " \" data-html=\"true\">"
+ "<span class=\"new-label fa fa-lock\"></span>"
+ "<span class=\"new-title\">" + rs.getString("nu_pasos") + "</span>"
+ " </div>";
}
}
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
throw new RuntimeException("ERROR");
} finally {
try {
this.conn.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return cadena;
} |
6cb5b3b1-d8c5-4437-b842-b13dc8540516 | 5 | private void psersistDimensions() throws IOException {
Set<Dimension> persistedDimensions = new HashSet<Dimension>();
Document dimensionXml = DocumentHelper.createDocument();
Element dimensionRoot = dimensionXml.addElement("dimensions");
Element dimensionElement;
Element levelElement;
Set<Level> levels;
Set<Dimension> dimensions;
Element rangeElement;
for (Schema schema : schemas) {
dimensions = schema.getDimensions();
for (Dimension dimension : dimensions) {
if (persistedDimensions.contains(dimension)) {
continue;
} else {
persistedDimensions.add(dimension);
}
dimensionElement = dimensionRoot.addElement("dimension");
// persist name
dimensionElement.addElement("name")
.addText(dimension.getName());
// persist levels
levels = dimension.getLevels();
for (Level level : levels) {
levelElement = dimensionElement.addElement("level");
levelElement.addElement("name").addText(level.getName());
levelElement.addElement("length").addText(
String.valueOf(level.getLength()));
levelElement.addElement("begin").addText(
String.valueOf(level.getBegin()));
levelElement.addElement("orderNumber").addText(
String.valueOf(level.getOrderNumber()));
}
// persist orderNumber
dimensionElement.addElement("orderNumber").addText(
String.valueOf(dimension.getOrderNumber()));
// persist dimensionRange
DimensionRange dimensionRange = dimension.getRange();
rangeElement = dimensionElement.addElement("range");
rangeElement.addElement("start").addText(
String.valueOf(dimensionRange.getStart()));
rangeElement.addElement("end").addText(
String.valueOf(dimensionRange.getEnd()));
}
}
if (DebugConf.isHadoopDebug()) {
FileWriter dimensionFileWriter = new FileWriter(
PathConf.getDimensionXmlFilePath());
dimensionXml.write(dimensionFileWriter);
dimensionFileWriter.close();
} else {
Path hdfsFile = new Path(PathConf.getDimensionXmlFilePath());
FileSystem hdfs = FileSystem.get(CubeConfiguration
.getConfiguration());
FSDataOutputStream out = hdfs.create(hdfsFile);
out.write(dimensionXml.asXML().getBytes());
out.close();
hdfs.close();
}
} |
f91413a2-ab7a-422e-bcb5-86c7cd456f76 | 4 | public int removeElement(int[] A, int elem) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int len = A.length;
int i = 0, j = 0;
for (; i < A.length; ++i, ++j) {
if (A[i] == elem) {
--j;
--len;
continue;
}
if (j >= 0 && A[i] != A[j]) {
A[j] = A[i];
}
}
return len;
} |
9986666b-cc14-4520-b441-e4883c30dc4c | 9 | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String ubicacion = "";
InterfaceContratoDAO c = new ContratoDAO();
try {
ubicacion = FactoryConnectionDB.url + "Contratos_Adjuntos/";
DiskFileItemFactory f = new DiskFileItemFactory();
if (f.getSizeThreshold() <= 500000) {
//out.print("adassd");
} else {
// out.print("putopoooo");
}
f.setRepository(new File(ubicacion));
ServletFileUpload upload = new ServletFileUpload(f);
List<FileItem> p = upload.parseRequest(request);
String idc = null;
String nombre_archivo = null;
String no_original = null;
long tamaño = 0;
// long sizeInBytes = 0;
Iterator it = p.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) {
String nombre = item.getFieldName();
String valor = item.getString();
if (nombre.equals("idc") & idc == null) {
idc = valor;
}
} else {
tamaño = item.getSize();
if (tamaño <= 500000) {
String fieldName = item.getFieldName();
Calendar fecha = new GregorianCalendar();
int hora = fecha.get(Calendar.HOUR_OF_DAY);
int min = fecha.get(Calendar.MINUTE);
int sec = fecha.get(Calendar.SECOND);
if (fieldName.equals("archivo")) {
nombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + idc + "_" + item.getName().toUpperCase();
no_original = item.getName();
Thread thread = new Thread(new Renombrar(item, ubicacion, nombre_archivo));
thread.start();
} else {
no_original = no_original;
nombre_archivo = nombre_archivo;
}
}
}
}
if (tamaño <= 500000) {
if (nombre_archivo != null) {
c.INSERT_CONTRATO_ADJUNTO(null, idc, nombre_archivo, no_original, null, null, null, null, null, null);
}
out.println(no_original);
out.println(nombre_archivo);
out.println(tamaño);
} else {
out.print("No se permite subir archivos mayores a 0.5MB");
out.print(upload.getFileSizeMax());
}
//sesion.setAttribute("ListaridTrabajador", tr.ListaridTrabajador(idtr));
//Thread.sleep(2000);
// response.sendRedirect("Vista/Trabajador/Detalle_Trabajador.jsp?idtr=" + idtr);
// out.println("Archivo subido correctamente");
} catch (Exception e) {
out.println(e.getMessage());
}
} |
b71e330b-eeb1-4fa2-893d-fcf05f906871 | 4 | public static boolean outsideAuburyShop() {
int x = Players.getLocal().getLocation().getX();
int y = Players.getLocal().getLocation().getY();
return x >= 3246 && y >= 3396 && x <= 3259 && y <= 3410 && !inAuburyShop();
} |
e163bd65-1736-45a2-a225-925412523b47 | 1 | public String getClassAlias(String className) {
ClassIdentifier classIdent = getClassIdentifier(className);
if (classIdent == null)
return className;
return classIdent.getFullAlias();
} |
33158060-f2b7-4987-8b7e-a4dc7ac3fa72 | 2 | public void deleteItemFromArticle(String id) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction().begin();
Article itemDelete = (Article) session.get(Article.class, id);
session.delete(itemDelete);
session.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
} |
b3aaceed-ced0-4c5d-9359-ebde5b71b297 | 9 | public static void index(String[] args) {
String usage = "java org.apache.lucene.demo.IndexFiles"
+ " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
+ "This indexes the documents in DOCS_PATH, creating a Lucene index"
+ "in INDEX_PATH that can be searched with SearchFiles";
String indexPath = "index2";
String docsPath = null;
boolean create = true;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
indexPath = args[i + 1];
i++;
} else if ("-docs".equals(args[i])) {
docsPath = args[i + 1];
i++;
} else if ("-update".equals(args[i])) {
create = false;
}
}
if (docsPath == null) {
System.err.println("Usage: " + usage);
System.exit(1);
}
final File docDir = new File(docsPath);
if (!docDir.exists() || !docDir.canRead()) {
System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
try {
System.out.println("Indexing to directory '" + indexPath + "'...");
Directory dir = FSDirectory.open(new File(indexPath));
// :Post-Release-Update-Version.LUCENE_XY:
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_0, analyzer);
if (create) {
// Create a new index in the directory, removing any
// previously indexed documents:
iwc.setOpenMode(OpenMode.CREATE);
} else {
// Add new documents to an existing index:
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
}
// Optional: for better indexing performance, if you
// are indexing many documents, increase the RAM
// buffer. But if you do this, increase the max heap
// size to the JVM (eg add -Xmx512m or -Xmx1g):
//
// iwc.setRAMBufferSizeMB(256.0);
IndexWriter writer = new IndexWriter(dir, iwc);
indexDocs(writer, docDir);
// NOTE: if you want to maximize search performance,
// you can optionally call forceMerge here. This can be
// a terribly costly operation, so generally it's only
// worth it when your index is relatively static (ie
// you're done adding documents to it):
//
// writer.forceMerge(1);
writer.close();
Date end = new Date();
System.out.println(end.getTime() - start.getTime() + " total milliseconds");
} catch (IOException e) {
System.out.println(" caught a " + e.getClass() +
"\n with message: " + e.getMessage());
}
} |
26ae460a-7c63-491f-a1d1-9b0456bacf41 | 4 | public int solution(int[] array) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : array) {
map.put(i, map.containsKey(i) ? map.get(i) + 1 : 1);
}
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > array.length / 2) {
return entry.getKey();
}
}
return -1;
} |
6b39f0f8-66cf-414b-ae76-4db4928108d9 | 1 | public long getWorldAge() {
if (world != null)
return world.getStepCount();
return 0;
} |
8ab5798d-158f-49c0-88f6-2d194178dcc9 | 0 | public FlyingAbility getFlyingAbility() {
return flyingAbility;
} |
c318f300-aa52-47b3-b7ce-2b2c5ba52e36 | 8 | private Client_Response angriff(SpielEreigniss Ereigniss) {
//***********wechsel der Phase????********************
if (Ereigniss.phasenwechsel)
return angriff_verlassen();
//***********Darf der Angriff durchgefuehrt werden???********************
if (!(DieSpielwelt.pruefe_Attacke(Ereigniss.erstesLand, Ereigniss.zweitesLand, aktueller_Spieler))) {
aktueller_Response = new Client_Response(DieSpielwelt, Zustand, aktueller_Spieler, true);
throw new IllegalArgumentException("can not attack!");
}
if ((Ereigniss.erstesLand.gib_anzahl_armeen()-Ereigniss.anz_Armeen)<=0) throw new IllegalArgumentException("To many armis are selected!");
//***********Angriff an sich********************
Land angreifer_Land = Ereigniss.erstesLand;
Land verteidiger_Land = Ereigniss.zweitesLand;
int angreifer = Ereigniss.anz_Armeen;
int angreifer_wuerfel=0;
int verteidiger_wuerfel=0;
if (angreifer>3) angreifer_wuerfel=3; else angreifer_wuerfel=angreifer;
if (verteidiger_Land.gib_anzahl_armeen()>2) verteidiger_wuerfel=2; else verteidiger_wuerfel=verteidiger_Land.gib_anzahl_armeen();
//if (verteidiger_wuerfel>angreifer_wuerfel) verteidiger_wuerfel=angreifer_wuerfel;
//wuerfeln...
int[] angreifer_wuerfel_array = new int[angreifer_wuerfel];
int[]verteidiger_wuerfel_array = new int[verteidiger_wuerfel];
wuerfele(angreifer_wuerfel_array, verteidiger_wuerfel_array);
//vergleichen
int tote_angreifer=0;
int tote_verteidiger=0;
for (int i=0; i<verteidiger_wuerfel_array.length;i++){
if (angreifer_wuerfel_array[i]<=verteidiger_wuerfel_array[i]){
tote_angreifer++;
}else{
tote_verteidiger++;
}
}
//Angriff durchfuehren
DieSpielwelt.fuehre_Angriff_durch(tote_angreifer, angreifer, tote_verteidiger, angreifer_Land, verteidiger_Land);
//Spiel zu ende?
if (pruefe_Spiel_ende()) {
Zustand = Spielzustaende.Beenden;
}
//Baue Response
aktueller_Response = new Client_Response(DieSpielwelt, Zustand, aktueller_Spieler, false);
aktueller_Response.angreifer_wuerfel = angreifer_wuerfel_array;
aktueller_Response.verteidiger_wuerfel = verteidiger_wuerfel_array;
return aktueller_Response;
} |
7ef8d0d0-6795-4acd-82f0-09bba8fb9b30 | 5 | public void run() {
StringBuilder builder = new StringBuilder();
try {
SteamOwnedGamesResponse response = TwitchTools.GSON.fromJson(Utils.urlToString("http://api.steampowered" +
".com/IPlayerService/GetOwnedGames/v0001/?key=" + TwitchTools.settings.getSteamApiKey() +
"&steamid=" + TwitchTools.settings.getSteamPlayerID() + "&format=json&include_appinfo=1")
, SteamOwnedGamesResponse.class);
int done = 0;
for (SteamOwnedGame game : response.getGames()) {
done++;
String info = "";
switch (this.type) {
case "october":
info = "\t{% partial \"game-panel\" game=\"" + game.getName() + "\" image=\"" +
game.getImageLogoURL() + "\" page=\"" + game.getLink() + "\" %}\n";
if (done == 1) {
info = "<div class=\"row\">\n" + info;
} else if ((done % 3) == 0) {
info = info + "</div>\n\n<div class=\"row\">\n";
}
break;
}
builder.append(info);
}
System.out.println(builder.toString());
} catch (IOException e) {
e.printStackTrace();
}
} |
01712deb-276d-455a-83f4-59f5b6fe9599 | 3 | @Override
public void updateIcon() {
if(isProperty()) {
if (isPropertyInherited()) {
setIcon(ICON_IS_PROPERTY_INHERITED);
} else {
setIcon(ICON_IS_PROPERTY);
}
} else {
if (isPropertyInherited()) {
setIcon(ICON_IS_NOT_PROPERTY_INHERITED);
} else {
setIcon(ICON_IS_NOT_PROPERTY);
}
}
} |
16bb4c4e-2e99-40b7-8904-fc480fc7c3ba | 6 | public final void setSuccs(Object newSuccs) {
if (succs == newSuccs)
return;
removeSuccs();
if (newSuccs == null)
return;
if (newSuccs instanceof Instruction[]) {
Instruction[] ns = (Instruction[]) newSuccs;
switch (ns.length) {
case 0:
break;
case 1:
succs = ns[0];
ns[0].addPredecessor(this);
break;
default:
succs = ns;
for (int i = 0; i < ns.length; i++)
ns[i].addPredecessor(this);
break;
}
} else {
succs = newSuccs;
((Instruction) newSuccs).addPredecessor(this);
}
} |
8c685406-07e5-4ddd-8078-637d09dfa1e1 | 1 | public void removePush() {
if (exprStack != null)
instr = exprStack.mergeIntoExpression(instr);
super.removePush();
} |
684da02c-9592-45ba-9413-0b25bdd53e0f | 6 | public int stochFLookback( int optInFastK_Period,
int optInFastD_Period,
MAType optInFastD_MAType )
{
int retValue;
if( (int)optInFastK_Period == ( Integer.MIN_VALUE ) )
optInFastK_Period = 5;
else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
return -1;
if( (int)optInFastD_Period == ( Integer.MIN_VALUE ) )
optInFastD_Period = 3;
else if( ((int)optInFastD_Period < 1) || ((int)optInFastD_Period > 100000) )
return -1;
retValue = (optInFastK_Period - 1);
retValue += movingAverageLookback ( optInFastD_Period, optInFastD_MAType );
return retValue;
} |
67bf75b5-ba27-4367-994e-dcc6e53c08a9 | 9 | public void moveToPlayer()
{
resetDirection();
int dx = player.getX()-getX();
int dy = player.getY()-getY();
// if( Math.abs(dx) < WeaponItem.range() && Math.abs(dy) < WeaponItem.range() ){
if( Math.abs(dx) < 30 && Math.abs(dy) < 30 ){
// Attack with delay 1500 ms inbetween slashes
if(getTimeStamp() == 0)
{
setTimeStamp(TimeHandler.getTime());
setActionTime(1500);
resetDirection();
setAttacking(true);
}
if( !TimeHandler.timePassed(getTimeStamp(), getActionTime()))
{
// Do nothing..
}
else
{
setTimeStamp(0);
}
}else{
if(dy > 0){
if( Math.abs(dy) > Math.abs(dx) ){
moveY(1);
move();
}else{
if(dx < 0){
moveX(-1);
move();
}else{
moveX(1);
move();
}
}
}else{
if( Math.abs(dy) > Math.abs(dx) ){
moveY(-1);
move();
}else{
if(dx < 0){
moveX(-1);
move();
}else{
moveX(1);
move();
}
}
}
}
} |
59543248-9a02-484b-8524-a77f3a6382ab | 6 | private void sortColComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortColComboBoxActionPerformed
// TODO add your handling code here:
Sorter sort = new Sorter(DATA_POINTS);
String optionChosen = sortColComboBox.getSelectedItem().toString();
int mode = sortDirComboBox.getSelectedItem().toString().equals("Low to High") ?
Sorter.LOW_TO_HIGH : Sorter.HIGH_TO_LOW;
String data[][] = {};
if(optionChosen.equals(dataTableHeader[0]))
{
data = sort.sortBest(recentData, 0, mode);
}
else if(optionChosen.equals(dataTableHeader[1]))
{
data = sort.sortBest(recentData, 1, mode);
}
else if(optionChosen.equals(dataTableHeader[2]))
{
data = sort.sortBest(recentData, 2, mode);
}
else if(optionChosen.equals(dataTableHeader[3]))
{
data = sort.sortBest(recentData, 3, mode);
}
else if(optionChosen.equals(dataTableHeader[4]))
{
// Penalties box! Make another sorter!
data = sort.filterPenalties(recentData, 4, mode);
}
else
{
System.err.println("OH GOD! THE BLOOD!! ITS EVERYWHERE");
System.exit(1);
}
displayData(data);
}//GEN-LAST:event_sortColComboBoxActionPerformed |
7b50b161-7b75-49e8-b680-ba0dbe4f1650 | 0 | public Screen( JPanel event_processor ) {
add( event_processor );
event_processor.setFocusable( true );
} |
67f81822-d5bd-4b01-bf63-9be06a4de3df | 9 | public String process() throws IOException {
StringWriter result = new StringWriter();
int nesting = 0;
String line;
while ((line = StringHelper.readLine(reader)) != null) {
Matcher m = begin.matcher(line);
if (m.matches()) {
nesting++;
}
else {
m = end.matcher(line);
if (m.matches()) {
if (nesting == 0) {
throw new IllegalArgumentException("Invalid nesting");
}
nesting--;
}
else if (nesting == 0) {
line = processComment(line);
if (line != null && line.length() > 0) {
line = processPrint(line);
if (line != null && line.length() > 0) {
result.write(line);
}
}
}
}
}
return result.toString();
} |
39d9bdd4-223e-4c8b-9f93-8b16dcd71711 | 1 | private void register(Path dir) throws IOException {
if(!dir.getFileName().toString().startsWith(".")){
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
keys.put(key, dir);
}
} |
e887cfcb-1280-4d34-80d7-128d3c338b95 | 9 | private boolean isDiagonalWin(int player) throws Exception {
boolean win = false;
if ((player < 0) || (player > TicTacToeBoard.PLAYER_O)) {
throw new Exception("Invalid player index -- must be 0 or 1");
}
String playerSymbol;
if( player == PLAYER_X) {
playerSymbol = X;
} else {
playerSymbol = O;
}
if ((square[0][0] == square[1][1]) && (square[1][1] == square[2][2])
&& (square[2][2] == playerSymbol)) {
win = true;
}
if ((square[0][2] == square[1][1]) && (square[1][1] == square[2][0])
&& (square[2][0] == playerSymbol)) {
win = true;
}
return win;
} |
e0937d7a-ef94-4ee5-a90e-8bb81d283f5f | 0 | public String getEmail() {
return Email;
} |
2f5540a3-7ccb-48e2-967f-048bc40ed5a7 | 6 | public void extraireBipartis() {
Fenetre.lePert.sommets = new ListeSommets();
for (int i = 0; i < sommets().size(); i++) {
Sommet leSommet = sommets().elementAt(i);
for (int j = 0; j < sommets().size(); j++) {
Sommet leSommet2 = sommets().elementAt(j);
if (leSommet.getSuccesseurs().isEmpty()) {
// System.out.println(" i j : " + i + " : "+ j);
// System.out.println(leSommet.getNom()+
// " : "+leSommet2.getNom());
break;
}
else {
// System.out.println(" i j : " + i + " "+ j);
if ((leSommet.getSuccesseurs().containsAll(leSommet2
.getSuccesseurs()))
&& (leSommet2.getSuccesseurs().containsAll(leSommet
.getSuccesseurs()))) {
if (getBiparti1(leSommet.getSuccesseurs()) == null) {
// System.out.println("exist not "+ i + " "+ j);
Sommet leBiparti = new Sommet();
ListeSommets liste = new ListeSommets();
liste.add(leSommet);
liste.add(leSommet2);
leBiparti.input.ajouterNonRedandante(liste);
leBiparti.output.addAll(leSommet.getSuccesseurs());
Fenetre.lePert.sommets.add(leBiparti);
leBiparti.setLibelle(Fenetre.lePert.nbreBiparti);
leBiparti.setNom("B" + Fenetre.lePert.nbreBiparti);
Fenetre.lePert.nbreBiparti++;
// System.out.println(leBiparti.getNom()+" ** ");
// afficherListe(leBiparti.input);
// System.out.println("***");
// afficherListe(leBiparti.output);
} else {
// System.out.println("exist "+ i + " "+ j);
ListeSommets liste = new ListeSommets();
liste.add(leSommet);
liste.add(leSommet2);
getBiparti1(leSommet.getSuccesseurs()).input
.ajouterNonRedandante(liste);
// System.out.println(getBiparti(leSommet.getSuccesseurs()).getNom()+
// " -- ");
// afficherListe(getBiparti(leSommet.getSuccesseurs()).input);
}
}
// else System.out.println("hola");
}
}
}
// for (Iterator<Sommet> it = Fenetre.pert.sommets.iterator();
// it.hasNext();){
// Sommet leSommet = it.next();
// System.out.println(leSommet.getNom());
// afficherListe(leSommet.input);
// System.out.println("*****");
// afficherListe(leSommet.output);
// }
} |
7484c6b2-5de3-4a3c-95cb-8a91e9ec22f4 | 0 | public LogFile getErrorLog() {return this.errorLog;} |
28ce1d34-15c1-4ad4-91bf-e7a47cf2fc19 | 3 | @Override
public boolean createCustomer(Customer customer) {
if (doc == null)
return false;
Element currRoot = doc.getRootElement();
Element parrentCusto = currRoot.getChild("customers");
Element newCusto = new Element("customer");
int id = 0;
for (Customer item : getCustomers()) {
if (item.getCustomerID() > id)
id = item.getCustomerID();
}
id++;
newCusto.addContent(new Element("customerID").setText(id + ""));
newCusto.addContent(new Element("name").setText(customer.getName()));
newCusto.addContent(new Element("surename").setText(customer
.getSurname()));
newCusto.addContent(new Element("address").setText(customer
.getAddress()));
parrentCusto.addContent(newCusto);
return this.saveToFile();
} |
d35713df-667d-4d50-b6c2-fa5b86a03321 | 6 | private void jbuttonMostrarAsistenciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbuttonMostrarAsistenciaActionPerformed
String str = String.valueOf(this.autocomboboxAsistencias.getSelectedItem());
if (str == null || str.isEmpty() || str.equals("") || str.equals("null")) {
JOptionPane.showMessageDialog(this, "El campo de nombre no puede estar vacio.");
} else {
if (str.indexOf(",") < 0) {
JOptionPane.showMessageDialog(this, "Cliente no esta en la lista.");
} else {
String idCliente = str.split(",")[1];
int id = Integer.parseInt(idCliente);
asistenteActual = new DataUtils().getClienteDB(id);
if (asistenteActual.getIdCliente() < 1 ) {
JOptionPane.showMessageDialog(this, "No se encontro el cliente.");
} else {
asistenteActual.setListaAsistencias(new DataUtils().obtenerAsistenciasClienteDB(asistenteActual.getIdCliente()));
actualizarAsistenteActual();
}
}
}
}//GEN-LAST:event_jbuttonMostrarAsistenciaActionPerformed |
bad7a3cf-ed85-433d-a9a2-d0fb8009f0ab | 0 | @Before
public void setUp()
throws Exception
{
createInjector( new QuartzModule()
{
@Override
protected void schedule()
{
scheduleJob( TimedTask.class ).updateExistingTrigger();
scheduleJob( TimedTask.class ).updateExistingTrigger();
}
} ).getMembersInjector( RepeatedSchedulingTestCase.class ).injectMembers( this );
} |
e4f1e8ac-9985-4ca2-b6c3-fcf6eabf1bdb | 8 | private void readCAIDAmap() throws Exception {
try {
FileReader fr = new FileReader(this.mapFilenameCAIDA1);
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
while (str != null) {
// if the string does not start with 'D' (direct link) or 'I'
// (indirect link), skip this string
if (!str.startsWith("D") && !str.startsWith("I")) {
str = br.readLine();
continue;
}
// get first AS (or AS set of multihomed ASs)
str = str.substring(str.indexOf("\t") + 1);
String as1_str = str.substring(0, str.indexOf("\t"));
// get second AS (or AS set of multihomed ASs)
str = str.substring(str.indexOf("\t") + 1);
String as2_str = str.substring(0, str.indexOf("\t"));
// prepare arrays for ASs
ArrayList<Integer> as1 = parseASsetCAIDA(as1_str);
ArrayList<Integer> as2 = parseASsetCAIDA(as2_str);
// add all to the graph
for (Integer first : as1) {
for (Integer second : as2) {
// add vertices if not already present
graphAS.addVertex(first);
graphAS.addVertex(second);
// add edge
try {
graphAS.addEdge(first, second);
} catch (Exception e) { // stupid library could throw an
// exception like
// "loops not allowed"
// I will catch them all!
logger.error(
"Error during adding link to the graph. Link will be ignored.",
e);
continue;
}
}
}
// read next line
str = br.readLine();
}
br.close();
} catch (FileNotFoundException e) {
logger.error("Error during reading map file", e);
throw new Exception("Error during reading map file");
} catch (IOException e) {
logger.error("Error during reading map file", e);
throw new Exception("Error during reading map file");
}
} |
36a16887-f88f-480a-9c79-2dd47a7fbcd3 | 2 | public void updatePlayerNames(){
playerCount=0;
for(int i = 0; i < maxPlayers; i++) {
if(players[i] != null) {
playersCurrentlyOn[i] = players[i].playerName;
playerCount++;
}
else {
playersCurrentlyOn[i] = "";
}
}
} |
64866551-4df8-498f-ab79-081b807979ce | 5 | private static void writeDistribution(HashMap<Double, Integer> distribution, LinkedList<String> columns, int numberEntries, String baseFilename) throws IOException
{
//
// Generate name for distribution
//
StringBuffer name = new StringBuffer();
java.util.Collections.sort(columns);
{
boolean first = true;
for(String col : columns) {
if(first) first = false;
else name.append("_");
if(REMOVE_STRING_IN_OUTPUT_FILENAME != null) {
col = col.replaceAll(REMOVE_STRING_IN_OUTPUT_FILENAME, "");
}
name.append(col);
}
}
String filename = baseFilename +" " +name.toString() +".csv";
FileWriter fw = new FileWriter(filename, false);
//
// Write header to file
//
fw.write("value" +SEPARATOR_OUT +"number" +SEPARATOR_OUT +"sum equal or smaller" +SEPARATOR_OUT +"percentage");
fw.write(NEW_LINE);
//
// Write data to file
//
System.out.println("Write statistic to '" +filename +"'");
System.out.println(" with " +distribution.size() +" entries");
System.out.println(" lang " +OUTPUT_LANGUAGE);
NumberFormat numberFormater = NumberFormat.getInstance(OUTPUT_LANGUAGE);
numberFormater.setMaximumFractionDigits(MAX_FRACTION_DIGITS_IN_OUTPUT);
List<Double> values = new ArrayList<Double>(distribution.keySet());
java.util.Collections.sort(values);
Integer numberSum = 0;
for(Double value : values) {
Integer number = distribution.get(value);
numberSum += number;
fw.write(numberFormater.format(value) +SEPARATOR_OUT +numberFormater.format(number) +SEPARATOR_OUT);
fw.write(numberFormater.format(numberSum) +SEPARATOR_OUT +numberFormater.format((Double)(numberSum.doubleValue() / numberEntries)));
fw.write(NEW_LINE);
}
fw.close();
System.out.println(" sum value = " +numberSum +" (expected=" +numberEntries +")");
if(numberSum != numberEntries) {
System.err.println("Sum of values and number of entries does not match.");
}
} |
d8bcaa3e-06e5-4b75-8c8d-1aff1593dc05 | 4 | public String gridToString () {
char[][] result = {{'x', 'x', 'x', 'x', 'x', 'x'},
{'x', 'x', 'x', 'x', 'x', 'x'},
{'x', 'x', 'x', 'x', 'x', 'x'},
{'x', 'x', 'x', 'x', 'x', 'x'},
{'x', 'x', 'x', 'x', 'x', 'x'},
{'x', 'x', 'x', 'x', 'x', 'x'}};
for(char c : this.vehicles.keySet()){
Vehicle current = vehicles.get(c);
//System.out.println(c);
ArrayList<Coordinate> coveredPositions = current.getCoveredCoordinates();
//System.out.println("Position x: " + current.getPosition().x + ", Position y: " + current.getPosition().y);
//System.out.println("Orientation: " + current.horizontal);
for(int i = 0; i < coveredPositions.size(); i++){
Coordinate currentCoordinate = coveredPositions.get(i);
//System.out.println("x: " + currentCoordinate.x + ", y: " + currentCoordinate.y);
result[currentCoordinate.y][currentCoordinate.x] = c;
}
}
String resultString = "";
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
resultString = resultString + result[i][j];
//System.out.println(resultString);
}
}
return resultString;
} |
05d54c44-e66e-47ab-9a2f-1b8853f81cac | 6 | @Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
for (int i = 0; i < COMPONENTS.getLength(); i++) {
if (e.getActionCommand().equals(COMPONENTS.get(i)))
panel.createComponent(COMPONENTS.get(i));
}
if (e.getActionCommand().equals(CHECK))
listener.actionPerformed(new ActionEvent(this, CHECKC, ""));
else if(e.getActionCommand().equals(ABOUT))
crearVentanaAcerca();
else if(e.getActionCommand().equals(TABLA))
generateTable();
else if (e.getActionCommand().equals(THEME))
panel.changeTheme();
//else if (e.getActionCommand().equals(SAVE))
} |
88540f30-d449-4c50-a4f5-728f2e82031e | 9 | public static void displayPrescription(PatientProfilePage profileP){
profileP.getPrescriptionList().setText("Unpaid Prescription List: \n");
BigDecimal tax = new BigDecimal(.07);
totalPrescriptionCost=BigDecimal.ZERO;
clearTable(profileP);
Patient p = Gui.getCurrentPatient();
BigDecimal coPay=p.getCoPay().divide(new BigDecimal(100));
int pid=p.getPid();
ArrayList<Integer> prescID=new ArrayList<Integer>();
currentActive="";
prescID=DatabaseProcess.getPrescription(pid);
ArrayList<Integer> paid=new ArrayList<Integer>();
ArrayList<Integer> expired=new ArrayList<Integer>();
int j=0;
boolean flag=true;
for(int i=0;i<prescID.size();i++){
Prescription bean =new Prescription();
bean.setPrescriptionID(prescID.get(i));
bean=(Prescription)DatabaseProcess.getRow(bean);
Drug active=new Drug();
active.setDrugId(bean.getDid());
active=(Drug)DatabaseProcess.getRow(active);
if(Gui.getCurrentPatient().getPid()==bean.getPid()&&bean.getDid()==active.getDrugId())
currentActive+=active.getDrugName()+" ";
if(!bean.getPayStatus()){
profileP.getPrescriptionHistory().setValueAt(prescID.get(i),j,0);
profileP.getPrescriptionHistory().setValueAt(bean.getQuantity(),j,2);
profileP.getPrescriptionHistory().setValueAt(bean.getDose(),j,3);
profileP.getPrescriptionHistory().setValueAt(bean.getThisDay().toString(),j,4);
profileP.getPrescriptionHistory().setValueAt(bean.getRefill(),j,6);
Drug d=new Drug();
d.setDrugId(bean.getDid());
d=(Drug)DatabaseProcess.getRow(d);
profileP.getPrescriptionHistory().setValueAt(d.getDrugName(),j,1);
profileP.getPrescriptionHistory().setValueAt(bean.getStartDate().toString(), j, 5);
profileP.getPrescriptionHistory().setValueAt(bean.getPayStatus(),j,7);j++;
BigDecimal x = HelperMethods.multiplyCost(bean.getQuantity(),d.getPrice());
if(flag){
totalPrescriptionCost=BigDecimal.ZERO;
flag=false;
}
if(totalPrescriptionCost!=null)
totalPrescriptionCost = HelperMethods.totalCost(x, totalPrescriptionCost);
String s = bean.getPrescriptionID()+": "+d.getDrugName()+" quantity: "+bean.getQuantity()
+" $"+x+"\n";
String a="";
a+=s;
profileP.getPrescriptionList().append(a);
}
else if(bean.getRefill()!=0)
paid.add(bean.getPrescriptionID());
else
expired.add(bean.getPrescriptionID());
}
profileP.getCoPayAmt().setText("%"+coPay);
totalPrescriptionCost=HelperMethods.patientCost(coPay,totalPrescriptionCost);
profileP.getSubAmt().setText("$"+HelperMethods.currencyFormat(totalPrescriptionCost));
profileP.getTaxAmt().setText("%7.00");
totalPrescriptionCost=HelperMethods.patientCost(HelperMethods.addOne(tax), totalPrescriptionCost);
profileP.getTotalAmt().setText(HelperMethods.currencyFormat(totalPrescriptionCost));
for(int i=0;i<paid.size();i++){
Prescription paidBean =new Prescription();
paidBean.setPrescriptionID(paid.get(i));
paidBean=(Prescription)DatabaseProcess.getRow(paidBean);
profileP.getPrescriptionHistory().setValueAt(paid.get(i),j,0);
profileP.getPrescriptionHistory().setValueAt(paidBean.getQuantity(),j,2);
profileP.getPrescriptionHistory().setValueAt(paidBean.getDose(),j,3);
profileP.getPrescriptionHistory().setValueAt(paidBean.getThisDay().toString(),j,4);
profileP.getPrescriptionHistory().setValueAt(paidBean.getRefill(),j,6);
Drug d=new Drug();
d.setDrugId(paidBean.getDid());
d=(Drug)DatabaseProcess.getRow(d);
profileP.getPrescriptionHistory().setValueAt(d.getDrugName(),j,1);
profileP.getPrescriptionHistory().setValueAt(paidBean.getStartDate().toString(), j, 5);
profileP.getPrescriptionHistory().setValueAt(paidBean.getPayStatus(),j,7);j++;}
for(int i=0;i<expired.size();i++){
Prescription expiredBean =new Prescription();
expiredBean.setPrescriptionID(expired.get(i));
expiredBean=(Prescription)DatabaseProcess.getRow(expiredBean);
profileP.getPrescriptionHistory().setValueAt(expired.get(i),j,0);
profileP.getPrescriptionHistory().setValueAt(expiredBean.getQuantity(),j,2);
profileP.getPrescriptionHistory().setValueAt(expiredBean.getDose(),j,3);
profileP.getPrescriptionHistory().setValueAt(expiredBean.getThisDay().toString(),j,4);
profileP.getPrescriptionHistory().setValueAt(expiredBean.getRefill(),j,6);
Drug d=new Drug();
d.setDrugId(expiredBean.getDid());
d=(Drug)DatabaseProcess.getRow(d);
profileP.getPrescriptionHistory().setValueAt(d.getDrugName(),j,1);
profileP.getPrescriptionHistory().setValueAt(expiredBean.getStartDate().toString(), j, 5);
profileP.getPrescriptionHistory().setValueAt(expiredBean.getPayStatus(),j,7);j++;}
profileP.getPrescriptionHistory().repaint();
} |
c55834a9-3a02-4718-85f5-c560f67c8dcd | 6 | private void initStartAndEndFromHadoopConf()
throws StartOrEndNotSetException {
String startPointForElementStr = this.conf.get(SystemConf
.getStartPointForConfSetString());
String endPointForElementStr = this.conf.get(SystemConf
.getEndPointForConfSetString());
if (null == startPointForElementStr
|| startPointForElementStr.equals("")) {
throw new StartOrEndNotSetException("start point not set");
}
if (null == endPointForElementStr || endPointForElementStr.equals("")) {
throw new StartOrEndNotSetException("end point not set");
}
startPointForElement = new ArrayList<Long>();
endPointForElement = new ArrayList<Long>();
String tmp[] = startPointForElementStr.split(SystemConf
.getHadoopConfDelimiter());
for (String str : tmp) {
startPointForElement.add(Long.valueOf(str));
}
tmp = endPointForElementStr.split(SystemConf.getHadoopConfDelimiter());
for (String str : tmp) {
endPointForElement.add(Long.valueOf(str));
}
} |
c6eb1d6c-7db4-4ac9-ac10-413284621f03 | 3 | public Transition transitionAtPoint(Point point) {
if (!valid)
refreshArrowMap();
Set arrows = arrowToTransitionMap.keySet();
Iterator it = arrows.iterator();
while (it.hasNext()) {
CurvedArrow arrow = (CurvedArrow) it.next();
if (arrow.isNear(point, 2))
return (Transition) arrowToTransitionMap.get(arrow);
}
return null;
} |
8ce2fd5e-4f8e-4102-b36b-22edae2e547d | 6 | @EventHandler
public void IronGolemWither(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.getIronGolemConfig().getDouble("IronGolem.Wither.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getIronGolemConfig().getBoolean("IronGolem.Wither.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, plugin.getIronGolemConfig().getInt("IronGolem.Wither.Time"), plugin.getIronGolemConfig().getInt("IronGolem.Wither.Power")));
}
} |
6ac40d57-1c65-425e-8a0e-f1fcd26d17d7 | 2 | @Override
public void fire() {
if(enabled) {
MobileNode mn = (MobileNode) this.node;
// Assemble an SMS and send it to the current anteanna
SmsMessage msg = new SmsMessage(mn.getNextSeqID(), destination, this.node, text, this);
Antenna a = mn.getCurrentAntenna();
if(a != null) {
this.node.send(msg, a);
}
this.startRelative(8, this.node); // TODO: time?
}
} |
bf9989f6-69f6-4824-98a7-b3c1dd8d90c4 | 1 | public void mousePressed(MouseEvent e) {
GameAction gameAction = getMouseButtonAction(e);
if (gameAction != null) {
gameAction.press();
}
} |
5853ff7f-8058-421d-8b4e-b2c9e8748726 | 1 | public void mainAction()
{
ship s = getShipToRecieveAction();
if(getTurnDecay() == 4)
{
s.recievesDamage(-3.00);
modifyTurnDecay(-1);
}
else
{
s.recievesDamage(-1.00);
modifyTurnDecay(-1);
}
} |
1d4ab40c-a8ea-449a-8d49-5045bb6e5536 | 3 | public boolean isNameChange()
{
return !isDeletion() && !isCreation() && toName != null && !toName.equals(fromName);
} |
6b6165b8-de84-4433-a561-e04c9fac569a | 9 | @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
Logger.getLogger(UserHandler.class.getName()).log(Level.FINER,
String.format("Setting %s in new user to %s.", qName, content.toString()));
if (qName.equalsIgnoreCase(USERNAME)) {
user.setUsername(content.toString());
}
if (qName.equalsIgnoreCase(PASSWORD)) {
user.setPassword(content.toString());
}
if (qName.equalsIgnoreCase(FIRSTNAME)) {
user.setFirstName(content.toString());
}
if (qName.equalsIgnoreCase(LASTNAME)) {
user.setLastName(content.toString());
}
if (qName.equalsIgnoreCase(EMAIL)) {
user.setEmail(content.toString());
}
if (qName.equalsIgnoreCase(INDEXEDRECORDS)) {
user.setIndexedRecords(Integer.parseInt(content.toString()));
}
if (qName.equalsIgnoreCase(IndexerHandler.USER)) {
try {
database.startTransaction();
database.insert(user);
database.endTransaction(true);
}
catch (Database.DatabaseException | Database.InsertFailedException ex) {
try {
database.endTransaction(false);
} catch (Database.DatabaseException ex1) {
Logger.getLogger(FieldHandler.class.getName()).log(Level.SEVERE, null, ex1);
}
finally {
throw new SAXException(ex.getMessage());
}
}
reader.setContentHandler(parent);
}
} |
5e8d7491-0efa-451e-af1c-c85f49b2abeb | 9 | public String GetPageContent(String url) {
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = (HttpURLConnection) obj.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// default is GET
try {
conn.setRequestMethod("GET");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
/*int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);*/
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String inputLine;
StringBuffer response = new StringBuffer();
try {
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
} |
9ffeb55a-42d9-481f-81d1-2716927c1715 | 2 | @Override
public Component getListCellRendererComponent(JList<? extends ICPBrasilSignature> jlist, ICPBrasilSignature e, int i, boolean bln, boolean bln1) {
ICPBrasilCertificate cert = e.getSignerCertificate();
String text = null;
if(cert != null){
text = cert.getSubjectSimpleName() +" "+cert.getICPBrasilVersion()+" " + dateFormat.format(e.getSignedTime());
}
else{
text = e.getICPVersion();
}
JLabel label = (JLabel) cellRenderer.getListCellRendererComponent(jlist, text, i, bln, bln1);
return label;
} |
715f8e2d-2387-4326-a0af-c4d561265360 | 3 | @Test
public void testIterator() throws Exception {
Object domainNode1 = new Object();
Object domainNode2 = new Object();
Object domainNode3 = new Object();
InternalNode<Object, Object> node1 = (InternalNode<Object, Object>) Mockito.mock(InternalNode.class);
Mockito.when(node1.getWrappedNode()).thenReturn(domainNode1);
InternalNode<Object, Object> node2 = (InternalNode<Object, Object>) Mockito.mock(InternalNode.class);
Mockito.when(node2.getWrappedNode()).thenReturn(domainNode2);
InternalNode<Object, Object> node3 = (InternalNode<Object, Object>) Mockito.mock(InternalNode.class);
Mockito.when(node3.getWrappedNode()).thenReturn(domainNode3);
List<Object> domainNodes = Arrays.asList(domainNode1, domainNode2, domainNode3);
BasicPredGraph<Object, Object> basicPredGraph1 = new BasicPredGraph<Object, Object>(node1, 42);
BasicPredGraph<Object, Object> basicPredGraph2 = new BasicPredGraph<Object, Object>(node2, 43);
BasicPredGraph<Object, Object> basicPredGraph3 = new BasicPredGraph<Object, Object>(node3, 44);
basicPredGraph1.setPredecessor(basicPredGraph2).setPredecessor(basicPredGraph3);
Iterator<InternalNode<Object, Object>> it = basicPredGraph1.iterator();
int i = 0;
for (; it.hasNext(); i++) {
Object obj = it.next().getWrappedNode();
Assert.assertEquals(domainNodes.get(i), obj);
}
Assert.assertEquals(i, domainNodes.size());
try {
it.next();
Assert.fail("Expected exception not thrown.");
} catch (NoSuchElementException e) {
; // do nothing
}
try {
it.remove();
Assert.fail("Expected exception not thrown.");
} catch (UnsupportedOperationException e) {
; // do nothing
}
} |
6f97f865-4148-41eb-9892-c9814f018edb | 7 | public LinkedList<LinkedList<Vertex>> _toVertexArray(boolean SHOULD_IGNORE_START_END_NODES){
// For the main store of vertices
LinkedList<LinkedList<Vertex>> mainResult = new LinkedList<LinkedList<Vertex>>();
LinkedList<Vertex> newResult = new LinkedList<Vertex>();
LinkedList<Vertex> currentLL = new LinkedList<Vertex>();
num+= 10;
boolean inSquares = false;
// Iterate through each node in the trace
for(Vertex v: nodes){
// Check if the node is actually a trace trapped in a vertex body
if(v.isTrace){ // It is, so lets process it as a trace.
// In square is used to group traces next to each other, i.e. <a, [<b,c>,<d,e>],f >
// for the group in the square <b,c>,<d,e>, the group should be OCP'd together (to get the result:
// <b,c,d,e>, <b,d,c,e>, <b,d,e,c>, <d,b,c,e> ... etc.
if(!inSquares){
inSquares = true;
}
Trace t = (Trace)v; // We expand the this trace into a list of lists of elements.
LinkedList<LinkedList<Vertex>> newvArray = t._toVertexArray(IGNORE_START_END_NODES_IN_TRACE) ;
// Result should be a list of possible alternatives.
// [<s, a,b, e>,<s, c,d, e>,<s, d,f, e>]
for(LinkedList<Vertex> ele : newvArray){
//a.e.println("Adding " + _num + " :: " + ele);
currentLL.addAll(ele);
}
//currentLL.addAll(newvArray);
}else{
if(inSquares){
inSquares = false;
// Process LL's
// a.e.print("1--");
LinkedList<Vertex> returnedResults = _processGroupsOfParallelNodes(currentLL);
newResult.addAll(returnedResults); // .substring(0, currentString.length()/2));
}
newResult.add(v);
}
if(v == nodes.getLast()){
if(inSquares){
inSquares = false;
// a.e.print("2--");
LinkedList<Vertex> returnedResults = _processGroupsOfParallelNodes(currentLL);
newResult.addAll(returnedResults); // .substring(0, currentString.length()/2));
}
}
}
mainResult.add(newResult);
return mainResult;
} |
589763ec-a20e-4e8a-bd70-9b294a8712c5 | 5 | @Override
public int hashCode() {
int result = pcaPosId != null ? pcaPosId.hashCode() : 0;
result = 31 * result + (pcaGrupo != null ? pcaGrupo.hashCode() : 0);
result = 31 * result + (pcaSubgru != null ? pcaSubgru.hashCode() : 0);
result = 31 * result + (pcaGenerico != null ? pcaGenerico.hashCode() : 0);
result = 31 * result + (pcaSecuen != null ? pcaSecuen.hashCode() : 0);
return result;
} |
b3262301-e4e5-44a2-a718-2f26d8323738 | 2 | public static CommandeFournisseur SelectCommandeFournisseurById(int id) throws SQLException {
String query = "";
CommandeFournisseur Commande = new CommandeFournisseur();
ResultSet resultat;
try {
query = "SELECT * from COMMANDE_FOURNISSEUR where ID_CMDFOUR =? ";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1, id);
resultat = pStatement.executeQuery();
while (resultat.next()) {
Commande = new CommandeFournisseur(resultat.getInt("ID_CMDFOUR"), resultat.getInt("ID_UTILISATEUR"), resultat.getString("COMFOUREF"), resultat.getDate("COMFOUDATE"), resultat.getFloat("COMFOUREMISE"));
}
} catch (SQLException ex) {
Logger.getLogger(RequetesCommandeFournisseur.class.getName()).log(Level.SEVERE, null, ex);
}
return Commande;
} |
ffb11e5c-decb-4c52-8abc-2262fa6facbe | 0 | public static double getPrice(CallInfo ci, IRule rule){
return rule.execute(ci.getStart(), ci.getEnd());
} |
d6f0b970-f199-4637-97a5-2b1ba9959174 | 7 | private void checkForKeyPress() {
if (defaultKeyMapping.takeScreenShot.isPressed()) {
File file = new File("screenshots");
if (!file.exists()) {
file.mkdir();
}
String fileName = System.currentTimeMillis() + ".png";
File screenshot = new File("screenshots" + File.separator + fileName);
GraphicUtils.takeScreenshot("screenshots" + File.separator + fileName);
screenShotAnimations.add(new ScreenShotAnimation("screenshots" + File.separator + fileName));
log("Screenshot " + fileName + " taken.");
}
if (defaultKeyMapping.toggleConsole.isPressed()) {
Config.toggleConsole();
}
if (defaultKeyMapping.toggleDebug.isPressed()) {
Config.toggleDebugMode();
}
if (defaultKeyMapping.toggleFullScreen.isPressed()) {
try {
log("Setting fullscreen");
Display.setFullscreen(!Display.isFullscreen());
DisplayMode previousDisplayMode = Display.getDisplayMode();
log("full screen?" +previousDisplayMode.isFullscreenCapable());
//resize(new DisplayMode(.getDi));
} catch (LWJGLException e) {
e.printStackTrace();
}
}
if (defaultKeyMapping.exit.isPressed()) {
end();
}
} |
6bb7f77d-6df8-422f-bfc9-05a5d3ed2414 | 3 | @Override
public boolean checkGuess(String question, String quess) {
for (WordsPair pair : newWordList) {
if (pair.getEngWord() == question) {
if (pair.getDkWord() == quess) {
return true;
}
return false;
}
}
return false;
} |
34db3709-b81f-407c-9a83-8719665981a2 | 4 | private void updateStatus() {
if (player.getY() >= 2)
if (keys[KeyEvent.VK_UP]) {
player.move(false);
}
if (player.getY() <= (height - 50))
if (keys[KeyEvent.VK_DOWN]) {
player.move(true);
}
} |
0f5718fa-7e34-4a00-bb18-2f6fda199dce | 4 | private void checkIgnoredFileForMarkup(File file) throws IOException {
if (!file.exists()) {
log.warning(String.format("Excluded file %s doesn't exist", file));
return;
}
try (BufferedReader is = new BufferedReader(new FileReader(file))) {
String line = null;
while ((line = is.readLine()) != null) {
if (line.contains("//-") ||
line.contains("//+")) {
log.warning("Excluded file " + file + " appears to contain markup");
return; // Only natter once per file
}
}
}
} |
dd514486-1386-4771-bfaa-5550107444c2 | 2 | @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) // event has MONITOR priority and will be skipped if it has been cancelled before
public void onPlayerJoin(PlayerJoinEvent event)
{
final PlayerJoinEvent pjEvent = event;
// Check if player has unfulfilled assignments to pick up
final int assRdyForPickup = plugin.getCompletedAssignmentsFromDB(event.getPlayer().getName());
if(assRdyForPickup > 0)
{
if(assRdyForPickup == 1) // there are completed assignments for this player to pick up
{
// DELAYED TASK (only called once)
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
pjEvent.getPlayer().sendMessage(ChatColor.GREEN + "Du hast noch einen erfuellten Auftrag. Du kannst am Schild deine Waren abholen.");
pjEvent.getPlayer().sendMessage(ChatColor.GREEN + "Mit " + ChatColor.WHITE + "/ass list" + ChatColor.GREEN + " kannst du deine Auftraege ansehen.");
}
}, 200L);
}
else
{
// DELAYED TASK (only called once)
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
pjEvent.getPlayer().sendMessage(ChatColor.GREEN + "Du hast noch " + Integer.toString(assRdyForPickup) + " erfuellte Auftraege. Bitte hole deine Waren ab.");
pjEvent.getPlayer().sendMessage(ChatColor.GREEN + "Mit " + ChatColor.WHITE + "/ass list" + ChatColor.GREEN + " kannst du deine Auftraege ansehen.");
}
}, 200L);
}
}
// --------------------------------------------
} |
12d2cccb-4b56-4603-bc4a-47833410c859 | 1 | @Test
public void testPlayerCapturesTwoFlagsAndOnePlayerBoxedIn() throws InvalidActionException {
final GameEnded gameEnded = new GameEnded();
game.addEventListener(new Listener() {
@Override
public void handleEvent(Event event) {
if(event.getType() == EventType.END_GAME)
gameEnded.setToTrue();
}
}, EventType.END_GAME);
// Player 1 moves 4 up
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
// Player 2 moves 4 down
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
// Player 3 moves 4 right
game.moveAction(Direction.RIGHT);
game.moveAction(Direction.RIGHT);
game.moveAction(Direction.RIGHT);
game.moveAction(Direction.RIGHT);
// Player 4 moves 4 up
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
// Player 1 moves 4 up
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
// Player 2 boxes in Player 4
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 3 moves 1 right
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 1 picks up flag of Player 3
game.moveAction(Direction.UP);
game.pickUpAction(0);
game.moveAction(Direction.RIGHTDOWN);
game.moveAction(Direction.DOWN);
// Player 2 moves 1 right
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 3 moves 1 right
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 1 moves 4 down
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
// Player 2 moves 1 up
game.moveAction(Direction.UP);
game.endTurnAction();
// Player 3 moves 1 down
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 1 captures flag and teleports
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.RIGHTUP);
// Player 2 moves 1 up
game.moveAction(Direction.UP);
game.endTurnAction();
// Player 3 moves 1 left
game.moveAction(Direction.LEFT);
game.endTurnAction();
// Player 1 moves 4 right up
game.moveAction(Direction.RIGHTUP);
game.moveAction(Direction.RIGHTUP);
game.moveAction(Direction.RIGHTUP);
game.moveAction(Direction.RIGHTUP);
// Player 2 moves 1 left down
game.moveAction(Direction.LEFTDOWN);
game.endTurnAction();
// Player 3 moves 1 left
game.moveAction(Direction.LEFT);
game.endTurnAction();
// Player 1 picks up flag of Player 2 and moves 2 left down
game.moveAction(Direction.UP);
game.pickUpAction(0);
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.LEFTDOWN);
// Player 2 moves 1 down
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 3 moves 1 up
game.moveAction(Direction.UP);
game.endTurnAction();
// Player 1 moves 4 left down
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.LEFTDOWN);
// Player 2 moves 1 down
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 3 moves 1 up
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 1 captures flag
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.LEFT);
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.DOWN);
assertTrue(gameEnded.isTrue);
} |
043c61bd-7c0a-4202-ad0a-f8ef3ae5f47d | 1 | @Override
public void replica(Integer id, Box obj) throws RemoteException, NenhumServidorDisponivelException
{
h.put(id, obj);
try
{
System.out.printf("Received object %s from %s\n", obj.toString(), RemoteServer.getClientHost());
}
catch (ServerNotActiveException e)
{
e.printStackTrace();
}
} |
5ad07dbf-60e5-4192-ac0c-b615eb48a5ea | 8 | public void movePointerTransition(Node nodo) {
TranslateTransition translateTransition = new TranslateTransition(Duration.millis(400), pointer);
translateTransition.setFromY(pointer.getTranslateY());
if ("newEventButton".equals(nodo.getId())) {
if (pointer.getTranslateY() > 100) {
if (pointer.getTranslateY() > 300) {
translateTransition.setToY(pointer.getTranslateY() - 360);
} else {
translateTransition.setToY(pointer.getTranslateY() - 180);
}
}
} else {
if ("loadTemplateButton".equals(nodo.getId())) {
if (pointer.getTranslateY() != 180) {
if (pointer.getTranslateY() > 180) {
translateTransition.setToY(pointer.getTranslateY() - 180);
} else {
translateTransition.setToY(pointer.getTranslateY() + 180);
}
}
} else {
if (pointer.getTranslateY() != 360) {
if (pointer.getTranslateY() < 180) {
translateTransition.setToY(pointer.getTranslateY() + 360);
} else {
translateTransition.setToY(pointer.getTranslateY() + 180);
}
}
}
}
translateTransition.setCycleCount(1);
translateTransition.setAutoReverse(false);
translateTransition.play();
} |
cff6cdd1-a94f-4e58-a00b-508bde28ad99 | 8 | private void deleteCategorie() {
int id_categorieTmp = -1;
System.out.println("ID :");
id_categorieTmp = Integer.parseInt(sc.nextLine());
CategorieDB.setConnection(con);
CategorieDB cat = null;
cat = new CategorieDB(id_categorieTmp);
try {
cat.read();
} catch (Exception ex) {
Logger.getLogger(Controler_antho.class.getName()).log(Level.SEVERE, null, ex);
}
if (cat.getId_categorie() != -1) {//client trouvé
String suppression = "";
System.out.println("Object trouvé :");
System.out.println(cat.toString());
System.out.println("Supprimer cet object ?");
do {
System.out.println("Choix(oui/non) :");
suppression = sc.nextLine();
if (suppression.equals("oui")) {
try {
cat.delete();
System.out.println("Suppression réussis");
} catch (Exception ex) {
Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (suppression.equals("non")) {
System.out.println("Annulation de la suppression");
}
} while (!suppression.equals("oui") && !suppression.equals("non"));
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Controler_antho.class.getName()).log(Level.SEVERE, null, ex);
}
} |
cfc109d0-70f6-4258-998b-d578b2180eb1 | 1 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String address=request.getParameter("address");
String lname=request.getParameter("studentlastname");
String userid=request.getParameter("studentfirstname");
HttpSession session = request.getSession();
StudentBean personInSession = (StudentBean)session.getAttribute("person");
String type="STUDENT";
PersonBean person = new PersonBean();
person.setAddress(address);
person.setLname(lname);
person.setType(type);
person.setFname(userid);
person.setId(personInSession.getStudentId());
PersonDao.updatePerson(person);
session.setAttribute("username", person.getFname());
StudentBean bean = (StudentBean)session.getAttribute("person");
bean.setAddress(address);
bean.setLname(lname);
bean.setType(type);
bean.setFname(userid);
bean.setId(personInSession.getStudentId());
session.setAttribute("person", bean);
RequestDispatcher rd=request.getRequestDispatcher("thankyouupdate.jsp");
rd.forward(request,response);
}catch(Exception e){
e.printStackTrace();
}
} |
1d89ab4e-4679-4a33-a439-22cc5a9af1fd | 5 | private void restart() {
Scanner sc = new Scanner(System.in);
System.out.println("Play again? (Y or N)");
String res = sc.next();
switch(res.toUpperCase().charAt(0)) {
case 'Y' :
for(int i =0;i<this.player.length;i++) {
Game.clearConsole();
System.out.println("Captain " +player[i].name+", it is time to deploy your fleet! Press enter to continue\n");
if(player[1] instanceof ArtificialPlayer && i == 1) {
player[1] = new ArtificialPlayer();
}
else
player[i] = new Player(player[i].name);
player[i].addFleet();
}
player[0].opponentGrid=player[1].myGrid;
player[1].opponentGrid=player[0].myGrid;
this.playGame();
break;
case 'N':
default:
this.clearConsole();
this.showMenu();
}
} |
b1f7c3de-57a4-4766-ae3a-d034eaa0628a | 6 | protected void receiveData(IRemoteCallObject rco) {
if (rco == null) throw new IllegalArgumentException("aRemoteCallObject is null");
try {
long callId = rco.getCallObjectId(); //..call id
IRemoteCallObjectMetaData meta = rco.getMetaDataObject(); //..meta data
IRemoteCallObjectData data = rco.getDataObject(); //..data
RemoteCallObjectType rcoType = meta.getCallObjectType(); //..receive type
//..
if (rcoType == RemoteCallObjectType.Message) {
//..receive message, forward handler and don't expect result
receiveMessageData(meta, data);
}
else if (rcoType == RemoteCallObjectType.Query) {
//..request to execute some method on this side
receiveQueryData(meta, data, callId);
}
else if (rcoType == RemoteCallObjectType.Respond) {
//..receive the result of the call, put it passed without errors
IRemoteCallObject obj = setResponse(callId, rco, true, false);
synchronized (obj) {
obj.notifyAll(); //..notify waiting thread in call method
}
}
else if (rcoType == RemoteCallObjectType.RespondError) {
//..receive the result of the call, put it passed with errors
IRemoteCallObject obj = setResponse(callId, rco, true, true);
synchronized (obj) {
obj.notifyAll(); //..notify waiting thread in call method
}
}
Thread.yield();
}
catch(Exception exc) {
catchException(this, new Exception("receiveData: " + exc.getMessage()));
}
} |
bd26f0b5-0c81-4aac-aad9-dddc49c63cd8 | 0 | protected Automaton createEmptyAutomaton(Document document) {
return new PushdownAutomaton();
} |
b37da831-f6ee-48dd-b200-b12635d69515 | 5 | public int maxArea(int[] height) {
int l = height.length;
if (l<2){
return 0;
}
int front = 0;
int end = l-1;
int result = 0;
while (front<end){
int value = (height[front]<height[end]?height[front]:height[end])*(end-front);
if (value >result){
result = value;
}
if(height[front]<height[end]){
front++;
}
else{
end--;
}
}
return result;
} |
f05b684e-e70f-4cd5-883a-95a0257ee7ce | 7 | public static void startTest(JFrame parent, List<String> algnames, int min, int max, int step, int repeat) {
ProgressDialog pd = new ProgressDialog(parent, false);
pd.setVisible(true);
pd.println("Testing started.");
Thread t = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
try {
int totalSize = 0;
for (int i = min; i <= max; i += min != max ? step : 1) {
for (int j = 0; j < repeat; j++) {
totalSize += i;
pd.print("Generating temporary file (" + i + " MB)... ");
long starttime = System.currentTimeMillis();
FileGenerator fg = new FileGenerator();
fg.generateNewFile(i);
files.add(fg);
long totaltime = System.currentTimeMillis() - starttime;
pd.println("\tDone in " + totaltime + " ms");
}
}
List<HashAlgoritm> algs = new ArrayList<>(algnames.size());
algnames.stream().forEach((algname) -> {
algs.add(HashAlgoritms.getInstance().getAlgoritm(algname));
});
ChartMaker chart = new ChartMaker();
for (HashAlgoritm alg : algs) {
pd.println("Start hashing with algorithm: '" + alg.getName() + "'");
Collection<Number> time = new ArrayList<>(files.size());
Collection<Number> size = new ArrayList<>(files.size());
for (FileGenerator f : files) {
pd.print("\tHashing " + f.getFileLength() / (1024 * 1024) + " MB ...");
byte[] b = new byte[(int) f.getFileLength()];
f.getInputStream().read(b);
long starttime = System.currentTimeMillis();
alg.update(b);
alg.digest();
long totaltime = System.currentTimeMillis() - starttime;
alg.reset();
pd.println("\t\tDone in " + totaltime + " ms");
time.add(totaltime);
size.add(f.getFileLength() / (1024 * 1024));
}
chart.addSeries(alg.getName(), size, time);
pd.println("End hashing with algorithm: '" + alg.getName() + "'");
}
pd.print("Deleting temporary files (" + totalSize + " MB total)... ");
deleteAllTempFiles();
pd.println("\tDone!");
pd.println("Test executed normaly.");
pd.setOkEnabled(true);
chart.display();
} catch (Exception ex) {
pd.println("\t\t\tFailed!");
pd.println("\t" + ex.getMessage());
pd.print("Deleting temporary files ... ");
deleteAllTempFiles();
pd.println("\tDone!");
pd.println("Test executed abnormaly.");
pd.setOkEnabled(true);
ex.printStackTrace();
return;
}
files.clear();
});
t.start();
} |
59c7d2b3-f74c-469b-8fc1-9ad84813647a | 7 | public void shuffle(int deck){
//Pretty much complete, could be more efficient
ArrayList<Integer> shuffler = new ArrayList<Integer>();
int num;
while(shuffler.size()<decksize){
num = (int)(Math.random()*(double)(decksize));
boolean inYet = false;
for(int i = 0; i < shuffler.size();i++){
if(num == shuffler.get(i)){
inYet = true;
}
}
if(!inYet){
shuffler.add(num);
}
}
ArrayList<Card> tempArray = new ArrayList<Card>();
if(deck == 1){
for(int i = 0; i < decksize; i++){
tempArray.add(Deck1.get(shuffler.get(i)));
}
Deck1 = tempArray;
}else{
for(int i = 0; i < decksize; i++){
tempArray.add(Deck2.get(shuffler.get(i)));
}
Deck2 = tempArray;
}
} |
24cf6fc7-254a-4016-a2a4-7518afa259f7 | 8 | @Override
public void import2Vcs() {
try {
SvnOperationFactory svnOp = new SvnOperationFactory();
ISVNAuthenticationManager authManager = new BasicAuthenticationManager(configEntry.getVcsUser(), configEntry.getVcsPass());
svnOp.setAuthenticationManager(authManager);
// get repository information
SvnGetInfo infoCmd = svnOp.createGetInfo();
infoCmd.setSingleTarget(SvnTarget.fromURL(SVNURL.parseURIEncoded(configEntry.getVcsUrl())));
SvnInfo repoInfo = infoCmd.run();
// if remote repository is not empty, and local working copy directory is empty, checkout remote repository
if (repoInfo.getRevision() > 0L && repoDir.listFiles().length == 0) {
SvnCheckout chk = svnOp.createCheckout();
chk.setSource(SvnTarget.fromURL(SVNURL.parseURIEncoded(configEntry.getVcsUrl())));
chk.setSingleTarget(SvnTarget.fromFile(repoDir));
chk.run();
}
List<File> newFiles = new ArrayList<>(), delFiles = new ArrayList<>();
if (merge(newFiles, delFiles)) {
// if first export of database, import to remote repository and checkout to create local working copy
SvnImport imp = svnOp.createImport();
imp.setSource(repoDir);
imp.setSingleTarget(SvnTarget.fromURL(SVNURL.parseURIEncoded(configEntry.getVcsUrl())));
imp.run();
FileUtils.cleanDirectory(repoDir);
SvnCheckout chk = svnOp.createCheckout();
chk.setSource(SvnTarget.fromURL(SVNURL.parseURIEncoded(configEntry.getVcsUrl())));
chk.setSingleTarget(SvnTarget.fromFile(repoDir));
chk.run();
} else {
// if local working copy exists, commit changes to remote repository
if (newFiles.size() > 0) {
SvnScheduleForAddition add = svnOp.createScheduleForAddition();
add.setAddParents(true);
for (File file : newFiles) {
add.addTarget(SvnTarget.fromFile(file));
}
add.run();
}
if (delFiles.size() > 0) {
SvnScheduleForRemoval del = svnOp.createScheduleForRemoval();
for (File file : delFiles) {
del.addTarget(SvnTarget.fromFile(file));
}
del.run();
}
SvnCommit commit = svnOp.createCommit();
commit.setSingleTarget(SvnTarget.fromFile(repoDir));
commit.setDepth(SVNDepth.INFINITY);
commit.run();
}
} catch (SVNException | IOException ex) {
throw new AssertionError("import2Vcs", ex);
}
} |
5b83de24-9342-4b56-9448-80818f8b0ce3 | 8 | public List<List<String>> checkCycle() {
List<String> erdRel = new ArrayList<String>();
erdRel.addAll(relationshipTypes.keySet());
for (int i = 0; i < erdRel.size() - 1; i++) {
String s = erdRel.get(i);
for (int j = i + 1; j < erdRel.size(); j++) {
String curr = erdRel.get(j);
List<String> cycleToBeSplit = isMatch(
relationshipTypes.get(s).getLinks(), relationshipTypes
.get(curr).getLinks());
if (cycleToBeSplit != null) {
boolean dependsOnRoot = true;
String doNotSplit = null;
for (int z = 0; z < cycleToBeSplit.size(); z++) {
// if there is one entity linked to other relationships,
// split all other entity but keep this one
if (entityTypes.get(cycleToBeSplit.get(z)).getLinks().size() > 2) {
doNotSplit = cycleToBeSplit.get(z);
dependsOnRoot = false;
break;
}
}
if (dependsOnRoot == true) {
cycles.add(cycleToBeSplit);
} else {
List<String> notARoot = new ArrayList<String>();
notARoot.add("0");
notARoot.add(doNotSplit);
// put everything else in the
for (int z = 0; z < cycleToBeSplit.size(); z++) {
String e = cycleToBeSplit.get(z);
if (!e.equals(doNotSplit)) {
notARoot.add(e);
}
}
cycles.add(notARoot);
}
List<String> relInCycle = new ArrayList<String>();
relInCycle.add(s);
relInCycle.add(curr);
relationshipInCycle.add(relInCycle);
}
/*String e1 = cycleToBeSplit.get(0);
String e2 = cycleToBeSplit.get(1);
int sizeE1 = entityTypes.get(e1).getLinks().size();
int sizeE2 = entityTypes.get(e2).getLinks().size();
if (sizeE1 > 2 && sizeE2 == 2) {
//split E2
setEntityToBeSplitted(e2, -1);
List<String> notARoot = new ArrayList<String>();
notARoot.add(e2);
cycles.add(notARoot);
} else if (sizeE1 == 2 && sizeE2 > 2) {
//split E1
setEntityToBeSplitted(e1, -1);
List<String> notARoot = new ArrayList<String>();
notARoot.add(e1);
cycles.add(notARoot);
} else {
// if both does not have links
cycles.add(cycleToBeSplit);
List<String> relInCycle = new ArrayList<String>();
relInCycle.add(s);
relInCycle.add(curr);
relationshipInCycle.add(relInCycle);
}*/
}
}
return cycles;
} |
d1a1a017-f52c-4421-b47b-bc9eb0c95c72 | 1 | public static void main( String[] args )
{
int loopLimit = 10;
int count = 0;
while ( count < loopLimit )
{
System.out.println( count );
count = count + 1;// increase the count by one
}
} |
38d07c09-b290-4e36-a4e0-3c32d6d2ad95 | 4 | public void minusEquals(Matrix bmat){
if((this.numberOfRows!=bmat.numberOfRows)||(this.numberOfColumns!=bmat.numberOfColumns)){
throw new IllegalArgumentException("Array dimensions do not agree");
}
int nr=bmat.numberOfRows;
int nc=bmat.numberOfColumns;
for(int i=0; i<nr; i++){
for(int j=0; j<nc; j++){
this.matrix[i][j] -= bmat.matrix[i][j];
}
}
} |
6f4ad109-2c3b-4669-9693-8ebf59e6b8a6 | 5 | public Component getEditorComponent(final PropertyEditor editor)
{
String[] tags = editor.getTags();
String text = editor.getAsText();
if (editor.supportsCustomEditor())
{
return editor.getCustomEditor();
}
else if (tags != null)
{
// make a combo box that shows all tags
final JComboBox comboBox = new JComboBox(tags);
comboBox.setSelectedItem(text);
comboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getStateChange() == ItemEvent.SELECTED)
editor.setAsText((String) comboBox.getSelectedItem());
}
});
return comboBox;
}
else
{
final JTextField textField = new JTextField(text, 10);
textField.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
try
{
editor.setAsText(textField.getText());
}
catch (IllegalArgumentException exception)
{
}
}
public void removeUpdate(DocumentEvent e)
{
try
{
editor.setAsText(textField.getText());
}
catch (IllegalArgumentException exception)
{
}
}
public void changedUpdate(DocumentEvent e)
{
}
});
return textField;
}
} |
7aea21e1-aa9b-4632-a4e5-5340516f7e2d | 3 | private void searchPage(Request req) {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(req.url.openStream()));
String inputLine, content = "";
while ((inputLine = in.readLine()) != null)
content += inputLine;
in.close();
if (content.indexOf("<div class='searchresults'>") != -1) {
req.result = formatSearchResults(content);
req.complete();
} else {
Matcher ma = findTitle.matcher(content);
ma.find();
req.title = formatSymbols(ma.group(1));
req.result = formatPage(content);
req.complete();
}
} catch (IOException e) {
req.result = e.toString();
req.complete();
}
} |
e43d1320-069c-4764-a00b-0f144e4c22f4 | 0 | public int getAge() {
return Age;
} |
d527a01d-d6fb-43f0-84fb-cb99a04c5986 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Reserva other = (Reserva) obj;
if (this.IdReserva != other.IdReserva && (this.IdReserva == null || !this.IdReserva.equals(other.IdReserva))) {
return false;
}
return true;
} |
32ee6287-8a71-44bf-8052-4c74031aa7aa | 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(OTPasswordDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OTPasswordDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OTPasswordDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OTPasswordDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the dialog
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
OTPasswordDialog dialog = new OTPasswordDialog(new javax.swing.JFrame(), true, "");
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
5b1592b1-ab88-4f7b-a94e-3308da432c0d | 2 | private Node determineNewSelectedNode(JoeTree tree) {
Node newSelectedNode = null;
// Find the range
Node firstNewSelectedNode = tree.getYoungestInSelection();
//int ioFirstNewSelectedNode = tree.getVisibleNodes().indexOf(firstNewSelectedNode);
Node lastNewSelectedNode = tree.getOldestInSelection();
//int ioLastNewSelectedNode = tree.getVisibleNodes().indexOf(lastNewSelectedNode);
// Handle Boundary conditions for the selection.
if (firstNewSelectedNode == tree.getVisibleNodes().get(0)) {
tree.getDocument().panel.layout.setNodeToDrawFrom(firstNewSelectedNode, 0);
newSelectedNode = firstNewSelectedNode;
} else if (lastNewSelectedNode == tree.getVisibleNodes().get(tree.getVisibleNodes().size() - 1)) {
newSelectedNode = lastNewSelectedNode;
} else {
newSelectedNode = firstNewSelectedNode;
}
return newSelectedNode;
} |
05031c30-a64f-49ef-985a-080fe30d392e | 0 | public String getVenue() {
return venue;
} |
057feefa-6f00-427c-ae4e-8230ac3b5971 | 5 | @Override
public void run() {
logger.info("Starting monitor thread: " + this.getClass().getSimpleName());
T data = null;
try {
data = preRun();
this.cont = true;
} catch(Throwable t) {
logger.error("Exception occured in pre watcher run.", t);
this.cont = false;
}
try {
while(this.cont) {
loopImpl(data);
if(performSleep) {
Thread.sleep(SLEEP_TIME);
}
}
} catch(Throwable t) {
logger.error("Exception occired in watcher run.", t);
} finally {
try {
postRun(data);
} catch(Throwable t) {
logger.error("Exception occured in post watcher run.", t);
}
logger.info("Thread exiting.");
}
} |
01e5b9a5-75e2-49c3-b076-79be2210170e | 5 | final int[][] method1274(int i, int j) {
if (j != 6) {
return null;
}
int ai[][] = super.aClass112_3320.method1036(-106, i);
if (super.aClass112_3320.aBoolean1822) {
int ai1[] = method1270(0, Class99.anInt1688 & i + -1, true);
int ai2[] = method1270(0, i, true);
int ai3[] = method1270(0, 1 + i & Class99.anInt1688, true);
int ai5[] = ai[1];
int ai6[] = ai[2];
int ai4[] = ai[0];
for (int k = 0; ~Class117.anInt1861 < ~k; k++) {
int k1 = anInt4396 * (-ai1[k] + ai3[k]);
int j2 = k1 >> 12;
int l1 = (ai2[Class115.anInt1841 & 1 + k] + -ai2[k + -1 & Class115.anInt1841]) * anInt4396;
int i2 = l1 >> 12;
int k2 = i2 * i2 >> 12;
int l2 = j2 * j2 >> 12;
int i3 = (int) (Math.sqrt((float) (4096 + (k2 + l2)) / 4096F) * 4096D);
int l;
int i1;
int j1;
if (i3 != 0) {
l = l1 / i3;
i1 = k1 / i3;
j1 = 0x1000000 / i3;
} else {
j1 = 0;
l = 0;
i1 = 0;
}
if (aBoolean4391) {
l = (l >> 1) + 2048;
j1 = (j1 >> 1) + 2048;
i1 = (i1 >> 1) + 2048;
}
ai4[k] = l;
ai5[k] = i1;
ai6[k] = j1;
}
}
return ai;
} |
5181cd5a-4a67-4000-ba88-b5010dbfff33 | 6 | private static boolean selectTests(){
System.out.println("Selecting songs...");
ArrayList<Integer> ids = dbModel.getAllSongIds();
if(ids.size() != insertCount){
reason = "The wrong amount of ids were returned";
failed = true;
return false;
}
ArrayList<DBSong> songs = dbModel.getAllSongs();
if(songs.size() != insertCount){
reason = "The wrong amount of songs were returned";
failed = true;
return false;
} else if (songs.get(0).getSongId() != song.getSongId()){
reason = "The wrong song id was returned";
failed = true;
return false;
}
DBSong dbSong = dbModel.getSong(song.getSongId());
if(dbSong.getSongId() != song.getSongId()){
reason = "The wrong song id was returned";
failed = true;
return false;
}
ids = dbModel.getSongFromBPMRange(song.getBPM(), song.getBPM() + 1);
if(ids.size() != 1){
reason = "The wrong amount of ids were returned in bpm range";
failed = true;
return false;
}
ids = dbModel.getSongFromPlayCountRange( song.getPlayCount(),
song.getPlayCount() + 1);
if(ids.size() != 1){
reason = "The wrong amount of ids were returned in play count range";
failed = true;
return false;
}
return true;
} |
d4c93977-febe-4786-ad68-2d04e7adbd9a | 0 | @Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
} |
02ec7027-c9d9-4ada-87bd-7b97547204b7 | 7 | private static ArrayList<GregorianCalendar> parseInputToGregorianCalendar(String input[],
ArrayList<GregorianCalendar> defaultDate)
{
ArrayList<GregorianCalendar> result = new ArrayList<GregorianCalendar>();
SimpleDateFormat sdf = new SimpleDateFormat();
for (int i = 0; i < input.length; i++) {
sdf.applyPattern("dd.MM.yyy");
result.add(new GregorianCalendar());
try {
result.get(i).setTime(sdf.parse(input[i]));
if (input.length == 1) {
result.add((GregorianCalendar) result.get(i).clone());
result.get(i + 1).add(GregorianCalendar.DAY_OF_YEAR, 1);
result.get(i + 1).add(GregorianCalendar.SECOND, -1);
} else if (i != 0) {
result.get(i).add(GregorianCalendar.DAY_OF_YEAR, 1);
result.get(i).add(GregorianCalendar.SECOND, -1);
}
} catch (ParseException e) {
sdf.applyPattern("MM.yyy");
try {
result.get(i).setTime(sdf.parse(input[i]));
if (input.length == 1) {
result.add((GregorianCalendar) result.get(i).clone());
result.get(i + 1).add(GregorianCalendar.MONTH, 1);
result.get(i + 1).add(GregorianCalendar.SECOND, -1);
} else if (i != 0) {
result.get(i).add(GregorianCalendar.MONTH, 1);
result.get(i).add(GregorianCalendar.SECOND, -1);
}
} catch (ParseException e1) {
result = defaultDate;
}
}
}
return result;
} |
4d21301e-f47f-4f45-aaab-cf2711c04d99 | 1 | public void accept(NodeVisitor visitor) {
for (ClassNode c : classes) {
c.accept(visitor);
}
} |
60e3128f-69df-488f-a51e-cf9bca8a7953 | 3 | public void processBytes(byte[] in, int inOff, int len, byte[] out, int outOff)
{
if((inOff + len) > in.length)
{
throw new RuntimeException("output buffer too short");
}
if((outOff + len) > out.length)
{
throw new RuntimeException("out put buffer too short");
}
for(int i = 0; i < len; i++)
{
x = (x + 1) & 0xff;
y = (engineState[x] + y) & 0xff;
//swap
byte tmp = engineState[x];
engineState[x] = engineState[y];
engineState[y] = tmp;
//xor
out[i + outOff] = (byte) (in[i + inOff] ^ engineState[(engineState[x] + engineState[y]) & 0xff]);
}
} |
d18e1e0e-acbb-4bf4-81f2-94f9630a54b5 | 0 | public void setEncryptedValue(EncryptedDataType value) {
this.encryptedValue = value;
} |
2453ad7d-312e-4d0a-bb32-31b21adbb834 | 5 | public boolean sRight(){
boolean change = false;
//i -> y | j -> x
for (int i = 0 ; i < 4 ; i ++){
for (int j = 3; j > -1 ; j--) {
//System.out.println("sRight> i: " + i + " j: " + j);
boolean tmp = mRight(j, i);
if (tmp == true)
change = true;
}
if(aRight(i))
change = true;
}
if (change){
//System.out.println(change); //debug
genTile();
}
return change;
} |
ab0f5dd1-9b43-41e6-abcb-8e357e056868 | 4 | public static int findLongestSubWithoutRep(String s) {
if (s.length() == 0) {
return 0;
}
char[] arr = s.toCharArray();
int i = 0;
int maxlength = 1;
int begin = 0;
int tempLen = 0;
int tempBegin = 0;
HashSet<Character> hs = new HashSet<Character>();
while (i < arr.length) {
if (!hs.contains(arr[i])) {
hs.add(arr[i]);
tempLen += 1;
if (tempLen > maxlength) {
maxlength = tempLen;
begin = tempBegin;
}
} else {
hs.clear();
tempBegin = i - tempLen + 1;
i = i - tempLen + 1;
hs.add(arr[i]);
tempLen = 1;
}
i++;
}
return maxlength;
} |
ef328edb-38dd-497c-83f4-5c991b0aec1e | 8 | @Override
public boolean equals(Object obj) {
if(obj == this) return true;
if(! (obj instanceof Map)) return false;
final Map<K,V> asM = (Map<K,V>) obj;
if(asM.size() != size()) return false;
final Iterator<Map.Entry<K, V>> it = asM.entrySet().iterator();
try {
while(it.hasNext()){
final Map.Entry<K, V> e = it.next();
final K k = e.getKey();
final V thatV = e.getValue();
final V thisV = get(k);
if(thisV == null){
if(thatV != null) return false;
} else {
if(!thisV.equals(thatV)) return false;
}
}
} catch(ClassCastException e) { return false; }
return true;
} |
d0870a71-d6a3-48b8-8a6f-d6e195d96155 | 9 | public String getSignature() {
StringBuilder buffer = new StringBuilder(256);
boolean found = false;
if (this.lowerBounds != null) {
found = true;
if (this.lowerBounds instanceof ClassTypeDesc) {
ClassTypeDesc clazz = (ClassTypeDesc) this.lowerBounds;
String name = clazz.getClassName();
if (Object.class.getName().equals(name)) {
found = false;
}
}
if (found) {
buffer.append('-').append(this.lowerBounds.getSignature());
}
}
else if (this.upperBounds != null) {
found = true;
if (this.upperBounds instanceof ClassTypeDesc) {
ClassTypeDesc clazz = (ClassTypeDesc) this.upperBounds;
String name = clazz.getClassName();
if (Object.class.getName().equals(name)) {
found = false;
}
}
if (found) {
buffer.append('+').append(this.upperBounds.getSignature());
}
}
if (!found) {
buffer.append('*');
}
return buffer.toString();
} |
27990694-6bbe-4c08-aa99-502e57c14aaa | 5 | static private final int jjMoveStringLiteralDfa1_0(long active0)
{
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(0, active0);
return 1;
}
switch(curChar)
{
case 42:
if ((active0 & 0x100L) != 0L)
return jjStartNfaWithStates_0(1, 8, 82);
break;
case 47:
if ((active0 & 0x40L) != 0L)
return jjStopAtPos(1, 6);
break;
default :
break;
}
return jjStartNfa_0(0, active0);
} |
d3bf92ba-e165-4ed8-9d9f-4a55adb3dbe5 | 7 | public String getTypeString() {
switch(this.type) {
case 1: return "Manga";
case 2: return "Novel";
case 3: return "One Shot";
case 4: return "Doujin";
case 5: return "Manhwa";
case 6: return "Manhua";
case 7: return "OEL";
default: return "Manga";
}
} |
60604aaa-5d25-4af2-8fd5-0e7609233879 | 7 | public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} |
73b758d8-0828-4ff2-a7d7-45bddcfad26f | 2 | private boolean addNumericId(String numericId) {
int id=-1;
try {
id=Integer.parseInt(numericId);
} catch (NumberFormatException e) {
throw new RuntimeException("Internal error, regex failed parsing what should be a numeric genre ID="+numericId);
}
String genre=GenreList.idToValue.get(id);
if(genre!=null) {
this.add(genre);
return true;
}
return false;
} |
d65e0522-3ced-441d-a26a-5d9d75a9ae9c | 4 | private static void addCompatibilityWarning(HTMLElement root) {
for (Object o : root.getChildren()) {
if (o instanceof HTML) {
for (Object e : ((HTMLElement) o).getChildren()) {
if (e instanceof BODY) {
BODY body = (BODY) e;
((BODY) e).addObject(new Warning(
"You are using an incompatible Browser"));
}
}
}
}
} |
75fca3ef-67b5-4912-9d36-0a6d80b5b56a | 6 | public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
if (!(sender instanceof Player))
return false;
if (!sender.hasPermission(Permissions.PERM_CLAIM))
{
Util.sendMessage("&cYou don't have permission!", sender.getName());
return true;
}
Player player = (Player) sender;
ChunkData cd = new ChunkData(player.getLocation().getChunk());
if (!player.hasPermission(Permissions.PERM_ADMIN))
{
if (!cd.isProtected())
{
Util.sendMessage("&cError: That chunk isn't protected!", player.getName());
return true;
}
if (!cd.getOwner().equalsIgnoreCase(player.getName()))
{
Util.sendMessage("&cError: That protection doesn't belong to you!", player.getName());
return true;
}
Util.sendMessage("&aProtection Deleted.", cd.getOwner());
cd.removeProtection();
}
else
{
if (!cd.isProtected())
{
Util.sendMessage("&cError: That chunk isn't protected!", player.getName());
return true;
}
Util.sendMessage("&a" + player.getName() + " removed your protection. At the coords " + cd.getCoords(), cd.getOwner());
Util.sendMessage("&aProtection Deleted.", player.getName());
cd.removeProtection();
}
return false;
} |
9edc530d-550c-4a75-aa5c-c41fed047eb0 | 5 | @Override
public void store() {
Map<Class<? extends IUser>, List<Map<String, Object>>> description = new HashMap<Class<? extends IUser>, List<Map<String, Object>>>();
for (IUser m : this.usersToList()) {
Class<? extends IUser> c = m.getClass();
if (description.containsKey(c)) {
description.get(c).add(m.getDescription());
} else {
List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
newList.add(m.getDescription());
description.put(c, newList);
}
}
ConfigXML.store(description, PATH_ACCOUNT_FILE, VERSION_ACCOUNT_FILE);
} |
f8370b79-dfdb-403b-b0fa-cb9bb59008db | 8 | @Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SickEntry other = (SickEntry) obj;
if (days != other.days)
return false;
if (id != other.id)
return false;
if (start == null)
{
if (other.start != null)
return false;
} else if (!start.equals(other.start))
return false;
return true;
} |
a62c90cb-6c39-4a0e-b28f-7be1f4c725bf | 0 | public int getPlayers(){
numberOfPlayers=1; // can set this up to ask for user input.
//Scanner input = new Scanner(System.in);
//System.out.prinln("How many players?: ");
//numberOfPlayers =input.nextInt();
return numberOfPlayers;
} |
0f01cdce-aa27-416f-aa44-dc634fe7d214 | 6 | @Override
protected Object decode(State state, IOBuffer buffer, Channel channel)
throws Exception
{
String line;
switch(state)
{
case HEADER_FIRST_LINE:
header = new HttpRequestHeader();
line = readLine(buffer);
String[] firstLine = line.split(" ");
header.setMethod(firstLine[0].trim());
header.setPlainUri(firstLine[1].trim());
header.setVersion(firstLine[2].trim());
checkpoint(State.HEADER);
case HEADER:
while( true )
{
line = readLine(buffer);
if( line.length() == 0 )
break;
String[] keyValue = line.split(":");
header.addHeader(keyValue[0], keyValue[1]);
checkpoint(State.HEADER);
}
checkpoint(State.BODY);
return header;
case BODY:
if( header.getMethod().equals("post") )
;
String contentLengthString = header.getHeader("content-length");
int contentLength = Integer.parseInt(contentLengthString);
checkpoint(State.BODY);
checkpoint();
}
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.