method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
147f4c9b-aad9-433d-aa67-2743b5500d7d | 2 | private static boolean supportsDnD() { // Static Boolean
if (supportsDnD == null) {
boolean support = false;
try {
Class arbitraryDndClass = Class
.forName("java.awt.dnd.DnDConstants");
support = true;
} // end try
catch (Exception e) {
support = false;
} // end catch
supportsDnD = new Boolean(support);
} // end if: first time through
return supportsDnD.booleanValue();
} // end supportsDnD |
271970d7-4463-4946-932b-073fd8649449 | 5 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<HTML>\n");
out.write("<BODY>\n");
out.write("<FORM METHOD=POST ACTION=\"SaveQuery4.jsp\">\n");
out.write("Enter \"desc\" to test <INPUT TYPE=TEXT NAME=username SIZE=20>\n");
out.write("<P><INPUT TYPE=SUBMIT>\n");
out.write("</FORM>\n");
out.write("</BODY>\n");
out.write("</HTML>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
c28dc3ba-6f0e-4086-94fe-872a1f71b2ea | 6 | public void onEnable() {
instance = this;
Configuration.reloadConfiguration();
dbcore = new DatabaseCore(this);
clisten = new CoreEvents(this);
plisten = new PlayerEvents(this);
elisten = new EntityEvents(this);
getServer().getPluginManager().registerEvents(clisten, this);
getServer().getPluginManager().registerEvents(plisten, this);
getServer().getPluginManager().registerEvents(elisten, this);
Configuration.version = "v" + getDescription().getVersion();
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
for (Player pl : Bukkit.getOnlinePlayers()) {
SecretPlayer player = dbcore.secplayers.get(pl.getName());
if (player != null) {
if (!player.isLoggedIn() && player.isRegistered() && player.thirtySeconds()) {
pl.kickPlayer("You've taken too long to login.");
}
}
}
}
}, 600L, 600L);
try {
Metrics metrics = new Metrics(this);
Graph graph = metrics.createGraph("SecretWord Data");
graph.addPlotter(new Metrics.Plotter("Blocked Attacks") {
@Override
public int getValue() {
return dbcore.failedlogins;
}
});
metrics.start();
// report version to ingame.
} catch (IOException e) {
System.out.println("Metrics haz failed.");
}
getLogger().log(Level.INFO, "SecretWord " + Configuration.version + " has been enabled! Please check for updates quite often for latest bug fixes!");
} |
0948d049-8e48-49d7-ad17-f1ebbaae8f07 | 1 | public List<String> getMedium() {
if (medium == null) {
medium = new ArrayList<String>();
}
return this.medium;
} |
8356407c-ad7c-4c37-ae51-f81238895b20 | 1 | public static ArrayList<Excel> move(int a, int b, int c, ArrayList<Excel> toScale)
{
ArrayList<Excel> result = new ArrayList<Excel>();
double matrix[][] = { {1, 0,0,0},
{0, 1,0,0},
{0, 0,1,0},
{a, b,c,1}
};
Matrix scaleMatrix = new Matrix(4,4);
scaleMatrix.setMatrix(matrix);
for (Excel ex: toScale)
{
double l[][] = {{ex.getX(),
ex.getY(),
ex.getZ(),
ex.getT()}
};
Matrix line = new Matrix(1,4);
line.setMatrix(l);
Matrix multiplied = Matrix.matrixMultiplication(line, scaleMatrix);
int x =(int) Math.round(multiplied.getEl(0, 0));
int y =(int) Math.round(multiplied.getEl(0, 1));
int z =(int) Math.round(multiplied.getEl(0, 2));
int t =(int) Math.round(multiplied.getEl(0, 3));
result.add(new Excel(x,y,z,t, ex.getColor()));
}
return result;
} |
e51869db-37db-478f-8b2a-3ccd9ed72ffb | 7 | public void saveReport(){
final Dictation self = this;
if(report == null) { //New report
if(ddlPatient.getSelectedIndex() > 0) {
SwingWorker<Boolean,Void> createWorker = new SwingWorker<Boolean,Void>(){
@Override
protected Boolean doInBackground() throws Exception {
return controller.createReport(
panel.txtBiased.getText(), panel.txtUnbiased.getText(),
panel.txtImpression.getText(), panel.txtPlan.getText(),
(String)ddlPatient.getSelectedItem());
}
@Override
protected void done(){
try {
if(this.get())
frame.dispose();
else{
WaitModal.close();
self.setVisible(true);
CSIGDialog.showError(lang.getString("Error.CouldNotCreateReport"), lang.getString("OK"));
//JOptionPane.showMessageDialog(frame, lang.getString("Error.CouldNotCreateReport"), "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException | InterruptedException
| ExecutionException e) {
e.printStackTrace();
WaitModal.close();
self.setVisible(true);
CSIGDialog.showError(lang.getString("Error.InternalError"), lang.getString("OK"));
//JOptionPane.showMessageDialog(frame, lang.getString("Error.InternalError"), "Error", JOptionPane.ERROR_MESSAGE);
}
}
};
WaitModal.open("Creando informe");
this.setVisible(false);
createWorker.execute();
} else {
CSIGDialog.showWarning(lang.getString("Warning.PatientNotSelected"), lang.getString("OK"));
//JOptionPane.showMessageDialog(frame, lang.getString("Warning.PatientNotSelected"), "Aviso", JOptionPane.WARNING_MESSAGE);
}
} else { //Existing report
SwingWorker<Boolean,Void> updateWorker = new SwingWorker<Boolean,Void>(){
@Override
protected Boolean doInBackground() throws Exception {
CSIGReport cleanR = null;
try {
//Update CSIGReport in memory
cleanR = report.clone();
cleanR.setBiased(panel.txtBiased.getText());
cleanR.setUnbiased(panel.txtUnbiased.getText());
cleanR.setImpressions(panel.txtImpression.getText());
cleanR.setPlan(panel.txtPlan.getText());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
CSIGDialog.showError(lang.getString("Error.InternalError"), lang.getString("OK"));
//JOptionPane.showMessageDialog(frame, lang.getString("Error.InternalError"), "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return controller.updateReport(cleanR, false);
}
@Override
protected void done(){
try {
if(this.get())
frame.dispose();
else{
WaitModal.close();
self.setVisible(true);
CSIGDialog.showError(lang.getString("Error.CouldNotUpdateReport"), lang.getString("OK"));
//JOptionPane.showMessageDialog(frame, lang.getString("Error.CouldNotUpdateReport"), "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException | InterruptedException
| ExecutionException e) {
e.printStackTrace();
WaitModal.close();
self.setVisible(true);
CSIGDialog.showError(lang.getString("Error.InternalError"), lang.getString("OK"));
//JOptionPane.showMessageDialog(frame, lang.getString("Error.InternalError"), "Error", JOptionPane.ERROR_MESSAGE);
}
}
};
WaitModal.open("Actualizando informe");
this.setVisible(false);
//And send it to update in SIIE
updateWorker.execute();
}
} |
b1531f75-46a1-4b58-b83b-5ca1ce67f0d1 | 5 | public void render()
{
BufferStrategy bs = getBufferStrategy();
if (bs == null)
{
createBufferStrategy(3);
return;
}
if (game != null)
game.render();
if (menu != null)
menu.render(art, this);
for (int y = 0; y < art.getHeight(); y++)
{
for (int x = 0; x < art.getWidth(); x++)
{
pixels[x + y * WIDTH] = art.getPixels()[x + y * art.getWidth()];
}
}
Graphics g = bs.getDrawGraphics();
int ww = WIDTH * SCALE;
int hh = HEIGHT * SCALE;
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(img, (getWidth() - ww) / 2, (getHeight() - hh) / 2, ww, hh, null);
g.dispose();
bs.show();
} |
949e3d2a-741c-4827-84d2-516e274dfb97 | 3 | protected void fireTreeNodesChanged(Object source, Object[] path,
int[] childIndices, Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = this.listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == TreeModelListener.class) {
// Lazily create the event:
if (e == null) {
e = new TreeModelEvent(source, path, childIndices, children);
}
((TreeModelListener) listeners[i + 1]).treeNodesChanged(e);
}
}
} |
a9670f72-9692-4475-b9eb-7e26c4ea2cd9 | 7 | public void removeKey(String var) {
Boolean changed = false;
if (this.props.containsKey(var)) {
this.props.remove(var);
changed = true;
}
// Use an iterator to prevent ConcurrentModification exceptions
Iterator<String> it = this.lines.listIterator();
while (it.hasNext()) {
String line = it.next();
if (line.trim().length() == 0) {
continue;
}
if (line.charAt(0) == '#') {
continue;
}
if (line.contains("=")) {
int delimPosition = line.indexOf('=');
String key = line.substring(0, delimPosition).trim();
if (key.equals(var)) {
it.remove();
changed = true;
}
} else {
continue;
}
}
// Save on change
if (changed) {
save();
}
} |
9b51249b-885f-4137-8258-79f251264037 | 2 | private <E extends AnnotatedElement> AnnotatedHandlerBuilder<E> handleElement( final Class<E> annotatedElementType )
{
return new AnnotatedHandlerBuilder<E>()
{
public <A extends Annotation> LinkedHandlingBuilder<E, A> annotatedWith( final Class<A> annotationType )
{
if ( annotationType == null )
{
throw new IllegalArgumentException( "Parameter 'annotationType' must not be null" );
}
return new LinkedHandlingBuilder<E, A>()
{
@SuppressWarnings( "unchecked" )
public void withHandler( AnnotationHandler<E, A> handler )
{
if ( handler == null )
{
throw new IllegalArgumentException( "Parameter 'handler' must not be null" );
}
AnnotationHandlerBinderImpl.this.registry.put( new Key( annotatedElementType, annotationType ),
(AnnotationHandler<AnnotatedElement, Annotation>) handler );
}
};
}
};
} |
89a6a847-7cc0-4ac8-a712-262e8474cf3e | 5 | public Object [][] getDatos(){
Object[][] data = new String[getCantidadElementos()][colum_names.length];
//realizamos la consulta sql y llenamos los datos en "Object"
try{
if (colum_names.length>=0){
r_con.Connection();
String campos = colum_names[0];
for (int i = 1; i < colum_names.length; i++) {
campos+=",";
campos+=colum_names[i];
}
String consulta = ("SELECT "+campos+" "+
"FROM "+name_tabla);
PreparedStatement pstm = r_con.getConn().prepareStatement(consulta);
ResultSet res = pstm.executeQuery();
int i = 0;
while(res.next()){
for (int j = 0; j < colum_names.length; j++) {
data[i][j] = res.getString(j+1);
}
i++;
}
res.close();
}
} catch(SQLException e){
System.out.println(e);
} finally {
r_con.cierraConexion();
}
return data;
} |
cb31f99a-d14d-47cb-86e1-796153343f5b | 7 | private boolean testFilterProperty_Size(SpecialFile other) {
String byteType = this.filter.getMetricSize();
BigInteger sourceSize = new BigInteger(String.valueOf(this.SIZE));
BigInteger targetSize = new BigInteger(String.valueOf(other.SIZE));
String num = "";
switch (byteType) {
default:
case "BYTE":
num = "1";
break;
case "KILOBYTE":
num = "1024";
break;
case "MEGABYTE":
num = "1048576";
break;
case "GIGABYTE":
num = "1073741824";
break;
}
sourceSize.multiply(new BigInteger(String.valueOf(num)));
targetSize.multiply(new BigInteger(String.valueOf(num)));
boolean sourceSizeIsBiggest = sourceSize.compareTo(targetSize) > 0;
double requiredPercent = this.filter.getSizePercentMatchDouble();
if (sourceSizeIsBiggest) {
double matchPercent = targetSize.divide(sourceSize).doubleValue();
if (!(matchPercent >= requiredPercent))
return false;
} else {
double matchPercent = sourceSize.divide(targetSize).doubleValue();
if (!(matchPercent >= requiredPercent))
return false;
}
return true;
} |
99122ca1-e267-46bf-9930-d4d9e78522d5 | 4 | private boolean init() {
for (Object i : graph.getEdgeMap().values()) {
Integer integer = (Integer) i;
// wenn es nagative Werte gibt, gib eine Warnung aus
if (Math.abs(integer) != integer) {
JOptionPane.showMessageDialog(null,
"Dijkstra kann auf diesen Graph nicht angewendet werden. Der Graph enthält negative Kantengewichte.",
"Fehler", JOptionPane.ERROR_MESSAGE);
return false;
}
}
startVertex.setDist(0);
queue.add(startVertex);
for (Vertex v : graph.getVertices()) {
if (v.getId() != startVertex.getId()) {
v.setDist(Integer.MAX_VALUE);
pred[v.getId()] = null;
queue.add(v);
}
}
startVertex.setDist(0);
return true;
} |
b2149a8e-3fad-43bb-9c66-b9cda0150e2a | 6 | private Zone checkActiveZone(Point eventLocation)
{
//Zone that event location is currently being checked against
Zone currentZone = null;
//Concise form of the event location
int x = eventLocation.x;
int y = eventLocation.y;
//Flag which is set if event is found to be within a zone
Boolean withinZone = false;
//Look at each zone in turn, checking if the event occurred within its
//boundaries. Once one is found, stop looking and return that zone
for(int i=0; i< zones.size(); i++)
{
currentZone = zones.get(i);
//Check if between left and right edges
Boolean xTrue = ((x >= currentZone.zoneBounds.get(0)) &&
(x <= currentZone.zoneBounds.get(1)));
//Check if between top and bottom edges
Boolean yTrue = ((y >= currentZone.zoneBounds.get(2)) &&
(y <= currentZone.zoneBounds.get(3)));
if(xTrue && yTrue)
{
withinZone = true;
break;
}
}
//If event was found to be within a zone, return that zone
//If no relevant zone found, return null
if(withinZone)
return currentZone;
else
return null;
} |
d6cc4d75-698b-4c4e-bfd1-e174ffc6efb6 | 5 | private void putComment (Graphics2D g2d, String t, int i) {
Integer fWidth = MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getFieldWidth();
Font font = MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getPrintFont();
Integer fontSize = font.getSize();
Integer minFontSize = fontSize / 2;
g2d.setFont(MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getPrintFont());
if ((t == null) || (t.equals(""))) {
return;
}
g2d.setColor(MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getPrintColor());
Point a = MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getAnchorPoint();
TextLayout tl = new TextLayout("AbcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ",
MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (i).getPrintFont(),
g2d.getFontRenderContext());
String[] outputs = t.split("\n");
for(int l=0; l<outputs.length; l++){
g2d.setFont(font);
while ((fWidth < g2d.getFontMetrics().getStringBounds(outputs[l], g2d).getWidth()) &&
( fontSize > minFontSize )) {
fontSize = fontSize -1;
g2d.setFont(font.deriveFont((float)fontSize));
}
g2d.drawString(outputs[l], a.x,(int) (a.getY()+l*tl.getBounds().getHeight()*1.3));
}
} |
e94ca38a-de8a-4245-b695-b5c73fda06b9 | 2 | public boolean opEquals(Operator o) {
if (o instanceof ConstOperator) {
Object otherValue = ((ConstOperator) o).value;
return value == null ? otherValue == null : value
.equals(otherValue);
}
return false;
} |
898114a2-a1c3-4b09-b24c-6c82b93c2f31 | 4 | public static Configuration getLauncherConfiguration()
{
final Configuration config = new Configuration();
// Load JavaConfig class.
try
{
Class<?> clazz = configClass;
if (clazz == null)
{
clazz = Configuration.class.getClassLoader().loadClass(
"com.kokakiwi.mclauncher.core.JavaConfig");
}
final Method method = clazz.getMethod("config");
final Configuration javaConfig = (Configuration) method
.invoke(null);
if (javaConfig.getBoolean("load.user-config"))
{
config.load(Configuration.class
.getResourceAsStream("/config/default.yml"), "yaml");
}
config.load(javaConfig);
}
catch (final Exception e)
{
config.load(Configuration.class
.getResourceAsStream("/config/default.yml"), "yaml");
}
return config;
} |
3aa1a0c8-7a31-4dbd-91b3-f1caeaaf768d | 7 | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String forwardTo = "";
String message = "";
String action = request.getParameter("action");
HttpSession session = request.getSession();
if (action != null) {
// LISTER LES UTILISATEURS
if (action.equals("listerLesMusiques")) {
System.out.println(session.getAttribute("login"));
//gestionnaireMusiques.CreationCatalogue();
Collection<Morceau> liste = gestionnaireMusiques.listeDesMorceaux();
request.setAttribute("listeDesMusiques", liste);
if (gestionnaireUtilisateurs.checkTemps(session.getAttribute("login").toString()) == true) {
forwardTo = "main.jsp?action=listerLesMusiques";
message = "Liste des musiques";
getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
} else {
forwardTo = "mainsansabo.jsp?action=listerLesMusiques";
message = "Liste des musiques";
getServletContext().getRequestDispatcher("/mainsansabo.jsp").forward(request, response);
}
//UTILISATEUR DE TEST
} else if (action.equals("modifiercompte")) {
System.out.println(session.getAttribute("login"));
String check = request.getParameter("abonnement");
System.out.println("Abonnement : " + check);
if (check == null) {
String login = session.getAttribute("login").toString();
System.out.println("Ouverture de la modification...");
Collection<Utilisateur> liste = gestionnaireUtilisateurs.getUtilisateur(login);
request.setAttribute("listeDesUsers", liste);
}
forwardTo = "modificationcompte.jsp";
message = "Liste des musiques";
getServletContext().getRequestDispatcher("/modificationcompte.jsp").forward(request, response);
} else if (action.equals("update")) {
gestionnaireUtilisateurs.modifierAbonnement(session.getAttribute("login").toString(), request.getParameter("abonnement"));
Collection<Morceau> liste = gestionnaireMusiques.listeDesMorceaux();
request.setAttribute("listeDesMusiques", liste);
if (gestionnaireUtilisateurs.checkTemps(session.getAttribute("login").toString()) == true) {
forwardTo = "main.jsp?action=listerLesMusiques";
message = "Liste des musiques";
getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
} else {
forwardTo = "mainsansabo.jsp?action=listerLesMusiques";
message = "Liste des musiques";
getServletContext().getRequestDispatcher("/mainsansabo.jsp").forward(request, response);
}
}
}
RequestDispatcher dp = request.getRequestDispatcher(forwardTo + "&message=" + message);
dp.forward(request, response);
//Après un forward, plus rien ne peut être exécuté après !
} |
1b37aaa4-397f-4d6d-b34a-f7f2754c0221 | 6 | public static boolean visibleFromP(Context viewedcontext, Context fromcontext) {
{ boolean testValue000 = false;
if (viewedcontext == fromcontext) {
testValue000 = true;
}
else {
if (fromcontext.allSuperContexts.membP(viewedcontext)) {
testValue000 = true;
}
else {
{ boolean foundP000 = false;
{ Module usesmodule = null;
Cons iter000 = (Stella_Object.isaP(fromcontext, Stella.SGT_STELLA_MODULE) ? ((Module)(fromcontext)).uses : fromcontext.baseModule.uses).theConsList;
loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
usesmodule = ((Module)(iter000.value));
if ((viewedcontext == usesmodule) ||
usesmodule.allSuperContexts.membP(viewedcontext)) {
foundP000 = true;
break loop000;
}
}
}
testValue000 = foundP000;
}
}
}
{ boolean value000 = testValue000;
return (value000);
}
}
} |
f9ab7d74-b1bf-421f-9a7c-a80b0098ee5c | 2 | public void start()
{
if(!Run)
{
this.StartTimeStamp = System.currentTimeMillis();
this.Run = true;
}
else
{
try {
throw new Exception("the stopwatch are running");
} catch (Exception e) {
e.printStackTrace();
}
}
} |
de74645b-23b1-4ee4-837c-53bd65419f32 | 1 | public void start()
{
if (timerOn)
timer.startTimer();
} |
3268e485-2ff4-4c29-818f-b56d72791fc4 | 4 | public void writeHistory(DataOutput output) {
try {
output.writeInt(VERSION);
int stringCount = stringCombo.getItemCount();
Vector strings = new Vector();
for (int i = 0; i < stringCount; ++i) {
String next= (String) stringCombo.getItemAt(i);
if (!next.trim().equals("")) {
strings.add(next);
}
}
output.writeInt(strings.size());
Iterator iter = strings.iterator();
while (iter.hasNext()) {
output.writeUTF((String) iter.next());
}
} catch (IOException e) {
// NYI
}
} |
4fec36e2-9783-4aac-860e-42df13ce08c5 | 8 | @Override
public void process(Object[] input) {
this.mowers=new ArrayList<Mower>();
if(this.readFile((String)input[1])&&lawn!=null&&mowers!=null&&mowers.size()>0)
{
for(Mower m:mowers)
{
lawn.addMower(m);
}
lawn.startMowers();
for(Mower m:lawn.getMowers())
{
System.out.print(m.getCurrentLocation());
if(!lawn.isInside(m.getCurrentLocation()))System.out.println(" [Out of bound]");
else System.out.println("");
}
for(CollisionException ex:lawn.getCollisions())
{
System.out.println(ex);
}
}else
{
System.err.println("Unable to proceed as input is not complete.");
}
} |
e6792f9b-52a9-499d-bcb0-ef1682951fb6 | 2 | private void jButton1ActionPerformed() {
if(Desktop.isDesktopSupported()){
try {
Desktop.getDesktop().browse(new URI("http://www.twitch.tv/" + TwitchStream.getStreamID(jList1.getModel().getElementAt(jList1.getSelectedIndex()).toString().replace(" (ONLINE)", ""))));
} catch (Exception ignored) {}
}
} |
1c5e413b-7686-4328-9fbf-6d7c9907008b | 9 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//out.println("<html><body>");
// Retrieving Data from the Ajax Post Call
String plane_number = request.getParameter("plane_number");
String flight_number = request.getParameter("flight_number");
String ticket_class = request.getParameter("ticket_class");
String source = request.getParameter("source");
String destination = request.getParameter("destination");
String deptTime = request.getParameter("deptTime");
String arrTime = request.getParameter("arrTime");
String operator = request.getParameter("operator");
String duration = request.getParameter("duration");
int number_of_seats_requested = Integer.parseInt(request.getParameter("number_of_seats"));
// Session
HttpSession session = request.getSession();
int cost_per_ticket = Integer.parseInt((String)session.getAttribute("cost"));
int total_cost = 0;
// Verify the number of seats by getting the flights bean from the session
List<Flights> l =(ArrayList<Flights>) session.getAttribute("flightsBean");
Flights flight_information_object = null;
// Iterate through the list of flight beans to find the plane with the above obtained plane number
for(int i=0;i<l.size();i++){
if(l.get(i).getPlane_number().equals(plane_number)){
// Now check for the availability of tickets
switch (ticket_class) {
case "Economy":
if(l.get(i).getEconomy_available() >= number_of_seats_requested){
total_cost = number_of_seats_requested * cost_per_ticket;
System.out.println("Total Cost Economy: " + total_cost);
}else{
// redirect to error page or search results page
}
break;
case "Business":
if(l.get(i).getBusinessclass_available() >= number_of_seats_requested){
total_cost = (number_of_seats_requested * cost_per_ticket) + 200;
System.out.println("Total Cost BC: " + total_cost);
}else{
// redirect to error page or search results page
}
break;
case "First":
if(l.get(i).getFirstclass_available() >= number_of_seats_requested){
total_cost = (number_of_seats_requested * cost_per_ticket) + 100;
System.out.println("Total Cost FC: " + total_cost);
}else{
// redirect to error page or search results page
}
break;
default:
break;
}
flight_information_object = l.get(i);
break;
}
}
ShoppingCart sc = new ShoppingCart();
sc.setFlight_class(ticket_class);
sc.setFlight_id(flight_number);
sc.setPlane_number(plane_number);
sc.setNumberOfTickets(number_of_seats_requested);
sc.setTotal_cost(total_cost);
sc.setDeparture_time(deptTime);
sc.setArrival_time(arrTime);
sc.setSource(source);
sc.setDestination(destination);
sc.setOperator(operator);
sc.setDuration(duration);
if(session.getAttribute("cart")==null) {
List<ShoppingCart> cart= new ArrayList();
cart.add(sc);
session.setAttribute("cart", cart);
System.out.println("cart is null");
}
else {
List<ShoppingCart> newcart = (List<ShoppingCart>) session.getAttribute("cart");
newcart.add(sc);
session.setAttribute("cart", newcart);
System.out.println("cart != null");
}
out.write("Flight successfully added to cart");
System.out.println("seats: " + number_of_seats_requested);
System.out.println("plane no. " + plane_number);
} |
591904e6-3153-4e0f-a205-e97cdb470d05 | 2 | public OtpErlangTuple receiveMessage() {
System.out.println("Controller:receiveMessage() is working");
try {
OtpErlangObject erlangObject = mbox.receive();
msg = (OtpErlangTuple) erlangObject;
System.out.println(msg);
// if (erlangObject != null ){
// break;
// }
return msg;
} catch (OtpErlangExit e) {
System.out.println("An error catch Controller:receiveMessage() 1");
} catch (OtpErlangDecodeException ex) {
System.out.println("An error catch Controller:receiveMessage() 2");
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
} |
a2ac46a4-d808-4442-a2e1-8af56fd0e1a5 | 7 | public void cleanNotChangedToDama(){
boolean ctd = false;
//Controllo se c'è una mossa che mi fa vincere
for(int i=0;i<desmosse.length;i++)
if(desmosse[i]!=null)
if(desmosse[i].isChangedToDama()){
ctd = true;
break;
}
System.out.println("Variabile che controlla se ci sono mossa che trasformano in dama: "+ctd);
//Se c'è una mossa che mi fa trasformare in dama
if(ctd)
for(int i=0;i<desmosse.length;i++)
if(desmosse[i]!=null)
if(!desmosse[i].isChangedToDama())
desmosse[i]=null;
} |
b2881c31-6862-4c93-911a-92ebc4c0be42 | 5 | public ArrayList<CharImage> extractCharImages(BufferedImage source){
//labeling image to this.labeledImage
labeling(source);
int width = labeledImage[0].length;
int height = labeledImage.length;
HashMap<Integer,CharRange> map = new HashMap<Integer,CharRange>();
ArrayList<CharImage> result = new ArrayList<CharImage>();
//count charactor range
for(int h = 0; h < height; h++){
for(int w = 0; w < width; w++){
int key = labeledImage[h][w];
if(!map.containsKey(key)){
CharRange range = new CharRange(w,h);
map.put(key,range);
}else{
map.get(key).update(w,h);
}
}
}
//crop charactor
Integer[] keys = new Integer[map.keySet().size()];
map.keySet().toArray(keys);
Arrays.sort(keys);
for(Integer key : keys){
CharRange range = map.get(key);
if(range.isValid()){
result.add(new CharImage(key,labeledImage,range));
}
}
return result;
} |
0872dae6-d87d-4bb2-92b8-192cf6f2224e | 7 | private boolean ctrlFields() {
if (ztAdresse.getText().isEmpty() ||
ztNom.getText().isEmpty() ||
ztPrenom.getText().isEmpty() ||
ztNumeroNational.getText().isEmpty() ||
ztTel.getText().isEmpty() ||
dpDateNaissance.getDate() == null ||
dpDebutTravail.getDate() == null ) {
return false;
} else {
return true;
}
} |
0c131812-fbc0-49e7-a3b0-00875a5b543e | 3 | private String getUsers(String data) throws Exception{
users = null;
users = new ArrayList<String>();
String userlist = "";
String begin = "<!--unameb-->";
String end = "<!--unamee-->";
String _tmp = data;
while (_tmp.indexOf(begin) != -1) {
int i = _tmp.indexOf(begin)+begin.length();
int k = _tmp.indexOf(end);
int m = k+end.length();
users.add(_tmp.substring(i,k).toLowerCase().trim());
_tmp = _tmp.substring(m);
}
Collections.sort(users);
ListIterator<String> it = users.listIterator();
while(it.hasNext()){
String tmp = (String)it.next();
System.out.println("tmp: "+tmp);
StringTokenizer tokenizer = new StringTokenizer((String)userdata.get(tmp), ":");
String username = tokenizer.nextToken();
String userid = tokenizer.nextToken();
String isaway = tokenizer.nextToken();
String userline = "<a href=\"http://"+config.getHost()+":"+config.getPort()+config.getComstring()+";jsessionid="+sessionID+
"?showreg="+userid+"&auth=1&design=0\">"+username+"</a><br>";
if (isaway.equals("true")) {
userline = "<i>"+userline+"</i>";
}
userlist += userline;
}
return userlist;
} |
0fe052e0-46db-428c-9d8c-6e10f13e7b7c | 0 | public String getSessionId() {
return sessionId;
} |
84744861-a896-45e8-bb0b-37aecc037574 | 6 | public static void main(String[] args) {
// Testing FileSet factory
FileSet aFileSet, bFileSet, cFileSet;
String testFile = "C:\\temp\\SerializedFileSet.sfs";
String testDirectory = "S:\\";
aFileSet = null;
bFileSet = null;
if(args.length < 2){
System.out.println("Please, specify valid parameters.");
System.out.println(
"example Test.jar C:\\temp\\SerializedFileSet.sfs S:\\");
System.exit(-1);
}else{
testFile = args[0];
testDirectory = args[1];
}
try {
aFileSet = FileSetFactory.getFileSet(testDirectory);
System.out.println("Generated FileSet:");
System.out.println(aFileSet);
} catch (IOException e) {
System.out.println(
"Exception while getting FileSet. " + e.getMessage());
System.exit(-1);
}
//Reading FileSet from file
try{
bFileSet = FileSetFactory.readFileSet(testFile);
System.out.println("Read FileSet:");
System.out.println(bFileSet);
} catch (Exception e){
System.out.println(
"Exception while reading FileSet." + e.getMessage());
try {
FileSetFactory.writeFileSet(testFile, aFileSet);
System.out.println("New file was saved.");
} catch (IOException ex) {
System.out.println(
"Exception while getting FileSet. " + ex.getMessage());
System.exit(-1);
} finally{
System.exit(-1);
}
}
//Printing out FileSet content
//aFileSet.stream().forEachOrdered(v -> System.out.println(
// v.getKey() + " " + v.getValue()));
//Comparing file sets
cFileSet = FileSetFactory.getModifiedFiles(bFileSet, aFileSet);
if(null != cFileSet){
System.out.println(cFileSet.size() + " files were changed.");
cFileSet.stream()
.forEachOrdered(v -> System.out.println(v.getKey()));
}else{
System.out.println("File sets are not equal");
}
//Saving FileSet to file
try {
FileSetFactory.writeFileSet(testFile, aFileSet);
} catch (IOException e) {
System.out.println(
"Exception while getting FileSet. " + e.getMessage());
System.exit(-1);
}
} |
a4b36aaf-d1ec-4ca1-8adc-14f17f13b59c | 4 | private void initSimplexe(Matrice ciDansB, Matrice iDansB)
{
int colN = 0;
int colB = 0;
int nbN = 0;
for(int i = 0; i<this.X.getNbColumns(); i++)
{
if(this.X.getValueAt(0, i) == 0)
{
nbN++;
}
}
this.B = new Matrice(this.A.getNbLines(), this.A.getNbColumns() - nbN);
this.N = new Matrice(this.A.getNbLines(), nbN);
for(int i = 0; i<this.X.getNbColumns(); i++)
{
if(this.X.getValueAt(0, i) == 0)
{
copyColumn(i, colN, this.A, this.N);
colN++;
}
else
{
copyColumn(i, colB, this.A, this.B);
ciDansB.setValueAt(colB, 0, this.contraintes.getValueAt(0, i));
iDansB.setValueAt(colB, 0, i);
colB++;
}
}
System.out.println("\n===> Init Simplexe :\n");
System.out.println("i appartenant à B :\n");
iDansB.printMatrice();
System.out.println("\nMatrice B :\n");
this.B.printMatrice();
System.out.println("\nMatrice N :\n");
this.N.printMatrice();
} |
a22fed12-1fa4-4bf4-ab24-be72a1b09dd9 | 8 | public void paintComponent(Graphics canvas)
{
canvas.setColor(Color.WHITE);
//Make sure the outside of the board is white.
canvas.fillRect(0, 0, this.cols * X_DIM + 2*X_OFFSET, this.rows * Y_DIM + 2*Y_OFFSET);
/*Placing the squares on the board*/
for(int i=0; i<this.rows; i++) {
for(int j=0; j<this.cols; j++) {
if((i+j)%2 == 1) {
canvas.setColor(GRID_COLOR_A);
} else {
canvas.setColor(GRID_COLOR_B);
}
canvas.fillRect(X_OFFSET + j * X_DIM, Y_OFFSET + i * Y_DIM, X_DIM, Y_DIM);
}
}
/*Placing the pegs: */
// CHANGE THIS DISPLAY FUNCTION
for(int i=0; i<this.rows; i++) {
for(int j=0; j<this.cols; j++) {
if(this.pegPlaced[i][j]) {
canvas.setColor(this.pegsColour[i][j]);
canvas.fillOval(X_OFFSET + j * X_DIM + X_DIM/4, Y_OFFSET + i * Y_DIM + Y_DIM/4, X_DIM/2, Y_DIM/2);
} else if(this.kingPlaced[i][j]) {
//Draw something that makes it more king looking...:
//Encircle it with black! (lazy solution...)
canvas.setColor(BLACK);
canvas.fillOval(X_OFFSET + j * X_DIM + X_DIM/8, Y_OFFSET + i * Y_DIM + Y_DIM/8, (X_DIM * 6)/8, (Y_DIM*6)/8);
//TODO: Make kings look better. (optional)
canvas.setColor(this.pegsColour[i][j]);
canvas.fillOval(X_OFFSET + j * X_DIM + X_DIM/4, Y_OFFSET + i * Y_DIM + Y_DIM/4, X_DIM/2, Y_DIM/2);
}
}
}
/*I want the Turkey */ //canvas.setFont(
/*Printing the display board*/
canvas.setColor(BLACK);
if(messageBoard != null) {
canvas.drawString(messageBoard, X_OFFSET, Y_OFFSET + this.rows * Y_DIM + Y_DIM);
}
} |
54eae530-451f-4a24-ac2f-76113aa3ef15 | 0 | public String getBookChapter(int book, int chapter) {
String strBook = String.format("B%02d", book);
String strChapter = String.format("C%03d", chapter);
return strBook + strChapter;
} |
5d62f4af-bdb8-4fc1-8783-bdf12feee68c | 3 | public List<TaxaNode[]> completeHierarchyPerTaxon(){
List<TaxaNode[]> completeHierarchy = new ArrayList<TaxaNode[]>();
TaxaNode t = null;
TaxaNode[] th = null;
for(String key: this.nodeList.keySet()){
t = this.nodeList.get(key);
if(TaxonRank.SPECIES == t.getTaxonRank() ||
TaxonRank.SUBSPECIES == t.getTaxonRank()){
th = this.fullHierarchy(t);
completeHierarchy.add(th);
}
}
return completeHierarchy;
} |
dc149953-72a1-4584-a482-6001af419fd8 | 4 | private JPanel getPanSaisieCle() {
if (panSaisieCle == null) {
GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
gridBagConstraints8.gridx = 4;
gridBagConstraints8.gridy = 6;
GridBagConstraints gridBagConstraints61 = new GridBagConstraints();
gridBagConstraints61.gridx = 5;
gridBagConstraints61.gridy = 7;
vide8 = new JLabel();
vide8.setText(" ");
GridBagConstraints gridBagConstraints51 = new GridBagConstraints();
gridBagConstraints51.gridx = 5;
gridBagConstraints51.gridy = 6;
vide7 = new JLabel();
vide7.setText(" ");
GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
gridBagConstraints41.gridx = 5;
gridBagConstraints41.gridy = 3;
vide6 = new JLabel();
vide6.setText(" ");
GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
gridBagConstraints31.gridx = 5;
gridBagConstraints31.gridy = 2;
vide5 = new JLabel();
vide5.setText(" ");
GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
gridBagConstraints21.fill = GridBagConstraints.BOTH;
gridBagConstraints21.gridwidth = 3;
gridBagConstraints21.gridy = 5;
gridBagConstraints21.weightx = 1.0;
gridBagConstraints21.gridx = 2;
gridBagConstraints21.gridheight = 1;
GridBagConstraints gridBagConstraints121 = new GridBagConstraints();
gridBagConstraints121.gridwidth = 4;
gridBagConstraints121.gridy = 4;
gridBagConstraints121.gridx = 4;
labSaisieCle = new JLabel();
if(this.selectionne.creerCode() instanceof ICodeClePublique) {
if(this.decrypte) {
labSaisieCle.setText("Ou saisie manuelle de la cl (prive ou complte):");
}
else {
labSaisieCle.setText("Ou saisie manuelle de la cl (publique ou complte):");
}
}
else {
labSaisieCle.setText("Ou saisie manuelle de la cl:");
}
panSaisieCle = new JPanel();
panSaisieCle.setLayout(new GridBagLayout());
panSaisieCle.add(labSaisieCle, gridBagConstraints121);
panSaisieCle.add(getTextSaisieCle(), gridBagConstraints21);
panSaisieCle.add(vide5, gridBagConstraints31);
panSaisieCle.add(vide6, gridBagConstraints41);
panSaisieCle.add(vide7, gridBagConstraints51);
panSaisieCle.add(vide8, gridBagConstraints61);
if(!decrypte) {
panSaisieCle.add(getButGenererCle(), gridBagConstraints8);
}
}
return panSaisieCle;
} |
e2a78e98-a4a6-4b41-8736-a1cb2bd8eb0b | 5 | public void imprimirRelatorioSQLNoRelatorio(Map parametros, String diretorio) {
Connection conn = null;
try {
// Carrega conexão via JDBC
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/smdados", "root", "mutkch");
// Preenche o relatório com os dados
JasperPrint print = JasperFillManager.fillReport(diretorio, parametros, conn);
// Exibe visualização dos dados
JasperViewer.viewReport(print, false);
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Erro ao localizar a classe responsável pela geração do relatório!\n" + ex.getMessage());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao executar consulta no Banco de dados!\n" + ex.getMessage());
} catch (JRException ex) {
JOptionPane.showMessageDialog(null, "Erro ao gerar relatório!\n" + ex.getMessage());
}catch(NoResultException e){
System.out.println("vazio");
}finally {
try {
conn.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao fechar conexão com o Banco de Dados.");
}
}
} |
e6dc4f99-0f9e-4662-8a3c-fe7041328d7a | 4 | public void loadServers(Bot bot, ResultSet rs) {
// If something goes wrong...
if (rs == null) {
logMessage(LOGLEVEL_CRITICAL, "Unable to load servers from MySQL!");
return;
}
// Go through each server and initialize them accordingly
int database_id = -1;
try {
Server server;
while (rs.next()) {
// The server should be marked as online, if it's not then skip it
if (rs.getInt("online") == SERVER_ONLINE) {
database_id = rs.getInt("id");
server = new Server(); // Reference a new object each time we run through the servers
server.bot = bot;
server.buckshot = (rs.getInt("buckshot") == 1);
server.compatflags = rs.getInt("compatflags");
server.compatflags2 = rs.getInt("compatflags2");
server.config = rs.getString("config");
server.dmflags = rs.getInt("dmflags");
server.dmflags2 = rs.getInt("dmflags2");
server.dmflags3 = rs.getInt("dmflags3");
server.enable_skulltag_data = (rs.getInt("enable_skulltag_data") == 1);
server.gamemode = rs.getString("gamemode");
server.host_command = rs.getString("host_command");
server.instagib = (rs.getInt("instagib") == 1);
server.irc_channel = rs.getString("irc_channel");
server.irc_hostname = rs.getString("irc_hostname");
server.irc_login = rs.getString("irc_login");
server.iwad = rs.getString("iwad");
server.mapwads = rs.getString("mapwads").replace(" ","").split(","); // Check this!
// server.play_time = 0; // NOT IN THE DATABASE
server.rcon_password = rs.getString("rcon_password");
server.sender = rs.getString("username"); // ???
server.server_id = rs.getString("unique_id"); // ???
server.servername = rs.getString("servername");
server.time_started = rs.getLong("time_started");
server.user_level = 0; // ??? Get from Mysql
//server.wads = rs.getString("wads").replace(" ","").split(","); // Check this!
// Handle the server (pass it to the appropriate places before referencing a new object) (server.port and server.serverprocess)
logMessage(LOGLEVEL_NORMAL, "Successfully processed server id " + database_id + "'s data.");
server.serverprocess = new ServerProcess(server);
server.serverprocess.start();
}
}
} catch (SQLException e) {
logMessage(LOGLEVEL_CRITICAL, "MySQL exception loading servers at " + database_id + "!");
e.printStackTrace();
}
} |
ff4999ad-07d4-48ca-9537-13723d360b7b | 2 | @Override
public Set<String> getUserNames() {
Set<String> users = new HashSet<String>();
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
pStmt = conn.prepareStatement("SELECT * FROM USER ORDER BY surname;");
rs = pStmt.executeQuery();
while (rs.next()) {
users.add(rs.getString("surname") + " " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResource(pStmt);
closeResource(rs);
}
return users;
} |
f82b2ac3-6489-4616-9d7b-7ef73d2a8f85 | 9 | @Override
public Scalar getScalar(String key) {
if ("%localData".equals(key)) {
return SleepUtils.getHashWrapper(data);
}
Scalar temp = (Scalar) data.get(key);
if (temp == null && parmsValue != null && (Character.isDigit(key.charAt(1)) || key.charAt(1) == '-')) {
StringParser parser;
int begin, end;
TokenizedString tokenizer = new TokenizedString(parmsValue, " ");
//
// look for $n-m pattern and return tokens n to m in a sequence
//
parser = new StringParser(key, rangePattern);
if (parser.matches()) {
begin = Integer.parseInt(parser.getParsedStrings()[0]);
end = Integer.parseInt(parser.getParsedStrings()[1]);
return SleepUtils.getScalar(tokenizer.getTokenRange(begin, end));
}
//
// look for $n- pattern and return tokens n on up in a sequence
//
parser = new StringParser(key, rangeToPattern);
if (parser.matches()) {
begin = Integer.parseInt(parser.getParsedStrings()[0]);
return SleepUtils.getScalar(tokenizer.getTokenTo(begin));
}
//
// look for $-m pattern and return tokens up to m in a sequence
//
parser = new StringParser(key, rangeFromPattern);
if (parser.matches()) {
begin = Integer.parseInt(parser.getParsedStrings()[0]);
return SleepUtils.getScalar(tokenizer.getTokenFrom(begin));
}
//
// look for $n pattern and return token n.
//
parser = new StringParser(key, normalPattern);
if (parser.matches()) {
begin = Integer.parseInt(parser.getParsedStrings()[0]);
return SleepUtils.getScalar(tokenizer.getToken(begin));
}
}
return temp;
} |
11402f99-2e8a-4678-bfdc-15f5d07230ac | 0 | public DatatypeProperty getDatatypeProperty(OntModel model) {
return model.createDatatypeProperty(getUri());
} |
f95cb046-a49d-4039-adb2-42aa9325bf48 | 6 | public void init()
{
boolean debug = CommandLine.booleanVariable("debug");
if (debug)
{
// Enable debug logging
Logger logger = Logger.getLogger("com.reuters.rfa");
logger.setLevel(Level.FINE);
Handler[] handlers = logger.getHandlers();
if (handlers.length == 0)
{
Handler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
logger.addHandler(handler);
}
for (int index = 0; index < handlers.length; index++)
handlers[index].setLevel(Level.FINE);
}
Context.initialize();
// Create a Session
String sessionName = CommandLine.variable("session");
_session = Session.acquire(sessionName);
if (_session == null)
{
System.out.println("Could not acquire session.");
Context.uninitialize();
System.exit(1);
}
System.out.println("RFA Version: " + Context.getRFAVersionInfo().getProductVersion());
// Create an Event Queue
_eventQueue = EventQueue.create("myEventQueue");
// Create a OMMPool.
_pool = OMMPool.create();
// Create an OMMEncoder
_encoder = _pool.acquireEncoder();
_encoder.initialize(OMMTypes.MSG, 5000);
// Initialize client for login domain.
_loginClient = new PrivateStrmGenMsgLoginClient(this);
// Initialize item manager for item domains
_itemManager = new PrivateStrmGenMsgItemManager(this);
// Initialize directory client for directory domain.
_directoryClient = new PrivateStrmGenMsgDirClient(this);
// Create an OMMConsumer event source
_ommConsumer = (OMMConsumer)_session.createEventSource(EventSource.OMM_CONSUMER,
"myOMMConsumer", true);
// Application may choose to down-load the enumtype.def and
// RWFFldDictionary
// This example program loads the dictionaries from file only.
String fieldDictionaryFilename = CommandLine.variable("rdmFieldDictionary");
String enumDictionaryFilename = CommandLine.variable("enumType");
try
{
PSGenericOMMParser.initializeDictionary(fieldDictionaryFilename, enumDictionaryFilename);
}
catch (DictionaryException ex)
{
System.out.println("ERROR: Unable to initialize dictionaries.");
System.out.println(ex.getMessage());
if (ex.getCause() != null)
System.err.println(": " + ex.getCause().getMessage());
cleanup(-1);
return;
}
// Send login request
// Application must send login request first
_loginClient.sendRequest();
} |
8a86daa7-842e-4f14-aeb1-a3489cb8515b | 8 | static WeiboMessage parseInfo(Node infoNode) throws UnsupportedEncodingException {
WeiboMessage msg = new WeiboMessage();
Span spanNode = (Span) Util.getFirstChildByTagName(infoNode, "span");
SimpleNodeIterator aNodeIter = Util.getChildrenByTagName(spanNode, "a")
.elements();
while (aNodeIter.hasMoreNodes()) {
LinkTag aNode = (LinkTag) aNodeIter.nextNode();
String innerText = aNode.getLinkText();
if (innerText.indexOf("转发(") >= 0) {
msg.repostCount = new Integer(innerText.substring(
innerText.indexOf("(") + 1, innerText.indexOf(")")));
} else if (innerText.indexOf("评论(") >= 0) {
msg.commentCount = new Integer(innerText.substring(
innerText.indexOf("(") + 1, innerText.indexOf(")")));
}
}
LinkTag aNode = (LinkTag) infoNode
.getChildren()
.extractAllNodesThatMatch(
new AndFilter(new TagNameFilter("a"),
new HasAttributeFilter("class", "date")))
.elementAt(0);
if (aNode.getAttribute("date") != null
&& aNode.getAttribute("date").length() > 0)
msg.postTime = new Date(new Long(aNode.getAttribute("date")));
msg.url = aNode.getLink();
Node aSourceNode = aNode.getNextSibling();
while (!aSourceNode.getClass().toString().endsWith(".tags.LinkTag")) {
aSourceNode = aSourceNode.getNextSibling();
if (aSourceNode == null)
break;
}
if (aSourceNode != null) {
LinkTag aSourceTag = (LinkTag) aSourceNode;
String[] postSource = new String[] { aSourceTag.getLinkText(),
aSourceTag.getLink() };
msg.postSource = postSource;
}
return msg;
} |
06328940-d05b-4dcd-a340-af9a7d7d6978 | 1 | public CachedRowSetImpl getRanking(){
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String url = "jdbc:derby:" + DBName;
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String getRanking = "SELECT jnick AS Jamertag, Level, points FROM USERS ORDER BY POINTS DESC FETCH FIRST 100 ROWS ONLY";
CachedRowSetImpl rowSet = new CachedRowSetImpl();
rowSet.populate(statement.executeQuery(getRanking));
statement.close();
connection.close();
return rowSet;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} |
16bb5f27-e414-45c0-9e3d-1a086e8bda49 | 0 | private boolean isValidInput(final String s) {
return s.matches("[0-9]{4}[-][0-9]{1,2}");
} |
15e4092e-fc76-4a65-bdb4-817a55c22248 | 9 | public static ArrayList<User> getAllUsers() {
String url = "jdbc:mysql://localhost:3306/ouaamou_com";
String username = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
ArrayList<User> users = new ArrayList<User>();
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
result = statement.executeQuery("SELECT id, first_name, last_name, email, phone_number FROM dw_user");
User user = new User();
while(result.next()) {
user.setId(result.getInt("id"));
user.setFirstName(result.getString("first_name"));
user.setLastName(result.getString("last_name"));
user.setEmail(result.getString("email"));
user.setPhoneNumber(result.getString("phone_number"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (result != null) {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return users;
} |
9ce86b92-90db-4987-8cc1-a58cb4d29cb4 | 3 | public static String compileToHSAIL(String openCLSource, String baseName, String batchScript) {
// return compileToHSAILJNI(openCLSource);
try {
final String oclFileName = baseName + ".ocl";
final String binFileName = baseName + ".bin";
final String hsailFileName = baseName + ".hsail";
// Set up source input file for hsail tools
FileOutputStream fos = new FileOutputStream(oclFileName);
fos.write(openCLSource.getBytes());
fos.flush();
fos.close();
executeCmd("aoc2", "-m64", "-I./", "-march=hsail", oclFileName);
executeCmd("HSAILasm", "-disassemble", "-o", hsailFileName, binFileName);
// Now the .hsail file should exist
FileInputStream fis = new FileInputStream(hsailFileName);
BufferedReader d = new BufferedReader(new InputStreamReader(fis));
StringBuffer hsailSourceBuffer = new StringBuffer();
String line;
String cr = System.getProperty("line.separator");
do {
line = d.readLine();
if (line != null) {
hsailSourceBuffer.append(line);
hsailSourceBuffer.append(cr);
}
} while (line != null);
String result = hsailSourceBuffer.toString();
return result;
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
return null;
}
} |
2627f3b9-3fcf-4854-b312-45ba82de0558 | 2 | public MCQ getModel(int Question_ID) {
MCQ mcquestion = new MCQ();
try {
StringBuffer sql = new StringBuffer("");
sql.append("SELECT Question_ID,QType_ID,Question_Text");
sql.append(" FROM `MCQ`");
sql.append(" where Question_ID=" + Question_ID);
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
ResultSet rs = sQLHelper.runQuery(sql.toString());
while (rs.next()) {
mcquestion.setQtype_ID(rs.getInt("QType_ID"));
mcquestion.setQuestion_ID(rs.getInt("Question_ID"));
mcquestion.setQuestion_Text(rs.getString("Question_Text"));
}
} catch (SQLException ex) {
Logger.getLogger(MCQ.class.getName()).log(Level.SEVERE, null, ex);
}
return mcquestion;
} |
a6ddd33a-11b9-46a4-bd3a-cc87a8a8a298 | 9 | @Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String view = "/WEB-INF/view/receiver/";
ReceiverCommand rcommand = null;
if (request.getParameter("buttonShowAll") != null) {
rcommand = new GetAllReceiverCommand();
view += "showall.jsp";
} else if (request.getParameter("buttonNew") != null) {
view += "new.jsp";
} else if (request.getParameter("buttonCreate") != null) {
rcommand = new CreateReceiverCommand();
view += "showall.jsp";
} else if (request.getParameter("buttonSearch") != null) {
view += "search.jsp";
} else if (request.getParameter("buttonDelete") != null) {
rcommand = new DeleteReceiverCommand();
view += "showall.jsp";
} else if (request.getParameter("buttonSearchByName") != null) {
rcommand = new SearchReceiverCommand();
view += "showall.jsp";
} else if (request.getParameter("buttonEdit") != null) {
rcommand = new EditReceiverCommand();
view += "edit.jsp";
} else if (request.getParameter("buttonUpdate") != null) {
rcommand = new UpdateReceiverCommand();
view += "showall.jsp";
} else {
view += "manage.jsp";
}
if (rcommand != null) {
rcommand.execute(request);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.include(request, response);
} |
ec3788ad-db36-45a8-8700-9fe912be12b1 | 3 | @SuppressWarnings("unchecked")
private static ArrayList<String> getCategoryCodes(
HashMap<String, Object> map) {
ArrayList<String> list = new ArrayList<String>();
Map<String, Object> attrs = (Map<String, Object>) map.get("attributes");
for (Object m : (ArrayList<Object>) attrs.get("subjects")) {
String name = ((Map<String, String>) m).get("title");
if (name != null && !name.isEmpty())
list.add(makeIdSafe(name));
}
return list;
} |
29bb51a3-3db3-492b-871a-eb66e81e3d86 | 2 | public static long task3(long x) {
long a = 2;
while (x > 1) {
if ((x % a) == 0) {
x = x / a;
} else {
a++;
}
}
return a;
} |
3da1ce22-8634-43a0-91c1-841cbbd1a451 | 0 | public LRParseController(LRParsePane pane) {
this.pane = pane;
productions = pane.grammar.getProductions();
} |
da63f699-3662-44e4-9a5c-1237fbb6d830 | 8 | public void TelnetRead(StringBuffer buf, InputStream rawin, BufferedReader in[]) throws InterruptedIOException, IOException
{
final char c = (char) in[0].read();
if (mccppattern[patDex] == c)
{
patDex++;
if ((patDex >= mccppattern.length) && (!neverSupportMCCP))
{
while (rawin.available() > 0)
rawin.read();
final ZInputStream zIn = new ZInputStream(rawin);
if (debugTelnetCodes)
System.out.println("MCCP compression started");
in[0] = new BufferedReader(new InputStreamReader(zIn));
patDex = 0;
}
return;
}
else
if (patDex > 0)
{
for (int i = 0; i < patDex; i++)
buf.append(mccppattern[i]);
patDex = 0;
}
buf.append(c);
if (c == 65535)
throw new java.io.InterruptedIOException("ARGH!");
} |
ddf18810-c315-4952-80d4-7534002b7db1 | 9 | private void createDocumentNodes(List listNodes, CleanTimeValues cleanTimeValues) {
Iterator it = listNodes.iterator();
while (it.hasNext()) {
Object child = it.next();
if (child == null) {
continue;
}
boolean toAdd = true;
if (child instanceof TagNode) {
TagNode node = (TagNode) child;
TagInfo tag = getTagInfoProvider().getTagInfo( node.getName() );
addPossibleHeadCandidate(tag, node, cleanTimeValues);
} else {
if (child instanceof ContentNode) {
toAdd = !"".equals(child.toString());
}
}
if (toAdd) {
cleanTimeValues.bodyNode.addChild(child);
}
}
// move all viable head candidates to head section of the tree
Iterator headIterator = cleanTimeValues._headTags.iterator();
while (headIterator.hasNext()) {
TagNode headCandidateNode = (TagNode) headIterator.next();
// check if this node is already inside a candidate for moving to head
TagNode parent = headCandidateNode.getParent();
boolean toMove = true;
while (parent != null) {
if ( cleanTimeValues._headTags.contains(parent) ) {
toMove = false;
break;
}
parent = parent.getParent();
}
if (toMove) {
headCandidateNode.removeFromTree();
cleanTimeValues.headNode.addChild(headCandidateNode);
}
}
} |
604aa0d6-9594-4f61-91b8-60fc9b5b0d88 | 2 | @Override
public void terminateSimulation(Host... network) {
logger_.debug("Hello");
for (Host host : network) {
logger_.debug("Trying to get a handle to {}:{}", host, host.getPort());
try {
SimulationHandle simulationHandle = getRemoteHandle(host);
logger_.debug("I have a handle to {}:{}", host, host.getPort());
simulationHandle.terminateSimulation();
logger_.info("{}:{} terminated.", host, host.getPort());
} catch (CommunicationException e) {
logger_.warn("{}:{} is already terminated.", host, host.getPort());
}
}
} |
2a2245b7-3e95-4ec4-acf4-4bf72fcb706d | 8 | public void removeComponent(Component component)
{
if(component instanceof InteractableContainer) {
InteractableContainer container = (InteractableContainer)component;
if(container.hasInteractable(currentlyInFocus)) {
Interactable original = currentlyInFocus;
Interactable current = contentPane.nextFocus(original);
while(container.hasInteractable(current) && original != current)
current = contentPane.nextFocus(current);
if(container.hasInteractable(current))
setFocus(null);
else
setFocus(current);
}
}
else if(component == currentlyInFocus)
setFocus(contentPane.nextFocus(currentlyInFocus));
contentPane.removeComponent(component);
for(ComponentInvalidatorAlert invalidatorAlert: invalidatorAlerts) {
if(component == invalidatorAlert.component) {
component.removeComponentListener(invalidatorAlert);
invalidatorAlerts.remove(invalidatorAlert);
break;
}
}
} |
4f4c81a7-8e4f-4767-8db1-d34ff869791c | 2 | public static Move TakeUserInput(int r1, int c1){
// Display the game board
Game.board.Display();
PrintSeparator('-');
// Ask for user input
System.out.println("Enter your Move.");
System.out.println("Piece To Move:");
System.out.print("\tRow(0-7): ");
if (r1==-1){
r1 = TakeInput();
}
else{
System.out.println(r1);
}
System.out.print("\tCol(0-7): ");
if (c1==-1){
c1 = TakeInput();
}
else{
System.out.println(c1);
}
System.out.println("Where To Move:");
System.out.print("\tRow(0-7): ");
int r2 = TakeInput();
System.out.print("\tCol(0-7): ");
int c2 = TakeInput();
return new Move(r1,c1,r2,c2);
} |
b567a71f-9363-4f32-8e35-69c4b20f5a47 | 0 | public void write(String symbol) {
buffer.deleteCharAt(tapeHead);
buffer.insert(tapeHead, symbol);
cachedHash = 0xdeadbeef;
} |
3db6f896-b0f8-4fb8-8a3f-24b2a34356ee | 3 | @Override
public boolean canImport(JComponent comp, DataFlavor[] flavors)
{
for (int i = 0; i < flavors.length; i++)
{
if (flavors[i] != null
&& flavors[i].equals(mxGraphTransferable.dataFlavor))
{
return true;
}
}
return false;
} |
b425f2c2-2ca2-4b36-bc86-7df6f7a19d35 | 7 | public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
} |
e57cc3da-830a-466f-88cc-4c325037e691 | 9 | public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
if (averageGroundLevel < 0)
{
averageGroundLevel = getAverageGroundLevel(par1World, par3StructureBoundingBox);
if (averageGroundLevel < 0)
{
return true;
}
boundingBox.offset(0, ((averageGroundLevel - boundingBox.maxY) + 6) - 1, 0);
}
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 0, 9, 4, 6, 0, 0, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 0, 9, 0, 6, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 4, 0, 9, 4, 6, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 5, 0, 9, 5, 6, Block.field_72079_ak.blockID, Block.field_72079_ak.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 1, 8, 5, 5, 0, 0, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 0, 2, 3, 0, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 0, 0, 4, 0, Block.wood.blockID, Block.wood.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 0, 3, 4, 0, Block.wood.blockID, Block.wood.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 6, 0, 4, 6, Block.wood.blockID, Block.wood.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.planks.blockID, 0, 3, 3, 1, par3StructureBoundingBox);
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 2, 3, 3, 2, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 1, 3, 5, 3, 3, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 1, 0, 3, 5, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 6, 5, 3, 6, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 5, 1, 0, 5, 3, 0, Block.fence.blockID, Block.fence.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 9, 1, 0, 9, 3, 0, Block.fence.blockID, Block.fence.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 6, 1, 4, 9, 4, 6, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.lavaMoving.blockID, 0, 7, 1, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.lavaMoving.blockID, 0, 8, 1, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fenceIron.blockID, 0, 9, 2, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fenceIron.blockID, 0, 9, 2, 4, par3StructureBoundingBox);
fillWithBlocks(par1World, par3StructureBoundingBox, 7, 2, 4, 8, 2, 5, 0, 0, false);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 6, 1, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stoneOvenIdle.blockID, 0, 6, 2, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stoneOvenIdle.blockID, 0, 6, 3, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.field_72085_aj.blockID, 0, 8, 1, 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 2, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 2, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 2, 1, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.pressurePlatePlanks.blockID, 0, 2, 2, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.planks.blockID, 0, 1, 1, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, getMetadataWithOffset(Block.stairCompactPlanks.blockID, 3), 2, 1, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactPlanks.blockID, getMetadataWithOffset(Block.stairCompactPlanks.blockID, 1), 1, 1, 4, par3StructureBoundingBox);
if (!hasMadeChest)
{
int i = getYWithOffset(1);
int l = getXWithOffset(5, 5);
int j1 = getZWithOffset(5, 5);
if (par3StructureBoundingBox.isVecInside(l, i, j1))
{
hasMadeChest = true;
func_74879_a(par1World, par3StructureBoundingBox, par2Random, 5, 1, 5, field_74918_a, 3 + par2Random.nextInt(6));
}
}
for (int j = 6; j <= 8; j++)
{
if (getBlockIdAtCurrentPosition(par1World, j, 0, -1, par3StructureBoundingBox) == 0 && getBlockIdAtCurrentPosition(par1World, j, -1, -1, par3StructureBoundingBox) != 0)
{
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), j, 0, -1, par3StructureBoundingBox);
}
}
for (int k = 0; k < 7; k++)
{
for (int i1 = 0; i1 < 10; i1++)
{
clearCurrentPositionBlocksUpwards(par1World, i1, 6, k, par3StructureBoundingBox);
fillCurrentPositionBlocksDownwards(par1World, Block.cobblestone.blockID, 0, i1, -1, k, par3StructureBoundingBox);
}
}
spawnVillagers(par1World, par3StructureBoundingBox, 7, 1, 1, 1);
return true;
} |
f8c8e9e2-c807-4b9b-b4ed-5acfb87c7dd2 | 8 | public void clear(){
for(int i=0;i<modes;i++){ mode_param[i]=null; }
mode_param=null;
for(int i=0;i<maps;i++){ // unpack does the range checking
FuncMapping.mapping_P[map_type[i]].free_info(map_param[i]);
}
map_param=null;
for(int i=0;i<times;i++){ // unpack does the range checking
FuncTime.time_P[time_type[i]].free_info(time_param[i]);
}
time_param=null;
for(int i=0;i<floors;i++){ // unpack does the range checking
FuncFloor.floor_P[floor_type[i]].free_info(floor_param[i]);
}
floor_param=null;
for(int i=0;i<residues;i++){ // unpack does the range checking
FuncResidue.residue_P[residue_type[i]].free_info(residue_param[i]);
}
residue_param=null;
// the static codebooks *are* freed if you call info_clear, because
// decode side does alloc a 'static' codebook. Calling clear on the
// full codebook does not clear the static codebook (that's our
// responsibility)
for(int i=0;i<books;i++){
// just in case the decoder pre-cleared to save space
if(book_param[i]!=null){
book_param[i].clear();
book_param[i]=null;
}
}
//if(vi->book_param)free(vi->book_param);
book_param=null;
for(int i=0;i<psys;i++){
psy_param[i].free();
}
//if(vi->psy_param)free(vi->psy_param);
//memset(vi,0,sizeof(vorbis_info));
} |
79be4774-155d-4da0-8385-c5603160965a | 9 | @Override
public void characters(char[] ch, int start, int length) throws SAXException
{
if (ch != null)
{
String s = new String(ch, start, length).trim();
if (product == null || s.length() < 1)
{
return;
}
else
{
if (qName.equalsIgnoreCase(ProductsConstants.PROVIDER.getContent()))
{
product.setProvider(s);
}
else
{
if (qName.equalsIgnoreCase(ProductsConstants.MODEL.getContent()))
{
product.setModel(s);
}
else
{
if (qName.equalsIgnoreCase(ProductsConstants.COLOR.getContent()))
{
product.setColor(s);
}
else
{
if (qName.equalsIgnoreCase(ProductsConstants.DATE.getContent()))
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date utilDate = null;
try
{
utilDate = dateFormat.parse(s);
}
catch (ParseException e)
{
log.error("Can't parse date", e);
}
product.setDateOfIssue(utilDate);
}
else
{
if (qName.equalsIgnoreCase(ProductsConstants.PRICE.getContent()))
{
product.setPrice(s);
}
}
}
}
}
}
}
} |
10f53d42-6a2d-4831-956a-5803bab4e8f1 | 9 | public void testClear() {
ByteArrayBuilder builder = new ByteArrayBuilder();
byte[] testdata = new byte[1024];
for(int i=0;i<testdata.length;i++) {
testdata[i] = (byte)i;
}
builder.clear();
for(int i=0;i<testdata.length;i++) {
assertEquals(i, builder.length());
builder.append(testdata[i]);
// check
{
byte[] result = builder.getBuffer();
int s = 0;
int e = builder.length();
assertEquals(i+1, e);
if(i==0||i%LEVEL==0){
for(int j=s;j<e;j++) {
assertEquals((byte)j, result[j]);
}
}
}
}
builder.clear();
for(int i=0;i<testdata.length;i++) {
assertEquals(i, builder.length());
builder.append(testdata[i]);
// check
{
byte[] result = builder.getBuffer();
int s = 0;
int e = builder.length();
assertEquals(i+1, e);
if(i==0||i%LEVEL==0){
for(int j=s;j<e;j++) {
assertEquals((byte)j, result[j]);
}
}
}
}
} |
f1451065-93c7-4e44-abf1-4eccbcb46e25 | 4 | private void mapEdge(){
if(Base.render.yOffset < 0) Base.render.yOffset += mapMovementSpeed;
if(Base.render.yOffset > (Base.level.height * 32) - Base.height) Base.render.yOffset -= mapMovementSpeed;
if(Base.render.xOffset < 0) Base.render.xOffset += mapMovementSpeed;
if(Base.render.xOffset > (Base.level.width * 32) - Base.width) Base.render.xOffset -= mapMovementSpeed;
} |
fe6548a5-fac7-4e0c-842b-d9cdf5803a40 | 7 | public String get(String keyValue, Object ... args)
{
String message = super.getMessage(keyValue, args, locale);
if(inCharset != null && outCharset != null) {
try {
message = new String(message.getBytes(inCharset), outCharset);
}
catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else if(inCharset != null) {
try {
message = new String(message.getBytes(inCharset));
}
catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else if(outCharset != null) {
try {
message = new String(message.getBytes(), outCharset);
}
catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return message;
} |
af5fd934-9485-47b4-8927-c58bcddbc0b6 | 5 | private int getY(Dimensions dim){
Face direction = surface.roomView.playerDirection;
if (direction == Face.EASTERN){
if (ceiling){
return dim.getX();
}
return 100 - dim.getX();
}
if (direction == Face.SOUTHERN){
return 100 - dim.getY();
}
if (direction == Face.WESTERN){
if (ceiling){
return 100 - dim.getX();
}
return dim.getX();
}
//must be facing north
return dim.getY();
} |
97d384d8-0fe4-438f-9268-56d90a859480 | 6 | public boolean isActive(Component c) {
boolean active = true;
if (c instanceof JDialog) {
JDialog dlg = (JDialog) c;
if (dlg.getParent() instanceof JComponent) {
return JTattooUtilities.isActive((JComponent) (dlg.getParent()));
}
} else if (c instanceof JInternalFrame) {
JInternalFrame frame = (JInternalFrame) c;
active = frame.isSelected();
if (active) {
return JTattooUtilities.isActive(frame);
}
} else if (c instanceof JRootPane) {
JRootPane jp = (JRootPane) c;
if (jp.getTopLevelAncestor() instanceof Window) {
Window window = (Window) jp.getTopLevelAncestor();
return JTattooUtilities.isWindowActive(window);
}
}
return active;
} |
aa0ccbf7-ec98-4ac3-87e9-6f62644ef23f | 7 | public void newPiece(double percent) {
Block piece = Block.EMPTY;
if (percent < .14)
piece = Block.TALL;
else if (percent < .28)
piece = Block.ELL;
else if (percent < .42)
piece = Block.BACKELL;
else if (percent < .56)
piece = Block.HORN;
else if (percent < .70)
piece = Block.EGYPT;
else if (percent < .85)
piece = Block.SNAKE;
else if (percent >= .85)
piece = Block.SQUARE;
createNewPiece(piece, false);
} |
b2b4f106-519a-4724-bd22-b89fba777f45 | 0 | @Override
public int compareTo(TVC o) {
return intencity.compareTo(o.intencity);
} |
945831b1-a9b9-40a7-b782-832a098e25d0 | 2 | protected void processMouseEvent(MouseEvent e) {
if (e.getID() == e.MOUSE_PRESSED) {
if (hasFocus()) {
int code = InputManager.getMouseButtonCode(e);
mapGameAction(code, true);
}
else {
requestFocus();
}
}
e.consume();
} |
215caba3-32e5-42d1-96d7-ab224bca9cae | 3 | edge depthFirstTraverse( edge e )
{
edge f;
if ( e == null )
{
f = this.root.leftEdge;
if ( f != null )
f = f.findBottomLeft();
//this is the first edge of this search pattern
return f;
}
else //e is non-null
{
if ( e.tail.leftEdge == e )
// if e is a left-oriented edge, we skip the entire
// tree cut below e, and find least edge
f = e.moveRight();
else
//if e is a right-oriented edge, we have already looked at its
// sibling and everything below e, so we move up
f = e.tail.parentEdge;
}
return f;
} |
af21a27e-f181-4662-9155-eea78e91ef3c | 8 | void load(){
theoriesSplittedsRead = original.split("END");
for(int i=0;i<theoriesSplittedsRead.length;i++)
if(theoriesSplittedsRead[i].contains("THEORY ProofList IS"))
proofListRead = theoriesSplittedsRead[i];
for(int i=0;i<theoriesSplittedsRead.length;i++)
if(theoriesSplittedsRead[i].contains("THEORY Formulas IS")){
formulasRead = theoriesSplittedsRead[i];
formulasRead= formulasRead.replaceFirst("&\nTHEORY Formulas IS", "");
}
for(int i=0;i<theoriesSplittedsRead.length;i++)
if(theoriesSplittedsRead[i].contains("THEORY EnumerateX IS"))
enumerateXRead = theoriesSplittedsRead[i];
for(int i=0;i<theoriesSplittedsRead.length;i++)
if(theoriesSplittedsRead[i].contains("THEORY Version IS"))
versionRead = theoriesSplittedsRead[i];
loadFormulas();
loadProofList();
} |
b871e7a3-da92-48be-8baf-7fd34b064591 | 6 | public void mutate(int probabilty, int mutationSize) {
Random randGen = new Random();
int test = randGen.nextInt(100);
if(test > probabilty)
return;
//mutation
if(bins.size() < mutationSize){
for(int i = 0; i < bins.size(); i++){
List<Element> items = bins.get(i).getAll();
for(int k = 0; k < items.size(); k++){
this.freeItems.add(items.get(k));
}
}
this.bins.clear();
addFreeItems();
return;
}
for(int i = 0; i < mutationSize; i++){
int pos = randGen.nextInt(bins.size());
List<Element> items = bins.get(pos).getAll();
for(int k = 0; k < items.size(); k++){
this.freeItems.add(items.get(k));
}
this.bins.remove(pos);
}
addFreeItems();
} |
0a1c9097-c53d-41df-b2b0-5354e86874b0 | 4 | public ImageIcon saveImg(String imgUrl, String fileName, boolean returnImage) {
System.out.println("Save to file " + fileName + " from " + imgUrl);
try {
URL url = new URL(imgUrl);
BufferedImage originalBufImg = ImageIO.read(url);
BufferedImage resizedBufImg = null;
if(originalBufImg.getHeight()>height && originalBufImg.getWidth() > width){
// Resize the image with the default image scaling algorithm Image.SCALE_DEFAULT
Image resizedImg = originalBufImg.getScaledInstance(width, height, Image.SCALE_DEFAULT);
resizedBufImg = new BufferedImage(width, height, originalBufImg.getType());
Graphics2D graphics = resizedBufImg.createGraphics();
// Draw the graphics object from coordinate (0, 0) with the ImageObserver set to null
graphics.drawImage(resizedImg, 0, 0, null);
// Dispose the graphics when no longer needed
graphics.dispose();
}
else{
//Don't resize if picture is smaller than max scale
resizedBufImg = originalBufImg;
}
// Save the img to disk
String targetPath = filePath + fileName;
FileOutputStream out = new FileOutputStream(targetPath);
ImageIO.write(resizedBufImg, FILE_EXTENSION, out);
out.close();
//If the saved image is also wanted to be returned
if(returnImage){
return new ImageIcon(resizedBufImg);
}
} catch (IOException e) {
System.err.println("Error when trying to save an img from URL. error: " + e.getMessage());
}
return null;
} |
d00ad401-6478-4005-a8d7-01274389840f | 8 | public static Vector<Vector<Move>> expandMoves(Board board, Player player){
Vector<Vector<Move>> outerVector = new Vector<Vector<Move>>();
if(player == Player.black){
Vector<Move> moves = null;
moves = Black.CalculateAllForcedMovesForBlack(board);
if(moves.isEmpty()){
moves = Black.CalculateAllNonForcedMovesForBlack(board);
for(Move m:moves){
Vector<Move> innerVector = new Vector<Move>();
innerVector.add(m);
outerVector.add(innerVector);
}
}else{
for(Move m:moves){
int r = m.finalRow;
int c = m.finalCol;
Vector<Move> innerVector = new Vector<Move>();
innerVector.add(m);
Board boardCopy = board.duplicate();
boardCopy.genericMakeBlackMove(m);
expandMoveRecursivelyForBlack(boardCopy, outerVector, innerVector, r, c);
innerVector.remove(m);
}
}
}else if(player == Player.white){
Vector<Move> moves = null;
moves = White.CalculateAllForcedMovesForWhite(board);
if(moves.isEmpty()){
moves = White.CalculateAllNonForcedMovesForWhite(board);
for(Move m:moves){
Vector<Move> innerVector = new Vector<Move>();
innerVector.add(m);
outerVector.add(innerVector);
}
}else{
for(Move m:moves){
int r = m.finalRow;
int c = m.finalCol;
Vector<Move> innerVector = new Vector<Move>();
innerVector.add(m);
Board boardCopy = board.duplicate();
boardCopy.genericMakeWhiteMove(m);
expandMoveRecursivelyForWhite(boardCopy, outerVector, innerVector, r, c);
innerVector.remove(m);
}
}
}
return outerVector;
} |
17bc79ce-fc9a-42de-8132-e97be19dbc6d | 9 | synchronized void resizeMap(int x, int y)
{
int i,
i2,
X,
Y;
short newMap[][][]= new short[MapLayers][x][y];
X = MapColumns;
if (x < MapColumns)
{
X = x;
}
Y = MapRows;
if (y < MapRows)
{
Y = y;
}
for (i=0;i<X;i++)
{
for (i2=0;i2<Y;i2++)
{
try
{
newMap[i][i2] = shrMap[i][i2];
}catch(Exception e)
{
}
}
}
shrMap = newMap;
DuskObject newEntities[][]= new DuskObject[x][y];
for (i=0;i<X;i++)
{
for (i2=0;i2<Y;i2++)
{
try
{
newEntities[i][i2] = objEntities[i][i2];
}catch(Exception e)
{
}
}
}
objEntities = newEntities;
MapColumns = x;
MapRows = y;
Entity thnStore;
for (i=0;i<vctSockets.size();i++)
{
thnStore = (Entity)vctSockets.elementAt(i);
thnStore.resizeMap();
}
BLN_MAP_CHANGE = true;
} |
4754ac4b-923c-4fd9-919b-174be8618fff | 8 | private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
if(con==null){
JOptionPane.showMessageDialog(null, "Could not connect to the database! Please check connection and then retry.", "Communication Failure", JOptionPane.ERROR_MESSAGE);
}
else{
String username,stringPass="";
char[] pass;
String passHash="";
username=this.txtUsername.getText();
pass=this.txtPassword.getPassword();
for(int i=0;i<pass.length;i++){
stringPass+=pass[i];
}
try{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(stringPass.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
passHash=sb.toString();
}
catch(Exception ex){
ex.printStackTrace();
}
String tempUserId,tempUserType,tempPassword;
try{
String query="SELECT userid,password,usertype FROM users WHERE username='"+username+"'";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
if(rs.next()==false){
JOptionPane.showMessageDialog(null, "Username not found!", "Login failed!", JOptionPane.ERROR_MESSAGE);
}
else{
tempUserId=Integer.toString(rs.getInt(1));
tempPassword=rs.getString(2);
tempUserType=rs.getString(3);
if(tempPassword.equals(passHash)){
this.lblSignedIn.setVisible(true);
this.lblName.setText(this.txtUsername.getText());
this.btnEmployees.setEnabled(true);
this.lblEmployees.setEnabled(true);
this.lblProjects.setEnabled(true);
this.btnProjects.setEnabled(true);
if(tempUserType.equals("administrator")){
this.lblDepartments.setEnabled(true);
this.btnDepartments.setEnabled(true);
this.lblDepartments.setText("Add/Remove/Change department details");
this.lblRegisterUser.setVisible(true);
}
else{
this.lblDepartments.setEnabled(false);
this.btnDepartments.setEnabled(false);
this.lblDepartments.setText("This Option is only for Database administrators");
this.lblRegisterUser.setVisible(false);
}
this.btnLogout.setEnabled(true);
this.txtPassword.setEnabled(false);
this.txtUsername.setEnabled(false);
this.btnLogin.setEnabled(false);
}
else{
JOptionPane.showMessageDialog(null, "Password not valid!", "Login failed!", JOptionPane.ERROR_MESSAGE);
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}//GEN-LAST:event_btnLoginActionPerformed |
e39335c8-829e-40c0-afdc-715f997a38f5 | 7 | @SuppressWarnings("RedundantIfStatement")
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
if (second != null ? !second.equals(pair.second) : pair.second != null) return false;
return true;
} |
ba59e4d2-566c-4da7-a59c-75b855fb947e | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ID3v2UrlFrameData other = (ID3v2UrlFrameData) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
} |
ab47a7b3-c1d8-442f-a19d-c922795552ba | 3 | public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
if (column == 4) {
setIcon(new ImageIcon(scaleAmmoImage));
setPreferredSize(new Dimension(30, 30));
setOpaque(true);
setText("");
} else {
if (column == 3) {
setIcon(new ImageIcon(scaleLifeImage));
setPreferredSize(new Dimension(30, 30));
setOpaque(true);
setText("");
} else {
if (column == 2) {
setIcon(new ImageIcon(scaleZombieImage));
setPreferredSize(new Dimension(30, 30));
setOpaque(true);
setText("");
} else {
setIcon(null);
setOpaque(false);
setPreferredSize(new Dimension(100, 30));
setText(value.toString());
}
}
}
return this;
} |
38be9924-c0d4-47d6-8cc6-15d793fc9511 | 5 | private static VirusStats[] getVirusStats() {
TreeMap<Integer, LinkedList<Virus>> invert = new TreeMap<Integer, LinkedList<Virus>>();
TreeMap<Virus, Integer> virusCounts = getVirusCounts();
// Invert the map
for (Entry<Virus, Integer> entry : virusCounts.entrySet()) {
int count = entry.getValue();
Virus v = entry.getKey();
LinkedList<Virus> viruses;
// Create or update the bucket
if (invert.containsKey(count))
viruses = invert.get(count);
else
viruses = new LinkedList<Virus>();
viruses.add(v);
invert.put(count, viruses);
}
// Append all of the buckets (they'll already be sorted thanks to the TreeMap)
LinkedList<Virus> answer = new LinkedList<Virus>();
for (LinkedList<Virus> l : invert.values()) {
if (l != null)
answer.addAll(l);
}
int k = answer.size();
VirusStats[] array = new VirusStats[k];
for (int i=0; i<k; i++) {
Virus v = answer.get(k-i-1);
array[i] = new VirusStats(virusCounts.get(v), v, getExtinctTime(v));
}
Arrays.sort(array, vsc);
return array;
} |
d5fdd1f0-dd98-4bb2-9b7a-845d5475f1df | 6 | public void assign(Entry entry) {
ColonyTile colonyTile = null;
Building building = null;
if (entry.getWorkLocation() instanceof ColonyTile) {
colonyTile = (ColonyTile) entry.getWorkLocation();
colonyTiles.remove(colonyTile);
} else if (entry.getWorkLocation() instanceof Building) {
building = (Building) entry.getWorkLocation();
unitCounts.incrementCount(building.getType(), 1);
}
Unit unit = null;
if (!entry.isOtherExpert()) {
unit = entry.getUnit();
units.remove(unit);
assigned.add(entry);
removeEntries(unit, colonyTile, reserved);
} else {
if (colonyTile == null) {
if (unitCounts.getCount(building.getType()) == 1) {
// only add building once
reserved.addAll(entries.get(entry.getGoodsType()));
}
} else {
reserved.addAll(removeEntries(null, colonyTile, entries.get(entry.getGoodsType())));
}
}
// if work location is a colony tile, remove it from all other
// lists, because it only supports a single unit
for (List<Entry> entryList : entries.values()) {
removeEntries(unit, colonyTile, entryList);
}
unitCount--;
} |
3a587ac9-5825-4f25-aa72-b26756fd03a9 | 9 | public boolean isSvek() {
boolean defaultValue = false;
// if (OptionFlags.SVEK && type == UmlDiagramType.CLASS) {
// defaultValue = true;
// }
if (type == UmlDiagramType.CLASS) {
defaultValue = true;
}
if (type == UmlDiagramType.OBJECT) {
defaultValue = true;
}
if (type == UmlDiagramType.USECASE) {
defaultValue = true;
}
if (type == UmlDiagramType.COMPONENT) {
defaultValue = true;
}
if (OptionFlags.SVEK && type == UmlDiagramType.ACTIVITY) {
defaultValue = true;
}
if (OptionFlags.SVEK && type == UmlDiagramType.STATE) {
defaultValue = true;
}
final String value = getValue("svek");
if (value == null) {
return defaultValue;
}
return "true".equalsIgnoreCase(value);
} |
2a3400dd-b4b1-456e-a91b-df3649a8cd39 | 9 | private boolean generateRoom(int x, int y, Direction direction)
{
int roomWidth = Main.rand.nextInt(ROOM_MAX_SIZE - ROOM_MIN_SIZE) + ROOM_MIN_SIZE;
int roomHeight = Main.rand.nextInt(ROOM_MAX_SIZE - ROOM_MIN_SIZE) + ROOM_MIN_SIZE;
int x1, x2, y1, y2;
if (direction == Direction.UP)
{
x1 = x - roomWidth/2;
x2 = x + roomWidth/2;
y1 = y - roomHeight - 1;
y2 = y - 1;
if (!isAreaEmpty(x1 - 1, x2 + 1, y1 - 1, y2))
return false;
walls.add(new WallRange(x1 - 1, x1 - 1, y1 + 1, y2 - 1, Direction.LEFT));
walls.add(new WallRange(x2 + 1, x2 + 1, y1 + 1, y2 - 1, Direction.RIGHT));
walls.add(new WallRange(x1 + 1, x2 - 1, y1 - 1, y1 - 1, Direction.UP));
}
else if (direction == Direction.DOWN)
{
x1 = x - roomWidth/2;
x2 = x + roomWidth/2;
y1 = y + 1;
y2 = y + roomHeight + 1;
if (!isAreaEmpty(x1 - 1, x2 - 1, y1, y2 + 1))
return false;
walls.add(new WallRange(x1 - 1, x1 - 1, y1 + 1, y2 - 1, Direction.LEFT));
walls.add(new WallRange(x2 + 1, x2 + 1, y1 + 1, y2 - 1, Direction.RIGHT));
walls.add(new WallRange(x1 + 1, x2 - 1, y2 + 1, y2 + 1, Direction.DOWN));
}
else if (direction == Direction.LEFT)
{
x1 = x - roomWidth - 1;
x2 = x - 1;
y1 = y - roomHeight/2;
y2 = y + roomHeight/2;
if (!isAreaEmpty(x1 - 1, x2, y1 - 1, y2 + 1))
return false;
walls.add(new WallRange(x1 + 1, x2 - 1, y1 - 1, y1 - 1, Direction.UP));
walls.add(new WallRange(x1 + 1, x2 - 1, y2 + 1, y2 + 1, Direction.DOWN));
walls.add(new WallRange(x1 - 1, x1 - 1, y1 + 1, y2 - 1, Direction.LEFT));
}
else
{
x1 = x + 1;
x2 = x + roomWidth + 1;
y1 = y - roomHeight/2;
y2 = y + roomHeight/2;
if (!isAreaEmpty(x1, x2 + 1, y1 - 1, y2 + 1))
return false;
walls.add(new WallRange(x1 + 1, x2 - 1, y1 - 1, y1 - 1, Direction.UP));
walls.add(new WallRange(x1 + 1, x2 - 1, y2 + 1, y2 + 1, Direction.DOWN));
walls.add(new WallRange(x2 - 1, x2 - 1, y1 + 1, y2 - 1, Direction.LEFT));
}
for(int i = y1; i <= y2; i++)
for( int k = x1; k <= x2; k++)
dungeon[k][i] = ".";
dungeon[x][y] = ".";
return true;
} |
e8dfe0c1-eaaa-4177-ad0b-664c9e61e1ae | 2 | public static boolean isCorporationID(int id) {
try {
InputSource data;
String notCorp = "{\"info\":null,\"characters\":[]}";
data = Download
.getFromHTTP("http://evewho.com/api.php?type=corplist&id="
+ id);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(data.getByteStream(), "UTF-8"));
String line = bufferedReader.readLine();
bufferedReader.close();
if (line.equalsIgnoreCase(notCorp)) {
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} |
b8891f02-2663-45b7-bdd5-8ed62ad675cf | 5 | public static Graph initialize(DynamicArray<String> matrix) {
Graph g = new Graph();
String[][] adjacencyMatrix = parseStringArray(matrix);
Vertex[] vertices = new Vertex[matrix.getSize()];
for (int i = 0; i < vertices.length; i++) {
vertices[i] = new Vertex(i);
g.addVertex(vertices[i]);
}
for (int i = 0; i < adjacencyMatrix.length; i++) {
for (int j = 0; j < adjacencyMatrix[0].length; j++) {
if (adjacencyMatrix[i][j].matches("^[0-9]{1,9}$")) {
int weight = Integer.parseInt(adjacencyMatrix[i][j]);
g.addEdge(vertices[i], vertices[j], weight);
if (!directed) {
g.addEdge(vertices[j], vertices[i], weight);
}
}
}
}
g.setDirected(directed);
return g;
} |
9d4bf282-44b2-4131-8751-5a51c47f3848 | 7 | public boolean Salvar(Pessoa obj) {
if (obj.getCodigo() == 0) {
try {
PreparedStatement sql = getConexao().prepareStatement("insert into pessoa(Nome,DataNascimento) values(?,?)");
sql.setString(1, obj.getNome());
sql.setDate(2, new java.sql.Date(obj.getDataNascimento().getTime()));
sql.executeUpdate();
PreparedStatement sql2 = getConexao().prepareStatement("select codPessoa from pessoa where nome = ? and DataNascimento = ?");
sql2.setString(1, obj.getNome());
sql2.setDate(2, new java.sql.Date(obj.getDataNascimento().getTime()));
ResultSet resultado = sql2.executeQuery();
if (resultado.next()) {
obj.setCodigo(resultado.getInt("codPessoa"));
}
// Salva o email
for (Email e : obj.getEmails()) {
SalvarEmail(obj, e);
}
//Salva o Endereco
for (Endereco e : obj.getEnderecos()) {
SalvarEndereco(obj, e);
}
// Salva o Telefone
for (Telefone e : obj.getTelefones()) {
SalvarTelefone(obj, e);
}
return true;
} catch (Exception ex) {
System.err.println(ex.getMessage());
return false;
}
} else {
try {
Connection con = getConexao();
PreparedStatement sql = con.prepareStatement("update Pessoa set nome=?, DataNascimento=? where codPessoa=?");
sql.setString(1, obj.getNome());
sql.setDate(2, new java.sql.Date(obj.getDataNascimento().getTime()));
sql.setInt(3, obj.getCodigo());
sql.executeUpdate();
return true;
} catch (Exception ex) {
System.err.println(ex.getMessage());
return false;
}
}
} |
f6317e93-d0c7-4b5c-9939-20307f01e94e | 8 | public void search(ListView<String> list, String word) {
//now to find them!
list.getItems().clear();
for (JournalEntry entry : journal.getEntries()) {
//look thru topics first...
boolean found = false;
for (String topic : entry.getTopic()) {
if (word.contains(topic)) {
found = true;
}
}
//then at scriptures!
for (Scripture s : entry.getScriptures()) {
if (word.contains(s.getBook())) {
if (word.contains(s.getChapters())) {
found = true;
}
}
}
//now see if we have found it!
if (found) {
//now add to the list!
list.getItems().add(entry.getTitle() + " " + entry.getDate());
}
}
//if list is empty then tell the user...
if (list.getItems().size() == 0) {
list.getItems().add("No entries found");
} else {
list.getItems().add(0, "Entries found:");
}
} |
01f06083-b8df-4838-bcfe-76805e4747b6 | 0 | public int getNum()
{
return num;
} |
a1135e37-fb21-4b7c-bc90-f9bfdc5eba56 | 2 | private String createProtectedLines() {
StringBuilder sb = new StringBuilder();
List<String> lines = getProtectedLines( fileName );
if ( !lines.isEmpty() ) {
for ( String line : lines ) {
sb.append( line );
}
}
else {
sb.append( "\n" );
sb.append( TAB + "//" );
sb.append( PROTECTED_CODE );
sb.append( "\n}\n" );
}
return sb.toString();
} |
265ebd11-c8be-48c1-8d80-39ed3cd6aacc | 0 | public DeviceType getDeviceType() {
return deviceType;
} |
3bd08e9a-8a6e-46ed-b89d-4882046fea60 | 7 | public String toString() {
return ((this.day == 0 ? "Mon " : (this.day == 1 ? "Tue " : (this.day == 2 ? "Wed " : (this.day == 3 ? "Thu " : (this.day == 4 ? "Fri " : (this.day == 5 ? "Sat " : (this.day == 6 ? "Sun " : "Unknown " + this.day + " "))))))) + (int)this.hour + "h" + (int)this.min + "m");
} |
b4b50d1a-60bc-406f-80c1-73b37e6ec428 | 8 | public static String[] verifyTimeArguments(String[] args) throws Exception {
if (null == args || args.length != 3) throw new IncorrectNoOfArgumentsException(3);
String[] t = new String[3];
int hour = Integer.parseInt(args[0]);
int min = Integer.parseInt(args[1]);
int ms = Integer.parseInt(args[2]);
if (hour < 0 || hour > 23) throw new IllegalArgumentException("hour exceed range, [" + hour + "]");
if (min < 0 || min > 60) throw new IllegalArgumentException("minute exceed range, [" + min + "]");
if (ms < 0 || ms > 1000) throw new IllegalArgumentException("mini-second exceed range, [" + ms + "]");
t[0] = "" + hour;
t[1] = "" + min;
t[2] = "" + ms;
return t;
} |
e8ae38c9-55a0-47e0-9f4e-b775e6d62858 | 7 | public int compareTo(Object o)
{
int row1 = modelIndex;
int row2 = ((Row)o).modelIndex;
for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();)
{
Directive directive = (Directive)it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null)
{
comparison = 0;
}
else if (o1 == null)
{
comparison = -1;
}
else if (o2 == null)
{
comparison = 1;
}
else
{
comparison = getComparator(column).compare(o1, o2);
}
if (comparison != 0)
{
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
} |
d325731d-16ba-4ffe-b1d0-6739106d37c9 | 2 | public void setAllAccessible(boolean b){
for(int x = 0; x< IConfig.LARGEUR_CARTE;x++ ){
for(int y = 0; y< IConfig.HAUTEUR_CARTE;y++ ){
this.mapGraph[x][y].setMarkedAccessible(b);
}
}
} |
ffddfc64-3c22-4344-953b-08f8895dfc94 | 7 | public void mouseMoved(MouseEvent e) {
MouseX = e.getX();
MouseY = e.getY();
if (state == 2)
{
int x = 50 * winZoom, y = 25 * winZoom, num = 0;
while (num < var.NUM_ELS) {
if (MouseX > x && MouseY > y && MouseX < x + (40*winZoom) && MouseY < y + (40*winZoom)) {
overEl = (byte)(num);
}
num++;
x += 40 * winZoom;
if (num % 13 == 0)
{
x = 50 * winZoom;
y += 40 * winZoom;
}
}
}
} |
a2496bd3-7a81-47ab-a0e2-6702529b7d9e | 6 | @Override
protected Object registeringGUI() {
long idProd, idBuyer, idSeller;
while(true){
try{
idProd = Long.parseLong(guiImpl.requestData("Código do produto:"));
break;
}catch(NumberFormatException e){
GUIAbsTemplate.operationFailedGUI("ID inválido.");
}
}
while(true){
try{
idBuyer = Long.parseLong(guiImpl.requestData("Código do comprador:"));
break;
}catch(NumberFormatException e){
GUIAbsTemplate.operationFailedGUI("ID inválido.");
}
}
while(true){
try{
idSeller = Long.parseLong(guiImpl.requestData("Código do vendedor:"));
break;
}catch(NumberFormatException e){
GUIAbsTemplate.operationFailedGUI("ID inválido.");
}
}
return new Deal(idBuyer, idSeller, idProd);
} |
6c3906c4-a903-40d5-867e-315ef52c1e0f | 9 | private void persist(String cubeIdentifier) throws PersistErrorException,
PageFullException, IOException, SchemaNotExistsException,
CubeNotExistsException {
SchemaClientInterface schemaClient = SchemaClient.getSchemaClient();
Schema schema = schemaClient.getSchema(cubeIdentifier);
// numberOfDimensions
int numberOfDimensions = schema.getDimensions().size();
// numberOfPages & pageLengths & numberOfPageSegmentsInDimension &
// dimensionLengths
long numberOfPages = PageHelper.getNumberOfPages(schema);
long pageLengths[] = PageHelper.getPageLengths(schema);
long numberOfPageSegmentsInDimension[] = PageHelper
.getNumberOfPageSegmentsInDimensions(schema);
long dimensionLengths[] = DimensionHelper.getDimensionLengths(schema);
System.out.println("numberOfPages:" + numberOfPages);
System.out.println("dimensionLength "
+ Arrays.toString(dimensionLengths));
System.out.println("pageLengths:" + Arrays.toString(pageLengths));
System.out.println("numberOfPageSegmentsInDimension:"
+ Arrays.toString(numberOfPageSegmentsInDimension));
Page page;
// double data;
for (long pageNo = 0; pageNo < numberOfPages; pageNo += 1) {
// construct a page
List<CubeElement<Double>> elementList = new ArrayList<CubeElement<Double>>();
long pointForPage[] = Serializer.deserialize(
numberOfPageSegmentsInDimension,
new BigInteger(String.valueOf(pageNo)));
long pointForElement[][] = new long[2][numberOfDimensions];
for (int i = 0; i < numberOfDimensions; i += 1) {
pointForElement[0][i] = pointForPage[i] * pageLengths[i];
pointForElement[1][i] = pointForElement[0][i] + pageLengths[i]
- 1;
}
System.out.println("Page:\t" + pageNo + "\tstart:\t"
+ Arrays.toString(pointForElement[0]) + "\tend:\t"
+ Arrays.toString(pointForElement[1]));
long[] start = pointForElement[0];
long[] end = pointForElement[1];
long[] point = new long[numberOfDimensions];
long[] lengths = pageLengths;
int pointLength = numberOfDimensions;
int pointAmount = 1;
for (int i = 0; i < pointLength; i++) {
pointAmount *= end[i] - start[i] + 1;
}
for (int i = 0; i < point.length; i++) {
point[i] = start[i];
}
elementList.add(new CubeElement<Double>(Serializer.serialize(
dimensionLengths, point).longValue(), r.nextDouble()
* dataRange));
for (int i = 0; i < pointAmount - 1; i++) {
point[pointLength - 1]++;
if (point[pointLength - 1] >= lengths[pointLength - 1]) {
for (int j = pointLength - 1; j >= 0; j--) {
if (point[j] >= lengths[j] && j > 0) {
point[j] = 0;
point[j - 1]++;
} else {
break;
}
}
}
elementList.add(new CubeElement<Double>(Serializer.serialize(
dimensionLengths, point).longValue(), this.r
.nextDouble() * dataRange));
}
page = new Page(cubeIdentifier, pageNo, elementList);
page.persist();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.