text
stringlengths
10
2.72M
package Models; /** * Interface será implementada em usuario, para autenticar o login */ public interface Autentica { public void login(String nome, String email, int senha); }
/* * TASSEL - Trait Analysis by a aSSociation Evolution & Linkage * Copyright (C) 2003 Ed Buckler * * This software evaluates linkage disequilibrium nucletide diversity and * associations. For more information visit http://www.maizegenetics.net * * This software is distributed under GNU general public license, version 2 and without * any warranty or technical support. * * You can redistribute and/or modify it under the terms of GNU General * public license. * */ //Title: TASSELMainFrame //Version: //Copyright: Copyright (c) 1997 //Author: Ed Buckler //Company: NCSU package net.maizegenetics.tassel; import net.maizegenetics.analysis.popgen.SequenceDiversityPlugin; import net.maizegenetics.analysis.data.ProjectionLoadPlugin; import net.maizegenetics.analysis.distance.KinshipPlugin; import net.maizegenetics.analysis.chart.TableDisplayPlugin; import net.maizegenetics.analysis.chart.Grid2dDisplayPlugin; import net.maizegenetics.analysis.chart.ManhattanDisplayPlugin; import net.maizegenetics.analysis.chart.QQDisplayPlugin; import net.maizegenetics.analysis.association.FixedEffectLMPlugin; import net.maizegenetics.analysis.association.MLMPlugin; import net.maizegenetics.analysis.data.PlinkLoadPlugin; import net.maizegenetics.analysis.popgen.LinkageDiseqDisplayPlugin; import net.maizegenetics.analysis.popgen.LinkageDisequilibriumPlugin; import net.maizegenetics.analysis.data.IRodsFileLoadPlugin; import net.maizegenetics.analysis.data.MergeGenotypeTablesPlugin; import net.maizegenetics.analysis.data.UnionAlignmentPlugin; import net.maizegenetics.analysis.data.FileLoadPlugin; import net.maizegenetics.analysis.data.IntersectionAlignmentPlugin; import net.maizegenetics.analysis.data.GenotypeSummaryPlugin; import net.maizegenetics.analysis.data.ExportPlugin; import net.maizegenetics.analysis.data.SeparatePlugin; import net.maizegenetics.analysis.data.SynonymizerPlugin; import net.maizegenetics.analysis.filter.FilterTaxaAlignmentPlugin; import net.maizegenetics.analysis.filter.FilterTaxaPropertiesPlugin; import net.maizegenetics.analysis.filter.FilterSiteNamePlugin; import net.maizegenetics.analysis.filter.FilterAlignmentPlugin; import net.maizegenetics.analysis.filter.FilterTraitsPlugin; import net.maizegenetics.analysis.tree.CreateTreePlugin; import net.maizegenetics.analysis.tree.ArchaeopteryxPlugin; import net.maizegenetics.analysis.chart.ChartDisplayPlugin; import net.maizegenetics.analysis.association.RidgeRegressionEmmaPlugin; import net.maizegenetics.analysis.modelfitter.StepwiseOLSModelFitterPlugin; import net.maizegenetics.analysis.numericaltransform.NumericalTransformPlugin; import net.maizegenetics.gui.PrintHeapAction; import net.maizegenetics.plugindef.*; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.progress.ProgressPanel; import net.maizegenetics.util.Utils; import org.apache.log4j.Logger; import org.bio5.irods.iplugin.bean.IPlugin; import org.bio5.irods.iplugin.views.IPlugin_OpenImage; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.io.*; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import net.maizegenetics.analysis.data.HetsToUnknownPlugin; import net.maizegenetics.analysis.gbs.BinaryToTextPlugin; /** * TASSELMainFrame * */ public class TASSELMainFrame extends JFrame implements ActionListener { private static final Logger myLogger = Logger.getLogger(TASSELMainFrame.class); public static final String version = "5.0.6"; public static final String versionDate = "May 15, 2014"; private DataTreePanel myDataTreePanel; private String tasselDataFile = "TasselDataFile"; //a variable to control when the progress bar was last updated private JFileChooser filerSave = new JFileChooser(); private JFileChooser filerOpen = new JFileChooser(); private JScrollPane reportPanelScrollPane = new JScrollPane(); private JTextArea reportPanelTextArea = new JTextArea(); JScrollPane mainPanelScrollPane = new JScrollPane(); JPanel mainDisplayPanel = new JPanel(); private JTextArea mainPanelTextArea = new JTextArea(); private JTextField myStatusTextField = new JTextField(); private JMenuItem openCompleteDataTreeMenuItem = new JMenuItem(); private JMenuItem openDataMenuItem = new JMenuItem(); private JMenuItem saveCompleteDataTreeMenuItem = new JMenuItem(); private JMenuItem saveDataTreeAsMenuItem = new JMenuItem(); private JMenuItem loginIRods = new JMenuItem(); private JMenuItem uploadFilesToIRods = new JMenuItem(); private PreferencesDialog thePreferencesDialog; private final ProgressPanel myProgressPanel = ProgressPanel.getInstance(); private HashMap<JMenuItem, Plugin> myMenuItemHash = new HashMap<JMenuItem, Plugin>(); private IPlugin irodsImagej = null; private IRodsFileLoadPlugin iRodsFileLoadPlugin = null; public TASSELMainFrame() { try { loadSettings(); myDataTreePanel = new DataTreePanel(this); myDataTreePanel.setToolTipText("Data Tree Panel"); addMenuBar(); initializeMyFrame(); /********************* Zhong Yang ***********************/ IPlugin_OpenImage.main(null); // Start irods-imageJ plugin irodsImagej = IPlugin_OpenImage.getIrodsImagej(); // Get irods-imageJ beans. irodsImagej.setTASSELMainFrame(this); // Set TASSEL itself to beans. irodsImagej.setIRodsFileLoadPlugin(iRodsFileLoadPlugin); // Set menu item "Load iRods" to beans. /*******************************************************/ this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage) " + version); myLogger.info("Tassel Version: " + version + " Date: " + versionDate); myLogger.info("Max Available Memory Reported by JVM: " + Utils.getMaxHeapSizeMB() + " MB"); myLogger.info("Java Version: " + System.getProperty("java.version")); } catch (Exception e) { e.printStackTrace(); } } //Component initialization private void initializeMyFrame() throws Exception { getContentPane().setLayout(new BorderLayout()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // it is time for TASSEL to claim more (almost all) of the screen real estate for itself // this size was selected so as to encourage the user to resize to full screen, thereby // insuring that all parts of the frame are visible. int xDim = TasselPrefs.getXDim(); int yDim = TasselPrefs.getYDim(); if ((xDim < 50) || (yDim < 50)) { setSize(new Dimension(screenSize.width * 19 / 20, screenSize.height * 19 / 20)); } else { setSize(xDim, yDim); } setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage)"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(WindowEvent e) { TasselPrefs.putXDim(getWidth()); TasselPrefs.putYDim(getHeight()); System.exit(0); } }); filerSave.setDialogType(JFileChooser.SAVE_DIALOG); JSplitPane dataTreeReportPanelsSplitPanel = new JSplitPane(); dataTreeReportPanelsSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT); reportPanelTextArea.setEditable(false); reportPanelTextArea.setToolTipText("Report Panel"); mainPanelTextArea.setDoubleBuffered(true); mainPanelTextArea.setEditable(false); mainPanelTextArea.setFont(new java.awt.Font("Monospaced", 0, 12)); mainPanelTextArea.setToolTipText("Main Panel"); myStatusTextField.setBackground(Color.lightGray); myStatusTextField.setBorder(null); /***************************** Zhong Yang ******************************/ // Adding two items in file menu: // 1. login to iRods; // 2. upload local file to iRods server. loginIRods.setText("Login iRods Account"); loginIRods.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { IPlugin_OpenImage.getIrodsImagej().getMainWindow().setVisible(true); IPlugin_OpenImage.getIrodsImagej().getMainWindow().setVisibleFlag(false); if(IPlugin_OpenImage.getIrodsImagej().getMainWindowStatus() == true){ IPlugin_OpenImage.getIrodsImagej().getMainWindow().setVisible(false); uploadFilesToIRods.setEnabled(true); } } }); uploadFilesToIRods.setText("Upload Files To iRods"); uploadFilesToIRods.setEnabled(false); uploadFilesToIRods.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { IPlugin_OpenImage.getIrodsImagej().getMainWindow().setVisible(true); } }); /*******************************************************************/ saveCompleteDataTreeMenuItem.setText("Save Data Tree"); saveCompleteDataTreeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveCompleteDataTreeMenuItem_actionPerformed(e); } }); saveDataTreeAsMenuItem.setText("Save Data Tree As ..."); saveDataTreeAsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveDataTreeMenuItem_actionPerformed(e); } }); openCompleteDataTreeMenuItem.setText("Open Data Tree"); openCompleteDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openCompleteDataTreeMenuItem_actionPerformed(e); } }); openDataMenuItem.setText("Open Data Tree..."); openDataMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openDataMenuItem_actionPerformed(e); } }); JSplitPane dataTreeReportMainPanelsSplitPanel = new JSplitPane(); getContentPane().add(dataTreeReportMainPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportMainPanelsSplitPanel.add(dataTreeReportPanelsSplitPanel, JSplitPane.LEFT); dataTreeReportPanelsSplitPanel.add(myDataTreePanel, JSplitPane.TOP); JSplitPane reportProgressSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); JPanel reportPanel = new JPanel(new BorderLayout()); reportProgressSplitPane.add(reportPanel, JSplitPane.TOP); reportPanel.add(reportPanelScrollPane, BorderLayout.CENTER); reportPanelScrollPane.getViewport().add(reportPanelTextArea, null); reportProgressSplitPane.add(new JScrollPane(myProgressPanel), JSplitPane.BOTTOM); dataTreeReportPanelsSplitPanel.add(reportProgressSplitPane, JSplitPane.BOTTOM); dataTreeReportMainPanelsSplitPanel.add(mainDisplayPanel, JSplitPane.RIGHT); mainDisplayPanel.setLayout(new BorderLayout()); mainPanelScrollPane.getViewport().add(mainPanelTextArea, null); mainDisplayPanel.add(mainPanelScrollPane, BorderLayout.CENTER); mainPanelScrollPane.getViewport().add(mainPanelTextArea, null); getContentPane().add(myStatusTextField, BorderLayout.SOUTH); dataTreeReportMainPanelsSplitPanel.setDividerLocation(getSize().width / 4); dataTreeReportPanelsSplitPanel.setDividerLocation((int) (getSize().height / 3.5)); reportProgressSplitPane.setDividerLocation((int) (getSize().height / 3.5)); } private void addMenuBar() { JMenuBar jMenuBar = new JMenuBar(); jMenuBar.add(getFileMenu()); jMenuBar.add(getDataMenu()); jMenuBar.add(getFiltersMenu()); jMenuBar.add(getAnalysisMenu()); jMenuBar.add(getResultsMenu()); jMenuBar.add(getGBSMenu()); jMenuBar.add(getHelpMenu()); this.setJMenuBar(jMenuBar); } //Help | About action performed private void helpAbout_actionPerformed(ActionEvent e) { AboutBox dlg = new AboutBox(this); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = getSize(); Point loc = getLocation(); dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); dlg.setVisible(true); } /*********************** Zhong Yang ***********************/ // Let other class enable "Upload files to iRods", because user may directly login form "Load iRods" in Data menu. public void setLoadDataFromIRodsMenuItemEnable(){ uploadFilesToIRods.setEnabled(true); } // IrodsImageJ is a java beans. public IPlugin getIrodsImagej(){ return irodsImagej; } /**********************************************************/ public void sendMessage(String text) { myStatusTextField.setForeground(Color.BLACK); myStatusTextField.setText(text); } public void sendErrorMessage(String text) { myStatusTextField.setForeground(Color.RED); myStatusTextField.setText(text); } public void setMainText(String text) { mainPanelTextArea.setText(text); } public void setNoteText(String text) { reportPanelTextArea.setText(text); } private void loadSettings() { filerOpen.setCurrentDirectory(new File(TasselPrefs.getOpenDir())); filerSave.setCurrentDirectory(new File(TasselPrefs.getSaveDir())); } /** * Provides a save filer that remembers the last location something was * saved to */ private File getSaveFile() { File saveFile = null; int returnVal = filerSave.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { saveFile = filerSave.getSelectedFile(); TasselPrefs.putSaveDir(filerSave.getCurrentDirectory().getPath()); } return saveFile; } /** * Provides a open filer that remember the last location something was * opened from */ private File getOpenFile() { File openFile = null; int returnVal = filerOpen.showOpenDialog(this); System.out.println("returnVal = " + returnVal); System.out.println("JFileChooser.OPEN_DIALOG " + JFileChooser.OPEN_DIALOG); if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) { openFile = filerOpen.getSelectedFile(); System.out.println("openFile = " + openFile); TasselPrefs.putOpenDir(filerOpen.getCurrentDirectory().getPath()); } return openFile; } public void addDataSet(DataSet theDataSet, String defaultNode) { myDataTreePanel.addDataSet(theDataSet, defaultNode); } private void saveDataTree(String file) { Map dataToSerialize = new LinkedHashMap(); Map dataFromTree = myDataTreePanel.getDataList(); StringBuilder builder = new StringBuilder(); Iterator itr = dataFromTree.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) dataFromTree.get(currentDatum); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(currentDatum); oos.close(); if (out.toByteArray().length > 0) { dataToSerialize.put(currentDatum, currentNode); } } catch (Exception e) { myLogger.warn("saveDataTree: object: " + currentDatum.getName() + " type: " + currentDatum.getData().getClass().getName() + " does not serialize."); myLogger.warn("saveDataTree: message: " + e.getMessage()); if (builder.length() == 0) { builder.append("Due to error, these data sets could not\n"); builder.append("included in the saved file..."); } builder.append("Data set: "); builder.append(currentDatum.getName()); builder.append(" type: "); builder.append(currentDatum.getData().getClass().getName()); builder.append("\n"); } } try { File theFile = new File(Utils.addSuffixIfNeeded(file, ".zip")); FileOutputStream fos = new FileOutputStream(theFile); java.util.zip.ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry thisEntry = new ZipEntry("DATA"); zos.putNextEntry(thisEntry); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(dataToSerialize); oos.flush(); zos.closeEntry(); fos.close(); sendMessage("Data saved to " + theFile.getAbsolutePath()); } catch (Exception ee) { sendErrorMessage("Data could not be saved: " + ee); ee.printStackTrace(); } if (builder.length() != 0) { JOptionPane.showMessageDialog(this, builder.toString(), "These data sets not saved...", JOptionPane.INFORMATION_MESSAGE); } } private boolean readDataTree(String file) { String dataTreeLoadFailed = "Unable to open the saved data tree. The file format of this version is " + "incompatible with other versions."; boolean loadedDataTreePanel = false; try { FileInputStream fis = null; ObjectInputStream ois = null; if (file.endsWith("zip")) { fis = new FileInputStream(file); java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(fis); zis.getNextEntry(); ois = new ObjectInputStream(zis); } else { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); } try { Map data = (Map) ois.readObject(); Iterator itr = data.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) data.get(currentDatum); myDataTreePanel.addDatum(currentNode, currentDatum); } loadedDataTreePanel = true; } catch (InvalidClassException ice) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); } finally { fis.close(); } if (loadedDataTreePanel) { sendMessage("Data loaded."); } } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "File not found: " + file, "File not found", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } catch (Exception ee) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed + ee, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } return loadedDataTreePanel; } private void helpButton_actionPerformed(ActionEvent e) { HelpDialog theHelpDialog = new HelpDialog(this); theHelpDialog.setLocationRelativeTo(this); theHelpDialog.setVisible(true); } private void openCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { String dataFileName = tasselDataFile + ".zip"; File dataFile = new File(dataFileName); if (dataFile.exists()) { readDataTree(dataFileName); } else if (new File("QPGADataFile").exists()) { // this exists to maintain backward compatibility with previous versions (pre-v0.99) readDataTree("QPGADataFile"); } else { JOptionPane.showMessageDialog(this, "File: " + dataFile.getAbsolutePath() + " does not exist.\n" + "Try using File/Open Data Tree..."); } } private void openDataMenuItem_actionPerformed(ActionEvent e) { File f = getOpenFile(); if (f != null) { readDataTree(f.getAbsolutePath()); } } private void saveDataTreeMenuItem_actionPerformed(ActionEvent e) { File f = getSaveFile(); if (f != null) { saveDataTree(f.getAbsolutePath()); } } private void saveCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { saveDataTree(tasselDataFile + ".zip"); } private void preferencesMenuItem_actionPerformed(ActionEvent e) { if (thePreferencesDialog == null) { thePreferencesDialog = new PreferencesDialog(); thePreferencesDialog.pack(); } thePreferencesDialog.setLocationRelativeTo(this); thePreferencesDialog.setVisible(true); } public void updateMainDisplayPanel(JPanel panel) { mainDisplayPanel.removeAll(); mainDisplayPanel.add(panel, BorderLayout.CENTER); mainDisplayPanel.repaint(); mainDisplayPanel.validate(); } public DataTreePanel getDataTreePanel() { return myDataTreePanel; } public ProgressPanel getProgressPanel() { return myProgressPanel; } private JMenuItem createMenuItem(Plugin theTP) { return createMenuItem(theTP, -1); } private JMenuItem createMenuItem(Plugin theTP, int mnemonic) { ImageIcon icon = theTP.getIcon(); JMenuItem menuItem = new JMenuItem(theTP.getButtonName(), icon); if (mnemonic != -1) { menuItem.setMnemonic(mnemonic); } int pixels = 30; if (icon != null) { pixels -= icon.getIconWidth(); pixels /= 2; } menuItem.setIconTextGap(pixels); menuItem.setBackground(Color.white); menuItem.setMargin(new Insets(2, 2, 2, 2)); menuItem.setToolTipText(theTP.getToolTipText()); menuItem.addActionListener(this); theTP.addListener(myDataTreePanel); myMenuItemHash.put(menuItem, theTP); return menuItem; } private JMenuItem createMenuItem(Action action, int mnemonic) { Icon icon = (Icon) action.getValue("SmallIcon"); JMenuItem menuItem = new JMenuItem(action.getValue("Name").toString(), icon); if (mnemonic != -1) { menuItem.setMnemonic(mnemonic); } int pixels = 30; if (icon != null) { pixels -= icon.getIconWidth(); pixels /= 2; } menuItem.setIconTextGap(pixels); menuItem.setBackground(Color.white); menuItem.setMargin(new Insets(2, 2, 2, 2)); menuItem.addActionListener(action); return menuItem; } private JMenu getFiltersMenu() { JMenu result = new JMenu("Filter"); result.setMnemonic(KeyEvent.VK_F); result.add(createMenuItem(new FilterAlignmentPlugin(this, true))); result.add(createMenuItem(new FilterSiteNamePlugin(this, true))); result.add(createMenuItem(new FilterTaxaAlignmentPlugin(this, true))); result.add(createMenuItem(new FilterTaxaPropertiesPlugin(this, true))); result.add(createMenuItem(new FilterTraitsPlugin(this, true))); return result; } private JMenu getDataMenu() { JMenu result = new JMenu("Data"); result.setMnemonic(KeyEvent.VK_D); PlinkLoadPlugin plinkLoadPlugin = new PlinkLoadPlugin(this, true); plinkLoadPlugin.addListener(myDataTreePanel); ProjectionLoadPlugin projectionLoadPlugin = new ProjectionLoadPlugin(this, true); projectionLoadPlugin.addListener(myDataTreePanel); iRodsFileLoadPlugin = new IRodsFileLoadPlugin(this, true, plinkLoadPlugin, projectionLoadPlugin); // Adding Load iRods item for menu. result.add(createMenuItem(new FileLoadPlugin(this, true, plinkLoadPlugin, projectionLoadPlugin), KeyEvent.VK_L)); result.add(createMenuItem(iRodsFileLoadPlugin)); result.add(createMenuItem(new ExportPlugin(this, true))); result.add(createMenuItem(new NumericalTransformPlugin(this, true))); result.add(createMenuItem(new SynonymizerPlugin(this, true))); result.add(createMenuItem(new IntersectionAlignmentPlugin(this, true))); result.add(createMenuItem(new UnionAlignmentPlugin(this, true))); result.add(createMenuItem(new MergeGenotypeTablesPlugin(this, true))); result.add(createMenuItem(new SeparatePlugin(this, true))); result.add(createMenuItem(new HetsToUnknownPlugin(this, true))); result.addSeparator(); JMenuItem delete = new JMenuItem("Delete Dataset"); delete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { myDataTreePanel.deleteSelectedNodes(); } }); delete.setToolTipText("Delete Dataset"); URL imageURL = TASSELMainFrame.class.getResource("images/trash.gif"); if (imageURL == null) { delete.setIconTextGap(30); } else { delete.setIcon(new ImageIcon(imageURL)); delete.setIconTextGap(6); } delete.setIconTextGap(6); result.add(delete); return result; } private JMenu getAnalysisMenu() { JMenu result = new JMenu("Analysis"); result.setMnemonic(KeyEvent.VK_A); result.add(createMenuItem(new SequenceDiversityPlugin(this, true))); result.add(createMenuItem(new LinkageDisequilibriumPlugin(this, true))); result.add(createMenuItem(new CreateTreePlugin(this, true))); result.add(createMenuItem(new KinshipPlugin(this, true))); result.add(createMenuItem(new FixedEffectLMPlugin(this, true))); result.add(createMenuItem(new MLMPlugin(this, true))); result.add(createMenuItem(new RidgeRegressionEmmaPlugin(this, true))); result.add(createMenuItem(new GenotypeSummaryPlugin(this, true))); result.add(createMenuItem(new StepwiseOLSModelFitterPlugin(this, true))); return result; } private JMenu getResultsMenu() { JMenu result = new JMenu("Results"); result.setMnemonic(KeyEvent.VK_R); result.add(createMenuItem(new TableDisplayPlugin(this, true))); result.add(createMenuItem(new ArchaeopteryxPlugin(this, true))); result.add(createMenuItem(new Grid2dDisplayPlugin(this, true))); result.add(createMenuItem(new LinkageDiseqDisplayPlugin(this, true))); result.add(createMenuItem(new ChartDisplayPlugin(this, true))); result.add(createMenuItem(new QQDisplayPlugin(this, true))); result.add(createMenuItem(new ManhattanDisplayPlugin(this, true))); return result; } private JMenu getFileMenu() { JMenu fileMenu = new JMenu(); fileMenu.setText("File"); fileMenu.add(saveCompleteDataTreeMenuItem); fileMenu.add(openCompleteDataTreeMenuItem); fileMenu.add(saveDataTreeAsMenuItem); fileMenu.add(openDataMenuItem); /************************* Zhong Yang **************************/ fileMenu.add(loginIRods); fileMenu.add(uploadFilesToIRods); /***************************************************************/ JMenuItem preferencesMenuItem = new JMenuItem(); preferencesMenuItem.setText("Set Preferences"); preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { preferencesMenuItem_actionPerformed(e); } }); fileMenu.add(preferencesMenuItem); fileMenu.addSeparator(); JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { TasselPrefs.putXDim(getWidth()); TasselPrefs.putYDim(getHeight()); System.exit(0); } }); fileMenu.add(exitMenuItem); return fileMenu; } private JMenu getGBSMenu() { JMenu result = new JMenu("GBS"); result.setMnemonic(KeyEvent.VK_G); result.add(createMenuItem(new BinaryToTextPlugin(this, true))); return result; } private JMenu getHelpMenu() { JMenu helpMenu = new JMenu(); helpMenu.setMnemonic(KeyEvent.VK_H); helpMenu.setText("Help"); URL infoImageURL = TASSELMainFrame.class.getResource("images/info.gif"); Icon infoIcon = null; if (infoImageURL != null) { infoIcon = new ImageIcon(infoImageURL); } helpMenu.add(createMenuItem(new AbstractAction("Help Manual", infoIcon) { @Override public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }, -1)); URL aboutImageURL = TASSELMainFrame.class.getResource("images/Tassel_Logo16.png"); Icon aboutIcon = null; if (aboutImageURL != null) { aboutIcon = new ImageIcon(aboutImageURL); } helpMenu.add(createMenuItem(new AbstractAction("About", aboutIcon) { @Override public void actionPerformed(ActionEvent e) { helpAbout_actionPerformed(e); } }, -1)); helpMenu.add(createMenuItem(PrintHeapAction.getInstance(this), -1)); return helpMenu; } @Override public void actionPerformed(ActionEvent e) { JMenuItem theMenuItem = (JMenuItem) e.getSource(); Plugin theTP = this.myMenuItemHash.get(theMenuItem); PluginEvent event = new PluginEvent(myDataTreePanel.getSelectedTasselDataSet()); ProgressPanel progressPanel = getProgressPanel(); progressPanel.addPlugin(theTP); ThreadedPluginListener thread = new ThreadedPluginListener(theTP, event); thread.start(); } }
package zda.task.webchat.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import zda.task.webchat.model.ChatMessage; import zda.task.webchat.repository.ChatMessageRepository; import java.util.Collections; import java.util.List; /** * Service for saving and searching ChatMessages * * @author Zhevnov D.A. * @ created 2020-08-08 */ @Service public class ChatMessageService { @Autowired private ChatMessageRepository chatMessageRepository; public ChatMessage saveMessage(ChatMessage chatMessage) { return chatMessageRepository.save(chatMessage); } public List<ChatMessage> findAll() { return chatMessageRepository.findAll(); } public List<ChatMessage> findLast1000By() { List<ChatMessage> usersList = chatMessageRepository.findTop1000ByOrderByIdDesc(); Collections.reverse(usersList); return usersList; } }
package controllers; import play.Logger; import play.Play; import play.data.DynamicForm; import play.mvc.Controller; import play.mvc.Result; import com.typesafe.plugin.*; public class Mail extends Controller { public static Result send() { DynamicForm form = form().bindFromRequest(); String email = form.get("email"); String message = form.get("message"); Logger.debug("sending feedback message from: " + email); String to = Play.application().configuration().getString("feedback.mail.to"); String subject = Play.application().configuration().getString("feedback.mail.subject"); MailerAPI mail = play.Play.application().plugin(MailerPlugin.class).email(); mail.setSubject(subject).addRecipient(to).addFrom(email); try { mail.send(message); } catch (Exception e) { Logger.error(e.getMessage()); e.printStackTrace(); return internalServerError("Sending email failed: " + e.getMessage()); } return ok(); } }
package com.ssm.service; import java.util.List; import com.ssm.entity.User; public interface UserService { public User findUserById(Integer id); public void insert(User user); public List<User> findAll(int offset,int limit); }
package com.itinerary.resort.ws; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.easymock.EasyMock; import org.junit.Test; //import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; //import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.itinerary.resort.model.ResortReservationModel; import com.itinerary.resort.service.resort.IResortService; /** * TestResortWS test class. * @author akuma408 * */ @PrepareForTest({ Response.class }) //@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:Test-ApplicationContext.xml" }) public class TestResortWS { /** * value. */ private final Integer value = 200; /** * value. */ private final Integer value1 = 201; /** * value. */ private final Long value2 = (long) 21; /** * resortservice autorired. */ @Autowired private BookResortWS bookResortWebService; /** * @throws Exception Exception */ @Test @SuppressWarnings("PMD.LawOfDemeter") public void bookResortReservationTest() throws Exception { BookResortWS resortWS = new BookResortWS(); ResortReservationModel resortReservationModel = new ResortReservationModel(); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value)).andReturn( responBuilder); EasyMock.expect(iResortService.bookResortReservation(EasyMock.anyObject( ResortReservationModel.class))) .andReturn(resortReservationModel); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.bookResortReservation(resortReservationModel); } /** * @throws Exception Exception */ @Test public void bookResortReservation2Test() throws Exception { BookResortWS resortWS = new BookResortWS(); ResortReservationModel resortReservationModel = new ResortReservationModel(); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value1)).andReturn( responBuilder); EasyMock.expect(iResortService.bookResortReservation(EasyMock.anyObject( ResortReservationModel.class))) .andThrow(new Exception()); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.bookResortReservation(resortReservationModel); } /** * @throws Exception Exception */ @Test public void provideReservationTest() throws Exception { BookResortWS resortWS = new BookResortWS(); List<ResortReservationModel> resortlist = new ArrayList<ResortReservationModel>(); ResortReservationModel resortReservationModel = new ResortReservationModel(); resortlist.add(resortReservationModel); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value1)). andReturn(responBuilder); EasyMock.expect(iResortService.provideResortReservation( EasyMock.anyLong())). andReturn(resortlist); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.provideReservation(value2); } /** * @throws Exception Exception */ @Test public void provideReservationTest1() throws Exception { BookResortWS resortWS = new BookResortWS(); List<ResortReservationModel> diningList = new ArrayList<ResortReservationModel>(); ResortReservationModel diningReservationModel = new ResortReservationModel(); diningList.add(diningReservationModel); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value1)).andReturn( responBuilder); EasyMock.expect(iResortService.provideResortReservation( EasyMock.anyLong())). andReturn(null); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.provideReservation(value2); } /** * @throws Exception Exception */ @Test public void provideReservationTest2() throws Exception { BookResortWS resortWS = new BookResortWS(); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)).andReturn( responBuilder); EasyMock.expect(Response.status(value1)).andReturn( responBuilder); EasyMock.expect(iResortService.provideResortReservation( EasyMock.anyLong())). andThrow(new Exception()); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.provideReservation(value2); } /** * @throws Exception Exception */ @Test public void cancelResortTest() throws Exception { BookResortWS resortWS = new BookResortWS(); ResortReservationModel resortReservationModel = new ResortReservationModel(); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value1)). andReturn( responBuilder); EasyMock.expect(iResortService.cancelResortReservation(EasyMock. anyLong(), EasyMock.anyLong())).andReturn(value2); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.cancelResort(resortReservationModel); } /** * @throws Exception Exception */ @Test public void cancelResortTest2() throws Exception { BookResortWS resortWS = new BookResortWS(); ResortReservationModel resortReservationModel = new ResortReservationModel(); IResortService iResortService = EasyMock.createMock( IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value1)). andReturn( responBuilder); EasyMock.expect(iResortService.cancelResortReservation( EasyMock.anyLong(), EasyMock.anyLong())) .andThrow(new Exception()); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.cancelResort(resortReservationModel); } /** * @throws Exception Exception */ @Test public void cancelResortTest3() throws Exception { BookResortWS resortWS = new BookResortWS(); ResortReservationModel resortReservationModel = new ResortReservationModel(); IResortService iResortService = EasyMock. createMock(IResortService.class); PowerMock.mockStatic(Response.class); ResponseBuilder responBuilder = EasyMock.createMock( ResponseBuilder.class); EasyMock.expect(responBuilder.entity(Object.class)). andReturn(responBuilder); EasyMock.expect(Response.status(value1)). andReturn(responBuilder); EasyMock.expect(iResortService.cancelResortReservation(EasyMock. anyLong(), EasyMock.anyLong())).andReturn(1L); EasyMock.replay(responBuilder, iResortService); PowerMock.replay(Response.class); resortWS.setResortservice(iResortService); resortWS.cancelResort(resortReservationModel); } }
package pro.likada.bot.orders.utils; /** * Created by Yusupov on 3/31/2017. */ public class LikadaOrdersBotUtils { public static final Integer LIK_ORDERS_BOT_ID = 370148039; public static final String LIK_ORDERS_BOT_USERNAME = "lik_orders_bot"; public static final String LIK_ORDERS_BOT_TOKEN = "370148039:AAGH_y756i2gvK4OHz8m4zPc4w-SuOd4Dn0"; public static final String PATH_TO_CERTIFICATE_STORE = "./TEMP/localhost.jks"; //self-signed and non-self-signed. public static final String CERTIFICATE_STORE_PASSWORD = "2711991z"; //password for your certificate-store public static final String PATH_TO_CERTIFICATE_PUBLIC_KEY = "./TEMP/localhost.pem"; //only for self-signed webhooks private static final int PORT = 8443; public static final String EXTERNAL_WEBHOOK_URL = "https://erp.likada.pro:" + PORT; // https://(xyz.)externaldomain.tld public static final String INTERNAL_WEBHOOK_URL = "https://localhost.erp.likada.pro:" + PORT; // https://(xyz.)localip/domain(.tld) the same if no forwarding in the server public static final Integer MAX_NUMBER_OF_RESULTS = 50; }
package uk.kainos.seleniumframework.properties; public class BrowserstackProperties { public static final String BROWSERSTACK_USERNAME = "browserstack.username"; public static final String BROWSERSTACK_ACCESS_KEY = "browserstack.access.key"; public static final String BROWSERSTACK_LOGGING = "browserstack.logging"; }
import java.util.*; public class SudokuContainer { private int solutionnumber = 0; private LinkedList<int[][]> sudokulist = new LinkedList<int[][]>(); private Iterator <int[][]> it = sudokulist.iterator(); public void addSolution(int[][] sol){ if(sol == null){ throw new NullPointerException(); } if(sudokulist.size() < 500){ sudokulist.add(sol); } solutionnumber ++; } public LinkedList<int[][]> getSolutions(){ return sudokulist; } public int[][] getNextSolution(){ int[][] tmp = null; if(it.hasNext()){ tmp = it.next(); return tmp; } else{ throw new NullPointerException(); } } public int getSolutionsNumber(){ return solutionnumber; } public boolean removeElement(int[][] sol){ if(sudokulist.contains(sol)){ sudokulist.remove(sol); } return false; } }
package demo.dubbo.provider; /** * Created by Bennett Dong <br> * Date : 2018/1/27 <br> * Mail: dongshujin.beans@gmail.com <br> <br> * Desc: */ public interface DemoService { void sayHi(); }
package com.example.hyunyoungpark.addressbookdemo.Data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; // this class creates and upgrade the database public class AddressBookDatabaseHelper extends SQLiteOpenHelper { // create a database name and version public static final String DatabaseName = "AddressBook"; public static final int DatabaseVersion = 1; //create a default constructor public AddressBookDatabaseHelper(Context context) { super(context,DatabaseName,null,DatabaseVersion); } @Override public void onCreate(SQLiteDatabase db) { // SQL query for creating the contact table // for primary key _id final String CREATE_CONTACTS_TABLE = "CREATE TABLE "+ DatabaseDescription.Contact.TABLE_NAME +" ( " + DatabaseDescription.Contact._ID + " integer primary key, " + DatabaseDescription.Contact.COLUMN_NAME +" TEXT, "+ DatabaseDescription.Contact.COLUMN_PHONE + " TEXT, "+ DatabaseDescription.Contact.COLUMN_EMAIL + " TEXT, "+ DatabaseDescription.Contact.COLUMN_STREET + " TEXT, "+ DatabaseDescription.Contact.COLUMN_CITY + " TEXT, "+ DatabaseDescription.Contact.COLUMN_STATE + " TEXT, "+ DatabaseDescription.Contact.COLUMN_ZIP + " TEXT);" ; db.execSQL(CREATE_CONTACTS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DatabaseDescription.Contact.TABLE_NAME); onCreate(db); } }
/** * */ package ua.epam.course.java.project01; import java.util.ArrayList; import ua.epam.course.java.project01.tools.TrackContainer; /** * Program view class * @author pipich3 * @version 1.0 * @since 09.11.2015 */ public class CDBurnerView { /** * string error messages */ private final String TOTAL_CD_LENGTH = "Total CD Length"; private final String INVALID_TIME_FORMAT = "invalid time format"; private final String UNKNOWN_COMMAND = "unknown command"; private final String MISSED_PARAMETER_OR_OPERATOR = "missed parameter or operator"; private final String UNKNOWN_ERROR = "unknown error"; /** * data columns width */ private final int[] BAND_FIELDS_WIDTH = new int[] {32,32,24,16,32}; private final int[] ALBUM_FIELDS_WIDTH = new int[] {32,32,20,16}; private final int[] TRACK_FIELDS_WIDTH = new int[] {32,16,32,32,8,8}; /** * singleton instance */ private static CDBurnerView singleton; /** * singleton constructor */ private CDBurnerView() { singleton = this; } /** * singleton initializer * @return instance of class */ public static CDBurnerView Initialize() { if (singleton == null) { new CDBurnerView(); } return singleton; } /** * prints String line on screen * @param line line to print */ public void printLine(String line) { System.out.println(line); } /** * message on unknown command input */ public void printUnknownCommandMessage() { printLine(UNKNOWN_COMMAND); } /** * missed parameter or operator */ public void printMissedCommandMessage() { printLine(MISSED_PARAMETER_OR_OPERATOR); } /** * unknown error message */ public void printUnknownErrorMessage() { printLine(UNKNOWN_ERROR); } /** * invalid time format message */ public void printUnknownTimeFromat() { printLine(INVALID_TIME_FORMAT); } /** * prints total length of CD * @param length CD length in seconds */ public void printCDLength(int length) { printLine(String.format(TOTAL_CD_LENGTH + ": %02d:%02d", length/60, length%60)); } /** * prints collection header and items line by line * @param container collection with items with overloaded toString() method */ public void printTrackContainerLevels (ArrayList<TrackContainer> container) { if (container.size() == 0) { printLine("no data"); return; } final int[] levelFieldWidth; int rowWidth; String levelClass = container.get(0).getClass().getSimpleName().toString(); String[] description = container.get(0).toStringDescription(); switch (levelClass) { case "Band": levelFieldWidth = BAND_FIELDS_WIDTH; break; case "Album": levelFieldWidth = ALBUM_FIELDS_WIDTH; break; case "Track": levelFieldWidth = TRACK_FIELDS_WIDTH; break; default: throw new IllegalArgumentException(); } rowWidth = calculateIntArraySum(levelFieldWidth) + levelFieldWidth.length + 4; printLine(fillLine("\u2500", rowWidth)); printLine(String.format("%-4s%-4s","#", StringArrayToString(description, levelFieldWidth))); printLine(fillLine("\u2500", rowWidth)); for (int i = 0; i < container.size(); i++) { printLine(String.format("%-4d%-4s", i + 1, StringArrayToString(container.get(i).toStringFields(), levelFieldWidth))); } printLine(fillLine("\u2500", rowWidth)); } /** * converts string array into pseudotable row * @param strings string array, pseudotable fields * @param lengths pseudotable columns width * @return line with pseudotable row */ private String StringArrayToString(String[] strings, int[] lengths) { String description = ""; for (int i = 0; i < lengths.length; i++) { description += String.format("\u2502%-" + lengths[i] + "s", strings[i]); } return description; } /** * constructs line, filled with symbols * @param filler symbols to fill line * @param count count of symbol groups * @return filled line */ private String fillLine(String filler, int count) { StringBuffer line = new StringBuffer(); for (int i = 0; i < count; i++) { line.append(filler); } return line.toString(); } /** * calculates sum of Integer array elements * @param array array to calculate sum * @return sum of array elements */ private int calculateIntArraySum(int[] array) { int sum = 0; for (int i : array) { sum += i; } return sum; } }
package com.github.emalock3.websocket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @EnableAutoConfiguration @ComponentScan @EnableWebSocket public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Configuration public static class MyWebSocketConfigurer implements WebSocketConfigurer { @Autowired private EchoWebSocketHandler handler; public void setEchoWebSocketHandler(EchoWebSocketHandler handler) { this.handler = handler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(handler, "/echo").withSockJS(); } } }
/* * Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com> * Copyright (C) 2016-2017 Joaquin Rodriguez Felici <joaquinfelici at gmail.com> * Copyright (C) 2016-2017 Leandro Asson <leoasson at gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.petrinator.editor; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Set; import org.petrinator.petrinet.Arc; import org.petrinator.petrinet.ArcEdge; import org.petrinator.petrinet.Element; import org.petrinator.petrinet.ElementCloner; import org.petrinator.petrinet.Marking; import org.petrinator.petrinet.Node; import org.petrinator.petrinet.PetriNet; import org.petrinator.petrinet.Place; import org.petrinator.petrinet.PlaceNode; import org.petrinator.petrinet.Subnet; import org.petrinator.petrinet.Transition; import org.petrinator.petrinet.TransitionNode; import org.petrinator.util.CollectionTools; /** * * @author Martin Riesz <riesz.martin at gmail.com> */ public class LocalClipboard { private Subnet subnet = new Subnet(); public LocalClipboard() { } public void setContents(Set<Element> elements, PetriNet petriNet) { subnet.removeElements(); elements = filterOutDisconnectedArcs(elements); elements = ElementCloner.getClones(elements, petriNet); subnet.addAll(elements); } public Set<Element> getContents(PetriNet petriNet) { return ElementCloner.getClones(subnet.getElements(), petriNet); } public boolean isEmpty() { return subnet.getElements().isEmpty(); } private static Set<Element> filterOutDisconnectedArcs(Set<Element> elements) { Set<Element> filteredElements = new HashSet<Element>(); Set<Node> nodes = getNodes(elements); for (Node node : nodes) { Set<ArcEdge> connectedArcEdges = node.getConnectedArcEdges(); for (ArcEdge connectedArcEdge : connectedArcEdges) { if (nodes.contains(connectedArcEdge.getPlaceNode()) && nodes.contains(connectedArcEdge.getTransitionNode())) { filteredElements.add(connectedArcEdge); } } } filteredElements.addAll(nodes); return filteredElements; } public static Set<Node> getNodes(Set<Element> elements) { Set<Node> nodes = new HashSet<Node>(); for (Element element : elements) { if (element instanceof Node) { nodes.add((Node) element); } } return nodes; } public Set<Node> getNodes() { Set<Node> nodes = new HashSet<Node>(); for (Element element : subnet.getElements()) { if (element instanceof Node) { nodes.add((Node) element); } } return nodes; } // private PetriNet clipboardNet = new PetriNet(); // // public void setContents(Set<Element> elements, PetriNet petriNet) { // clipboardNet.clear(); // Map<Element, Element> originalToCloneMap = makeOriginalToCloneMap(elements); // copyMarking(originalToCloneMap, petriNet.getInitialMarking(), clipboardNet.getInitialMarking()); // clipboardNet.getRootSubnet().addAll(new HashSet<Element>(originalToCloneMap.values())); // } // // public Set<Element> getContents(PetriNet petriNet) { // Map<Element, Element> originalToCloneMap = makeOriginalToCloneMap(clipboardNet.getRootSubnet().getElements()); // copyMarking(originalToCloneMap, clipboardNet.getInitialMarking(), petriNet.getInitialMarking()); // return new HashSet<Element>(originalToCloneMap.values()); // } // // public boolean isEmpty() { // return clipboardNet.getRootSubnet().getElements().isEmpty(); // } // // // ------------------------------------------------------------------------- // // private void copyMarking(Map<Element, Element> originalToCloneMap, Marking sourceMarking, Marking destinationMarking) { // for (Place place : CollectionTools.getFilteredByClass(originalToCloneMap.keySet(), Place.class)) { // int tokens = sourceMarking.getTokens(place); // destinationMarking.setTokens((Place)originalToCloneMap.get(place), tokens); // } // } // // private static Map<Element, Element> makeOriginalToCloneMap(Collection<Element> elements) { // Map<Element, Element> clones = new Hashtable<Element, Element>(); // Set<ArcEdge> connectedArcs = new HashSet<ArcEdge>(); // // for (Element element : elements) { // if (element instanceof Node) { // Node node = (Node)element; // clones.put(node, node.getClone()); // connectedArcs.addAll(node.getConnectedArcEdges()); // } // } // // for (ArcEdge arcEdge : connectedArcs) { // if (elements.contains(arcEdge.getPlaceNode()) || elements.contains(arcEdge.getTransitionNode())) { // ArcEdge clonedArc = arcEdge.getClone(); // // if (elements.contains(arcEdge.getPlaceNode())) { // clonedArc.setPlaceNode((PlaceNode)clones.get(arcEdge.getPlaceNode())); // } // if (elements.contains(arcEdge.getTransitionNode())) { // clonedArc.setTransitionNode((TransitionNode)clones.get(arcEdge.getTransitionNode())); // } // clones.put(arcEdge, clonedArc); // } // } // return clones; // } }
package kr.or.ddit.profile_file.service; import java.util.List; import java.util.Map; import kr.or.ddit.vo.ProfileFileVO; public interface IProfileFileService { public ProfileFileVO selectProfileFileInfo(Map<String, String> params) throws Exception; public void insertProfileFileInfo(ProfileFileVO profileInfo) throws Exception; public void insertMypageFileInfo(List<ProfileFileVO> fileitemList) throws Exception; }
package service; import javax.crypto.spec.SecretKeySpec; import java.security.Key; import java.util.Base64; import java.util.Date; import java.util.Map; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.SignatureAlgorithm; public class JWT { private static String SECRET_KEY = System.getenv("JWT_KEY"); public static String createJWT(String issuer, Map<String,Object> claims, long ttlSeconds) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); byte[] apiKeySecretBytes = Base64.getEncoder().encode(SECRET_KEY.getBytes()); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setIssuedAt(now) .setIssuer(issuer) .addClaims(claims) .signWith(signatureAlgorithm, signingKey); if (ttlSeconds >= 0) { long expMillis = nowMillis + (ttlSeconds * 1000); Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } }
package gr.uoa.di.dbm.webapp.controller; import gr.uoa.di.dbm.webapp.entity.AppUser; import gr.uoa.di.dbm.webapp.entity.AuditLog; import gr.uoa.di.dbm.webapp.service.ServiceRequestServiceImpl; import gr.uoa.di.dbm.webapp.service.UserDetailsServiceImpl; import gr.uoa.di.dbm.webapp.utils.WebUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.security.Principal; import java.util.ArrayList; import java.util.List; @Controller public class MainController { private final UserDetailsServiceImpl userDetailsService; private final ServiceRequestServiceImpl serviceRequestService; private static final String ADMIN = "admin"; private static final String ERROR403 = "error403"; private static final String LOGIN = "login"; private static final String MESSAGE = "message"; private static final String REGISTER = "register"; private static final String TITLE = "title"; private static final String USER_INFO = "userInfo"; private static final String WELCOME = "welcome"; private static final String APP_USER = "appUser"; @Autowired public MainController(UserDetailsServiceImpl userDetailsService, ServiceRequestServiceImpl serviceRequestService) { this.userDetailsService = userDetailsService; this.serviceRequestService = serviceRequestService; } @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET) public String welcomePage(Model model) { model.addAttribute(TITLE, "Home"); return WELCOME; } @RequestMapping(value = "/admin", method = RequestMethod.GET) public String adminPage(Model model) { List<AuditLog> L = new ArrayList<AuditLog>(); L = serviceRequestService.findLogAll(); model.addAttribute("allLogsList",L); model.addAttribute(TITLE, "Admin Page"); return ADMIN; } @RequestMapping(value = "/userAudit", method = RequestMethod.GET) public String userPage(Model model, Principal principal) { User loggedinUser = (User) ((Authentication) principal).getPrincipal(); String username = loggedinUser.getUsername(); List<AuditLog> L; L = serviceRequestService.findLogByUsername(username); model.addAttribute("logsList",L); model.addAttribute(TITLE, "User Page"); return "userAudit"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String loginPage(Model model) { return LOGIN; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String registerPage(Model model) { AppUser appUser = new AppUser(); model.addAttribute(APP_USER, appUser); return REGISTER; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public String registrationPage(@ModelAttribute AppUser appUser) { return userDetailsService.checkIfUserExists(appUser.getUserName()) ? REGISTER : userDetailsService.registerUser(appUser) != null ? LOGIN : REGISTER; } @RequestMapping(value = "/error403", method = RequestMethod.GET) public String accessDenied(Model model, Principal principal) { if (principal != null) { User loggedinUser = (User) ((Authentication) principal).getPrincipal(); String userInfo = WebUtils.toString(loggedinUser); model.addAttribute(USER_INFO, userInfo); String message = "Hi " + principal.getName() // + "<br> You do not have permission to access this page!"; model.addAttribute(MESSAGE, message); } return ERROR403; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.web.servlet.view; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.http.MediaType; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.support.WebApplicationObjectSupport; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.SmartView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; /** * Implementation of {@link ViewResolver} that resolves a view based on the request file name * or {@code Accept} header. * * <p>The {@code ContentNegotiatingViewResolver} does not resolve views itself, but delegates to * other {@link ViewResolver ViewResolvers}. By default, these other view resolvers are picked up automatically * from the application context, though they can also be set explicitly by using the * {@link #setViewResolvers viewResolvers} property. <strong>Note</strong> that in order for this * view resolver to work properly, the {@link #setOrder order} property needs to be set to a higher * precedence than the others (the default is {@link Ordered#HIGHEST_PRECEDENCE}). * * <p>This view resolver uses the requested {@linkplain MediaType media type} to select a suitable * {@link View} for a request. The requested media type is determined through the configured * {@link ContentNegotiationManager}. Once the requested media type has been determined, this resolver * queries each delegate view resolver for a {@link View} and determines if the requested media type * is {@linkplain MediaType#includes(MediaType) compatible} with the view's * {@linkplain View#getContentType() content type}). The most compatible view is returned. * * <p>Additionally, this view resolver exposes the {@link #setDefaultViews(List) defaultViews} property, * allowing you to override the views provided by the view resolvers. Note that these default views are * offered as candidates, and still need have the content type requested (via file extension, parameter, * or {@code Accept} header, described above). * * <p>For example, if the request path is {@code /view.html}, this view resolver will look for a view * that has the {@code text/html} content type (based on the {@code html} file extension). A request * for {@code /view} with a {@code text/html} request {@code Accept} header has the same result. * * @author Arjen Poutsma * @author Juergen Hoeller * @author Rossen Stoyanchev * @since 3.0 * @see ViewResolver * @see InternalResourceViewResolver * @see BeanNameViewResolver */ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered, InitializingBean { @Nullable private ContentNegotiationManager contentNegotiationManager; private final ContentNegotiationManagerFactoryBean cnmFactoryBean = new ContentNegotiationManagerFactoryBean(); private boolean useNotAcceptableStatusCode = false; @Nullable private List<View> defaultViews; @Nullable private List<ViewResolver> viewResolvers; private int order = Ordered.HIGHEST_PRECEDENCE; /** * Set the {@link ContentNegotiationManager} to use to determine requested media types. * <p>If not set, ContentNegotiationManager's default constructor will be used, * applying a {@link org.springframework.web.accept.HeaderContentNegotiationStrategy}. * @see ContentNegotiationManager#ContentNegotiationManager() */ public void setContentNegotiationManager(@Nullable ContentNegotiationManager contentNegotiationManager) { this.contentNegotiationManager = contentNegotiationManager; } /** * Return the {@link ContentNegotiationManager} to use to determine requested media types. * @since 4.1.9 */ @Nullable public ContentNegotiationManager getContentNegotiationManager() { return this.contentNegotiationManager; } /** * Indicate whether a {@link HttpServletResponse#SC_NOT_ACCEPTABLE 406 Not Acceptable} * status code should be returned if no suitable view can be found. * <p>Default is {@code false}, meaning that this view resolver returns {@code null} for * {@link #resolveViewName(String, Locale)} when an acceptable view cannot be found. * This will allow for view resolvers chaining. When this property is set to {@code true}, * {@link #resolveViewName(String, Locale)} will respond with a view that sets the * response status to {@code 406 Not Acceptable} instead. */ public void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode) { this.useNotAcceptableStatusCode = useNotAcceptableStatusCode; } /** * Whether to return HTTP Status 406 if no suitable is found. */ public boolean isUseNotAcceptableStatusCode() { return this.useNotAcceptableStatusCode; } /** * Set the default views to use when a more specific view can not be obtained * from the {@link ViewResolver} chain. */ public void setDefaultViews(List<View> defaultViews) { this.defaultViews = defaultViews; } public List<View> getDefaultViews() { return (this.defaultViews != null ? Collections.unmodifiableList(this.defaultViews) : Collections.emptyList()); } /** * Sets the view resolvers to be wrapped by this view resolver. * <p>If this property is not set, view resolvers will be detected automatically. */ public void setViewResolvers(List<ViewResolver> viewResolvers) { this.viewResolvers = viewResolvers; } public List<ViewResolver> getViewResolvers() { return (this.viewResolvers != null ? Collections.unmodifiableList(this.viewResolvers) : Collections.emptyList()); } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override protected void initServletContext(ServletContext servletContext) { Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values(); if (this.viewResolvers == null) { this.viewResolvers = new ArrayList<>(matchingBeans.size()); for (ViewResolver viewResolver : matchingBeans) { if (this != viewResolver) { this.viewResolvers.add(viewResolver); } } } else { for (int i = 0; i < this.viewResolvers.size(); i++) { ViewResolver vr = this.viewResolvers.get(i); if (matchingBeans.contains(vr)) { continue; } String name = vr.getClass().getName() + i; obtainApplicationContext().getAutowireCapableBeanFactory().initializeBean(vr, name); } } AnnotationAwareOrderComparator.sort(this.viewResolvers); this.cnmFactoryBean.setServletContext(servletContext); } @Override public void afterPropertiesSet() { if (this.contentNegotiationManager == null) { this.contentNegotiationManager = this.cnmFactoryBean.build(); } if (this.viewResolvers == null || this.viewResolvers.isEmpty()) { logger.warn("No ViewResolvers configured"); } } @Override @Nullable public View resolveViewName(String viewName, Locale locale) throws Exception { RequestAttributes attrs = RequestContextHolder.getRequestAttributes(); Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes"); List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest()); if (requestedMediaTypes != null) { List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes); View bestView = getBestView(candidateViews, requestedMediaTypes, attrs); if (bestView != null) { return bestView; } } String mediaTypeInfo = (logger.isDebugEnabled() && requestedMediaTypes != null ? " given " + requestedMediaTypes.toString() : ""); if (this.useNotAcceptableStatusCode) { if (logger.isDebugEnabled()) { logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo); } return NOT_ACCEPTABLE_VIEW; } else { logger.debug("View remains unresolved" + mediaTypeInfo); return null; } } /** * Determines the list of {@link MediaType} for the given {@link HttpServletRequest}. * @param request the current servlet request * @return the list of media types requested, if any */ @Nullable protected List<MediaType> getMediaTypes(HttpServletRequest request) { Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set"); try { ServletWebRequest webRequest = new ServletWebRequest(request); List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest); List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request); Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>(); for (MediaType acceptable : acceptableMediaTypes) { for (MediaType producible : producibleMediaTypes) { if (acceptable.isCompatibleWith(producible)) { compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible)); } } } List<MediaType> selectedMediaTypes = new ArrayList<>(compatibleMediaTypes); MimeTypeUtils.sortBySpecificity(selectedMediaTypes); return selectedMediaTypes; } catch (HttpMediaTypeNotAcceptableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage()); } return null; } } @SuppressWarnings("unchecked") private List<MediaType> getProducibleMediaTypes(HttpServletRequest request) { Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); if (!CollectionUtils.isEmpty(mediaTypes)) { return new ArrayList<>(mediaTypes); } else { return Collections.singletonList(MediaType.ALL); } } /** * Return the more specific of the acceptable and the producible media types * with the q-value of the former. */ private MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produceType) { produceType = produceType.copyQualityValue(acceptType); if (acceptType.isLessSpecific(produceType)) { return produceType; } else { return acceptType; } } private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes) throws Exception { List<View> candidateViews = new ArrayList<>(); if (this.viewResolvers != null) { Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set"); for (ViewResolver viewResolver : this.viewResolvers) { View view = viewResolver.resolveViewName(viewName, locale); if (view != null) { candidateViews.add(view); } for (MediaType requestedMediaType : requestedMediaTypes) { List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType); for (String extension : extensions) { String viewNameWithExtension = viewName + '.' + extension; view = viewResolver.resolveViewName(viewNameWithExtension, locale); if (view != null) { candidateViews.add(view); } } } } } if (!CollectionUtils.isEmpty(this.defaultViews)) { candidateViews.addAll(this.defaultViews); } return candidateViews; } @Nullable private View getBestView(List<View> candidateViews, List<MediaType> requestedMediaTypes, RequestAttributes attrs) { for (View candidateView : candidateViews) { if (candidateView instanceof SmartView smartView) { if (smartView.isRedirectView()) { return candidateView; } } } for (MediaType mediaType : requestedMediaTypes) { for (View candidateView : candidateViews) { if (StringUtils.hasText(candidateView.getContentType())) { MediaType candidateContentType = MediaType.parseMediaType(candidateView.getContentType()); if (mediaType.isCompatibleWith(candidateContentType)) { mediaType = mediaType.removeQualityValue(); if (logger.isDebugEnabled()) { logger.debug("Selected '" + mediaType + "' given " + requestedMediaTypes); } attrs.setAttribute(View.SELECTED_CONTENT_TYPE, mediaType, RequestAttributes.SCOPE_REQUEST); return candidateView; } } } } return null; } private static final View NOT_ACCEPTABLE_VIEW = new View() { @Override @Nullable public String getContentType() { return null; } @Override public void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); } }; }
package PACKAGE_NAME; public class IllegalAgeException { }
package com.esum.comp.socket.packet; import com.esum.comp.socket.SocketException; /** * 송수신한 Packet을 읽어서 <code>ReaderableMessage</code> 객체를 생성한다. * * 다양한 포맷의 Packet를 수신할 수 있으며, 수신한 메시지의 규격에 의해 파싱하고, 그 결과로 ReaderableMessage를 생성한다. */ public interface PacketReader { public ReaderableMessage readPacket(byte[] packet) throws SocketException; }
package main.employees; public class Contractor extends Employee { public Contractor(String firstName, String lastName, int fixedPay) { super(firstName, lastName, fixedPay); } @Override public void applyForLeave(int days) throws UnsupportedOperationException { throw new UnsupportedOperationException("Contract employees cannot apply leave"); } }
package lab6; import java.util.Scanner; public class SV { String hoten; double tb; public String name; public String getHoten() { return hoten; } public void setHoten(String hoten) { this.hoten = hoten; } public double getTb() { return tb; } public void setTb(double tb) { this.tb = tb; } public void nhap() { Scanner scanner = new Scanner(System.in); System.out.print("Nhap ten sinh vien: "); this.hoten = scanner.nextLine(); System.out.print("Nhap diem sinh vien: "); this.tb = Double.parseDouble(scanner.nextLine()); } public void xuat() { System.out.println("Ho ten:" +this.hoten); System.out.println("Diem trung binh:" +this.tb); System.out.println("............"); } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.transaction.aspectj; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.testfixture.CallCountingTransactionManager; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatException; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatRuntimeException; /** * @author Rod Johnson * @author Ramnivas Laddad * @author Juergen Hoeller * @author Sam Brannen */ public class TransactionAspectTests { private final CallCountingTransactionManager txManager = new CallCountingTransactionManager(); private final TransactionalAnnotationOnlyOnClassWithNoInterface annotationOnlyOnClassWithNoInterface = new TransactionalAnnotationOnlyOnClassWithNoInterface(); private final ClassWithProtectedAnnotatedMember beanWithAnnotatedProtectedMethod = new ClassWithProtectedAnnotatedMember(); private final ClassWithPrivateAnnotatedMember beanWithAnnotatedPrivateMethod = new ClassWithPrivateAnnotatedMember(); private final MethodAnnotationOnClassWithNoInterface methodAnnotationOnly = new MethodAnnotationOnClassWithNoInterface(); @BeforeEach public void initContext() { AnnotationTransactionAspect.aspectOf().setTransactionManager(txManager); } @Test public void testCommitOnAnnotatedClass() throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); annotationOnlyOnClassWithNoInterface.echo(null); assertThat(txManager.commits).isEqualTo(1); } @Test public void commitOnAnnotatedProtectedMethod() throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); beanWithAnnotatedProtectedMethod.doInTransaction(); assertThat(txManager.commits).isEqualTo(1); } @Test public void commitOnAnnotatedPrivateMethod() throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); beanWithAnnotatedPrivateMethod.doSomething(); assertThat(txManager.commits).isEqualTo(1); } @Test public void commitOnNonAnnotatedNonPublicMethodInTransactionalType() throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); annotationOnlyOnClassWithNoInterface.nonTransactionalMethod(); assertThat(txManager.begun).isEqualTo(0); } @Test public void commitOnAnnotatedMethod() throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); methodAnnotationOnly.echo(null); assertThat(txManager.commits).isEqualTo(1); } @Test public void notTransactional() throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); new NotTransactional().noop(); assertThat(txManager.begun).isEqualTo(0); } @Test public void defaultCommitOnAnnotatedClass() throws Throwable { Exception ex = new Exception(); assertThatException() .isThrownBy(() -> testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false)) .isSameAs(ex); } @Test public void defaultRollbackOnAnnotatedClass() throws Throwable { RuntimeException ex = new RuntimeException(); assertThatRuntimeException() .isThrownBy(() -> testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true)) .isSameAs(ex); } @Test public void defaultCommitOnSubclassOfAnnotatedClass() throws Throwable { Exception ex = new Exception(); assertThatException() .isThrownBy(() -> testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false)) .isSameAs(ex); } @Test public void defaultCommitOnSubclassOfClassWithTransactionalMethodAnnotated() throws Throwable { Exception ex = new Exception(); assertThatException() .isThrownBy(() -> testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false)) .isSameAs(ex); } @Test public void noCommitOnImplementationOfAnnotatedInterface() throws Throwable { Exception ex = new Exception(); testNotTransactional(() -> new ImplementsAnnotatedInterface().echo(ex), ex); } @Test public void noRollbackOnImplementationOfAnnotatedInterface() throws Throwable { Exception rollbackProvokingException = new RuntimeException(); testNotTransactional(() -> new ImplementsAnnotatedInterface().echo(rollbackProvokingException), rollbackProvokingException); } protected void testRollback(TransactionOperationCallback toc, boolean rollback) throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); try { toc.performTransactionalOperation(); } finally { assertThat(txManager.begun).isEqualTo(1); long expected1 = (rollback ? 0 : 1); assertThat(txManager.commits).isEqualTo(expected1); long expected = (rollback ? 1 : 0); assertThat(txManager.rollbacks).isEqualTo(expected); } } protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable { txManager.clear(); assertThat(txManager.begun).isEqualTo(0); assertThatExceptionOfType(Throwable.class) .isThrownBy(toc::performTransactionalOperation) .isSameAs(expected); assertThat(txManager.begun).isEqualTo(0); } private interface TransactionOperationCallback { Object performTransactionalOperation() throws Throwable; } public static class SubclassOfClassWithTransactionalAnnotation extends TransactionalAnnotationOnlyOnClassWithNoInterface { } public static class SubclassOfClassWithTransactionalMethodAnnotation extends MethodAnnotationOnClassWithNoInterface { } public static class ImplementsAnnotatedInterface implements ITransactional { @Override public Object echo(Throwable t) throws Throwable { if (t != null) { throw t; } return t; } } public static class NotTransactional { public void noop() { } } }
package trabalhotheobaldo; public class Main { public static void main(String[] args) { CadastroCliente c =new CadastroCliente(); c.setVisible(true); } }
package com.lidaye.shopIndex.service; import com.lidaye.shopIndex.domain.vo.CategoryVo; import com.lidaye.shopIndex.domain.vo.ShopVo; import com.lidaye.shopIndex.utils.IndexHeadRes; import java.util.List; public interface ListService { List<ShopVo> getShopFoCate(int cid); List<ShopVo> getShopToSearch(String name,Integer type); }
package br.com.leandrocolevati.bancodedados; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class Crud { private boolean verificaTabela(Connection c, Object model) throws SQLException { boolean ver = false; String sql = "SELECT COUNT(*) FROM " + model.getClass().getSimpleName(); try { PreparedStatement ps = c.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { ver = true; } rs.close(); ps.close(); } catch (SQLException e) { throw new SQLException("Objeto e tabela devem ter o mesmo nome"); } return ver; } private int contaAtributos(Connection c, Object model) throws SQLException { String conta = "select count(syscolumns.name) as tamanho from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.xtype = 'u' and sysobjects.name = ?"; int numColunas = 0; PreparedStatement psConta = c.prepareStatement(conta); psConta.setString(1, model.getClass().getSimpleName()); ResultSet rsConta = psConta.executeQuery(); if (rsConta.next()) { numColunas = rsConta.getInt("tamanho"); } rsConta.close(); psConta.close(); return numColunas; } private boolean verificaColunas(Connection c, Object model) throws SecurityException, SQLException { boolean ver = false; if (verificaTabela(c, model)) { List<String> listaAtributos = new ArrayList<String>(); for (Method m : model.getClass().getMethods()) { if (m.getName().contains("set")) { listaAtributos.add(m.getName().substring(3, m.getName().length())); } } String sql = "select syscolumns.name as coluna from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.xtype = 'u' and sysobjects.name = ? order by syscolumns.name"; try { PreparedStatement ps = c.prepareStatement(sql); ps.setString(1, model.getClass().getSimpleName()); ResultSet rs = ps.executeQuery(); if (contaAtributos(c, model) != listaAtributos.size()) { throw new SQLException( "Definições do objeto diferentes da tabela"); } else { int contadorIguais = 0; while (rs.next()) { for (String s : listaAtributos) { if (rs.getString("coluna").toLowerCase() .equals(s.toLowerCase())) { contadorIguais++; break; } } } if (contadorIguais == listaAtributos.size()) { ver = true; } } rs.close(); ps.close(); } catch (SQLException e) { throw new SQLException( "Definições de Objeto e tabela incompatíveis"); } } return ver; } private List<String> colunas(Connection c, Object model) throws SecurityException, SQLException { List<String> listaAtributos = new ArrayList<String>(); if (verificaColunas(c, model)) { for (Method m : model.getClass().getMethods()) { if (m.getName().contains("set")) { listaAtributos.add(m.getName().substring(3, m.getName().length())); } } } return listaAtributos; } private List<Method> getGetters(Object model) { List<Method> listaGetters = new ArrayList<Method>(); for (Method m : model.getClass().getMethods()) { if (m.getName().contains("get") && !m.getName().contains("Class")) { listaGetters.add(m); } } return listaGetters; } private int codigoStatement(String[] atributos, Method m) { int posicao = 0; for (int i = 0; i < atributos.length; i++) { if (atributos[i].toLowerCase().equals( m.getName().toLowerCase() .substring(3, m.getName().toLowerCase().length()))) { posicao = i + 1; break; } } return posicao; } /** * Insere o conteúdo dos getters no Objeto model, na tabela de mesmo nome no * SGBD definido no Connection c (Só funcionando com SQL SERVER) * * @param c * - Conexão com o SGBD * @param model * - Objeto com os dados (Seu nome deve ser igual ao da tabela, * bem como seus atributos) * @return * - TRUE (registro inserido) * - FALSE (nenhum registro inserido) * @throws SecurityException * @throws SQLException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ @SuppressWarnings("unused") public boolean insert(Connection c, Object model) throws SecurityException, SQLException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { boolean inserido = false; if (verificaColunas(c, model)) { List<String> lista = colunas(c, model); if (lista != null) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO "); sql.append(model.getClass().getSimpleName()); sql.append(" ("); int cont = 0; for (String s : lista) { sql.append(s); cont++; if (cont < lista.size()) { sql.append(","); } } sql.append(") VALUES ("); cont = 0; for (String s : lista) { sql.append("?"); cont++; if (cont < lista.size()) { sql.append(","); } } sql.append(")"); PreparedStatement ps = c.prepareStatement(sql.toString()); String[] atributos = lista.toArray(new String[0]); for (Method m : getGetters(model)) { int posicao = codigoStatement(atributos, m); if (posicao != 0){ Object valor = m.invoke(model); ps.setObject(posicao, valor); } } ps.execute(); ps.close(); inserido = true; } else { throw new SQLException("Erro na Definição da Tabela"); } } return inserido; } /** * Deleta linha que atende a todas as condições citadas no List<String> where (Só funcionando com SQL SERVER) * @param c * - Conexão com o SGBD * @param model * - Objeto com os dados (Seu nome deve ser igual ao da tabela, * bem como seus atributos) * @param where * - List<String> com os atributos que tem dados que são utilizados * na cláusula Where da query DELETE * *Só será excluída a linha que atenda a todas as condições. * @return * - TRUE (registro(s) excluídos(s)) * - FALSE (nenhum registro(s) excluídos(s)) * @throws SQLException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ public boolean delete(Connection c, Object model, List<String> where) throws SQLException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { boolean deletado = false; if (verificaColunas(c, model)) { List<String> lista = colunas(c, model); if (lista != null) { StringBuffer sql = new StringBuffer(); sql.append("DELETE "); sql.append(model.getClass().getSimpleName()); sql.append(" WHERE "); int cont = 0; for (String s : where) { sql.append(s + " = ?"); if (cont < where.size() - 1){ sql.append(" AND "); } cont++; } PreparedStatement ps = c.prepareStatement(sql.toString()); String[] atributos = where.toArray(new String[0]); for (Method m : getGetters(model)) { int posicao = codigoStatement(atributos, m); if (posicao != 0){ Object valor = m.invoke(model); ps.setObject(posicao, valor); } } ps.execute(); ps.close(); deletado = true; } else { throw new SQLException("Erro na Definição da Tabela"); } } return deletado; } }
/* * 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 com.victuxbb.javatest.security.service; import com.victuxbb.javatest.model.role.RoleEnum; import com.victuxbb.javatest.model.user.User; import com.victuxbb.javatest.security.token.UserToken; import com.victuxbb.javatest.security.token.UserTokenNotFoundException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author victux */ public class AuthorizationService { private static AuthorizationService instance; public boolean isAuthorized(String uri,UserToken userToken) { String pattern = "(pag_[0-9]).jsp*"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(uri); String page = ""; if (m.find()) { page = m.group(1); } boolean authorized = false; User user = userToken.getUser(); for (RoleEnum role : user.getRoles()) { if( role.name().toLowerCase().equals(page) ) { authorized = true; } } return authorized; } public static AuthorizationService getInstance() { if(null == instance){ instance = new AuthorizationService(); } return instance; } }
package ru.sgu.csit.csc.graphs.labeled; import ru.sgu.csit.csc.graphs.Graph; public interface EdgeLabeledGraph<L> extends Graph { boolean addEdge(int from, int to, L label); Iterable<Edge<L>> getNeighborEdges(int vertex); public static class Edge<L> { private final int to; private final L label; public int getTo() { return to; } public L getLabel() { return label; } public Edge(int to, L label) { this.to = to; this.label = label; } } }
package patterns.structure.flyweight; /** * 享元模式(共享对象模式):运用共享技术有效地支持大量细粒度的对象 */ public class Client { public static void main(String[] args) { FlyweightFactory flyweightFactory = new FlyweightFactory(); Flyweght flyweght1 =flyweightFactory.getFlyweight("aa"); Flyweght flyweght2 = flyweightFactory.getFlyweight("aa"); flyweght1.doOperation("x"); flyweght2.doOperation("y"); } }
package com.metoo.module.app.view.web.action; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpException; import org.junit.Test; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.annotation.EmailMapping; import com.metoo.core.domain.virtual.SysMap; import com.metoo.core.mv.JModelAndView; import com.metoo.core.query.support.IPageList; import com.metoo.core.tools.CommUtil; import com.metoo.core.tools.Md5Encrypt; import com.metoo.core.tools.ResponseUtils; import com.metoo.core.tools.database.DatabaseTools; import com.metoo.foundation.domain.Address; import com.metoo.foundation.domain.Album; import com.metoo.foundation.domain.Area; import com.metoo.foundation.domain.Coupon; import com.metoo.foundation.domain.CouponInfo; import com.metoo.foundation.domain.Document; import com.metoo.foundation.domain.GameLog; import com.metoo.foundation.domain.GameTask; import com.metoo.foundation.domain.GoodsVoucher; import com.metoo.foundation.domain.GoodsVoucherInfo; import com.metoo.foundation.domain.IntegralLog; import com.metoo.foundation.domain.Role; import com.metoo.foundation.domain.User; import com.metoo.foundation.domain.query.AddressQueryObject; import com.metoo.foundation.service.IAddressService; import com.metoo.foundation.service.IAlbumService; import com.metoo.foundation.service.IAppGameLogService; import com.metoo.foundation.service.IAreaService; import com.metoo.foundation.service.ICouponInfoService; import com.metoo.foundation.service.ICouponService; import com.metoo.foundation.service.IDocumentService; import com.metoo.foundation.service.IGameTaskService; import com.metoo.foundation.service.IGoodsVoucherInfoService; import com.metoo.foundation.service.IGoodsVoucherService; import com.metoo.foundation.service.IIntegralLogService; import com.metoo.foundation.service.IRoleService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.IUserConfigService; import com.metoo.foundation.service.IUserService; import com.metoo.modul.app.game.tree.tools.AppFriendBuyerTools; import com.metoo.modul.app.game.tree.tools.AppGameAwardTools; import com.metoo.module.app.buyer.domain.Result; import com.metoo.module.app.view.tools.AppGoodsVoucherTools; import com.metoo.module.app.view.web.tool.AppobileTools; import com.metoo.msg.MsgTools; @Controller @RequestMapping("/app/") public class AppRegisterViewAction { @Autowired private IUserService userService; @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IRoleService roleService; @Autowired private IIntegralLogService integralLogService; @Autowired private IAlbumService albumService; @Autowired private IDocumentService documentService; @Autowired private IAreaService areaService; @Autowired private ICouponService couponService; @Autowired private ICouponInfoService couponInfoService; @Autowired private AppobileTools mobileTools; @Autowired private DatabaseTools databaseTools; @Autowired private IAddressService addressService; @Autowired private MsgTools msgTools; @Autowired private IGameTaskService gameTaskService; @Autowired private AppGameAwardTools appGameAwardTools; @Autowired private IAppGameLogService appGameLogService; @Autowired private AppFriendBuyerTools appFriendBuyerTools; @Autowired private AppGoodsVoucherTools appGoodsVoucherTools; @Autowired private IGoodsVoucherService goodsVoucherService; @Autowired private IGoodsVoucherInfoService goodsVoucherInfoService; private static final String REGEX1 = "(.*管理员.*)"; private static final String REGEX2 = "(.*admin.*)"; @RequestMapping("v1/register.json") public void register_json(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> registermap = new HashMap<String, Object>(); request.getSession(false).removeAttribute("verify_code"); Document doc = this.documentService.getObjByProperty(null, "mark", "reg_agree"); registermap.put("dos_content", doc.getContent()); registermap.put("dos_id", doc.getId()); Result result = new Result(4200, "success", registermap); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); try { response.getWriter().print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @RequestMapping("v1/verify_username.json") public void verify_username(HttpServletRequest request, HttpServletResponse response, String userName, String id) { int code = 4200; String message = "Success"; Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", userName.replace(" ", "")); params.put("id", CommUtil.null2Long(id)); List<User> users = this.userService.query( "select obj.id from User obj where (obj.userName=:userName or obj.mobile=:userName or obj.email=:userName) and obj.id!=:id", params, -1, -1); if (users.size() > 0) { code = 4225; message = "The user already exists"; } Result result = new Result(code, message); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 验证Email * * @param request * @param response * @param userName */ @RequestMapping("v1/verify_email.json") public void verify_email(HttpServletRequest request, HttpServletResponse response, String email, String id) { int ret = -1; String msg = ""; if (!CommUtil.null2String(email).equals("")) { Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); Matcher matcher = pattern.matcher(CommUtil.null2String(email)); if (matcher.matches()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("email", email); params.put("id", CommUtil.null2Long(id)); List<User> users = this.userService .query("select obj.id from User obj where obj.email=:email and obj.id!=:id", params, -1, -1); if (users.size() == 0) { ret = 4200; msg = "Success"; } } else { ret = 4400; msg = "Email format error"; } } Result result = new Result(ret, msg); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @description 自动注册验证用户邮箱是否被占用 * @param request * @param response * @param email * @param id */ @RequestMapping("v2/verify_email.json") public void verify_email2(HttpServletRequest request, HttpServletResponse response, String email, String mobile, String id) { int code = -1; String msg = ""; if (!CommUtil.null2String(email).equals("")) { Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); Matcher matcher = pattern.matcher(CommUtil.null2String(email)); Map map = this.mobileTools.mobile(mobile); if (matcher.matches()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("email", email); params.put("id", CommUtil.null2Long(id)); List<User> users = this.userService .query("select obj from User obj where obj.email=:email and obj.id!=:id", params, -1, -1); if (users.size() > 0) { boolean flag = false; for (User user : users) { if (map.get("areaMobile").toString().equals(user.getTelephone())) { flag = true; break; } } if (flag) { code = 4200; msg = "Success"; } else { code = 4300; msg = "The mailbox is already in use"; } } else { code = 4200; msg = "Success"; } } else { code = 4400; msg = "Email format error"; } } else { code = 4403; msg = "The mailbox is empty"; } Result result = new Result(code, msg); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @RequestMapping("v3/verify_email.json") public void verify_email3(HttpServletRequest request, HttpServletResponse response, String email, String token, String password) { int code = 4200; String msg = "Success"; User user = null; if (token != null && !token.equals("")) { user = this.userService.getObjByProperty(null, "app_login_token", token); } if (user != null) { if (!CommUtil.null2String(email).equals("") && !CommUtil.null2String(password).equals("")) { Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); Matcher matcher = pattern.matcher(CommUtil.null2String(email)); if (matcher.matches()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("email", email); List<User> users = this.userService.query("select obj from User obj where obj.email=:email", params, -1, -1); if (users.size() > 0) { if (!users.get(0).getId().equals(user.getId())) { code = 4300; msg = "The mailbox is already in use"; } else { // 验证用户密码 password = Md5Encrypt.md5(password).toLowerCase(); if (!user.getPassword().equals(password)) { code = 4400; msg = "Password error"; } } } } else { code = 4400; msg = "Email format error"; } } else { code = 4400; msg = "Password error"; } } else { code = -100; msg = "Log in"; } Result result = new Result(code, msg); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(result, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 验证Mobile * * @param request * @param response * @param userName */ @RequestMapping("v1/verify_mobile.json") public void verify_mobile(HttpServletRequest request, HttpServletResponse response, String mobile, String id) { int code = -1; String msg = ""; boolean flag = this.mobileTools.verify(mobile); Map map = this.mobileTools.mobile(mobile); String areaMobile = (String) map.get("areaMobile"); String userMobile = (String) map.get("userMobile"); if (flag) { Map<String, Object> params = new HashMap<String, Object>(); params.put("mobile", userMobile); params.put("userName", areaMobile); params.put("id", CommUtil.null2Long(id)); List<User> users = this.userService.query( "select obj.id from User obj where obj.mobile=:mobile or obj.userName=:userName and obj.id!=:id", params, -1, -1); if (users.size() > 0) { code = 4300; msg = "The current account is registered"; } else { code = 4200; msg = "Success"; } } else { code = 4400; msg = "Format error"; } this.send_json(Json.toJson(new Result(code, msg), JsonFormat.compact()), response); } /** * @param request * @param response * @param userName * @param password * @param email * @param mobile * @param code * @param user_type * @throws HttpException * @throws IOException * @throws InterruptedException * @throws SQLException * @description 1,用户手动注册 2,赠送抽奖次数 */ @EmailMapping(title = "手动注册", value = "register_finish") @RequestMapping("v1/register_finish.json") public void register_finish_json(HttpServletRequest request, HttpServletResponse response, String userName, String password, String email, String mobile, String code, String user_type, String invitation, @RequestParam(value = "imei", required = true) String imei, String uid) throws HttpException, InterruptedException { Result result = null; Map<String, Object> registerMap = new HashMap<String, Object>(); List<User> invi = new ArrayList<User>(); boolean flag = true; boolean register = false; // 使用邀请码时检测设备,一台设备只允许使用一次邀请码 if (invitation != null && !invitation.equals("")) { Map<String, Object> params = new HashMap<String, Object>(); params.put("code", invitation); invi = this.userService.query("select obj from User obj where obj.code=:code", params, -1, -1); if (invi.size() < 0) { result = new Result(4205, "邀请码错误"); } else { // 手机IMEI码 /*if (!imei.equals("")) { User imeiUser = this.userService.getObjByProperty(null, "imei", imei); if (imeiUser != null) { result = new Result(4215, "邀请码在同一台设备"); } else { flag = true; } }*/ } } else { register = true; } if (flag || register) { try { boolean reg = true; // 防止机器注册,如后台开启验证码则强行验证验证码 /* * if (code != null && !code.equals("")) { code = * CommUtil.filterHTML(code);// 过滤验证码 } // * System.out.println(this.configService.getSysConfig(). * isSecurityCodeRegister()); if * (this.configService.getSysConfig().isSecurityCodeRegister ()) * { if (!request.getSession(false).getAttribute("verify_code") * .equals(code)) { reg = false; } } */ // 禁止用户注册带有 管理员 admin 等字样用户名 if (userName.matches(REGEX1) || userName.toLowerCase().matches(REGEX2)) { reg = false; } if (reg) { Map<String, String> map = new HashMap<String, String>(); if (mobile != null && !mobile.equals("")) { boolean mFlag = this.mobileTools.verify(mobile); if (mFlag) { map = this.mobileTools.mobile(mobile); mobile = (String) map.get("areaMobile"); } } String firebase_token = ""; // 合并firebase 游客身份信息 if (!CommUtil.null2String(uid).equals("")) { User firebaseUser = this.userService.getObjById(CommUtil.null2Long(uid)); if (firebaseUser != null) { firebase_token = firebaseUser.getFirebase_token(); } } User user = new User(); user.setUserName(userName.replace(" ", "")); user.setUserRole("BUYER"); user.setAddTime(new Date()); user.setEmail(email); user.setMobile(map.get("userMobile")); user.setTelephone(map.get("areaMobile")); user.setAvailableBalance(BigDecimal.valueOf(0)); user.setFreezeBlance(BigDecimal.valueOf(0)); user.setPassword(Md5Encrypt.md5(password).toLowerCase()); user.setPwd(password); user.setImei(imei); user.setSex(-1); user.setFirebase_token(firebase_token); // user.setRaffle(configService.getSysConfig().getRegister_lottery()); Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "BUYER"); List<Role> roles = this.roleService.query("select new Role(id) from Role obj where obj.type=:type", params, -1, -1); user.getRoles().addAll(roles); String query = "select * from metoo_lucky_draw where switchs = 1"; Map resultSet = this.databaseTools.selectIns(query, null, "register"); int lucky = CommUtil.null2Int(resultSet.get("lucky")); user.setRaffle(lucky); registerMap.put("raffle", lucky); // 邀请码 boolean goods_voucher_flag = true; if (invitation != null && !invitation.equals("")) { User friend = null; params.clear(); params.put("code", invitation); List<User> userList = this.userService.query("select obj from User obj where obj.code=:code", params, -1, -1); if(userList.size() > 0){ goods_voucher_flag = false; friend = userList.get(0); friend.setPointNum(friend.getPointNum() + 1); user.setPointName(friend.getUsername()); user.setPointId(friend.getId()); user.setParent(friend); this.userService.update(friend); this.userService.save(user); // 设置互为好友 this.appFriendBuyerTools.creatFriend(user, friend); } // 邀请好友 params.clear(); params.put("type", 5); params.put("status", 1); List<GameTask> gameTasks = this.gameTaskService.query( "SELECT obj FROM GameTask obj WHERE obj.status=:status AND obj.type=:type", params, -1, -1); List gameAward = null; if (gameTasks.size() > 0) { GameTask gameTask = gameTasks.get(0); if(gameTask.getGameAward() != null){ // 自动-发放奖品 gameAward = this.appGameAwardTools.createUpgradeAward(friend, gameTask.getGameAward()); // 记录奖励日志 } } // 设置互为好友 日志、记录奖励日志 this.appFriendBuyerTools.registerGameLog(user, friend, gameAward.toString()); // 邀约抵用券 // 1, 查询邀约人已邀约数量 params.clear(); params.put("pointId", friend.getId()); List<User> users = this.userService.query("SELECT obj FROM User obj WHERE obj.pointId=:pointId ", params, -1, -1); // 2, 查询邀约抵用金额 params.clear(); params.put("type", 6);// 6: 邀约抵用券 List<GoodsVoucher> point_goods_voucher_list = this.goodsVoucherService.query("SELECT obj FROM GoodsVoucher obj WHERE obj.type=:type", params, -1, -1); if(users.size() > 3){ params.clear(); params.put("type", 7);// 6: 邀约抵用券 point_goods_voucher_list = this.goodsVoucherService.query("SELECT obj FROM GoodsVoucher obj WHERE obj.type=:type", params, -1, -1); } GoodsVoucher goodsVoucherPoint = point_goods_voucher_list.get(0); // 记录邀约抵用券记录 this.appGoodsVoucherTools.getVoucher(goodsVoucherPoint, friend); // 记录邀约日志 String message = "Reward for inviting " + user.getUserName() + " to register"; String message_sa = "مكافأة لدعوة " + user.getUserName() + " للتسجيل"; this.appGoodsVoucherTools.createLog(goodsVoucherPoint, friend, 2, 0, message, message_sa, null); params.clear(); params.put("type", 5);// 被邀约抵用券 List<GoodsVoucher> goods_voucher_list = this.goodsVoucherService.query("SELECT obj FROM GoodsVoucher obj WHERE obj.type=:type", params, -1, -1); if(goods_voucher_list.size() > 0){ GoodsVoucher goodsVoucher = goods_voucher_list.get(0); // 记录抵用券记录 this.appGoodsVoucherTools.getVoucher(goodsVoucher, user); // 记录邀约日志 String message1 = "Reward for registration"; String message_sa1 = "مكافأة للتسجيل"; this.appGoodsVoucherTools.createLog(goodsVoucher, user, 3, 0, message1, message_sa1, null); registerMap.put("voucher", goodsVoucher.getNumber()); } }else{ this.userService.save(user); } /*if (this.configService.getSysConfig().isIntegral()) { // [积分] user.setIntegral(this.configService.getSysConfig().getMemberRegister()); // 设置用户积分 IntegralLog log = new IntegralLog(); log.setAddTime(new Date()); log.setContent("用户注册增加" + this.configService.getSysConfig().getMemberRegister() + "分"); log.setIntegral(this.configService.getSysConfig().getMemberRegister()); log.setIntegral_user(user); log.setType("reg"); this.integralLogService.save(log); }*/ // 创建用户默认相册 Album album = new Album(); album.setAddTime(new Date()); album.setAlbum_default(true); album.setAlbum_name("默认相册"); album.setAlbum_sequence(-10000); album.setUser(user); this.albumService.save(album); request.getSession(false).removeAttribute("verify_code"); // 优惠券 params.clear(); params.put("employ_type", 1);// 注册优惠券 List<Coupon> coupons = this.couponService .query("select obj from Coupon obj where obj.employ_type=:employ_type", params, -1, -1); for (Coupon coupon : coupons) { int size = coupon.getCouponinfos().size(); if (size <= coupon.getCoupon_count() || coupon.getCoupon_count() == 0) { CouponInfo info = new CouponInfo(); info.setAddTime(new Date()); info.setUser(user); info.setCoupon(coupon); info.setCoupon_sn(UUID.randomUUID().toString()); info.setStore_id(CommUtil.null2Long("-1")); this.couponInfoService.save(info); registerMap.put("coupon_amount", coupon.getCoupon_amount()); } } // 抵用券 非主动注册用户不赠送改抵用券 if(goods_voucher_flag){ params.clear(); params.put("type", 4);// 注冊抵用券 List<GoodsVoucher> goods_voucher_list = this.goodsVoucherService.query("SELECT obj FROM GoodsVoucher obj WHERE obj.type=:type", params, -1, -1); if(goods_voucher_list.size() > 0){ // 记录抵用券记录 GoodsVoucher goodsVoucher = goods_voucher_list.get(0); this.appGoodsVoucherTools.getVoucher(goodsVoucher, user); registerMap.put("voucher", goodsVoucher.getNumber()); // 记录邀约日志 String message1 = "Reward for registration"; String message_sa1 = "مكافأة للتسجيل"; this.appGoodsVoucherTools.createLog(goodsVoucher, user, 1, 0, message1, message_sa1, null); } } result = new Result(0, "Success", registerMap); } else { result = new Result(4204, "注册名中不允许存在'admin and 管理员'"); } } catch (Exception e) { e.printStackTrace(); result = new Result(2, "error"); } } else { result = new Result(4, "违规注册"); } this.send_json(Json.toJson(result, JsonFormat.compact()), response); } @EmailMapping(title = "自动注册", value = "wap_register") @RequestMapping("v1/wap_register.json") public void wap_register(HttpServletRequest request, HttpServletResponse response, String currentPage, String area_id, String area_info, String mobile, String true_name, String email) throws SQLException, UnsupportedEncodingException { ModelAndView mv = new JModelAndView("admin/blue/goods_list.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); Map map = new HashMap(); Map<String, Object> registerMap = new HashMap(); Result result = null; boolean flag = this.mobileTools.verify(mobile); if (flag) { map = this.mobileTools.mobile(mobile); String areaMobile = (String) map.get("areaMobile"); Map params = new HashMap(); params.put("email", areaMobile); params.put("mobile", areaMobile); params.put("userName", areaMobile.replace(" ", "")); params.put("areaMobil", areaMobile); params.put("deleteStatus", 0); List<User> users = this.userService.query( "select obj from User obj where obj.deleteStatus=:deleteStatus and obj.userName =:userName or obj.userName =:areaMobil or obj.email=:email or obj.mobile=:mobile", params, -1, -1); User user = null; if (users.size() > 0) { user = users.get(0); user.setEmail(email); this.userService.update(user); } else { user = new User(); user.setUserName(map.get("areaMobile").toString()); user.setMobile(map.get("userMobile").toString()); user.setTelephone(map.get("areaMobile").toString()); user.setAddTime(new Date()); user.setUserRole("BUYER"); user.setPassword(Md5Encrypt.md5("123456").toLowerCase()); user.setPwd("123456"); user.setAutomatic("1"); user.setEmail(email); params.clear(); params.put("type", "BUYER"); List<Role> roles = this.roleService.query("select new Role(id) from Role obj where obj.type=:type", params, -1, -1); user.getRoles().addAll(roles); String query = "select * from metoo_lucky_draw where switchs = 1"; Map resultSet = this.databaseTools.selectIns(query, null, "order"); int lucky = CommUtil.null2Int(resultSet.get("lucky")); map.put("raffle", lucky); user.setRaffle(lucky); registerMap.put("raffle", lucky); this.userService.save(user); } AddressQueryObject qo = new AddressQueryObject(currentPage, mv, null, null); qo.addQuery("obj.user.id", new SysMap("user_id", CommUtil.null2Long(user.getId())), "="); qo.addQuery("obj.area.id", new SysMap("area_id", CommUtil.null2Long(area_id)), "="); qo.addQuery("obj.area_info", new SysMap("area_info", area_info), "="); qo.addQuery("obj.mobile", new SysMap("mobile", map.get("areaMobile").toString()), "="); qo.addQuery("obj.trueName", new SysMap("true_name", true_name), "="); IPageList pList = this.addressService.list(qo); List<Address> addressList = pList.getResult(); Address address = new Address(); if (addressList.size() == 0) { address.setAddTime(new Date()); address.setTrueName(true_name); address.setArea_info(area_info); address.setMobile(map.get("phoneNumber").toString()); address.setTelephone(map.get("phoneNumber").toString()); address.setDefault_val(1); Area area = this.areaService.getObjById(CommUtil.null2Long(area_id)); address.setArea(area); User addressUser = this.userService.getObjById(CommUtil.null2Long(user.getId())); address.setUser(addressUser); address.setEmail(email); this.addressService.save(address); } // 给自动注册买家发送注册通知短信 if (this.configService.getSysConfig().isSmsEnbale()) { String sms_mobile = mobile; /* * String content = * "Congratulations on the success of your order in Soarmall." + * " Your account: " + map.get("areaMobile").toString() + * " Your password: 123456" + * " App download link:http://app.soarmall.com/download/ " + * " Contact us: " + " service@soarmall.com" + * " WhatsApp: + 86 18900700488"; */ String content = "Thank you for browsing soarmall, our website insist on giving the best service and goods to every customer." + " Account: " + map.get("areaMobile").toString() + " Password: 123456" + " Welcome to the best shopping website soarmall!" + " WhatsApp: + 86 18900700488" + " Email: service@soarmall.com"; if (!areaMobile.equals("88888888")) { try { boolean sms_flag = this.msgTools.sendSMS(sms_mobile, content); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } registerMap.put("pwd", "123456"); registerMap.put("userName", user.getUserName()); registerMap.put("phoneNumber", map.get("phoneNumber").toString()); result = new Result(4200, "Success", registerMap); } else { result = new Result(4400, "Wrong number format"); } this.send_json(Json.toJson(result, JsonFormat.compact()), response); } /** * 绑定firesetoken * * @param request * @param response * @param token * @param firebase_token * @return */ @RequestMapping("bind_firebase.json") @ResponseBody public Object bindFirebase(HttpServletRequest request, HttpServletResponse response, String token, String firebase_token) { Map map = new HashMap(); User user = null; if (firebase_token != null && !firebase_token.equals("")) { User visitor = this.userService.getObjByProperty(null, "firebase_token", firebase_token); if (visitor == null) { boolean flag = true; if (token != null && !token.equals("")) { user = this.userService.getObjByProperty(null, "app_login_token", token); if (user != null) { flag = false; user.setFirebase_token(firebase_token); this.userService.update(user); } } // 创建游客身份 if (flag) { user = new User(); user.setAddTime(new Date()); user.setFirebase_token(firebase_token); user.setUserRole("BUYER"); Map params = new HashMap(); params.put("type", "BUYER"); List<Role> roles = this.roleService.query("select new Role(id) from Role obj where obj.type=:type", params, -1, -1); user.getRoles().addAll(roles); user.setUser_type(4); String number = CommUtil.randomInt(9); user.setUserName(number); user.setPassword(Md5Encrypt.md5("123456").toLowerCase()); user.setAutomatic("1"); String login_token = CommUtil.randomString(12) + user.getId(); user.setApp_login_token(login_token); map.put("token", login_token); this.userService.save(user); } map.put("user_id", user.getId()); } else { map.put("user_id", visitor.getId()); map.put("token", visitor.getApp_login_token()); } return new Result(4200, "Success", map); } return new Result(4400, "Parameter error"); } private void send_json(String json, HttpServletResponse response) { response.setContentType("application/json"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(json); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package ntou.cs.java2021.hw1; import java.util.Scanner; /* * by 00857005 周固廷 * */ public class PalindromeTest { public static void main(String[] args) { Palindrome palindrome = new Palindrome(); Scanner scanner = new Scanner(System.in); while (true) { System.out.print("\nEnter a number (-1 to leave): "); long input; input = scanner.nextLong(); if (input == -1L) break; try { palindrome.setValue(input); } catch (Palindrome.OutOfRangeException e) { System.out.println("the length of the number is not an odd number"); System.out.println(input + " is not a palindrome."); continue; } catch (Palindrome.NotPalindromeException e) { System.out.println(input + " is not a palindrome"); continue; } catch (Palindrome.NumberTooBigException e) { System.out.println("Number is too big"); continue; } System.out.println(palindrome + " is a palindrome!!!"); } } }
package com.xnarum.thonline.recon.entity; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Table; @Table(name="thijari_unrecon_trans") public class THIJARI_UNRECON_TRANS { @Column(name="BUSINESS_DATE", length=4) private Date businessDate; @Column(name="PAYOR_IC", length=30) private String payorIC; @Column(name="TRANSACTION_TYPE", length=4) private String transactionType; @Column(name="TRANSACTION_ID", length=30) private String transactionId; @Column(name="TRANSACTION_TIME", length=30) private String transactionTime; @Column(name="TRANSACTION_DATE", length=30) private String transactionDate; @Column(name="DEBTOR_ACC_NO", length=30) private String debtor; @Column(name="CREDITOR_ACC_NO", length=30) private String creditor; @Column(name="TRANSACTION_AMOUNT", length=30) private BigDecimal amount; @Column(name="CURRENCY_CDE", length=30) private String currencyCode; @Column(name="SOURCE_ID", length=30) private String sourceId; @Column(name="RECON_STATUS", length=30) private String reconStatus; @Column(name="LEVEL", length=30) private String level; @Column(name="CHECKED_BY", length=30) private String checkedBy; @Column(name="CHECKED_DATETIME", length=30) private Date checkedAt; @Column(name="APPROVED_BY", length=30) private String approvedBy; @Column(name="APPROVED_DATETIME", length=30) private Date approvedAt; @Column(name="APPVL_CODE_P38", length=30) private String approvalCodeP38; @Column(name="TRX_DATETIME_P7", length=30) private String transactionDateTimeP7; public Date getBusinessDate() { return businessDate; } public void setBusinessDate(Date businessDate) { this.businessDate = businessDate; } public String getTransactionType() { return transactionType; } public void setTransactionType(String transactionType) { this.transactionType = transactionType; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getTransactionTime() { return transactionTime; } public void setTransactionTime(String transactionTime) { this.transactionTime = transactionTime; } public String getTransactionDate() { return transactionDate; } public void setTransactionDate(String transactionDate) { this.transactionDate = transactionDate; } public String getDebtor() { return debtor; } public void setDebtor(String debtor) { this.debtor = debtor; } public String getCreditor() { return creditor; } public void setCreditor(String creditor) { this.creditor = creditor; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public String getSourceId() { return sourceId; } public void setSourceId(String sourceId) { this.sourceId = sourceId; } public String getReconStatus() { return reconStatus; } public void setReconStatus(String reconStatus) { this.reconStatus = reconStatus; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getCheckedBy() { return checkedBy; } public void setCheckedBy(String checkedBy) { this.checkedBy = checkedBy; } public Date getCheckedAt() { return checkedAt; } public void setCheckedAt(Date checkedAt) { this.checkedAt = checkedAt; } public String getApprovedBy() { return approvedBy; } public void setApprovedBy(String approvedBy) { this.approvedBy = approvedBy; } public Date getApprovedAt() { return approvedAt; } public void setApprovedAt(Date approvedAt) { this.approvedAt = approvedAt; } public String getApprovalCodeP38() { return approvalCodeP38; } public void setApprovalCodeP38(String approvalCodeP38) { this.approvalCodeP38 = approvalCodeP38; } public String getTransactionDateTimeP7() { return transactionDateTimeP7; } public void setTransactionDateTimeP7(String transactionDateTimeP7) { this.transactionDateTimeP7 = transactionDateTimeP7; } public String getPayorIC() { return payorIC; } public void setPayorIC(String payorIC) { this.payorIC = payorIC; } }
package jesk.desktopgui.item; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.util.ArrayList; import java.util.List; import jesk.Jesk; import jesk.desktopgui.DesktopObject; import jesk.desktopgui.Menu; import jesk.system.MouseButton; import jesk.system.OperatingSystem; import jesk.util.FileComparatorByName; import jesk.util.Util; public class ItemSpace extends DesktopObject { public List<Item> items = new ArrayList<>(); public List<Item> selectedItems = new ArrayList<>(); private FileComparatorByName fileComparator = new FileComparatorByName(); private int scrollX, scrollY; private Menu currentMenu; private boolean menuOpen; public ItemSpace() { this(0, 0); } public ItemSpace(int x, int y) { super(x, y); items = Jesk.itemsConfig.getItems(); for (int i=0; i<items.size(); i++) { items.get(i).setItemSpace(this); } } @Override public void update(Graphics2D g) { if (currentMenu != null) { currentMenu.update(g); } } public void updateItems(Graphics2D g) { boolean change = false; File[] files = OperatingSystem.listFilesOnDesktop(fileComparator); for (int i=0; i<files.length; i++) { File f = files[i]; if (!hasItem(f)) { items.add(new ItemFile(this, 0, 0, f)); change = true; } } for (int i=0; i<items.size(); i++) { Item item = items.get(i); item.update(g); if (!items.contains(item)) // item removed itself i--; } for (int i=0; i<selectedItems.size(); i++) { Item item = selectedItems.get(i); if (!items.contains(item)) { selectedItems.remove(i); i--; change = true; } } if (change) { arrangeGrid(g); Jesk.update(); } Jesk.itemsConfig.setFromItemSpace(this); } @Override public void render(Graphics2D g) { for (int i=0; i<items.size(); i++) { Item item = items.get(i); item.render(g); } if (currentMenu != null) { currentMenu.render(g); } } @Override public DesktopObject getParent() { return null; } @Override public int getScrollX() { return scrollX; } @Override public int getScrollY() { return scrollY; } @Override public void dragBy(int x, int y) { scrollX += x; scrollY += y; } @Override public boolean canDrag(MouseButton button, int x, int y) { return button == MouseButton.MIDDLE; } public boolean hasItem(File file) { for (int i=0; i<items.size(); i++) { Item item = items.get(i); if (item instanceof ItemFile && Util.equals(((ItemFile) item).file(), file)) return true; } return false; } public void arrangeGrid(Graphics2D g) { List<List<Item>> cols = new ArrayList<>(); cols.add(new ArrayList<Item>()); int y = 2; for (int i=0; i<items.size(); i++) { Item item = items.get(i); if (y + item.getHeight(g) > Jesk.getEffectiveHeight()-4) { y = 0; cols.add(new ArrayList<Item>()); } item.setY(y); cols.get(cols.size()-1).add(item); y += item.getHeight(g) + 10; } int x = 2; for (List<Item> col : cols) { int w = 0; for (Item item : col) { w = Math.max(item.getWidth(g), w); } for (Item item : col) { item.setX(x + (w - item.getWidth(g))/2); } x += w + 4; } } public boolean isSelected(Item item) { return selectedItems.contains(item); } public void setSelected(Item item, boolean selected) { if (selected) { if (!selectedItems.contains(item)) selectedItems.add(item); } else { selectedItems.remove(item); } } public void setAllSelected(boolean selected) { if (selected) { selectedItems.addAll(items); } else { selectedItems.clear(); } } public int getSelectionCount() { return selectedItems.size(); } public Rectangle2D getSelectionBounds(Graphics2D g) { int x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (int i=0; i<selectedItems.size(); i++) { Item item = selectedItems.get(i); int ix1 = item.getXOnScreen(), iy1 = item.getYOnScreen(), ix2 = ix1 + item.getWidth(g), iy2 = iy1 + item.getHeight(g); if (i == 0) { x1 = ix1; y1 = iy1; x2 = ix2; y2 = iy2; } x1 = Math.min(x1, ix1); y1 = Math.min(y1, iy1); x2 = Math.max(x2, ix2); y2 = Math.max(y2, iy2); } return new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); } public boolean isHoverPossible(DesktopObject object) { return object != null && (!hasMenu() || getMenu() == object); } public DesktopObject getHoveredObject(Graphics2D g) { if (hasMenu()) return getMenu(); for (int i=0; i<items.size(); i++) { Item item = items.get(i); if (item.isMouseOver(g)) return item; } return null; } public boolean hasMenu() { return currentMenu != null && menuOpen; } public Menu getMenu() { return currentMenu; } public void openMenu(Menu menu) { if (menu == null) { removeMenu(); return; } this.currentMenu = menu; this.menuOpen = true; menu.onOpen(); } public void closeMenu() { if (this.currentMenu != null) this.currentMenu.onClose(); this.menuOpen = false; } public void removeMenu() { this.currentMenu = null; } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hcp.base.model; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; /** * TREAT_DRUG * * @author zyus * @version 1.0.0 2017-12-16 */ public class IDrug implements java.io.Serializable { /** 版本号 */ /** hosNo */ private String hosNo; /** hosName */ private String hosName; /** code */ private String code; /** name */ private String name; /** pinyin */ private String pinyin; /** wubi */ private String wubi; /** price */ private BigDecimal price; /** unit */ private String unit; /** spec */ private String spec; /** packages */ private String packages; /** supplier */ private String producer; /** inPrice */ private BigDecimal inPrice; /** effectDate */ private String effectDate; /** miFlag */ private String miFlag; /** status */ private String status; private Hospital hospital; /** * 获取hosId * * @return hosId */ /** * 获取hosNo * * @return hosNo */ public String getHosNo() { return this.hosNo; } /** * 设置hosNo * * @param hosNo */ public void setHosNo(String hosNo) { this.hosNo = hosNo; } /** * 获取hosName * * @return hosName */ public String getHosName() { return this.hosName; } /** * 设置hosName * * @param hosName */ public void setHosName(String hosName) { this.hosName = hosName; } /** * 获取code * * @return code */ public String getCode() { return this.code; } /** * 设置code * * @param code */ public void setCode(String code) { this.code = code; } /** * 获取name * * @return name */ public String getName() { return this.name; } /** * 设置name * * @param name */ public void setName(String name) { this.name = name; } /** * 获取pinyin * * @return pinyin */ public String getPinyin() { return this.pinyin; } /** * 设置pinyin * * @param pinyin */ public void setPinyin(String pinyin) { this.pinyin = pinyin; } /** * 获取wubi * * @return wubi */ public String getWubi() { return this.wubi; } /** * 设置wubi * * @param wubi */ public void setWubi(String wubi) { this.wubi = wubi; } /** * 获取price * * @return price */ public BigDecimal getPrice() { return this.price; } /** * 设置price * * @param price */ public void setPrice(BigDecimal price) { this.price = price; } /** * 获取unit * * @return unit */ public String getUnit() { return this.unit; } /** * 设置unit * * @param unit */ public void setUnit(String unit) { this.unit = unit; } /** * 获取spec * * @return spec */ public String getSpec() { return this.spec; } /** * 设置spec * * @param spec */ public void setSpec(String spec) { this.spec = spec; } /** * 获取packages * * @return packages */ public String getPackages() { return this.packages; } /** * 设置packages * * @param packages */ public void setPackages(String packages) { this.packages = packages; } /** * 获取supplier * * @return supplier */ /** * 获取inPrice * * @return inPrice */ public BigDecimal getInPrice() { return this.inPrice; } public String getProducer() { return producer; } public void setProducer(String producer) { this.producer = producer; } /** * 设置inPrice * * @param inPrice */ public void setInPrice(BigDecimal inPrice) { this.inPrice = inPrice; } /** * 获取effectDate * * @return effectDate */ public String getEffectDate() { return this.effectDate; } /** * 设置effectDate * * @param effectDate */ public void setEffectDate(String effectDate) { this.effectDate = effectDate; } /** * 获取miFlag * * @return miFlag */ public String getMiFlag() { return this.miFlag; } /** * 设置miFlag * * @param miFlag */ public void setMiFlag(String miFlag) { this.miFlag = miFlag; } /** * 获取status * * @return status */ public String getStatus() { return this.status; } /** * 设置status * * @param status */ public void setStatus(String status) { this.status = status; } public Hospital getHospital() { return hospital; } public void setHospital(Hospital hospital) { this.hospital = hospital; } }
package com.asiainfo.worktime.entity; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * The persistent class for the TB_WORK_TIME database table. * */ @Entity @Table(name="TB_WORK_TIME") //@NamedQuery(name="TbWorkTime.findAll", query="SELECT t FROM TbWorkTime t") public class WorkTimeEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="WORK_ID") private int workId; @Column(name="APPLY_DEV_HOUR") private int applyDevHour; @Column(name="APPLY_QA_HOUR") private int applyQaHour; @Column(name="APPLY_WHOLE_HOUR") private int applyWholeHour; @Column(name="CREATE_TIME") private Timestamp createTime; @Column(name="REAL_DEV_HOUR") private int realDevHour; @Column(name="REAL_QA_HOUR") private int realQaHour; @Column(name="REAL_WHOLE_HOUR") private int realWholeHour; @Column(name="REQUEST_CODE") private String requestCode; @Column(name="REQUEST_NAME") private String requestName; //bi-directional many-to-one association to TbWorkState @ManyToOne @JoinColumn(name="WORK_STATE_CODE") private WorkStateEntity tbWorkState; //bi-directional many-to-one association to TbProc @ManyToOne @JoinColumn(name="PROC_ID") private ProcEntity tbProc; //bi-directional many-to-one association to TbEmployee @ManyToOne @JoinColumn(name="DEV") private EmployeeEntity dev; //bi-directional many-to-one association to TbEmployee @ManyToOne @JoinColumn(name="QA") private EmployeeEntity qa; public WorkTimeEntity() { this.tbProc = new ProcEntity(); this.tbWorkState = new WorkStateEntity(); this.qa = new EmployeeEntity(); this.dev = new EmployeeEntity(); } public int getWorkId() { return this.workId; } public void setWorkId(int workId) { this.workId = workId; } public int getApplyDevHour() { return this.applyDevHour; } public void setApplyDevHour(int applyDevHour) { this.applyDevHour = applyDevHour; } public int getApplyQaHour() { return this.applyQaHour; } public void setApplyQaHour(int applyQaHour) { this.applyQaHour = applyQaHour; } public int getApplyWholeHour() { return this.applyWholeHour; } public void setApplyWholeHour(int applyWholeHour) { this.applyWholeHour = applyWholeHour; } public Timestamp getCreateTime() { return this.createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public int getRealDevHour() { return this.realDevHour; } public void setRealDevHour(int realDevHour) { this.realDevHour = realDevHour; } public int getRealQaHour() { return this.realQaHour; } public void setRealQaHour(int realQaHour) { this.realQaHour = realQaHour; } public int getRealWholeHour() { return this.realWholeHour; } public void setRealWholeHour(int realWholeHour) { this.realWholeHour = realWholeHour; } public String getRequestCode() { return this.requestCode; } public void setRequestCode(String requestCode) { this.requestCode = requestCode; } public String getRequestName() { return this.requestName; } public void setRequestName(String requestName) { this.requestName = requestName; } public WorkStateEntity getTbWorkState() { return this.tbWorkState; } public void setTbWorkState(WorkStateEntity tbWorkState) { this.tbWorkState = tbWorkState; } public ProcEntity getTbProc() { return this.tbProc; } public void setTbProc(ProcEntity tbProc) { this.tbProc = tbProc; } public EmployeeEntity getDev() { return dev; } public void setDev(EmployeeEntity dev) { this.dev = dev; } public EmployeeEntity getQa() { return qa; } public void setQa(EmployeeEntity qa) { this.qa = qa; } @Override public String toString() { return "WorkTimeEntity [workId=" + workId + ", applyDevHour=" + applyDevHour + ", applyQaHour=" + applyQaHour + ", applyWholeHour=" + applyWholeHour + ", createTime=" + createTime + ", realDevHour=" + realDevHour + ", realQaHour=" + realQaHour + ", realWholeHour=" + realWholeHour + ", requestCode=" + requestCode + ", requestName=" + requestName + "]"; } }
package CollectionProgram; import java.util.ArrayList; import java.util.Collections; public class SwapTwoElementsInAArrayList { public static void main(String a[]) { ArrayList<String> ArrList = new ArrayList<String>(); ArrList.add("Item 1"); ArrList.add("Item 2"); ArrList.add("Item 3"); ArrList.add("Item 4"); ArrList.add("Item 5"); System.out.println("Before Swap the ArrayList "); System.out.println(ArrList); Collections.swap(ArrList, 1, 2); System.out.println("After Swap the ArrayList"); System.out.println(ArrList); } }
package com.rengu.operationsoanagementsuite.Utils; import com.rengu.operationsoanagementsuite.Entity.ResultEntity; import com.rengu.operationsoanagementsuite.Entity.UserEntity; import org.springframework.http.HttpStatus; import java.security.Principal; public class ResultUtils { // 创建ResultEntity public static ResultEntity resultBuilder(String username, int code, String message, Object data) { ResultEntity resultEntity = new ResultEntity(); resultEntity.setUsername(username); resultEntity.setCode(code); resultEntity.setMessage(message); resultEntity.setData(data); return resultEntity; } // 创建ResultEntity public static ResultEntity resultBuilder(UserEntity userEntity, HttpStatus httpStatus, Object data) { String username = userEntity == null ? "" : userEntity.getUsername(); int code = httpStatus.value(); String message = httpStatus.getReasonPhrase(); return resultBuilder(username, code, message, data); } // 创建ResultEntity public static ResultEntity resultBuilder(Principal principal, HttpStatus httpStatus, Throwable throwable) { String username = principal == null ? null : principal.getName(); int code = httpStatus.value(); String message = httpStatus.getReasonPhrase(); String data = throwable == null ? null : throwable.getMessage(); return resultBuilder(username, code, message, data); } }
package de.trispeedys.resourceplanning.delegate.requesthelp; import org.camunda.bpm.engine.delegate.DelegateExecution; import de.trispeedys.resourceplanning.datasource.Datasources; import de.trispeedys.resourceplanning.delegate.requesthelp.misc.RequestHelpNotificationDelegate; import de.trispeedys.resourceplanning.entity.Event; import de.trispeedys.resourceplanning.entity.Helper; import de.trispeedys.resourceplanning.entity.MessagingType; import de.trispeedys.resourceplanning.entity.Position; import de.trispeedys.resourceplanning.entity.misc.HistoryType; import de.trispeedys.resourceplanning.entity.misc.MessagingFormat; import de.trispeedys.resourceplanning.entity.util.EntityFactory; import de.trispeedys.resourceplanning.execution.BpmVariables; import de.trispeedys.resourceplanning.messaging.SendReminderMailTemplate; import de.trispeedys.resourceplanning.service.MessagingService; public class SendReminderMailDelegate extends RequestHelpNotificationDelegate { public void execute(DelegateExecution execution) throws Exception { // find helper and event Long helperId = (Long) execution.getVariable(BpmVariables.RequestHelpHelper.VAR_HELPER_ID); Long eventId = (Long) execution.getVariable(BpmVariables.RequestHelpHelper.VAR_EVENT_ID); Long positionId = (Long) execution.getVariable(BpmVariables.RequestHelpHelper.VAR_PRIOR_POSITION); // write mail Helper helper = (Helper) Datasources.getDatasource(Helper.class).findById(helperId); Event event = (Event) Datasources.getDatasource(Event.class).findById(eventId); Position position = (Position) Datasources.getDatasource(Position.class).findById(positionId); int attemptCount = (Integer) execution.getVariable(BpmVariables.RequestHelpHelper.VAR_MAIL_ATTEMPTS); SendReminderMailTemplate template = new SendReminderMailTemplate(helper, event, position, (Boolean) execution.getVariable(BpmVariables.RequestHelpHelper.VAR_PRIOR_POS_AVAILABLE), attemptCount); MessagingService.createMessage("noreply@tri-speedys.de", helper.getEmail(), template.constructSubject(), template.constructBody(), getMessagingType(attemptCount), MessagingFormat.HTML); // increase attempts execution.setVariable(BpmVariables.RequestHelpHelper.VAR_MAIL_ATTEMPTS, (attemptCount + 1)); // write history entry... writeHistoryEntry(HistoryType.REMINDER_MAIL_SENT, execution); } private MessagingType getMessagingType(int attempt) { switch (attempt) { case 0: return MessagingType.REMINDER_STEP_0; case 1: return MessagingType.REMINDER_STEP_1; case 2: return MessagingType.REMINDER_STEP_2; default: return MessagingType.NONE; } } }
package com.pelephone_mobile.mypelephone.ui.activities; import android.view.View; import android.view.Window; import android.webkit.WebView; import android.widget.ImageButton; import com.pelephone_mobile.R; /** * Created by Gali.Issachar on 17/09/13. */ public class TermsOfUseActivity extends MPBaseActivity { public static final String LOAD_PDF_LINK = "https://docs.google.com/gview?embedded=true&url="; public static final String PDF_LINK_EXAMPLE = "https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/61936/national-security-strategy.pdf"; ImageButton ibBack; @Override protected void initContentView() { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.terms_of_use_layout); ibBack = (ImageButton)findViewById(R.id.ibBack); ibBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); WebView webView = (WebView)findViewById(R.id.wvTerms); webView.getSettings().setJavaScriptEnabled(true); /* webView.getSettings().setPluginEnable(true);*/ webView.loadUrl("https://www.pelephone.co.il/digital/3G/Corporate/digital/general/terms/.aspx"); // webView.loadUrl(LOAD_PDF_LINK+PDF_LINK_EXAMPLE); } @Override protected void onServiceConnected() { } }
package com.arquitecturajava.app1; import java.util.Arrays; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration @EnableWebSecurity(debug=true) public class WebSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // desactivamos la cache http.headers().cacheControl(); //eliminamos csrf http.csrf().disable().cors().and() // disable csrf for our requests. .authorizeRequests() //permitimos la url por defecto .antMatchers("/").permitAll() .antMatchers(HttpMethod.POST, "/webapi/login").permitAll() //protegemos el resto .anyRequest().authenticated() .and() //We filter the api/login requests .addFilterBefore(new FiltroLogin("/webapi/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class) // And filter other requests to check the presence of JWT in header .addFilterBefore(new FiltroJWTAutenticacion(), UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //creamos un autenticantion manager en memoria PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); auth.inMemoryAuthentication() .withUser("cecilio") .password(encoder.encode("miclave")) .roles("ADMINISTRADOR"); } @Bean CorsConfigurationSource corsConfigurationSource() { System.out.println("llega"); CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowCredentials(true); configuration.addAllowedOrigin("http://localhost:8081"); configuration.addAllowedHeader("*"); configuration.addExposedHeader("Authorization"); configuration.addAllowedMethod("*"); //configuration.setAllowedHeaders(Arrays.asList("Authorization")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); //FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); return source; } }
/* * Copyright (C) 2016 The Android Open Source Project * * 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 art; import java.util.Base64; public class Test1997 { public static class SuperTransform { // We will be shadowing this function. public static void sayHi() { System.out.println("Hello!"); } } // The class we will be transforming. public static class Transform extends SuperTransform { public static void sayHiTwice() { Transform.sayHi(); Transform.sayHi(); } } // public static class Transform extends SuperTransform { // public static void sayHiTwice() { // Transform.sayHi(); // Transform.sayHi(); // } // public static void sayHi() { // System.out.println("Hello World!"); // } // } private static final byte[] DEX_BYTES = Base64.getDecoder() .decode( "ZGV4CjAzNQA9wdy7Lgbrv+sD+wixborREr0maZCK5yqABAAAcAAAAHhWNBIAAAAAAAAAALwDAAAW" + "AAAAcAAAAAkAAADIAAAAAgAAAOwAAAABAAAABAEAAAUAAAAMAQAAAQAAADQBAAAsAwAAVAEAAMIB" + "AADKAQAA2AEAAPcBAAARAgAAIQIAAEUCAABlAgAAfAIAAJACAACkAgAAswIAAL4CAADBAgAAxQIA" + "ANICAADYAgAA3QIAAOYCAADtAgAA+QIAAAADAAACAAAAAwAAAAQAAAAFAAAABgAAAAcAAAAIAAAA" + "CQAAAAwAAAAMAAAACAAAAAAAAAANAAAACAAAALwBAAAHAAUAEAAAAAAAAAAAAAAAAQAAAAAAAAAB" + "AAAAEgAAAAEAAAATAAAABQABABEAAAABAAAAAQAAAAAAAAAAAAAACgAAAKwDAACHAwAAAAAAAAEA" + "AQABAAAAqgEAAAQAAABwEAAAAAAOAAIAAAACAAAArgEAAAgAAABiAAAAGgEBAG4gBAAQAA4AAAAA" + "AAAAAACzAQAABwAAAHEAAgAAAHEAAgAAAA4ADwAOABUADngAEQAOPDwAAAAAAQAAAAYABjxpbml0" + "PgAMSGVsbG8gV29ybGQhAB1MYXJ0L1Rlc3QxOTk3JFN1cGVyVHJhbnNmb3JtOwAYTGFydC9UZXN0" + "MTk5NyRUcmFuc2Zvcm07AA5MYXJ0L1Rlc3QxOTk3OwAiTGRhbHZpay9hbm5vdGF0aW9uL0VuY2xv" + "c2luZ0NsYXNzOwAeTGRhbHZpay9hbm5vdGF0aW9uL0lubmVyQ2xhc3M7ABVMamF2YS9pby9Qcmlu" + "dFN0cmVhbTsAEkxqYXZhL2xhbmcvU3RyaW5nOwASTGphdmEvbGFuZy9TeXN0ZW07AA1UZXN0MTk5" + "Ny5qYXZhAAlUcmFuc2Zvcm0AAVYAAlZMAAthY2Nlc3NGbGFncwAEbmFtZQADb3V0AAdwcmludGxu" + "AAVzYXlIaQAKc2F5SGlUd2ljZQAFdmFsdWUAdn5+RDh7ImNvbXBpbGF0aW9uLW1vZGUiOiJkZWJ1" + "ZyIsIm1pbi1hcGkiOjEsInNoYS0xIjoiNjBkYTRkNjdiMzgxYzQyNDY3NzU3YzQ5ZmI2ZTU1NzU2" + "ZDg4YTJmMyIsInZlcnNpb24iOiIxLjcuMTItZGV2In0AAgMBFBgCAgQCDgQJDxcLAAADAAGBgATU" + "AgEJ7AIBCYwDAAAAAAAAAAIAAAB4AwAAfgMAAKADAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAEAAAAA" + "AAAAAQAAABYAAABwAAAAAgAAAAkAAADIAAAAAwAAAAIAAADsAAAABAAAAAEAAAAEAQAABQAAAAUA" + "AAAMAQAABgAAAAEAAAA0AQAAASAAAAMAAABUAQAAAyAAAAMAAACqAQAAARAAAAEAAAC8AQAAAiAA" + "ABYAAADCAQAABCAAAAIAAAB4AwAAACAAAAEAAACHAwAAAxAAAAIAAACcAwAABiAAAAEAAACsAwAA" + "ABAAAAEAAAC8AwAA"); public static void run() throws Exception { Redefinition.setTestConfiguration(Redefinition.Config.COMMON_REDEFINE); doTest(); } public static void doTest() throws Exception { Transform.sayHiTwice(); Transform.sayHi(); Redefinition.doCommonStructuralClassRedefinition(Transform.class, DEX_BYTES); Transform.sayHiTwice(); Transform.sayHi(); } }
package videopoker.model; import java.io.FileNotFoundException; import java.io.IOException; public class App { public static void main(String[] args) throws FileNotFoundException, IOException{ Deck deck = new Deck("C:\\Users\\Bruno\\workspace\\VideoPoker\\src\\card-file.txt"); } }
package Dico; public class Levenshtein { private String mot1; private String mot2; private int distance; public Levenshtein(String mot1, String mot2) { this.mot1 = mot1; this.mot2 = mot2; distance = 0; } private void swap(){ String tmp; tmp = mot1; mot1 = mot2; mot2 = tmp; } private void reduceWords(){ mot1 = mot1.substring(0, mot1.length() - 1); mot2 = mot2.substring(0, mot2.length() - 1); } public int getDistance(){ if(mot1.length() > mot2.length()) swap(); if (mot1.length() == 0) return distance; char lastChar1 = mot1.charAt(mot1.length()-1); char lastChar2 = mot2.charAt(mot2.length()-1); if (lastChar1 == lastChar2) { reduceWords(); getDistance(); } else { if (mot1.length() < mot2.length() && mot1.indexOf(lastChar2) == -1) mot1 += lastChar2; else mot1 = mot1.replace(lastChar1, lastChar2); ++distance; getDistance(); } return distance; } }
package com.example.tddfpcrud; import org.springframework.data.mongodb.core.mapping.Document; @Document public class Person { private String id; private String nombre; public Person() { } public Person(String nombre) { this.nombre = nombre; } public Person(String id, String nombre) { this.id = id; this.nombre = nombre; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
package com.test.proxy.dynamic; import com.test.proxy.statics.Renter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Created with IntelliJ IDEA. * User: wuzbin * Date: 13-5-6 * Time: 下午10:30 * To change this template use File | Settings | File Templates. */ public class AgentInvocationHandler implements InvocationHandler { private Renter renter; public AgentInvocationHandler(Renter renter) { this.renter = renter; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String proxyName = proxy.getClass().getSimpleName(); System.out.println("我是代理: " + proxyName); System.out.println(proxyName + "找到一个房源");//中介做的事情 System.out.println(proxyName + "联系到了房东");//中介做的事情 method.invoke(renter, args); System.out.println(proxyName + "收到" + renter.getName() + "的中介费");//中介做的事情 return null; } }
package com.example.van.baotuan.VP.act.launch.page1; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import com.example.van.baotuan.R; import com.example.van.baotuan.VP.act.launch.page2.LaunchAct2Activity; import com.example.van.baotuan.model.act.entity.TagPanel; import com.example.van.baotuan.util.ActivityManger.MyActivity; import com.example.van.baotuan.widget.layout.WrapLayout; import com.example.van.baotuan.widget.titleBar.TitleBar; import butterknife.BindView; import butterknife.ButterKnife; /** * 发起活动 */ public class LaunchActActivity extends MyActivity implements LaunchActContract.View { @BindView(R.id.RV_tagList) RecyclerView RV_TagList; @BindView(R.id.layout_selected) WrapLayout layoutSelected; @BindView(R.id.title) TitleBar titleBar; private LaunchActContract.Presenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_launch_act); ButterKnife.bind(this); setPresenter(new LaunchActPresenter(this)); init(); } private void init(){ presenter.initTagList(); RV_TagList.setLayoutManager(new LinearLayoutManager(this)); RV_TagList.setAdapter(new TagListAdapter(this,this.presenter)); titleBar.setRightButtonOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { presenter.tranData(); startActivity(new Intent(LaunchActActivity.this,LaunchAct2Activity.class)); } }); //不自动弹出输入框 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); } @Override public void initTagList(TagPanel[] tagPanels) { } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void selectTag(String tag) { Button btn = newButton(tag); layoutSelected.addView(btn); } @Override public void removeTag(String tag) { } @Override public void setPresenter(LaunchActContract.Presenter presenter) { this.presenter = presenter; } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) private Button newButton(final String tag){ final Button btn = new Button(this); btn.setText(tag); LinearLayoutCompat.LayoutParams lp = new LinearLayoutCompat.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, 50); btn.setLayoutParams(lp); btn.setBackground(ContextCompat.getDrawable(this,R.drawable.bg_gray_tag)); btn.setPadding(10,0,10,0); btn.setTextSize(14); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { layoutSelected.removeView(btn); presenter.removeTag(tag); } }); return btn; } }
package 设计模式.工厂模式.简单工厂.披萨店.订购; import 设计模式.工厂模式.简单工厂.披萨店.披萨.CheesePizza; import 设计模式.工厂模式.简单工厂.披萨店.披萨.GreekPizza; import 设计模式.工厂模式.简单工厂.披萨店.披萨.Pizza; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //普通的方法 public class OrderPizza { //构造器 public OrderPizza(SimpleFactory simpleFactory){ setSimpleFactory(simpleFactory); } /* public String OrderPizza() { Pizza pizza = null; String orderType;//订购披萨的类型 do { orderType = gettype(); if (orderType.equals("greek")) { pizza = new GreekPizza(); pizza.setName("希腊披萨"); } else if ((orderType.equals("cheese"))) { pizza = new CheesePizza(); pizza.setName("奶酪披萨"); } else break; //输出披萨的制作过程 pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); } while (true); } */ //定义一个简单工厂对象 SimpleFactory simpleFactory; Pizza pizza=null; public void setSimpleFactory(SimpleFactory simpleFactory){ String orderType="";//用户输入 this.simpleFactory=simpleFactory;//设置一个简单工厂对象 do{ orderType=gettype(); pizza=this.simpleFactory.createPizza(orderType); //输出披萨的信息 if(pizza!=null){//订购成功 pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); }else System.out.println("没有这个披萨"); }while(true); } //写一个方法动态地获取客户需要披萨的种类 private String gettype() { try { //用户自己输入想要获取的披萨 BufferedReader strin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("input pizza 种类:"); String str = strin.readLine(); return str; } catch (IOException e) { e.printStackTrace(); return ""; } } }
package com.github.dongchan.scheduler.testhelper; import com.github.dongchan.scheduler.Clock; import java.time.Instant; /** * @author DongChan * @date 2020/10/22 * @time 11:22 PM */ public class SettableClock implements Clock { public Instant now = Instant.now(); public void setNow(Instant now) { this.now = now; } @Override public Instant now() { return now; } }
/* * Copyright 2002-2020 the original author or authors. * * 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 * * https://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.springframework.expression.spel.support; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.expression.EvaluationException; import org.springframework.expression.TypeLocator; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; /** * A simple implementation of {@link TypeLocator} that uses the context ClassLoader * (or any ClassLoader set upon it). It supports 'well-known' packages: So if a * type cannot be found, it will try the registered imports to locate it. * * @author Andy Clement * @author Juergen Hoeller * @since 3.0 */ public class StandardTypeLocator implements TypeLocator { @Nullable private final ClassLoader classLoader; private final List<String> knownPackagePrefixes = new ArrayList<>(1); /** * Create a StandardTypeLocator for the default ClassLoader * (typically, the thread context ClassLoader). */ public StandardTypeLocator() { this(ClassUtils.getDefaultClassLoader()); } /** * Create a StandardTypeLocator for the given ClassLoader. * @param classLoader the ClassLoader to delegate to */ public StandardTypeLocator(@Nullable ClassLoader classLoader) { this.classLoader = classLoader; // Similar to when writing regular Java code, it only knows about java.lang by default registerImport("java.lang"); } /** * Register a new import prefix that will be used when searching for unqualified types. * Expected format is something like "java.lang". * @param prefix the prefix to register */ public void registerImport(String prefix) { this.knownPackagePrefixes.add(prefix); } /** * Remove that specified prefix from this locator's list of imports. * @param prefix the prefix to remove */ public void removeImport(String prefix) { this.knownPackagePrefixes.remove(prefix); } /** * Return a list of all the import prefixes registered with this StandardTypeLocator. * @return a list of registered import prefixes */ public List<String> getImportPrefixes() { return Collections.unmodifiableList(this.knownPackagePrefixes); } /** * Find a (possibly unqualified) type reference - first using the type name as-is, * then trying any registered prefixes if the type name cannot be found. * @param typeName the type to locate * @return the class object for the type * @throws EvaluationException if the type cannot be found */ @Override public Class<?> findType(String typeName) throws EvaluationException { String nameToLookup = typeName; try { return ClassUtils.forName(nameToLookup, this.classLoader); } catch (ClassNotFoundException ey) { // try any registered prefixes before giving up } for (String prefix : this.knownPackagePrefixes) { try { nameToLookup = prefix + '.' + typeName; return ClassUtils.forName(nameToLookup, this.classLoader); } catch (ClassNotFoundException ex) { // might be a different prefix } } throw new SpelEvaluationException(SpelMessage.TYPE_NOT_FOUND, typeName); } }
package com.brainacademy.threads; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class ThreadPoolTest { private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(2); public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 10; i++) { EXECUTOR_SERVICE.execute(() -> { System.out.println(Thread.currentThread().getId() + ", " + Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }); } EXECUTOR_SERVICE.shutdown(); EXECUTOR_SERVICE.awaitTermination(10, TimeUnit.SECONDS); System.out.println("Finish"); } }
package com.zzh.cloud; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.zzh.cloud.mapper.**") public class MysqlMybatisApplication { public static void main(String[] args) { SpringApplication.run(MysqlMybatisApplication.class, args); } }
package com.javarush.test.level07.lesson08.Example02; /* * Reading list of numbers from keyboard, even numbers are added to the end of list, * odd numbers are added to be beginning of list. */ import java.io.*; import java.util.ArrayList; public class Example { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> list = new ArrayList<Integer>(); while (true) { String s = br.readLine(); if (s.isEmpty()) break; int x = Integer.parseInt(s); if (x % 2 == 0) //check that the remainder of division by two equals zero list.add(x); //add to the end else list.add(0,x); //add to the beginning list } } }
/* * 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 bioskop; import java.io.Serializable; /** * * @author satria */ public class film_booking implements Serializable{ private String nama_lokasi; private String nama_bioskop; private String nomor_studio; private String judul_film; private String tgl_tayang; private String jam_tayang; private String no_seat; private double harga; public film_booking(String nama_lokasi, String nama_bioskop, String nomor_studio, String judul_film, String tgl_tayang, String jam_tayang, String no_seat, double harga) { this.nama_lokasi = nama_lokasi; this.nama_bioskop = nama_bioskop; this.nomor_studio = nomor_studio; this.judul_film = judul_film; this.tgl_tayang = tgl_tayang; this.jam_tayang = jam_tayang; this.no_seat = no_seat; this.harga = harga; } public String getNama_lokasi() { return nama_lokasi; } public void setNama_lokasi(String nama_lokasi) { this.nama_lokasi = nama_lokasi; } public String getNama_bioskop() { return nama_bioskop; } public void setNama_bioskop(String nama_bioskop) { this.nama_bioskop = nama_bioskop; } public String getNomor_studio() { return nomor_studio; } public void setNomor_studio(String nomor_studio) { this.nomor_studio = nomor_studio; } public String getJudul_film() { return judul_film; } public void setJudul_film(String judul_film) { this.judul_film = judul_film; } public String getTgl_tayang() { return tgl_tayang; } public void setTgl_tayang(String tgl_tayang) { this.tgl_tayang = tgl_tayang; } public String getJam_tayang() { return jam_tayang; } public void setJam_tayang(String jam_tayang) { this.jam_tayang = jam_tayang; } public String getNo_seat() { return no_seat; } public void setNo_seat(String no_seat) { this.no_seat = no_seat; } public double getHarga() { return harga; } public void setHarga(double harga) { this.harga = harga; } }
package com.altmedia.billboard.entity; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDocument; @DynamoDBDocument public class UserInfo { private String firstName; private String lastName; private String emailAddress; private String phone; private String additonalInfo; public UserInfo() { } @DynamoDBAttribute(attributeName = "FirstName") public String getFirstName() { return firstName; } @DynamoDBAttribute(attributeName = "LastName") public String getLastName() { return lastName; } @DynamoDBAttribute(attributeName = "EmailAddress") public String getEmailAddress() { return emailAddress; } @DynamoDBAttribute(attributeName = "Phone") public String getPhone() { return phone; } @DynamoDBAttribute(attributeName = "AdditonalInfo") public String getAdditonalInfo() { return additonalInfo; } public UserInfo setFirstName(String firstName) { this.firstName = firstName; return this; } public UserInfo setLastName(String lastName) { this.lastName = lastName; return this; } public UserInfo setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; return this; } public UserInfo setPhone(String phone) { this.phone = phone; return this; } public UserInfo setAdditonalInfo(String additonalInfo) { this.additonalInfo = additonalInfo; return this; } }
/** * Represents the progress made in the current game. * */ public class Progress { static final int nHighScores = 10; static final String filename = "score.cfg"; static int levelsCompleted = 0; static int levelScore[][] = new int[Levels.nLevels][nHighScores]; static { load(); } public static void load() { } public static void save() { } }
package ua.siemens.dbtool.dao; import ua.siemens.dbtool.model.auxilary.JobType; /** * The DAO interface for {@link JobType} * * @author Perevoznyk Pavlo * creation date 29 August 2017 * @version 1.0 */ public interface JobTypeDAO extends GenericDAO<JobType, Long> { }
package com.git.cloud.common.support; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class TimeUtils { public static long formatDateStringToInt(String strDate, String _format) { Date time; SimpleDateFormat format = new SimpleDateFormat(_format, Locale.getDefault()); try { time = format.parse(strDate); return time.getTime() / 1000; } catch (Exception e) { return -1; } } public static long formatDateToInt(Date p_date) { if (p_date != null) { return p_date.getTime() / 1000; } return 0; } }
package rs2.model; /** * Represents a single skill belonging to the player. * * @author Jake Bellotti * @since 1.0 */ public class Skill { /** * The level that the level is currently at, which may be affected by combat effects, potions, * etc., for example a Player may have reached level 99 in prayer, but their current level is 59 because * they've had a prayer activated. */ private int currentLevel = 1; /** * The level in which a Player has leveled to. This will never change like the <code>currentLevel</code>, unless * the Player happens to level up. */ private int level = 1; /** * The amount of experience the player has for this level. */ private double experience = 0; /** * Increments the current level and actual level by the amount specified. * Does not check to see if the level goes over the maximum amount allowed, so * that logic will need to be done elsewhere. * @param amount The amount to increase the current and actual level by. */ public void incrementLevel(int amount) { this.currentLevel = currentLevel + amount; this.level = level + amount; } /** * Increments the current level only, by the amount specified. * @param amount The amount to increase the current level by. */ public void incrementCurrentLevel(int amount) { this.currentLevel = currentLevel + amount; } /** * Increments the experience of this skill. * Does not check to see if it goes over the maximum experience, so that logic will need to * be done elsewhere. * @param amount The amount to increase the experience by. */ public void incrementExperience(double amount) { this.experience = experience + amount; } public void setCurrentLevel(int amount) { this.currentLevel = amount; } public void setLevel(int amount) { this.level = amount; } public void setExperience(double amount) { this.experience = amount; } public int getCurrentLevel() { return this.currentLevel; } public int getLevel() { return this.level; } public double getExperience() { return this.experience; } }
package org.wanholi.erw.excel; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.wanholi.erw.pub.XXML; public class Sheet extends XXML{ String path="xl"+File.separator+"worksheets"+File.separator+"sheet1.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Sheet() throws ParserConfigurationException { super(); DocumentBuilder db = dbf.newDocumentBuilder(); XMLD = db.newDocument(); XMLD.setXmlStandalone(true); root=XMLD.createElement("worksheet"); XMLD.appendChild(root); } void build(){ setAttribute("xmlns", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); setAttribute("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); addElement("dimension").setAttribute("ref", "A1"); Element sheetViews=addElement("sheetViews"); Element sheetView=XMLD.createElement("sheetView"); sheetViews.appendChild(sheetView); sheetView.setAttribute("tabSelected", "1"); sheetView.setAttribute("workbookViewId", "0"); addElement("sheetFormatPr").setAttribute("defaultRowHeight", "15"); addElement("sheetData"); Element pageMargins =addElement("pageMargins"); pageMargins.setAttribute("left", "0.7"); pageMargins.setAttribute("right", "0.7"); pageMargins.setAttribute("top", "0.75"); pageMargins.setAttribute("bottom", "0.75"); pageMargins.setAttribute("header", "0.3"); pageMargins.setAttribute("footer", "0.3"); } }
package uk.co.mtford.jalp; import org.apache.commons.io.FileUtils; import org.apache.log4j.*; import uk.co.mtford.jalp.abduction.AbductiveFramework; import uk.co.mtford.jalp.abduction.Result; import uk.co.mtford.jalp.abduction.logic.instance.*; import uk.co.mtford.jalp.abduction.logic.instance.constraints.ChocoConstraintSolverFacade; import uk.co.mtford.jalp.abduction.logic.instance.constraints.IConstraintInstance; import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance; import uk.co.mtford.jalp.abduction.parse.program.JALPParser; import uk.co.mtford.jalp.abduction.parse.program.ParseException; import uk.co.mtford.jalp.abduction.parse.query.JALPQueryParser; import uk.co.mtford.jalp.abduction.rules.RuleNode; import uk.co.mtford.jalp.abduction.rules.visitor.AbstractRuleNodeVisitor; import uk.co.mtford.jalp.abduction.rules.visitor.EfficientRuleNodeVisitor; import uk.co.mtford.jalp.abduction.rules.visitor.SimpleRuleNodeVisitor; import java.io.*; import java.util.*; /** * Responsible for executing queries on an abductive theory. Used by both the shell and interpreter as well * as with the Java API. * @author Michael Ford */ public class JALPSystem { private static final Logger LOGGER = Logger.getLogger(JALPSystem.class); private AbductiveFramework framework; private static final int MAX_SECONDS = 3; public JALPSystem(AbductiveFramework framework) { this.framework = framework; } public JALPSystem(String fileName) throws FileNotFoundException, ParseException { framework = JALPParser.readFromFile(fileName); } public JALPSystem(String[] fileNames) throws FileNotFoundException, ParseException { setFramework(fileNames); } public JALPSystem() { framework = new AbductiveFramework(); } /** Combines the given framework with the current framework. * * @param newFramework */ public void mergeFramework(AbductiveFramework newFramework) { if (framework == null) { framework = newFramework; } else { framework.getP().addAll(newFramework.getP()); framework.getIC().addAll(newFramework.getIC()); framework.getA().putAll(newFramework.getA()); } } /** Combines the given framework from the file specified with the current framework. * * @param file */ public void mergeFramework(File file) throws FileNotFoundException, ParseException { mergeFramework(JALPParser.readFromFile(file.getPath())); } /** Combines the given framework with the current framework. * * @param program */ public void mergeFramework(String program) throws ParseException { mergeFramework(JALPParser.readFromString(program)); } /** Clears the current abductive framework. * */ private void reset() { framework = new AbductiveFramework(); } public AbductiveFramework getFramework() { return framework; } public void setFramework(AbductiveFramework framework) { this.framework = framework; } public void setFramework(String fileName) throws FileNotFoundException, ParseException { framework = JALPParser.readFromFile(fileName); } public void setFramework(String[] fileName) throws FileNotFoundException, ParseException { for (String f:fileName) { mergeFramework(JALPParser.readFromFile(f)); } } /** For the given query, generates a log file and a visualizer at folderName. * * @param query * @param folderName * @return A list of results that represent abduction explanations. * @throws IOException * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public List<Result> generateDebugFiles(String query, String folderName) throws IOException, uk.co.mtford.jalp.abduction.parse.query.ParseException, InterruptedException { return generateDebugFiles(new LinkedList<IInferableInstance>(JALPQueryParser.readFromString(query)),folderName); } /** For the given query, generates a log file and a visualizer at folderName. * * @param query * @param folderName * @return A list of results that represent abduction explanations. * @throws IOException * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public List<Result> generateDebugFiles(List<IInferableInstance> query, String folderName) throws JALPException, uk.co.mtford.jalp.abduction.parse.query.ParseException, IOException, InterruptedException { File folder = new File(folderName); FileUtils.touch(folder); FileUtils.forceDelete(folder); folder = new File(folderName); Appender R = Logger.getRootLogger().getAppender("R"); Level previousLevel = Logger.getRootLogger().getLevel(); Logger.getRootLogger().removeAppender("R"); Logger.getRootLogger().setLevel(Level.DEBUG); FileAppender newAppender = new DailyRollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n"), folderName+"/log.txt", "'.'dd-MM-yyyy"); newAppender.setName("R"); Logger.getRootLogger().addAppender(newAppender); LOGGER.info("Abductive framework is:\n"+framework); LOGGER.info("Query is:" + query); List<Result> results = new LinkedList<Result>(); RuleNode root = query(query, results); JALP.getVisualizer(folderName + "/visualizer", root); int rNum = 1; LOGGER.info("Found "+results.size()+" results"); for (Result r:results) { LOGGER.info("Result "+rNum+" is\n"+r); rNum++; } Logger.getRootLogger().removeAppender("R"); Logger.getRootLogger().addAppender(R); Logger.getRootLogger().setLevel(previousLevel); return results; } /** Executes query represented by the string e.g. 'p(X)' * * @param query * @return A list of results that represent abduction explanations. * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public List<Result> query(String query) throws uk.co.mtford.jalp.abduction.parse.query.ParseException, InterruptedException { List<Result> results = new LinkedList<Result>(); query(query, results); return results; } /** Executes query e.g. 'p(X)' * * @param query * @return A list of results that represent abduction explanations. * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public List<Result> query(List<IInferableInstance> query) throws InterruptedException { List<Result> results = new LinkedList<Result>(); query(query, results); return results; } /** Executes the query represented by the string and generates result objects in the list. * * @param query * @param results * @return The root node of the derivation tree. * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public RuleNode query(String query, List<Result> results) throws uk.co.mtford.jalp.abduction.parse.query.ParseException, InterruptedException { List<IInferableInstance> queryList = JALPQueryParser.readFromString(query); return query(queryList, results); } /** Executes the query and generates result objects in the list. * * @param query * @param results * @return The root node of the derivation tree. * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public RuleNode query(List<IInferableInstance> query, List<Result> results) throws InterruptedException { try { AbstractRuleNodeVisitor visitor = new SimpleRuleNodeVisitor(); Stack<RuleNode> nodeStack = new Stack<RuleNode>(); List<IInferableInstance> goals = new LinkedList<IInferableInstance>(query); goals.addAll(framework.getIC()); RuleNode rootNode = goals.get(0).getPositiveRootRuleNode(framework,new LinkedList<IInferableInstance>(query),goals); RuleNode currentNode; nodeStack.add(rootNode); int n = 0; while (!nodeStack.isEmpty()) { currentNode = nodeStack.pop(); if (currentNode.getGoals().isEmpty()&&!currentNode.getNodeMark().equals(RuleNode.NodeMark.FAILED)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Found a leaf node!"); } generateResults(rootNode, currentNode, query, results); } else if (currentNode.getNodeMark()==RuleNode.NodeMark.FAILED) { LOGGER.debug("Found a failed node:\n" + currentNode); } else if (currentNode.getNodeMark()==RuleNode.NodeMark.UNEXPANDED) { currentNode.acceptVisitor(visitor); nodeStack.addAll(currentNode.getChildren()); } else { throw new JALPException("Expanded node on the node stack?\n"+currentNode); // Sanity check. } } return rootNode; } catch (StackOverflowError e) { throw new JALPException("Error: Stack overflow detected. Occurs problem?"); } } /** Executes the query represented by the string and generates result objects in the list. Doesn't preserve the * derivation tree and ensures proper garbage collection. * * @param query * @return The root node of the derivation tree. * @throws uk.co.mtford.jalp.abduction.parse.query.ParseException */ public List<Result> efficientQuery(List<IInferableInstance> query) throws InterruptedException { try { List<Result> results = new LinkedList<Result>(); AbstractRuleNodeVisitor visitor = new EfficientRuleNodeVisitor(); Stack<RuleNode> nodeStack = new Stack<RuleNode>(); List<IInferableInstance> goals = new LinkedList<IInferableInstance>(query); goals.addAll(framework.getIC()); RuleNode rootNode = goals.get(0).getPositiveRootRuleNode(framework,new LinkedList<IInferableInstance>(query),goals); RuleNode currentNode; nodeStack.add(rootNode); rootNode = null; // Encourage garbage collect. int n = 0; while (!nodeStack.isEmpty()) { currentNode = nodeStack.pop(); if (currentNode.getGoals().isEmpty()&&!currentNode.getNodeMark().equals(RuleNode.NodeMark.FAILED)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Found a leaf node!"); } generateResults(rootNode, currentNode, query, results); } else if (currentNode.getNodeMark()==RuleNode.NodeMark.FAILED) { LOGGER.debug("Found a failed node:\n" + currentNode); } else if (currentNode.getNodeMark()==RuleNode.NodeMark.UNEXPANDED) { currentNode.acceptVisitor(visitor); nodeStack.addAll(currentNode.getChildren()); } else { throw new JALPException("Expanded node on the node stack?\n"+currentNode); // Sanity check. } } return results; } catch (StackOverflowError e) { throw new JALPException("Error: Stack overflow detected. Occurs problem?"); } } /** Generates result objects. Each result object represents an abductive explanation. * * @param rootNode * @param successNode * @param originalQuery * @param results */ private void generateResults(RuleNode rootNode, RuleNode successNode, List<IInferableInstance> originalQuery, List<Result> results) throws InterruptedException { List<RuleNode> newSuccessNodes = applyConstraintSolver(successNode); for (RuleNode node:newSuccessNodes) { generateResult(rootNode,node,originalQuery,results); } } /** Generates a single result object. * * @param rootNode * @param successNode * @param originalQuery * @param results */ private void generateResult(RuleNode rootNode, RuleNode successNode, List<IInferableInstance> originalQuery, List<Result> results) { Result result = new Result(successNode.getStore(),successNode.getAssignments(),originalQuery,rootNode); results.add(result); } /** * Applys the constraint solver to the given node. * * @param node * @return A list of possible child nodes each one * representing a possible assignment to the constrained variables in the given node. */ private synchronized List<RuleNode> applyConstraintSolver(final RuleNode node) throws InterruptedException { final List<RuleNode> results = new LinkedList<RuleNode>(); Runnable r = new Runnable() { public void run() { if (LOGGER.isDebugEnabled()) LOGGER.debug("Applying constraint solver to ruleNode:\n"+node); List<Map<VariableInstance,IUnifiableInstance>> possibleAssignments; if (node.getStore().constraints.isEmpty()) { possibleAssignments = new LinkedList<Map<VariableInstance, IUnifiableInstance>>(); possibleAssignments.add(node.getAssignments()); if (LOGGER.isDebugEnabled()) LOGGER.debug("No need to apply constraint solver. Returning unmodified node."); } else { LinkedList<IConstraintInstance> constraints = new LinkedList<IConstraintInstance>(); for (IConstraintInstance d:node.getStore().constraints) { IConstraintInstance newConstraint = (IConstraintInstance) d.shallowClone(); newConstraint = (IConstraintInstance) newConstraint.performSubstitutions(node.getAssignments()); // TODO Substitute elsewhere i.e. at each state rewrite. constraints.add(newConstraint); } ChocoConstraintSolverFacade constraintSolver = new ChocoConstraintSolverFacade(); possibleAssignments = constraintSolver.execute(new HashMap<VariableInstance,IUnifiableInstance>(node.getAssignments()),constraints); } if (possibleAssignments.isEmpty()) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Constraint solver failed on rulenode:\n"+node); node.setNodeMark(RuleNode.NodeMark.FAILED); } else { // Constraint solver succeeded. Generate possible children. if (LOGGER.isDebugEnabled()) LOGGER.debug("Constraint solver returned "+possibleAssignments.size()+" results."); node.setNodeMark(RuleNode.NodeMark.EXPANDED); for (Map<VariableInstance,IUnifiableInstance> assignment:possibleAssignments) { RuleNode newLeafNode =node.shallowClone(); newLeafNode.setAssignments(assignment); newLeafNode.applySubstitutions(); newLeafNode.setNodeMark(RuleNode.NodeMark.SUCCEEDED); results.add(newLeafNode); } } } }; Thread t = new Thread(r); t.start(); int n = 0; while (n<MAX_SECONDS) { t.join(1000); n++; if (!t.isAlive()) break; if (n==MAX_SECONDS) { t.stop(); throw new JALPException("Floundering detected."); } } return results; } }
package org.wso2.carbon.identity.recovery.endpoint; import org.wso2.carbon.identity.recovery.endpoint.dto.*; import org.wso2.carbon.identity.recovery.endpoint.CaptchaApiService; import org.wso2.carbon.identity.recovery.endpoint.factories.CaptchaApiServiceFactory; import io.swagger.annotations.ApiParam; import org.wso2.carbon.identity.recovery.endpoint.dto.ErrorDTO; import org.wso2.carbon.identity.recovery.endpoint.dto.ReCaptchaPropertiesDTO; import org.wso2.carbon.identity.recovery.endpoint.dto.ReCaptchaVerificationResponseDTO; import org.wso2.carbon.identity.recovery.endpoint.dto.ReCaptchaResponseTokenDTO; import java.util.List; import java.io.InputStream; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import javax.ws.rs.core.Response; import javax.ws.rs.*; @Path("/captcha") @Consumes({ "application/json" }) @Produces({ "application/json" }) @io.swagger.annotations.Api(value = "/captcha", description = "the captcha API") public class CaptchaApi { private final CaptchaApiService delegate = CaptchaApiServiceFactory.getCaptchaApi(); @GET @Consumes({ "application/json" }) @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "Get Captcha", notes = "return the reCaptcha information if its supported for the given tenant.", response = ReCaptchaPropertiesDTO.class) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Successful response"), @io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request"), @io.swagger.annotations.ApiResponse(code = 500, message = "Server Error") }) public Response getCaptcha(@ApiParam(value = "type of captcha",required=true) @QueryParam("captcha-type") String captchaType, @ApiParam(value = "username recovery or password recovery",required=true) @QueryParam("recovery-type") String recoveryType, @ApiParam(value = "tenant domain. Default `carbon.super`") @QueryParam("tenant-domain") String tenantDomain) { return delegate.getCaptcha(captchaType,recoveryType,tenantDomain); } @POST @Consumes({ "application/json" }) @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "Verify Captcha", notes = "return true or false after verify the captcha response.", response = ReCaptchaVerificationResponseDTO.class) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Successful response"), @io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request"), @io.swagger.annotations.ApiResponse(code = 500, message = "Server Error") }) public Response verifyCaptcha(@ApiParam(value = "recaptcha response from google." ,required=true ) ReCaptchaResponseTokenDTO reCaptchaResponse, @ApiParam(value = "type of captcha",required=true) @QueryParam("captcha-type") String captchaType, @ApiParam(value = "tenant domain. Default `carbon.super`") @QueryParam("tenant-domain") String tenantDomain) { return delegate.verifyCaptcha(reCaptchaResponse,captchaType,tenantDomain); } }
package com.gxjtkyy.standardcloud.common.domain; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; import java.util.List; /** * 分页对象模型 * @Package com.gxjtkyy.domain * @Author lizhenhua * @Date 2018/5/29 15:36 */ @Setter @Getter @ToString public class Page<T> implements Serializable{ /**总记录数*/ private int count; /**页面大小*/ private int pageSize =10; /**当前页*/ private int currentPage =1; /**总页数*/ private int totalPage; /**结果集*/ private List<T> dataList; public int getTotalPage() { if(pageSize > 0){ int totalPages = count / pageSize; return totalPages == 0?1:totalPages; }else { return 1; } } }
package juegovectores; import java.util.Scanner; public class Juegovectores { public static void main(String[] args) { // TODO code application logic here Scanner Entrada=new Scanner(System.in); System.out.print("Ingrese canticad de jugadores "); int x =Entrada.nextInt(); int []juego=new int[x]; int []juego2=new int[x]; int []juego3=new int[x]; int []juego4=new int[x]; System.out.print("*****************************"); System.out.print("=PRIMER INTENTO="); System.out.println("*****************************"); int c=0; for(int i=0;i<x;i++){ c=c+1;//donde c es el numeros de caballos juego[i]=(int)(Math.random()*6)+1; System.out.println("caballo "+c+": "+juego[i]); } System.out.print("*****************************"); System.out.print("=SEGUNDO INTENTO="); System.out.println("*****************************"); int p=0; for(int i=0;i<x;i++){ p=p+1;//donde p es el numeros de caballos juego2[i]=(int)(Math.random()*6)+1; int t2=juego[i]+juego2[i]; System.out.println("caballo "+p+": "+juego2[i]+" + " +juego[i]+ " = "+t2); } System.out.print("*****************************"); System.out.print("=TERCER INTENTO="); System.out.println("*****************************"); int n=0; for(int i=0;i<x;i++){ n=n+1;//donde n es el numeros de caballos juego3[i]=(int)(Math.random()*6)+1; int t3=juego[i]+juego2[i]+juego3[i]; System.out.println("caballo "+n+": "+juego2[i]+" + " +juego[i]+" + " +juego3[i]+ " = "+t3); } System.out.print("*****************************"); System.out.print("=CUARTO INTENTO="); System.out.println("*****************************"); int m=0; for(int i=0;i<x;i++){ m=m+1;//donde m es el numeros de caballos juego4[i]=(int)(Math.random()*6)+1; int t4=juego[i]+juego2[i]+juego3[i]+juego4[i]; System.out.print("caballo "+m+": "+juego2[i]+" + " +juego[i]+" + " +juego3[i]+" + " +juego4[i]+ " = "+t4); if (t4>=20){ System.out.println( " YOU WIN"); }else if(t4<20){ System.out.println( " LOSER"); } } } }
/* * Copyright (c) 2009-2010 Granite Kirill Grouchnikov. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of Granite Kirill Grouchnikov nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.pushingpixels.granite; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.pushingpixels.granite.details.DetailsWindowManager; import org.pushingpixels.trident.Timeline; import org.pushingpixels.trident.swt.SWTRepaintCallback; /** * The close button of the Granite demo. * * @author Kirill Grouchnikov */ public class CloseButton extends Canvas { /** * The alpha value of this button. Is updated in the fade-in timeline which * starts when this button becomes a part of the host window hierarchy. */ int alpha; /** * Creates a new close button. * * @param parent * Parent composite. */ public CloseButton(Composite parent) { super(parent, SWT.TRANSPARENT); this.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE)); this.alpha = 0; this.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { DetailsWindowManager.disposeCurrentlyShowing(); // fade out the main shell and dispose it when it is // at full transparency GraniteUtils.fadeOutAndDispose(getShell(), 500); } }); // timeline for the rollover effect (interpolating the // button's foreground color) final Timeline rolloverTimeline = new Timeline(this); rolloverTimeline.addPropertyToInterpolate("foreground", parent .getDisplay().getSystemColor(SWT.COLOR_WHITE), new Color(parent .getDisplay(), 64, 140, 255)); rolloverTimeline.setDuration(200); // and register a mouse listener to play the rollover // timeline this.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { rolloverTimeline.play(); } @Override public void mouseExit(MouseEvent e) { rolloverTimeline.playReverse(); } }); // fade in the component Timeline shownTimeline = new Timeline(CloseButton.this); shownTimeline.addPropertyToInterpolate("alpha", 0, 255); shownTimeline.addCallback(new SWTRepaintCallback(CloseButton.this)); shownTimeline.setDuration(500); shownTimeline.play(); this.addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { GC gc = e.gc; gc.setAntialias(SWT.ON); // use the current alpha gc.setAlpha(alpha); int width = getBounds().width; int height = getBounds().height; // paint the background - black fill and a dark outline // based on the current foreground color gc .setBackground(gc.getDevice().getSystemColor( SWT.COLOR_BLACK)); gc.fillOval(1, 1, width - 3, height - 3); gc.setLineAttributes(new LineAttributes(2.0f)); Color currFg = getForeground(); int currR = currFg.getRed(); int currG = currFg.getGreen(); int currB = currFg.getBlue(); Color darkerFg = new Color(gc.getDevice(), currR / 2, currG / 2, currB / 2); gc.setForeground(darkerFg); gc.drawOval(1, 1, width - 3, height - 3); darkerFg.dispose(); // paint the outer cross (always white) gc .setForeground(gc.getDevice().getSystemColor( SWT.COLOR_WHITE)); gc.setLineAttributes(new LineAttributes(6.0f, SWT.CAP_ROUND, SWT.JOIN_ROUND)); int offset = width / 3; gc.drawLine(offset, offset, width - offset - 1, height - offset - 1); gc.drawLine(width - offset - 1, offset, offset, height - offset - 1); // paint the inner cross (using the current foreground color) gc.setForeground(currFg); gc.setLineAttributes(new LineAttributes(4.2f, SWT.CAP_ROUND, SWT.JOIN_ROUND)); gc.drawLine(offset, offset, width - offset - 1, height - offset - 1); gc.drawLine(width - offset - 1, offset, offset, height - offset - 1); } }); } /** * Sets the alpha value. Used by the fade-in timeline. * * @param alpha * Alpha value for this button. */ public void setAlpha(int alpha) { this.alpha = alpha; } }
package com.ConfigPoste.RecetteCuisine.RecetteCuisine.services; public class MyFileNotFoundException extends Exception { public MyFileNotFoundException(String s) { super(s); } }
package com.designpatterns.pwdp.strategy; public class SecondOperation implements Strategy { @Override public int doOperation(int x, int y) { return x-y; } }
package com.mycompany.myapp.web.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.mycompany.myapp.IntegrationTest; import com.mycompany.myapp.domain.Proba; import com.mycompany.myapp.repository.ProbaRepository; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link ProbaResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class ProbaResourceIT { private static final String DEFAULT_IME = "AAAAAAAAAA"; private static final String UPDATED_IME = "BBBBBBBBBB"; private static final String ENTITY_API_URL = "/api/probas"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private ProbaRepository probaRepository; @Autowired private EntityManager em; @Autowired private MockMvc restProbaMockMvc; private Proba proba; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Proba createEntity(EntityManager em) { Proba proba = new Proba().ime(DEFAULT_IME); return proba; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Proba createUpdatedEntity(EntityManager em) { Proba proba = new Proba().ime(UPDATED_IME); return proba; } @BeforeEach public void initTest() { proba = createEntity(em); } @Test @Transactional void createProba() throws Exception { int databaseSizeBeforeCreate = probaRepository.findAll().size(); // Create the Proba restProbaMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(proba))) .andExpect(status().isCreated()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeCreate + 1); Proba testProba = probaList.get(probaList.size() - 1); assertThat(testProba.getIme()).isEqualTo(DEFAULT_IME); } @Test @Transactional void createProbaWithExistingId() throws Exception { // Create the Proba with an existing ID proba.setId(1L); int databaseSizeBeforeCreate = probaRepository.findAll().size(); // An entity with an existing ID cannot be created, so this API call must fail restProbaMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(proba))) .andExpect(status().isBadRequest()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional void getAllProbas() throws Exception { // Initialize the database probaRepository.saveAndFlush(proba); // Get all the probaList restProbaMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(proba.getId().intValue()))) .andExpect(jsonPath("$.[*].ime").value(hasItem(DEFAULT_IME))); } @Test @Transactional void getProba() throws Exception { // Initialize the database probaRepository.saveAndFlush(proba); // Get the proba restProbaMockMvc .perform(get(ENTITY_API_URL_ID, proba.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(proba.getId().intValue())) .andExpect(jsonPath("$.ime").value(DEFAULT_IME)); } @Test @Transactional void getNonExistingProba() throws Exception { // Get the proba restProbaMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putNewProba() throws Exception { // Initialize the database probaRepository.saveAndFlush(proba); int databaseSizeBeforeUpdate = probaRepository.findAll().size(); // Update the proba Proba updatedProba = probaRepository.findById(proba.getId()).get(); // Disconnect from session so that the updates on updatedProba are not directly saved in db em.detach(updatedProba); updatedProba.ime(UPDATED_IME); restProbaMockMvc .perform( put(ENTITY_API_URL_ID, updatedProba.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(updatedProba)) ) .andExpect(status().isOk()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); Proba testProba = probaList.get(probaList.size() - 1); assertThat(testProba.getIme()).isEqualTo(UPDATED_IME); } @Test @Transactional void putNonExistingProba() throws Exception { int databaseSizeBeforeUpdate = probaRepository.findAll().size(); proba.setId(count.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restProbaMockMvc .perform( put(ENTITY_API_URL_ID, proba.getId()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(proba)) ) .andExpect(status().isBadRequest()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchProba() throws Exception { int databaseSizeBeforeUpdate = probaRepository.findAll().size(); proba.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restProbaMockMvc .perform( put(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(proba)) ) .andExpect(status().isBadRequest()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamProba() throws Exception { int databaseSizeBeforeUpdate = probaRepository.findAll().size(); proba.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restProbaMockMvc .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(proba))) .andExpect(status().isMethodNotAllowed()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdateProbaWithPatch() throws Exception { // Initialize the database probaRepository.saveAndFlush(proba); int databaseSizeBeforeUpdate = probaRepository.findAll().size(); // Update the proba using partial update Proba partialUpdatedProba = new Proba(); partialUpdatedProba.setId(proba.getId()); partialUpdatedProba.ime(UPDATED_IME); restProbaMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedProba.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedProba)) ) .andExpect(status().isOk()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); Proba testProba = probaList.get(probaList.size() - 1); assertThat(testProba.getIme()).isEqualTo(UPDATED_IME); } @Test @Transactional void fullUpdateProbaWithPatch() throws Exception { // Initialize the database probaRepository.saveAndFlush(proba); int databaseSizeBeforeUpdate = probaRepository.findAll().size(); // Update the proba using partial update Proba partialUpdatedProba = new Proba(); partialUpdatedProba.setId(proba.getId()); partialUpdatedProba.ime(UPDATED_IME); restProbaMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedProba.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedProba)) ) .andExpect(status().isOk()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); Proba testProba = probaList.get(probaList.size() - 1); assertThat(testProba.getIme()).isEqualTo(UPDATED_IME); } @Test @Transactional void patchNonExistingProba() throws Exception { int databaseSizeBeforeUpdate = probaRepository.findAll().size(); proba.setId(count.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restProbaMockMvc .perform( patch(ENTITY_API_URL_ID, proba.getId()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(proba)) ) .andExpect(status().isBadRequest()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchProba() throws Exception { int databaseSizeBeforeUpdate = probaRepository.findAll().size(); proba.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restProbaMockMvc .perform( patch(ENTITY_API_URL_ID, count.incrementAndGet()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(proba)) ) .andExpect(status().isBadRequest()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamProba() throws Exception { int databaseSizeBeforeUpdate = probaRepository.findAll().size(); proba.setId(count.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restProbaMockMvc .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(proba))) .andExpect(status().isMethodNotAllowed()); // Validate the Proba in the database List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void deleteProba() throws Exception { // Initialize the database probaRepository.saveAndFlush(proba); int databaseSizeBeforeDelete = probaRepository.findAll().size(); // Delete the proba restProbaMockMvc .perform(delete(ENTITY_API_URL_ID, proba.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<Proba> probaList = probaRepository.findAll(); assertThat(probaList).hasSize(databaseSizeBeforeDelete - 1); } }
package hu.lamsoft.hms.nutritionist.service.nutritionist.impl; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import hu.lamsoft.hms.common.service.mapper.ModelMapper; import hu.lamsoft.hms.common.service.search.impl.SearchPredicateBuilderContext; import hu.lamsoft.hms.nutritionist.persistence.nutritionist.dao.BlogEntryDao; import hu.lamsoft.hms.nutritionist.service.nutritionist.BlogEntryService; import hu.lamsoft.hms.nutritionist.service.nutritionist.dto.BlogEntryDTO; import hu.lamsoft.hms.nutritionist.service.nutritionist.vo.BlogEntrySearchVO; @Service @Transactional public class BlogEntryServiceImpl implements BlogEntryService { @Autowired private BlogEntryDao blogEntryDao; @Autowired private ModelMapper modelMapper; @Autowired private SearchPredicateBuilderContext searchPredicateBuilderComponent; @Override public Page<BlogEntryDTO> searchBlogEntry(BlogEntrySearchVO blogEntrySearchVO) { return modelMapper.convertToDTO(blogEntryDao.findAll(searchPredicateBuilderComponent.build(blogEntrySearchVO, BlogEntrySearchVO.class), blogEntrySearchVO), BlogEntryDTO.class); } }
public class insertIntoBST { /* You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. */ public static Node insert(Node root, int data) { if (root == null) { return new Node(data); } if (root.data > data) { root.left = insert(root.left, data); } else { root.right = insert(root.right, data); } return root; } }
package io.jrevolt.sysmon.agent; import java.util.Set; /** * @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a> * @version $Id$ */ public class DnsReport { }
package com.trump.auction.activity.service; import com.cf.common.utils.ServiceResult; import com.trump.auction.activity.model.ActivityUserModel; /** * 活动用户相关 * @author wangbo 2018/1/11. */ public interface ActivityUserService { /** * 初始化活动用户 * @param activityUserModel 活动用户信息 * @return 受影响的行数 */ ServiceResult initActivityUser(ActivityUserModel activityUserModel); /** * 根据userId查询活动用户信息 * @param userId 用户id * @return 活动用户信息 */ ActivityUserModel findActivityUserByUserId(Integer userId); /** * 查询用户剩余的免费抽奖次数 * @param userId 用户id * @return 免费抽奖次数 */ int findFreeLotteryTimes(Integer userId); /** * 更新用户的免费抽奖次数 * @param userId 用户id * @param freeLotteryTimes 免费抽奖次数 * @param freeLotteryTimesOld 更新前的免费抽奖次数 * @return ServiceResult */ ServiceResult updateFreeLotteryTimes(Integer userId,int freeLotteryTimes,int freeLotteryTimesOld); }
/** * Copyright (C) Alibaba Cloud Computing, 2012 * All rights reserved. * * 版权所有 (C)阿里巴巴云计算,2012 */ package com.aliyun.oss.common.auth; import static com.aliyun.oss.common.utils.CodingUtils.assertParameterNotNull; /** * 表示用户访问的授权信息。 * */ public class ServiceCredentials { private String accessKeyId; private String accessKeySecret; /** * 获取访问用户的Access Key ID。 * @return Access Key ID。 */ public String getAccessKeyId() { return accessKeyId; } /** * 设置访问用户的Access ID。 * @param accessKeyId * Access Key ID。 */ public void setAccessKeyId(String accessKeyId) { assertParameterNotNull(accessKeyId, "accessKeyId"); this.accessKeyId = accessKeyId; } /** * 获取访问用户的Access Key Secret。 * @return Access Key Secret。 */ public String getAccessKeySecret() { return accessKeySecret; } /** * 设置访问用户的Access Key Secret。 * @param accessKeySecret * Access Key Secret。 */ public void setAccessKeySecret(String accessKeySecret) { assertParameterNotNull(accessKeySecret, "accessKeySecret"); this.accessKeySecret = accessKeySecret; } /** * 构造函数。 */ public ServiceCredentials(){ } /** * 构造函数。 * @param accessKeyId * Access Key ID。 * @param accessKeySecret * Access Key Secret。 * @exception NullPointerException accessKeyId或accessKeySecret为空指针。 */ public ServiceCredentials(String accessKeyId, String accessKeySecret){ setAccessKeyId(accessKeyId); setAccessKeySecret(accessKeySecret); } }
package io.github.satr.aws.lambda.bookstore.ask.handlers; // Copyright © 2020, github.com/satr, MIT License import io.github.satr.aws.lambda.bookstore.services.ServiceFactory; import io.github.satr.aws.lambda.bookstore.strategies.intenthandler.IntentHandlerStrategyFactory; import org.slf4j.Logger; public class AskRequestHandlerFactory { private final Logger logger; private final IntentHandlerStrategyFactory intentHandlerStrategyFactory; public AskRequestHandlerFactory(ServiceFactory serviceFactory, Logger logger) { intentHandlerStrategyFactory = new IntentHandlerStrategyFactory(serviceFactory.getBookStorageService(), serviceFactory.getSearchBookResultService(), serviceFactory.getBasketService()); this.logger = logger; } public GeneralAskRequestHandler getRequestHandlerFor(String intentName) { return new GeneralAskRequestHandler(intentHandlerStrategyFactory, intentName, logger); } public NotRecognizedAskIntentHandler getNotRecognizedIntentHandler() { return new NotRecognizedAskIntentHandler(logger); } }
package com.core.common; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.http.HttpException; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 17-9-9 * Time: 上午9:43 * To change this template use File | Settings | File Templates. */ public class GetDataUtil { // 构造一个缓存管理器 public static ConcurrentHashMap<String, Object> dkCacheManager = new ConcurrentHashMap<String, Object>(); /** * dk缓存机制 * @param url * @return */ public static JSONArray getData(String url) throws HttpException, IOException, URISyntaxException { SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date=new Date(); String nowDate=sf.format(date); JSONArray dataSource=new JSONArray(); //缓存里面的取取url,只要重复的url就从缓存里面取 JSONObject cache = (JSONObject) dkCacheManager.get(url); if (cache != null) { // 如果在缓存中,则直接返回缓存的结果 //如果缓存中, //超过15分钟的缓存清空 String history=cache.getString("time"); try { if(sf.parse(nowDate).getTime()>sf.parse(history).getTime()&&(sf.parse(nowDate).getTime()-sf.parse(history).getTime())>15*60000){ dkCacheManager.remove(url);//删除缓存,从数据库直接查找 String jsonStr = HttpClientHelper.httpClientGet(url); if (jsonStr != null) dataSource = JSONUtil.strToArr(jsonStr); if(dataSource!=null&&dataSource.size()>0){ JSONObject jsonObject=new JSONObject(); jsonObject.put("time",nowDate); jsonObject.put("data",dataSource); dkCacheManager.put(url, jsonObject); return dataSource; } }else{ return cache.getJSONArray("data"); } } catch (ParseException e) { e.printStackTrace(); } return dataSource; } else { // 否则到数据库中查询 String jsonStr = HttpClientHelper.httpClientGet(url); if (jsonStr != null) dataSource = JSONUtil.strToArr(jsonStr); if(dataSource!=null&&dataSource.size()>0){ JSONObject jsonObject=new JSONObject(); jsonObject.put("time",nowDate); jsonObject.put("data",dataSource); dkCacheManager.put(url, jsonObject); // 将数据库查询的结果更新到缓存中 } return dataSource; } } public static void clearCache(){ dkCacheManager.clear(); } }
package com.seven.contract.manage.service.impl; import com.seven.contract.manage.dao.LabelDao; import com.seven.contract.manage.model.Label; import com.seven.contract.manage.service.LabelService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Transactional(rollbackFor = Exception.class) public class LabelServiceImpl implements LabelService { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private LabelDao labelDao; public int addLabel(long mid, String labelName) { Map<String, Object> params = new HashMap<>(); params.put("mid", mid); params.put("labelName", labelName); List<Label> labels = labelDao.selectList(params); if (labels.size() > 0) { return labels.get(0).getId(); } else { Label label = new Label(); label.setMid(mid); label.setLabelName(labelName); label.setAddTime(new Date()); labelDao.insert(label); return label.getId(); } } public void updateLabel(Label label){ labelDao.update(label); } public void deleteById(long id) { labelDao.deleteById(id); } public Label selectOneById(long id) { Label label = labelDao.selectOne(id); return label; } @Override public List<Label> selectList(Map<String, Object> params) { return labelDao.selectList(params); } }
package it.greenvulcano.util.remotefs.hdfs.utility; public interface HDFSParamsKey { public String deleteSource = "dfs.file.delete-source"; public String useRawLocalFileSystem = "dfs.file.raw-local-filesystem"; public String bufferSize = "dfs.stream-buffer-size"; public String overwrite = "dfs.file.overwrite"; public String permission = "dfs.permissions.path"; public String replication = "dfs.replication"; public String blockSize = "dfs.blocksize"; public String ownerUserName = "dfs.permissions.user"; public String ownerGroupName = "dfs.permissions.group"; }
package java.com.eq.domain.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; /** * TextFilterModel */ public class TextFilterModel implements FilterModel { private String fieldName = null; @JsonProperty("type") private TypeEnum type = null; @JsonProperty("filter") private String filter = null; public String getFieldName() { return fieldName; } public TextFilterModel setFieldName(String fieldName) { this.fieldName = fieldName; return this; } public TextFilterModel fieldName(String fieldName) { this.fieldName = fieldName; return this; } public TextFilterModel type(TypeEnum type) { this.type = type; return this; } /** * The filter type. The type of text filter to apply. One of [&#39;equals&#39;, &#39;notEqual&#39;, &#39;contains&#39;, &#39;notContains&#39;, &#39;startsWith&#39;, &#39;endsWith&#39;]. * * @return type **/ @JsonProperty("type") public TypeEnum getType() { return type; } public void setType(TypeEnum type) { this.type = type; } public TextFilterModel filter(String filter) { this.filter = filter; return this; } /** * The actual filter number to apply, or the start of the range if the filter type is inRange. * * @return filter **/ @JsonProperty("filter") public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } /** * The filter type. The type of text filter to apply. One of [&#39;equals&#39;, &#39;notEqual&#39;, &#39;contains&#39;, &#39;notContains&#39;, &#39;startsWith&#39;, &#39;endsWith&#39;]. */ public enum TypeEnum { EQUALS("equals"), NOTEQUAL("notEqual"), CONTAINS("contains"), NOTCONTAINS("notContains"), STARTSWITH("startsWith"), ENDSWITH("endsWith"); private String value; TypeEnum(String value) { this.value = value; } @JsonCreator public static TypeEnum fromValue(String text) { for (TypeEnum b : TypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } @Override @JsonValue public String toString() { return String.valueOf(value); } } }
package singletonDPpackage; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class testStaticGlobalSetting { @Test void testVisibility() { //System.out.println(); // StaticGlobalSettings have a private constructor // cannot instantiate an object StaticGlobalSettings gs1StaticSingleton = new StaticGlobalSettings(); // The constructor StaticGlobalSettings() is not visible // No Clone method provided. } }
package concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class FutureDemo { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); testNormal(3, 3, 5); // testAsynchronous(3, 3, 5); System.out.printf("Elapsed time: %d seconds\n", (System.currentTimeMillis() - start) / 1000); } private static void testNormal(int s1, int s2, int s3) { String r1 = doLongTask(s1); String r2 = doLongTask(s2); String r3 = doLongTask(s3); System.out.println(r1); System.out.println(r2); System.out.println(r3); } private static void testAsynchronous(int s1, int s2, int s3) throws InterruptedException, ExecutionException { int poolSize = 3; // try to change it to 1 ExecutorService executor = Executors.newFixedThreadPool(poolSize); // Kick of multiple, asynchronous lookups Future<String> r1 = executor.submit(() -> { return doLongTask(s1); }); Future<String> r2 = executor.submit(() -> { return doLongTask(s2); }); Future<String> r3 = executor.submit(() -> { return doLongTask(s3); }); // Wait until they are all done // Sometimes we even don't need following code (because Future.get will block main thread) while (!(r1.isDone() && r2.isDone() && r3.isDone())) { Thread.sleep(10); // 10-millisecond pause between each check } // Get return values System.out.println(r1.get()); System.out.println(r2.get()); System.out.println(r3.get()); // Executors have to be stopped explicitly // otherwise they keep listening for new tasks executor.shutdown(); } private static String doLongTask(int second) { try { Thread.sleep(1000 * second); return "Finish after " + second + " second"; } catch (InterruptedException ex) { return null; } } }
/* * Copyright 2002-2022 the original author or authors. * * 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 * * https://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.springframework.orm.jpa.support; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.function.BiConsumer; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.beans.testfixture.beans.TestBeanWithPackagePrivateField; import org.springframework.beans.testfixture.beans.TestBeanWithPackagePrivateMethod; import org.springframework.beans.testfixture.beans.TestBeanWithPrivateMethod; import org.springframework.beans.testfixture.beans.TestBeanWithPublicField; import org.springframework.core.test.tools.CompileWithForkedClassLoader; import org.springframework.core.test.tools.Compiled; import org.springframework.core.test.tools.TestCompiler; import org.springframework.javapoet.ClassName; import org.springframework.javapoet.CodeBlock; import org.springframework.javapoet.JavaFile; import org.springframework.javapoet.MethodSpec; import org.springframework.javapoet.ParameterizedTypeName; import org.springframework.javapoet.TypeSpec; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InjectionCodeGenerator}. * * @author Phillip Webb */ class InjectionCodeGeneratorTests { private static final String INSTANCE_VARIABLE = "instance"; private static final ClassName TEST_TARGET = ClassName.get("com.example", "Test"); private final RuntimeHints hints = new RuntimeHints(); @Test void generateCodeWhenPublicFieldInjectsValue() { TestBeanWithPublicField bean = new TestBeanWithPublicField(); Field field = ReflectionUtils.findField(bean.getClass(), "age"); ClassName targetClassName = TEST_TARGET; CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( field, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBeanWithPublicField.class, (actual, compiled) -> { TestBeanWithPublicField instance = new TestBeanWithPublicField(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("instance.age = 123"); }); } @Test @CompileWithForkedClassLoader void generateCodeWhenPackagePrivateFieldInTargetPackageInjectsValue() { TestBeanWithPackagePrivateField bean = new TestBeanWithPackagePrivateField(); Field field = ReflectionUtils.findField(bean.getClass(), "age"); ClassName targetClassName = ClassName.get(TestBeanWithPackagePrivateField.class.getPackageName(), "Test"); CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( field, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBeanWithPackagePrivateField.class, (actual, compiled) -> { TestBeanWithPackagePrivateField instance = new TestBeanWithPackagePrivateField(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("instance.age = 123"); }); } @Test void generateCodeWhenPackagePrivateFieldInAnotherPackageUsesReflection() { TestBeanWithPackagePrivateField bean = new TestBeanWithPackagePrivateField(); Field field = ReflectionUtils.findField(bean.getClass(), "age"); ClassName targetClassName = TEST_TARGET; CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( field, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBeanWithPackagePrivateField.class, (actual, compiled) -> { TestBeanWithPackagePrivateField instance = new TestBeanWithPackagePrivateField(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("setField("); }); } @Test void generateCodeWhenPrivateFieldInjectsValueUsingReflection() { TestBean bean = new TestBean(); Field field = ReflectionUtils.findField(bean.getClass(), "age"); ClassName targetClassName = ClassName.get(TestBean.class); CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( field, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBean.class, (actual, compiled) -> { TestBean instance = new TestBean(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("setField("); }); } @Test void generateCodeWhenPrivateFieldAddsHint() { TestBean bean = new TestBean(); Field field = ReflectionUtils.findField(bean.getClass(), "age"); createGenerator(TEST_TARGET).generateInjectionCode( field, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); assertThat(RuntimeHintsPredicates.reflection().onField(TestBean.class, "age")) .accepts(this.hints); } @Test void generateCodeWhenPublicMethodInjectsValue() { TestBean bean = new TestBean(); Method method = ReflectionUtils.findMethod(bean.getClass(), "setAge", int.class); ClassName targetClassName = TEST_TARGET; CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( method, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBean.class, (actual, compiled) -> { TestBean instance = new TestBean(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("instance.setAge("); }); } @Test @CompileWithForkedClassLoader void generateCodeWhenPackagePrivateMethodInTargetPackageInjectsValue() { TestBeanWithPackagePrivateMethod bean = new TestBeanWithPackagePrivateMethod(); Method method = ReflectionUtils.findMethod(bean.getClass(), "setAge", int.class); ClassName targetClassName = ClassName.get(TestBeanWithPackagePrivateMethod.class); CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( method, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBeanWithPackagePrivateMethod.class, (actual, compiled) -> { TestBeanWithPackagePrivateMethod instance = new TestBeanWithPackagePrivateMethod(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("instance.setAge("); }); } @Test void generateCodeWhenPackagePrivateMethodInAnotherPackageUsesReflection() { TestBeanWithPackagePrivateMethod bean = new TestBeanWithPackagePrivateMethod(); Method method = ReflectionUtils.findMethod(bean.getClass(), "setAge", int.class); ClassName targetClassName = TEST_TARGET; CodeBlock generatedCode = createGenerator(targetClassName).generateInjectionCode( method, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBeanWithPackagePrivateMethod.class, (actual, compiled) -> { TestBeanWithPackagePrivateMethod instance = new TestBeanWithPackagePrivateMethod(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("invokeMethod("); }); } @Test void generateCodeWhenPrivateMethodInjectsValueUsingReflection() { TestBeanWithPrivateMethod bean = new TestBeanWithPrivateMethod(); Method method = ReflectionUtils.findMethod(bean.getClass(), "setAge", int.class); ClassName targetClassName = ClassName.get(TestBeanWithPrivateMethod.class); CodeBlock generatedCode = createGenerator(targetClassName) .generateInjectionCode(method, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); testCompiledResult(targetClassName, generatedCode, TestBeanWithPrivateMethod.class, (actual, compiled) -> { TestBeanWithPrivateMethod instance = new TestBeanWithPrivateMethod(); actual.accept(instance); assertThat(instance).extracting("age").isEqualTo(123); assertThat(compiled.getSourceFile()).contains("invokeMethod("); }); } @Test void generateCodeWhenPrivateMethodAddsHint() { TestBeanWithPrivateMethod bean = new TestBeanWithPrivateMethod(); Method method = ReflectionUtils.findMethod(bean.getClass(), "setAge", int.class); createGenerator(TEST_TARGET).generateInjectionCode( method, INSTANCE_VARIABLE, CodeBlock.of("$L", 123)); assertThat(RuntimeHintsPredicates.reflection() .onMethod(TestBeanWithPrivateMethod.class, "setAge").invoke()).accepts(this.hints); } private InjectionCodeGenerator createGenerator(ClassName target) { return new InjectionCodeGenerator(target, this.hints); } @SuppressWarnings("unchecked") private <T> void testCompiledResult(ClassName generatedClasName, CodeBlock generatedCode, Class<T> target, BiConsumer<Consumer<T>, Compiled> result) { JavaFile javaFile = createJavaFile(generatedClasName, generatedCode, target); TestCompiler.forSystem().compile(javaFile::writeTo, compiled -> result.accept(compiled.getInstance(Consumer.class), compiled)); } private JavaFile createJavaFile(ClassName generatedClasName, CodeBlock generatedCode, Class<?> target) { TypeSpec.Builder builder = TypeSpec.classBuilder(generatedClasName.simpleName() + "__Injector"); builder.addModifiers(Modifier.PUBLIC); builder.addSuperinterface(ParameterizedTypeName.get(Consumer.class, target)); builder.addMethod(MethodSpec.methodBuilder("accept").addModifiers(Modifier.PUBLIC) .addParameter(target, INSTANCE_VARIABLE).addCode(generatedCode).build()); return JavaFile.builder(generatedClasName.packageName(), builder.build()).build(); } }
package org.abrahamalarcon.datastream.dom.response; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; public class BaseResponse implements Serializable { BaseError baseError; @JsonProperty("error") public BaseError getError() { return baseError; } public void setError(BaseError baseError) { this.baseError = baseError; } @JsonIgnore public boolean isFailure() { if(baseError != null && (baseError.getCode() != null || baseError.getFieldErrors() != null || baseError.getMessage() != null)) { return true; } return false; } }
package com.edasaki.rpg.spells; import java.util.function.IntToDoubleFunction; import com.edasaki.rpg.spells.alchemist.Bomb; import com.edasaki.rpg.spells.alchemist.Gravitron; import com.edasaki.rpg.spells.alchemist.HeatWall; import com.edasaki.rpg.spells.alchemist.Minefield; import com.edasaki.rpg.spells.alchemist.MysteryDrink; import com.edasaki.rpg.spells.alchemist.Transmute; public class SpellbookAlchemist extends Spellbook { public static final Spell BOMB = new Spell("Bomb", 2, 10, 1, 0, "Throw a bomb that explodes after 1 second, dealing %.0f%% damage to nearby enemies.", new IntToDoubleFunction[] { (x) -> { return 150 + 20 * x; } }, null, new Bomb()); public static final Spell GRAVITRON = new Spell("Gravitron", 3, 5, 2, 0, "Throw a gravity device that pulls in enemies towards it every second for %.0f seconds.", new IntToDoubleFunction[] { (x) -> { return 1 + x; } }, new Object[] { BOMB, 2 }, new Gravitron()); public static final Spell HEAT_WALL = new Spell("Heat Wall", 4, 10, 2, 1, "Throw a heat wall device that creates flame pulses for 3 seconds dealing %.0f%% damage per second.", new IntToDoubleFunction[] { (x) -> { return 125 + 25 * x; } }, new Object[] { BOMB, 3 }, new HeatWall()); public static final Spell MINEFIELD = new Spell("Minefield", 8, 15, 1, 1, "Scatter %.0f mines randomly around you, exploding for %.0f%% damage if activated by a nearby enemy.", new IntToDoubleFunction[] { (x) -> { if (x <= 5) return 3; else if (x <= 10) return 4; else return 5; }, (x) -> { return 120 + 10 * x; } }, new Object[] { BOMB, 6 }, new Minefield()); public static final Spell TRANSMUTE = new Spell("Transmute", 1, 6, 3, 0, "Convert your HP to mana, losing %.0f%% of your maximum HP in exchange for %.0f Mana. The 1 Mana spell cost is also refunded.", new IntToDoubleFunction[] { (x) -> { return 30 - 2 * x; }, (x) -> { if (x <= 2) return 2; else if (x <= 4) return 3; else return 4; } }, null, new Transmute()); public static final Spell MYSTERY_DRINK = new Spell("Mystery Drink", 4, 3, 3, 1, new String[] { "Consume a mystery elixir that gives you and nearby party members a random buff for 5 seconds.", "Consume a mystery elixir that gives you and nearby party members a random buff for 7 seconds.", "Consume a mystery elixir that gives you and nearby party members a random buff for 11 seconds.", }, null, new MysteryDrink()); public static final Spell SPEEDY_BREWER = new Spell("Speedy Brewer", 0, 3, 1, 8, new String[] { "Increase your attack speed by 10%.", "Increase your attack speed by 20%.", "Increase your attack speed by 30%.", }, null, new PassiveSpellEffect()); public static final Spell POTION_MASTERY = new Spell("Potion Mastery", 0, 5, 2, 8, new String[] { "Gain +10% healing from consumable healing potions.", "Gain +20% healing from consumable healing potions.", "Gain +30% healing from consumable healing potions.", "Gain +40% healing from consumable healing potions.", "Gain +50% healing from consumable healing potions.", }, null, new PassiveSpellEffect()); private static final Spell[] SPELL_LIST = { BOMB, MINEFIELD, GRAVITRON, HEAT_WALL, /*QUICK_SMOKE,*/ TRANSMUTE, MYSTERY_DRINK, SPEEDY_BREWER, POTION_MASTERY }; // DON'T FORGET TO ADD TO SPELL_LIST public static final Spellbook INSTANCE = new SpellbookAlchemist(); @Override public Spell[] getSpellList() { return SPELL_LIST; } }
package github.dwstanle.tickets.model; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity @Getter @Setter @RequiredArgsConstructor public class Account { @Id @GeneratedValue private Long id; @NonNull @Column(unique=true) private String email; //JPA construction only private Account() { } }
package com.prenevin.application.service.api ; import com.prenevin.library.crud.service.api.BaseCrudService; import com.prenevin.application.domain.Person; public interface PersonService extends BaseCrudService<Person> { }
package com.flyusoft.apps.jointoil.entity; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "FLY_TWO_SCREW_MACHINE") public class TwoScrewMachine extends CompressorMD { private Double oilPressure;// 机油压力, private Double exhaustPressure;// 排气压力, private Double outScrewTemperature1;//螺杆出气温度1 private Double outScrewTemperature2;//螺杆出气温度2 private String compressorCode;// 压缩机的编码, public Double getOilPressure() { return oilPressure; } public void setOilPressure(Double oilPressure) { this.oilPressure = oilPressure; } public Double getExhaustPressure() { return exhaustPressure; } public void setExhaustPressure(Double exhaustPressure) { this.exhaustPressure = exhaustPressure; } public String getCompressorCode() { return compressorCode; } public void setCompressorCode(String compressorCode) { this.compressorCode = compressorCode; } public Double getOutScrewTemperature1() { return outScrewTemperature1; } public void setOutScrewTemperature1(Double outScrewTemperature1) { this.outScrewTemperature1 = outScrewTemperature1; } public Double getOutScrewTemperature2() { return outScrewTemperature2; } public void setOutScrewTemperature2(Double outScrewTemperature2) { this.outScrewTemperature2 = outScrewTemperature2; } }
package com.db.retail.exception; /** * Error codes to be thrown along with exception * @author RD00488188 * */ public enum ErrorCodes { UNKNOWN_ERROR("system error"), NO_SHOP_IN_THE_SYSTEM("no shop is available in the system"), INSUFFICIENT_SHOP_INFO("mandatory shop info missing in input request"), INSUFFICIENT_GEO_INFO("latitude/longitude missing"), INVALID_ADDRESS("address not found"), GEOCODE_TEMP_ERROR("unable to fetch geocode, please try later"), GEOCODE_FETCH_ERROR("unable to fetch geocode"); private String errorMsg; private ErrorCodes(String errorMsg) { this.errorMsg = errorMsg; } public String getErrorMsg() { return errorMsg; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.scheduling.annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import io.micrometer.observation.ObservationRegistry; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Flowable; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupport.createSubscriptionRunnable; import static org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupport.getPublisherFor; import static org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupport.isReactive; /** * @author Simon Baslé * @since 6.1 */ class ScheduledAnnotationReactiveSupportTests { @Test void ensureReactor() { assertThat(ScheduledAnnotationReactiveSupport.reactorPresent).isTrue(); } @ParameterizedTest // Note: monoWithParams can't be found by this test. @ValueSource(strings = { "mono", "flux", "monoString", "fluxString", "publisherMono", "publisherString", "monoThrows", "flowable", "completable" }) void checkIsReactive(String method) { Method m = ReflectionUtils.findMethod(ReactiveMethods.class, method); assertThat(isReactive(m)).as(m.getName()).isTrue(); } @Test void checkNotReactive() { Method string = ReflectionUtils.findMethod(ReactiveMethods.class, "oops"); assertThat(isReactive(string)).as("String-returning").isFalse(); } @Test void rejectReactiveAdaptableButNotDeferred() { Method future = ReflectionUtils.findMethod(ReactiveMethods.class, "future"); assertThatIllegalArgumentException().isThrownBy(() -> isReactive(future)) .withMessage("Reactive methods may only be annotated with @Scheduled if the return type supports deferred execution"); } @Test void isReactiveRejectsWithParams() { Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "monoWithParam", String.class); // isReactive rejects with context assertThatIllegalArgumentException().isThrownBy(() -> isReactive(m)) .withMessage("Reactive methods may only be annotated with @Scheduled if declared without arguments") .withNoCause(); } @Test void rejectCantProducePublisher() { ReactiveMethods target = new ReactiveMethods(); Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "monoThrows"); // static helper method assertThatIllegalArgumentException().isThrownBy(() -> getPublisherFor(m, target)) .withMessage("Cannot obtain a Publisher-convertible value from the @Scheduled reactive method") .withCause(new IllegalStateException("expected")); } @Test void rejectCantAccessMethod() { ReactiveMethods target = new ReactiveMethods(); Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "monoThrowsIllegalAccess"); // static helper method assertThatIllegalArgumentException().isThrownBy(() -> getPublisherFor(m, target)) .withMessage("Cannot obtain a Publisher-convertible value from the @Scheduled reactive method") .withCause(new IllegalAccessException("expected")); } @Test void fixedDelayIsBlocking() { ReactiveMethods target = new ReactiveMethods(); Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono"); Scheduled fixedDelayString = AnnotationUtils.synthesizeAnnotation(Map.of("fixedDelayString", "123"), Scheduled.class, null); Scheduled fixedDelayLong = AnnotationUtils.synthesizeAnnotation(Map.of("fixedDelay", 123L), Scheduled.class, null); List<Runnable> tracker = new ArrayList<>(); assertThat(createSubscriptionRunnable(m, target, fixedDelayString, () -> ObservationRegistry.NOOP, tracker)) .isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr -> assertThat(sr.shouldBlock).as("fixedDelayString.shouldBlock").isTrue() ); assertThat(createSubscriptionRunnable(m, target, fixedDelayLong, () -> ObservationRegistry.NOOP, tracker)) .isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr -> assertThat(sr.shouldBlock).as("fixedDelayLong.shouldBlock").isTrue() ); } @Test void fixedRateIsNotBlocking() { ReactiveMethods target = new ReactiveMethods(); Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono"); Scheduled fixedRateString = AnnotationUtils.synthesizeAnnotation(Map.of("fixedRateString", "123"), Scheduled.class, null); Scheduled fixedRateLong = AnnotationUtils.synthesizeAnnotation(Map.of("fixedRate", 123L), Scheduled.class, null); List<Runnable> tracker = new ArrayList<>(); assertThat(createSubscriptionRunnable(m, target, fixedRateString, () -> ObservationRegistry.NOOP, tracker)) .isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr -> assertThat(sr.shouldBlock).as("fixedRateString.shouldBlock").isFalse() ); assertThat(createSubscriptionRunnable(m, target, fixedRateLong, () -> ObservationRegistry.NOOP, tracker)) .isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr -> assertThat(sr.shouldBlock).as("fixedRateLong.shouldBlock").isFalse() ); } @Test void cronIsNotBlocking() { ReactiveMethods target = new ReactiveMethods(); Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono"); Scheduled cron = AnnotationUtils.synthesizeAnnotation(Map.of("cron", "-"), Scheduled.class, null); List<Runnable> tracker = new ArrayList<>(); assertThat(createSubscriptionRunnable(m, target, cron, () -> ObservationRegistry.NOOP, tracker)) .isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr -> assertThat(sr.shouldBlock).as("cron.shouldBlock").isFalse() ); } @Test void hasCheckpointToString() { ReactiveMethods target = new ReactiveMethods(); Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono"); Publisher<?> p = getPublisherFor(m, target); assertThat(p.getClass().getName()) .as("checkpoint class") .isEqualTo("reactor.core.publisher.FluxOnAssembly"); assertThat(p).hasToString("checkpoint(\"@Scheduled 'mono()' in 'org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupportTests$ReactiveMethods'\")"); } static class ReactiveMethods { public String oops() { return "oops"; } public Mono<Void> mono() { return Mono.empty(); } public Flux<Void> flux() { return Flux.empty(); } public Mono<String> monoString() { return Mono.just("example"); } public Flux<String> fluxString() { return Flux.just("example"); } public Publisher<Void> publisherMono() { return Mono.empty(); } public Publisher<String> publisherString() { return fluxString(); } public CompletableFuture<String> future() { return CompletableFuture.completedFuture("example"); } public Mono<Void> monoWithParam(String param) { return Mono.just(param).then(); } public Mono<Void> monoThrows() { throw new IllegalStateException("expected"); } public Mono<Void> monoThrowsIllegalAccess() throws IllegalAccessException { // simulate a reflection issue throw new IllegalAccessException("expected"); } public Flowable<Void> flowable() { return Flowable.empty(); } public Completable completable() { return Completable.complete(); } AtomicInteger subscription = new AtomicInteger(); public Mono<Void> trackingMono() { return Mono.<Void>empty().doOnSubscribe(s -> subscription.incrementAndGet()); } public Mono<Void> monoError() { return Mono.error(new IllegalStateException("expected")); } } }
package ro.ase.csie.g1093.testpractice.command; import java.util.ArrayList; public class TaskManager { ArrayList<TaskAsyncAbstract> tasks = new ArrayList<>(); public void adaugaTask(TaskAsyncAbstract task) { tasks.add(task); } public void executaTask() { if(this.tasks.size() > 0) { TaskAsyncAbstract task = tasks.get(0); tasks.remove(0); task.executaTask(1000); } } }
package pageTests; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import pageObjects.FlightResultPage; import pageObjects.FlightHomePage; import seleniumTests.BaseTestUsingTestNG; public class FlightHomePageTest extends BaseTestUsingTestNG { FlightHomePage flightHomePage; FlightResultPage flightResultPage; //@Test(description="User is presented at flight tab when go to flight home page.") public void Verify_Page_Title_And_User_Is_Presented_At_Flight_Tab_In_Flight_Home_Page() { flightHomePage = new FlightHomePage(driver); Assert.assertTrue(flightHomePage.VerifyFlightHomePageTitle()); Assert.assertTrue(flightHomePage.VerifyUserIsPresentFlightTab()); } @Test(description="User can search for flight after entering destination, depart date, return date") public void Verify_User_Can_Search_For_Flight() { String strDestination = "Ho Chi Minh City, Vietnam - Tan Son Nhat International [SGN]"; String strDepartDate = "15/11/2018"; String strReturnDate = "16/12/2018"; flightHomePage = new FlightHomePage(driver); flightHomePage.UserEnterFlightDestination(strDestination); flightHomePage.UserPickDepartDate(strDepartDate); flightHomePage.UserPickReturnDate(strReturnDate); flightResultPage = flightHomePage.UserClickSearchFlightAndGoToFlightResultPage(); Assert.assertTrue(flightResultPage.VerifySearchFareModalDialogExist(), "Search modal dialog is not exist, please recheck"); Assert.assertTrue(flightResultPage.VerifySearchCheapestFaresText(), "Search cheapest fare text is not exist, please recheck"); } @Test(description="User can select different business class before searching for a flight") public void Verify_User_Can_Select_Different_Business_Class() { flightHomePage = new FlightHomePage(driver); flightHomePage.UserClickOnFlightClassComboBox(); Assert.assertTrue(flightHomePage.VerifyBusinessClassComboBox()); } @Test(description="User can see passenger type before searching for a flight") public void Verify_User_Can_Select_Different_Passenger_Type() { flightHomePage = new FlightHomePage(driver); flightHomePage.UserClickOnPassengerComboBox(); Assert.assertTrue(flightHomePage.VerifyPassengerComboBox()); } @Test (description="User will see validation errors when clicking on search flight button") public void Verify_User_Is_Present_With_Validation_Errors() { flightHomePage = new FlightHomePage(driver); Assert.assertTrue(driver.getTitle().contains("Cheap Flights, Airfare, and Hotels - FlightHub.com")); flightResultPage = flightHomePage.UserClickSearchFlightAndGoToFlightResultPage(); List<String> results = flightHomePage.GetValidationErrors(); Assert.assertEquals(results.get(0), "Please select a destination city."); Assert.assertEquals(results.get(1), "Please select a departure date."); Assert.assertEquals(results.get(2), "Please select a return date."); } @Test(description="User can search choose a depart and return date for the flight") public void TestDatePicker() { String strDestination = "Ho Chi Minh City, Vietnam - Tan Son Nhat International [SGN]"; String strDepartDate = "24/4/2019"; String strReturnDate = "16/4/2020"; flightHomePage = new FlightHomePage(driver); flightHomePage.UserEnterFlightDestination(strDestination); flightHomePage.UserPickDepartDate(strDepartDate); flightHomePage.UserPickReturnDate(strReturnDate); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.melodygram.model; import java.io.Serializable; import java.util.Comparator; import java.util.Random; import android.graphics.Bitmap; /** * Created by LALIT on 15-06-2016. */ public class ContactsModel implements Serializable { public static final int aItem = 0; public static final int aSection = 1; public int getSectionType() { return sectionType; } public void setSectionType(int sectionType) { this.sectionType = sectionType; } public int getSectionData() { return sectionData; } public void setSectionData(int sectionData) { this.sectionData = sectionData; } public String getSectionText() { return sectionText; } public void setSectionText(String sectionText) { this.sectionText = sectionText; } public int sectionType, sectionData; public String sectionText; String phContactId, phContactName, phContactNumber, appContactName, phContactLabel, phChatContactStatus, phContactPicPath, lastSeen, contactType, contactServerName, avtarName, gender, mute, profilePicPrivacy, lastSeenPrivacy, statusPrivacy, onlinePrivacy, readReceiptsPrivacy, muteGame, notification, buzzControl, muteChat; public String getPhContactPicPath() { return phContactPicPath; } public String getContactServerName() { return contactServerName; } public void setContactServerName(String contactServerName) { this.contactServerName = contactServerName; } public void setPhContactPicPath(String phContactPicPath) { this.phContactPicPath = phContactPicPath; } public String getPhChatContactStatus() { return phChatContactStatus; } public void setPhChatContactStatus(String phChatContactStatus) { this.phChatContactStatus = phChatContactStatus; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } Bitmap contactPicBitmap; public Bitmap getContactPicBitmap() { return contactPicBitmap; } public void setContactPicBitmap(Bitmap contactPicBitmap) { this.contactPicBitmap = contactPicBitmap; } public String getPhContactId() { return phContactId; } public void setPhContactId(String phContactId) { this.phContactId = phContactId; } public String getPhContactName() { return phContactName; } public void setPhContactName(String phContactName) { this.phContactName = phContactName; } public String getPhContactNumber() { return phContactNumber; } public void setAppContactName(String appContactName) { this.appContactName = appContactName; } public String getAppContactNumber() { return appContactName; } public void setPhContactNumber(String phContactNumber) { this.phContactNumber = phContactNumber; } public String getPhContactLabel() { return phContactLabel; } public void setPhContactLabel(String phContactLabel) { this.phContactLabel = phContactLabel; } public static Comparator<ContactsModel> compareByName = new Comparator<ContactsModel>() { public int compare(ContactsModel one, ContactsModel other) { return one.getPhContactName().compareToIgnoreCase( other.getPhContactName()); } }; String appContactsUserId, appContactsCountry, appContactsCountryCode, appContactsStatus, appContactsProfilePic; String[] appContactsPicArray; public String getAppContactsUserId() { return appContactsUserId; } public void setAppContactsUserId(String appContactsUserId) { this.appContactsUserId = appContactsUserId; } public String getAppContactsCountry() { return appContactsCountry; } public void setAppContactsCountry(String appContactsCountry) { this.appContactsCountry = appContactsCountry; } public String getAppContactsCountryCode() { return appContactsCountryCode; } public void setAppContactsCountryCode(String appContactsCountryCode) { this.appContactsCountryCode = appContactsCountryCode; } public String getAppContactsStatus() { return appContactsStatus; } public void setAppContactsStatus(String appContactsStatus) { this.appContactsStatus = appContactsStatus; } public String getAppContactsProfilePic() { return appContactsProfilePic; } public void setAppContactsProfilePic(String appContactsProfilePic) { this.appContactsProfilePic = appContactsProfilePic; } public String getAppContactsPicArray() { String str = ""; for (int i = 0; i < appContactsPicArray.length; i++) { str = str + appContactsPicArray[i] + ","; } str = str.substring(0, str.lastIndexOf(",")); return str; } public void setAppContactsPicArray(String[] arr) { this.appContactsPicArray = arr; } public String getAppContactsRandomPics() { Random r = new Random(); int max = appContactsPicArray.length; int index = r.nextInt(max) + 0; return appContactsPicArray[index]; } public String getAppContactsZeroIndexPic() { return appContactsPicArray[0]; } String chatType, contactsRoomId, fromLanguage, toLanguage, countryCode, isPrivate, blocked, isBlocked, timeStamp; public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public String getChatType() { return chatType; } public void setChatType(String chatType) { this.chatType = chatType; } public String getContactsRoomId() { return contactsRoomId; } public void setContactsRoomId(String contactsRoomId) { this.contactsRoomId = contactsRoomId; } public String getContactsLastSeen() { return lastSeen; } public void setContactsLastSeen(String lastSeen) { this.lastSeen = lastSeen; } public String getContactType() { return contactType; } public void setContactType(String contactType) { this.contactType = contactType; } public String getPrivateType() { return isPrivate; } public void setPrivateType(String isPrivate) { this.isPrivate = isPrivate; } public String getBlocked() { return blocked; } public void setBlocked(String blocked) { this.blocked = blocked; } public String getIsBlocked() { return isBlocked; } public void setIsBlocked(String isBlocked) { this.isBlocked = isBlocked; } public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public String getAvtarName() { return avtarName; } public void setAvtarName(String avtarName) { this.avtarName = avtarName; } public String getMute() { return mute; } public void setMute(String mute) { this.mute = mute; } public String getProfilePicPrivacy() { return profilePicPrivacy; } public void setProfilePicPrivacy(String profilePicPrivacy) { this.profilePicPrivacy = profilePicPrivacy; } public String getLastSeenPrivacy() { return lastSeenPrivacy; } public void setLastSeenPrivacy(String lastSeenPrivacy) { this.lastSeenPrivacy = lastSeenPrivacy; } public String getStatusPrivacy() { return statusPrivacy; } public void setStatusPrivacy(String statusPrivacy) { this.statusPrivacy = statusPrivacy; } public String getOnlinePrivacy() { return onlinePrivacy; } public void setOnlinePrivacy(String onlinePrivacy) { this.onlinePrivacy = onlinePrivacy; } public String getReadReceiptsPrivacy() { return readReceiptsPrivacy; } public String getMuteGame() { return muteGame; } public String getNotification() { return notification; } public void setNotification(String notification) { this.notification = notification; } public String getBuzzControl() { return buzzControl; } public void setBuzzControl(String buzzControl) { this.buzzControl = buzzControl; } public String getMuteChat() { return muteChat; } public void setMuteChat(String muteChat) { this.muteChat = muteChat; } }
package com.programapprentice.app; /** * User: program-apprentice * Date: 8/8/15 * Time: 5:22 PM */ public class StrStr_28 { // brute force solution public int strStr(String haystack, String needle) { if(needle.length() == 0) { return 0; } if(needle.length() > haystack.length() || needle.length() == 0) { return -1; } for(int i = 0; i < haystack.length(); i++) { for(int j = 0; j < needle.length(); j++) { if(i + j >= haystack.length()) { return -1; } if(haystack.charAt(i+j) != needle.charAt(j)) { break; } else { if(j == needle.length()-1) { return i; } } } } return -1; } }
package com.tw; import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match; import java.io.*; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Library { // private Test_Class add=new Test_Class(); public boolean someLibraryMethod() { return true; } private List<StudentInfo> members = new ArrayList<>();//保存学生信息 public void mainPrint() { //主界面输出 System.out.println("1.添加学生"); System.out.println("2.生成成绩单"); System.out.println("3.退出"); System.out.println("请输入你的选择(1~3):"); } public int getGrade(String str) { //获得字符串中的学生成绩 int result=-1; String[] tmp; if(str.contains(":")){ tmp = str.split(":"); result =Integer.parseInt(tmp[1]);} return result; } public Boolean addStudent(String tmp) { //添加学生信息 Boolean result; //String regx = "[\\u4e00-\\u9fa5]+,[0-9]+(,[\\u4e00-\\u9fa5]+:[1-9][0-9]){4}"; //正则 String regx = "[\\u4e00-\\u9fa5]+,[0-9]+,数学:[1-9][0-9],语文:[1-9][0-9],英语:[1-9][0-9],编程:[1-9][0-9]"; //正则 Pattern p = Pattern.compile(regx); Matcher m = p.matcher(tmp); if (m.matches()) { //输入匹配则提取信息,创建学生类,保存数据 String name; int id = 0, math, chinese, english, coding; String[] pname = tmp.split(","); name = pname[0]; id = Integer.parseInt(pname[1]); math = getGrade(pname[2]); chinese = getGrade(pname[3]); english = getGrade(pname[4]); coding = getGrade(pname[5]); StudentInfo addStudent = new StudentInfo(name, id, math, chinese, english, coding); members.add(addStudent); //保存学生信息 result=true; System.out.println("学生" + pname[0] + "的成绩被添加"); } else { System.out.println("请按正确的格式输入(格式:姓名, 学号, 学科: 成绩, ...):"); result=false; // add.addStudents(); } return result; } public Boolean printGrade(String id) { //打印学生成绩 Boolean result=false; String rgx = "[0-9]+(,([0-9]+))?"; Pattern p = Pattern.compile(rgx); Matcher m = p.matcher(id); if (m.matches()) { int all_sum = 0, count = 1, sum; List<Integer> middle = new ArrayList<>(); String[] tmpv; tmpv = id.split(","); System.out.println("成绩单\n" + "姓名|数学|语文|英语|编程|平均分|总分"); System.out.println("========================"); for (int i = 0; i < tmpv.length; i++) { //过滤学生成绩 for (int j = 0; j < members.size(); j++) { if (Integer.parseInt(tmpv[i]) == members.get(j).getId()) { count += 1; sum = members.get(j).getMath() + members.get(j).getChinese() + members.get(j).getEnglish() + members.get(j).getCoding(); middle.add(sum); all_sum += sum; System.out.println(members.get(j).getName() + "|" + members.get(j).getMath() + "|" + members.get(j).getChinese() + "|" + members.get(j).getEnglish() + "|" + members.get(j).getCoding() + "|" + sum / 4 + "|" + sum); } } } System.out.println("========================"); if(middle.size()!=0){ System.out.println("全班总分平均数:" + all_sum / count); System.out.println("全班总分中位数:" + calculate(middle)); } result =true; } else { System.out.println("请按正确的格式输入要打印的学生的学号(格式: 学号, 学号,...),按回车提交:"); result=false; } return result; } public int calculate(List<Integer> sum) { //计算中位数 int result=0; if(sum.size()%2==0) { int tmp; tmp= sum.stream().sorted(Comparator.naturalOrder()) .skip(sum.size()/2-1) .limit(2) .reduce(Integer::sum).get(); result=tmp/2; } else { if (sum.size()>1){ result=sum.stream() .sorted(Comparator.naturalOrder()) .skip(sum.size()/2+1) .limit(1) .findFirst() .get(); } else { result=sum.get(0); } } return result; } }
package uk.co.onehp.btcirl; import uk.co.onehp.btcirl.domain.Transaction; public interface IrlService { void setIrl(Transaction transaction, int place); }
import org.junit.Test; import static org.junit.Assert.assertArrayEquals;; public class SolutionTest { @Test public void test() { char c = 'e'; String s = "loveleetcode"; int[] sol = {3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0}; assertArrayEquals(sol, new Solution().shortestToChar(s,c)); } }
package se.arvidbodkth.laboration2; import android.content.Context; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * @author Jonas Wåhslén, jwi@kth.se. * Revised by Anders Lindström, anderslm@kth.se * * Modifyed by Arvid Bodin and Mattias Grehning. */ /* * The game board positions 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 * */ public class NineMenMorrisRules implements Serializable { private int[] gameplan; private int bluemarker, redmarker; private int turn; // player in turn public static final int BLUE_MOVES = 1; public static final int RED_MOVES = 2; public static final int EMPTY_SPACE = 0; public static final int BLUE_MARKER = 4; public static final int RED_MARKER = 5; private boolean canRemove; /** * Constructor of the model. Creates the array of ints * that represents the places on the gameBoard. Also the * number of markers foe each player, the starting turn. */ public NineMenMorrisRules() { gameplan = new int[25]; // zeroes bluemarker = 9; redmarker = 9; turn = RED_MOVES; canRemove = false; } /** * Returns true if a move is successful */ public boolean legalMove(int To, int From, int color) { //System.out.println("To: " + To + " From: " + From); if (color == turn) { if (turn == RED_MOVES) { if (redmarker > 0) { if (gameplan[To] == EMPTY_SPACE) { gameplan[To] = RED_MARKER; redmarker--; return true; } } /*else*/ if (gameplan[To] == EMPTY_SPACE) { if (isValidMove(To, From)) { gameplan[To] = RED_MARKER; clearSpace(From, RED_MARKER); return true; } else { return false; } } else { return false; } } else { if (bluemarker > 0) { if (gameplan[To] == EMPTY_SPACE) { gameplan[To] = BLUE_MARKER; bluemarker--; return true; } } if (gameplan[To] == EMPTY_SPACE) { if (isValidMove(To, From)) { gameplan[To] = BLUE_MARKER; clearSpace(From, BLUE_MARKER); return true; } else { return false; } } else { return false; } } } else { return false; } } /** * Returns true if position "to" is part of three in a row. */ public boolean remove(int to) { boolean remove = false; if ((to == 7 || to == 8 || to == 9) && gameplan[7] == gameplan[8] && gameplan[8] == gameplan[9]) { remove = true; } else if ((to == 4 || to == 5 || to == 6) && gameplan[4] == gameplan[5] && gameplan[5] == gameplan[6]) { remove = true; } else if ((to == 1 || to == 2 || to == 3) && gameplan[1] == gameplan[2] && gameplan[2] == gameplan[3]) { remove = true; } else if ((to == 9 || to == 13 || to == 18) && gameplan[9] == gameplan[13] && gameplan[13] == gameplan[18]) { remove = true; } else if ((to == 6 || to == 14 || to == 21) && gameplan[6] == gameplan[14] && gameplan[14] == gameplan[21]) { remove = true; } else if ((to == 3 || to == 15 || to == 24) && gameplan[3] == gameplan[15] && gameplan[15] == gameplan[24]) { remove = true; } else if ((to == 16 || to == 17 || to == 18) && gameplan[16] == gameplan[17] && gameplan[17] == gameplan[18]) { remove = true; } else if ((to == 19 || to == 20 || to == 21) && gameplan[19] == gameplan[20] && gameplan[20] == gameplan[21]) { remove = true; } else if ((to == 22 || to == 23 || to == 24) && gameplan[22] == gameplan[23] && gameplan[23] == gameplan[24]) { remove = true; } else if ((to == 7 || to == 12 || to == 16) && gameplan[7] == gameplan[12] && gameplan[12] == gameplan[16]) { remove = true; } else if ((to == 4 || to == 11 || to == 19) && gameplan[4] == gameplan[11] && gameplan[11] == gameplan[19]) { remove = true; } else if ((to == 1 || to == 10 || to == 22) && gameplan[1] == gameplan[10] && gameplan[10] == gameplan[22]) { remove = true; } else if ((to == 12 || to == 11 || to == 10) && gameplan[12] == gameplan[11] && gameplan[11] == gameplan[10]) { remove = true; } else if ((to == 2 || to == 5 || to == 8) && gameplan[2] == gameplan[5] && gameplan[5] == gameplan[8]) { remove = true; } else if ((to == 13 || to == 14 || to == 15) && gameplan[13] == gameplan[14] && gameplan[14] == gameplan[15]) { remove = true; } else if ((to == 17 || to == 20 || to == 23) && gameplan[17] == gameplan[20] && gameplan[20] == gameplan[23]) { remove = true; } return remove; } /** * Request to remove a marker for the selected player. * Returns true if the marker where successfully removed */ public boolean clearSpace(int From, int color) { if (canRemove) { if (color != turn && color != EMPTY_SPACE && !remove(From)) { gameplan[From] = EMPTY_SPACE; canRemove = false; return true; } else { return false; } } if (gameplan[From] == color) { gameplan[From] = EMPTY_SPACE; return true; } else { return false; } } /** * Returns true if the selected player have less than three markers left. */ public boolean win(int color) { int countMarker = 0; int count = 0; while (count < 25) { if (gameplan[count] != EMPTY_SPACE && gameplan[count] != color) countMarker++; count++; } return bluemarker <= 0 && redmarker <= 0 && countMarker < 3; } /** * Returns the bord array. * @return gamePlan[] */ public int[] getBoard() { return gameplan; } /** * Return the color of a given poition. * @param pos the position to get the color of. * @return the color. */ public int getColorOfPos(int pos) { return gameplan[pos - 1]; } /** * Get the color of the marker of the current turn. * @param turn the turn to get color of. * @return color. */ public int getMarkerColor(int turn) { if (turn == BLUE_MOVES) return BLUE_MARKER; if (turn == RED_MOVES) return RED_MARKER; else return 0; } /** * Get the current turn. * @return turn */ public int getTurn() { return turn; } /** * Set the turn to the next turn. */ public void nextTurn() { if (turn == BLUE_MOVES) turn = RED_MOVES; else turn = BLUE_MOVES; } /** * Get teh last turn. * @return the last turn. */ public int getLastTurn() { if (turn == BLUE_MOVES) return RED_MOVES; else return BLUE_MOVES; } /** * Get the number of the remaining markers of a given * player. * @param color the color of the player. * @return number of markers left. */ public boolean markersLeft(int color) { return color == BLUE_MOVES && bluemarker > 0 || color == RED_MOVES && redmarker > 0; } /** * Check whether this is a legal move. */ private boolean isValidMove(int to, int from) { if (this.gameplan[to] != EMPTY_SPACE) return false; switch (to) { case 1: return (from == 2 || from == 10); case 2: return (from == 5 || from == 3 || from == 1); case 3: return (from == 15 || from == 2); case 4: return (from == 11 || from == 5); case 5: return (from == 2 || from == 4 || from == 6 || from == 8); case 6: return (from == 5 || from == 14); case 7: return (from == 8 || from == 12); case 8: return (from == 5 || from == 7 || from == 9); case 9: return (from == 13 || from == 8); case 10: return (from == 1 || from == 22 || from == 11); case 11: return (from == 4 || from == 12 || from == 19 || from == 10); case 12: return (from == 7 || from == 16 || from == 11); case 13: return (from == 9 || from == 18 || from == 14); case 14: return (from == 21 || from == 6 || from == 15 || from == 13); case 15: return (from == 14 || from == 3 || from == 24); case 16: return (from == 12 || from == 17); case 17: return (from == 16 || from == 20 || from == 18); case 18: return (from == 17 || from == 13); case 19: return (from == 11 || from == 20); case 20: return (from == 19 || from == 23 || from == 17 || from == 21); case 21: return (from == 14 || from == 20); case 22: return (from == 10 || from == 23); case 23: return (from == 22 || from == 20 || from == 24); case 24: return (from == 15 || from == 23); } return false; } /** * Get if a piece can be removed. * @return can be removed. */ public boolean getCanRemove() { return canRemove; } /** * Set if a piece can be removed. * @param canRemove if it can be removed. */ public void setCanRemove(boolean canRemove) { this.canRemove = canRemove; } /** * Get the number of markers left of the current turn * @return number of markers left. */ public int getNoOfMarkers() { if (turn == RED_MOVES) return redmarker; else return bluemarker; } /** * Get a string with the ints in the gamePlan. * @return string with gamePlan. */ public String toString() { String gameplanString = ""; for (int i = 0; i < gameplan.length; i++) { gameplanString += gameplan[i]; if (i < 24) gameplanString += ", "; } return gameplanString; } /** * Get the string of the current turn. * @return string of the current turn. */ public String turnToString() { if (turn == RED_MOVES) return "Red"; else return "Blue"; } /** * Load a file from a set file name. * @param context the context * @return the read object * @throws IOException * @throws ClassNotFoundException */ public Object readFile(Context context) throws IOException, ClassNotFoundException { FileInputStream fileIn = context.openFileInput("state"); ObjectInputStream in = new ObjectInputStream(fileIn); return in.readObject(); } /** * Write the model to a set file. * @param context the context * @param state the state used to save the model. * @throws IOException */ public void writeFile(Context context, State state) throws IOException { FileOutputStream fileOut = context.openFileOutput("state", Context.MODE_PRIVATE); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(state); out.close(); fileOut.close(); } }
package espm_algoritmos.lista_exerc2; import java.util.Scanner; public class Exerc03_a { public static void main(String[] args) { double x, y; Scanner sentinela = new Scanner(System.in); System.out.print("Insira o valor de 'x': "); x = sentinela.nextDouble(); System.out.print("Insira o valor de 'y': "); y = sentinela.nextDouble(); if (x > y) { y = x * y; System.out.printf("Novo valor: y = %.2f", y); } else { System.out.println("O valor de 'x' não é maior que o de 'y'."); } sentinela.close(); } }
package com.xrlj.configserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.config.server.EnableConfigServer; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableEurekaClient @EnableDiscoveryClient @EnableConfigServer // 开启配置中心功能 @SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class}) public class ConfigServerApplication { private final static Logger log = LoggerFactory.getLogger(ConfigServerApplication.class); public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); log.info(">>>>>服务{}启动成功:{}", ConfigServerApplication.class.getSimpleName(), args); } }
package com.uchain.core; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.Maps; import com.uchain.common.Serializabler; import com.uchain.cryptohash.Crypto; import com.uchain.cryptohash.Fixed8; import com.uchain.cryptohash.UInt160; import com.uchain.cryptohash.UInt256; import com.uchain.util.Utils; import lombok.Getter; import lombok.Setter; import lombok.val; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Iterator; import java.util.Map; @Getter @Setter public class Account implements Identifier<UInt160> { private boolean active; // 账户状态 private String name; //12字符串名字 private Map<UInt256, Fixed8> balances; //UInt256资产类型,Fixed8资产余额 private Long nextNonce; // 每发起一笔交易,增加1 private int version; // 预留 @JsonIgnore private UInt160 id; // // private byte[] codeHash; //合约代码的Hash值 public Account(boolean active, String name, Map<UInt256, Fixed8> balances, long nextNonce, int version, UInt160 id) { this.name = name; this.active = active; this.balances = balances; this.nextNonce = nextNonce; this.version = version; this.id = id; } public Fixed8 getBalance(UInt256 assetID) { Iterator<UInt256> assetIds = balances.keySet().iterator(); while (assetIds.hasNext()) { UInt256 id = assetIds.next(); if (assetID.equals(id)) { return balances.get(id); } } return Fixed8.Zero; } public void updateBalance(UInt256 assetID, Fixed8 value) { Iterator<UInt256> assetIds = balances.keySet().iterator(); while (assetIds.hasNext()) { UInt256 id = assetIds.next(); if (assetID.equals(id)) { Fixed8 before = balances.get(id); Fixed8 after = before.add(value); balances.put(id, after); return; } } balances.put(assetID, value); } private void serializeExcludeId(DataOutputStream os) { Map<UInt256, Fixed8> map = Maps.newLinkedHashMap(); try { os.writeInt(version); os.writeBoolean(active); Serializabler.writeString(os, name); balances.forEach((key, value) -> { map.put(key, value); }); Serializabler.writeMap(os, map); os.writeLong(nextNonce); } catch (IOException e) { e.printStackTrace(); } } @Override public void serialize(DataOutputStream os) { serializeExcludeId(os); Serializabler.write(os, id()); } private UInt160 genId() { val bs = new ByteArrayOutputStream(); val os = new DataOutputStream(bs); serializeExcludeId(os); return UInt160.fromBytes(Crypto.hash160(bs.toByteArray())); } public static Account deserialize(DataInputStream is) { try { val version = is.readInt(); val active = is.readBoolean(); val name = Serializabler.readString(is); Map<UInt256, Fixed8> balances = readMap(is); val nextNonce = is.readLong(); val id = UInt160.deserialize(is); return new Account(active, name, balances, nextNonce, version, id); } catch (IOException e) { e.printStackTrace(); } return null; } public static Map<UInt256, Fixed8> readMap(DataInputStream is) throws IOException { Map<UInt256, Fixed8> map = Maps.newLinkedHashMap(); val size = Utils.readVarInt(is); for (int i = 1; i <= size; i++) { map.put(UInt256.deserialize(is), Fixed8.deserialize(is)); } return map; } @Override public UInt160 id() { if (id == null) { id = genId(); } return id; } @JsonProperty("id") public String idJson() { return id.toAddressString(); } public void IncNonce() { nextNonce += 1; } public Account withIncrementedNonce() { this.nextNonce = this.nextNonce + 1; return this; } public Account withNonce(Long nextNonce) { this.nextNonce = nextNonce; return this; } public boolean isEmpty() { // return FastByteComparisons.equal(codeHash, EMPTY_DATA_HASH) && // BigInteger.ZERO.equals(balance) && // BigInteger.ZERO.equals(nonce); return false; } public Account(BigInteger nonce, Map<UInt256, Fixed8> frombalances, UInt160 id) { this(true, "", frombalances, nonce.longValue(), 0x01, id); } // public boolean isContractExist() { // return !FastByteComparisons.equal(codeHash, EMPTY_DATA_HASH); // } public Account withBalanceIncrement(UInt256 assetID, BigInteger value) { Fixed8 fixed8Value = new Fixed8(value); if (balances.get(assetID) == null) { balances.put(assetID, fixed8Value); } else { balances.put(assetID, balances.get(assetID).add(fixed8Value)); } return this; } }
package com.example.sourabh.bookmyticket; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.sourabh.bookmyticket.R; /** * Created by Sourabh on 07-02-2017. */ public class MyListAdapter extends ArrayAdapter<String>{ private final Activity context; private final String[] film; private final Integer[] progImages; public MyListAdapter(Activity context,String[] film,Integer[] progImages) { super(context, R.layout.activity_image_list,film); this.context=context; this.film=film; this.progImages=progImages; } @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater inflater=context.getLayoutInflater(); View rowview = inflater.inflate(R.layout.activity_imgete,null,true); TextView txtTitle=(TextView)rowview.findViewById(R.id.textView1); ImageView imageView=(ImageView)rowview.findViewById(R.id.imageView1); txtTitle.setText(film[position]); Button btn=(Button)rowview.findViewById(R.id.button3); imageView.setImageResource(progImages[position]); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(context,Main5Activity.class); i.putExtra("U",film[position]); context.startActivity(i); } }); return rowview; } }
package com.test.billing.dao; import com.test.billing.dao.mapper.BalanceHistoryMapper; import com.test.billing.dao.model.BalanceHistory; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; /** * Created by denis.medvedev on 09.08.2016. */ @RegisterMapper(BalanceHistoryMapper.class) public interface BalanceHistoryDAO { @SqlUpdate("create table balance_history (history_id bigint, balance_id bigint, old_value float, new_value float, cre_date timestamp without time zone)") void createBalanceHistoryTable(); @SqlUpdate("drop table balance_history") void dropBalanceHistoryTable(); @SqlQuery("select * from balance_history where balance_id = :balance_id") public BalanceHistory getBalanceHistoryByBalanceId(@Bind("balance_id") Long balance_id); @SqlUpdate("insert into balance_history (history_id, balance_id, old_value, new_value, cre_date) values (:historyId, :balanceId, :oldValue, :newValue, :creDate)") void insert(@BindBean BalanceHistory balanceHistory); @SqlUpdate("update balance_history set old_value=:oldValue, new_value=:newValue, cre_date=:creDate where history_id=:historyId") void update(@BindBean BalanceHistory balanceHistory); }