text
stringlengths
10
2.72M
package notepad; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.DefaultEditorKit; public class NoteJFrame extends javax.swing.JFrame { /** * Creates new form NoteJFrame */ public NoteJFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { db = new javax.swing.JFileChooser(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem12 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem5 = new javax.swing.JMenuItem(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem(); jMenuItem8 = new javax.swing.JMenuItem(); jMenuItem9 = new javax.swing.JMenuItem(); jMenuItem10 = new javax.swing.JMenuItem(); jMenuItem11 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); jMenu5 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jMenu1.setText("File"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem1.setText("New"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem2.setText("Open"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem3.setText("Save"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); jMenuItem4.setText("Save As..."); jMenu1.add(jMenuItem4); jMenuItem12.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK)); jMenuItem12.setText("Exit"); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem12ActionPerformed(evt); } }); jMenu1.add(jMenuItem12); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenu2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu2ActionPerformed(evt); } }); jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem5.setText("Undo"); jMenu2.add(jMenuItem5); jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem6.setText("Cut"); jMenuItem6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem6ActionPerformed(evt); } }); jMenu2.add(jMenuItem6); jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem7.setText("Copy"); jMenu2.add(jMenuItem7); jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem8.setText("Paste"); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem8ActionPerformed(evt); } }); jMenu2.add(jMenuItem8); jMenuItem9.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0)); jMenuItem9.setText("Delete"); jMenuItem9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem9ActionPerformed(evt); } }); jMenu2.add(jMenuItem9); jMenuItem10.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem10.setText("Find"); jMenu2.add(jMenuItem10); jMenuItem11.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem11.setText("Replace"); jMenuItem11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem11ActionPerformed(evt); } }); jMenu2.add(jMenuItem11); jMenuBar1.add(jMenu2); jMenu3.setText("Format"); jMenuBar1.add(jMenu3); jMenu4.setText("View"); jMenuBar1.add(jMenu4); jMenu5.setText("Help"); jMenuBar1.add(jMenu5); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed // TODO add your handling code here: JMenuItem jMenuItem6 = new JMenuItem(new DefaultEditorKit.CutAction()); }//GEN-LAST:event_jMenuItem6ActionPerformed private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenuItem11ActionPerformed private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed JMenuItem jMenuItem8 = new JMenuItem(new DefaultEditorKit.PasteAction()); }//GEN-LAST:event_jMenuItem8ActionPerformed private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed JMenuItem jMenuItem2 = new JMenuItem(new DefaultEditorKit.CopyAction()); }//GEN-LAST:event_jMenu2ActionPerformed private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed jTextArea1.setText(""); }//GEN-LAST:event_jMenuItem9ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed int retval = db.showOpenDialog(this); if(retval == javax.swing.JFileChooser.APPROVE_OPTION){ java.io.File file = db.getSelectedFile(); try { jTextArea1.read(new FileReader(file.getAbsolutePath()), null); } catch(java.io.IOException e){ System.out.println("problem accessing file"+file.getAbsolutePath()); } } /*catch (java.io.IOException e){ JOptionPane.showMessageDialog(NoteJFrame.this, file_name); }*/ }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed System.exit(0); }//GEN-LAST:event_jMenuItem12ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed FileFilter f = new FileNameExtensionFilter("Text Files","txt"); db.addChoosableFileFilter(f); int retval = db.showSaveDialog(this); if (retval == javax.swing.JFileChooser.APPROVE_OPTION){ java.io.File save_file = db.getSelectedFile(); String file_name = save_file.toString(); try{ FileWriter data = new FileWriter(file_name, false); String text = jTextArea1.getText(); data.write(text); } catch(java.io.IOException e) { System.out.println("File name already exist"); } } }//GEN-LAST:event_jMenuItem3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NoteJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NoteJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NoteJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NoteJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NoteJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JFileChooser db; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem10; private javax.swing.JMenuItem jMenuItem11; private javax.swing.JMenuItem jMenuItem12; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JMenuItem jMenuItem9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
package com.example.mercaya; import androidx.appcompat.app.ActionBar; import android.os.Bundle; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.List; public class ImagenesPapas extends AppCompatActivity { ImageSwitcher imagenPapas; Button buttonNext, buttonPreviouss; int [] images = { R.drawable.carne, R.drawable.frutas_variadas, R.drawable.condimentos, R.drawable.productos_lacteos, }; int position =-1; List<Productos> listaFrutas = new ArrayList<>(); ProductoAdapter adapter = new ProductoAdapter(listaFrutas,this); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.prod_papas); imagenPapas = findViewById(R.id.ImagPapas); buttonNext = findViewById(R.id.BSiguiente); buttonPreviouss =findViewById(R.id.Banterior); imagenPapas.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { ImageView imageView=new ImageView(getApplicationContext()); imageView.setLayoutParams(new ImageSwitcher.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT)); return imageView; } }); buttonNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(position<images.length-1){ position=position+1; imagenPapas.setBackgroundResource(images[position]); } } }); buttonPreviouss.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(position>0){ position=position-1; imagenPapas.setBackgroundResource(images[position]); } } }); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jade; /** * * @author AFRIZAL */ import jade.core.Agent; import jade.core.behaviours.TickerBehaviour; public class JADE extends Agent { protected void setup(){ addBehaviour(new timer (this,300) ); // addBehaviour(new timer (this) ); } }
package pl.finapi.paypal.output.pdf.element; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import pl.finapi.paypal.model.Amount; import pl.finapi.paypal.model.Currency; import pl.finapi.paypal.model.DateTimeRange; import pl.finapi.paypal.model.TransactionLine; import pl.finapi.paypal.model.output.PaypalFeeReportModel; import pl.finapi.paypal.output.EwidencjaProwizjiWriter; import pl.finapi.paypal.util.NumberFormatter; import pl.finapi.paypal.util.NumberUtil; import pl.finapi.paypal.util.PdfFactory; import pl.finapi.paypal.util.TimeUtil; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; @Component public class EwidencjaProwizjiPdfWriter implements EwidencjaProwizjiWriter { private final String[] headerCells = new String[] { "L.p.", "Data operacji", "Typ operacji", "Wartość prowizji w walucie", "Waluta", "Kurs waluty", "Identyfikacja kursu przeliczeniowego", "Wartość prowizji (PLN)" }; private final float[] columnWidth = new float[] { 5, 10, 27, 8, 7, 7, 30, 8 }; private final Font blackFont; private final Font tableFont; private final DateFormat yearMonthDayDotDelimitedFormat; private final TimeUtil timeUtil; private final NumberUtil numberUtil; private final PdfFactory pdfFactory; private final NumberFormatter numberFormatter; @Autowired public EwidencjaProwizjiPdfWriter(@Value("#{yearMonthDayDotDelimitedFormat_WarsawTimeZone}") DateFormat yearMonthDayDotDelimitedFormat, TimeUtil timeUtil, NumberUtil numberUtil, PdfFactory pdfFactory, NumberFormatter numberFormatter) { this.yearMonthDayDotDelimitedFormat = yearMonthDayDotDelimitedFormat; this.timeUtil = timeUtil; this.numberUtil = numberUtil; this.pdfFactory = pdfFactory; this.numberFormatter = numberFormatter; this.blackFont = pdfFactory.createFont(BaseColor.BLACK, 12, Font.NORMAL); this.tableFont = pdfFactory.createFont(BaseColor.BLACK, 8, Font.NORMAL); } public void createPdf(PaypalFeeReportModel reportModel, File outputFile) { OutputStream outputStream; try { outputStream = new FileOutputStream(outputFile); } catch (FileNotFoundException e1) { throw new RuntimeException(e1); } write(reportModel, outputStream); } @Override public void write(PaypalFeeReportModel reportModel, OutputStream outputStream) { try { Document document = new Document(PageSize.A4); com.itextpdf.text.pdf.PdfWriter.getInstance(document, outputStream); document.setMargins(30, 30, 30, 30); document.open(); addContent(document, reportModel); document.close(); } catch (DocumentException e) { throw new RuntimeException(e); } } public void addContent(Document document, PaypalFeeReportModel reportModel) throws DocumentException { Paragraph preface = new Paragraph(); preface.add(buildTitleParapraph(reportModel)); addEmptyLine(preface, 1); document.add(preface); Paragraph paragraph = new Paragraph(); PdfPTable table = createTable(reportModel.getTransactionLines(), reportModel.getTransactionFeeInPlnSum()); paragraph.add(table); addEmptyLine(paragraph, 2); document.add(paragraph); } private Paragraph buildTitleParapraph(PaypalFeeReportModel reportModel) { return new Paragraph(buildTitle(reportModel.getTransactionDateRange()), blackFont); } private String buildTitle(DateTimeRange dateRange) { return "Ewidencja prowizji Paypal za okres " + timeUtil.dayRangeDotFormatted(dateRange); } private PdfPTable createTable(List<TransactionLine> transactionLines, Amount amount) { PdfPTable table = pdfFactory.createEmptyTable(columnWidth); addHeaderRow(table); addDataRows(transactionLines, table); addFooterRow(table, amount); return table; } private void addDataRows(List<TransactionLine> transactionLines, PdfPTable table) { for (TransactionLine transactionLine : removeZeroFeeLines(transactionLines)) { table.addCell(pdfFactory.createCell(transactionLine.getNumber())); table.addCell(createTableCell(yearMonthDayDotDelimitedFormat.format(transactionLine.getTransactionDateTime().toDate()))); table.addCell(createTableCell(transactionLine.getTransactionType().getPolishName())); table.addCell(createTableCell(numberFormatter.formatTwoDecimal(numberUtil.negateAndFixZeroCase(transactionLine.getFeeInForeignCurrency()) .getAmount()))); table.addCell(createTableCell(transactionLine.getCurrency().name())); table.addCell(createTableCell(isPlnTransaction(transactionLine) ? "-" : numberFormatter.formatFourDecimal(transactionLine.getExchangeRate() .getExchangeRate().getAmount()))); table.addCell(createTableCell(isPlnTransaction(transactionLine) ? "-" : "Tabela nr " + transactionLine.getTableName() + " z dnia " + timeUtil.formatDotDelimited(transactionLine.getNbpExchangeRateDay()))); String format = numberFormatter.formatTwoDecimal(numberUtil.negateAndFixZeroCase(transactionLine.getFeeInPln()).getAmount()); table.addCell(createTableCell(format)); } } private List<TransactionLine> removeZeroFeeLines(List<TransactionLine> transactionLines) { List<TransactionLine> filtered = new ArrayList<>(); for (TransactionLine transactionLine : transactionLines) { if (!transactionLine.getFeeInPln().isZero()) { filtered.add(transactionLine); } } return filtered; } private boolean isPlnTransaction(TransactionLine transactionLine) { return transactionLine.getCurrency().equals(Currency.PLN); } private PdfPCell createTableCell(String text) { return pdfFactory.createCell(text, tableFont); } private void addHeaderRow(PdfPTable table) { for (String headerCell : getHeaderCells()) { PdfPCell c1 = createTableCell(headerCell); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); } table.setHeaderRows(1); } private String[] getHeaderCells() { return headerCells; } private void addFooterRow(PdfPTable table, Amount amount) { table.addCell(pdfFactory.createEmptyCell()); table.addCell(pdfFactory.createEmptyCell()); table.addCell(pdfFactory.createEmptyCell()); table.addCell(pdfFactory.createEmptyCell()); table.addCell(pdfFactory.createEmptyCell()); table.addCell(pdfFactory.createEmptyCell()); table.addCell(pdfFactory.createCell("Suma:", tableFont)); table.addCell(pdfFactory.createCell(numberFormatter.formatTwoDecimal((amount.getAmount())), tableFont)); } private void addEmptyLine(Paragraph paragraph, int emptyLineCount) { for (int i = 0; i < emptyLineCount; i++) { paragraph.add(new Paragraph(" ")); } } }
package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context; import android.content.Context; import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.persistence.DB; public class InstanceFactoryForTests extends AbstractInstanceFactory { public InstanceFactoryForTests(Context context) { super(context); } @Override protected DB getDB() { return DB.TEST; } }
package xyz.mijack.blog.csdn.model; import android.content.Context; import xyz.mijack.blog.csdn.R; /** * Created by MiJack on 2015/4/16. */ public class CategoryList { private static final Category[] categories = new Category[]{ new Category(R.string.category_mobile, "mobile"), new Category(R.string.category_web, "web"), new Category( R.string.category_enterprise, "enterprise"), new Category( R.string.category_code, "code"), new Category( R.string.category_www, "www"), new Category( R.string.category_database, "database"), new Category(R.string.category_system, "system"), new Category( R.string.category_cloud, "cloud"), new Category( R.string.category_software, "software"), new Category(R.string.category_other, "other"), }; public static int getCount() { return categories.length; } public static Category get(int position) { return categories[position]; } public static Category getCategoryByString(Context context, String title) { for (Category category : categories) { if (context.getString(category.getCategory()).equals(title)) { return category; } } return null; } }
package com.revature.resources; import static com.revature.utils.LogUtil.logger; import java.io.IOException; import java.net.URI; import javax.persistence.NoResultException; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.revature.entity.TfAssociate; import com.revature.entity.TfRole; import com.revature.entity.TfTrainer; import com.revature.entity.TfUser; import com.revature.services.*; import com.revature.utils.LogUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * <p> </p> * @version v6.18.06.13 * */ @Path("/users") @Api(value = "users") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class UserResource { // You're probably thinking, why would you ever do this? Why not just just make the methods all static in the service class? // This is to allow for Mockito tests, which have problems with static methods // This is here for a reason! // - Adam 06.18.06.13 AssociateService associateService = new AssociateService(); BatchService batchService = new BatchService(); ClientService clientService = new ClientService(); CurriculumService curriculumService = new CurriculumService(); InterviewService interviewService = new InterviewService(); TrainerService trainerService = new TrainerService(); UserService userService = new UserService(); MarketingStatusService marketingStatusService = new MarketingStatusService(); /** * @author Adam L. * <p> </p> * @version v6.18.06.13 * * @param newUser * @return */ @Path("/newUser") @POST @Consumes("application/json") @ApiOperation(value = "Creates new user", notes = "") public Response createUser(TfUser newUser) { logger.info("creating new user..." + newUser); // any user created by an admin is approved newUser.setIsApproved(1); // get the role being passed in int role = newUser.getRole(); TfRole tfrole = new TfRole(); boolean works = true; if(role != 0) { switch(role) { case 1: tfrole = new TfRole(1, "Admin"); newUser.setTfRole(tfrole); works = userService.insertUser(newUser); break; case 2: tfrole = new TfRole(2, "Trainer"); newUser.setTfRole(tfrole); TfTrainer newTrainer = new TfTrainer(); newTrainer.setTfUser(newUser); newTrainer.setFirstName("placeholder"); newTrainer.setLastName("placeholder"); logger.info("creating new trainer..." + newTrainer); works = trainerService.createTrainer(newTrainer); break; case 3: tfrole = new TfRole(3, "Sales-Delivery"); newUser.setTfRole(tfrole); works = userService.insertUser(newUser); break; case 4: tfrole = new TfRole(4, "Staging"); newUser.setTfRole(tfrole); works = userService.insertUser(newUser); break; case 5: tfrole = new TfRole(5, "Associate"); newUser.setTfRole(tfrole); TfAssociate newAssociate = new TfAssociate(); newAssociate.setUser(newUser); newAssociate.setFirstName("placeholder"); newAssociate.setLastName("placeholder"); logger.info("creating new associate..." + newAssociate); works = associateService.createAssociate(newAssociate); break; } } if(works) { return Response.status(Status.CREATED).build(); } return Response.status(Status.EXPECTATION_FAILED).build(); } /** * @author Adam L. * <p> </p> * @version v6.18.06.13 * * @param newAssociate * @return */ @Path("/newAssociate") @POST @Consumes("application/json") @ApiOperation(value = "Creates new Associate", notes = "Takes username, password, fname and lname to create new associate and user") public Response createNewAssociate(TfAssociate newAssociate) { logger.info("createNewAssociate()..."); LogUtil.logger.info(newAssociate); if (newAssociate.getUser().getRole() == 5) { boolean works = false; TfRole tfrole = new TfRole(); tfrole = new TfRole(5, "Associate"); newAssociate.getUser().setTfRole(tfrole); logger.info(newAssociate.getUser().getTfRole()); logger.info("creating new associate..." + newAssociate); works = associateService.createAssociate(newAssociate); if (works) { return Response.status(Status.CREATED).build(); } return Response.status(Status.EXPECTATION_FAILED).build(); } else { return Response.status(Status.FORBIDDEN).build(); } } /** * @author Adam L. * <p> </p> * @version v6.18.06.13 * * @param newTrainer * @return */ @Path("/newTrainer") @POST @Consumes("application/json") @ApiOperation(value = "Creates new trainer", notes = "") public Response createTrainer(TfTrainer newTrainer) { logger.info("creating new user..."); LogUtil.logger.info(newTrainer); if (newTrainer.getTfUser().getRole() == 2) { boolean works = false; TfRole tfrole = new TfRole(); tfrole = new TfRole(5, "Associate"); newTrainer.getTfUser().setIsApproved(0); newTrainer.getTfUser().setTfRole(tfrole); logger.info(newTrainer.getTfUser().getTfRole()); logger.info("creating new trainer..." + newTrainer); works = trainerService.createTrainer(newTrainer); if (works) { return Response.status(Status.CREATED).build(); } return Response.status(Status.EXPECTATION_FAILED).build(); } else { return Response.status(Status.FORBIDDEN).build(); } } /** * @author Adam L. * <p> </p> * @version v6.18.06.13 * * @param loginUser * @return * @throws IOException */ @Path("/login") @POST @Consumes("application/json") @Produces("application/json") @ApiOperation(value = "login method", notes = "The method takes login inforation and verifies whether or not it is valid. returns 200 if valid, 403 if invalid.") public Response submitCredentials(TfUser loginUser) throws IOException { logger.info("submitCredentials()..."); logger.info(" login: " + loginUser); TfUser user; try { user = userService.submitCredentials(loginUser); logger.info(" user: " + user); } catch (NoResultException nre) { nre.printStackTrace(); return Response.status(Status.FORBIDDEN).build(); } if (user != null) { logger.info("sending 200 response.."); return Response.status(Status.OK).entity(user).build(); } else { logger.info("sending unauthorized response.."); return Response.status(Status.UNAUTHORIZED).build(); } } }
package com.infotecsjava.keyvalue.repository; import com.infotecsjava.keyvalue.model.KeyValueModel; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /* * Класс, описывающий репозиторий для хранения пар ключ-значение * Наследуется от JpaRepository */ @Repository public interface KeyValueRepository extends JpaRepository<KeyValueModel, String> { }
package com.deepak.dynamic; public class Quicksort { public int[] quicksort(int[]a,int start, int end){ int pivot; if(start<end){ pivot=pivoting(a,start,end); a=quicksort(a,start,pivot-1); a=quicksort(a,pivot+1,end); } return a; } public int pivoting(int[] a,int start,int end){ int pivot=start; for(int i=start;i<end;i++){ if(a[i]<=a[end]){ int temp=a[pivot]; a[pivot]=a[i]; a[i]=temp; pivot++; } } int temp=a[end]; a[end]=a[pivot]; a[pivot]=temp; return pivot; } public static void main(String[] args){ int[] array=new int[]{1,3,4,5,2,6,99,55,34,2}; Quicksort quick=new Quicksort(); array=quick.quicksort(array,0,array.length-1); for(int i=0;i<array.length;i++){ System.out.print(array[i]+" "); } } }
package com.jk.jkproject.ui.inter; import com.jk.jkproject.ui.entity.LiveGiftInfoBean; public interface LiveGiftSvgaAnimListener extends LiveRelease { void addTimes(LiveGiftInfoBean.DataBean paramLiveGiftResponse); boolean isRunning(); void startAnim(LiveGiftInfoBean.DataBean paramLiveGiftResponse); }
package ai; import game.TextOutput; import java.util.*; import state.Initialisable; import util.*; public class MinMaxAi extends AI { /** * Class to hold the alpha and beta values */ private class PruneValues { public PruneValues(double alpha, double beta) { this.alpha = alpha; this.beta = beta; } public double alpha; public double beta; } private int ply; private BoardScorerBase scorer; private int evals = 0; private int maxEvaluations = -1; private boolean useAlphaBeta = true; private double alphaBetaTolerance = 0.0; private boolean useRandomChoice = false; private double randomChoiceTolerance = 0.0; private boolean useQuiescenceExpansion = true; private int quiescenceDepthLimit = 3; private double quiesenceThreshold = 5.0; private boolean useQuiescentChoice = true; private int depestDepth = 0; private long timeLimit = -1; private long startTime = 0; private long endtime = 0; List<Move> moves = new ArrayList<Move>(); /** * Function to get the best move for the player * @param int playerId The id of the player moving * @return Move the move being proposed */ public Move getMove(int playerId) { evals = 0; startTime = System.currentTimeMillis(); endtime = startTime + timeLimit; if(scorer == null) { TextOutput.printError("Board Scorer Has Not Been Set\n"); System.exit(1); } // initialise the tree with the current state Board currentState = getCurrentState(playerId); scorer.score(currentState); TreeNode<Board> root = new TreeNode<Board>(currentState); Tree<Board> tree = new Tree<Board>(root); // if there are no stored moves (from double or secret tickets) get a new one if(moves.size() == 0) { Board b = max(root, tree, ply, Double.MIN_VALUE, Double.MAX_VALUE); moves = b.getMoves(); //printTreePath(tree); // un-comment to print the tree } // get the next move then remove it from the stack Move currentMove = moves.get(0); moves.remove(0); return currentMove; } /** * This function is used to check if a board is terminal. That is, the tree will * not be expanded from this node * @param board The board we are testing * @param maximising If we are maximising or minimising * @param depth The current depth of the tree expansion * @return If the node is terminal or not */ private boolean isTerminal(Board board, boolean maximising, int depth) { // we have reached the time limit if(timeLimit != -1 && System.currentTimeMillis() > endtime) return true; if(depth < depestDepth) { depestDepth = depth; } if(evals >= maxEvaluations && maxEvaluations > -1) return true; // always stop at a win condition if(depth < ply) if(board.isDetectiveWin() || board.isMrXWin()) return true; // always carry on if depth is less than the standard search params if(depth > 0) return false; // standard terminal test for depth limit without quiesence if(!useQuiescenceExpansion) { if(depth == 0) return true; else return false; } else { // stop at quiescent depth limit if(depth == -quiescenceDepthLimit) return true; // if the node is quiet return true if(isNodeQuiet(board)) return true; return false; } } /** * Function to check if a board is 'quiet' or not. If it is not * it is a candidate for quiescent expansion * @param board The board we are testing * @return If the board is quiet */ private boolean isNodeQuiet(Board board) { double meanDiff = board.getMeanScoreDifference(); if(meanDiff < quiesenceThreshold) return true; else return false; } /** * At a certain node of the tree, this function is used to pick the best board * out of the possible children depending on if we are maximising or minimising * @param boards The list of boards we are checking * @param maximise If we maximise or not * @return The best board */ private Board chooseBoard(List<Board> boards, boolean maximise) { if(useRandomChoice) return makeRandomChoice(boards, maximise); if(useQuiescentChoice) return makeQuiescentChoice(boards, maximise); // standard choice if(maximise) return Collections.max(boards); else return Collections.min(boards); } /** * If we are using the quiescence value in our choice method, this function * choose the set of boards that have the best scores, and order them in terms * of their 'quietness'. It will then choose the least 'quiet' board * @param boards The list of boards * @param maximise If we are maximising or minimising * @return The best board */ private Board makeQuiescentChoice(List<Board> boards, boolean maximise) { List<Board> choices = new ArrayList<Board>(); if(maximise) { Board best = Collections.max(boards); for(int i = boards.size()-1; i >= 0; i--) { if(boards.get(i).getScore() == best.getScore()) choices.add(boards.get(i)); } } else { Board best = Collections.min(boards); for(int i = 0; i < boards.size(); i++) { if(boards.get(i).getScore() == best.getScore()) choices.add(boards.get(i)); } } // sort the choices by quiescence double maxQ = Double.MIN_VALUE; int maxQIndex = 0; for(int i = 0; i < choices.size(); i++) { if(choices.get(i).getMeanScoreDifference() > maxQ) { maxQ = choices.get(i).getMeanScoreDifference(); maxQIndex = i; } } return choices.get(maxQIndex); } /** * If we are suing randomness in our choice of boards, this function * will sort the input list by their scores. It will select the set * of boards that are within the set tolerance value of the best board * and make a random choice from them * @param boards The set of boards * @param maximise If we are maximising or not * @return The best board */ private Board makeRandomChoice(List<Board> boards, boolean maximise) { List<Board> choices = new ArrayList<Board>(); if(maximise) { Board best = Collections.max(boards); //choices.add(best); double threshold = best.getScore() * this.randomChoiceTolerance; for(int i = boards.size()-1; i >= 0; i--) { if(boards.get(i).getScore() >= (best.getScore() - threshold)) choices.add(boards.get(i)); } } else { Board best = Collections.min(boards); //choices.add(best); double threshold = best.getScore() * this.randomChoiceTolerance; for(int i = 0; i < boards.size(); i++) { if(boards.get(i).getScore() <= (best.getScore() + threshold)) choices.add(boards.get(i)); } } // get a random choice int min = 0; int max = choices.size() - 1; int choice = min + (int) (Math.random() * ((max-min) + 1)); return choices.get(choice); } /** * Function to process the maximisation part of the min-max algorithm * @param parent The parent node in the tree * @param tree The tree itself * @param depth The current depth of the tree * @param alpha The current alpha value for the pruning * @param beta The current beta value for the pruning * @return The Best board as a result of the maximisation step */ public Board max(TreeNode<Board> parent, Tree<Board> tree, int depth, double alpha, double beta) { // check for terminal condition if(isTerminal(parent.data(), true, depth)) { return parent.data(); } PruneValues pruneValues = new PruneValues(alpha, beta); // get the child boards List<Board> inputBoards = parent.data().getMrXMoves(false); List<Board> outputBoards = new ArrayList<Board>(); for(int i = 0; i < inputBoards.size(); i++) { // get the board and set the parents value Board board = inputBoards.get(i); scorer.score(board); board.addParentScores(parent.data().getParentScores()); // create the tree node and add it TreeNode<Board> node = new TreeNode<Board>(board); tree.addNode(parent, node); Board sub = min(node, tree, depth-1, pruneValues.alpha, pruneValues.beta); board.setScore(sub.getScore()); outputBoards.add(board); evals++; if(prune(board.getScore(), pruneValues, true)) break; } return chooseBoard(outputBoards, true); } /** * Function to process the minimisation part of the min-max algorithm * @param parent The parent node in the tree * @param tree The tree itself * @param depth The current depth of the tree * @param alpha The current alpha value for the pruning * @param beta The current beta value for the pruning * @return The Best board as a result of the minimisation step */ private Board min(TreeNode<Board> parent, Tree<Board> tree, int depth, double alpha, double beta) { // check for the terminal conditions (winnning) if(isTerminal(parent.data(), false, depth)) { return parent.data(); } // create the object for the alpha and beta values PruneValues pruneValues = new PruneValues(alpha, beta); // get the child boards List<Board> inputBoards = parent.data().getDetectiveMoves(); List<Board> outputBoards = new ArrayList<Board>(); for(int i = 0; i < inputBoards.size(); i++) { // get the board and set the parents value Board board = inputBoards.get(i); scorer.score(board); board.addParentScores(parent.data().getParentScores()); // create the tree node and add it TreeNode<Board> node = new TreeNode<Board>(board); tree.addNode(parent, node); Board sub = max(node, tree, depth-1, pruneValues.alpha, pruneValues.beta); board.setScore(sub.getScore()); outputBoards.add(board); evals++; if(prune(board.getScore(), pruneValues, false)) break; } return chooseBoard(outputBoards, false); } /** * Function to test if we want to prune the tree given the current alpha and beta values * @param score The score of the board * @param pruneValues The pruning values * @param maximise If we are maximising or minimising * @return If we prune or not */ private boolean prune(double score, PruneValues pruneValues, boolean maximise) { if(!useAlphaBeta) return false; if(maximise) { pruneValues.alpha = Math.max(pruneValues.alpha, score); return pruneCheck(pruneValues.alpha, pruneValues.beta); } else { pruneValues.beta = Math.min(pruneValues.beta, score); return pruneCheck(pruneValues.alpha, pruneValues.beta); } } /** * Function to check if we prune the tree or not. If the alphaBeta tolerance * is above 0.0 then this will be taken into account in the pruning descision * @param alpha Current alpha value * @param beta Current beta value * @return If we are pruning at a given node */ private boolean pruneCheck(double alpha, double beta) { double threshold = alpha * alphaBetaTolerance; if(beta > (alpha - threshold)) return false; return true; } /** * Function to get the current info of the player * @param playerId * @return */ private Board.PlayerInfo getPlayerInfo(int playerId) { Board.PlayerInfo info = new Board.PlayerInfo(); info.playerId = playerId; info.position = aiReadable.getNodeId(playerId); info.tickets.put(Initialisable.TicketType.Bus, aiReadable.getNumberOfTickets(Initialisable.TicketType.Bus, playerId)); info.tickets.put(Initialisable.TicketType.Taxi, aiReadable.getNumberOfTickets(Initialisable.TicketType.Taxi, playerId)); info.tickets.put(Initialisable.TicketType.Underground, aiReadable.getNumberOfTickets(Initialisable.TicketType.Underground, playerId)); info.tickets.put(Initialisable.TicketType.SecretMove, aiReadable.getNumberOfTickets(Initialisable.TicketType.SecretMove, playerId)); info.tickets.put(Initialisable.TicketType.DoubleMove, aiReadable.getNumberOfTickets(Initialisable.TicketType.DoubleMove, playerId)); return info; } /** * Set the class that will be scoring the board * @param scorer */ public void setBoardScorer(BoardScorerBase scorer) { this.scorer = scorer; } /** * Function to set the depth of the game tree we are going to explore. * This is without any quiescent expansion * @param ply */ public void setPly(int ply) { this.ply = ply; } /** * Do we want to use alpha beta pruning on the game tree? * @param val */ public void setUseAlphaBetaPruning(boolean val) { this.useAlphaBeta = val; } /** * Function to get the current state of the game given the player id * @param playerId * @return The board representing the current state */ private Board getCurrentState(int playerId) { // set the players HashMap<Integer, Board.PlayerInfo> players = new HashMap<Integer, Board.PlayerInfo>(); for(int id : aiReadable.getDetectiveIdList()) { players.put(id, getPlayerInfo(id)); } for(int id : aiReadable.getMrXIdList()) { players.put(id, getPlayerInfo(id)); } // get the current state and put it as the root Board currentState = new Board(aiReadable.getGraph(), true, players, playerId, null); return currentState; } /** * Function to set the tolerance on the alpha beta pruning. * @param val */ public void setAlphaBetaTolerance(double val) { this.alphaBetaTolerance = val; } /** * Function to print the chosen path by the ai * @param tree The tree to print */ private void printTreePath(Tree<Board> tree) { TreeNode<Board> parent = tree.root(); boolean maxing = true; int depth = 0; while(!parent.isLeaf()) { System.out.print("Depth: " + depth); List<TreeNode<Board>> children = parent.children(); double maxVal = Double.MIN_VALUE; double minVal = Double.MAX_VALUE; int index = 0; for(int i = 0; i < children.size(); i++) { TreeNode<Board> child = children.get(i); double v = child.data().getScore(); System.out.print(" " + v); if(maxing) { if(v > maxVal) { index = i; maxVal = v; } } else { if(v < minVal) { index = i; minVal = v; } } } parent = children.get(index); if(maxing) System.out.print(" maxing\n"); else System.out.print(" mining\n"); List<Double> scores = parent.data().getParentScores(); System.out.print("Parent scores: "); for(double d : scores) { System.out.print(" " + d); } System.out.print(" Mean: " +parent.data().getMeanScoreDifference() + "\n"); maxing = !maxing; depth++; } } /** * Function to decide if we want to use quiescent expansion * @param val If we are using it or not */ public void setUseQuiescenceExpansion(boolean val) { this.useQuiescenceExpansion = val; } /** * This function sets the maximum depth at which the quiescence will * work. For example, if ply = 2 and this value = 2, the total depth * that can be expanded is 2+2=4 * @param depth The depth of quiescent expansion */ public void setQuiescenceDepthLimit(int depth) { this.quiescenceDepthLimit = depth; } /** * This is the threshold at which a node is considered 'quiet' or not. * As the tree is expanded, the estimated score from the parent node is * added to the child. The child then computes the mean difference between * the set of parent scores. If this differences if above the threshold * the node is quiet * @param threshold The quiescent threshold */ public void setQuiescenceThreshold(double threshold) { this.quiesenceThreshold = threshold; } /** * This function allows us to choose the best child board at a given node * by first selecting the best set of nodes, and then ordering them by their * quietness and choosing the lest quiet of them * @param val */ public void setUseQuiescentChoice(boolean val) { this.useQuiescentChoice = val; } /** * Function to set the maximum board evaluations that will be done * bt the AI. This is useful in limiting the ai to make a move * within a certain time. If you set this to -1 there will be no * limit of evaluations * @param max The max evaluations to be done */ public void setMaxEvaluations(int max) { this.maxEvaluations = max; } /** * Function to set if we want to use randomness in our choice of * best child node. * @param val */ public void setUseRandomChoice(boolean val) { this.useRandomChoice = val; } /** * This function sets the tolerance for the inclusion of nodes in * the random selection. The best choice of child at a given node is selected. * if another node is within best+(best*tolerance) then it is included as * part of the random selection * @param tolerance The value of the tolerance */ public void setRandomChoiceTolerance(double tolerance) { this.randomChoiceTolerance = tolerance; } /** * Function to set a time limit for the tree building. If this value is set to * -1 there will be no time limit. Note that this time limit will stop tree * expansion but actual move selection requires more processing. If you use this to * limit your AI to be within a certain time, compensate for this. * @param milliseconds The time limit */ public void setTimeLimit(long milliseconds) { timeLimit = milliseconds; } }
package com.smxknife.java2.nio.channel; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/10/2 */ public class _13_FileChannel_FileLock_2 { public static void main(String[] args) { // 获取此通道的文件给定区域上的锁定 // 在可以锁定该区域之前、已关闭此通道之前、或已中断调用线程之前,将阻塞此方法调用 // 在此方法调用期间,如果另一个线程关闭了此通道,则抛出AsynchronousCloseException // 如果在等待获取锁定的同时中断了调用线程,则将状态设置为中断并抛出FileLockInterruptionException异常 // 如果调用此方法是已设置调用方的中断状态,则立即抛出该异常,不更改线程的调用状态 // 由position和size参数所指定的区域无须包含在实际的底层文件中,设置无须与文件重叠。 // 锁定区域的大小是固定的;如果某个已锁定区域最初包含整个文件,并且文件因扩大而超出了该区域,则该锁定不覆盖此文件的新部分。如果期望文件大小扩容并且要求锁定整个文件,则应锁定position从零开始,size传入大于或等于预计文件的最大值 // 零参数的lock方法只是锁定大小为Long.MAX_VALUE的区域 // 文件锁要么是独占的,要么是共享的 // 共享锁定可以阻止其他并发运行的程序获取重叠的独占锁定,但允许该程序偶去重叠的共享锁定 // 独占锁定则阻止其他程序获取共享锁定或者独占锁定的重叠部分 // 某些操作系统不支持共享锁定,自动对共享锁定转换为独占锁定的请求,可以通过调用所得的锁定对象的isShared()方法来测试新获取的锁定是共享的还是独占的 // 文件锁定是以整个Java虚拟机来保持的。但是不适用于控制同一虚拟机内多个线程对文件的访问 // 验证FileLock lock(long position, long size, boolean shared)是同步的 // 需要FileLock_1先运行,然后再启动FileLock_2,观察FileLock_2的输出,只有在FileLock_1执行完(释放了锁),才能获取锁继续执行,之前一直处于阻塞状态 // lockTest1(); // lockTest4(); // lockTest7(); // lockTest10(); // lockTest12(); // lockTest13(); // lockTest14(); // lockTest15(); fileTryLockTest16(); } private static void fileTryLockTest16() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { System.out.println("2 before tryLock"); FileLock fileLock = channel.tryLock(0, Integer.MAX_VALUE, true); System.out.println("2 after tryLock lock = " + fileLock); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest15() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_2.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { channel.lock(0, Integer.MAX_VALUE, false); System.out.println("2 get lock"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest14() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_2.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { channel.lock(0, Integer.MAX_VALUE, true); System.out.println("2 get lock"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest13() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_2.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { channel.lock(0, Integer.MAX_VALUE, true); System.out.println("2 get lock"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest12() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_2.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { channel.lock(0, Integer.MAX_VALUE, false); System.out.println("2 get lock"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest10() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { channel.write(ByteBuffer.wrap("11111111".getBytes())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest7() { try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) { channel.write(ByteBuffer.wrap("world".getBytes())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void lockTest4() { try(FileChannel channel = new FileOutputStream(_13_FileChannel_FileLock_1.class.getClassLoader() .getResource("channel/_13_FileChannel_fileLock").getPath()).getChannel()) { Thread lockThread2 = new Thread(() -> { try { System.out.println("lockThread2 before lock"); channel.lock(1, 2, false); // 与lockThread一样获取 System.out.println("lockThread2 has get lock"); } catch (IOException e) { e.printStackTrace(); } }); lockThread2.start(); TimeUnit.SECONDS.sleep(1); lockThread2.interrupt(); // 这里应该是lockThread2处于阻塞状态,等待获取fileLock,这里调用interrupt之后,会抛出异常 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private static void lockTest1() { try(FileChannel fileChannel = new RandomAccessFile(new File(_13_FileChannel_FileLock_1.class.getClassLoader().getResource("channel/_13_FileChannel_fileLock").getPath()),"rw").getChannel()) { System.out.println("2_1 begin"); fileChannel.lock(1, 2, false); System.out.println("2_2 end"); TimeUnit.SECONDS.sleep(30); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package test; import publisher.PublishModel; import subscription.SubscriptionCallback; public class DataBucketListner implements SubscriptionCallback { public static final String ref = "DataBucketListner"; @Override public void configUpdate(PublishModel publishModel) { System.out.println("Config update received publishModel = " + publishModel); } }
package com.zhangyanye.didipark.activity; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.ImageLoader.ImageListener; import com.google.gson.Gson; import com.zhangyanye.didipark.R; import com.zhangyanye.didipark.application.MyApplication; import com.zhangyanye.didipark.pojo.Carport; import com.zhangyanye.didipark.pojo.User; import com.zhangyanye.didipark.utils.BFImageCache; import com.zhangyanye.didipark.utils.MyContants; import com.zhangyanye.didipark.utils.SharedPreferencesUtil; import com.zhangyanye.didipark.view.CircleImageView; import com.zhangyanye.didipark.view.MyNotification; import com.zhangyanye.didipark.view.ToolBarOnClickListener; import com.zhangyanye.didipark.view.TopBar; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class AuditActivity extends Activity { private ProgressDialog dialog; private String customer_id; private String carport_id; private ImageLoader imageLoader; private Carport carport; private User user; private Intent intent; private TopBar topbar; private CircleImageView img; private ImageView photo; private ImageListener listener_figure, listener_carport; private TextView tv_nickName, tv_addr, tv_time, tv_phone, tv_num; private String time; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_audit); getBundle(); initView(); getInfo(); } private void getBundle() { topbar = (TopBar) findViewById(R.id.audit_topBar); topbar.setOnTopbarClickListener(new ToolBarOnClickListener() { @Override public void rightBtnClick() { } @Override public void leftBtnClick() { intent.setClassName("com.zhangyanye.didipark.activity", "MainActivity"); if (intent.resolveActivity(getPackageManager()) == null) { // 说明系统中不存在这个activity startActivity(intent); } System.gc(); finish(); } }); Bundle bundle = getIntent().getExtras(); time = bundle.getString("time"); customer_id = bundle.getString("customer_id"); carport_id = bundle.getString("carport_id"); MyNotification manager = MyNotification.getInstance(AuditActivity.this); manager.dismissNotification(Integer.parseInt(customer_id)); } private void initView() { tv_num = (TextView) findViewById(R.id.audit_tv_num); tv_phone = (TextView) findViewById(R.id.audit_tv_phone); tv_time = (TextView) findViewById(R.id.audit_time); tv_addr = (TextView) findViewById(R.id.audit_tv_addr); photo = (ImageView) findViewById(R.id.audit_iv_photo); imageLoader = new ImageLoader(MyApplication.queue, BFImageCache.getInstance()); img = (CircleImageView) findViewById(R.id.audit_iv_figure); tv_nickName = (TextView) findViewById(R.id.audit_tv_nickname); intent = new Intent(AuditActivity.this, MainActivity.class); } private void getInfo() { dialog = new ProgressDialog(AuditActivity.this); dialog.show(); RequestQueue requestQueue = MyApplication.queue; StringRequest stringRequest = new StringRequest(Request.Method.GET, MyContants.URL_ORDER_DETAIL + "customer_id=" + customer_id + "&carport_id=" + carport_id, new Response.Listener<String>() { @Override public void onResponse(String response) { Gson gson = new Gson(); try { Log.e("zyy", response); JSONObject json = new JSONObject(response); user = gson.fromJson(json.get("user").toString(), User.class); user.setNickName(new String(user.getNickName() .getBytes("ISO8859-1"), "utf-8")); carport = gson.fromJson(json.get("carport") .toString(), Carport.class); carport.setAddr(new String(carport.getAddr() .getBytes("ISO8859-1"), "utf-8")); carport.setDescribe(new String(carport .getDescribe().getBytes("ISO8859-1"), "utf-8")); tv_nickName.setText(user.getNickName()); listener_figure = ImageLoader.getImageListener(img, R.drawable.ic_figure_def, R.drawable.ic_figure_def); imageLoader.get(user.getImageUrl(), listener_figure); listener_carport = ImageLoader.getImageListener( photo, R.drawable.ic_carport_def, R.drawable.ic_carport_def); imageLoader.get(json.get("photo").toString(), listener_carport); tv_num.setText("剩余" + carport.getNum() + "个车位"); tv_addr.setText(carport.getAddr()); tv_time.setText(time); tv_phone.setText("手机尾号:" + user.getPhone().substring( user.getPhone().length() - 4, user.getPhone().length())); dialog.cancel(); dialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dialog.dismiss(); dialog.cancel(); Crouton.makeText(AuditActivity.this, "服务器出错!", Style.ALERT, R.id.audit_alternate_view_group) .show(); } }); requestQueue.add(stringRequest); } private void submitResult(final String result) { dialog = new ProgressDialog(AuditActivity.this); dialog.show(); RequestQueue requestQueue = MyApplication.queue; StringRequest stringRequest = new StringRequest(Request.Method.POST, MyContants.URL_ORDER_RESULT, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("zyy", response); dialog.dismiss(); dialog.cancel(); intent.setClassName("com.zhangyanye.didipark.activity", "MainActivity"); if (intent.resolveActivity(getPackageManager()) == null) { // 说明系统中不存在这个activity startActivity(intent); } System.gc(); finish(); finish(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dialog.dismiss(); dialog.cancel(); Crouton.makeText(AuditActivity.this, "服务器出错!", Style.ALERT, R.id.audit_alternate_view_group) .show(); } }) { @Override protected Map<String, String> getParams() { // 在这里设置需要post的参数 Map<String, String> params = new HashMap<String, String>(); params.put("result", result); params.put("carport_id", carport_id); params.put("customer_id", customer_id); params.put( "user_id", SharedPreferencesUtil.getData(AuditActivity.this, "user_id", 0) + ""); return params; } }; requestQueue.add(stringRequest); } public void buttonClick(View v) { switch (v.getId()) { case R.id.audit_agree: submitResult("agree"); break; case R.id.audit_disagree: submitResult("disagree"); break; } } }
package android.support.v7.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public final class ap { public final TypedArray Ww; private final Context mContext; public static ap a(Context context, AttributeSet attributeSet, int[] iArr) { return new ap(context, context.obtainStyledAttributes(attributeSet, iArr)); } public static ap a(Context context, AttributeSet attributeSet, int[] iArr, int i) { return new ap(context, context.obtainStyledAttributes(attributeSet, iArr, i, 0)); } private ap(Context context, TypedArray typedArray) { this.mContext = context; this.Ww = typedArray; } public final Drawable getDrawable(int i) { if (this.Ww.hasValue(i)) { int resourceId = this.Ww.getResourceId(i, 0); if (resourceId != 0) { return h.eJ().a(this.mContext, resourceId, false); } } return this.Ww.getDrawable(i); } public final Drawable bP(int i) { if (this.Ww.hasValue(i)) { int resourceId = this.Ww.getResourceId(i, 0); if (resourceId != 0) { return h.eJ().a(this.mContext, resourceId, true); } } return null; } public final CharSequence getText(int i) { return this.Ww.getText(i); } public final boolean getBoolean(int i, boolean z) { return this.Ww.getBoolean(i, z); } public final int getInt(int i, int i2) { return this.Ww.getInt(i, i2); } public final int bQ(int i) { return this.Ww.getColor(i, -1); } public final int getDimensionPixelOffset(int i, int i2) { return this.Ww.getDimensionPixelOffset(i, i2); } public final int getDimensionPixelSize(int i, int i2) { return this.Ww.getDimensionPixelSize(i, i2); } public final int getLayoutDimension(int i, int i2) { return this.Ww.getLayoutDimension(i, i2); } public final int getResourceId(int i, int i2) { return this.Ww.getResourceId(i, i2); } public final boolean hasValue(int i) { return this.Ww.hasValue(i); } }
package edu.metrostate.ics372.thatgroup.clinicaltrial.android.clinicactivity; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.BasePresenter; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.statemachine.ClinicalTrialState; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.statemachine.ClinicalTrialStateMachine; import edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Clinic; /** * @author That Group */ public class ClinicPresenter implements BasePresenter { private ClinicalTrialStateMachine machine; private ClinicView view = null; private Clinic clinic = null; public ClinicPresenter(ClinicalTrialStateMachine machine) { this.machine = machine; } public void setView(ClinicView view){ this.view = view; } public void setClinic(Clinic clinic) { this.clinic = clinic; } public Clinic getClinic() { if (view != null) { if (clinic == null) { clinic = new Clinic(); } clinic.setId(view.getClinicId()); clinic.setName(view.getClinicName()); clinic.setTrialId(machine.getApplication().getModel().getTrialId()); } return clinic; } /** * */ @Override public void subscribe(){ updateView(); } /** * */ @Override public void unsubscribe(){ } /** * */ public void updateView() { updateView(true); } /** * * @param setData */ public void updateView(boolean setData) { if (view != null && clinic != null) { ClinicalTrialState state = (ClinicalTrialState) machine.getCurrentState(); if (setData) { view.setClinicName(clinic.getName()); view.setDisabledId(!state.canAdd()); view.setDisabledName(!(state.canUpdate() || state.canAdd())); view.setVisibleAddReading(state.canAddReading()); view.setVisibleViewReadings(state.canViewReadings()); view.setVisibleSave((state.canUpdate() || state.canAdd())); view.setDisabledSave(true); view.setClinicId(clinic.getId()); } else { view.setDisabledSave(!(state.canUpdate() || state.canAdd())); } } } }
package com.sinata.rwxchina.component_aboutme.adapter; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.sinata.rwxchina.basiclib.base.BaseActivity; import com.sinata.rwxchina.basiclib.commonclass.activity.InsuranceWebViewActivity; import com.sinata.rwxchina.basiclib.commonclass.activity.ShareWebActivity; import com.sinata.rwxchina.basiclib.utils.appUtils.AppUtils; import com.sinata.rwxchina.basiclib.utils.logUtils.LogUtils; import com.sinata.rwxchina.basiclib.utils.retrofitutils.commonparametersutils.CommonParametersUtils; import com.sinata.rwxchina.basiclib.utils.toastUtils.ToastUtils; import com.sinata.rwxchina.basiclib.utils.userutils.UserUtils; import com.sinata.rwxchina.basiclib.webViewUtils.activity.DefaultWebViewActivity; import com.sinata.rwxchina.component_aboutme.bean.AboutMeFragmentFunctionBean; import com.sinata.rwxchina.basiclib.HttpPath; import com.sinata.rwxchina.basiclib.utils.imageUtils.ImageUtils; import com.sinata.rwxchina.component_aboutme.R; import java.util.List; /** * @author:zy * @detetime:2017/11/21 * @describe:类描述 * @modifyRecord:修改记录 */ public class FunctionRVAdapter extends RecyclerView.Adapter<FunctionRVAdapter.ViewHolder> { private BaseActivity context; private List<AboutMeFragmentFunctionBean> list; private OnItemCilckListener onItemCilckListener; public OnItemCilckListener getOnItemCilckListener() { return onItemCilckListener; } public void setOnItemCilckListener(OnItemCilckListener onItemCilckListener) { this.onItemCilckListener = onItemCilckListener; } public interface OnItemCilckListener { void onItemCilckListener(View view, int postion); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_fagment_aboutme_gv, null); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } public FunctionRVAdapter(BaseActivity context, List<AboutMeFragmentFunctionBean> list) { this.context = context; this.list = list; } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { ImageUtils.showImage(context, HttpPath.IMAGEURL + list.get(position).getImg(), holder.icon); holder.textView.setText(list.get(position).getTitle()); final Bundle bundle = new Bundle(); holder.relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (list.get(position).getIs_url().equals("1")) { //判断是否需要登录 1:需要 0:不需要 if ("1".equals(list.get(position).getIs_must_login())){ if (!UserUtils.isLogin(context)){ return; } } bundle.putString("url", list.get(position).getUrl()); switch (list.get(position).getTitle()){ case "我的爱车": case "我的保单": case "我的分享": if (AppUtils.isLogin(context)){ LogUtils.e("FunctionRVAdapter","isShare="+list.get(position).getIs_share()); if ("1".equals(list.get(position).getIs_share())){ bundle.putString("content", list.get(position).getShare_content()); bundle.putString("share_title", list.get(position).getShare_title()); bundle.putString("url_share", list.get(position).getShare_url()); bundle.putString("uid", CommonParametersUtils.getUid(context)); context.startActivity(ShareWebActivity.class,bundle); }else { bundle.putBoolean("isTitle",false); context.startActivity(DefaultWebViewActivity.class, bundle); } } break; case "审车记录": Intent intent=new Intent(context,InsuranceWebViewActivity.class); Bundle shenche=new Bundle(); shenche.putString("url", list.get(position).getUrl()); if (AppUtils.isLogin( context)){ shenche.putString("uid", CommonParametersUtils.getUid(context)); } shenche.putString("token", CommonParametersUtils.getToken(context)); intent.putExtras(shenche); context.startActivity(intent); break; default: bundle.putBoolean("isTitle",true); context.startActivity(DefaultWebViewActivity.class, bundle); break; } } } }); } @Override public int getItemCount() { return list.size(); } class ViewHolder extends RecyclerView.ViewHolder { private ImageView icon; private TextView textView; private RelativeLayout relativeLayout; public ViewHolder(View itemView) { super(itemView); icon = itemView.findViewById(R.id.item_function_iv); textView = itemView.findViewById(R.id.item_function_tv); relativeLayout = itemView.findViewById(R.id.item_function_rl); } } }
package com.flutterwave.raveandroid.di.modules; import com.flutterwave.raveandroid.francMobileMoney.FrancMobileMoneyUiContract; import javax.inject.Inject; import dagger.Module; import dagger.Provides; @Module public class FrancModule { private FrancMobileMoneyUiContract.View view; @Inject public FrancModule(FrancMobileMoneyUiContract.View view) { this.view = view; } @Provides public FrancMobileMoneyUiContract.View providesContract() { return view; } }
package com.yjp.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @ClassName: indexController * @Description: TODO * @author: v_jpyin * @date: 2020/6/5 */ @RestController public class InitController { @GetMapping("/") public String init(){ return "Hello World"; } }
package projection; import utility.Point2D; import utility.Ray; public abstract class Projection { public abstract Ray createRay(Point2D point); }
package com.sinotao.business.dao.entity; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * 检查项目信息表 * @author 佟磊 */ @Table(name = "t_clinicar_check_item") public class ClinicarCheckItem { /** * 代理主键 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 删除标记 */ private Boolean deleted; /** * 登记表ID */ @Column(name = "check_id") private Integer checkId; /** * 检查项目编号 */ @Column(name = "item_code") private String itemCode; /** * 检查项目名称 */ @Column(name = "item_name") private String itemName; /** * 科室编号 */ @Column(name = "dpt_code") private String dptCode; /** * 科室名称 */ @Column(name = "dpt_name") private String dptName; /** * 该项检查是否完成 */ private Boolean completed; /** * 弃检 */ private Boolean canceled; /** * 小结 */ private String summary; /** * 结论 */ private String conclusion; /** * 建议 */ private String advice; /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the deleted */ public Boolean getDeleted() { return deleted; } /** * @param deleted the deleted to set */ public void setDeleted(Boolean deleted) { this.deleted = deleted; } /** * @return the checkId */ public Integer getCheckId() { return checkId; } /** * @param checkId the checkId to set */ public void setCheckId(Integer checkId) { this.checkId = checkId; } /** * @return the itemCode */ public String getItemCode() { return itemCode; } /** * @param itemCode the itemCode to set */ public void setItemCode(String itemCode) { this.itemCode = itemCode; } /** * @return the itemName */ public String getItemName() { return itemName; } /** * @param itemName the itemName to set */ public void setItemName(String itemName) { this.itemName = itemName; } /** * @return the dptCode */ public String getDptCode() { return dptCode; } /** * @param dptCode the dptCode to set */ public void setDptCode(String dptCode) { this.dptCode = dptCode; } /** * @return the dptName */ public String getDptName() { return dptName; } /** * @param dptName the dptName to set */ public void setDptName(String dptName) { this.dptName = dptName; } /** * @return the completed */ public Boolean getCompleted() { return completed; } /** * @param completed the completed to set */ public void setCompleted(Boolean completed) { this.completed = completed; } /** * @return the canceled */ public Boolean getCanceled() { return canceled; } /** * @param canceled the canceled to set */ public void setCanceled(Boolean canceled) { this.canceled = canceled; } /** * @return the summary */ public String getSummary() { return summary; } /** * @param summary the summary to set */ public void setSummary(String summary) { this.summary = summary; } /** * @return the conclusion */ public String getConclusion() { return conclusion; } /** * @param conclusion the conclusion to set */ public void setConclusion(String conclusion) { this.conclusion = conclusion; } /** * @return the advice */ public String getAdvice() { return advice; } /** * @param advice the advice to set */ public void setAdvice(String advice) { this.advice = advice; } }
package com.tencent.mm.ui.tools; class PressImageView$1 implements Runnable { final /* synthetic */ PressImageView uBj; PressImageView$1(PressImageView pressImageView) { this.uBj = pressImageView; } public final void run() { this.uBj.setPressed(false); this.uBj.invalidate(); } }
package edu.john.practice.singleton; /** * 第二种:慢性子式 1/3 * (延迟创建这个实例对象) * 1.构造器私有化 * 2.类当中用一个静态变量来保存唯一实例 * 3.提供一个静态方法来,获取这个实例对象 * * 线程不安全(适合单线程) * @author John * @date 8/24/2020 1:35 AM */ public class Singleton4 { private static Singleton4 instance; private Singleton4(){} public static Singleton4 getInstance() { if (instance == null) { try { // 会导致线程阻塞 Thread.sleep(100); // 为了模拟线程不安全,加入睡眠 } catch (InterruptedException e) { e.printStackTrace(); } instance = new Singleton4(); } return instance; } }
package pro.mickey.spring.data.util; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.id.IdentifierGenerator; public class IdGenerator implements IdentifierGenerator { public String id; public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { Number number = new MickeySnowflake(123).generateKey(); long idLong = number.longValue(); return idLong; } }
package com.rofour.baseball.common; import java.io.IOException; import java.text.SimpleDateFormat; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; /** * @ClassName: JsonMapper * @Description: 自定义 ObjectMapper * @author wq * @date 2016年4月6日 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class JsonMapper extends ObjectMapper{ private static final long serialVersionUID = -5106109699769842408L; public JsonMapper() { //忽略位置的属性 this.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //设置时间格式 this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); //将null 值 转换成空字符串 this.getSerializerProvider().setNullValueSerializer(new JsonSerializer() { public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(""); } }); //空字符串 反序列时 转换为null this.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); } }
package com.sunny.token.response; import lombok.Getter; /** * 响应CODE */ public enum ResponseCode{ SUCCESS("0000", "成功"), ERROR("9999","异常"), TOKEN_IS_NULL("4001", "TOKEN 为空"), NO_LOGIN("4002", "您还没有登录"), ; ResponseCode(String code, String message){ this.code = code; this.message = message; } @Getter private String code; @Getter private String message; /** * 判定状态是否是成功 * @return */ public boolean equals(String code){ return this.code.equals(code); } }
package com.responsyve.codegen.domain; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import lombok.Data; @Data @XmlRootElement(name="field") @XmlAccessorType(XmlAccessType.FIELD) public class CodeGenField { @XmlAttribute(name="name") private String name; @XmlAttribute(name="type") private String type; @XmlElementWrapper(name="annotations") @XmlElement(name="annotation") private List <CodeGenAnnotation> annotations; }
package com.example.mifareclassicreader; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import com.example.mifareclassicreader.CustomAdapter; import com.example.mifareclassicreader.MainActivity; import com.example.mifareclassicreader.Sector; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.content.res.Resources; import android.graphics.Color; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.MifareClassic; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.os.Build; public class MainActivity extends Activity { private Intent mOldIntent = null; private NfcAdapter mAdapter; private TextView tv; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); private static final byte[] KEY_A_2 = new byte[] { (byte)0x67, (byte)0xa1, (byte)0x34, (byte)0xe0, (byte)0x4a, (byte) 0x6a}; private static final byte[] KEY_A = new byte[] { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte) 0xff}; /** * Filtro para activar/desactivar el foreground dispatch. */ private IntentFilter[] intentFiltersArray; /** * Lista de tecnologías que soporta la app. */ private String[][] techListsArray; /** * PendingIntent que utiliza el Foreground Dispatch System (FDS) */ private PendingIntent pendingIntent; /** * ListView para visualizar los sectores */ ListView list; /** * Adapter para el listview */ CustomAdapter adapter; /** * La imagen que se muestra al principio */ ImageView im; /** * Arraylist para guardar los sectores que se muestran en la lista */ public ArrayList<Sector> CustomListViewValuesArr = new ArrayList<Sector>(); private boolean listaHecha; /** * Check for NFC hardware, Mifare Classic support and for external storage. * If the directory structure and the std. keys files is not already there * it will be created. Also, at the first run of this App, a warning * notice will be displayed. * @see #copyStdKeysFilesIfNecessary() */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); Toast.makeText(getApplicationContext(), "Posicione el tag", Toast.LENGTH_SHORT).show(); //Inicialización del Pending Intent para que sea esta aplicación la prioridad cuando esté abierta pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); mAdapter = NfcAdapter.getDefaultAdapter(this); //tv = (TextView) findViewById(R.id.textView1); //tv.setText(""); //tv.setTextSize(12); if(mAdapter == null){ //tv.setText("Active NFC en su dispositivo"); } /** Se hace un PendingIntent para darle prioridad a esta aplicación * de que se quede abierta cuando se detecte un tag. Android "llena" este intent * con los detalles del tag cuando se escanea. */ IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); intentFiltersArray = new IntentFilter[] {ndef, }; techListsArray = new String[][] { new String[] { MifareClassic.class.getName() } }; /** * Esto es lo que concierne a la listview */ list= ( ListView )findViewById( R.id.list); //list.setEnabled(false); //list.setOnClickListener(null); /**************** Create Custom Adapter *********/ //setListData(); adapter=new CustomAdapter( this, CustomListViewValuesArr,getResources() ); listaHecha = false; //list.setAdapter( adapter ); im = (ImageView) findViewById(R.id.imageView1); im.setImageResource(R.drawable.home); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } /** * Cuando la actividad pierde focus se deshabilita el FDS. */ public void onPause(){ super.onPause(); mAdapter.disableForegroundDispatch(this); } /** * Cuando se reanuda la actividad se habilita el FDS. */ public void onResume(){ super.onResume(); mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray); } public void onNewIntent(Intent intent) { //tv.setText(""); if(!listaHecha){ list.setAdapter( adapter ); im.setImageResource(android.R.color.transparent); listaHecha = true; View someView = findViewById(R.id.imageView1); View root = someView.getRootView(); //root.setBackgroundColor(getResources().getColor(Color.GRAY)); root.setBackgroundColor(Color.parseColor("#bFbFbF")); } if(CustomListViewValuesArr.size()>0){ CustomListViewValuesArr.clear(); } //CustomListViewValuesArr.clear(); Toast.makeText(getApplicationContext(), "Tag detectado", Toast.LENGTH_SHORT).show(); //tv.append("Technology: \n"); Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); for (String tech : tagFromIntent.getTechList()) { // tv.append(tech + "\n"); } boolean autenticado = false; MifareClassic mfc = MifareClassic.get(tagFromIntent); try { String metaInfo = ""; //Enable I/O operations to the tag from this TagTechnology object. mfc.connect(); int type = mfc.getType(); int sectorCount = mfc.getSectorCount(); String typeS = ""; switch (type) { case MifareClassic.TYPE_CLASSIC: typeS = "TYPE_CLASSIC"; break; case MifareClassic.TYPE_PLUS: typeS = "TYPE_PLUS"; break; case MifareClassic.TYPE_PRO: typeS = "TYPE_PRO"; break; case MifareClassic.TYPE_UNKNOWN: typeS = "TYPE_UNKNOWN"; break; } metaInfo += "Card type:" + typeS + " with " + sectorCount + " Sectors, " + mfc.getBlockCount() + " Blocks Storage Space: " + mfc.getSize() + "B\n"; for (int j = 0; j < sectorCount; j++) { //Authenticate a sector with key A. //autenticado = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT); autenticado = mfc.authenticateSectorWithKeyA(j, KEY_A); int bCount; int bIndex; Sector sector = new Sector(); sector.setNumero(j); if (autenticado) { sector.setAutenticado(true); metaInfo += "Sector " + j + ": Verified successfully\n"; bCount = mfc.getBlockCountInSector(j); bIndex = mfc.sectorToBlock(j); for (int i = 0; i < bCount; i++) { byte[] data = mfc.readBlock(bIndex); /* String str = new String(data, Charset.forName("US-ASCII")); metaInfo += "Block " + bIndex + " : " + str + "\n";*/ metaInfo += "Block " + bIndex + " : " + bytesToHex(data) + "\n"; sector.setBloqueValue(i, bytesToHex(data)); bIndex++; } } else { sector.setAutenticado(false); metaInfo += "Sector " + j + ": Verified failure\n"; } CustomListViewValuesArr.add( sector ); } // tv.append(metaInfo); } catch (Exception e) { e.printStackTrace(); } adapter.notifyDataSetChanged(); } public String readTag(Tag tag) { //Hace una instancia de un tag Mifare Classic MifareClassic mifare = MifareClassic.get(tag); try { //Abre la comunicación con el tag mifare.connect(); //Autentica el sector 0 //mifare.authenticateSectorWithKeyA(0,hexStringToByteArray("FFFFFFFFFFFF")); //Lee el bloque 0 byte[] payload = mifare.readBlock(0); //Retorna lo que lee en el bloque 0 en formato String return new String(payload, Charset.forName("US-ASCII")); } catch (IOException e) { //Se encarga de los errores que haya en la lectura Log.e(mifare.getClass().getSimpleName(), "IOException while closing MifareClassic...", e); } finally { if (mifare != null) { try { //Cerrar la comunicación con el tag mifare.close(); } catch (IOException e) { Log.e(mifare.getClass().getSimpleName(), "Error closing tag...", e); } } } return null; } private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } private void processIntent(Intent intent){ Toast.makeText(getApplicationContext(), "Tag detectado!!!", Toast.LENGTH_SHORT).show(); Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); for (String tech : tagFromIntent.getTechList()) { tv.append(tech + "\n"); } } private String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public void setListData() { for (int i = 0; i < 16; i++) { Sector sched = new Sector(); /******* Firstly take data in model object ******/ sched.setNumero(i); /******** Take Model Object in ArrayList **********/ CustomListViewValuesArr.add( sched ); } } }
package com.example.vcv.ui.calendar; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.vcv.R; import com.example.vcv.utility.CalendarOrder; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; /** * @author Mattia Da Campo e Andrea Dalle Fratte * @version 1.0 */ public class ModifyCalendarFragment extends Fragment { private CalendarViewModel calendarViewModel; private CalendarOrder currentOrder; private Boolean useRemoteDate; private CalendarFragment calendarFragment; private TextView hourStart, hourEnd, job; private EditText etJob, etStartHour, etEndHour, etTotalHour, etEquipment, etNote, twExtraHour; private Button modify; /** * Constructor * * @param calendarFragment */ public ModifyCalendarFragment(CalendarFragment calendarFragment) { this.calendarFragment = calendarFragment; currentOrder = calendarFragment.currentOrder; useRemoteDate = calendarFragment.useRemoteDate; } /** * Method used to create the fragment * * @param inflater * @param container * @param savedInstanceState * @return */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { CalendarViewModel.context = this.getContext(); CalendarViewModel.currentCalendarOrder = currentOrder; calendarViewModel = ViewModelProviders.of(this).get(CalendarViewModel.class); View root = inflater.inflate(R.layout.fragment_modifycalendar, container, false); initGraphic(root); setData(); modify.setOnClickListener(new View.OnClickListener() { /** * Method to handle modify button's click * * @param view */ @Override public void onClick(View view) { try { CalendarOrder newOrder = new CalendarOrder( currentOrder.dateCalendarOrder, hourStart.getText().toString(), hourEnd.getText().toString(), etTotalHour.getText().toString(), etJob.getText().toString(), currentOrder.confirmed, etEquipment.getText().toString(), etNote.getText().toString(), etStartHour.getText().toString(), etEndHour.getText().toString() ); if (currentOrder.equals(newOrder)) { calendarViewModel.saveChanges(newOrder); etStartHour.setText(newOrder.realHourFrom); etEndHour.setText(newOrder.realHourTo); calendarFragment.checkOnLocalData(newOrder); twExtraHour.setText(getExtraordinaryHours(newOrder.realHourFrom, newOrder.realHourTo, newOrder.defaultHourToWork)); currentOrder = newOrder; Toast.makeText(getContext(), getString(R.string.save_data_success), Toast.LENGTH_SHORT).show(); } else { Log.e("SAVE_ORDER_CHANGES", "Error to save changes of specific order"); Toast.makeText(getContext(), getString(R.string.please_change_fields), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { Log.e("SAVE_ORDER_CHANGES", "Error to save changes of specific order " + e.getMessage()); Toast.makeText(getContext(), getString(R.string.please_change_fields), Toast.LENGTH_SHORT).show(); } } }); return root; } /** * Method used to initialize graphics components * * @param root */ private void initGraphic(View root) { hourStart = root.findViewById(R.id.HourStart); hourEnd = root.findViewById(R.id.HourEnd); job = root.findViewById(R.id.job); etJob = root.findViewById(R.id.et_Job); etStartHour = root.findViewById(R.id.et_startHour); etEndHour = root.findViewById(R.id.et_endHour); etTotalHour = root.findViewById(R.id.et_totalHour); etEquipment = root.findViewById(R.id.et_equipment); etNote = root.findViewById(R.id.et_note); twExtraHour = root.findViewById(R.id.et_extraordinaryHour); modify = root.findViewById(R.id.button_modify); } /** * Method used to set value in graphic components */ private void setData() { hourStart.setText(currentOrder.hourFrom); hourEnd.setText(currentOrder.hourTo); job.setText(currentOrder.job); etJob.setText(currentOrder.job); etTotalHour.setText(currentOrder.defaultHourToWork); if (!currentOrder.realHourFrom.equals("00:00")) { etStartHour.setText(currentOrder.realHourFrom); } if (!currentOrder.realHourTo.equals("00:00")) { etEndHour.setText(currentOrder.realHourTo); } if (!currentOrder.equipment.equals("")) { etEquipment.setText(currentOrder.equipment); } if (!currentOrder.note.equals("")) { etNote.setText(currentOrder.note); } if (!currentOrder.realHourTo.equals("00:00") && !currentOrder.realHourFrom.equals("00:00")) { twExtraHour.setText(getExtraordinaryHours(currentOrder.realHourFrom, currentOrder.realHourTo, currentOrder.defaultHourToWork)); } if (!useRemoteDate) { modify.setEnabled(true); modify.setBackgroundResource(R.drawable.button_confirm); } else { modify.setEnabled(false); modify.setBackgroundResource(R.drawable.button_disabled); } } /** * Method used to get extra hours * * @param startHour * @param endHour * @param dftHour * @return extra hours */ public String getExtraordinaryHours(String startHour, String endHour, String dftHour) { long extraSeconds = ((getSeconds(endHour) - getSeconds(startHour)) - getSeconds(dftHour)); return getHourFromSeconds(extraSeconds); } /** * Method used to convert string to long that rappresent hours and minutes in seconds * * @param hour * @return long that rappresent hours and minutes in seconds */ private long getSeconds(String hour) { long hourSeconds = Integer.parseInt(hour.split(":")[0]) * 3600; long minutesSeconds = Integer.parseInt(hour.split(":")[1]) * 60; return hourSeconds + minutesSeconds; } /** * Method used to convert long into String that rappresent hour and minutes from seconds * * @param seconds * @return String that rappresent hour and minutes from seconds */ private String getHourFromSeconds(long seconds) { String res = ""; if (seconds > 0) { if ((seconds / 3600.0) < 1.0) { String minutes = Double.toString(seconds / 60.0); res += "00:" + String.format("%02d", Integer.parseInt(minutes.split("\\.")[0])); } else { String hourString = Double.toString(seconds / 3600.0); int hourInt = Integer.parseInt(hourString.split("\\.")[0]); res += String.format("%02d", hourInt); res += ":"; String minutes = Double.toString((seconds - (3600 * hourInt)) / 60.0); res += String.format("%02d", Integer.parseInt(minutes.split("\\.")[0])); } } else { res = "00:00"; } return res; } }
package com.javaex.ex01; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class BuffedStramApp { public static void main(String[] args)throws IOException { InputStream in = new FileInputStream("C:\\javaStudy\\img.jpg"); //통로만 준비 BufferedInputStream bin=new BufferedInputStream(in); //BufferedInputStream(bin)안에 in의 값을 넣어 주었다. OutputStream out= new FileOutputStream("C:\\javaStudy\\Buffimg.jpg"); BufferedOutputStream bout = new BufferedOutputStream(out); //BufferedOutputStream안에 out의 값을 넣어줌 //BufferedOutputStream안에는 이미 배열이 담겨져 있음 System.out.println("복사시작"); while (true) { int bData = bin.read(); //bin의 리턴 값이 bData에 담김 System.out.println("복사끝"); if (bData==-1) { break; } bout.write(bData); } bin.close(); //프로그램에는 bin이 연결되어 있으므로 bin을 닫으면 못둘어간다. bout.close(); } }
/* * Copyright (C) 2020-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.common.domain.entity; import com.hedera.mirror.common.exception.InvalidEntityException; import lombok.experimental.UtilityClass; /** * Encodes given shard, realm, num into 8 bytes long. * <p/> * Only 63 bits (excluding signed bit) are used for encoding to make it easy to encode/decode using mathematical * operations too. That's because javascript's (REST server) support for bitwise operations is very limited (truncates * numbers to 32 bits internally before bitwise operation). * <p/> * Format: <br/> First bit (sign bit) is left 0. <br/> Next 15 bits are for shard, followed by 16 bits for realm, and * then 32 bits for entity num. <br/> This encoding will support following ranges: <br/> shard: 0 - 32767 <br/> realm: 0 * - 65535 <br/> num: 0 - 4294967295 <br/> Placing entity num in the end has the advantage that encoded ids <= * 4294967295 will also be human readable. */ @UtilityClass public class EntityIdEndec { static final int SHARD_BITS = 15; static final int REALM_BITS = 16; static final int NUM_BITS = 32; // bits for entity num private static final long SHARD_MASK = (1L << SHARD_BITS) - 1; private static final long REALM_MASK = (1L << REALM_BITS) - 1; private static final long NUM_MASK = (1L << NUM_BITS) - 1; public static Long encode(long shardNum, long realmNum, long entityNum) { if (shardNum > SHARD_MASK || shardNum < 0 || realmNum > REALM_MASK || realmNum < 0 || entityNum > NUM_MASK || entityNum < 0) { throw new InvalidEntityException("Invalid entity ID: " + shardNum + "." + realmNum + "." + entityNum); } return (entityNum & NUM_MASK) | (realmNum & REALM_MASK) << NUM_BITS | (shardNum & SHARD_MASK) << (REALM_BITS + NUM_BITS); } public static EntityId decode(long encodedId, EntityType entityType) { if (encodedId < 0) { throw new InvalidEntityException("encodedId can not be negative: " + encodedId); } long shard = encodedId >> (REALM_BITS + NUM_BITS); long realm = (encodedId >> NUM_BITS) & REALM_MASK; long num = encodedId & NUM_MASK; return EntityId.of(shard, realm, num, entityType); } }
package com.stackedtalent.portal.service; import com.stackedtalent.portal.entity.CandidateEmployment; import java.util.List; public interface CandidateEmploymentService { List<CandidateEmployment> getEmploymentListByCandidateId(Long candidateId); }
package com.zhowin.miyou.recommend.adapter; import androidx.annotation.NonNull; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.zhowin.base_library.model.UserLevelInfo; import com.zhowin.base_library.model.UserRankInfo; import com.zhowin.base_library.utils.GlideUtils; import com.zhowin.miyou.R; import com.zhowin.miyou.main.utils.GenderHelper; import com.zhowin.miyou.recommend.model.GZBUserList; /** * 贵族榜单 */ public class NobleListAdapter extends BaseQuickAdapter<GZBUserList, BaseViewHolder> { public NobleListAdapter() { super(R.layout.include_noble_list_item_view); } @Override protected void convert(@NonNull BaseViewHolder helper, GZBUserList item) { if (0 == helper.getAdapterPosition()) { helper.setBackgroundRes(R.id.tvLevelText, R.drawable.list_shouhu1_iocn) .setText(R.id.tvLevelText, ""); } else if (1 == helper.getAdapterPosition()) { helper.setBackgroundRes(R.id.tvLevelText, R.drawable.list_shouhu2_iocn) .setText(R.id.tvLevelText, ""); } else if (2 == helper.getAdapterPosition()) { helper.setBackgroundRes(R.id.tvLevelText, R.drawable.list_shouhu3_iocn) .setText(R.id.tvLevelText, ""); } else { helper.setText(R.id.tvLevelText, String.valueOf(helper.getAdapterPosition() + 1)) .setBackgroundRes(R.id.tvLevelText, 0); } helper.setText(R.id.tvUserNickName, item.getAvatar()) .setText(R.id.tvRewardNam, item.getStatus()) .setImageResource(R.id.ivUserSexImage, GenderHelper.getSexResource(item.getGender())); GlideUtils.loadUserPhotoForLogin(mContext, item.getProfilePictureKey(), helper.getView(R.id.civUserHeadPhoto)); UserLevelInfo userLevelInfo = item.getLevelObj(); if (userLevelInfo != null) { helper.setGone(R.id.tvUserLevel, 0 != userLevelInfo.getLevel()) .setText(R.id.tvUserLevel, "V" + userLevelInfo.getLevel()); } UserRankInfo userRankInfo = item.getRank(); if (userRankInfo != null) { helper.setGone(R.id.ivUserKnightImage, true); GlideUtils.loadObjectImage(mContext, userRankInfo.getRankPictureKey(), helper.getView(R.id.ivUserKnightImage)); } else { helper.setGone(R.id.ivUserKnightImage, false); } } }
package com.ibm.order.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class OrderDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String customerName; private Date date; private String shippingAddress; private String orderItems; private double totals; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getShippingAddress() { return shippingAddress; } public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; } public String getOrderItems() { return orderItems; } public void setOrderItems(String orderItems) { this.orderItems = orderItems; } public double getTotals() { return totals; } public void setTotals(double totals) { this.totals = totals; } }
package ducksim.goose; import java.awt.Color; import ducksim.behaviors.FlyBehavior.FlyBehavior; import ducksim.behaviors.FlyBehavior.FlyWithWings; import ducksim.behaviors.QuackBehavior.NormalQuack; import ducksim.behaviors.QuackBehavior.QuackBehavior; public class Goose { public static final FlyBehavior FLY_BEHAVIOR = new FlyWithWings(); public static final QuackBehavior QUACK_BEHAVIOR = new NormalQuack(); public static final Color COLOR = Color.WHITE; public String getHonk() { return "Honk!"; } public String getName() { return "Goose"; } }
/* * Copyright 2008 Eckhart Arnold (eckhart_arnold@hotmail.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package tddd24.ajgallery.client.gwtphotoalbum; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; /** * Class <code>HTMLLayout</code> allows to code the layout of the image panel, * control panel and caption in HTML. * * <p>Insances of the class are instantiated with a chunk of HTML code. * The elements of the slide show, i.e. * control panel, image panel and caption will be attached by to tags (or * DOM elements respectively) that have the ids "display", "controlPanel" and * "caption" of the HTML code. * * @author ecki * */ public class HTMLLayout extends Layout { /** An example HTML chunk that puts the control panel at the top, * the image panel in the middle and the caption at the bottom. */ public static final String DEFAULT_HTML = "<table class=\"imageBackground\" style=\"width:100%; height:100%;\">" + "<tr><td style=\"width:100%\"><hr class=\"tiledSeparator\" /></td>" + "<td id=\"controlPanel\"></td></tr>" + "<tr><td id=\"display\" colspan=\"2\" style=\"width:100%; height:100%;\"></td></tr>" + "<tr><td colspan=\"2\"><hr class=\"tiledSeparator\" /></td></tr>" + "<tr><td id=\"caption\" colspan=\"2\" align=\"center\" style=\"color:white;\"></td></tr>" + "</table>"; /** The html panel widget that represents the html chunk. */ protected HTMLPanel htmlPanel; /** * The constructor of class <code>HTMLLayout</code>. * * @param collection the image collection info object * @param HTMLChunk a chunk of HTML code that contains tags with * the id's "display", "controlPanel" and "caption" * @param configuration the configuration string of the layout */ public HTMLLayout(ImageCollectionInfo collection, String HTMLChunk, String configuration) { super(collection, configuration); htmlPanel = new HTMLPanel(HTMLChunk); htmlPanel.add(imagePanel, "display"); if (caption != null) { htmlPanel.add(caption, "caption"); // caption.setSpacing(true); } if (controlPanel != null) { htmlPanel.add(controlPanel, "controlPanel"); } } /** * An alternative constructor that only takes the image collection info * object and the HTML chunk as parameters. * * @param collection the image collection info object * @param HTMLChunk the HTML chunk defining the layout */ public HTMLLayout(ImageCollectionInfo collection, String HTMLChunk) { this(collection, HTMLChunk, detectConfiguration(HTMLChunk)); } /** * An alternative constructor that only takes the image collection info * as parameter and otherwise uses <code>DEFAULT_HTML</code> for the * layout. * * @param collection the image collection info object */ public HTMLLayout(ImageCollectionInfo collection) { this(collection, DEFAULT_HTML, detectConfiguration(DEFAULT_HTML)); } /* (non-Javadoc) * @see de.eckhartarnold.client.Layout#getRootWidget() */ @Override public Widget getRootWidget() { return htmlPanel; } private static String detectConfiguration(String HTMLChunk) { String cfg = "I"; if (HTMLChunk.indexOf("\"caption\"") >= 0) cfg += "C"; if (HTMLChunk.indexOf("\"controlPanel\"") >= 0) cfg += "P"; return cfg; } }
package com.home.test; import java.util.HashMap; import java.util.List; import java.util.Map; import com.orientechnologies.common.util.OCallable; import com.orientechnologies.orient.core.intent.OIntentMassiveInsert; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraph; public class PublisherAdTagService { static{ int mb = 1024*1024; //Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); System.out.println("##### Heap utilization statistics [MB] #####"); //Print used memory System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb); //Print free memory System.out.println("Free Memory:" + runtime.freeMemory() / mb); //Print total available memory System.out.println("Total Memory:" + runtime.totalMemory() / mb); //Print Maximum available memory System.out.println("Max Memory:" + runtime.maxMemory() / mb); } /* static{ try { System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("/home/pubmatic/git/pizzaconnections/OrientClassDiagramCreator/src/main/java/generated/orient.log",true)))); } catch (FileNotFoundException e) { e.printStackTrace(); } } */ public static void pushDataIntoDatabase() { List<Map<String, Object>> pubAdTagData = new FirstExample().getData( "select id,name from publisher_site_ad limit 255000", Constants.PUBLISHER_AD_TAG.toLowerCase()); OrientBaseGraph graphNoTx = OrientGraphConnectionPool.getInstance().getOrientGraph(false); graphNoTx.declareIntent(new OIntentMassiveInsert()); VertexUtility.dropClass(graphNoTx, Constants.PUBLISHER_AD_TAG); VertexUtility.dropIndex(graphNoTx, "publisheradtag_idIndex"); createClass(graphNoTx); long tms = System.currentTimeMillis(); int count = 0; if (graphNoTx instanceof OrientGraph) { // ((OrientGraph) graphNoTx).begin(); count = insertData(graphNoTx, pubAdTagData, count); // ((OrientGraph) graphNoTx).commit(); } else { count = insertData(graphNoTx, pubAdTagData, count); } graphNoTx.declareIntent(null); System.out.println(count + " created. " + (System.currentTimeMillis() - tms) / 1000); } private static int insertData(OrientBaseGraph graphNoTx, List<Map<String, Object>> pubAdTagData, int count) { if (pubAdTagData.size() > 0) { for (Map<String, Object> pubAdTag : pubAdTagData) { // ((OrientGraph) graphNoTx).begin(); Map<Object, Object> propMap = new HashMap<Object, Object>(); propMap.put("adTagId", pubAdTag.get("publisheradtag_id")); propMap.put("name", pubAdTag.get("name")); graphNoTx.addVertex("class:PublisherAdTag", propMap); // ((OrientGraph) graphNoTx).commit(); count++; } } return count; } public static void createClass(final OrientBaseGraph graphNoTx) { if (graphNoTx instanceof OrientGraph) { ((OrientGraph) graphNoTx).executeOutsideTx(new OCallable<Object, OrientBaseGraph>() { public Object call(OrientBaseGraph iArgument) { OClass publisherAdTag = graphNoTx.getRawGraph().getMetadata().getSchema() .createClass(Constants.PUBLISHER_AD_TAG, (OClass) graphNoTx.getVertexBaseType()); publisherAdTag.createProperty("adTagId", OType.LONG).setMandatory(true); publisherAdTag.createProperty("name", OType.STRING).setMandatory(true); publisherAdTag.createIndex("publisheradtag_idIndex", OClass.INDEX_TYPE.UNIQUE, "adTagId"); return null; } }); } else { OClass publisherAdTag = graphNoTx.getRawGraph().getMetadata().getSchema() .createClass(Constants.PUBLISHER_AD_TAG, (OClass) graphNoTx.getVertexBaseType()); publisherAdTag.createProperty("adTagId", OType.LONG).setMandatory(true); publisherAdTag.createProperty("name", OType.STRING).setMandatory(true); publisherAdTag.createIndex("publisheradtag_idIndex", OClass.INDEX_TYPE.UNIQUE, "adTagId"); } } public static void main(String[] args) { try { // pushDataIntoDatabase(); VertexUtility.printAllVertex(Constants.PUBLISHER_AD_TAG); // VertexUtility.deleteAllVertex(OrientGraphConnectionPool.getInstance().getOrientGraph(true), // Constants.PUBLISHER_AD_TAG,"publisheradtag_idIndex"); // VertexUtility.printAllVertex(Constants.PUBLISHER_AD_TAG); } finally { } } } // https://github.com/orientechnologies/orientdb-docs/wiki/Java-Schema-Api // /https://github.com/orientechnologies/orientdb-docs/wiki/Graph-Database-Tinkerpop // http://pettergraff.blogspot.in/2014/01/getting-started-with-orientdb.html // http://devdocs.inightmare.org/introduction-to-orientdb-graph-edition/ // https://github.com/orientechnologies/orientdb-docs/wiki/Java-Schema-Api
package soduku.main; public class Coordinates { int row; int column; Coordinates(int column, int row){ this.row = row; this.column = column; } public String toString(){ return "Row "+this.row+" - column "+this.column; } }
package com.cyberwith.service; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.widget.Toast; import androidx.annotation.Nullable; public class MyService extends Service implements MediaPlayer.OnCompletionListener { MediaPlayer mediaPlayer; @Nullable @Override public IBinder onBind(Intent intent) { Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show(); return null; } @Override public void onCreate() { mediaPlayer = MediaPlayer.create(this, R.raw.batuque_bom); mediaPlayer.setOnCompletionListener(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(getApplicationContext(), "Service Start", Toast.LENGTH_LONG).show(); if (!mediaPlayer.isPlaying()){ mediaPlayer.start(); } return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Toast.makeText(getApplicationContext(), "Service Destroy", Toast.LENGTH_LONG).show(); if (mediaPlayer.isPlaying()){ mediaPlayer.stop(); } mediaPlayer.release(); } @Override public void onCompletion(MediaPlayer mp) { stopSelf(); } }
package boj; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class BOJ_1987_알파벳 { private static int R; private static int C; private static int max; private static int count; private static String[][] map; private static int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}}; private static Set<String> alpha; private static boolean[] visited; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); R = Integer.parseInt(st.nextToken()); C = Integer.parseInt(st.nextToken()); map = new String[R][C]; for (int r = 0; r < R; r++) { map[r] = br.readLine().split(""); //equal 주의 } alpha = new HashSet<>(); max =0; count =0; alpha.add(map[0][0]); dfs(new Pair(0,0)); System.out.println(max); } /*public static void dfs(Pair p) { count++; max = Math.max(max, count); for (int i = 0; i < dir.length; i++) { int a = p.x + dir[i][0]; int b = p.y + dir[i][1]; if(isIn(a,b) && !alpha.contains(map[a][b])) { alpha.add(map[a][b]); dfs(new Pair(a,b)); alpha.remove(map[a][b]); count--; } } }*/ public static void dfs(Pair p) { count++; max = Math.max(max, count); for (int i = 0; i < dir.length; i++) { int a = p.x + dir[i][0]; int b = p.y + dir[i][1]; int tmp =map[a][b].charAt(0)-65; if(isIn(a,b) && !visited[tmp]) { alpha.add(map[a][b]); dfs(new Pair(a,b)); alpha.remove(map[a][b]); count--; } } } public static class Pair{ int x; int y; public Pair(int x, int y) { super(); this.x = x; this.y = y; } @Override public String toString() { return "Pair [x=" + x + ", y=" + y + "]"; } } public static boolean isIn(int r, int c) { return r>=0 && c>=0 && r < R && c < C; } }
package capeonato; import java.sql.*; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author danielmora */ public class Ingresar_Jugadores extends javax.swing.JFrame { DefaultTableModel model; PreparedStatement pr; // para realizar consultas en la base de dats necesitamos esta variable ResultSet rs; // /** * Creates new form Ingresar_Jugadores */ public Ingresar_Jugadores() { initComponents(); limpiar(); bloquear(); mostrarDatos(); } public void mostrarDatos() { String[] titulos = {"Cedula", "Nombre", "Apellido", "Direccion", "Estado-Civil", "Sexo", "Edad"}; // ponemos los titulos en el Vector String[] t_datos = new String[7]; String sql = "select * from Jugadores "; model = new DefaultTableModel(null, titulos); // agregamos los titulos Conexion conec = new Conexion(); // objeto de tipo conxion Connection conex = conec.getConnection(); try { Statement st = conex.createStatement(); rs = st.executeQuery(sql);// ejecutamos la sentencia sql while (rs.next()) { // me permita ingresar los datos al jtable t_datos[0] = rs.getString("cedula"); t_datos[1]=rs.getString("Nombre"); t_datos[2]=rs.getString("Apellido"); t_datos[3]=rs.getString("Direccion"); t_datos[4]=rs.getString("estado_civil"); t_datos[5]=rs.getString("sexo"); model.addRow(t_datos); // llenamos el vector } tablaMostrarDatos.setModel(model); // agegamos el defaultmodel } catch (Exception er) { System.err.println("Error" + er); } } public void limpiar() { cajaCedula.setText(""); cajaNombre.setText(""); cajaApellido.setText(""); cajaDireccion.setText(""); cajaEdad.setText(""); } public void bloquear() { cajaCedula.setEnabled(false); cajaNombre.setEnabled(false); cajaApellido.setEnabled(false); cajaDireccion.setEnabled(false); cajaEdad.setEnabled(false); botonNuevo.setEnabled(true); botonGuardar.setEnabled(false); botonCancelar.setEnabled(false); botonEliminar.setEnabled(false); } public void habilitar() { cajaCedula.setEnabled(true); cajaNombre.setEnabled(true); cajaApellido.setEnabled(true); cajaDireccion.setEnabled(true); cajaEdad.setEnabled(true); botonNuevo.setEnabled(false); botonGuardar.setEnabled(true); botonCancelar.setEnabled(true); botonEliminar.setEnabled(true); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jColorChooser1 = new javax.swing.JColorChooser(); jColorChooser2 = new javax.swing.JColorChooser(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); cajaNombre = new javax.swing.JTextField(); cajaApellido = new javax.swing.JTextField(); cajaDireccion = new javax.swing.JTextField(); comboBoxEstado = new javax.swing.JComboBox<>(); comboBoxSexo = new javax.swing.JComboBox<>(); cajaEdad = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); botonNuevo = new javax.swing.JButton(); botonGuardar = new javax.swing.JButton(); botonCancelar = new javax.swing.JButton(); botonSalir = new javax.swing.JButton(); botonModificar = new javax.swing.JButton(); botonEliminar = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); cajaCedula = new javax.swing.JTextField(); jScrollPane3 = new javax.swing.JScrollPane(); tablaMostrarDatos = new javax.swing.JTable(); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane2.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Nombre :"); jLabel2.setText("Apellido :"); jLabel3.setText("Direccion :"); jLabel4.setText("Estado civil :"); jLabel5.setText("Sexo :"); jLabel6.setText("Edad :"); cajaNombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cajaNombreActionPerformed(evt); } }); cajaApellido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cajaApellidoActionPerformed(evt); } }); cajaDireccion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cajaDireccionActionPerformed(evt); } }); comboBoxEstado.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Soltero", "Casado" })); comboBoxEstado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { comboBoxEstadoActionPerformed(evt); } }); comboBoxSexo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Femenino", "Masculino", "Otros" })); cajaEdad.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cajaEdadActionPerformed(evt); } }); jLabel7.setForeground(new java.awt.Color(15, 15, 15)); jLabel7.setText("Ingreso Jugadores"); botonNuevo.setText("NUEVO"); botonNuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonNuevoActionPerformed(evt); } }); botonGuardar.setText("GUARDAR"); botonGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonGuardarActionPerformed(evt); } }); botonCancelar.setText("CANCELAR"); botonCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonCancelarActionPerformed(evt); } }); botonSalir.setText("SALIR"); botonSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonSalirActionPerformed(evt); } }); botonModificar.setText("MODIFICAR"); botonModificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonModificarActionPerformed(evt); } }); botonEliminar.setText("ELIMINAR"); botonEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonEliminarActionPerformed(evt); } }); jLabel8.setText("Cedula"); cajaCedula.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cajaCedulaActionPerformed(evt); } }); tablaMostrarDatos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPane3.setViewportView(tablaMostrarDatos); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(botonNuevo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(botonGuardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botonCancelar)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboBoxSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(comboBoxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cajaEdad, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel8)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cajaNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE) .addComponent(cajaApellido) .addComponent(cajaDireccion) .addComponent(cajaCedula))))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(botonModificar, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(botonEliminar, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(botonSalir, javax.swing.GroupLayout.Alignment.LEADING))) .addGroup(layout.createSequentialGroup() .addGap(151, 151, 151) .addComponent(jLabel7)) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(34, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(cajaCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(cajaNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(cajaApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(botonModificar) .addGap(38, 38, 38) .addComponent(botonEliminar))))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(cajaDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(comboBoxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(comboBoxSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(cajaEdad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botonNuevo) .addComponent(botonGuardar) .addComponent(botonCancelar) .addComponent(botonSalir)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void botonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonNuevoActionPerformed habilitar(); cajaNombre.requestFocus(); // habilita el cursor en la casilla nombrada }//GEN-LAST:event_botonNuevoActionPerformed private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed bloquear(); }//GEN-LAST:event_botonCancelarActionPerformed private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed this.dispose(); }//GEN-LAST:event_botonSalirActionPerformed private void cajaNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cajaNombreActionPerformed cajaNombre.transferFocus(); }//GEN-LAST:event_cajaNombreActionPerformed private void cajaApellidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cajaApellidoActionPerformed cajaApellido.transferFocus(); }//GEN-LAST:event_cajaApellidoActionPerformed private void cajaDireccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cajaDireccionActionPerformed cajaDireccion.transferFocus(); }//GEN-LAST:event_cajaDireccionActionPerformed private void cajaEdadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cajaEdadActionPerformed cajaEdad.transferFocus(); }//GEN-LAST:event_cajaEdadActionPerformed private void botonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGuardarActionPerformed Conexion conec = new Conexion(); // llamamos al objeto conctar de nuestraclase Conexion Connection conex = conec.getConnection();// Creamos nuestra variable de conxion String cedula, nombre, apellido, direccion, estadoCivil, sexo, edad, sql = ""; // creamos las variables temporales para almenar lo que contiene las cajas de texto cedula = cajaCedula.getText(); nombre = cajaNombre.getText(); apellido = cajaApellido.getText(); direccion = cajaDireccion.getText(); estadoCivil = comboBoxEstado.getSelectedItem().toString(); sexo = comboBoxSexo.getSelectedItem().toString(); edad = cajaEdad.getText(); sql = "insert into Jugadores(cedula,Nombre,Apellido,Direccion,estado_civil,sexo,edad) values(?,?,?,?,?,?,?)";// creamos la sentencia sql try { // CallableStatement ps = conex.prepareCall("call insertarJugadores(?,?,?,?,?,?,?)"); PreparedStatement ps = conex.prepareStatement(sql); ps.setString(1, cedula); ps.setString(2, nombre); ps.setString(3, apellido); ps.setString(4, direccion); ps.setString(5, estadoCivil); ps.setString(6, sexo); ps.setString(7, edad); int result = ps.executeUpdate(); // ejecutamos la inserccion en la base de datos if (result > 0) { JOptionPane.showMessageDialog(null, "Registro Insertado correctamente "); bloquear(); mostrarDatos(); } else { JOptionPane.showMessageDialog(null, " Error al Insertar el Registro "); } } catch (Exception ex) { System.err.println("Error" + ex); } }//GEN-LAST:event_botonGuardarActionPerformed private void cajaCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cajaCedulaActionPerformed cajaCedula.transferFocus(); }//GEN-LAST:event_cajaCedulaActionPerformed private void comboBoxEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxEstadoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_comboBoxEstadoActionPerformed private void botonModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonModificarActionPerformed try{ Conexion conec = new Conexion(); // llamamos al objeto conctar de nuestraclase Conexion Connection conex = conec.getConnection(); pr=conex.prepareStatement("update Jugadores set cedula=?,Nombre=?,Apellido=?,Direccion=?,estado_civil=?,sexo=?,edad=?"); //CallableStatement pr = conex.prepareCall("call modificarJugadores (?,?,?,?,?,?,?)"); pr.setString(1,cajaCedula.getText()); pr.setString(2,cajaNombre.getText()); pr.setString(3,cajaApellido.getText()); pr.setString(4,cajaDireccion.getText()); pr.setString(5,comboBoxEstado.getSelectedItem().toString()); pr.setString(6,comboBoxSexo.getSelectedItem().toString()); pr.setString(7,cajaEdad.getText()); int resultado = pr.executeUpdate(); // ejecutamos la Modificacion en la base de datos if (resultado>0) { JOptionPane.showMessageDialog(null,"Registro Modificado correctamente "); limpiar(); mostrarDatos(); } else{ JOptionPane.showMessageDialog(null,"Error al ingresar el Registro "); } } catch(Exception ex){ System.err.println("Error"+ex); } }//GEN-LAST:event_botonModificarActionPerformed private void botonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEliminarActionPerformed try{ Conexion conec = new Conexion(); // llamamos al objeto conctar de nuestraclase Conexion Connection conex = conec.getConnection(); pr=conex.prepareStatement("delete from Jugadores where cedula=?"); pr.setString(1,cajaCedula.getText()); int resultado = pr.executeUpdate(); // ejecutamos la Eliminacion en la base de datos if (resultado>0) { JOptionPane.showMessageDialog(null,"Registro Eliminado correctamente "); limpiar(); mostrarDatos(); } else{ JOptionPane.showMessageDialog(null,"Error al ELIMINAR el Registro "); } } catch(Exception ex){ System.err.println("Error"+ex); } }//GEN-LAST:event_botonEliminarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Ingresar_Jugadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Ingresar_Jugadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Ingresar_Jugadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Ingresar_Jugadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Ingresar_Jugadores().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonCancelar; private javax.swing.JButton botonEliminar; private javax.swing.JButton botonGuardar; private javax.swing.JButton botonModificar; private javax.swing.JButton botonNuevo; private javax.swing.JButton botonSalir; private javax.swing.JTextField cajaApellido; private javax.swing.JTextField cajaCedula; private javax.swing.JTextField cajaDireccion; private javax.swing.JTextField cajaEdad; private javax.swing.JTextField cajaNombre; private javax.swing.JComboBox<String> comboBoxEstado; private javax.swing.JComboBox<String> comboBoxSexo; private javax.swing.JColorChooser jColorChooser1; private javax.swing.JColorChooser jColorChooser2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTable jTable1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTable tablaMostrarDatos; // End of variables declaration//GEN-END:variables }
package com.lzh.net.handler; import java.util.ArrayList; import java.util.List; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.bytes.ByteArrayDecoder; import io.netty.handler.codec.bytes.ByteArrayEncoder; import io.netty.handler.codec.string.LineEncoder; import io.netty.handler.timeout.IdleStateHandler; public class ByteInitializer extends ChannelInitializer<Channel>{ private List<ChannelHandler> last = new ArrayList<>(); private List<ChannelHandler> first = new ArrayList<>(); private int TIMEOUT = -1; @Override protected void initChannel(Channel channel) throws Exception { // TODO Auto-generated method stub ChannelPipeline pipeline = channel.pipeline(); // pipeline.addLast(new LineBasedFrameDecoder(100*1024)); pipeline.addLast(new ByteArrayDecoder()); pipeline.addLast(new ByteArrayEncoder()); pipeline.addLast(new IdleStateHandler(TIMEOUT,TIMEOUT,TIMEOUT)); for(int i =0;i<last.size();i++){ pipeline.addLast(last.get(i)); } for(int i =0;i<first.size();i++){ pipeline.addFirst(first.get(i)); } } public ByteInitializer addLast(ChannelHandler handler) { last.add(handler); return this; } public ByteInitializer addFirst(ChannelHandler handler) { first.add(handler); return this; } public int getTIMEOUT() { return TIMEOUT; } public ByteInitializer setTIMEOUT(int tIMEOUT) { TIMEOUT = tIMEOUT; return this; } }
package com.tencent.mm.plugin.appbrand.jsapi.f.a; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.View; import android.view.ViewGroup; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.appbrand.compat.a.c; import com.tencent.mm.plugin.appbrand.e$b; import com.tencent.mm.pluginsdk.q; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public final class b { public static SensorManager ejl; private static HashMap<String, HashMap<String, c>> fSQ = new HashMap(); private static HashMap<String, e$b> fSR = new HashMap(); private static Set<c> fSS = new HashSet(); public static com.tencent.mm.plugin.appbrand.r.b.b fST; public static a fSU; private static class a implements SensorEventListener { private float fSV = 0.0f; private long timestamp = 200; public final void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.sensor.getType() == 3) { long currentTimeMillis = System.currentTimeMillis() - this.timestamp; float ay = q.ay(sensorEvent.values[0]); if (currentTimeMillis > 200 && Math.abs(ay - this.fSV) > 3.0f) { synchronized (b.fSQ) { for (HashMap values : b.fSQ.values()) { for (c cVar : values.values()) { if (!(cVar == null || !cVar.fSX || cVar.isBackground || cVar.fSY == null)) { d dVar = cVar.fSY; dVar.fTV = ay; float heading = dVar.getHeading(); if (dVar.fTv != null) { x.d("MicroMsg.AppbrandMapLocationPoint", "updateRotation rotation:%f", new Object[]{Float.valueOf(heading)}); dVar.fTv.setRotation(heading); } } } } } this.fSV = ay; this.timestamp = System.currentTimeMillis(); } } } public final void onAccuracyChanged(Sensor sensor, int i) { } } private static synchronized void init() { synchronized (b.class) { x.i("MicroMsg.AppBrandMapManager", "init"); if (fST == null) { fST = new 1(); com.tencent.mm.plugin.appbrand.r.b.a.b.aoC().a(fST); } if (fSU == null) { fSU = new a(); SensorManager sensorManager = (SensorManager) ad.getContext().getSystemService("sensor"); ejl = sensorManager; ejl.registerListener(fSU, sensorManager.getDefaultSensor(3), 1); } } } public static synchronized void a(c cVar) { synchronized (b.class) { x.i("MicroMsg.AppBrandMapManager", "registerListener map:%s", new Object[]{cVar}); fSS.add(cVar); if (fSS.size() == 1) { init(); } } } private static synchronized void uninit() { synchronized (b.class) { x.i("MicroMsg.AppBrandMapManager", "uninit"); if (fST != null) { x.i("MicroMsg.AppBrandMapManager", "locationListener uninit"); com.tencent.mm.plugin.appbrand.r.b.a.b.aoC().b(fST); fST = null; } if (!(fSU == null || ejl == null)) { x.i("MicroMsg.AppBrandMapManager", "sensorListener uninit"); ejl.unregisterListener(fSU); ejl = null; fSU = null; } } } public static synchronized void b(c cVar) { synchronized (b.class) { x.i("MicroMsg.AppBrandMapManager", "unregisterListener map:%s", new Object[]{cVar}); fSS.remove(cVar); if (fSS.size() == 0) { uninit(); } } } public static c a(Context context, String str, int i, int i2, boolean z) { if (i2 == -1) { x.e("MicroMsg.AppBrandMapManager", "[createMapView]INVALID_MAP_ID"); return null; } HashMap hashMap; synchronized (fSQ) { HashMap hashMap2 = (HashMap) fSQ.get(str); if (hashMap2 == null) { e$b e_b; hashMap = new HashMap(); fSQ.put(str, hashMap); synchronized (fSR) { e_b = (e$b) fSR.get(str); } if (e_b == null) { x.i("MicroMsg.AppBrandMapManager", "[initLifeListener] appId:%s", new Object[]{str}); fSR.put(str, new 2(str)); } } else { hashMap = hashMap2; } } c cVar = (c) hashMap.get(i + "&" + i2); if (cVar != null) { x.i("MicroMsg.AppBrandMapManager", "map is exist, return"); View view = cVar.getView(); if (view == null || !ViewGroup.class.isInstance(view.getParent())) { return cVar; } ((ViewGroup) view.getParent()).removeView(view); return cVar; } x.i("MicroMsg.AppBrandMapManager", "createMapView appId:%s, componentId:%d mapId:%d", new Object[]{str, Integer.valueOf(i), Integer.valueOf(i2)}); com.tencent.mm.plugin.appbrand.compat.a.b l = ((c) g.l(c.class)).l(context, z); l.adv(); l.onResume(); cVar = new c(context, str, i2, l); hashMap.put(i + "&" + i2, cVar); x.i("MicroMsg.AppBrandMapManager", "appId:%s, map count:%d", new Object[]{str, Integer.valueOf(hashMap.size())}); return cVar; } public static c E(String str, int i, int i2) { if (i2 == -1) { x.e("MicroMsg.AppBrandMapManager", "[getMapView]INVALID_MAP_ID"); return null; } synchronized (fSQ) { HashMap hashMap = (HashMap) fSQ.get(str); if (hashMap == null) { return null; } c cVar = (c) hashMap.get(i + "&" + i2); return cVar; } } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static void F(java.lang.String r9, int r10, int r11) { /* r8 = 2; r7 = 1; r6 = 0; r1 = fSQ; monitor-enter(r1); r0 = fSQ; Catch:{ all -> 0x003d } r0 = r0.get(r9); Catch:{ all -> 0x003d } r0 = (java.util.HashMap) r0; Catch:{ all -> 0x003d } if (r0 != 0) goto L_0x0012; L_0x0010: monitor-exit(r1); Catch:{ all -> 0x003d } L_0x0011: return; L_0x0012: monitor-exit(r1); Catch:{ all -> 0x003d } r1 = new java.lang.StringBuilder; r1.<init>(); r1 = r1.append(r10); r2 = "&"; r1 = r1.append(r2); r1 = r1.append(r11); r1 = r1.toString(); r1 = r0.get(r1); r1 = (com.tencent.mm.plugin.appbrand.jsapi.f.a.c) r1; if (r1 != 0) goto L_0x0040; L_0x0033: r0 = "MicroMsg.AppBrandMapManager"; r1 = "[destroyMapView] mapview not exist, err"; com.tencent.mm.sdk.platformtools.x.e(r0, r1); goto L_0x0011; L_0x003d: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x003d } throw r0; L_0x0040: r2 = "MicroMsg.AppBrandMapManager"; r3 = "destoryMapView appId:%s, componentId:%d, mapId:%d"; r4 = 3; r4 = new java.lang.Object[r4]; r4[r6] = r9; r5 = java.lang.Integer.valueOf(r10); r4[r7] = r5; r5 = java.lang.Integer.valueOf(r11); r4[r8] = r5; com.tencent.mm.sdk.platformtools.x.i(r2, r3, r4); r2 = new java.lang.StringBuilder; r2.<init>(); r2 = r2.append(r10); r3 = "&"; r2 = r2.append(r3); r2 = r2.append(r11); r2 = r2.toString(); r0.remove(r2); r2 = r0.size(); if (r2 > 0) goto L_0x00ae; L_0x007b: r2 = fSQ; monitor-enter(r2); r3 = fSQ; Catch:{ all -> 0x00cd } r3.remove(r9); Catch:{ all -> 0x00cd } b(r1); Catch:{ all -> 0x00cd } monitor-exit(r2); Catch:{ all -> 0x00cd } r2 = "MicroMsg.AppBrandMapManager"; r3 = "[uninitLifeListener] appId:%s"; r4 = new java.lang.Object[r7]; r4[r6] = r9; com.tencent.mm.sdk.platformtools.x.i(r2, r3, r4); r3 = fSR; monitor-enter(r3); r2 = fSR; Catch:{ all -> 0x00d0 } r2 = r2.get(r9); Catch:{ all -> 0x00d0 } r2 = (com.tencent.mm.plugin.appbrand.e$b) r2; Catch:{ all -> 0x00d0 } monitor-exit(r3); Catch:{ all -> 0x00d0 } if (r2 == 0) goto L_0x00a5; L_0x00a2: com.tencent.mm.plugin.appbrand.e.b(r9, r2); L_0x00a5: r2 = fSR; monitor-enter(r2); r3 = fSR; Catch:{ all -> 0x00d3 } r3.remove(r9); Catch:{ all -> 0x00d3 } monitor-exit(r2); Catch:{ all -> 0x00d3 } L_0x00ae: r1.onPause(); r1.onDestroy(); r1 = "MicroMsg.AppBrandMapManager"; r2 = "[destroyMapView]appid:%s, map count:%d"; r3 = new java.lang.Object[r8]; r3[r6] = r9; r0 = r0.size(); r0 = java.lang.Integer.valueOf(r0); r3[r7] = r0; com.tencent.mm.sdk.platformtools.x.i(r1, r2, r3); goto L_0x0011; L_0x00cd: r0 = move-exception; monitor-exit(r2); Catch:{ all -> 0x00cd } throw r0; L_0x00d0: r0 = move-exception; monitor-exit(r3); Catch:{ all -> 0x00d0 } throw r0; L_0x00d3: r0 = move-exception; monitor-exit(r2); Catch:{ all -> 0x00d3 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.appbrand.jsapi.f.a.b.F(java.lang.String, int, int):void"); } }
package replicatorg.drivers.commands; import replicatorg.drivers.Driver; import replicatorg.drivers.RetryException; public class DisableFan implements DriverCommand { int toolhead = -1; ///lazy auto-detect tool public DisableFan() {} public DisableFan(int toolhead) { this.toolhead = toolhead; } @Override public void run(Driver driver) throws RetryException { driver.disableFan(toolhead); } }
package com.hikki.sergey.montecarlo.component; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; public class Divider extends View { private Resources mResources; public static int HORIZONTAL = -1; public static int VERTICAL = -2; public Divider(Context context, int type) { super(context, null); mResources = getResources(); if (type == HORIZONTAL){ this.setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, getDps(1))); this.setPadding(0,getDps(2), 0, getDps(2)); } else { this.setLayoutParams(new LinearLayout.LayoutParams(getDps(2), LinearLayoutCompat.LayoutParams.MATCH_PARENT)); this.setPadding(0, getDps(2), getDps(2),0); } this.setBackgroundColor(Color.LTGRAY); } public Divider(Context context, AttributeSet attrs) { super(context, attrs); } private int getDps(int pixels){ float scale = mResources.getDisplayMetrics().density; int dpAsPixels = (int) (pixels*scale + 0.5f); return dpAsPixels; } }
package io.github.vibrouter.hardware; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import java.util.HashSet; import java.util.Set; public class RotationSensor implements SensorEventListener { public interface OnRotationChangeListener { void onRotationChange(float newRotation); } private SensorManager mSensorManager; private Set<OnRotationChangeListener> mListeners = new HashSet<>(); public RotationSensor(Context context) { mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } public void startUpdating() { Sensor rotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); mSensorManager.registerListener(this, rotationSensor, SensorManager.SENSOR_DELAY_UI); } public void stopUpdating() { mSensorManager.unregisterListener(this); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() != Sensor.TYPE_ROTATION_VECTOR) { return; } float[] rotationVectorReading = new float[3]; System.arraycopy(event.values, 0, rotationVectorReading, 0, rotationVectorReading.length); float rotation = clipAngle(computeDeviceOrientation(rotationVectorReading)); announceNewRotation(rotation); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing for now } public void registerOnRotationChangeListener(OnRotationChangeListener listener) { mListeners.add(listener); } public void unregisterOnRotationChangeListener(OnRotationChangeListener listener) { mListeners.remove(listener); } private void announceNewRotation(float rotation) { for (OnRotationChangeListener listener : mListeners) { listener.onRotationChange(rotation); } } private float computeDeviceOrientation(float[] values) { final float[] orientationAngles = new float[3]; float[] rotationMatrix = new float[9]; SensorManager.getRotationMatrixFromVector(rotationMatrix, values); SensorManager.getOrientation(rotationMatrix, orientationAngles); for (int i = 0; i < orientationAngles.length; ++i) { orientationAngles[i] = (float) Math.toDegrees(orientationAngles[i]); } return orientationAngles[0]; } private float clipAngle(float rotation) { return (rotation < 0) ? rotation + 360.0f : rotation; } }
package com.research.api.table; import org.apache.flink.core.fs.Path; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.TableEnvironment; import org.apache.flink.table.api.java.StreamTableEnvironment; import org.apache.flink.table.descriptors.FileSystem; import org.apache.flink.table.descriptors.Schema; import java.util.Objects; /** * @fileName: TableEnvCreate.java * @description: table环境创建以及create table * @author: by echo huang * @date: 2020-03-09 16:27 */ public class TableEnvCreate { public static void main(String[] args) { StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.getExecutionEnvironment(); //create flink stream table env EnvironmentSettings envSetting = EnvironmentSettings.newInstance().useOldPlanner() .withBuiltInCatalogName("stream-catalog") .inStreamingMode().build(); StreamTableEnvironment streamTabEnv = StreamTableEnvironment.create(streamEnv, envSetting); //create table //创建一个临时表 Table pojoTable = streamTabEnv.scan("X").select("xxx"); streamTabEnv.registerTable("pojoTable", pojoTable); //connector streamTabEnv.connect(new FileSystem().path(String.valueOf(new Path(Objects.requireNonNull(TableEnvCreate.class.getClassLoader().getResource("word.txt")).getPath())))) .withFormat(null) .withSchema(new Schema()) .inAppendMode() .registerTableSource("text"); //create blink stream table env EnvironmentSettings envBlinkSetting = EnvironmentSettings.newInstance().useBlinkPlanner() .withBuiltInCatalogName("blink-stream-catalog") .inStreamingMode().build(); StreamTableEnvironment blinkTableEnv = StreamTableEnvironment.create(streamEnv, envBlinkSetting); //create blink batch table env EnvironmentSettings bbSettings = EnvironmentSettings.newInstance().useBlinkPlanner().inBatchMode().build(); TableEnvironment bbTableEnv = TableEnvironment.create(bbSettings); } }
package IB; import java.util.ArrayList; /** * Created by joetomjob on 3/8/18. */ public class TreeTraversalRecursive { public void inorderTraversal1(TreeNode a, ArrayList<Integer> res){ if(a==null) { return; } inorderTraversal1(a.left,res); res.add(a.val); inorderTraversal1(a.right,res); } public void preorderTraversal1(TreeNode a, ArrayList<Integer> res){ if(a==null) { return; } res.add(a.val); preorderTraversal1(a.left,res); preorderTraversal1(a.right,res); } public void postorderTraversal1(TreeNode a, ArrayList<Integer> res){ if(a==null) { return; } postorderTraversal1(a.left,res); postorderTraversal1(a.right,res); res.add(a.val); } public ArrayList<Integer> inorderTraversal(TreeNode a){ ArrayList<Integer> res = new ArrayList<>(); inorderTraversal1(a,res); return res; } public ArrayList<Integer> preorderTraversal(TreeNode a){ ArrayList<Integer> res = new ArrayList<>(); preorderTraversal1(a,res); return res; } public ArrayList<Integer> postorderTraversal(TreeNode a){ ArrayList<Integer> res = new ArrayList<>(); postorderTraversal1(a,res); return res; } public static void main(String[] args) { TreeNode a = new TreeNode(9); TreeNode b = new TreeNode(8); TreeNode c = new TreeNode(7); TreeNode d = new TreeNode(6); TreeNode e = new TreeNode(10); TreeNode f = new TreeNode(11); TreeNode g = new TreeNode(12); a.left = b; b.right = c; b.left = d; a.right = f; f.left = e; f.right = g; TreeTraversalRecursive in = new TreeTraversalRecursive(); ArrayList<Integer> res = new ArrayList<>(); res = in.inorderTraversal(a); for (Integer x:res) { System.out.print(x); System.out.print('\t'); } System.out.print('\n'); res = in.preorderTraversal(a); for (Integer x:res) { System.out.print(x); System.out.print('\t'); } System.out.print('\n'); res = in.postorderTraversal(a); for (Integer x:res) { System.out.print(x); System.out.print('\t'); } // node a = new node(9); // node a = new node(9); } }
package vegoo.stockcommon.db.redis.hq; import java.text.ParseException; import java.util.Date; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import vegoo.commons.DateUtil; import vegoo.commons.redis.RedisService; import vegoo.stockcommon.bo.KDayService; import vegoo.stockcommon.bo.JgccService; import vegoo.stockcommon.dao.KDayDao; import vegoo.stockcommon.db.redis.RedisBoServiceImpl; @Component (name = "KDayServiceImpl", immediate = true) public class KDayServiceImpl extends RedisBoServiceImpl implements KDayService, ManagedService{ private static final Logger logger = LoggerFactory.getLogger(KDayServiceImpl.class); @Reference protected RedisService redis; static String getKeyOfKDay(String stockCode) { return getKey(TBL_KDAY, stockCode); } static String getKeyOfKDay(String stockCode, Date rDate) { return getKey(TBL_KDAY, stockCode, rDate); } static String getKeyOfKDay(String stockCode, String rDate) { return getKey(TBL_KDAY, stockCode, rDate); } @Override public void updated(Dictionary<String, ?> properties) throws ConfigurationException { // TODO Auto-generated method stub } @Override public Date getEarliestTradeDate(String stockCode) { Set<String> result = redis.zrange(getKeyOfKDay(stockCode), 0, 0); if(result==null) { return null; } try { for(String s : result) { return DateUtil.parseDate(s); } } catch (ParseException e) { } return null; } @Override public Date getLatestTradeDate(String stockCode) { return getLatestTradeDate(stockCode, new Date()); } @Override public Date getLatestTradeDate(String stockCode, Date date) { String result = redis.getNearest(getKeyOfKDay(stockCode), date.getTime(), true); if(result==null) { return null; } try { return DateUtil.parseDate(result); } catch (ParseException e) { return null; } } @Override public void saveKDayData(List<KDayDao> newItems) { newItems.forEach((dao)->{ Date rDate = dao.getTransDate(); Map<String, String> props = new HashMap<>(); props.put("O", String.valueOf(dao.getOpen())); props.put("H", String.valueOf(dao.getHigh())); props.put("L", String.valueOf(dao.getLow())); props.put("C", String.valueOf(dao.getClose())); props.put("V", String.valueOf(dao.getVolume())); props.put("A", String.valueOf(dao.getAmount())); props.put("CR", String.valueOf(dao.getChangeRate())); //涨幅 props.put("AR", String.valueOf(dao.getAmplitude())); // 振幅 props.put("TR", String.valueOf(dao.getTurnoverRate())); // 换手 redis.hmset(getKeyOfKDay(dao.getSCode(), rDate), props); redis.zadd(getKeyOfKDay(dao.getSCode()), rDate.getTime(), DateUtil.formatDate(rDate)); }); } @Override public double getOpen(String sCode, Date transDate) { return redis.getDoubleValue(getKeyOfKDay(sCode, transDate),"O"); } @Override public double getHigh(String stockCode, Date date) { return redis.getDoubleValue(getKeyOfKDay(stockCode, date),"H"); } public double getHigh(String stockCode, String date) { return redis.getDoubleValue(getKeyOfKDay(stockCode, date),"H"); } @Override public double getLow(String sCode, Date transDate) { return redis.getDoubleValue(getKeyOfKDay(sCode, transDate),"L"); } public double getLow(String sCode, String transDate) { return redis.getDoubleValue(getKeyOfKDay(sCode, transDate),"L"); } @Override public double getClose(String sCode, Date transDate) { return redis.getDoubleValue(getKeyOfKDay(sCode, transDate),"C"); } @Override public double getZhangFu(String stockCode, Date beginDate, Date endDate) throws Exception { Date transDate1 = getLatestTradeDate(stockCode, beginDate); Date transDate2 = getLatestTradeDate(stockCode, endDate); if(transDate1==null || transDate2==null) { logger.error("{}没有对应的交易日:{}={}, {}={}", stockCode, DateUtil.formatDate(beginDate), DateUtil.formatDate(transDate1), DateUtil.formatDate(endDate), DateUtil.formatDate(transDate2)); throw new Exception(); } if(transDate1==transDate2) { return 0; } double close1 = getClose(stockCode, transDate1); double close2 = getClose(stockCode, transDate2); if(close1<=0) { logger.error("{}对应交易日{}的收盘价为0", stockCode, transDate1); throw new Exception(); } return (close2-close1)*100/close1; } @Override public double[] getMaxMinZhangFu(String stockCode, Date beginDate, Date endDate) throws Exception { Date transDate1 = getLatestTradeDate(stockCode, beginDate); Date transDate2 = getLatestTradeDate(stockCode, endDate); if(transDate1==null || transDate2==null) { logger.error("{}没有对应的交易日:{}={}, {}={}", stockCode, DateUtil.formatDate(beginDate), DateUtil.formatDate(transDate1), DateUtil.formatDate(endDate), DateUtil.formatDate(transDate2)); throw new Exception(); } if(transDate1==transDate2) { return new double[] {0,0}; } double close1 = getClose(stockCode, transDate1); if(close1 == 0) { return new double[] {0,0}; } Set<String> transDates = redis.zrangeByScore(getKeyOfKDay(stockCode), transDate1.getTime(), transDate2.getTime()); if(transDates.isEmpty()) { return new double[] {0,0}; } double high = Double.MIN_VALUE; double low = Double.MAX_VALUE; for(String date:transDates){ double h = getHigh(stockCode, date); double l = getLow(stockCode, date); if(h>high) { high = h; } if(l<low) { low = l; } } double zfx = (high-close1)*100/close1; double zfn = (low-close1)*100/close1; if(high == Double.MIN_VALUE || low == Double.MAX_VALUE) { logger.error("{}在[{},{}]计算MaxMin时出现极值", stockCode, DateUtil.formatDate(transDate1), DateUtil.formatDate(transDate2)); throw new Exception(); } return new double[] {zfx, zfn}; } }
package com.infogen.rpc_client; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.protobuf.InvalidProtocolBufferException; import com.infogen.rpc.header.X_HttpHeaderNames; import com.infogen.structure.map.LRULinkedHashMap; import io.netty.buffer.ByteBuf; /** * @author larry/larrylv@outlook.com/创建时间 2015年8月25日 下午6:06:27 * @since 1.0 * @version 1.0 */ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; public class InfoGen_Handler extends SimpleChannelInboundHandler<FullHttpResponse> { private static final Logger LOGGER = LogManager.getLogger(InfoGen_Handler.class.getName()); private LRULinkedHashMap<Long, SimpleStatus> map; public InfoGen_Handler(LRULinkedHashMap<Long, SimpleStatus> map) { this.map = map; } @Override public void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) { HttpHeaders headers = response.headers(); String sequence = headers.get(X_HttpHeaderNames.x_sequence.key); HttpResponseStatus status = response.status(); int code = status.code(); if (code == 100) { return; } if (sequence != null) { SimpleStatus simplestatus = map.get(Long.valueOf(sequence)); if (simplestatus != null) { ByteBuf buf = response.content(); byte[] resp = new byte[buf.readableBytes()]; buf.readBytes(resp); try { simplestatus.callback.run(simplestatus.responsePrototype.getParserForType().parseFrom(resp)); } catch (InvalidProtocolBufferException e) { LOGGER.error(e.getMessage(), e); simplestatus.controller.setFailed(e.getMessage()); } } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
import javax.swing.*; public class Eje17 { public static void main(String[] args) { int num = Integer.parseInt(JOptionPane.showInputDialog("Numero:")); if (num % 2 == 0) { System.out.println("Es Par"); } else { System.out.println("Es Impar"); } } }
package com.bloomberg.server.arithmeticservice.businesslogic; import com.bloomberg.server.arithmeticservice.businesslogic.exceptions.ExpressionBuildException; import com.bloomberg.server.arithmeticservice.businesslogic.exceptions.ExpressionSolverException; import com.bloomberg.server.arithmeticservice.businesslogic.interfaces.IExpressionBuilder; import com.bloomberg.server.arithmeticservice.models.Expression; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class ExpressionBuilderTest { IExpressionBuilder expressionBuilder = new ExpressionBuilder(); @Test void When_NullExpression_Throws_ExpressionException(){ assertThrows(ExpressionBuildException.class, () ->expressionBuilder.build(null)); } @Test void When_DefaultExpression_Throws_ExpressionBuildException() throws ExpressionBuildException { var expression = new Expression(); assertThrows(ExpressionBuildException.class, () ->expressionBuilder.build(expression)); } @Test void When_ExpressionWithValidOperationButNullNumbers_Throws_ExpressionBuildException() throws ExpressionBuildException { var expression = new Expression(); expression.setOperation('+'); assertThrows(ExpressionBuildException.class, () ->expressionBuilder.build(expression)); } @Test void When_ValidExpression_Return_StringRepresentationOfExpression() throws ExpressionBuildException { var expression = new Expression(); expression.setNumbers(List.of(3.0, 4.0)); expression.setOperation('+'); String result = expressionBuilder.build(expression); assertEquals("3.0+4.0",result); } }
/** * @author André Pinto * * Esta classe garante que a pergunta que o chatbot não respondeu não foi vazia */ package br.com.fiap.ston.bo; public class PerguntaNaoRespondidaBO { public boolean incluir(String pergunta) { if(pergunta.length() > 0) { return true; } return false; } }
package java_Map; import java.util.*; //KeySet()返回一个映射关系的Set. public class Maptest1 { public static void main(String[] args) { //创建Map集合. Map<String,String> map = new HashMap<String ,String>(); map.put("01", "jaker"); map.put("02", "Lucy") ; map.put("03", "corder"); //Set有迭代器Iterator可以得到单例 Set<String> Keyset = map.keySet(); Iterator<String> it = Keyset.iterator(); while(it.hasNext()){ String key = it.next(); String value = map.get(key); System.out.println(key+" -- "+ value); } } }
package com.tencent.mm.plugin.fingerprint.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.widget.CheckBox; class FingerPrintAuthTransparentUI$10 implements OnClickListener { final /* synthetic */ FingerPrintAuthTransparentUI jhl; final /* synthetic */ CheckBox jhm; FingerPrintAuthTransparentUI$10(FingerPrintAuthTransparentUI fingerPrintAuthTransparentUI, CheckBox checkBox) { this.jhl = fingerPrintAuthTransparentUI; this.jhm = checkBox; } public final void onClick(DialogInterface dialogInterface, int i) { FingerPrintAuthTransparentUI.b(this.jhl, this.jhm.isChecked()); } }
/* * Created by IntelliJ IDEA. * User: Vaibhav * Date: 23-Mar-20 * Time: 7:06 PM */ package problem5.node; import problem5.student.Student; // to define node properties public class Node { private Student data; private problem3.node.Node next; public Node(Student data) { this.data = data; this.next= null; } public Student getData() { return data; } public void setData(Student data) { this.data = data; } public problem3.node.Node getNext() { return next; } public void setNext(problem3.node.Node next) { this.next = next; } public Node(Student data, problem3.node.Node next) { this.data = data; this.next = next; } @Override public String toString() { return this.getData().toString(); } }
package com.issCollege.po; import java.io.Serializable; /** * standardsample * @author */ public class Standardsample implements Serializable { /** * 标准样品表自增主键 id */ private Long standardsampleId; /** * 标准样名称 */ private String standardsampleName; /** * 标准样品类型 */ private String standardsampleType; /** * 标准样品状态 */ private String standardsampleState; /** * 元素名称 */ private String elementName; /** * 元素含量 */ private Float elementContent; private static final long serialVersionUID = 1L; public Long getStandardsampleId() { return standardsampleId; } public void setStandardsampleId(Long standardsampleId) { this.standardsampleId = standardsampleId; } public String getStandardsampleName() { return standardsampleName; } public void setStandardsampleName(String standardsampleName) { this.standardsampleName = standardsampleName; } public String getStandardsampleType() { return standardsampleType; } public void setStandardsampleType(String standardsampleType) { this.standardsampleType = standardsampleType; } public String getStandardsampleState() { return standardsampleState; } public void setStandardsampleState(String standardsampleState) { this.standardsampleState = standardsampleState; } public String getElementName() { return elementName; } public void setElementName(String elementName) { this.elementName = elementName; } public Float getElementContent() { return elementContent; } public void setElementContent(Float elementContent) { this.elementContent = elementContent; } }
package de.codingchallenge; import de.codingchallenge.main.Application; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.testcontainers.junit.jupiter.Testcontainers; import java.nio.file.Files; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { Application.class, SpringMongoTestConfiguration.class }) @SpringBootTest(properties = { "db.seed=true" , "spring.main.allow-bean-definition-overriding=true" }) @AutoConfigureMockMvc @Testcontainers @ActiveProfiles("test") class RestControllerIT extends ContainerBaseTest { @Autowired private MockMvc mockMvc; @Test void if_all_four_categories_can_be_retrieved() throws Exception { var result = mockMvc.perform(MockMvcRequestBuilders.get("/api/categories")).andReturn(); var contentAsString = result.getResponse().getContentAsString(); var expectedJson = "[\"hard_fact\",\"lifestyle\",\"introversion\",\"passion\"]"; JSONAssert.assertEquals(expectedJson, contentAsString, false); } @Test void if_the_survey_is_retrieved_correctly() throws Exception { var result = mockMvc.perform(MockMvcRequestBuilders.get("/api/surveys")).andReturn(); var contentAsString = result.getResponse().getContentAsString(); var jsonFile = new ClassPathResource("expected_survey.json").getFile(); var expectedJson = Files.readString(jsonFile.toPath()); JSONAssert.assertEquals(expectedJson, contentAsString, false); } @Test void if_a_valid_response_can_be_saved() throws Exception { var jsonFile = new ClassPathResource("survey_response.json").getFile(); var jsonToPost = Files.readString(jsonFile.toPath()); mockMvc.perform(MockMvcRequestBuilders.post("/api/response").contentType(MediaType.APPLICATION_JSON) .content(jsonToPost)) .andExpect(status().isCreated()); } @Test void if_a_valid_response_with_extra_can_be_saved() throws Exception { var jsonFile = new ClassPathResource("survey_response_extra.json").getFile(); var jsonToPost = Files.readString(jsonFile.toPath()); mockMvc.perform(MockMvcRequestBuilders.post("/api/response").contentType(MediaType.APPLICATION_JSON) .content(jsonToPost)) .andExpect(status().isCreated()); } @Test void if_a_invalid_response_is_rejected() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/api/response").contentType(MediaType.APPLICATION_JSON) .content("{}")) .andExpect(status().isUnprocessableEntity()); } }
package com.demo.test.tenc; public class TestBigNumber { static int numberA = 1243462314; static int numberB = 1343545632; private static int add(int a, int b, boolean position) { int sum = 0; boolean addPosition = false; if (position) { if (a + b + 1 <= 9 && a + b + 1 >= 0) { sum = a + b + 1; } else { sum = a + b - 10; addPosition = true; } } else { if (a + b <= 9 && a + b >= 0) { sum = a + b; } else { sum = a + b - 10; addPosition = true; } } return sum; } // 123456 // 1*10^5+2*10^4 /*@getter @Setter @NoArgument class BigNumber{ private long base; private int ten; private long square; public long getNumber(){ return base * 10 ^ square; } }*/ public static void main(String[] args) { int processLength = 100000; int pa = numberA % processLength; int pb = numberB % processLength; System.out.println(add(pa, pb, false)); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * BOperationLinkId generated by hbm2java */ public class BOperationLinkId implements java.io.Serializable { private String opuid1; private String opuid2; private String operlinktype; public BOperationLinkId() { } public BOperationLinkId(String opuid1, String opuid2, String operlinktype) { this.opuid1 = opuid1; this.opuid2 = opuid2; this.operlinktype = operlinktype; } public String getOpuid1() { return this.opuid1; } public void setOpuid1(String opuid1) { this.opuid1 = opuid1; } public String getOpuid2() { return this.opuid2; } public void setOpuid2(String opuid2) { this.opuid2 = opuid2; } public String getOperlinktype() { return this.operlinktype; } public void setOperlinktype(String operlinktype) { this.operlinktype = operlinktype; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof BOperationLinkId)) return false; BOperationLinkId castOther = (BOperationLinkId) other; return ((this.getOpuid1() == castOther.getOpuid1()) || (this.getOpuid1() != null && castOther.getOpuid1() != null && this.getOpuid1().equals(castOther.getOpuid1()))) && ((this.getOpuid2() == castOther.getOpuid2()) || (this.getOpuid2() != null && castOther.getOpuid2() != null && this.getOpuid2().equals(castOther.getOpuid2()))) && ((this.getOperlinktype() == castOther.getOperlinktype()) || (this.getOperlinktype() != null && castOther.getOperlinktype() != null && this.getOperlinktype().equals(castOther.getOperlinktype()))); } public int hashCode() { int result = 17; result = 37 * result + (getOpuid1() == null ? 0 : this.getOpuid1().hashCode()); result = 37 * result + (getOpuid2() == null ? 0 : this.getOpuid2().hashCode()); result = 37 * result + (getOperlinktype() == null ? 0 : this.getOperlinktype().hashCode()); return result; } }
package zajecia.cwiczenie1; public class Product { private String name; private Producer producer; private double price; private boolean isAvailable; public Product(String name, Producer producer, double price, boolean isAvailable) { this.name = name; this.producer = producer; this.price = price; this.isAvailable = isAvailable; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Producer getProducer() { return producer; } public void setProducer(Producer producer) { this.producer = producer; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public boolean isAvailable() { return isAvailable; } public void setAvailable(boolean available) { isAvailable = available; } @Override public String toString() { return "Product{" + "name='" + name + '\'' + ", producer=" + producer + ", price=" + price + ", isAvailable=" + isAvailable + '}'; } }
package alg; import java.util.Comparator; import java.util.TreeSet; public class BestSolutions { private TreeSet<PairBest> arbol; private static final int MAX_SOLS = 10; public BestSolutions(){ arbol = new TreeSet<>(); } public void addSolution(PairBest sol){ arbol.add(sol); if(arbol.size() > MAX_SOLS) arbol.remove(arbol.last()); } public TreeSet<PairBest> getSolutions(){ return arbol; } public int getSize(){ return arbol.size(); } }
package LinkedList; /** * @author admin * @version 1.0.0 * @ClassName mergeTwoLists.java * @Description 合并两个有序链表 * 首先,我们设定一个哨兵节点 prehead ,这可以在最后让我们比较容易地返回合并后的链表。我们维护一个 prev 指针, * 我们需要做的是调整它的 next 指针。然后,我们重复以下过程,直到 l1 或者 l2 指向了 null : * 如果 l1 当前节点的值小于等于 l2 ,我们就把 l1 当前的节点接在 prev 节点的后面同时将 l1 指针往后移一位。 * 否则,我们对 l2 做同样的操作。不管我们将哪一个元素接在了后面,我们都需要把 prev 向后移一位。 * 在循环终止的时候, l1 和 l2 至多有一个是非空的。由于输入的两个链表都是有序的, * 所以不管哪个链表是非空的,它包含的所有元素都比前面已经合并链表中的所有元素都要大。 * 这意味着我们只需要简单地将非空链表接在合并链表的后面,并返回合并链表即可。 * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 * @createTime 2021年03月07日 20:06:00 */ public class mergeTwoLists { public static ListNode mergeTwoSortList(ListNode l1,ListNode l2){ ListNode prehead = new ListNode(-1); ListNode pre = prehead; while (l1 != null && l2 != null){ if (l1.val <= l2.val){ pre.next = l1; l1 = l1.next; }else { pre.next = l2; l2 = l2.next; } pre = pre.next; } // 合并后 l1 和 l2 最多只有一个还未被合并完, //我们直接将链表末尾指向未合并完的链表即可 pre.next = l1 == null ? l2 : l1; return prehead.next; } }
package org.kuali.mobility.tours.entity; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity(name="TourPermission") @Table(name="TOUR_PRMSSN_T") public class TourPermission { @Id //@SequenceGenerator(name="tour_permission_sequence", sequenceName="SEQ_TOUR_PRMSSN_T", initialValue=1000, allocationSize=1) //@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="tour_permission_sequence") @GeneratedValue(strategy = GenerationType.TABLE) @Column(name="PRMSSN_ID") private Long permissionId; @Basic @Column(name="TOUR_ID", insertable=false, updatable=false) private Long tourId; @OneToOne(fetch=FetchType.LAZY) @JoinColumn(name="TOUR_ID", nullable=true) private Tour tour; @Column(name="PRMSSN_TYPE") private String type; @Column(name="GRP_NM") private String groupName; public Long getPermissionId() { return permissionId; } public void setPermissionId(Long permissionId) { this.permissionId = permissionId; } public Long getTourId() { return tourId; } public void setTourId(Long tourId) { this.tourId = tourId; } public Tour getTour() { return tour; } public void setTour(Tour tour) { this.tour = tour; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public TourPermission copy(boolean includeIds) { TourPermission copy = new TourPermission(); if (includeIds) { copy.setPermissionId(new Long(permissionId)); } copy.setTourId(new Long(tourId)); copy.setType(new String(type)); copy.setGroupName(new String(groupName)); return copy; } }
package ba.bitcamp.LabS06D05; public class TicTacToeGUI { }
package com.example.patienttracker; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Fragment_Patient_Home extends Fragment { //variables private static final String TAG = "Fragment_Patient_Home"; public static final String firstNameKey = "firstname"; public static final String lastNameKey = "lastname"; public static final String phoneKey = "phonenumber"; public static final String emailKey = "emailaddress"; public static final String dateFormatPatten = "yyyy-MM-dd"; private String patient_first_name, patient_last_name, patient_phone, patient_email, date_today; private final Date dateToday = new Date(); private QueryDocumentSnapshot up_coming_appointment; //widgets private TextView tv_userFirstName, tv_userLastName, tv_userPhone, tv_userEmail, tv_userDocumentID, tv_upComingDateTime, tv_upComingDoctor, tv_upComingDoctorNumber, tv_upComingDateOfAction; private Button btn_booking; private RelativeLayout rl_upComing; private LinearLayout ll_upComingNo; //databse private FirebaseFirestore db = FirebaseFirestore.getInstance(); private CollectionReference collectionDoctorReference = db.collection("Doctor"); private CollectionReference collectionBookingReference = db.collection("Booking"); public Fragment_Patient_Home() { // Required empty public constructor } public static Fragment_Patient_Home newInstance( String FName,String LName,String Phone,String Email) { Fragment_Patient_Home fragment = new Fragment_Patient_Home(); Bundle bundle = new Bundle(); bundle.putString(firstNameKey,FName); bundle.putString(lastNameKey,LName); bundle.putString(phoneKey,Phone); bundle.putString(emailKey,Email); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { patient_first_name = getArguments().getString(firstNameKey); patient_last_name = getArguments().getString(lastNameKey); patient_phone = getArguments().getString(phoneKey); patient_email = getArguments().getString(emailKey); } date_today = formatDate(dateToday.getTime()); }//End of onCrete @SuppressLint("SetTextI18n") @Nullable @Override //Cycle After onCrete public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_patient, container, false); getUpcomingBooking(); tv_userFirstName = view.findViewById(R.id.TV_F_Patient_First_Name); tv_userLastName = view.findViewById(R.id.TV_F_Patient_Last_Name); tv_userPhone = view.findViewById(R.id.TV_F_Patient_Phone); tv_userEmail = view.findViewById(R.id.TV_F_Patient_Email); tv_userDocumentID = view.findViewById(R.id.TV_F_Patient_userID); tv_upComingDateTime = view.findViewById(R.id.TV_F_patient_upComing_dateTime); tv_upComingDoctor = view.findViewById(R.id.TV_F_patient_upComing_doctor); tv_upComingDoctorNumber = view.findViewById(R.id.TV_F_patient_upComing_doctor_phone); tv_upComingDateOfAction = view.findViewById(R.id.TV_F_patient_upComing_dateOfAction); rl_upComing = view.findViewById(R.id.RL_F_patient_upComing); ll_upComingNo = view.findViewById(R.id.LL_patient_upComingNo); tv_userFirstName.setText(patient_first_name); tv_userLastName.setText(patient_last_name); tv_userPhone.setText(patient_phone); tv_userEmail.setText(patient_email); tv_userDocumentID.setText("Login ID : " + patient_phone); btn_booking = view.findViewById(R.id.B_F_Patient_Book); return view; }//end of onCreteView @SuppressLint("SetTextI18n") @Override //Cycle After onCreteView public void onStart() { super.onStart(); btn_booking.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Activity_Patient_Booking_Select_Doctor.class); intent.putExtra(phoneKey, patient_phone); intent.putExtra(emailKey, patient_email); intent.putExtra(firstNameKey,patient_first_name); intent.putExtra(lastNameKey,patient_last_name); startActivity(intent); } }); }//end of onStart private String formatDate(long date){ @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat(dateFormatPatten); return format.format(date); } private void getUpcomingBooking() { collectionBookingReference .whereEqualTo("patient_documentID",patient_phone) .orderBy("date", Query.Direction.ASCENDING) .orderBy("timeSlot", Query.Direction.ASCENDING) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.getResult().isEmpty()){ ll_upComingNo.setVisibility(View.VISIBLE); rl_upComing.setVisibility(View.GONE); }else { for (QueryDocumentSnapshot document : task.getResult()) { // Log.d(TAG, document.getId() + " => " + document.getData()); try { findUpcomingDocumnet(document); } catch (ParseException e) { e.printStackTrace(); } } } } }); } private void findUpcomingDocumnet(QueryDocumentSnapshot document) throws ParseException { String document_date = (String) document.get("date"); SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPatten); Date documentDate = sdf.parse(document_date); Date today = sdf.parse(date_today); if (today.equals(documentDate) || today.before(documentDate)) { if (up_coming_appointment == null){ up_coming_appointment = document; setupUpomingCard(up_coming_appointment); }else { Date currDocumentDate = sdf.parse( (String) up_coming_appointment.get("date")); if (documentDate.before(currDocumentDate)){ up_coming_appointment = document; setupUpomingCard(up_coming_appointment); } } }else { } } @SuppressLint("SetTextI18n") private void setupUpomingCard(QueryDocumentSnapshot document) { ll_upComingNo.setVisibility(View.GONE); rl_upComing.setVisibility(View.VISIBLE); tv_upComingDateTime.setText( (String) document.getData().get("date") + " " + getTime((String) document.getData().get("timeSlot") , (Boolean) document.getData().get("doctor_isHalfHourSlot"))); getDoctorName((String) document.getData().get("doctor_documentID")); tv_upComingDoctorNumber.setText( "Doctor Number : " + (String) document.getData().get("doctor_documentID")); tv_upComingDateOfAction.setText( "Appointment was booked on : " + (String) document.getData().get("dateOfAction")); } private String getTime(String time,Boolean isHalfHourSlot) { String temp_time_string = "Error Getting Time"; if (isHalfHourSlot){ switch (time){ case "time01": temp_time_string = "00:00"; break; case "time02": temp_time_string = "00:30"; break; case "time03": temp_time_string = "01:00"; break; case "time04": temp_time_string = "01:30"; break; case "time05": temp_time_string = "02:00"; break; case "time06": temp_time_string = "02:30"; break; case "time07": temp_time_string = "03:00"; break; case "time08": temp_time_string = "03:30"; break; case "time09": temp_time_string = "04:00"; break; case "time10": temp_time_string = "04:30"; break; case "time11": temp_time_string = "05:00"; break; case "time12": temp_time_string = "05:30"; break; case "time13": temp_time_string = "06:00"; break; case "time14": temp_time_string = "06:30"; break; case "time15": temp_time_string = "07:00"; break; case "time16": temp_time_string = "07:30"; break; case "time17": temp_time_string = "08:00"; break; case "time18": temp_time_string = "08:30"; break; case "time19": temp_time_string = "09:00"; break; case "time20": temp_time_string = "09:30"; break; case "time21": temp_time_string = "10:00"; break; case "time22": temp_time_string = "10:30"; break; case "time23": temp_time_string = "11:00"; break; case "time24": temp_time_string = "11:30"; break; case "time25": temp_time_string = "12:00"; break; case "time26": temp_time_string = "12:30"; break; case "time27": temp_time_string = "13:00"; break; case "time28": temp_time_string = "13:30"; break; case "time29": temp_time_string = "14:00"; break; case "time30": temp_time_string = "14:30"; break; case "time31": temp_time_string = "15:00"; break; case "time32": temp_time_string = "15:30"; break; case "time33": temp_time_string = "16:00"; break; case "time34": temp_time_string = "16:30"; break; case "time35": temp_time_string = "17:00"; break; case "time36": temp_time_string = "17:30"; break; case "time37": temp_time_string = "18:00"; break; case "time38": temp_time_string = "18:30"; break; case "time39": temp_time_string = "19:00"; break; case "time40": temp_time_string = "19:30"; break; case "time41": temp_time_string = "20:00"; break; case "time42": temp_time_string = "20:30"; break; case "time43": temp_time_string = "21:00"; break; case "time44": temp_time_string = "21:30"; break; case "time45": temp_time_string = "22:00"; break; case "time46": temp_time_string = "22:30"; break; case "time47": temp_time_string = "23:00"; break; case "time48": temp_time_string = "23:30"; break; } }else { switch (time){ case "time01": temp_time_string = "00:00"; break; case "time02": temp_time_string = "01:00"; break; case "time03": temp_time_string = "02:00"; break; case "time04": temp_time_string = "03:00"; break; case "time05": temp_time_string = "04:00"; break; case "time06": temp_time_string = "05:00"; break; case "time07": temp_time_string = "06:00"; break; case "time08": temp_time_string = "07:00"; break; case "time09": temp_time_string = "08:00"; break; case "time10": temp_time_string = "09:00"; break; case "time11": temp_time_string = "10:00"; break; case "time12": temp_time_string = "11:00"; break; case "time13": temp_time_string = "12:00"; break; case "time14": temp_time_string = "13:00"; break; case "time15": temp_time_string = "14:00"; break; case "time16": temp_time_string = "15:00"; break; case "time17": temp_time_string = "16:00"; break; case "time18": temp_time_string = "17:00"; break; case "time19": temp_time_string = "18:00"; break; case "time20": temp_time_string = "19:00"; break; case "time21": temp_time_string = "20:00"; break; case "time22": temp_time_string = "21:00"; break; case "time23": temp_time_string = "22:00"; break; case "time24": temp_time_string = "23:00"; break; } } return temp_time_string; } private void getDoctorName(String doctor_document_id){ collectionDoctorReference.document(doctor_document_id) .get() .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @SuppressLint("SetTextI18n") @Override public void onSuccess(DocumentSnapshot documentSnapshot) { String temp_name1 = (String) documentSnapshot.get("FirstName"); String temp_name2 = (String) documentSnapshot.get("LastName"); tv_upComingDoctor.setText(temp_name1 + " " + temp_name2); } }) .addOnFailureListener(new OnFailureListener() { @SuppressLint("SetTextI18n") @Override public void onFailure(@NonNull Exception e) { tv_upComingDoctor.setText("Error Getting Doctor Name"); } }); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onResume() { super.onResume(); } }
package jneiva.hexbattle.comum; public class MaquinaEstado { protected Estado estadoAtual; protected boolean travarEstado = false; protected boolean emTransicao; public Estado getEstado() { return estadoAtual; } public <T extends Estado> void mudarEstado(T estado) { transicao(estado); } protected void transicao(Estado estado) { if (travarEstado) return; if (estadoAtual == estado || emTransicao) return; emTransicao = true; if (estadoAtual != null) estadoAtual.sair(); estadoAtual = estado; emTransicao = false; if (estadoAtual != null) estadoAtual.entrar(); } }
package sample.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * klasa model majaca na celu odwzorowac dane adresowe */ @AllArgsConstructor @NoArgsConstructor @Data public class Address { private String country; private String voivodeship; private String town; private String street; private String houseNumber; }
package apniKaksha; public class BitwiseOperator { public static void main(String[] args) { int a=5; int b=13; /*int c=a|b; //OR operation int d=a&b; //AND operation */ int c=b<<2; //Left shift 1101 -->110100 ==> 32+16+4=52 int d=b>>2; //Right shift 1101 -->0011 ==> 3 System.out.println(d); System.out.println(c); System.out.println(a!=b); //comparison operator ---- not-equal-to opera } }
package com.robotarm.core.arduino; import com.robotarm.RobotArm; import com.robotarm.core.executable.Task; import com.robotarm.util.Helper; import org.ardulink.core.Link; import org.ardulink.core.events.CustomEvent; import org.ardulink.core.events.CustomListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.BlockingQueue; /** * Created by higgsy789 on 31/03/2017. */ public class ArduinoListener implements CustomListener { Helper h = Helper.getInstance(); @Override public void customEventReceived(CustomEvent customEvent) { String message = customEvent.getMessage(); if (message.startsWith("RAWMONITOR") && RobotArm.DEBUG) { message = message.substring(11); h.confirm(message); } } }
package me.zhongmingmao.fallback; import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @Component public class UserConsumerFallback implements ZuulFallbackProvider { private static final String SERVICE_ID = "user-consumer"; @Override public String getRoute() { return SERVICE_ID; // 表明为微服务user-consumer提供fallback,即Eureka Server中的service-id } @Override public ClientHttpResponse fallbackResponse() { return new ClientHttpResponse() { @Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.OK; } @Override public int getRawStatusCode() throws IOException { return getStatusCode().value(); // 200 } @Override public String getStatusText() throws IOException { return getStatusCode().getReasonPhrase(); // OK } @Override public void close() { } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream( String.format("Microservice[%s] is not available, Please try Again later.", SERVICE_ID) .getBytes()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_HTML); return headers; } }; } }
package ba.bitcamp.LabS10D02; /** * Class Priority Queue Integer * * @author nermingraca * */ public class PriorityQueueInt { private Node head; private Node tail; /** * Constructor of object Priority Queue Int */ public PriorityQueueInt() { head = null; tail = null; } /** * Method inserts new Node into linked list based on its priority * @param value = Variable value of object Node * @param priority = Variable priority of object Node */ public void push(int value, int priority) { Node newNode = new Node(value, priority); if (head == null) { head = newNode; tail = newNode; return; } Node previous = head; Node current = previous.next; if (previous.priority < newNode.priority) { newNode.next = previous; head = newNode; return; } else if (previous.priority >= newNode.priority) { while (current != null) { if (current.priority < newNode.priority) { newNode.next = current; previous.next = newNode; return; } previous = previous.next; current = current.next; } previous.next = newNode; tail = newNode; } } /** * Method pop removes head element in the list */ public void pop() { Node previous = head; Node current = previous.next; if (current == null) { previous = null; } head = current; previous = null; } /** * Method Peek return value of head element in linked list * @return Value of head element */ public int peek() { if (head == null) { throw new NullPointerException("List is empty"); } return head.value; } public boolean isEmpty() { return head == null; } /** * Method prints value and priority of object Node into console */ public void print() { Node current = head; while (current != null) { System.out.print("Value:"+current.value + " Priority:" + current.priority + " "); System.out.println(); current = current.next; } System.out.println(); } /** * Private class Node * * @author nermingraca * */ private class Node { public int value; public int priority; public Node next; /** * Constructor of object Node with one parameter * @param value = Integer variable which is held in object node */ public Node(int value, int priority) { this.value = value; this.priority = priority; this.next = null; } } }
package sling.gsoc.david.operation; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.servlets.HtmlResponse; import org.apache.sling.commons.scheduler.Scheduler; import org.apache.sling.servlets.post.SlingPostOperation; import org.apache.sling.servlets.post.SlingPostProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sling.gsoc.david.job.SendTask; @Component(metatype = false, immediate = true) @Service public class EmailOperation implements SlingPostOperation{ @Property(value = "email") static final String OPERATION = "sling.post.operation"; @Property(value = "from") static final String FROM = "notify.email.from"; @Property(value = "to") static final String TO = "notify.email.to"; @Property(value = "Seen on David Mini CMS") static final String SUBJECT = "notify.email.subject"; @Property(value = "text") static final String TEXT = "notify.email.text"; @Property(value = "http://localhost:8080") static final String HOST = "notify.email.host"; @Reference private Scheduler scheduler; private static final Logger log = LoggerFactory.getLogger(EmailOperation.class); public void run(SlingHttpServletRequest request, HtmlResponse response, SlingPostProcessor[] spps) { try { log.info("This will send an email..."); log.info(request.getParameter(FROM)); log.info(request.getParameter(TO)); log.info(request.getParameter(SUBJECT)); log.info(request.getParameter(TEXT)); Map<String, Serializable> config = new HashMap<String, Serializable>(); SendTask task = new SendTask(); task.setFrom(request.getParameter(FROM)); task.setTo(request.getParameter(TO)); task.setSubject(request.getParameter(SUBJECT)); task.setText("Read this article: "+HOST+request.getParameter(TEXT)); String jobName = "EmailOperation"; final long delay = 10 * 1000; final Date fireDate = new Date(); fireDate.setTime(System.currentTimeMillis() + delay); this.scheduler.fireJobAt(jobName, task, config, fireDate); } catch (Exception ex) { log.error(ex.toString()); } } }
/* * @Author : fengzhi * @date : 2019 - 04 - 17 10 : 57 * @Description : */ package nowcoder_leetcode; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Stack; public class p_6 { // 用循环实现后续遍历二叉树 public ArrayList<Integer> postorderTraversal(TreeNode root) { // 讲真的,这个程序我写不出来 ArrayList<Integer> arrayList = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); Stack<TreeNode> stack2 = new Stack<>(); stack.push(root); while(!stack.empty()) { TreeNode node = stack.pop(); stack2.push(node); //arrayList.add(node.val); if (node.right != null) stack.push(node.right); if (node.left != null) stack.push(node.left); } while (!stack2.empty()) { arrayList.add(stack2.pop().val); } return arrayList; } public ArrayList<Integer> postorderTraversal_New(TreeNode root) { ArrayList<Integer> arrayList = new ArrayList<>(); if (root == null) return arrayList; Stack<TreeNode> stack2 = new Stack<>(); stack2.push(root); while (!stack2.empty()) { TreeNode node = stack2.pop(); arrayList.add(node.val); if (node.right != null) stack2.push(node.right); if (node.left != null) stack2.push(node.left); } return arrayList; } // 没怎么看懂。。。。。 public ArrayList<Integer> midorderTraversal_New(TreeNode root) { ArrayList<Integer> arrayList = new ArrayList<>(); if (root == null) return arrayList; Stack<TreeNode> stack2 = new Stack<>(); TreeNode temp = root; while (!stack2.empty() || temp != null) { if (temp != null) { stack2.push(temp); temp = temp.left; } else { TreeNode node = stack2.pop(); arrayList.add(node.val); temp = node.right; } } return arrayList; } public static ArrayList<Integer> postOrderTraversalRecursively(TreeNode root) { ArrayList<Integer> arrayList = new ArrayList<>(); postOrderTraversalRecursively(root, arrayList); return arrayList; } private static void postOrderTraversalRecursively(TreeNode root, ArrayList<Integer> arrayList) { if (root == null) return; postOrderTraversalRecursively(root.left, arrayList); postOrderTraversalRecursively(root.right, arrayList); arrayList.add(root.val); } public static void main(String[] args) { TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(5); TreeNode node6 = new TreeNode(6); TreeNode node7 = new TreeNode(7); node1.left = node2; node1.right = node3; node2.left = node4; node2.right = node5; node3.left = node6; node3.right = node7; ArrayList<Integer> arrayList = postOrderTraversalRecursively(node1); System.out.println(arrayList); } // 使用栈实现前序遍历 public static void preOrderStack_1(TreeNode root){ if (root == null) return; Stack<TreeNode> s = new Stack<TreeNode>(); s.push(root); while (!s.isEmpty()) { TreeNode temp = s.pop(); // 取出来的时候再打印 System.out.println(temp.val); if (temp.right != null) s.push(temp.right); if (temp.left != null) s.push(temp.left); } } public static void preOrderStack_2(TreeNode root){ if (root == null) return; Stack<TreeNode> s = new Stack<TreeNode>(); while (root != null || !s.isEmpty()) { while (root != null) { System.out.println(root.val); s.push(root); // 先访问再入栈 root = root.left; } root = s.pop(); root = root.right; // 如果是null,出栈并处理右子树 } } public static void inOrderStack(TreeNode root){ if (root == null) return; Stack<TreeNode> s = new Stack<TreeNode>(); while (root != null || !s.isEmpty()) { while (root != null) { s.push(root); // 先访问再入栈 root = root.left; } root = s.pop(); System.out.println(root.val); root = root.right; // 如果是null,出栈并处理右子树 } } public static void postOrderStack(TreeNode root){ if (root == null) return; Stack<TreeNode> s = new Stack<TreeNode>(); Map<TreeNode, Boolean> map = new HashMap<TreeNode, Boolean>(); s.push(root); while (!s.isEmpty()) { // peek与pop的区别在于,peek在返回栈顶值之后不删除该值,而pop删除。 TreeNode temp = s.peek(); // 判断无左节点 if (temp.left != null && !map.containsKey(temp.left)) { temp = temp.left; while (temp != null) { if (map.containsKey(temp)) break; else s.push(temp); temp = temp.left; } continue; } // 判断无右节点 if (temp.right != null && !map.containsKey(temp.right)) { s.push(temp.right); continue; } TreeNode t = s.pop(); map.put(t, true); System.out.println(t.val); } } }
package com.goldgov.gtiles.core.web.freemarker.model; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.goldgov.gtiles.core.Keys; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; @SuppressWarnings("rawtypes") public class PathTemplateModel implements TemplateDirectiveModel{ private HttpServletRequest request; private String modelPath; public PathTemplateModel(HttpServletRequest request){ this.request = request; } @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Object localParam = params.get("local"); Object patternParam = params.get("pattern"); boolean local = false; if(localParam != null){ local= Boolean.valueOf(localParam.toString()); } String pattern = "HCM"; if(patternParam != null){ pattern= patternParam.toString(); } char[] fragments = pattern.toCharArray(); StringBuilder stringBuilder = new StringBuilder(); String contextPath = getContextPath(local); for (char c : fragments) { switch (c) { case 'H'://Host //FIXME https String host = "http://"+request.getLocalName()+":"+request.getLocalPort(); if(!local){ Object remoteHost = request.getAttribute(Keys.REMOTE_CALL_FROM); if(remoteHost != null){ host = remoteHost.toString(); } } stringBuilder.append(host); break; case 'C'://Context stringBuilder.append(contextPath); break; case 'M'://MdulePath // String[] modelPath = (String[]) request.getAttribute(Keys.GTILES_MODEL_PATH); // if(modelPath != null){ // if(contextPath.equals("/")){ // stringBuilder.append(modelPath); // }else{ // stringBuilder.append(contextPath + modelPath); // } // } stringBuilder.append(modelPath); break; } } env.getOut().write(stringBuilder.toString()); } private String getContextPath(boolean local) { String contextPath = request.getContextPath(); if(!local){ Object remoteContextName = request.getAttribute(Keys.REMOTE_CALL_CONTEXT_NAME); if(remoteContextName != null){ contextPath = remoteContextName.toString(); } } return contextPath; } public void setModelPath(String modelPath) { this.modelPath = modelPath; } }
package iks.pttrns.collections; public interface Menu { java.util.Iterator createIterator(); }
package generadorcv; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class GeneradorCV { public static void main(String[] args) { try { String linea = ""; FileWriter fw = null; PrintWriter pw = null; BufferedReader br1 = new BufferedReader(new FileReader("curriculum.txt")); BufferedReader br2 = new BufferedReader(new FileReader("curriculum.txt")); fw = new FileWriter("mycurriculum.html"); pw = new PrintWriter(fw); linea = br1.readLine(); // HTML // Head pw.println("<html>"); pw.println("<head><meta charset=\"UTF-8\"><title>" + (linea + "\n") + "</title></head>"); // Fin Head // Body pw.println("<body>"); linea = br2.readLine(); pw.println("<center><h1><font color=\"cyan\">" + linea + "</font></h1></center>"); pw.println("<center><p>"); // Fin Body // Contacto br2.readLine(); linea = br2.readLine(); pw.println("Tlf contacto: " + linea + "<br>"); br2.readLine(); linea = br2.readLine(); pw.println("E-mail contacto: " + linea + "<br><br>"); br2.readLine(); // Fin Contacto // Formacion pw.println("<h2> Formacion: </h2>"); do { linea = br2.readLine(); if (linea != null) { pw.println(linea + "<br>"); if (linea.isEmpty()) { break; } } } while (linea != null); // Fin Formacion // Experiencia Laboral pw.println("<h2> Experiencia laboral: </h2>"); do { linea = br2.readLine(); if (linea != null) { pw.println(linea + "<br>"); if (linea.isEmpty()) { break; } } } while (linea != null); // Fin Experiencia Laboral pw.println("</p></center>"); pw.println("</body>"); pw.println("</html>"); br1.close(); br2.close(); pw.close(); fw.close(); System.out.println("Curriculum generado satisfactoriamente"); } catch (FileNotFoundException fnf) { System.out.println("Archivos no encontrados"); } catch (IOException ioe) { System.out.println("Error de lectura/escritura"); } } }
/* * 文 件 名: SpringUtil.java * 版 权: qieyigoo Technologies Co., Ltd. Copyright YYYY-YYYY, All rights reserved * 描 述: <描述> * 修 改 人 创建人 * 修改时间: 2015年11月13日 * 跟踪单号: <跟踪单号> * 修改单号: <修改单号> * 修改内容: <修改内容> */ package com.nemo.api.services.tools; import java.util.Locale; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 切面获取service * * @author 姓名 工号 * @version [版本号, 2015年11月13日] * @see [相关类/方法] * @since [产品/模块版本] */ public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext context; @SuppressWarnings("static-access") public void setApplicationContext(ApplicationContext contex) throws BeansException { this.context = contex; } public static Object getBean(String beanName) { return context.getBean(beanName); } public static String getMessage(String key) { return context.getMessage(key, null, Locale.getDefault()); } }
/* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.ui.server.services; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import org.overlord.rtgov.common.util.BeanResolverUtil; import org.overlord.rtgov.ui.client.shared.services.IServicesService; import org.overlord.rtgov.ui.client.shared.services.ISituationsService; /** * Services application. */ @ApplicationPath("/rest") public class RTGovApplication extends Application { private java.util.Set<Object> _singletons=new java.util.HashSet<Object>(); public RTGovApplication() { IServicesService services = BeanResolverUtil.getBean(IServicesService.class); if (services != null) { _singletons.add(services); } ISituationsService situations = BeanResolverUtil.getBean(ISituationsService.class); if (situations != null) { _singletons.add(situations); } } public Set<Object> getSingletons() { return (_singletons); } }
package com.jasoftsolutions.mikhuna.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.jasoftsolutions.mikhuna.util.InternetUtil; /** * Created by Hugo on 26/02/2015. */ public class InternetBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (InternetUtil.isInternetConnected(context)){ context.startService(ServiceSendLikeDish.getIntentOfActionSendLike(context)); } } }
import java.awt.*; import java.applet.*; public class myapplet extends Applet implements Runnable { String msg="hai hello"; public void init() { Thread t=new Thread(this); t.start(); } public void run() { for(;;) { for(int i=msg.length();i>=0;i--) { msg=msg.substring(0,i); repaint(); try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e); }}msg="hai hello"; } } public void paint(Graphics g) { g.drawString(msg,100,200); } }
package MatriculaEstudiantes; import java.util.Objects; public class Materias { String nombre; public Materias(String nombre) { this.nombre = nombre; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Override public String toString() { return nombre; } @Override public boolean equals(Object obj) { final Materias otrasMaterias = (Materias) obj; return false; } }
/* * Sonar Scala Plugin * Copyright (C) 2011 Felix Müller * felix.mueller.berlin@googlemail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.scala.sensor; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.nio.charset.Charset; import org.junit.Before; import org.junit.Test; import org.sonar.api.batch.SensorContext; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.resources.Project; import org.sonar.api.resources.ProjectFileSystem; import org.sonar.plugins.scala.language.Scala; import org.sonar.plugins.scala.language.ScalaPackage; import org.sonar.plugins.scala.util.FileTestUtils; public class BaseMetricsSensorTest { private BaseMetricsSensor baseMetricsSensor; private ProjectFileSystem fileSystem; private Project project; private SensorContext sensorContext; @Before public void setUp() { baseMetricsSensor = new BaseMetricsSensor(Scala.INSTANCE); fileSystem = mock(ProjectFileSystem.class); when(fileSystem.getSourceCharset()).thenReturn(Charset.defaultCharset()); project = mock(Project.class); when(project.getFileSystem()).thenReturn(fileSystem); sensorContext = mock(SensorContext.class); } @Test public void shouldIncrementFileMetricForOneScalaFile() { analyseOneScalaFile(); verify(sensorContext, times(1)).saveMeasure( eq(FileTestUtils.SCALA_SOURCE_FILE), eq(CoreMetrics.FILES), eq(1.0)); } @Test public void shouldIncrementPackageMetricForOneScalaFile() { analyseOneScalaFile(); verify(sensorContext, times(1)).saveMeasure( any(ScalaPackage.class), eq(CoreMetrics.PACKAGES), eq(1.0)); } @Test public void shouldIncreaseFileMetricForAllScalaFiles() throws IOException { analyseAllScalaFiles(); verify(sensorContext, times(3)).saveMeasure( eq(FileTestUtils.SCALA_SOURCE_FILE), eq(CoreMetrics.FILES), eq(1.0)); } @Test public void shouldIncreasePackageMetricForAllScalaFiles() { analyseAllScalaFiles(); verify(sensorContext, times(2)).saveMeasure( any(ScalaPackage.class), eq(CoreMetrics.PACKAGES), eq(1.0)); } private void analyseOneScalaFile() { analyseScalaFiles(1); } private void analyseAllScalaFiles() { analyseScalaFiles(3); } private void analyseScalaFiles(int numberOfFiles) { when(fileSystem.mainFiles(baseMetricsSensor.getScala().getKey())) .thenReturn(FileTestUtils.getInputFiles("/baseMetricsSensor/", "ScalaFile", numberOfFiles)); baseMetricsSensor.analyse(project, sensorContext); } }
package br.com.helpdev.quaklog.entity; import br.com.helpdev.quaklog.entity.vo.ConnectStatus; import br.com.helpdev.quaklog.entity.vo.GameTime; import lombok.*; @ToString @Getter @AllArgsConstructor(access = AccessLevel.PRIVATE) @Builder public class PlayerStatus { private final GameTime time; private final ConnectStatus status; static PlayerStatus newConnectedTime(final GameTime time) { return new PlayerStatus(time, ConnectStatus.CONNECTED); } static PlayerStatus newDisconnectedTime(final GameTime time) { return new PlayerStatus(time, ConnectStatus.DISCONNECTED); } static PlayerStatus newBeginTime(final GameTime time) { return new PlayerStatus(time, ConnectStatus.BEGIN); } }
public class Nesting { public static void main(String args[]) { Large ob = new Large(2,3); ob.disp(); } }
package View.GUISistemaDeMenu; import Model.SistemaDeInventario.GestorInventario; import Model.SistemaDeMenu.GestorDeMenu; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class GUISistemaDeMenu{ public GUISistemaDeMenu() { } public void menuChef() throws IOException, FileNotFoundException, ClassNotFoundException{ GestorDeMenu geM = new GestorDeMenu(); int selector; Boolean flag = true; while (flag) { System.out.println("Ingrese que quieres hacer\n1.Ver menu completo\n2.Agregar Platillo\n3.añadir ingredientes Platillo\n4.Ver receta\n0.Salir"); selector = ingresoDatosInt(); switch (selector) { case 1: try { System.out.println(geM.menuClompleto()); }catch (Exception e){} break; case 2: crearPlatillo(); break; case 3: System.out.println("Ingresa el id del platillo a agregar ingredientes"); selector = ingresoDatosInt(); try { addIngredienteFP(selector); }catch (Exception e){} break; case 4: System.out.println("Ingresa el id del platillo "); selector = ingresoDatosInt(); try { System.out.println(informacionProductoReceta(selector)); }catch (Exception e){} break; case 0: flag = false; break; default: System.out.println("ingresa una opcion correwcta"); break; } if(flag){ pressAnyKeyToContinue(); } clearScreen(); } } public Boolean crearPlatillo() throws IOException, FileNotFoundException, ClassNotFoundException{ System.out.println("Ingresa el nombre del platillo"); String name = ingresoDatosString(); System.out.println("Ingresa la receta"); String receta = ingresoDatosString(); System.out.println("Ingresa una descripcion a mostrar"); String info = ingresoDatosString(); System.out.println("Ingresa el precio del platillo"); float costo = ingresaDatosFloat(); return new GestorDeMenu().agregarPlatilloAlMenu(name,receta,info,costo); } public Boolean addIngredienteDG(int id) throws IOException, FileNotFoundException, ClassNotFoundException{ if(!addIngredienteFP(id)){ System.out.println("No se pudo ingresar producto"); } System.out.println("Quieres ingresar un producto mas a tu platillo\n1.Si\n2.No"); int selector = ingresoDatosInt(); if (selector == 1) { return true; } return false; } public Boolean addIngredienteFP(int id) throws IOException, FileNotFoundException, ClassNotFoundException{ int selector; int idProducto; int cantidad; System.out.println("Quieres ver la lista de Productos\n1.Si\n2.No"); selector = ingresoDatosInt(); if (selector == 1) { System.out.println( new GestorInventario().verInventario(1)); } System.out.println("Ingrese el id del producto a agregar al platillo"); idProducto = ingresoDatosInt(); System.out.println("Ingrese la cantidad que se le asignara al platillo"); cantidad = ingresoDatosInt(); return new GestorDeMenu().addInd(id,idProducto,cantidad); } private String informacionProductoReceta(int id) throws IOException, FileNotFoundException, ClassNotFoundException{ return new GestorDeMenu().receteIngredientes(id); } public void menuClientes() throws IOException, FileNotFoundException, ClassNotFoundException{ System.out.println("Menu disponible"); System.out.println(new GestorDeMenu().menuDisponible()); } private int ingresoDatosInt() { Scanner scan = new Scanner(System.in); while (true) { try { return scan.nextInt(); } catch (Exception e) { System.out.println("Ingresa un Numero"); scan.nextLine(); } } } private String ingresoDatosString() { Scanner scan = new Scanner(System.in); while (true) { try { return scan.nextLine(); } catch (Exception e) { System.out.println("Ingresa un valor valido"); scan.nextLine(); } } } private float ingresaDatosFloat(){ Scanner scan = new Scanner(System.in); while (true) { try { return scan.nextFloat(); } catch (Exception e) { System.out.println("Ingresa un Numero"); scan.nextLine(); } } } public static void clearScreen() { System.out.print("\033[H\033[2J"); System.out.flush(); } public static void pressAnyKeyToContinue() { String seguir; Scanner teclado = new Scanner(System.in); System.out.println("\nPress Enter key to continue..."); try { seguir = teclado.nextLine(); } catch(Exception ignored) {} } }
package com.lachesis.anroid.apprtcx.share; /** * 一般常量类 * * Created by Robert on 2017/9/19. */ public class Constants { public static final String SP_KEY_SERVER_HOST = "KEY_SERVER_HOST"; }
package Tugas; public class Manusia { public void bernafas(){ System.out.println("Manusia Bernafas"); } public void makan(){ System.out.println("Makan"); } }
package com.mx.profuturo.bolsa.web.controller.recruitment; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.LinkedList; import com.mx.profuturo.bolsa.configuration.TokenService; import com.mx.profuturo.bolsa.model.interview.InterviewAvailableHoursRequestDTO; import com.mx.profuturo.bolsa.model.recruitment.vo.InterviewInfoVO; import com.mx.profuturo.bolsa.model.recruitment.vo.InterviewsListVO; import com.mx.profuturo.bolsa.model.vo.common.CatalogoVO; import com.mx.profuturo.bolsa.service.interview.InterviewService; import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import com.mx.profuturo.bolsa.model.recruitment.dto.InterviewDTO; import com.mx.profuturo.bolsa.model.recruitment.vo.InterviewVO; import com.mx.profuturo.bolsa.model.service.BaseResponseBean; import com.mx.profuturo.bolsa.model.service.EntityResponseBean; import com.mx.profuturo.bolsa.model.service.auth.response.UserCredentialsVO; import com.mx.profuturo.bolsa.web.controller.common.BaseController; import sun.awt.image.ImageWatched; @Controller("InterviewController") @Scope("request") @CrossOrigin public class InterviewControllerImpl extends BaseController{ @Autowired private TokenService tokenService; @Autowired InterviewService interviewService; @ResponseBody @RequestMapping(value="reclutamiento/obtener-horas-disponibles-entrevista", method = RequestMethod.POST) public EntityResponseBean<LinkedList<CatalogoVO>> getInterviewAvailableHours (@RequestBody InterviewAvailableHoursRequestDTO interviewHourDTO) throws GenericStatusException { LinkedList<CatalogoVO> response = interviewService.getAvailableShcedule(interviewHourDTO); return this.buildEntitySuccessResponse(response); } /* //reclutamiento/agendar-entrevista @ResponseBody @RequestMapping(value="reclutamiento/guardar-entrevista", method = RequestMethod.POST) private BaseResponseBean saveInterview(@RequestBody InterviewDTO dto) { return this.buildSuccessResponse(); } @ResponseBody @RequestMapping(value="reclutamiento/obtener-entrevista", method = RequestMethod.GET) private EntityResponseBean<InterviewVO> getInterviewById(@RequestParam Integer id) { InterviewVO vo = new InterviewVO(); vo.setFecha("10/04/2020"); vo.setHora("20:30"); vo.setNombreEntrevistador("Ricky Llamas"); vo.setIdSede(1); vo.setTipoEntrevista(1); vo.setNombreSede("Profuturo Corporativo"); return this.buildEntitySuccessResponse(vo); } @ResponseBody @RequestMapping(value="reclutamiento/responder-entrevista", method = RequestMethod.POST) private BaseResponseBean answerInterview(@RequestBody InterviewDTO dto) { return this.buildSuccessResponse(); } */ @ResponseBody @RequestMapping(value="entrevistas/obtener-entrevistas", method = RequestMethod.GET) private EntityResponseBean<InterviewsListVO> getInterviewsList(@RequestHeader(value="Authorization")String token,@RequestParam(value="paginaActual") int paginaActual) throws GenericStatusException { UserCredentialsVO user = tokenService.getUserFromToken(this.getCleanToken(token)); Integer idRama = tokenService.getBranchId(this.getCleanToken(token)); InterviewsListVO entrevistas = interviewService.getInterviews(user, paginaActual, idRama); return this.buildEntitySuccessResponse(entrevistas); } }
package es.uma.sportjump.sjs.dao.test.util; import static org.junit.Assert.assertEquals; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import es.uma.sportjump.sjs.dao.daos.ExerciseBlockDao; import es.uma.sportjump.sjs.model.entities.Coach; import es.uma.sportjump.sjs.model.entities.Exercise; import es.uma.sportjump.sjs.model.entities.ExerciseBlock; @Component public class ExerciseBlockDaoTestUtil { @Autowired ExerciseBlockDao exerciseBlockDao; public ExerciseBlock createCompleteExerciseBlockNum(Coach coach, int num){ // Definition ExerciseBlock String name = "Bloque rapidez" + num; String type = "Velocidad"+ num; String description = "Bloque donde se trabaja la velocidad inmediata y la fuerza explosiva"+ num; //Create ExerciseBlock ExerciseBlock block = new ExerciseBlock(); block.setName(name); block.setDescription(description); block.setType(type); block.setCoach(coach); //Persist entity exerciseBlockDao.persistExerciseBlock(block); return block; } public Long createExerciseBlock(String name, String type, String description, List<Exercise> exerciseList, Coach coach) { //create object ExerciseBlock exerciseBlock = new ExerciseBlock(); exerciseBlock.setName(name); exerciseBlock.setDescription(description); exerciseBlock.setType(type); exerciseBlock.setListExercises(exerciseList); exerciseBlock.setCoach(coach); //Persist exerciseBlockDao.persistExerciseBlock(exerciseBlock); return Long.valueOf(exerciseBlock.getIdExerciseBlock()); } public ExerciseBlock readExerciseBlock(Long idExerciseBlock) { return exerciseBlockDao.getExerciseBlockById(idExerciseBlock); } public ExerciseBlock readExerciseBlockByNameAndCoach(String name, Coach coach) { return exerciseBlockDao.getExerciseBlockByNameAndCoach(name, coach); } public void deleteExerciseBlock(ExerciseBlock exerciseBlock) { //remove exerciseBlockDao.deleteExerciseBlock(exerciseBlock.getIdExerciseBlock()); } public void updateExerciseBlock(String name2, String type2,ExerciseBlock exerciseBlock) { //set attributes exerciseBlock.setName(name2); exerciseBlock.setType(type2); exerciseBlockDao.persistExerciseBlock(exerciseBlock); } public void makeAssertExerciseBlock(String name, String type, ExerciseBlock exerciseBlock) { assertEquals(name, exerciseBlock.getName()); assertEquals(type, exerciseBlock.getType()); } }
package parser.parsertables; import parser.syntax.Syntax; import java.util.Hashtable; public class LRParserTables extends LRPrimitiveTables { public LRParserTables(Syntax syntax) throws ParserBuildException { super(syntax); } protected LRSyntaxNode createStartNode(Nullable nullable, FirstSets firstSets) { return new LRSyntaxNode(nullable, firstSets); } protected void init() throws ParserBuildException { Nullable nullable = new Nullable(syntax, nonterminals); firstSets = new FirstSets(syntax, nullable, nonterminals); syntaxNodes = createStartNode(nullable, firstSets).build(syntax, syntaxNodes, new Hashtable()); gotoTable = generateGoto(syntaxNodes); parseTable = generateParseAction(syntaxNodes); } }
package logicaDeNegocio; public class Apl { public static void main(String[] args) { // TODO Auto-generated method stub String a = "2019-11-11 20:00:00"; System.out.println(DateTimeManager.fixHour(a)); } }
package com.snab.tachkit.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; /** * Created by Ringo on 08.08.2015. */ public class AutoHeightImageView extends ImageView { public AutoHeightImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMeasuredWidth(); setMeasuredDimension(width, (int)((float)width * 0.7f)); } }
package com.example.alumnos.enemyappv2; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; public class Top5Fragment extends Fragment { ArrayAdapter adapter; GridView top5GridView; MainActivity mainActivity; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.top_5_enemies_fragment,container,false); mainActivity = (MainActivity)getActivity(); top5GridView = view.findViewById(R.id.top5_grid); adapter = new Top5GridAdapter(getContext(), R.layout.top_5_enemies_grid_layout, mainActivity.getEnemiesListClass().getArrayList()); top5GridView.setAdapter(adapter); return view; } }
package techokami.lib.integration; import buildcraft.api.tools.IToolWrench; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Optional; public class Integration { private boolean bcLoaded = false; public Integration() { bcLoaded = Loader.isModLoaded("BuildCraft|Core"); } @Optional.Method(modid = "BuildCraft|Core") private boolean bc_isWrench(Item item) { return (item instanceof IToolWrench); } @Optional.Method(modid = "BuildCraft|Core") private boolean bc_wrench(Item item, EntityPlayer player, int x, int y, int z) { if(item instanceof IToolWrench) { IToolWrench wrench = (IToolWrench)item; if(wrench.canWrench(player, x, y, z)) { wrench.wrenchUsed(player, x, y, z); return true; } } return false; } public boolean isWrench(Item item) { return (bcLoaded ? bc_isWrench(item) : false) || false; } public boolean wrench(Item item, EntityPlayer player, int x, int y, int z) { return (bcLoaded ? bc_wrench(item, player, x, y, z) : false) || false; } }
package kevin.jugg.order_service.service; import kevin.jugg.order_service.domain.ProductOrder; /** * @Description:订单业务类 * @Author: Kevin * @Create 2020-01-09 18:17 */ public interface ProductOrderService { /** * 下单接口 * * @param userId * @param productId * @return */ ProductOrder save(int userId, int productId); }
package backend; import lombok.*; import java.util.ArrayList; @Data public class OpenWeather { private ArrayList<Weather> weather = new ArrayList<>(); private Main main; private Wind wind; private String name; @Data class Weather { private String description; } @Data class Main { private String temp; private String pressure; private String humidity; } @Data class Wind { private String speed; private String deg; } }
package com.anchor.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; public abstract class BaseResource { @Context protected HttpServletRequest request; @Context protected HttpServletResponse response; }
package herencia; /** * * @author OHMASTER */ public class Herencia { public static void main(String[] args) { Dog doguno = new Dog(); doguno.LlenarDatosPerro(); doguno.VerSalida(); Dog dogdos = new Dog(); dogdos.LlenarDatosPerro(); dogdos.VerSalida(); Dog dogtres = new Dog(); dogtres.LlenarDatosPerro(); dogtres.VerSalida(); Dog dogcuatro = new Dog(); dogcuatro.LlenarDatosPerro(); dogcuatro.VerSalida(); Dog dogcinco = new Dog(); dogcinco.LlenarDatosPerro(); dogcinco.VerSalida(); /*Dog2 perro = new Dog2(); Scanner SC= new Scanner (System.in); System.out.println("ingresa parte"); perro.portion=SC.nextDouble();*/ } }
package com.stackroute.activitystream.servicesbackend.dao; import java.util.List; <<<<<<< HEAD import com.stackroute.activitystream.servicesbackend.model.Circle; ======= import com.stackroute.activitystream.ServicesBackEnd.model.Circle; //Why one method is public and others are default >>>>>>> 510ac28f9ce32f7248135fde80af97a7e75898fb public interface CircleDao { //what is c boolean addCircle(Circle c); boolean removeCircle(String circleId); //the method name should be getAllCircles() List<Circle> getAllCircle(); //You need one more method getCircleByName(String circleName); Circle getCircleById(String circleId ); public boolean updateCircle(Circle circle); }