text
stringlengths
10
2.72M
package com.example.csc207app; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import type.Nurse; import type.Patient; import type.PatientDataBase; import account.LoginAccount; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.TextView; /** The second activity. */ public class OperationActivity extends Activity { // The file with all of the Patient's info. public static final String FILENAME = "patientdata.txt"; // The PatientDataBase that holds and record all of the info private PatientDataBase database; // The Patient with info and is sent to the text file private Patient patient; @Override /** * The button that takes all of the info from the text field * and transfers them to other classes in order to create Patient. * This gives them attributes such as * Name, ID, DOB, Vital Signs and symptoms */ // Modified from the lecture notes protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_operation); // Gets the intent passed to it by MainActivity. Intent intent = getIntent(); // Gets the Nurse object from the intent. database = (PatientDataBase) intent.getSerializableExtra("databaseKey"); String accountNumber = (String) intent .getSerializableExtra("accountNumberKey"); // Sets the TextView to the name of Person person. } @Override // Modified from the lecture notes public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.operation, menu); return true; } /** * Chooses a certain Patient and allows the edit of the Patient's * attributes. It reads the data from patientdata.txt and modifies a certain * Patient object. * * @param view * A user interface component */ public void loadPatient(View view) { Intent intent = getIntent(); // Gets the account number from the first EditText field. EditText cardNumberText = (EditText) findViewById(R.id.patient_number_field1); String cardNumber = cardNumberText.getText().toString(); Patient patient = database.getPatientByCardNumber(cardNumber); // Saves all Persons managed by manager to file. if (patient != null) { // If the patient is empty intent = new Intent(this, UpdateActivity.class); // Adds the three main components that is needed to create Patient intent.putExtra("patientKey", patient); intent.putExtra("cardNumberKey", cardNumber); intent.putExtra("databaseKey", database); startActivity(intent); } else { String pushInfo = "Cannot find this patient!"; } } /** * When the button is pressed it creates a Patient given the Healthcard ID, * Name, and DOB. It can then be used to modify the vital signs and/or * symptoms * * @param view * A user interface component */ public void addPatient(View view) { // Gets the account number from the first EditText field. EditText cardNumberText = (EditText) findViewById(R.id.patient_number_field2); String cardNumber = cardNumberText.getText().toString(); // Gets the patient name from the second EditText field. EditText patientNameText = (EditText) findViewById(R.id.patient_name_field); String patientName = patientNameText.getText().toString(); // Gets the DOB from the third EditText field. EditText dobText = (EditText) findViewById(R.id.dob_field); String dob = dobText.getText().toString(); // Creates a new Patient with the given info patient = new Patient(cardNumber, patientName, dob, Calendar.getInstance()); if (patient != null) { database.addNewPatient(cardNumber, patient); // Saves all Persons managed by manager to file. String pushInfo = "New patient added!"; // Sets the TextView to the name of Person person. } } /** * Once the info for the Patient is given with the vital signs, the Nurse * can logout of the triage application whilst adding all of the information * of the Patient to patientdata.txt * * @param view * A user interface component */ public void logOut(View view) { if (database != null) try { FileOutputStream outputStream; outputStream = openFileOutput(FILENAME, 0); database.saveToFile(outputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
package com.elizeire.codecatas; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early * to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens * with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter * strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block in a * direction and you know it takes you one minute to traverse one city block, so create a function that will * return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) * and will, of course, return you to your starting point. Return false otherwise. * <p> * Note: you will always receive a valid array containing a random assortment of direction * letters ('n', 's', 'e', or 'w' only). * It will never give you an empty array (that's not a walk, that's standing still!). */ public class TenMinWalkTest { private TenMinWalk tenMinWalk = new TenMinWalk(); @Test public void Test() { assertEquals("Should return true", true, TenMinWalk.isValid(new char[]{'n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 's'})); assertEquals("Should return false", false, TenMinWalk.isValid(new char[]{'w', 'e', 'w', 'e', 'w', 'e', 'w', 'e', 'w', 'e', 'w', 'e'})); assertEquals("Should return false", false, TenMinWalk.isValid(new char[]{'w'})); assertEquals("Should return false", false, TenMinWalk.isValid(new char[]{'n', 'n', 'n', 's', 'n', 's', 'n', 's', 'n', 's'})); } }
package com.yixin.kepler.dto; import java.io.Serializable; /** * 接口返回值对象 * @author sukang * * @param <T> */ public class RespMessageDTO<T extends Object> implements Serializable{ private static final long serialVersionUID = 1L; private T data; private String errorMessage; private boolean hasErrors; public static <T> RespMessageDTO<T> getInstance(Class<T> clazz){ return new RespMessageDTO<T>(); } public RespMessageDTO<T> success(){ this.setHasErrors(false); this.setErrorMessage("success"); return this; } public RespMessageDTO<T> fail(String failMsg){ this.setHasErrors(true); this.setErrorMessage(failMsg); return this; } public RespMessageDTO<T> hashErrors(boolean hasError){ this.setHasErrors(hasError); return this; } public RespMessageDTO<T> errorMessage(String errorMessage){ this.setErrorMessage(errorMessage); return this; } public RespMessageDTO<T> data(T data){ this.setData(data); return this; } private RespMessageDTO(){} public T getData() { return data; } public void setData(T data) { this.data = data; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public boolean isHasErrors() { return hasErrors; } public void setHasErrors(boolean hasErrors) { this.hasErrors = hasErrors; } @Override public String toString() { return "RespMessageDTO [data=" + data + ", errorMessage=" + errorMessage + ", hasErrors=" + hasErrors + "]"; } }
package com.example.ashvant.stock; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; /** * Created by ashvant on 11/26/17. */ public class CurrentStockAdapter extends ArrayAdapter<StockDetailData> { private static ArrayList<StockDetailData> currentDetails = new ArrayList<StockDetailData>(); public CurrentStockAdapter(Context context, ArrayList<StockDetailData> resource) { super(context,0,resource); this.currentDetails = resource; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { StockDetailData currentItem = currentDetails.get(position); View listItemView = convertView; if(listItemView==null){ listItemView = LayoutInflater.from(getContext()).inflate(R.layout.stock_detail_list_row,parent,false); } TextView header = (TextView)listItemView.findViewById(R.id.detail); header.setText(currentItem.getHeader()); TextView value = (TextView)listItemView.findViewById(R.id.value); value.setText(currentItem.getValue()); ImageView upDown = (ImageView)listItemView.findViewById(R.id.imageView); upDown.setImageDrawable(currentItem.getFlag()); return listItemView; } }
package com.xkzhangsan.time.holiday; import com.xkzhangsan.time.LunarDate; import com.xkzhangsan.time.constants.Constant; import com.xkzhangsan.time.converter.DateTimeConverterUtil; import com.xkzhangsan.time.formatter.DateTimeFormatterUtil; import com.xkzhangsan.time.utils.CollectionUtil; import com.xkzhangsan.time.utils.StringUtil; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.MonthDay; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAdjusters; import java.util.Date; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; /** * 节日处理<br> * 包含<br> * 1.公历节假日计算, getLocalHoliday* 比如getLocalHoliday(Date date) 计算date的公历节日,{@code getLocalHoliday(Date date, Map<String, String> localHolidayMap)} 可以传入自定义公历节日数据<br> * 2.农历节假日计算, getChineseHoliday* 比如getChineseHoliday(Date date) 计算date的农历节日,{@code getChineseHoliday(Date date, Map<String, String> chineseHolidayMap)} 可以传入自定义农历节日数据<br> * 3.二十四节气计算, getSolarTerm* 比如getSolarTerm(Date date) 计算date的二十四节气<br> * * 农历相关,仅支持公历1900-2100年的计算,使用{@link LunarDate}<br> * @author xkzhangsan */ public interface Holiday { /** * 根据日期获取公历节日 * @param date 日期 * @return String */ static String getLocalHoliday(Date date){ return getLocalHoliday(date, null); } /** * 根据日期获取公历节日 * @param date 日期 * @param localHolidayMap 自定义节日数据,特殊节日如,"母亲节", "5-W-2-7" 5表示5月,W表示星期,2表示第二个星期,7表示星期的第7天 * @return String */ static String getLocalHoliday(Date date, Map<String, String> localHolidayMap){ Objects.requireNonNull(date, "date"); return getLocalHoliday(DateTimeConverterUtil.toLocalDateTime(date), localHolidayMap); } /** * 根据日期获取公历节日 * @param temporal 支持 LocalDate、LocalDateTime、Instant和ZonedDateTime * @return String */ static String getLocalHoliday(Temporal temporal){ return getLocalHoliday(temporal, null); } /** * 根据日期获取公历节日 * @param temporal 支持 LocalDate、LocalDateTime、Instant和ZonedDateTime * @param localHolidayMap 自定义节日数据,特殊节日如,"母亲节", "5-W-2-7" 5表示5月,W表示星期,2表示第二个星期,7表示星期的第7天 * @return String */ static String getLocalHoliday(Temporal temporal, Map<String, String> localHolidayMap){ Objects.requireNonNull(temporal, "temporal"); StringBuilder localHoliday = new StringBuilder(""); if(CollectionUtil.isEmpty(localHolidayMap)){ localHolidayMap = LocalHolidayEnum.convertToMap(); } MonthDay monthDay = MonthDay.from(temporal); String monthDayStr = monthDay.format(DateTimeFormatterUtil.MMDD_FMT); for(Entry<String, String> entry : localHolidayMap.entrySet()){ if (entry.getKey().equals(monthDayStr)) { if(localHoliday == null || localHoliday.length() == 0){ localHoliday = new StringBuilder(entry.getValue()); }else{ localHoliday.append(" " +entry.getValue()); } } //如果为特殊格式,解析对比 if (entry.getKey().contains("W")) { String[] arr = entry.getKey().split("-"); int month = Integer.parseInt(arr[0]); int weekIndex = Integer.parseInt(arr[2]); int weekValue = Integer.parseInt(arr[3]); DayOfWeek dow = DayOfWeek.of(weekValue); //设置到当前节日的月份 Temporal tempTem = temporal.with(ChronoField.MONTH_OF_YEAR, month); //设置到当前节日的第几星期第几天 Temporal targetTem = tempTem.with(TemporalAdjusters.dayOfWeekInMonth(weekIndex, dow)); MonthDay targetMonthDay = MonthDay.from(targetTem); String targetMonthDayStr = targetMonthDay.format(DateTimeFormatterUtil.MMDD_FMT); if (monthDayStr.equals(targetMonthDayStr)) { if(localHoliday == null || localHoliday.length() == 0){ localHoliday = new StringBuilder(entry.getValue()); }else{ localHoliday.append(" " +entry.getValue()); } } } } return localHoliday.toString(); } /** * 根据日期获取农历几日 * @param date 日期 * @return String */ static String getChineseHoliday(Date date){ return getChineseHoliday(date, null); } /** * 根据日期获取农历几日 * @param date 日期 * @param chineseHolidayMap 自定义节日数据,特殊节日如除夕 用CHUXI表示 * @return String */ static String getChineseHoliday(Date date, Map<String, String> chineseHolidayMap){ Objects.requireNonNull(date, "date"); return getChineseHoliday(DateTimeConverterUtil.toLocalDateTime(date), chineseHolidayMap); } /** * 根据日期获取农历几日 * @param temporal 支持 LocalDate、LocalDateTime、Instant和ZonedDateTime 支持 LocalDate、LocalDateTime、Instant和ZonedDateTime * @return String */ static String getChineseHoliday(Temporal temporal){ return getChineseHoliday(temporal, null); } /** * 根据日期获取农历几日 * @param temporal 支持 LocalDate、LocalDateTime、Instant和ZonedDateTime * @param chineseHolidayMap 自定义节日数据,特殊节日如除夕 用CHUXI表示 * @return String */ static String getChineseHoliday(Temporal temporal, Map<String, String> chineseHolidayMap){ Objects.requireNonNull(temporal, "temporal"); StringBuilder chineseHoliday = new StringBuilder(""); if(CollectionUtil.isEmpty(chineseHolidayMap)){ chineseHolidayMap = ChineseHolidayEnum.convertToMap(); } LunarDate lunarDate = LunarDate.from(temporal); //闰月不计算节假日 if(StringUtil.isNotEmpty(lunarDate.getLeapMonthCn())){ return chineseHoliday.toString(); } String monthDayStr = lunarDate.formatShort(); //对比枚举日期,返回假日 for(Entry<String, String> entry : chineseHolidayMap.entrySet()){ if (entry.getKey().equals(monthDayStr)) { if(chineseHoliday == null || chineseHoliday.length() == 0){ chineseHoliday = new StringBuilder(entry.getValue()); }else{ chineseHoliday.append(" " +entry.getValue()); } } //如果为特殊节日除夕 if (entry.getKey().equals(Constant.CHUXI)) { LocalDate tempLocalDate = lunarDate.getLocalDate(); LocalDate targetLocalDate = tempLocalDate.plus(1, ChronoUnit.DAYS); LunarDate targetLunarDate = LunarDate.from(targetLocalDate); String targetMonthDayStr = targetLunarDate.formatShort(); if(Constant.CHUNJIE.equals(targetMonthDayStr)){ if(chineseHoliday == null || chineseHoliday.length() == 0){ chineseHoliday= new StringBuilder(entry.getValue()); }else{ chineseHoliday.append(" " +entry.getValue()); } } } } return chineseHoliday.toString(); } /** * 根据日期获取二十四节气 * @param date 日期 * @return String */ static String getSolarTerm(Date date){ Objects.requireNonNull(date, "date"); LunarDate lunarDate = LunarDate.from(date); return lunarDate.getSolarTerm(); } /** * 根据日期获取二十四节气 * @param temporal 支持 LocalDate、LocalDateTime、Instant和ZonedDateTime * @return String */ static String getSolarTerm(Temporal temporal){ Objects.requireNonNull(temporal, "temporal"); LunarDate lunarDate = LunarDate.from(temporal); return lunarDate.getSolarTerm(); } }
package com.nmoumoulidis.opensensor.view; import java.util.ArrayList; import java.util.HashMap; import android.support.v4.widget.SimpleCursorAdapter; import android.widget.SimpleAdapter; import com.nmoumoulidis.opensensor.R; /** * UI utility class, used to populate data results in a structured way using * the powerful {@link SimpleCursorAdapter} Android class. * @author Nikos Moumoulidis * */ public class ServerDataListViewAdapter { private ServerActivity serverActivity; public ServerDataListViewAdapter(ServerActivity serverActivity) { this.serverActivity = serverActivity; } public void populateListView(ArrayList<HashMap<String,String>> data) { String[] from = new String[] { "date", "location", "sensor_name", "avg_value", "min_value", "max_value" }; int[] to = new int[] { R.id.server_date_column, R.id.server_location_column, R.id.server_sensor_name_column, R.id.server_avg_column, R.id.server_min_column, R.id.server_max_column }; SimpleAdapter adapter = new SimpleAdapter(serverActivity, data, R.layout.server_result_layout, from, to); serverActivity.getResultsListView().setAdapter(adapter); } public void detachAdapterFromListView() { serverActivity.getResultsListView().setAdapter(null); } }
package com.example.mysqlite.annotion; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * PROJECT_NAME:MyApplication * PACKAGE_NAME:com.example.mysqlite.annotion * USER:Frank * DATE:2018/10/29 * TIME:9:19 * DAY_NAME_FULL:星期一 * DESCRIPTION:On the description and function of the document **/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DbTable { String value(); }
package com.cflox.number_converter.service; import com.cflox.number_converter.model.AuditTrail; import com.cflox.number_converter.pojo.ApplicationResponse; public interface ConverterService { public ApplicationResponse saveRequest(AuditTrail auditTrail); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package unalcol.types.integer; import unalcol.io.Read; import unalcol.io.RowColumnReaderException; import unalcol.io.ShortTermMemoryReader; import java.io.IOException; /** * @author jgomez */ public class IntegerPlainRead extends Read<Integer> { public static void back(char c, ShortTermMemoryReader reader) { if (c != (char) -1) { reader.back(); } } public static void readDigitStar(ShortTermMemoryReader reader, StringBuilder sb) throws IOException { char c = (char) reader.read(); while (Character.isDigit(c)) { sb.append(c); c = (char) reader.read(); } back(c, reader); } public static void removeSpaces(ShortTermMemoryReader reader) throws IOException { char c = (char) reader.read(); while (Character.isSpaceChar(c)) { c = (char) reader.read(); } back(c, reader); } @Override public Integer read(ShortTermMemoryReader reader) throws RowColumnReaderException { try { removeSpaces(reader); char c = (char) reader.read(); if (Character.isDigit(c) || c == '-' || c == '+') { StringBuilder sb = new StringBuilder(); sb.append(c); readDigitStar(reader, sb); return Integer.parseInt(sb.toString()); } throw new Exception("Unexpected symbol " + c); } catch (Exception e) { throw reader.getException("Integer Parser Error " + e.getMessage()); } } }
package com.example.android.tflitecamerademo; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.webkit.WebView; public class BuyActivity extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy); WebView ourBrow=(WebView) findViewById(R.id.web); ourBrow.getSettings().setJavaScriptEnabled(true); ourBrow.getSettings().setLoadWithOverviewMode(true); ourBrow.getSettings().setUseWideViewPort(true); ourBrow.setWebViewClient(new ourViewClient()); ourBrow.loadUrl("https://www.google.com/search?q=supermarkets+near+me&oq=supermarkets+near+me&aqs=chrome..69i57j0l3.5598j0j4&client=ms-android-xiaomi&sourceid=chrome-mobile&ie=UTF-8#istate=lrl:xpd"); } }
import Manager.DownloadManager; import Utils.TableUtils.ProgressRenderer; import Utils.TableUtils.DownloadsTableModel; import Utils.TableUtils.ColumnKeeper; import Utils.Utils; import Config.Config; import Sockets.TCPConnection; import Sockets.TCPEchoSelectorProtocol; import Sockets.TCPServerSelector; import TorrentMetadata.TorrentFile; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; /** * Bittorrent class - main class * * @author Niesuch */ public class Bittorrent extends JFrame implements Observer { private final DownloadsTableModel _tableModel = new DownloadsTableModel(); private final JTable _table; private JButton _pauseButton, _resumeButton; private JButton _cancelButton, _deleteButton; private final JPanel _infoPanel, _downloadsPanel, _buttonsPanel; private DownloadManager _selectedDownload; private final JTextField[] _textFields; private final String[] _formLabels = { "Name: ", "Size: ", "% downloaded: ", "Status: ", "Download: ", "Upload: ", "Time remaining: ", "Pieces: ", "Peer data including IP addresses: ", "Speed download from them: ", "Speed upload to them: ", "Port using: ", "Port client: " }; public Bittorrent() { setTitle("BitTorrent"); setSize(Config.getWindowWidth(), Config.getWindowHeight()); _table = new JTable(_tableModel); _table.setAutoCreateRowSorter(true); _downloadsPanel = new JPanel(); _buttonsPanel = new JPanel(); _infoPanel = new JPanel(new BorderLayout()); _textFields = new JTextField[_formLabels.length]; addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); _initNativeWindowView(); _initMenuBar(); _initTable(); _initInfoPanel(); _initButtonsPanel(); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, _downloadsPanel, _infoPanel); splitPane.setResizeWeight(0.7); getContentPane().setLayout(new BorderLayout()); getContentPane().add(_buttonsPanel, BorderLayout.SOUTH); getContentPane().add(splitPane, BorderLayout.CENTER); } /** * Initialization buttons panel */ private void _initButtonsPanel() { _pauseButton = new JButton("Pause"); _pauseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { _actionPause(); } }); _pauseButton.setEnabled(false); _buttonsPanel.add(_pauseButton); _resumeButton = new JButton("Resume"); _resumeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { _actionResume(); } }); _resumeButton.setEnabled(false); _buttonsPanel.add(_resumeButton); _cancelButton = new JButton("Cancel"); _cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { _actionCancel(); } }); _cancelButton.setEnabled(false); _buttonsPanel.add(_cancelButton); _deleteButton = new JButton("Delete"); _deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { _actionDelete(); } }); _deleteButton.setEnabled(false); _buttonsPanel.add(_deleteButton); } /** * Initialization menu bar */ private void _initMenuBar() { JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); JMenuItem fileOpenMenuItem = new JMenuItem("Open", KeyEvent.VK_X); fileOpenMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TorrentFile openedTorrent = null; String torrent = Utils.openFileChooser(); File torrentFile = new File(torrent); try { openedTorrent = TorrentFile.load(torrentFile); // String msg = "<html>File <span style='color:green'>" + torrentFile.getName() + "</span> opened succesfully</html>"; // JOptionPane.showMessageDialog(null, msg, "Torrent Load", JOptionPane.INFORMATION_MESSAGE); _actionAdd(openedTorrent.fileName, openedTorrent.getTorrentSize()); TCPConnection oTCPConnection =new TCPConnection("127.0.0.1", 1337); } catch (IOException | NoSuchAlgorithmException ex) { String s = "<html> Failed to open <span style='color:red'>" + torrentFile.getName() +"</span> </html>"; JOptionPane.showMessageDialog(null, s, "Torrent Load Failure", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Bittorrent.class.getName()).log(Level.SEVERE, null, ex); } } }); JMenuItem torrentCreateMenuItem = new JMenuItem("Create new torrent from file", KeyEvent.VK_X); torrentCreateMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { URI testAnnounce = null; String loadedFile = Utils.openFileChooser(); File createTorrentFile = new File(loadedFile); TorrentFile createdTorrent = null; File newFile = null; FileOutputStream fopNewFile = null; String savingName = loadedFile; int spaceIndex = savingName.indexOf("."); if (spaceIndex != -1) { savingName = savingName.substring(0, spaceIndex); } savingName += "(createdTorrent).torrent"; try { testAnnounce = new URI("udp://tracker.openbittorrent.com"); createdTorrent = TorrentFile.create(createTorrentFile,testAnnounce , "robert"); newFile = new File(savingName); fopNewFile = new FileOutputStream(newFile); // if file doesnt exists, then create it if (!newFile.exists()) { newFile.createNewFile(); } createdTorrent.save(fopNewFile); String msg = "<html>Saving <span style='color:green'>" + createTorrentFile.getName() + "</span> to <span style='color:green'>" + newFile.getPath() + "</span> succesfull</html>"; JOptionPane.showMessageDialog(null, msg, "Creating new .torrent", JOptionPane.INFORMATION_MESSAGE); System.out.println(msg); fopNewFile.flush(); fopNewFile.close(); } catch (URISyntaxException | NoSuchAlgorithmException | InterruptedException | IOException ex) { String s = "<html> Creating torrent from <span style='color:red'>" + createTorrentFile.getName() +"</span> FAILED </html>"; JOptionPane.showMessageDialog(null, s, "Create Torrent Failed", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Bittorrent.class.getName()).log(Level.SEVERE, null, ex); } } }); JMenuItem fileExitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X); fileExitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_F); JMenuItem helpAboutMenuItem = new JMenuItem("About", KeyEvent.VK_X); helpAboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { _showAboutDialog(); } }); JMenu mViewMenu = new JMenu("View"); mViewMenu.setMnemonic(KeyEvent.VK_F); TableColumnModel model = _table.getColumnModel(); for (int i = 0; i < _tableModel.getColumnCount(); i++) { JCheckBoxMenuItem item = new JCheckBoxMenuItem( _tableModel.getColumnName(i)); item.setSelected(true); TableColumn column = model.getColumn(i); item.addActionListener(new ColumnKeeper(column, _table, _tableModel)); mViewMenu.add(item); } fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.add(fileOpenMenuItem); fileMenu.add(torrentCreateMenuItem); fileMenu.add(fileExitMenuItem); helpMenu.add(helpAboutMenuItem); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(mViewMenu); menuBar.add(helpMenu); setJMenuBar(menuBar); } /** * Initialization download table */ private void _initTable() { _table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { _tableSelectionChanged(); } }); _table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); ProgressRenderer renderer = new ProgressRenderer(0, 100); renderer.setStringPainted(true); _table.setDefaultRenderer(JProgressBar.class, renderer); _table.setRowHeight((int) renderer.getPreferredSize().getHeight()); _downloadsPanel.setBorder(BorderFactory.createTitledBorder("Downloads")); _downloadsPanel.setLayout(new BorderLayout()); _table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); _downloadsPanel.add(new JScrollPane(_table), BorderLayout.CENTER); int i = 0; for (int size : _tableModel.getColumnSizes()) { if (size != 0) { _table.getColumnModel().getColumn(i).setPreferredWidth(size); } i++; } } /** * Initialization information panel */ private void _initInfoPanel() { JPanel formPanel = new JPanel(); formPanel.setBorder(BorderFactory.createTitledBorder("Informations")); JPanel form = new JPanel(new GridLayout(0, 2)); int i = 0; for (String formLabel : _formLabels) { form.add(new JLabel(formLabel)); _textFields[i] = new JTextField(10); form.add(_textFields[i++]); } formPanel.add(form); _infoPanel.add(formPanel); _infoPanel.add(new JScrollPane(formPanel), BorderLayout.CENTER); } /** * Initialization native window view */ private void _initNativeWindowView() { Utils.nativeWindowView(); } /** * Pause action for button */ private void _actionPause() { _selectedDownload.pause(); updateButtons(); } /** * Resume action for button */ private void _actionResume() { _selectedDownload.resume(); updateButtons(); } /** * Cancel action for button */ private void _actionCancel() { _selectedDownload.cancel(); updateButtons(); } /** * Delete action for button */ private void _actionDelete() { _tableModel.deleteDownload(_table.getSelectedRow()); _selectedDownload = null; updateButtons(); } private void _actionAdd(String torrentName, long size) { _tableModel.addDownload(new DownloadManager(torrentName, size)); } /** * Function to update buttons views */ private void updateButtons() { if (_selectedDownload != null) { int status = _selectedDownload.getStatus(); switch (status) { case DownloadManager.DOWNLOADING: _pauseButton.setEnabled(true); _resumeButton.setEnabled(false); _cancelButton.setEnabled(true); _deleteButton.setEnabled(true); break; case DownloadManager.PAUSED: _pauseButton.setEnabled(false); _resumeButton.setEnabled(true); _cancelButton.setEnabled(true); _deleteButton.setEnabled(false); break; case DownloadManager.ERROR: _pauseButton.setEnabled(false); _resumeButton.setEnabled(true); _cancelButton.setEnabled(false); _deleteButton.setEnabled(true); break; default: _pauseButton.setEnabled(false); _resumeButton.setEnabled(false); _cancelButton.setEnabled(false); _deleteButton.setEnabled(true); } } else { _pauseButton.setEnabled(false); _resumeButton.setEnabled(false); _cancelButton.setEnabled(false); _deleteButton.setEnabled(false); } } /** * Function to change table selection */ private void _tableSelectionChanged() { if (_selectedDownload != null) { _selectedDownload.deleteObserver(Bittorrent.this); _setFields(_table.getSelectedRow()); } else { _selectedDownload = _tableModel.getDownload(_table.getSelectedRow()); _selectedDownload.addObserver(Bittorrent.this); updateButtons(); } } /** * Function set text to text field in form * * @param index */ private void _setFields(int index) { // Informations from all table columns if (index >= 0) { for (int i = 0; i < _tableModel.getColumnCount(); i++) { _textFields[i].setText(_tableModel.getValueAt(index, i).toString()); } } // Other informations // _textFields[0].setText(_table.getValueAt(index, 0).toString()); // ... } /** * Function to update buttons state * * @param o * @param arg */ @Override public void update(Observable o, Object arg) { if (_selectedDownload != null && _selectedDownload.equals(o)) { updateButtons(); } } /** * Function to show dialog about authors */ private static void _showAboutDialog() { String authors = "GitHub:" + "\nhttps://github.com/niesuch/bittorrentclient" + "\n\nAuthors:" + "\n- Banasiuk Paweł" + "\n- Grzebuła Łukasz" + "\n- Kolek Robert" + "\n- Niesłuchowski Kamil" + "\n- Puszczyński Paweł" + "\n\nApplication version: 1.0"; Utils.generateDialogWithString(authors, "About"); } public static void main(String[] args) { Bittorrent bittorrent = new Bittorrent(); bittorrent.setVisible(true); } }
/* * Sonar PHP Plugin * Copyright (C) 2010 Sonar PHP Plugin * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ /*** */ package org.sonar.plugins.php.cpd; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.sonar.api.resources.Project; import org.sonar.plugins.php.api.Php; import org.sonar.plugins.php.core.AbstractPhpPluginConfiguration; /*** * @author akram */ public class PhpCpdConfiguration extends AbstractPhpPluginConfiguration { /** PhpCpd command line. */ public static final String PHPCPD_COMMAND_LINE = "phpcpd"; public static final String PHPCPD_REPORT_FILE_OPTION = "--log-pmd"; /** The report file name property key. */ public static final String PHPCPD_REPORT_FILE_NAME_PROPERTY_KEY = "sonar.phpcpd.reportFileName"; /** The relative report path property key. */ public static final String PHPCPD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY = "sonar.phpcpd.reportFileRelativePath"; /** The default report file name. */ public static final String PHPCPD_DEFAULT_REPORT_FILE_NAME = "php-cpd.xml"; public static final String PHPCPD_SUFFIXES = "--suffixes"; public static final String PHPCPD_EXCLUDE_PACKAGE_KEY = "sonar.phpcpd.excludes"; public static final String PHPCPD_EXCLUDE_OPTION = "--exclude"; public static final String PHPCPD_MINIMUM_NUMBER_OF_IDENTICAL_LINES_KEY = "sonar.phpcpd.min.lines"; public static final String PHPCPD_MINIMUM_NUMBER_OF_IDENTICAL_LINES_MODIFIER = "--min-lines"; public static final String PHPCPD_DEFAULT_MINIMUM_NUMBER_OF_IDENTICAL_LINES = "3"; public static final String PHPCPD_MINIMUM_NUMBER_OF_IDENTICAL_TOKENS_KEY = "sonar.phpcpd.min.tokens"; public static final String PHPCPD_MINIMUM_NUMBER_OF_IDENTICAL_TOKENS_MODIFIER = "--min-tokens"; public static final String PHPCPD_DEFAULT_MINIMUM_NUMBER_OF_IDENTICAL_TOKENS = "5"; public static final String PHPCPD_DIRECTORY_SEPARATOR = " "; public static final String PHPCPD_MODIFIER_VALUE_SEPARATOR = " "; private static final String PHPCPD_SUFFIXE_SEPARATOR = ","; /** The default report path beginning after {PROJETC_BUILD_PATH}. */ public static final String PHPCPD_DEFAULT_REPORT_FILE_PATH = "/logs"; /** The should run property key. */ public static final String PHPCPD_SHOULD_RUN_PROPERTY_KEY = "sonar.phpcpd.shouldRun"; public static final String PHPCPD_DEFAULT_SHOULD_RUN = "true"; public static final String PHPCPD_SKIP_PROPERTY_KEY = "sonar.cpd.skip"; public static final String PHPCPD_ANALYZE_ONLY_KEY = "sonar.phpcpd.analyzeOnly"; public static final String PHPCPD_DEFAULT_ANALYZE_ONLY = "false"; public static final String PHPCPD_ANALYZE_ONLY_MESSAGE = "Only analyze existing phpcpd files"; public static final String PHPCPD_ANALYZE_ONLY_DESCRIPTION = "If set to true the plugin will only parse " + "the result file. If set to false launch tool and parse result."; /** * Instantiates a new php cpd configuration. * * @param project * the project */ public PhpCpdConfiguration(Project project) { super(project); } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getCommandLine() */ @Override protected String getCommandLine() { return PHPCPD_COMMAND_LINE; } /** * Gets the suffixes command option. * * @return the suffixes command option */ public String getSuffixesCommandOption() { return StringUtils.join(Php.PHP.getFileSuffixes(), PHPCPD_SUFFIXE_SEPARATOR); } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getPhpunitArgumentLineKey() */ @Override protected String getArgumentLineKey() { return ""; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getPhpunitDefaultArgumentLine() */ @Override protected String getDefaultArgumentLine() { return ""; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getDefaultReportFileName() */ @Override protected String getDefaultReportFileName() { return PHPCPD_DEFAULT_REPORT_FILE_NAME; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getShouldRunKey() */ @Override protected String getShouldRunKey() { return PHPCPD_SHOULD_RUN_PROPERTY_KEY; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#shouldAnalyzeOnlyDefault() */ @Override protected boolean shouldAnalyzeOnlyDefault() { return Boolean.parseBoolean(PHPCPD_DEFAULT_ANALYZE_ONLY); } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#shouldRunDefault() * * @deprecated */ @Override protected boolean shouldRunDefault() { return true; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#skipDefault() */ @Override protected boolean skipDefault() { return false; } @Override protected String getDefaultReportFilePath() { return PHPCPD_DEFAULT_REPORT_FILE_PATH; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getReportFileRelativePathKey() */ @Override protected String getReportFileRelativePathKey() { return PHPCPD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY; } /** * @see org.sonar.plugins.php.core.AbstractPhpPluginConfiguration#getReportFileNameKey() */ @Override protected String getReportFileNameKey() { return PHPCPD_REPORT_FILE_NAME_PROPERTY_KEY; } protected String getShouldAnalyzeOnlyKey() { return PHPCPD_ANALYZE_ONLY_KEY; } /** * @return */ public String getMinimunNumberOfIdenticalLines() { Configuration configuration = getProject().getConfiguration(); return configuration.getString(PHPCPD_MINIMUM_NUMBER_OF_IDENTICAL_LINES_KEY, PHPCPD_DEFAULT_MINIMUM_NUMBER_OF_IDENTICAL_LINES); } /** * @return */ public String getMinimunNumberOfIdenticalTokens() { Configuration configuration = getProject().getConfiguration(); return configuration.getString(PHPCPD_MINIMUM_NUMBER_OF_IDENTICAL_TOKENS_KEY, PHPCPD_DEFAULT_MINIMUM_NUMBER_OF_IDENTICAL_TOKENS); } /** * @return */ public String getExcludePackages() { String[] values = getProject().getConfiguration().getStringArray(PHPCPD_EXCLUDE_PACKAGE_KEY); if (values != null && values.length > 0) { return StringUtils.join(values, PHPCPD_DIRECTORY_SEPARATOR); } return null; } }
package com.project.service.taxi.stub_connector; import com.project.service.taxi.exception.NotFoundException; import com.project.service.taxi.stub_connector.utils.UtilsGeneration; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentHashMap; @Component public class TaxiConnector implements Connector { ConcurrentHashMap<String, HashMap<String, List<?>>> foundTaxiForTheUser = new ConcurrentHashMap<>(); @Override public List<ExpensiveTaxi> connectToExpensiveTaxi(String startAddress, String finishAddress, String userIdentification) { List<ExpensiveTaxi> expensiveTaxi = (List<ExpensiveTaxi>) checkingUpToDateData(userIdentification, "expensive", startAddress, finishAddress); if (!expensiveTaxi.get(0).getStartLocation().equals(startAddress) || !expensiveTaxi.get(0).getDestination().equals(finishAddress)) { foundTaxiForTheUser.get(userIdentification).get("expensive").clear(); expensiveTaxi = (List<ExpensiveTaxi>) checkingUpToDateData(userIdentification, "expensive", startAddress, finishAddress); } return expensiveTaxi; } @Override public List<RegularTaxi> connectTohRegularTaxi(String startAddress, String finishAddress, String userIdentification) { List<RegularTaxi> regularTaxis = (List<RegularTaxi>) checkingUpToDateData(userIdentification, "regular", startAddress, finishAddress); if (!regularTaxis.get(0).getStartLocation().equals(startAddress) || !regularTaxis.get(0).getDestination().equals(finishAddress)) { foundTaxiForTheUser.get(userIdentification).get("regular").clear(); regularTaxis = (List<RegularTaxi>) checkingUpToDateData(userIdentification, "regular", startAddress, finishAddress); } return regularTaxis; } @Override public List<CheapTaxi> connectTohCheapTaxi(String startAddress, String finishAddress, String userIdentification) { List<CheapTaxi> cheapTaxis = (List<CheapTaxi>) checkingUpToDateData(userIdentification, "cheap", startAddress, finishAddress); if (!cheapTaxis.get(0).getStartLocation().equals(startAddress) || !cheapTaxis.get(0).getDestination().equals(finishAddress)) { foundTaxiForTheUser.get(userIdentification).get("cheap").clear(); cheapTaxis = (List<CheapTaxi>) checkingUpToDateData(userIdentification, "cheap", startAddress, finishAddress); } return cheapTaxis; } public List<?> checkingUpToDateData(String userIdentification, String brand, String startAddress, String finishAddress) { if (!foundTaxiForTheUser.containsKey(userIdentification)) { foundTaxiForTheUser.put(userIdentification, new HashMap<>()); } if (foundTaxiForTheUser.get(userIdentification).get(brand) == null || foundTaxiForTheUser.get(userIdentification).get(brand).isEmpty()) { switch (brand) { case "expensive": { List<ExpensiveTaxi> expensiveTaxis = UtilsGeneration.generationExpensiveCar(); expensiveTaxis.forEach(el -> { el.setStartLocation(startAddress); el.setDestination(finishAddress); }); foundTaxiForTheUser.get(userIdentification).put(brand, expensiveTaxis); return expensiveTaxis; } case "regular": { List<RegularTaxi> regularTaxis = UtilsGeneration.generationRegularCar(); regularTaxis.forEach(el -> { el.setStartLocation(startAddress); el.setDestination(finishAddress); }); foundTaxiForTheUser.get(userIdentification).put(brand, regularTaxis); return regularTaxis; } case "cheap": { List<CheapTaxi> cheapTaxis = UtilsGeneration.generationCheapCar(); cheapTaxis.forEach(el -> { el.setStartLocation(startAddress); el.setDestination(finishAddress); }); foundTaxiForTheUser.get(userIdentification).put(brand, cheapTaxis); return cheapTaxis; } } throw new NotFoundException(); } return foundTaxiForTheUser.get(userIdentification).get(brand); } }
package com.testengine; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/ExaminationServlet") public class ExaminationServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ServletConfig config; String Page="Examination.jsp"; public ExaminationServlet() { super(); } public void init(ServletConfig config) throws ServletException { this.config=config; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String msg="No More Questions"; HttpSession ses=request.getSession(true); String subject=(String)ses.getAttribute("sub"); Connection con=null; ResultSet rs=null; int c=0; PreparedStatement pstmt=null; response.setContentType("text/html"); List qlist=new ArrayList(); try { con=ConnectionProvider.getCon(); pstmt=con.prepareStatement("SELECT * from questions where lang=?"); pstmt.setString(1,subject); pstmt.executeQuery(); rs=pstmt.getResultSet(); while(rs.next()) { qlist.add(rs.getInt(8)); qlist.add(rs.getString(2)); qlist.add(rs.getString(7)); qlist.add(rs.getString(3)); qlist.add(rs.getString(4)); qlist.add(rs.getString(5)); qlist.add(rs.getString(6)); } HttpSession sess=request.getSession(true); String sesid=sess.getId(); sess.setAttribute("qlist",qlist); RequestDispatcher rd=request.getRequestDispatcher(Page); System.out.println(sesid); System.out.println(subject); if(rd !=null) { rd.forward(request, response); } rs.close(); pstmt.close(); con.close(); } catch(SQLException sqle) { System.out.println("SQL Error"); } try { HttpSession sess=request.getSession(); String sesid=sess.getId(); con=ConnectionProvider.getCon(); String name=request.getParameter("fname"); String qid=request.getParameter("qid"); String corans=request.getParameter("corans"); String option=request.getParameter("option"); pstmt=con.prepareStatement("INSERT INTO result (username,QID,Answer,seloption,sessid) values(?,?,?,?,?)"); pstmt.setString(1,name); pstmt.setString(2,qid); pstmt.setString(3,corans); pstmt.setString(4,option); pstmt.setString(5,sesid); c=pstmt.executeUpdate(); System.out.println(name); System.out.println(qid); System.out.println(corans); System.out.println(option); System.out.println(sesid); rs.close(); pstmt.close(); con.close(); } catch(SQLException sqle) { System.out.println("SQL Error"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
package lildoop.mapReduce.client; import lildoop.mapReduce.enums.ConditionOperator; public class QueryObject { public String functionColumn; public String field; public ConditionOperator condition; public String data; public String conditionValue; public String conditionColumn; public boolean IsCondition() { return true; } }
package domain; import datasource.daos.TrackDAO; import javax.inject.Inject; public abstract class Track { private int id; private String titel; private String url; private int afspeelduur; private int resterendeTrackTijd; private boolean offlineBeschikbaar; private String performer; public Track(int id, String titel, String url, int afspeelduur, boolean offlineBeschikbaar, String performer) { this.id = id; this.titel = titel; this.url = url; this.afspeelduur = afspeelduur; this.offlineBeschikbaar = offlineBeschikbaar; this.performer = performer; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitel() { return titel; } public void setTitel(String titel) { this.titel = titel; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getAfspeelduur() { return afspeelduur; } public void setAfspeelduur(int afspeelduur) { this.afspeelduur = afspeelduur; } public int getResterendeTrackTijd() { return resterendeTrackTijd; } public void setResterendeTrackTijd(int resterendeTrackTijd) { this.resterendeTrackTijd = resterendeTrackTijd; } public boolean isOfflineBeschikbaar() { return offlineBeschikbaar; } public void setOfflineBeschikbaar(boolean offlineBeschikbaar) { this.offlineBeschikbaar = offlineBeschikbaar; } public String getPerformer() { return performer; } public void setPerformer(String performer) { this.performer = performer; } }
package net.cep.main; public class Main { public static void main(String[] args) { garageStarter(); } public static void garageStarter() { Garage myGarage = new Garage(); Vehicle myFirstCar = new Car("clare", "blue", true, "SG10 FDB", "BMW"); Vehicle myFirstBike = new Bike("fish", "red", false, false); Vehicle myFirstMotorbike = new MotorBike("Troy", "red", false, true); myGarage.addVehicle(myFirstBike); myGarage.addVehicle(myFirstCar); myGarage.addVehicle(myFirstMotorbike); //System.out.println(myGarage.toString()); myGarage.showVehicles(); System.out.println(myGarage.fixVehicle(myFirstMotorbike)); System.out.println(myGarage.fixVehicle(myFirstMotorbike)); myGarage.removeVehicle(myFirstMotorbike); myGarage.letsCloseGarage(); myGarage.showVehicles(); } }
package com.tencent.mm.ui.chatting.gallery; import android.view.animation.AnimationUtils; import com.tencent.mm.R; import com.tencent.mm.ui.chatting.gallery.MediaHistoryGalleryUI.3; class MediaHistoryGalleryUI$3$1 implements Runnable { final /* synthetic */ 3 tXG; MediaHistoryGalleryUI$3$1(3 3) { this.tXG = 3; } public final void run() { MediaHistoryGalleryUI.b(this.tXG.tXF).startAnimation(AnimationUtils.loadAnimation(this.tXG.tXF.mController.tml, R.a.fast_faded_out)); MediaHistoryGalleryUI.b(this.tXG.tXF).setVisibility(8); } }
package com.estrelladelsur.databases; import android.content.Context; public class DL { private SQLiteDBConnection sqLiteDBConnection; private static DL dl; public DL(){ } public static DL getDl() { if (dl == null) { dl = new DL(); } return dl; } public void setSqLiteDBConnection(Context context){ sqLiteDBConnection = new SQLiteDBConnection(context); } public SQLiteDBConnection getSqLiteDBConnection(){ return sqLiteDBConnection; } }
package com.zpjr.cunguan.entity.parameter; import com.zpjr.cunguan.common.base.BaseParameter; /** * Description: 描述 * Autour: LF * Date: 2017/7/11 10:58 */ public class InvestmentListParameter extends BaseParameter{ /** * 当前页码 */ public String currentPage; /** * 每页条数 */ public String pageSize; /** * 状态 */ public String status; public String minDuration; public String maxDuration; public String minRate; public String maxRate; /** * 产品类型 */ public String product; }
/******************************************************************************* * 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 net.adoptopenjdk.bumblebench.core; import java.io.BufferedReader; import java.io.PrintStream; import java.lang.Math; import java.math.BigDecimal; import java.math.MathContext; import java.net.URL; import java.net.URLClassLoader; import java.net.MalformedURLException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Base class for all BumbleBench benchmarks. * <p> * Implements the core self-tuning trial-and-error experimentation system, plus a number of core facilities such as options processing */ public abstract class BumbleBench extends Util implements Runnable { static final int SERIES_NUMBER = 7; // Increment whenever a change can alter reported benchmark scores static final int VERSION_NUMBER = 5; // Increment whenever new features are added that new benchmarks may rely on static final int REVISION_NUMBER = 10; // Increment whenever you want /* * The workload */ /** Run repeatedly by {@link #bumbleMain()} with varying values of * <tt>targetScore</tt> in order to find the highest target score for which * the attempt succeeds. * <p> * The exact meaning of the <em>score</em> differs from benchmark to * benchmark, but is very often some number of operations performed per * second. * <p> * After completing an attempt, the benchmark may choose to return an * estimate of the largest <tt>targetScore</tt> that might succeed. This * return value doubles as a success indicator: returning a value less than * <tt>targetScore</tt> indicates failure to achieve the target score, while * any other value indicates success. * <p> * If the benchmark is unable or unwilling to provide an estimate, it can * instead return {@link #UNSPECIFIED_SUCCESS} or {@link #UNSPECIFIED_FAILURE}. * * @param targetScore the benchmark score to attempt * @return an estimate of the highest achievable score, or {@link #UNSPECIFIED_SUCCESS} or {@link #UNSPECIFIED_FAILURE} */ protected abstract float attempt(float targetScore) throws InterruptedException; /** Optionally implemented by subclasses and called at the end of a run to verify * whether the run was correct or not. Defaults to true. If false, an ERROR message * is printed instead of the final score. Implementing methods may output their own * error message(s) as well. */ protected boolean verify() {return true;} /** Returned by {@link #attempt(float targetScore)} to indicate that the * attempt succeeded without providing an estimate of the highest achievable score. */ public static final float UNSPECIFIED_SUCCESS = Float.NaN; /** Returned by {@link #attempt(float targetScore)} to indicate that the * attempt failed without providing an estimate of the highest achievable score. */ public static final float UNSPECIFIED_FAILURE = Float.NEGATIVE_INFINITY; /* * Core heuristic */ // Benchmark execution state // private float _maxPeak = Float.NEGATIVE_INFINITY; private float _recentPeak = Float.NEGATIVE_INFINITY; private float _estimate = 1F; private float _uncertainty = 0.5F; private float _maxPeakUncertainty = Float.POSITIVE_INFINITY; private long _startTime; /** Indicates that the user has requested additional information from the * benchmark, usually to follow its progress or understand its operation. * * Benchmarks are encouraged to use this to guard status and progress * messages. When VERBOSE is false, benchmarks should be silent. */ static public final boolean VERBOSE = option("verbose", false); /** Indicates that the user doesn't trust the benchmark's correctness has * requested additional information to verify its proper operation. * * Benchmarks are encouraged to use this to guard all messages that trace * fine-grained execution steps and report internal state. */ static public final boolean DEBUG = option("debug", false); /** Handy helper to print a debug message in the appropriate way. * * Requires that {@link DEBUG} is true. This forces the caller to check * <code>DEBUG</code> before calling this method. This design helps to avoid * accidentally executing the code to construct the message string itself * when <code>DEBUG</code> is false. The usual idiom would be: * * <code>if (DEBUG) debug(...);</code> */ final void debug(String message) { assert(DEBUG); out().println("DEBUG: " + message); } final boolean runAttempt(boolean lowball) throws InterruptedException { float under = _estimate * (1-_uncertainty/2); float over = _estimate * (1+_uncertainty/2); float target = lowball? under : over; // Run an experiment // if (VERBOSE) out().println("attempt(" + target + ")"); float result = attempt(target); // Analyze the results // boolean runSucceeded; // Was the target score achieved? boolean guessWasCorrect; // Was runSucceeded what we expected it to be based on the lowball/highball setting? boolean newEstimateWasSpecified = false; // Did the run provide an estimate of the score it can achieve? float oldEstimate = _estimate; if (result >= target && result < Float.POSITIVE_INFINITY) { runSucceeded = true; recordSuccess(target); guessWasCorrect = lowball; _estimate = result; newEstimateWasSpecified = true; } else if (result <= 0F) { // UNSPECIFIED_FAILURE runSucceeded = false; guessWasCorrect = !lowball; _estimate = lowball? _estimate * (1-_uncertainty) : _estimate; } else if (result < target) { runSucceeded = false; guessWasCorrect = !lowball; _estimate = result; // This is why we can't handle result==0 here. Estimate hits zero and never recovers newEstimateWasSpecified = true; } else { // UNSPECIFIED_SUCCESS runSucceeded = true; recordSuccess(target); guessWasCorrect = lowball; _estimate = lowball? _estimate : _estimate * (1+_uncertainty); } if (_recentPeak == _maxPeak) { if (under <= _maxPeak && _maxPeak <= over) _maxPeakUncertainty = Math.min(_maxPeakUncertainty, _uncertainty); } if (!runSucceeded && target < _recentPeak) _recentPeak = Float.NEGATIVE_INFINITY; float oldUncertainty = _uncertainty; if (runSucceeded && target >= Float.POSITIVE_INFINITY) { // lowball guess or not, if we thought it was infinitely fast and the // runSucceeded, we were right. Otherwise, we may never terminate, // always attempting to increase the already-infinite target score ever higher. guessWasCorrect = true; } if (newEstimateWasSpecified) { float impliedUncertainty = Math.abs(oldEstimate - result) / target; if (impliedUncertainty > _uncertainty) { if (TAME_UNCERTAINTY) { // If the estimate was way off, just bump up the _uncertainty as though our guess was incorrect _uncertainty *= INCORRECT_GUESS_ADJUSTMENT; } else { _uncertainty = impliedUncertainty; } } else { _uncertainty *= guessWasCorrect? CORRECT_GUESS_ADJUSTMENT : INCORRECT_GUESS_ADJUSTMENT; } } else { _uncertainty *= guessWasCorrect? CORRECT_GUESS_ADJUSTMENT : INCORRECT_GUESS_ADJUSTMENT; } _uncertainty = Math.min(_uncertainty, MAX_UNCERTAINTY); report(target, result, oldUncertainty, lowball, guessWasCorrect, runSucceeded); return guessWasCorrect; } final void recordSuccess(float target) { _recentPeak = max(_recentPeak, target); _maxPeak = max(_maxPeak, target); } public float currentEstimatedScore(){ return _estimate; } static final boolean LOWBALL = true; static final boolean HIGHBALL = false; static final int MIN_WARMUP_SECONDS = option("minWarmupSeconds", 10); static final int MAX_WARMUP_SECONDS = option("maxWarmupSeconds", 150); static final float WARMUP_TARGET_UNCERTAINTY = option("warmupTargetUncertainty", 0.1F); static final int BALLPARK_ITERATIONS = option("ballparkIterations", 20); static final int FINALE_ITERATIONS = option("finaleIterations", BALLPARK_ITERATIONS/2); static final float CORRECT_GUESS_ADJUSTMENT = option("correctGuessAdjustment", 0.6F); static final float INCORRECT_GUESS_ADJUSTMENT = option("incorrectGuessAdjustment", 1.2F); static final float MAX_UNCERTAINTY = option("maxUncertainty", 0.40F); static final boolean TAME_UNCERTAINTY = option("tameUncertainty", false); public void run() { out().println("\n-= BumbleBench series " + SERIES_NUMBER + " version " + VERSION_NUMBER + "." + REVISION_NUMBER + " running " + _name + " " + new java.util.Date() + " =-\n"); _startTime = System.currentTimeMillis(); try { _estimate = option("initialEstimate", 100F); _uncertainty = 0.2F; reportHeader(); long startTime = System.currentTimeMillis(); long minEndTime = startTime + 1000 * MIN_WARMUP_SECONDS; long maxEndTime = startTime + 1000 * MAX_WARMUP_SECONDS; if (DEBUG) debug("Starting warmup"); while (true) { long currentTime = System.currentTimeMillis(); if (currentTime > maxEndTime) break; else if (currentTime > minEndTime && _uncertainty <= WARMUP_TARGET_UNCERTAINTY) break; else if (_estimate >= Float.POSITIVE_INFINITY) break; if (DEBUG) debug("Warmup: runAttempt(HIGHBALL)..."); while (!runAttempt(HIGHBALL)) { if (currentTime > maxEndTime) break; } if (DEBUG) debug("Warmup: runAttempt(LOWBALL)..."); while (!runAttempt(LOWBALL)) { if (currentTime > maxEndTime) break; } } if (DEBUG) debug("...Warmup completed: "+((System.currentTimeMillis()-startTime)/1000)+" seconds."); out().println(" -- ballpark --"); for (int i = 0; i < BALLPARK_ITERATIONS; i+=2) { while (!runAttempt(HIGHBALL)){} while (!runAttempt(LOWBALL)){} } out().println(" -- finale --"); _maxPeak = _recentPeak; _maxPeakUncertainty = Float.POSITIVE_INFINITY; for (int i = 0; i < FINALE_ITERATIONS; i+=2) { while (!runAttempt(HIGHBALL)){} while (!runAttempt(LOWBALL)){} } } catch (InterruptedException e) { out().println(" -- interrupted: " + e.getMessage() + " --"); } String spaces = String.format("%" + (_name.length()-5) + "s", ""); if (verify()) { out().println("\n " + _name + " score: " + String.format("%f",_maxPeak) + " (" + score(_maxPeak) + " " + logPoints(_maxPeak) + "%)"); out().println(" " + spaces + "uncertainty: " + percentage(_uncertainty) + "%"); } else { out().println("ERROR: failed verification."); } } /** The main entry point for a BumbleBench program. * <p> * Can be overridden to provide additional startup or shutdown functionality * around the entire benchmark run. Subclasses can call super.bumbleMain to * run the benchmark. */ public void bumbleMain() throws Exception { Thread watchdog = DISABLE_WATCHDOG? null : new WatchdogThread(Thread.currentThread()); if (watchdog != null) watchdog.start(); try { if (_targetScores == null) run(); // Normal run else runAsWorker(); } finally { if (watchdog != null) { watchdog.interrupt(); try { watchdog.join(); } catch (InterruptedException e) { // Shouldn't get interrupted, but if we do, clean everything up System.exit(1); } } } } /* * Support for parallel runs */ volatile BlockingQueue<Float> _targetScores, _resultScores; void makeWorker(int queueSize) { _targetScores = new ArrayBlockingQueue<Float>(queueSize); _resultScores = new ArrayBlockingQueue<Float>(queueSize); } void runAsWorker() { BlockingQueue<Float> targetScores = _targetScores, resultScores = _resultScores; try { // Keep taking targets until we hit a Nan or get interrupted for (float targetScore = targetScores.take(); !Thread.interrupted() && !Float.isNaN(targetScore); targetScore = targetScores.take()) resultScores.put(attempt(targetScore)); } catch (InterruptedException e) { // Workers get interrupted at shutdown. Exit normally. return; } } class WorkerThread extends Thread implements Runnable { BumbleBench _workload; public void run() { try { Launcher.runBumbleMainOn(_workload); } catch (Exception e) { throw new RuntimeException(e); } } public WorkerThread(BumbleBench workload) { _workload = workload; } } /* * Watchdog functionality */ class WatchdogThread extends Thread { Thread _benchmarkThread; WatchdogThread(Thread benchmarkThread) { _benchmarkThread = benchmarkThread; } public void run() { try { Thread.sleep(1000*watchdogSeconds()); out().println("!!! WATCHDOG TIMER ELAPSED !!!"); System.exit(1); } catch (InterruptedException e) {} } } static final boolean DISABLE_WATCHDOG = option("disableWatchdog", true); int watchdogSeconds(){ return option("defaultWatchdogSeconds", 300); } /* * Output */ final String _name; BumbleBench() { StringBuilder sb = new StringBuilder(); buildSimpleInnerClassName(getClass(), sb); _name = sb.toString(); } private boolean buildSimpleInnerClassName(Class c, StringBuilder sb) { if (c == null) { return false; } else { if (buildSimpleInnerClassName(c.getEnclosingClass(), sb)) sb.append('.'); sb.append(c.getSimpleName()); return true; } } BumbleBench(String name) { _name = name; } void report(float target, float result, float oldUncertainty, boolean lowball, boolean guessWasCorrect, boolean runSucceeded) { boolean unspecified = (result < 0F) || Float.isNaN(result); out().println(" " + timestamp() + ": " + (unspecified? '?':' ') + (runSucceeded? '>':'<') + (guessWasCorrect? ' ':'!') + ' ' + score(target) + '\t' + score(_estimate) + '\t' + percentage(_uncertainty) + '\t' + score(_maxPeak) + '\t' + score(_recentPeak) + '\t' + logPoints(_recentPeak) + extraReportInfo() ); } void reportHeader() { out().println(" Target\tEst\tUncert%\tMaxPeak\tPeak\tPeak%" + extraReportHeader()); } String extraReportInfo() { return ""; } String extraReportHeader() { return ""; } static final DecimalFormat ONE_DECIMAL_PLACE = initOneDecimalPlace(); private static DecimalFormat initOneDecimalPlace() { DecimalFormatSymbols sym = new DecimalFormatSymbols(); sym.setInfinity("inf"); return new DecimalFormat("0.0", sym); } static final boolean SPREADSHEET_MODE = option("spreadsheetMode", false); final String spreadsheet(double value) { try { return new java.math.BigDecimal(value).toString(); } catch (NumberFormatException e) { return Double.toString(value); } } final String timestamp() { double elapsedSeconds = (System.currentTimeMillis() - _startTime) / 1000.0; if (SPREADSHEET_MODE) return spreadsheet(elapsedSeconds); else return String.format("%5ss", ONE_DECIMAL_PLACE.format(elapsedSeconds)); } final String percentage(double value) { if (SPREADSHEET_MODE) return spreadsheet(100*value); else return String.format("%5s", ONE_DECIMAL_PLACE.format(100*value)); } static final MathContext PRETTY_MODE = new MathContext(option("sigFigs", 4)); final String siSuffixed(String exponential) { int eIndex = exponential.indexOf('E'); if (eIndex > 0) { StringBuilder sb = new StringBuilder(exponential); if (exponential.endsWith("E-9")) sb.replace(eIndex, sb.length(), "n"); else if (exponential.endsWith("E-6")) sb.replace(eIndex, sb.length(), "u"); else if (exponential.endsWith("E-3")) sb.replace(eIndex, sb.length(), "m"); else if (exponential.endsWith("E+3")) sb.replace(eIndex, sb.length(), "K"); else if (exponential.endsWith("E+6")) sb.replace(eIndex, sb.length(), "M"); else if (exponential.endsWith("E+9")) sb.replace(eIndex, sb.length(), "G"); else if (exponential.endsWith("E+12")) sb.replace(eIndex, sb.length(), "T"); else return exponential; // I give up, just leave the string alone return sb.toString(); } // default return exponential; } final String pretty(double value) { if (Double.isNaN(value)) { return "NaN"; } else try { return siSuffixed(new BigDecimal(value, PRETTY_MODE).toEngineeringString()); } catch (NumberFormatException e) { return ONE_DECIMAL_PLACE.format(value); } } final String logPoints(double value) { if (value <= 0) return "--"; else return ONE_DECIMAL_PLACE.format(100*Math.log(value)); } static final boolean DISPLAY_RAW_SCORES = option("displayRawScores", false); static final boolean REPORT_RECIPROCAL_SCORES = option("reportReciprocalScores", false); final String rawScore(double value) { if (REPORT_RECIPROCAL_SCORES) return Double.toString(1/value); else return Double.toString(value); } final String score(double value) { if (SPREADSHEET_MODE) return spreadsheet(value); else if (DISPLAY_RAW_SCORES) return rawScore(value); else if (REPORT_RECIPROCAL_SCORES) return pretty(1/value); else return pretty(value); } static float max(float left, float right) { // Math.max doesn't handle NaN vs. Inifinity well if (left > right) return left; else if (right > left) return right; else return left; } /* * Odds and ends */ static final long RANDOM_SEED = option("randomSeed", 123L); public static Random newRandom(){ return new Random(RANDOM_SEED); } static final boolean VERBOSE_LOGN = option("verboseLogN", false); protected static int log2(long n) { int result = 63 - Long.numberOfLeadingZeros(n); if (VERBOSE_LOGN) out().println("log2(" + n + ") = " + result); return result; } protected static long nlogn(long n) { return n * log2(n); } protected static int nlogn( int n) { return n * log2(n); } protected static int inverse_nlogn( int y) { return (int)inverse_nlogn((long)y); } protected static long inverse_nlogn(long y) { // Given y = x log x, returns an approximation for x. // There is no closed-form inverse for nlogn. This is an approximation, // and it usually (but not always) under-estimates. if (y < _inverse_nlogn.length) { long x = _inverse_nlogn[(int)y]; if (VERBOSE_LOGN) out().println("inverse_nlogn(" + y + ") = " + x + " from array; nlogn=" + x*log2(x)); return x; } // For convenience, we write Lx instead of "log x". // int Ly = log2(y); int LLy = log2(Ly); // Derivation: // y = xLx // Ly = Lx + LLx // = Lx * (Lx+LLx)/Lx // // As an approximation, we say (Lx+LLx)/Lx is roughly (Ly+LLy)/Ly which we can compute. // Hence: // // Ly ~ Lx * (Ly+LLy)/Ly // so Lx ~ Ly*Ly / (Ly+LLy) // and x = y/Lx // int Lx = Ly*Ly / (Ly + LLy); long x = y/Lx; if (VERBOSE_LOGN) out().println("inverse_nlogn(" + y + ") = " + x + "; nlogn=" + x*log2(x)); return x; } static final byte[] _inverse_nlogn = { 1, 1, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9,10,10, 10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15, 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15 }; protected static int sqrt( int y) { return (int)sqrt((long)y); } protected static long sqrt(long y) { return (long)Math.sqrt((double)y); } }
package printtreelevelbylevel; import java.util.LinkedList; import java.util.Queue; public class Solution { public void printtree(TreeNode root){ if(root == null){ return; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ int size = queue.size(); for(int i = 0; i < size; i++){ TreeNode cur = queue.poll(); System.out.println(cur.key); if (cur.left != null){ queue.offer(cur.left); } if (cur.right != null){ queue.offer(cur.right); } } System.out.println(""); } return; } public static void main (String [] args){ TreeNode t1 = new TreeNode(1); TreeNode t2 = new TreeNode(2); TreeNode t3 = new TreeNode(3); TreeNode t4 = new TreeNode(4); TreeNode t5 = new TreeNode(5); TreeNode t6 = new TreeNode(6); TreeNode t7 = new TreeNode(7); t1.left = t2; t2.left = t4; t1.right = t3; t2.right = t5; t3.left = t6; t3.right = t7; Solution s = new Solution(); s.printtree(t1); } }
package com.tencent.mm.plugin.multitalk.ui.widget; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.model.r; import com.tencent.mm.plugin.multitalk.a.e; import com.tencent.mm.plugin.multitalk.a.i; import com.tencent.mm.plugin.multitalk.a.o; import com.tencent.mm.plugin.multitalk.ui.MultiTalkMainUI; import com.tencent.mm.pluginsdk.ui.a.b; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.pb.talkroom.sdk.MultiTalkGroup; import com.tencent.pb.talkroom.sdk.MultiTalkGroupMember; import java.util.ArrayList; import java.util.List; public final class c implements OnClickListener { private TextView hoe; private MultiTalkMainUI lvs; private View lvt; private TextView lvu; private ImageView lvv; private LinearLayout lvw; private ImageButton lvx; private ImageButton lvy; public c(MultiTalkMainUI multiTalkMainUI) { this.lvs = multiTalkMainUI; this.lvt = multiTalkMainUI.findViewById(R.h.invite_layout); this.lvu = (TextView) multiTalkMainUI.findViewById(R.h.invite_main_nickname_tv); this.lvv = (ImageView) multiTalkMainUI.findViewById(R.h.invite_main_avatar_iv); this.lvw = (LinearLayout) multiTalkMainUI.findViewById(R.h.small_avatar_iv_container); this.hoe = (TextView) multiTalkMainUI.findViewById(R.h.introduce_tv); this.lvx = (ImageButton) multiTalkMainUI.findViewById(R.h.invite_pickup_btn); this.lvy = (ImageButton) multiTalkMainUI.findViewById(R.h.invite_hangup_btn); this.lvx.setOnClickListener(this); this.lvy.setOnClickListener(this); } public final void n(MultiTalkGroup multiTalkGroup) { int i; this.lvt.setVisibility(0); String bgD = i.bgD(); List arrayList = new ArrayList(); if (!bi.oW(bgD)) { for (i = 0; i < multiTalkGroup.vgq.size(); i++) { if (!((MultiTalkGroupMember) multiTalkGroup.vgq.get(i)).vgr.equals(bgD)) { arrayList.add(((MultiTalkGroupMember) multiTalkGroup.vgq.get(i)).vgr); } } this.lvu.setText(j.a(this.lvs, r.gT(bgD))); b.a(this.lvv, bgD, 0.1f, true); } if (arrayList.size() > 0) { this.hoe.setVisibility(0); this.hoe.setText(R.l.multitalk_member_wording); this.lvw.setVisibility(0); this.lvw.removeAllViews(); for (i = 0; i < arrayList.size(); i++) { View imageView = new ImageView(this.lvs.mController.tml); LayoutParams layoutParams = new LinearLayout.LayoutParams(b.lvl, b.lvl); if (i != 0) { layoutParams.leftMargin = b.lvj; } imageView.setLayoutParams(layoutParams); this.lvw.addView(imageView); b.a(imageView, (String) arrayList.get(i), 0.1f, false); } return; } this.hoe.setVisibility(8); this.lvw.setVisibility(8); } public final void bgT() { this.lvt.setVisibility(8); } public final void onClick(View view) { if (view.getId() == R.h.invite_hangup_btn) { o.bgN().g(true, false, false); } else if (view.getId() == R.h.invite_pickup_btn) { e bgN = o.bgN(); if (bgN.bgl()) { x.i("MicroMsg.MT.MultiTalkManager", "acceptCurrentMultiTalk: %s", new Object[]{i.h(bgN.ltt)}); o.bgM().lta.B(bgN.ltt.vgm, bgN.ltt.vcc, bgN.ltt.vgo); return; } x.e("MicroMsg.MT.MultiTalkManager", "acceptCurrentMultiTalk: Not in MultiTalking"); } } }
package org.sagebionetworks.repo.model; import java.util.List; import org.sagebionetworks.repo.web.NotFoundException; public interface AccessRequirementDAO { /** * @param dto * object to be created * @param paramsSchema the schema of the parameters field * @return the id of the newly created object * @throws DatastoreException * @throws InvalidModelException */ public <T extends AccessRequirement> T create(T dto) throws DatastoreException, InvalidModelException; /** * Retrieves the object given its id * * @param id * @return * @throws DatastoreException * @throws NotFoundException */ public AccessRequirement get(String id) throws DatastoreException, NotFoundException; /** * Updates the 'shallow' properties of an object. * * @param dto * @throws DatastoreException */ public <T extends AccessRequirement> T update(T accessRequirement) throws InvalidModelException, NotFoundException, ConflictingUpdateException, DatastoreException; /** * delete the object given by the given ID * * @param id * the id of the object to be deleted * @throws DatastoreException * @throws NotFoundException */ public void delete(String id) throws DatastoreException, NotFoundException; /** * Retrieve a page of AccessRequirements. * * @param subject the subject of the access restriction * @param limit * @param offset * @return the AccessRequirement objects related to this node * @throws DatastoreException */ public List<AccessRequirement> getAccessRequirementsForSubject( List<Long> subjectIds, RestrictableObjectType type, long limit, long offset) throws DatastoreException; /** * Retrieve the concreteType of an access requirement. * * @param accessRequirementId * @return */ public String getConcreteType(String accessRequirementId); /** * Retrieve the statistic of access requirements for list of given subjectIds * * @param subjectIds * @param type - if type is ENTITY, subjectIds should contain the entityID and its ancestor IDs; * if type is TEAM, subjectIds should contain the teamID * @return */ public AccessRequirementStats getAccessRequirementStats(List<Long> subjectIds, RestrictableObjectType type); /** * Retrieving the subjects under a given access requirement * * @param accessRequirementId * @return */ public List<RestrictableObjectDescriptor> getSubjects(long accessRequirementId); /** * Retrieve information to update an AccessRequirement. * * @param accessRequirementId * @return * @throws NotFoundException */ public AccessRequirementInfoForUpdate getForUpdate(String accessRequirementId) throws NotFoundException; /** * Returns all access requirement IDs that applies to source subjects but does not apply to destination subjects. * * @param sourceSubjects * @param destSubjects * @param type * @return */ public List<String> getAccessRequirementDiff(List<Long> sourceSubjects, List<Long> destSubjects, RestrictableObjectType type); /** * Retrieve an AccessRequirement for update * * @param accessRequirementId * @return */ public AccessRequirement getAccessRequirementForUpdate(String accessRequirementId); /** * Retrieve a page of subjects that the given accessRequirementId applies to * * @param accessRequirementId * @param limit * @param offset * @return */ public List<RestrictableObjectDescriptor> getSubjects(long accessRequirementId, long limit, long offset); // For testing void clear(); }
package com.link.common.kit; /** * Created by linkzz on 2017-07-20. */ public class StrKit extends com.jfinal.kit.StrKit { public static String subString(String str,int num){ if (str.length() > num){ return str.substring(0,num); }else { return str; } } }
package ru.Makivay.sandbox.xlsxReport.cellsFiller; import org.apache.poi.ss.usermodel.CellStyle; public interface Stylist { CellsFiller decorate(CellStyle cellStyle); }
package problem_solve.bfs.baekjoon; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class BaekJoon2468 { private static int[][] region; private static boolean[][] visited; private static int moveX[] = {0, 1, 0, -1}; private static int moveY[] = {1, 0, -1, 0}; public static void main(String[] args){ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); region = new int[size][size]; int highest = 0; for(int i=0; i < size; i++){ for(int j=0; j < size; j++){ region[i][j] = scan.nextInt(); highest = Math.max(highest, region[i][j]); } } int max_val = 0; for(int raining=0; raining <= 100; raining++){ if(highest <= raining) break; visited = new boolean[size][size]; for(int i=0; i < size; i++){ for(int j=0; j < size; j++){ if(region[i][j] <= raining){ visited[i][j] = true; } } } RegionPoint rp; int safeRegion = 0; for(int i=0; i < size; i++){ for(int j=0; j < size; j++){ if(!visited[i][j]){ rp = new RegionPoint(i, j); visited[i][j] = true; safeRegion++; bfs(rp, raining, size); } } } max_val = Math.max(max_val, safeRegion); } System.out.println(max_val); scan.close(); } private static void bfs(RegionPoint rp, int r, int size){ Queue<RegionPoint> q = new LinkedList<>(); q.add(rp); while(!q.isEmpty()){ RegionPoint actual = q.remove(); int now_y = actual.getY(); int now_x = actual.getX(); for(int i=0; i < 4; i++){ int nextY = now_y + moveY[i]; int nextX = now_x + moveX[i]; if(0 <= nextX && nextX < size && 0 <= nextY && nextY < size && !visited[nextY][nextX]){ q.add(new RegionPoint(nextY, nextX)); visited[nextY][nextX] = true; } } } } } class RegionPoint{ private int y; private int x; public int getY() { return y; } public void setY(int y) { this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public RegionPoint(int y, int x) { this.y = y; this.x = x; } }
package com.appdear.client.utility.cache; import java.util.List; public interface ListviewSourceCacheInterface<T> { //添加缓存信息到key文件/sdcard/appdear/source/key public boolean addListview(String key,T source); //从缓存取key文件资源 public T getListview(String key); }
/* DAVID DE SAN LÁZARO LORENTE * ACTIVIDAD DE APRENDIZAJE SEGUNDA EVALUACIÓN * * Esta es una aplicación para gestionar una cadena de cines. Su función es introducir la información de sus * salas, películas o trabajadores. También permite consultar la información introducida. */ package com.sanvalero.cine; public class Application { public static void main(String[] args) { Cine cine = new Cine(); cine.ejecutar(); } }
package com.database.endingCredit.domain.user.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public class SignUpDTO { private String lastName; private String firstName; private String email; private String phoneNum; private String creditNum; private String password; private String accountType; /** * @return String return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return String return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return String return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return String return the phoneNum */ public String getPhoneNum() { return phoneNum; } /** * @param phoneNum the phoneNum to set */ public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } /** * @return String return the creditNum */ public String getCreditNum() { return creditNum; } /** * @param creditNum the creditNum to set */ public void setCreditNum(String creditNum) { this.creditNum = creditNum; } /** * @return String return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @return String return the accountType */ public String getAccountType() { return accountType; } /** * @param accountType the accountType to set */ public void setAccountType(String accountType) { this.accountType = accountType; } }
package com.tuanhk.login; import android.support.annotation.Nullable; import com.tuanhk.splashscreen.SplashScreenFragment; import com.tuanhk.ui.activity.BaseActivity; import com.tuanhk.ui.fragment.BaseFragment; public class LoginScreenActivity extends BaseActivity { @Nullable @Override protected BaseFragment getFragmentToHost() { return LoginScreenFragment.newInstance(getIntent().getExtras()); } }
package com.example.rnztx.donors.models; /** * Created by rnztx on 9/3/16. */ public class KeyReference extends Object{ String uniqueKey; public KeyReference() { } public KeyReference(String uniqueKey) { this.uniqueKey = uniqueKey; } public String getUniqueKey() { return uniqueKey; } }
package interfaceTest; public interface Car { // 3개의 기능 정의 >> 추상메서드 정의 public void speed(int sp); public void wheel(String wh); public void key(String k); }
package tree; import java.util.Iterator; public interface IIterator<T> extends Iterable<T> { @Override public Iterator<T> iterator(); public T next(); public boolean hasNext(); public void remove(); }
package com.simple.core.database; public class FilterData { private String filterDef; private String filterParamName; private Object filterParamValue; public FilterData(String filterDef, String filterParamName, Object filterParamValue) { this.filterDef = filterDef; this.filterParamName = filterParamName; this.filterParamValue = filterParamValue; } public String getFilterDef() { return filterDef; } public void setFilterDef(String filterDef) { this.filterDef = filterDef; } public String getFilterParamName() { return filterParamName; } public void setFilterParamName(String filterParamName) { this.filterParamName = filterParamName; } public Object getFilterParamValue() { return filterParamValue; } public void setFilterParamValue(Object filterParamValue) { this.filterParamValue = filterParamValue; } }
package com.rs.game.player.dialogues; public class Starter extends Dialogue { public Starter() { } @Override public void start() { stage = 1; // STARTING DIALOGUE FOR WHEN A NEW PLAYER JOINS, THEY CHOOSE A GOD. sendOptionsDialogue("Welcome new one, choose your god.", "The Dark, <col=ff0000>Zamorak", "The Holy, <col=00AAFF>Saradomin", "The Neutral, <col=088A08>Guthix"); } @Override public void run(int interfaceId, int componentId) { if (stage == 1) { // STARTERS FOR EACH GOD. ALL SAME BUT THE CLOAK. if (componentId == OPTION_1) { player.sm("You have chosen your god to be, The Mighty <col=ff0000>Zamorak</col>."); player.getInterfaceManager().closeChatBoxInterface(); player.isZamorak = 1; player.getAppearence().setTitle(900001); player.getInventory().addItem(995, 5000000); // Money, 5M player.getInventory().addItem(1856, 1); // Guide Book player.getInventory().addItem(1137, 1); // Few items below are player.getInventory().addItem(1115, 1); // iron items, helm, plate player.getInventory().addItem(1067, 1); // legs, weapon, etc! player.getInventory().addItem(1323, 1); // Iron Scim player.getInventory().addItem(4587, 1); // Dragon Scim player.getInventory().addItem(10450, 1); // Zammy Cloak player.getInventory().addItem(841, 1); // Shortbow player.getInventory().addItem(861, 1); // Magic Sb player.getInventory().addItem(884, 100); // Iron Arrows player.getInventory().addItem(556, 100); // Air Rune player.getInventory().addItem(555, 100); // Water Rune player.getInventory().addItem(558, 100); // Mind Rune player.getInventory().addItem(554, 100); // Fire Rune player.getInventory().addItem(557, 100); // Earth Rune player.getInventory().addItem(386, 100); // Sharks player.getInventory().addItem(1856, 1); player.getPackets().sendGameMessage( "Congratulations! You finished the start tutorial."); player.getPackets() .sendGameMessage( "You've received a guide book. Use it if you have questions or talk with other players."); player.getPackets().sendGameMessage("or talk with other players."); player.getInventory().refresh(); } else if (componentId == OPTION_2) { player.sm("You have chosen your god to be, The Holy <col=013ADF>Saradomin</col>."); player.isSaradomin = 1; player.getAppearence().setTitle(900003); player.getInterfaceManager().closeChatBoxInterface(); player.getInventory().addItem(995, 5000000); // Money, 5M player.getInventory().addItem(1856, 1); // Guide Book player.getInventory().addItem(1137, 1); // Few items below are player.getInventory().addItem(1115, 1); // iron items, helm, plate player.getInventory().addItem(1067, 1); // legs, weapon, etc! player.getInventory().addItem(1323, 1); // Iron Scim player.getInventory().addItem(4587, 1); // Dragon Scim player.getInventory().addItem(10446, 1); // Sara Cloak player.getInventory().addItem(841, 1); // Shortbow player.getInventory().addItem(859, 1); // Magic Sb player.getInventory().addItem(884, 100); // Iron Arrows player.getInventory().addItem(556, 100); // Air Rune player.getInventory().addItem(555, 100); // Water Rune player.getInventory().addItem(558, 100); // Mind Rune player.getInventory().addItem(554, 100); // Fire Rune player.getInventory().addItem(557, 100); // Earth Rune player.getInventory().addItem(386, 100); // Sharks player.getInventory().addItem(1856, 1); player.getPackets().sendGameMessage( "Congratulations! You finished the start tutorial."); player.getPackets() .sendGameMessage( "You've received a guide book. Use it if you have questions or talk with other players."); player.getPackets().sendGameMessage("or talk with other players."); player.getInventory().refresh(); player.getInventory().refresh(); } else if (componentId == OPTION_3) { player.sm("You have chosen your god to be, The Neutral <col=088A08>Guthix</col>."); player.isGuthix = 1; player.getAppearence().setTitle(900002); player.getInventory().addItem(995, 5000000); // Money, 5M player.getInventory().addItem(1856, 1); // Guide Book player.getInventory().addItem(1137, 1); // Few items below are player.getInventory().addItem(1115, 1); // iron items, helm, plate player.getInventory().addItem(1067, 1); // legs, weapon, etc! player.getInventory().addItem(1323, 1); // Iron Scim player.getInventory().addItem(4587, 1); // Dragon Scim player.getInventory().addItem(1, 1); // Zammy Cloak player.getInventory().addItem(841, 1); // Shortbow player.getInventory().addItem(859, 1); // Magic Sb player.getInventory().addItem(884, 100); // Iron Arrows player.getInventory().addItem(556, 100); // Air Rune player.getInventory().addItem(555, 100); // Water Rune player.getInventory().addItem(558, 100); // Mind Rune player.getInventory().addItem(554, 100); // Fire Rune player.getInventory().addItem(557, 100); // Earth Rune player.getInventory().addItem(386, 150); // Sharks player.getInventory().addItem(1856, 1); player.getPackets().sendGameMessage( "Congratulations! You finished the start tutorial."); player.getPackets() .sendGameMessage( "You've received a guide book. Use it if you have questions or talk with other players."); player.getPackets().sendGameMessage("or talk with other players."); player.getInventory().refresh(); player.getInventory().refresh(); if (stage == 2) { player.getInterfaceManager().closeChatBoxInterface(); end(); } }} } /* private void teleportPlayer(int x, int y, int z) { player.setNextWorldTile(new WorldTile(x, y, z)); player.stopAll(); } Not used for now*/ @Override public void finish() { } }
class Solution { public int[] topKFrequent(int[] nums, int k) { /* map of freq: 1: 3,2, 2, 3, 1 PriorityQueue **/ HashMap<Integer, Integer> freq = new HashMap<>(); for (int i : nums) { freq.put(i, freq.getOrDefault(i, 0) + 1); } PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> freq.get(a) - freq.get(b)); for (int key : freq.keySet()) { pq.offer(key); if (pq.size() > k) { pq.poll(); } } int n = pq.size() - 1; int[] res = new int[n + 1]; while (!pq.isEmpty()) { res[n--] = pq.poll(); } return res; } }
/* * 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 Entidades; import java.util.List; /** * * @author Toditos */ public class entSesion { private int posicion; private entDiaRecepcion objDiaRecepcion; private boolean dia_recepcion; private entUsuario objUsuario; private entBrotacion objBrotacion; private entDesbrote objDesbrote; private entPrePoda objPrePoda; private entPoda objPoda; private entRaleo objRaleo; private entRecepcion objRecepcion; private entConfiguracion objConfiguracion; private entPaleta objPaleta; private entCargaTunel objCargaTunel; private entEmbarque objEmbarque; List<entModulo> listModulos; List<entDetalleReceta> listDetalleReceta; public entSesion() { this.posicion=0; this.dia_recepcion=false; this.listDetalleReceta=null; this.objDiaRecepcion=null; this.listModulos=null; this.objRecepcion=null; this.objUsuario=null; this.objConfiguracion=null; this.objPaleta=null; this.objCargaTunel=null; this.objEmbarque=null; } public List<entDetalleReceta> getListDetalleReceta() { return listDetalleReceta; } public void setListDetalleReceta(List<entDetalleReceta> listDetalleReceta) { this.listDetalleReceta = listDetalleReceta; } public boolean isDia_recepcion() { return dia_recepcion; } public void setDia_recepcion(boolean dia_recepcion) { this.dia_recepcion = dia_recepcion; } public entUsuario getObjUsuario() { return objUsuario; } public void setObjUsuario(entUsuario objUsuario) { this.objUsuario = objUsuario; } public List<entModulo> getListModulos() { return listModulos; } public void setListModulos(List<entModulo> listModulos) { this.listModulos = listModulos; } public int getPosicion() { return posicion; } public void setPosicion(int posicion) { this.posicion = posicion; } public entBrotacion getObjBrotacion() { return objBrotacion; } public void setObjBrotacion(entBrotacion objBrotacion) { this.objBrotacion = objBrotacion; } public entDesbrote getObjDesbrote() { return objDesbrote; } public void setObjDesbrote(entDesbrote objDesbrote) { this.objDesbrote = objDesbrote; } public entPrePoda getObjPrePoda() { return objPrePoda; } public void setObjPrePoda(entPrePoda objPrePoda) { this.objPrePoda = objPrePoda; } public entPoda getObjPoda() { return objPoda; } public void setObjPoda(entPoda objPoda) { this.objPoda = objPoda; } public entRaleo getObjRaleo() { return objRaleo; } public void setObjRaleo(entRaleo objRaleo) { this.objRaleo = objRaleo; } public entRecepcion getObjRecepcion() { return objRecepcion; } public void setObjRecepcion(entRecepcion objRecepcion) { this.objRecepcion = objRecepcion; } public entDiaRecepcion getObjDiaRecepcion() { return objDiaRecepcion; } public void setObjDiaRecepcion(entDiaRecepcion objDiaRecepcion) { this.objDiaRecepcion = objDiaRecepcion; } public entConfiguracion getObjConfiguracion() { return objConfiguracion; } public void setObjConfiguracion(entConfiguracion objConfiguracion) { this.objConfiguracion = objConfiguracion; } public entPaleta getObjPaleta() { return objPaleta; } public void setObjPaleta(entPaleta objPaleta) { this.objPaleta = objPaleta; } public entCargaTunel getObjCargaTunel() { return objCargaTunel; } public void setObjCargaTunel(entCargaTunel objCargaTunel) { this.objCargaTunel = objCargaTunel; } public entEmbarque getObjEmbarque() { return objEmbarque; } public void setObjEmbarque(entEmbarque objEmbarque) { this.objEmbarque = objEmbarque; } }
package com.moon.sevlet.file; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; /** * Created by maguoqiang on 2016/9/21. * 文件servlet */ public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //设置编码 //获得磁盘文件条目工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //获取文件需要上传到的路径 //String path = req.getRealPath("/upload"); String path=req.getSession().getServletContext().getRealPath("/upload"); System.out.println(path); //如果没以下两行设置的话,上传大的 文件 会占用 很多内存, //设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同 /** * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的 * 然后再将其真正写到 对应目录的硬盘上 */ File file=new File(path); if (!file.exists()){ file.mkdir(); } factory.setRepository(file); //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室 factory.setSizeThreshold(1024*1024) ; //高水平的API文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory); try { //可以上传多个文件 List<FileItem> list = (List<FileItem>)upload.parseRequest(req); for(FileItem item : list) { //获取表单的属性名字 String name = item.getFieldName(); //如果获取的 表单信息是普通的 文本 信息 if(item.isFormField()) { //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的 String value = item.getString() ; req.setAttribute(name, value); } //对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些 else { /** * 以下三步,主要获取 上传文件的名字 */ //获取路径名 String value = item.getName() ; //索引到最后一个反斜杠 int start = value.lastIndexOf("\\"); //截取 上传文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start+1); req.setAttribute(name, filename); //真正写到磁盘上 //它抛出的异常 用exception 捕捉 //item.write( new File(path,filename) );//第三方提供的 //手动写的 OutputStream out = new FileOutputStream(new File(path,filename)); InputStream in = item.getInputStream() ; int length = 0 ; byte [] buf = new byte[1024] ; System.out.println("获取上传文件的总共的容量:"+item.getSize()); // in.read(buf) 每次读到的数据存放在 buf 数组中 while( (length = in.read(buf) ) != -1) { //在 buf 数组中 取出数据 写到 (输出流)磁盘上 out.write(buf, 0, length); } in.close(); out.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } req.getRequestDispatcher("/WEB-INF/pages/filedemo.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } @Override public void destroy() { super.destroy(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); System.out.println("FileServlet。web服务器加载执行。。。"); } @Override public void init() throws ServletException { super.init(); System.out.println("FileServlet。init() web服务器加载执行。。。"); } }
import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.*; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import java.util.TreeMap; public class CreateLength { private JComboBox jComboBox1, jComboBox2; private JTextField jTextField; private ObjectInputStream objectInputStream1, objectInputStream2; private ObjectOutputStream objectOutputStream; private File lengthFile; private File pointFile; private double length[][]; private Toolkit toolkit = Toolkit.getDefaultToolkit(); private TreeMap treeMap; private Set set; private LengthInfo lengthInfo; private ArrayList arrayList; public CreateLength(JFrame jFrame) { lengthFile = new File("D://length.obj"); pointFile = new File("D://point.obj"); try { objectInputStream1 = new ObjectInputStream(new FileInputStream(pointFile)); } catch (IOException e) { new mDialog("错误", "没有景点信息!", jFrame); } try { objectInputStream2 = new ObjectInputStream(new FileInputStream(lengthFile)); treeMap = (TreeMap) objectInputStream1.readObject(); arrayList = (ArrayList) objectInputStream2.readObject(); } catch (IOException e) { lengthInfo = new LengthInfo(); lengthInfo.init(); arrayList = new ArrayList(); arrayList.add(lengthInfo); try { objectOutputStream = new ObjectOutputStream(new FileOutputStream(lengthFile)); objectOutputStream.writeObject(arrayList); objectOutputStream.flush(); } catch (IOException e1) { } } catch (ClassNotFoundException e) { } frameInit(); } public void frameInit() { JFrame jFrame = new JFrame(); jFrame.setLayout(new FlowLayout()); jFrame.setBounds((toolkit.getScreenSize().width - 350) / 2, (toolkit.getScreenSize().height - 200) / 2, 350, 200); jTextField = new JTextField(27); jComboBox1 = new JComboBox(); jComboBox1.setPreferredSize(new Dimension(270, 30)); jComboBox2 = new JComboBox(); jComboBox2.setPreferredSize(new Dimension(270, 30)); set = treeMap.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { String string = (String) iterator.next(); jComboBox1.addItem(string); jComboBox2.addItem(string); } int from = jComboBox1.getSelectedIndex(); int to = jComboBox2.getSelectedIndex(); lengthInfo = (LengthInfo) arrayList.get(0); jTextField.setText(lengthInfo.getLength(from, to) + ""); jComboBox1.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { jTextField.setText(lengthInfo.getLength(jComboBox1.getSelectedIndex(), jComboBox2.getSelectedIndex()) + ""); } }); jComboBox2.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { jTextField.setText(lengthInfo.getLength(jComboBox1.getSelectedIndex(), jComboBox2.getSelectedIndex()) + ""); } }); JButton cancelButton = new JButton("取消"); JButton okayButton = new JButton("确认"); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { jFrame.setVisible(false); } }); okayButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { double weight = Double.parseDouble(jTextField.getText().toString()); lengthInfo.editLength(jComboBox1.getSelectedIndex(), jComboBox2.getSelectedIndex(), weight); objectOutputStream = new ObjectOutputStream(new FileOutputStream(lengthFile)); objectOutputStream.writeObject(arrayList); new mDialog("成功", "数据修改成功!", jFrame); jFrame.setVisible(false); } catch (NumberFormatException e1) { e1.printStackTrace(); new mDialog("错误", "请输入正确信息!", jFrame); } catch (IOException e1) { new mDialog("错误", "信息写入失败!", jFrame); } } }); jFrame.add(jComboBox1); jFrame.add(jComboBox2); jFrame.add(jTextField); jFrame.add(cancelButton); jFrame.add(okayButton); jFrame.setVisible(true); jFrame.setResizable(false); } public static void main(String[] args) { new CreateLength(new JFrame()); } }
/* * created 20.10.2005 * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id: BytesNode.java 154 2006-02-01 19:45:24Z csell $ */ package com.byterefinery.rmbench.export.diff; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.eclipse.compare.IStreamContentAccessor; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; /** * a model node that represents a leaf value (e.g., column comment, datatype). * * @author cse */ public abstract class BytesNode extends BaseNode implements IStreamContentAccessor { private boolean ignoreCase; private byte[] bytes; private String string; public BytesNode(String name, Image image) { super(name, image); } public BytesNode(String name) { super(name, null); } public void setIgnoreCase(boolean ignoreCase) { super.setIgnoreCase(ignoreCase); this.ignoreCase = ignoreCase; bytes = null; string = null; } public InputStream getContents() throws CoreException { if(bytes == null) createValues(); return new ByteArrayInputStream(bytes); } public String toString() { if(string == null)createValues(); return string; } private void createValues() { string = generateValue(ignoreCase); bytes = string.getBytes(); } protected abstract String generateValue(boolean ignoreCase); }
public class Problem1_3 { public static void main(String[]args) { System.out.println(" J A V V A "); System.out.println(" J A A V V A A "); System.out.println("J J AAAAA V V AAAAA "); System.out.println("J J A A V A A "); } }
package com.puxtech.reuters.rfa.Common; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.PropertyConfigurator; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import com.puxtech.reuters.rfa.utility.MD5; public class Configuration { public static final int TRDPRC_1 = 6; public static final int OPEN1 = 47; public static final int OPEN_PRC = 19; public static final int OPEN_BID = 57; public static final int CLOSE_BID = 60; public static final int CLOSE_ASK = 61; public static final int HST_CLOSE = 21; public static final int CLOSE1 = 50; public static final int BID_HIGH_1 = 203; public static final int HIGH_1 = 12; public static final int BID_LOW_1 = 204; public static final int LOW_1 = 13; public static final int SETTLE = 70; public static final int NETCHNG_1 = 11; public static final int BID = 22; public static final int ASK = 25; private static final Log log = LogFactory.getLog("moniter"); private static final String defaultConfigFilePath = System.getProperty("user.dir") + "/appConfig.xml"; private static Configuration configInstance = null; public static Configuration getInstance(){ if (configInstance == null) { // synchronized (configInstance) { try { configInstance = new Configuration(defaultConfigFilePath); } catch (Exception e) { e.printStackTrace(); log.error(e); log.info("初始化配置文件失败!"); System.exit(0); } // } } return configInstance; } public static void refreshConfiguration(){ synchronized (configInstance) { if(configInstance != null){ try { log.info("刷新配置文件开始!"); configInstance = new Configuration(defaultConfigFilePath); log.info("刷新配置文件成功!"); } catch (Exception e) { log.error(e); log.info("刷新配置文件失败!"); } } } } public static void backupConfigurationFile(){ if(configInstance != null && configInstance.configFile != null){ File backupFile = new File(defaultConfigFilePath + "." + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); if(backupFile.exists()){ backupFile.delete(); } OutputStreamWriter writer = null; InputStreamReader reader = null; try { backupFile.createNewFile(); writer = new OutputStreamWriter(new FileOutputStream(backupFile),"utf-8"); reader = new InputStreamReader(new FileInputStream(configInstance.configFile), "utf-8"); int readLength = -1; char[] buff = new char[1024]; while((readLength = reader.read(buff)) != -1){ writer.write(buff, 0, readLength); } } catch (IOException e) { e.printStackTrace(); } finally { if(writer != null){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public static void updateConfigurationFile(){ backupConfigurationFile(); if(configInstance != null && configInstance.doc != null && configInstance.configFile != null){ try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(configInstance.configFile),"utf-8"),format); writer.write(configInstance.doc); writer.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private int localPort = 9901; private String logHead = ""; private int logFlag = 1; private String quoteFormat = ""; private String spreadFormat = ""; private int monitorInterval = 20000; private List<String> itemNames = new ArrayList<String>(); private List<QuoteSignal> dcQuoteSignList = new ArrayList<QuoteSignal>(); private List<QuoteSignal> virtualSignList = new ArrayList<QuoteSignal>(); private Map<String, QuoteSignal> quoteSignMap = new HashMap<String, QuoteSignal>(); private List<QuoteSource> quoteSourceList = new ArrayList<QuoteSource>(); private Map<String, QuoteSource> quoteSourceMap = new HashMap<String, QuoteSource>(); private List<Contract> contractList = new ArrayList<Contract>(); private Map<String, List<Contract>> quoteSourceContractMap = new HashMap<String, List<Contract>>(); private String configFilePath = ""; private File configFile = null; private Document doc = null; private String SourcePath = ""; private String cronExpress = ""; public Configuration(String configFilePath) throws Exception { super(); if(configFilePath == null){ throw new Exception("配置文件路径未定义!"); } this.configFilePath = configFilePath; configFile = new File(this.configFilePath); doc = new SAXReader().read(configFile); initGlobalCfg(); initQuoteSourceCfg(); initContractCfg(); initLogCfg(); initSpreadCfg(quoteSource); } public Document getDoc() { return doc; } public Element getGlobalConfig(){ Element globalConfigEle = null; if(this.doc != null){ globalConfigEle = doc.getRootElement().element("Config").element("GlobalConfig"); } return globalConfigEle; } //初始化参数配置 begin private String quoteSource; public String getQuoteSource() { return quoteSource; } private void initGlobalCfg(){ Element globalCfgEle = this.getGlobalConfig(); if(globalCfgEle != null){ if(globalCfgEle.elementText("LocalPort") != null && globalCfgEle.elementText("LocalPort").matches("\\d+")){ this.setLocalPort(Integer.valueOf(globalCfgEle.elementText("LocalPort"))); } if(globalCfgEle.elementText("LogHead") != null && globalCfgEle.elementText("LogHead").length() > 0){ this.setLogHead(globalCfgEle.elementText("LogHead")); } if(globalCfgEle.elementText("logFlag") != null && globalCfgEle.elementText("logFlag").matches("\\d+")){ this.setLogFlag(Integer.valueOf(globalCfgEle.elementText("logFlag"))); } if(globalCfgEle.elementText("QuoteFormat") != null && globalCfgEle.elementText("QuoteFormat").length() > 0){ this.setQuoteFormat(globalCfgEle.elementText("QuoteFormat")); } if(globalCfgEle.elementText("SpreadFormat") != null && globalCfgEle.elementText("SpreadFormat").length() > 0){ this.setSpreadFormat(globalCfgEle.elementText("SpreadFormat")); } if(globalCfgEle.elementText("MonitorInterval") != null && globalCfgEle.elementText("MonitorInterval").length() > 0){ this.setMonitorInterval(Integer.valueOf(globalCfgEle.elementText("MonitorInterval"))); } if(globalCfgEle.elementText("SourcePath") != null && globalCfgEle.elementText("SourcePath").length() > 0){ this.setSourcePath(globalCfgEle.elementText("SourcePath")); } if(globalCfgEle.elementText("cronExpress") != null && globalCfgEle.elementText("cronExpress").length() > 0){ this.setCronExpress(globalCfgEle.elementText("cronExpress")); } if(globalCfgEle.elementText("QuoteSource") != null && globalCfgEle.elementText("QuoteSource").length() > 0){ this.quoteSource = globalCfgEle.elementText("QuoteSource"); } } } //初始化参数配置 end public List<Element> getQuoteSourceConfigs(){ List<Element> quoteSourceConfigEle = null; if(this.doc != null){ quoteSourceConfigEle = doc.getRootElement().element("Config").elements("QuoteSource"); } return quoteSourceConfigEle; } private void initQuoteSourceCfg(){ List<Element> quoteSourceCfgElements = this.getQuoteSourceConfigs(); for(Element quoteSourceCfg : quoteSourceCfgElements){ String quoteSourceName = quoteSourceCfg.attributeValue("name"); List<Element> propertyEle = quoteSourceCfg.elements(); QuoteSource quoteSource = new QuoteSource(); quoteSource.setName(quoteSourceName); if(propertyEle != null && propertyEle.size() > 0){ for(Element pro : propertyEle){ quoteSource.setProperty(pro.getName(), pro.getTextTrim()); } } if(quoteSourceName != null){ this.quoteSourceMap.put(quoteSourceName, quoteSource); if(this.quoteSourceContractMap.get(quoteSourceName) == null){ this.quoteSourceContractMap.put(quoteSourceName, new ArrayList<Contract>()); } } } } private Element getSpreadConfigs(){ Element spreadConfigEle = null; if(this.doc != null){ spreadConfigEle = doc.getRootElement().element("Config").element("Spread"); } return spreadConfigEle; } private List<Element> getOffSetConfigs(){ List<Element> offSetConfigEle = null; if(this.doc != null){ offSetConfigEle = doc.getRootElement().element("Config").elements("OffSetConfig"); } return offSetConfigEle; } SpreadConfig spreadConfig = null; private void initSpreadCfg(String quoteSourceName){ //从读xml方式修改为读数据库方式 bein /* Element spreadCfgElements = getSpreadConfigs(); if(spreadCfgElements != null){ spreadConfig = new SpreadConfig(spreadCfgElements); } */ //从读xml方式修改为读数据库方式 emd spreadConfig = new SpreadConfig(quoteSourceName); } public SpreadConfig getSpreadConfig() { return spreadConfig; } private List<Element> getContractConfigs(){ List<Element> contractConfigEle = null; if(this.doc != null){ contractConfigEle = doc.getRootElement().element("Config").element("Contracts").elements("Contract"); } return contractConfigEle; } private void initContractCfg() throws Exception{ List<Element> contractCfgElements = this.getContractConfigs(); for(Element contractCfg : contractCfgElements){ Contract contract = new Contract(); contract.setSourceName(contractCfg.elementText("SourceName") != null ? contractCfg.elementText("SourceName") : ""); contract.setExchangeCode(contractCfg.elementText("ExchangeCode") != null ? contractCfg.elementText("ExchangeCode") : ""); contract.setPriceAlgorithm(contractCfg.elementText("PriceAlgorithm") != null ? Integer.valueOf(contractCfg.elementText("PriceAlgorithm")) : 0); contract.setScale(contractCfg.element("PriceAlgorithm").attributeValue("scale") != null ? Integer.valueOf(contractCfg.element("PriceAlgorithm").attributeValue("scale")) : 0); // contract.setOffset(contractCfg.elementText("Offset") != null && !contractCfg.elementText("Offset").isEmpty() ? new BigDecimal(contractCfg.elementText("Offset")) : new BigDecimal("0")); contract.setFilterName(contractCfg.elementText("Filter") != null ? contractCfg.elementText("Filter") : ""); List<Element> sourceCfgs = contractCfg.element("SourceConfig").elements(); for(Element sourceCfg : sourceCfgs){ contract.appendSourceCfg(sourceCfg.getName(), sourceCfg.getTextTrim()); } Element vPriceGenCfg = contractCfg.element("VirtualPriceGenerator"); if(vPriceGenCfg != null && "true".equalsIgnoreCase(vPriceGenCfg.attributeValue("Enabled"))){ contract.setVirtual(true); } this.contractList.add(contract); List<Contract> contractList = this.quoteSourceContractMap.get(contract.getSourceName()); if(contractList != null){ contractList.add(contract); }else{ log.info("name=" + contract.getSourceName() + "的quoteSource未配置!"); } } } public int getLocalPort() { return localPort; } public void setLocalPort(int localPort) { this.localPort = localPort; } public String getLogHead() { return logHead; } public void setLogHead(String logHead) { this.logHead = logHead; } public int getLogFlag() { return logFlag; } public void setLogFlag(int logFlag) { this.logFlag = logFlag; } public String getQuoteFormat() { return quoteFormat; } public void setQuoteFormat(String quoteFormat) { this.quoteFormat = quoteFormat; } public int getMonitorInterval() { return monitorInterval; } public void setMonitorInterval(int monitorInterval) { this.monitorInterval = monitorInterval; } public List<QuoteSignal> getDcQuoteSignList() { return dcQuoteSignList; } public List<QuoteSignal> getVirtualSignList() { return virtualSignList; } public Map<String, QuoteSignal> getQuoteSignMap() { return quoteSignMap; } private void initLogCfg(){ Properties pro; for(Contract contract : this.contractList){ String itemName = contract.getExchangeCode(); pro = new Properties(); pro.put("log4j.logger." + itemName, "INFO, " + itemName + "log"); pro.put("log4j.additivity." + itemName,"false"); pro.put("log4j.appender." + itemName + "log","org.apache.log4j.DailyRollingFileAppender"); pro.put("log4j.appender." + itemName + "log.file","./logs/" + itemName + ".log"); pro.put("log4j.appender." + itemName + "log.DatePattern","'.'yyyy-MM-dd"); pro.put("log4j.appender." + itemName + "log.Threshold","INFO"); pro.put("log4j.appender." + itemName + "log.layout","com.puxtech.reuters.rfa.Common.MyPatternLayout"); pro.put("log4j.appender." + itemName + "log.layout.ConversionPattern","%m"); pro.put("log4j.appender." + itemName + "log.layout.Header", this.logHead.trim().length() > 0 ? this.logHead + "\r\n" : "\u5546\u54C1\u4EE3\u7801,\u8DEF\u900F\u4EE3\u7801,\u65F6\u95F4,ASK,BID,\u4EF7\u683C,\u4E0A\u4E00\u53E3\u6709\u6548\u4EF7\u683C,\u6DA8\u8DCC\u5E45,\u662F\u5426\u88AB\u8FC7\u6EE4\r\n"); //未计算价差数据日志 String itemRawName = itemName + "_RAW"; pro.put("log4j.logger." + itemRawName, "INFO, " + itemRawName + "log"); pro.put("log4j.additivity." + itemRawName,"false"); pro.put("log4j.appender." + itemRawName + "log","org.apache.log4j.DailyRollingFileAppender"); pro.put("log4j.appender." + itemRawName + "log.file","./logs/" + itemRawName + ".log"); pro.put("log4j.appender." + itemRawName + "log.DatePattern","'.'yyyy-MM-dd"); pro.put("log4j.appender." + itemRawName + "log.Threshold","INFO"); pro.put("log4j.appender." + itemRawName + "log.layout","com.puxtech.reuters.rfa.Common.MyPatternLayout"); pro.put("log4j.appender." + itemRawName + "log.layout.ConversionPattern","%m"); pro.put("log4j.appender." + itemRawName + "log.layout.Header", this.logHead.trim().length() > 0 ? this.logHead + "\r\n" : "\u5546\u54C1\u4EE3\u7801,\u8DEF\u900F\u4EE3\u7801,\u65F6\u95F4,ASK,BID,\u4EF7\u683C,\u4E0A\u4E00\u53E3\u6709\u6548\u4EF7\u683C,\u6DA8\u8DCC\u5E45,\u662F\u5426\u88AB\u8FC7\u6EE4\r\n"); PropertyConfigurator.configure(pro); log.info("logger (" + itemName + ") configure finish!"); } for(QuoteSource quoteSource : this.quoteSourceMap.values()){ if(quoteSource.getProperty("LoggerName") != null && !"".equals(quoteSource.getProperty("LoggerName"))){ String loggerName = quoteSource.getProperty("LoggerName"); pro = new Properties(); pro.put("log4j.logger." + loggerName, "INFO, " + loggerName + "log"); pro.put("log4j.additivity." + loggerName,"false"); pro.put("log4j.appender." + loggerName + "log","org.apache.log4j.DailyRollingFileAppender"); pro.put("log4j.appender." + loggerName + "log.file","./logs/" + loggerName + ".log"); pro.put("log4j.appender." + loggerName + "log.DatePattern","'.'yyyy-MM-dd"); pro.put("log4j.appender." + loggerName + "log.Threshold","INFO"); pro.put("log4j.appender." + loggerName + "log.layout","com.puxtech.reuters.rfa.Common.MyPatternLayout"); pro.put("log4j.appender." + loggerName + "log.layout.ConversionPattern","%d{yyyy-MM-dd HH:mm:ss.SSS} - %m"); // pro.put("log4j.appender." + loggerName + "log.layout.Header", this.logHead); //\u5546\u54C1\u4EE3\u7801,\u8DEF\u900F\u4EE3\u7801,\u65F6\u95F4,ASK,BID,\u4EF7\u683C,\u4E0A\u4E00\u53E3\u6709\u6548\u4EF7\u683C,\u6DA8\u8DCC\u5E45,\u662F\u5426\u88AB\u8FC7\u6EE4\r\n PropertyConfigurator.configure(pro); log.info("logger (" + loggerName + ") configure finish!"); } } } public Element getFilterConfig(){ Element filterConfigEle = null; if(this.doc != null){ filterConfigEle = doc.getRootElement().element("Config").element("Filters"); } return filterConfigEle; } public List<QuoteSource> getQuoteSourceList() { return quoteSourceList; } public Map<String, QuoteSource> getQuoteSourceMap() { return quoteSourceMap; } public Map<String, List<Contract>> getQuoteSourceContractMap() { return quoteSourceContractMap; } public List<Contract> getContractList() { return contractList; } public String getSourcePath() { return SourcePath; } public String getCronExpress() { return cronExpress; } public void setSourcePath(String sourcePath) { SourcePath = sourcePath; } public void setCronExpress(String cronExpress) { this.cronExpress = cronExpress; } public File getConfigFile() { return configFile; } public String getSpreadFormat() { return spreadFormat; } public void setSpreadFormat(String spreadFormat) { this.spreadFormat = spreadFormat; } }
package java2.domain.builders; import java2.domain.AnnouncementCategory; import java2.domain.Term; public class AnnouncementCategoryBuilder { private int id; private AnnouncementCategory parentCategory; private Term title; private Term description; private AnnouncementCategoryBuilder() {} public static AnnouncementCategoryBuilder createAnnouncementCategory() { return new AnnouncementCategoryBuilder(); } public AnnouncementCategory build() { AnnouncementCategory announcementCategory = new AnnouncementCategory(); announcementCategory.setId(id); announcementCategory.setParentCategory(parentCategory); announcementCategory.setTitle(title); announcementCategory.setDescription(description); return announcementCategory; } public AnnouncementCategoryBuilder withId(int id) { this.id = id; return this; } public AnnouncementCategoryBuilder withParentCategory(AnnouncementCategory parentCategory) { this.parentCategory = parentCategory; return this; } public AnnouncementCategoryBuilder withParentCategory(AnnouncementCategoryBuilder parentCategory) { this.parentCategory = parentCategory.build(); return this; } public AnnouncementCategoryBuilder withTitle(Term title) { this.title = title; return this; } public AnnouncementCategoryBuilder withTitle(TermBuilder title) { this.title = title.build(); return this; } public AnnouncementCategoryBuilder withDescription(Term description) { this.description = description; return this; } public AnnouncementCategoryBuilder withDescription(TermBuilder description) { this.description = description.build(); return this; } }
package com.bierocratie.ui.component; import com.bierocratie.db.accounting.IncomeDAO; import com.bierocratie.db.accounting.InvoiceDAO; import com.bierocratie.model.accounting.BudgetYear; import com.bierocratie.model.accounting.Category; import com.bierocratie.model.accounting.CategoryAndMonth; import com.bierocratie.model.accounting.Invoice; import com.vaadin.addon.jpacontainer.JPAContainer; import com.vaadin.data.Item; import com.vaadin.ui.VerticalLayout; import java.math.BigInteger; import java.sql.SQLException; import java.util.List; import java.util.Map; /** * Created with IntelliJ IDEA. * User: pir * Date: 11/02/15 * Time: 23:15 * To change this template use File | Settings | File Templates. */ public class CashPlanTab extends VerticalLayout { /** * */ private static final long serialVersionUID = -1662482594147865263L; // TODO //@Inject private InvoiceDAO invoiceDAO = new InvoiceDAO(); //@Inject private IncomeDAO incomeDAO = new IncomeDAO(); private JPAContainer<Category> categories; private Map<String, BigInteger> incomesByMonth; private Map<String, BigInteger> outcomesByMonth; private Table table; private BudgetYear budgetYear; public CashPlanTab(BudgetYear budgetYear, JPAContainer<Category> categories, Map<String, BigInteger> incomesByMonth, Map<String, BigInteger> outcomesByMonth) throws SQLException { this.budgetYear = budgetYear; this.categories = categories; this.incomesByMonth = incomesByMonth; this.outcomesByMonth = outcomesByMonth; table = new Table(DashboardMenuBar.CASH_PLAN_TITLE); createTableContainerPropertiesAndItems(); if (budgetYear.isCurrentYear() && !BudgetYear.getCurrentMonth().equals(budgetYear.getLastMonth())) { createCurrentAmountsColumn(); } createTotalColumn(); table.setFooterVisible(true); table.setPageLength(categories.size() + 3); addComponent(table); } public BudgetYear getBudgetYear() { return budgetYear; } public Table getTable() { return table; } private void createCurrentAmountsColumn() throws SQLException { table.addContainerProperty("currentSum", BigInteger.class, null); table.setColumnHeader("currentSum", "Total en cours"); List<CategoryAndMonth> currentAmounts = invoiceDAO.getCurrentAmountsByYearForCash(budgetYear.getYear()); BigInteger sumCurrentOutcomes = BigInteger.ZERO; for (CategoryAndMonth amount : currentAmounts) { Item categoryItem = table.getItem(amount.getCategory()); BigInteger sum = amount.getAmount(); BigInteger noMonth = (BigInteger) categoryItem.getItemProperty(Invoice.DEFAULT_MONTH).getValue(); if (sum == null) { sum = BigInteger.ZERO; } if (noMonth == null) { noMonth = BigInteger.ZERO; } sum = sum.add(noMonth); categoryItem.getItemProperty("currentSum").setValue(sum); sumCurrentOutcomes = sumCurrentOutcomes.add(sum); } BigInteger sumCurrentIncomes = incomeDAO.getSumCurrentIncomesByYear(budgetYear.getYear()).toBigInteger(); table.getItem("outcomeByMonth").getItemProperty("currentSum").setValue(sumCurrentOutcomes); table.getItem("incomeByMonth").getItemProperty("currentSum").setValue(sumCurrentIncomes); BigInteger profit; if (sumCurrentIncomes == null) { profit = sumCurrentOutcomes.negate(); } else { profit = sumCurrentIncomes.subtract(sumCurrentOutcomes); } table.setColumnFooter("currentSum", Table.integerFormatter.format(profit.longValue())); } private void createTotalColumn() throws SQLException { table.addContainerProperty("sum", BigInteger.class, null); table.setColumnHeader("sum", "Total"); List<CategoryAndMonth> amounts = invoiceDAO.getAmountsByYearForCash(budgetYear.getYear()); BigInteger sumOutcomes = BigInteger.ZERO; for (CategoryAndMonth amount : amounts) { Item categoryItem = table.getItem(amount.getCategory()); BigInteger sum = amount.getAmount(); BigInteger noMonth = (BigInteger) categoryItem.getItemProperty(Invoice.DEFAULT_MONTH).getValue(); if (sum == null) { sum = BigInteger.ZERO; } if (noMonth == null) { noMonth = BigInteger.ZERO; } sum = sum.add(noMonth); categoryItem.getItemProperty("sum").setValue(sum); sumOutcomes = sumOutcomes.add(sum); } BigInteger sumIncomes = incomeDAO.getSumIncomesByYear(budgetYear.getYear()).toBigInteger(); table.getItem("outcomeByMonth").getItemProperty("sum").setValue(sumOutcomes); table.getItem("incomeByMonth").getItemProperty("sum").setValue(sumIncomes); BigInteger profit; if (sumIncomes == null) { profit = sumOutcomes.negate(); } else { profit = sumIncomes.subtract(sumOutcomes); } table.setColumnFooter("sum", Table.integerFormatter.format(profit.longValue())); } private void createTableContainerPropertiesAndItems() throws SQLException { table.addContainerProperty("category", String.class, null); table.setColumnHeader("category", "Catégorie"); Item incomeByMonthItem = table.addItem("incomeByMonth"); incomeByMonthItem.getItemProperty("category").setValue("--- Recettes ---"); for (Object id : categories.getItemIds()) { Category category = categories.getItem(id).getEntity(); Item categoryItem = table.addItem(category); categoryItem.getItemProperty("category").setValue(category.getName()); } Category emptyCategory = new Category(); Item categoryItem = table.addItem(emptyCategory); categoryItem.getItemProperty("category").setValue(emptyCategory.getName()); Item outcomeByMonthItem = table.addItem("outcomeByMonth"); outcomeByMonthItem.getItemProperty("category").setValue("--- Dépenses ---"); List<String> months = invoiceDAO.getMonthsByYearForCash(budgetYear.getYear()); if (budgetYear.isCurrentYear()) { months.add(Invoice.DEFAULT_MONTH); } for (String month : months) { createColumnForMonth(month, incomeByMonthItem, outcomeByMonthItem); } } private void createColumnForMonth(String month, Item incomeByMonthItem, Item outcomeByMonthItem) throws SQLException { table.addContainerProperty(month, BigInteger.class, null); List<CategoryAndMonth> amounts = invoiceDAO.getAmountsByMonthForCash(month); for (CategoryAndMonth amount : amounts) { Item categoryItem = table.getItem(amount.getCategory()); categoryItem.getItemProperty(amount.getMonth()).setValue(amount.getAmount()); } if (outcomesByMonth.get(month) != null) { outcomeByMonthItem.getItemProperty(month).setValue(outcomesByMonth.get(month)); } incomeByMonthItem.getItemProperty(month).setValue(incomesByMonth.get(month)); if (incomesByMonth.get(month) != null) { incomeByMonthItem.getItemProperty(month).setValue(incomesByMonth.get(month)); } BigInteger profit = BigInteger.ZERO; if (outcomesByMonth.get(month) != null) { if (incomesByMonth.get(month) == null) { profit = outcomesByMonth.get(month).negate(); } else { profit = incomesByMonth.get(month).subtract(outcomesByMonth.get(month)); } } table.setColumnFooter(month, Table.integerFormatter.format(profit.longValue())); } }
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.form.onboarding.service.base; import com.liferay.exportimport.kernel.lar.ExportImportHelperUtil; import com.liferay.exportimport.kernel.lar.ManifestSummary; import com.liferay.exportimport.kernel.lar.PortletDataContext; import com.liferay.exportimport.kernel.lar.StagedModelDataHandlerUtil; import com.liferay.exportimport.kernel.lar.StagedModelType; import com.liferay.form.onboarding.model.OBFormEntry; import com.liferay.form.onboarding.service.OBFormEntryLocalService; import com.liferay.form.onboarding.service.persistence.OBFormEntryPersistence; import com.liferay.form.onboarding.service.persistence.OBFormFieldMappingPersistence; import com.liferay.portal.aop.AopService; import com.liferay.portal.kernel.dao.db.DB; import com.liferay.portal.kernel.dao.db.DBManagerUtil; import com.liferay.portal.kernel.dao.jdbc.SqlUpdate; import com.liferay.portal.kernel.dao.jdbc.SqlUpdateFactoryUtil; import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery; import com.liferay.portal.kernel.dao.orm.DefaultActionableDynamicQuery; import com.liferay.portal.kernel.dao.orm.DynamicQuery; import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil; import com.liferay.portal.kernel.dao.orm.ExportActionableDynamicQuery; import com.liferay.portal.kernel.dao.orm.IndexableActionableDynamicQuery; import com.liferay.portal.kernel.dao.orm.Projection; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.model.PersistedModel; import com.liferay.portal.kernel.module.framework.service.IdentifiableOSGiService; import com.liferay.portal.kernel.search.Indexable; import com.liferay.portal.kernel.search.IndexableType; import com.liferay.portal.kernel.service.BaseLocalServiceImpl; import com.liferay.portal.kernel.service.PersistedModelLocalService; import com.liferay.portal.kernel.service.persistence.BasePersistence; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.portal.kernel.util.PortalUtil; import java.io.Serializable; import java.util.List; import javax.sql.DataSource; import org.osgi.service.component.annotations.Reference; /** * Provides the base implementation for the ob form entry local service. * * <p> * This implementation exists only as a container for the default service methods generated by ServiceBuilder. All custom service methods should be put in {@link com.liferay.form.onboarding.service.impl.OBFormEntryLocalServiceImpl}. * </p> * * @author Evan Thibodeau * @see com.liferay.form.onboarding.service.impl.OBFormEntryLocalServiceImpl * @generated */ public abstract class OBFormEntryLocalServiceBaseImpl extends BaseLocalServiceImpl implements AopService, IdentifiableOSGiService, OBFormEntryLocalService { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this class directly. Use <code>OBFormEntryLocalService</code> via injection or a <code>org.osgi.util.tracker.ServiceTracker</code> or use <code>com.liferay.form.onboarding.service.OBFormEntryLocalServiceUtil</code>. */ /** * Adds the ob form entry to the database. Also notifies the appropriate model listeners. * * <p> * <strong>Important:</strong> Inspect OBFormEntryLocalServiceImpl for overloaded versions of the method. If provided, use these entry points to the API, as the implementation logic may require the additional parameters defined there. * </p> * * @param obFormEntry the ob form entry * @return the ob form entry that was added */ @Indexable(type = IndexableType.REINDEX) @Override public OBFormEntry addOBFormEntry(OBFormEntry obFormEntry) { obFormEntry.setNew(true); return obFormEntryPersistence.update(obFormEntry); } /** * Creates a new ob form entry with the primary key. Does not add the ob form entry to the database. * * @param obFormEntryId the primary key for the new ob form entry * @return the new ob form entry */ @Override @Transactional(enabled = false) public OBFormEntry createOBFormEntry(long obFormEntryId) { return obFormEntryPersistence.create(obFormEntryId); } /** * Deletes the ob form entry with the primary key from the database. Also notifies the appropriate model listeners. * * <p> * <strong>Important:</strong> Inspect OBFormEntryLocalServiceImpl for overloaded versions of the method. If provided, use these entry points to the API, as the implementation logic may require the additional parameters defined there. * </p> * * @param obFormEntryId the primary key of the ob form entry * @return the ob form entry that was removed * @throws PortalException if a ob form entry with the primary key could not be found */ @Indexable(type = IndexableType.DELETE) @Override public OBFormEntry deleteOBFormEntry(long obFormEntryId) throws PortalException { return obFormEntryPersistence.remove(obFormEntryId); } /** * Deletes the ob form entry from the database. Also notifies the appropriate model listeners. * * <p> * <strong>Important:</strong> Inspect OBFormEntryLocalServiceImpl for overloaded versions of the method. If provided, use these entry points to the API, as the implementation logic may require the additional parameters defined there. * </p> * * @param obFormEntry the ob form entry * @return the ob form entry that was removed * @throws PortalException */ @Indexable(type = IndexableType.DELETE) @Override public OBFormEntry deleteOBFormEntry(OBFormEntry obFormEntry) throws PortalException { return obFormEntryPersistence.remove(obFormEntry); } @Override public DynamicQuery dynamicQuery() { Class<?> clazz = getClass(); return DynamicQueryFactoryUtil.forClass( OBFormEntry.class, clazz.getClassLoader()); } /** * Performs a dynamic query on the database and returns the matching rows. * * @param dynamicQuery the dynamic query * @return the matching rows */ @Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return obFormEntryPersistence.findWithDynamicQuery(dynamicQuery); } /** * Performs a dynamic query on the database and returns a range of the matching rows. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent, then the query will include the default ORDER BY logic from <code>com.liferay.form.onboarding.model.impl.OBFormEntryModelImpl</code>. * </p> * * @param dynamicQuery the dynamic query * @param start the lower bound of the range of model instances * @param end the upper bound of the range of model instances (not inclusive) * @return the range of matching rows */ @Override public <T> List<T> dynamicQuery( DynamicQuery dynamicQuery, int start, int end) { return obFormEntryPersistence.findWithDynamicQuery( dynamicQuery, start, end); } /** * Performs a dynamic query on the database and returns an ordered range of the matching rows. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent, then the query will include the default ORDER BY logic from <code>com.liferay.form.onboarding.model.impl.OBFormEntryModelImpl</code>. * </p> * * @param dynamicQuery the dynamic query * @param start the lower bound of the range of model instances * @param end the upper bound of the range of model instances (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching rows */ @Override public <T> List<T> dynamicQuery( DynamicQuery dynamicQuery, int start, int end, OrderByComparator<T> orderByComparator) { return obFormEntryPersistence.findWithDynamicQuery( dynamicQuery, start, end, orderByComparator); } /** * Returns the number of rows matching the dynamic query. * * @param dynamicQuery the dynamic query * @return the number of rows matching the dynamic query */ @Override public long dynamicQueryCount(DynamicQuery dynamicQuery) { return obFormEntryPersistence.countWithDynamicQuery(dynamicQuery); } /** * Returns the number of rows matching the dynamic query. * * @param dynamicQuery the dynamic query * @param projection the projection to apply to the query * @return the number of rows matching the dynamic query */ @Override public long dynamicQueryCount( DynamicQuery dynamicQuery, Projection projection) { return obFormEntryPersistence.countWithDynamicQuery( dynamicQuery, projection); } @Override public OBFormEntry fetchOBFormEntry(long obFormEntryId) { return obFormEntryPersistence.fetchByPrimaryKey(obFormEntryId); } /** * Returns the ob form entry matching the UUID and group. * * @param uuid the ob form entry's UUID * @param groupId the primary key of the group * @return the matching ob form entry, or <code>null</code> if a matching ob form entry could not be found */ @Override public OBFormEntry fetchOBFormEntryByUuidAndGroupId( String uuid, long groupId) { return obFormEntryPersistence.fetchByUUID_G(uuid, groupId); } /** * Returns the ob form entry with the primary key. * * @param obFormEntryId the primary key of the ob form entry * @return the ob form entry * @throws PortalException if a ob form entry with the primary key could not be found */ @Override public OBFormEntry getOBFormEntry(long obFormEntryId) throws PortalException { return obFormEntryPersistence.findByPrimaryKey(obFormEntryId); } @Override public ActionableDynamicQuery getActionableDynamicQuery() { ActionableDynamicQuery actionableDynamicQuery = new DefaultActionableDynamicQuery(); actionableDynamicQuery.setBaseLocalService(obFormEntryLocalService); actionableDynamicQuery.setClassLoader(getClassLoader()); actionableDynamicQuery.setModelClass(OBFormEntry.class); actionableDynamicQuery.setPrimaryKeyPropertyName("obFormEntryId"); return actionableDynamicQuery; } @Override public IndexableActionableDynamicQuery getIndexableActionableDynamicQuery() { IndexableActionableDynamicQuery indexableActionableDynamicQuery = new IndexableActionableDynamicQuery(); indexableActionableDynamicQuery.setBaseLocalService( obFormEntryLocalService); indexableActionableDynamicQuery.setClassLoader(getClassLoader()); indexableActionableDynamicQuery.setModelClass(OBFormEntry.class); indexableActionableDynamicQuery.setPrimaryKeyPropertyName( "obFormEntryId"); return indexableActionableDynamicQuery; } protected void initActionableDynamicQuery( ActionableDynamicQuery actionableDynamicQuery) { actionableDynamicQuery.setBaseLocalService(obFormEntryLocalService); actionableDynamicQuery.setClassLoader(getClassLoader()); actionableDynamicQuery.setModelClass(OBFormEntry.class); actionableDynamicQuery.setPrimaryKeyPropertyName("obFormEntryId"); } @Override public ExportActionableDynamicQuery getExportActionableDynamicQuery( final PortletDataContext portletDataContext) { final ExportActionableDynamicQuery exportActionableDynamicQuery = new ExportActionableDynamicQuery() { @Override public long performCount() throws PortalException { ManifestSummary manifestSummary = portletDataContext.getManifestSummary(); StagedModelType stagedModelType = getStagedModelType(); long modelAdditionCount = super.performCount(); manifestSummary.addModelAdditionCount( stagedModelType, modelAdditionCount); long modelDeletionCount = ExportImportHelperUtil.getModelDeletionCount( portletDataContext, stagedModelType); manifestSummary.addModelDeletionCount( stagedModelType, modelDeletionCount); return modelAdditionCount; } }; initActionableDynamicQuery(exportActionableDynamicQuery); exportActionableDynamicQuery.setAddCriteriaMethod( new ActionableDynamicQuery.AddCriteriaMethod() { @Override public void addCriteria(DynamicQuery dynamicQuery) { portletDataContext.addDateRangeCriteria( dynamicQuery, "modifiedDate"); } }); exportActionableDynamicQuery.setCompanyId( portletDataContext.getCompanyId()); exportActionableDynamicQuery.setPerformActionMethod( new ActionableDynamicQuery.PerformActionMethod<OBFormEntry>() { @Override public void performAction(OBFormEntry obFormEntry) throws PortalException { StagedModelDataHandlerUtil.exportStagedModel( portletDataContext, obFormEntry); } }); exportActionableDynamicQuery.setStagedModelType( new StagedModelType( PortalUtil.getClassNameId(OBFormEntry.class.getName()))); return exportActionableDynamicQuery; } /** * @throws PortalException */ public PersistedModel createPersistedModel(Serializable primaryKeyObj) throws PortalException { return obFormEntryPersistence.create(((Long)primaryKeyObj).longValue()); } /** * @throws PortalException */ @Override public PersistedModel deletePersistedModel(PersistedModel persistedModel) throws PortalException { return obFormEntryLocalService.deleteOBFormEntry( (OBFormEntry)persistedModel); } public BasePersistence<OBFormEntry> getBasePersistence() { return obFormEntryPersistence; } /** * @throws PortalException */ @Override public PersistedModel getPersistedModel(Serializable primaryKeyObj) throws PortalException { return obFormEntryPersistence.findByPrimaryKey(primaryKeyObj); } /** * Returns all the ob form entries matching the UUID and company. * * @param uuid the UUID of the ob form entries * @param companyId the primary key of the company * @return the matching ob form entries, or an empty list if no matches were found */ @Override public List<OBFormEntry> getOBFormEntriesByUuidAndCompanyId( String uuid, long companyId) { return obFormEntryPersistence.findByUuid_C(uuid, companyId); } /** * Returns a range of ob form entries matching the UUID and company. * * @param uuid the UUID of the ob form entries * @param companyId the primary key of the company * @param start the lower bound of the range of ob form entries * @param end the upper bound of the range of ob form entries (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the range of matching ob form entries, or an empty list if no matches were found */ @Override public List<OBFormEntry> getOBFormEntriesByUuidAndCompanyId( String uuid, long companyId, int start, int end, OrderByComparator<OBFormEntry> orderByComparator) { return obFormEntryPersistence.findByUuid_C( uuid, companyId, start, end, orderByComparator); } /** * Returns the ob form entry matching the UUID and group. * * @param uuid the ob form entry's UUID * @param groupId the primary key of the group * @return the matching ob form entry * @throws PortalException if a matching ob form entry could not be found */ @Override public OBFormEntry getOBFormEntryByUuidAndGroupId(String uuid, long groupId) throws PortalException { return obFormEntryPersistence.findByUUID_G(uuid, groupId); } /** * Returns a range of all the ob form entries. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent, then the query will include the default ORDER BY logic from <code>com.liferay.form.onboarding.model.impl.OBFormEntryModelImpl</code>. * </p> * * @param start the lower bound of the range of ob form entries * @param end the upper bound of the range of ob form entries (not inclusive) * @return the range of ob form entries */ @Override public List<OBFormEntry> getOBFormEntries(int start, int end) { return obFormEntryPersistence.findAll(start, end); } /** * Returns the number of ob form entries. * * @return the number of ob form entries */ @Override public int getOBFormEntriesCount() { return obFormEntryPersistence.countAll(); } /** * Updates the ob form entry in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. * * <p> * <strong>Important:</strong> Inspect OBFormEntryLocalServiceImpl for overloaded versions of the method. If provided, use these entry points to the API, as the implementation logic may require the additional parameters defined there. * </p> * * @param obFormEntry the ob form entry * @return the ob form entry that was updated */ @Indexable(type = IndexableType.REINDEX) @Override public OBFormEntry updateOBFormEntry(OBFormEntry obFormEntry) { return obFormEntryPersistence.update(obFormEntry); } @Override public Class<?>[] getAopInterfaces() { return new Class<?>[] { OBFormEntryLocalService.class, IdentifiableOSGiService.class, PersistedModelLocalService.class }; } @Override public void setAopProxy(Object aopProxy) { obFormEntryLocalService = (OBFormEntryLocalService)aopProxy; } /** * Returns the OSGi service identifier. * * @return the OSGi service identifier */ @Override public String getOSGiServiceIdentifier() { return OBFormEntryLocalService.class.getName(); } protected Class<?> getModelClass() { return OBFormEntry.class; } protected String getModelClassName() { return OBFormEntry.class.getName(); } /** * Performs a SQL query. * * @param sql the sql query */ protected void runSQL(String sql) { try { DataSource dataSource = obFormEntryPersistence.getDataSource(); DB db = DBManagerUtil.getDB(); sql = db.buildSQL(sql); sql = PortalUtil.transformSQL(sql); SqlUpdate sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate( dataSource, sql); sqlUpdate.update(); } catch (Exception exception) { throw new SystemException(exception); } } protected OBFormEntryLocalService obFormEntryLocalService; @Reference protected OBFormEntryPersistence obFormEntryPersistence; @Reference protected OBFormFieldMappingPersistence obFormFieldMappingPersistence; @Reference protected com.liferay.counter.kernel.service.CounterLocalService counterLocalService; @Reference protected com.liferay.portal.kernel.service.ClassNameLocalService classNameLocalService; @Reference protected com.liferay.portal.kernel.service.GroupLocalService groupLocalService; @Reference protected com.liferay.portal.kernel.service.ResourceLocalService resourceLocalService; @Reference protected com.liferay.portal.kernel.service.UserLocalService userLocalService; }
package birkann.com.kanaltakip.DbObject; /** * Created by birkan on 23.10.2016. */ public class ChannelStatistics { private String id; private String viewsCount; private String subCount; private String videoCount; public ChannelStatistics(String id, String viewsCount, String subCount, String videoCount) { this.id = id; this.viewsCount = viewsCount; this.subCount = subCount; this.videoCount = videoCount; } public ChannelStatistics(String id) { this.id = id; } public String getId() { return id; } public String getViewsCount() { return viewsCount; } public String getSubCount() { return subCount; } public String getVideoCount() { return videoCount; } public void setId(String id) { this.id = id; } public void setViewsCount(String viewsCount) { this.viewsCount = viewsCount; } public void setSubCount(String subCount) { this.subCount = subCount; } public void setVideoCount(String videoCount) { this.videoCount = videoCount; } }
package com.ece496.feature_handling; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.view.View.OnClickListener; import com.ece496.R; import com.ece496.assignments.Essay; import com.ece496.assignments.Exam; import com.ece496.assignments.Presentation; import com.ece496.assignments.CustomAssignment; public class Assignment extends AppCompatActivity { public Assignment() { // Required empty public constructor } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_assignment); Button button = (Button) findViewById(R.id.button_back); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { finish(); } }); Button button1 = (Button) findViewById(R.id.button_essay); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Assignment.this, Essay.class); startActivity(i); } }); Button button2 = (Button) findViewById(R.id.button_exam); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Assignment.this, Exam.class); startActivity(i); } }); Button button3 = (Button) findViewById(R.id.button_custom_assignment); button3.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Assignment.this, CustomAssignment.class); startActivity(i); } }); Button button4 = (Button) findViewById(R.id.button_presentation); button4.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Assignment.this, Presentation.class); startActivity(i); } }); } }
package com.packtpub.javaee8; import org.glassfish.jersey.media.multipart.MultiPartFeature; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import java.util.HashSet; import java.util.Set; /** * Configures a JAX-RS endpoint. */ @ApplicationPath("api") public class JAXRSConfiguration extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<>(); classes.add(DocumentsResource.class); classes.add(MultiPartFeature.class); classes.add(HateosResource.class); classes.add(JsonbResource.class); classes.add(JsonpResource.class); classes.add(VersionResource.class); return classes; } }
package com.wood.videoplayer; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; public class NetFileFragment extends ListFragment { TextView showTextView; public NetFileFragment() { // TODO Auto-generated constructor stub } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.file_list, container,false); showTextView=(TextView)view.findViewById(android.R.id.empty); showTextView.setText("找不到服务器,请检查你的网络后再试"); return view; } @Override public void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); } }
package com.tencent.mm.plugin.wallet_core.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.wallet_core.b.b; import com.tencent.mm.plugin.wallet_core.model.Bankcard; import com.tencent.mm.plugin.wxpay.a$i; import com.tencent.mm.ui.widget.a.c$a; import com.tencent.mm.wallet_core.c; class WalletVerifyCodeUI$5 implements OnClickListener { final /* synthetic */ Bankcard oZt; final /* synthetic */ WalletVerifyCodeUI pyT; WalletVerifyCodeUI$5(WalletVerifyCodeUI walletVerifyCodeUI, Bankcard bankcard) { this.pyT = walletVerifyCodeUI; this.oZt = bankcard; } public final void onClick(View view) { c cDK = this.pyT.cDK(); if (!WalletVerifyCodeUI.a(this.pyT) || (cDK instanceof b)) { this.pyT.bQE(); return; } int i; if (this.oZt == null) { i = 0; } else if (this.oZt.bOs()) { i = 1; } else if (this.oZt.bOt()) { i = 3; } else { i = 2; } c$a c_a = new c$a(this.pyT.mController.tml); c_a.Gq(a$i.wallet_verify_code_comfirm_title); c_a.abu(this.pyT.getString(a$i.wallet_verify_code_comfirm_text, new Object[]{this.pyT.bQD()})); c_a.mF(true); c_a.Gt(a$i.wallet_verify_code_comfirm_ok_btn); c_a.Gu(a$i.wallet_verify_code_comfirm_cancel_btn); c_a.a(new 1(this, i)); c_a.b(new 2(this, i)); c_a.anj().show(); h.mEJ.h(15443, new Object[]{Integer.valueOf(1)}); WalletVerifyCodeUI.b(this.pyT); } }
package martin.s4a.shift4all2; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.fourmob.datetimepicker.date.DatePickerDialog; import com.sleepbot.datetimepicker.time.RadialPickerLayout; import com.sleepbot.datetimepicker.time.TimePickerDialog; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.Calendar; import martin.s4a.library.Database; import martin.s4a.library.NoteHelper; import martin.s4a.library.ShiftHelper; import martin.s4a.library.WakeUpAlarm; import martin.s4a.templates.NotesTemplate; import martin.s4a.templates.SchemeTemplates; import martin.s4a.templates.ShiftTemplates; public class ChangeCalendarValues extends ActionBarActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener { public static final String TIMEPICKER_TAG = "timepicker"; public static final String DATEPICKER_TAG = "datepicker"; ActionBar actionBar; LinearLayout changeShift, schemeDate; EditText changeShiftReminder, note, noteReminder; SchemeListAdapter schemeAdapter; Database database; ArrayList<ShiftTemplates> shifts; ArrayList<SchemeTemplates> schemes; ArrayList<NotesTemplate> notes; LinearLayout circle, schemeCircle; TextView title, shortTitle,iconTitle, schemeTitle; String titleS, timeFromS, timeToS, iconTitleS; ImageView deleteShift, deleteNote; EditText schemeTimeFrom, schemeTimeTo; CheckBox checkbox; View clickedTime; DatePickerDialog datePickerDialog; int positionOfShift = -1; int day, month, year; TimePickerDialog timePickerDialog; Calendar calendar; Calendar cal; int positionOfScheme = -1; ShiftHelper shiftHelper; NoteHelper noteHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_calendar_values); actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); database = new Database(ChangeCalendarValues.this); Bundle b = getIntent().getExtras(); day = b.getInt("day"); month = b.getInt("month"); year = b.getInt("year"); setTitle(String.valueOf(day) + ". " + new DateFormatSymbols().getMonths()[month] + " " + String.valueOf(year)); title = (TextView)findViewById(R.id.textView_change_values_list_title); shortTitle = (TextView)findViewById(R.id.textView_change_values_list_desc); iconTitle = (TextView)findViewById(R.id.textView_change_values_list_icon_title); circle = (LinearLayout)findViewById(R.id.linearLayout_change_values_list_circle); changeShift = (LinearLayout)findViewById(R.id.linearLayout_change_values_chage_shift); changeShiftReminder = (EditText)findViewById(R.id.editText_change_values_reminder); noteReminder = (EditText)findViewById(R.id.editText_change_values_note_reminder); note = (EditText)findViewById(R.id.editText_change_values_noter); deleteShift = (ImageView)findViewById(R.id.imageView_shift_delete); deleteNote = (ImageView)findViewById(R.id.imageView_note_delete); checkbox = (CheckBox)findViewById(R.id.checkBox_change_values_scheme_date_infinite); schemeTimeFrom = (EditText)findViewById(R.id.editText_change_values_scheme_date_from); schemeTimeTo = (EditText)findViewById(R.id.editText_change_values_scheme_date_to); schemeDate = (LinearLayout)findViewById(R.id.linearLayout_change_values_chage_scheme_date); schemeTitle = (TextView)findViewById(R.id.textView_change_values_scheme_list_title); schemeCircle = (LinearLayout)findViewById(R.id.linearLayout_change_values_scheme_list_circle); ((GradientDrawable) circle.getBackground()).setColor(Color.parseColor("#BBBBBB")); title.setText("Vlastní Směna"); shortTitle.setText("Zvolte kliknutím"); iconTitle.setText("?"); shifts = database.getAllShifts(); schemes = database.getAllScheme(); calendar = Calendar.getInstance(); cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.MONTH, month); cal.set(Calendar.YEAR, year); datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), false); timePickerDialog = TimePickerDialog.newInstance(ChangeCalendarValues.this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true, false); shiftHelper = new ShiftHelper(database, cal); noteHelper = new NoteHelper(database,cal); //Tohle ještě zlepšit - nahradit metodu, tak že z obsahu vytvořím fragment if(shiftHelper.getCustomShift() != -1) { setCustomShiftView(shiftHelper.getCustomShift()); } changeShiftReminder.setText(WakeUpAlarm.getValuesOfDialog(ChangeCalendarValues.this, shiftHelper.getShiftAlarmPosition())); note.setText(noteHelper.getNote()); noteReminder.setText(noteHelper.getAlarm()); changeShift.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final MaterialDialog dialog = new MaterialDialog.Builder(ChangeCalendarValues.this) .title(R.string.choose_shift) .adapter(new ShiftListAdapter(ChangeCalendarValues.this), new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) { } }) .build(); ListView listView = dialog.getListView(); if (listView != null) { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setCustomShiftView(position); positionOfShift = position; dialog.dismiss(); } }); } dialog.show(); } }); schemeDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final MaterialDialog dialog = new MaterialDialog.Builder(ChangeCalendarValues.this) .title(R.string.choose_shift) .adapter(new SchemeListAdapter(ChangeCalendarValues.this), new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) { } }) .build(); ListView listView = dialog.getListView(); schemeAdapter = new SchemeListAdapter(ChangeCalendarValues.this); listView.setAdapter(schemeAdapter); if (listView != null) { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setSchemeDateView(position); positionOfScheme = position; dialog.dismiss(); } }); } dialog.show(); } }); changeShiftReminder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(ChangeCalendarValues.this) .callback(new MaterialDialog.ButtonCallback() { @Override public void onNeutral(MaterialDialog dialog) { } }) .items(getResources().getStringArray(R.array.alarm_values)) .autoDismiss(false) .itemsCallbackSingleChoice(1, new MaterialDialog.ListCallbackSingleChoice() { @Override public boolean onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) { return false; } }) .negativeText("OK") .title(getString(R.string.dialog_alarm_title)) .content(ChangeCalendarValues.this.getString(R.string.alertdialog_shift_content)) .show(); } }); noteReminder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clickedTime = v; timePickerDialog.setVibrate(false); timePickerDialog.setCloseOnSingleTapMinute(false); timePickerDialog.show(getSupportFragmentManager(), TIMEPICKER_TAG); timePickerDialog = TimePickerDialog.newInstance(ChangeCalendarValues.this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true, false); } }); schemeTimeFrom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setDateFromDialog(v); } }); schemeTimeTo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setDateFromDialog(v); } }); checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(checkbox.isChecked()) { schemeTimeTo.setEnabled(false); schemeTimeTo.setTag("Inf"); schemeTimeTo.setText("Na neučito"); } else { schemeTimeTo.setText(""); schemeTimeTo.setTag(""); schemeTimeTo.setEnabled(true); } } }); deleteShift.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(ChangeCalendarValues.this) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); ((GradientDrawable) circle.getBackground()).setColor(Color.parseColor("#BBBBBB")); title.setText("Vlastní Směna"); shortTitle.setText("Zvolte kliknutím"); iconTitle.setText("?"); database.deleteCustomShift(day,month,year); //místo pro smazani z database dialog.dismiss(); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); } }) .content(getString(R.string.alertdialog_shift_content)) .positiveText(getString(R.string.alertdialog_remove)) .negativeText(getString(R.string.alertdialog_cancel)) .show(); } }); deleteNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(ChangeCalendarValues.this) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); note.setText(""); noteReminder.setText(""); database.deleteNote(day,month,year); dialog.dismiss(); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); } }) .content(getString(R.string.alertdialog_note_content)) .positiveText(getString(R.string.alertdialog_remove)) .negativeText(getString(R.string.alertdialog_cancel)) .show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_change_calendar_values, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_confirm) { if(positionOfShift != -1) { if (shiftHelper.isEdited()) { database.updateCustomShift(day, month, year, positionOfShift, "-1"); finish(); } else { database.insertCustomShift(day, month, year, positionOfShift, "-1"); finish(); } } else { database.deleteCustomShift(day, month, year); } if(note.getText().length() != 0) { if(noteHelper.isEdited()) { database.updateNote(day, month, year, note.getText().toString(), noteReminder.getText().toString()); finish(); } else { database.insertNote(day, month, year, note.getText().toString(), noteReminder.getText().toString()); finish(); } } else { if(noteHelper.isEdited()) database.deleteNote(day,month,year); } if(positionOfScheme != -1) { if ((schemeTimeFrom.getText().toString().length() == 0) || (schemeTimeTo.getText().toString().length() == 0)) { Toast.makeText(ChangeCalendarValues.this, "musiš vyplnit všechna pole", Toast.LENGTH_LONG).show(); } else if (isSecondComparedCalendarBigger(schemeTimeFrom.getTag().toString(), schemeTimeTo.getTag().toString())) { Toast.makeText(ChangeCalendarValues.this, "Od musí být větší než do", Toast.LENGTH_LONG).show(); } else { database.insertSchemeDates(schemeTimeFrom.getTag().toString(), schemeTimeTo.getTag().toString(), positionOfScheme); finish(); } } updateWidget(ChangeCalendarValues.this); return true; } else if(id == R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } public void setCustomShiftView(int position) { titleS = shifts.get(position).getTitle(); timeFromS = shifts.get(position).getTimeFrom(); timeToS = shifts.get(position).getTimeTo(); iconTitleS = shifts.get(position).getShortTitle(); ((GradientDrawable) circle.getBackground()).setColor(Color.parseColor(shifts.get(position).getColor())); title.setText(titleS); shortTitle.setText(timeFromS + " - " + timeToS); iconTitle.setText(iconTitleS); positionOfShift = position; } public void setSchemeDateView(int position) { ((GradientDrawable) schemeCircle.getBackground()).setColor(getResources().getColor(R.color.theme_color)); schemeTitle.setText(schemes.get(position).getTitle()); // iconTitle.setText("S"); } public void updateWidget(Context context) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int appWidgetIds[] = appWidgetManager.getAppWidgetIds(new ComponentName(context, WeekWidgetProvider.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.gridView_week_widget); } @Override public void onTimeSet(RadialPickerLayout radialPickerLayout, int i, int i2) { EditText time = (EditText) clickedTime; int hour = i; int minute = i2; String minuteString = ""; if(minute < 10) { minuteString = "0" + String.valueOf(minute); } else minuteString = String.valueOf(i2); time.setText(hour + ":" + minuteString); } public void setDateFromDialog(View v) { clickedTime = v; datePickerDialog.setVibrate(false); //datePickerDialog.setCloseOnSingleTapMinute(false); datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG); } @Override public void onDateSet(DatePickerDialog datePickerDialog, int i, int i2, int i3) { EditText date = (EditText) clickedTime; date.setTag(String.valueOf(i3) + "." + String.valueOf(i2) + "." + String.valueOf(i)); date.setText(String.valueOf(i3) + ". " + new DateFormatSymbols().getMonths()[i2] + " " + String.valueOf(i)); } public boolean isSecondComparedCalendarBigger(String first, String second) { if(second != "Inf") { String[] firstC = first.split("\\."); String[] secondC = second.split("\\."); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.add(Calendar.DAY_OF_MONTH, Integer.parseInt(firstC[0])); c2.add(Calendar.DAY_OF_MONTH, Integer.parseInt(secondC[0])); c1.add(Calendar.MONTH, Integer.parseInt(firstC[1])); c2.add(Calendar.MONTH, Integer.parseInt(secondC[1])); c1.add(Calendar.YEAR, Integer.parseInt(firstC[2])); c2.add(Calendar.YEAR, Integer.parseInt(secondC[2])); if (c1.getTimeInMillis() < c2.getTimeInMillis()) return false; else return true; }else return false; } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.qq.net; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * <pre> * 实现Proxy的一些共同的部分 * </pre> * * @author luma */ public abstract class AbstractProxy implements IProxy, INIOHandler { /** Log类 */ private static final Log log = LogFactory.getLog(AbstractProxy.class); /** 连接Proxy的channel */ protected SocketChannel socketChannel; /** udp channel */ protected DatagramChannel datagramChannel; /** 代理事件处理器 */ protected IProxyHandler handler; /** byte buffer */ protected ByteBuffer buffer; /** 用户名 */ protected String username; /** 密码 */ protected String password; /** 要连接的服务器地址 */ protected InetSocketAddress serverAddress; /** 代理服务器地址 */ protected InetSocketAddress proxyAddress; /** 当前状态 */ protected int status; /** proxy是否已经连接上 */ protected boolean connected; /** 是否udp,该字段只对Socks5代理有效 */ protected boolean udp; /** 客户端端口,该字段制作UDP Socks5时有效 */ protected int clientPort; /** * 构造函数 * * @throws IOException */ public AbstractProxy(IProxyHandler handler) throws IOException { this.handler = handler; buffer = ByteBuffer.allocateDirect(300); username = password = ""; connected = false; udp = false; socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); } /** * 创建一个UDP Socks5代理对象 * * @param handler * @param channel */ public AbstractProxy(IProxyHandler handler, DatagramChannel channel) { this.handler = handler; buffer = ByteBuffer.allocateDirect(300); username = password = ""; connected = true; udp = true; datagramChannel = channel; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.IProxy#channel() */ public SelectableChannel channel() { if(socketChannel != null) return socketChannel; else return datagramChannel; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.net.IProxy#getNIOHandler() */ public INIOHandler getNIOHandler() { return this; } /** * 发送 */ protected void send() { try { if(connected) { if(socketChannel != null) socketChannel.write(buffer); if(datagramChannel != null) datagramChannel.write(buffer); } } catch (IOException e) { log.error(e.getMessage()); handler.proxyError(e.getMessage()); } } /** * 接收数据 * @throws IOException */ protected void receive() { try { buffer.clear(); if(socketChannel != null) for (int len = socketChannel.read(buffer); len > 0; len = socketChannel.read(buffer)); else datagramChannel.receive(buffer); buffer.flip(); } catch (IOException e) { log.error(e.getMessage()); handler.proxyError(e.getMessage()); } } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.IProxy#start() */ public void start() { try { // 打开连接代理的channel if(socketChannel != null) socketChannel.connect(proxyAddress); if(datagramChannel != null) datagramChannel.connect(proxyAddress); } catch (Exception e) { log.error(e.getMessage()); handler.proxyError(e.getMessage()); } } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.IProxy#dispose() */ public void dispose() { try { if(socketChannel != null) socketChannel.close(); if(datagramChannel != null) datagramChannel.close(); } catch(Exception e) { } } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.INIOHandler#processConnect(java.nio.channels.SelectionKey) */ public void processConnect(SelectionKey sk) throws IOException { if(connected) return; //完成SocketChannel的连接 socketChannel.finishConnect(); while(!socketChannel.isConnected()) { try { Thread.sleep(300); } catch (InterruptedException e) { // 没有什么要做的 } socketChannel.finishConnect(); } sk.interestOps(SelectionKey.OP_READ); connected = true; log.debug("已连接上代理服务器"); } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.INIOHandler#processError(java.lang.Exception) */ public void processError(Exception e) { handler.proxyError(e.getMessage()); } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.IProxy#setProxyAddress(java.net.InetSocketAddress) */ public void setProxyAddress(InetSocketAddress proxyAddress) { this.proxyAddress = proxyAddress; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.IProxy#setServerAddress(java.net.InetSocketAddress) */ public void setRemoteAddress(InetSocketAddress serverAddress) { this.serverAddress = serverAddress; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.IProxy#setClientPort(int) */ public void setClientPort(int p) { clientPort = p; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @param username The username to set. */ public void setUsername(String username) { this.username = username; } }
package com.crimson.picshu; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.crimson.picshu.gallery.FolderwiseImageActivity; import com.crimson.picshu.login_signup.OtpGenerateActivity; import com.crimson.picshu.utils.ApiRequest; import com.crimson.picshu.utils.UserSessionManager; import com.crimson.picshu.utils.Utility; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; public class SplashScreen extends AppCompatActivity { final int SPLASH_TIME_OUT = 3000; UserSessionManager sessionManager; String versioncode = "22"; //String versionapi = "http://picshu.com/picshu/index.php/API/version_controller"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); //getSupportActionBar().hide(); sessionManager = new UserSessionManager(this); // getVersion(); new Handler().postDelayed(new Runnable() { @Override public void run() { String user_id = sessionManager.getUserId(); Log.d("TAG111", "userid-" + user_id); if (user_id.isEmpty()) { Intent intent = new Intent(SplashScreen.this, OtpGenerateActivity.class); startActivity(intent); finish(); } else { Intent mainIntent = new Intent(SplashScreen.this, FolderwiseImageActivity.class); startActivity(mainIntent); finish(); } } }, SPLASH_TIME_OUT); } private void getVersion() { RestAdapter adapter = new RestAdapter.Builder() .setEndpoint("https://picshu.com/picshu/index.php/API/version_controller") .build(); //Finally building the adapter //Creating object for our interface ApiRequest api = adapter.create(ApiRequest.class); api.version( //Passing the values by getting it from editTexts //Creating an anonymous callback new Callback<Response>() { @Override public void success(Response result, Response response) { //On success we will read the server's output using bufferedreader //Creating a bufferedreader object BufferedReader reader = null; //An string to store output from the server String output = ""; try { //Initializing buffered reader reader = new BufferedReader(new InputStreamReader(result.getBody().in())); //Reading the output in the string output = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } //Displaying the output as a toast // Toast.makeText(Main2Activity.this, output, Toast.LENGTH_LONG).show(); if (output == null || output.equals("") || output.equals("null") || output.contains("error") || output.contains("exception") || output.contains("Exception")) { Toast.makeText(SplashScreen.this, "Server Error!!", Toast.LENGTH_LONG).show(); } else { try { JSONArray jsonArray = new JSONArray(output); JSONObject jsonObject = jsonArray.getJSONObject(0); if (jsonObject.getString("version").equalsIgnoreCase(versioncode)) { try { new Handler().postDelayed(new Runnable() { @Override public void run() { String user_id = sessionManager.getUserId(); Log.d("TAG111", "userid-" + user_id); if (user_id.isEmpty()) { Intent intent = new Intent(SplashScreen.this, OtpGenerateActivity.class); startActivity(intent); finish(); } else { Intent mainIntent = new Intent(SplashScreen.this, FolderwiseImageActivity.class); startActivity(mainIntent); finish(); } } }, SPLASH_TIME_OUT); } catch (Exception e) { e.printStackTrace(); } } else { showDialogForVersion(); } } catch (JSONException e) { e.printStackTrace(); } } } @Override public void failure(RetrofitError error) { // Toast.makeText(OnBoardingActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show(); //If any error occured displaying the error as toast Toast.makeText(SplashScreen.this, "" + error.getMessage() + "Error in Connection in getversion", Toast.LENGTH_LONG).show(); } } ); } private void showDialogForVersion() { LayoutInflater inflater = LayoutInflater.from(SplashScreen.this); View dialogView = inflater.inflate(R.layout.dialog_for_version, new LinearLayout(SplashScreen.this), false); final AlertDialog dialog = new AlertDialog.Builder(SplashScreen.this) .setView(dialogView) .create(); DisplayMetrics metrics = new DisplayMetrics(); int nWidth = metrics.widthPixels; int nHeight = metrics.heightPixels; dialog.getWindow().setLayout(nWidth, nHeight); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); dialog.setCancelable(false); final TextView scrolloingText, tv_cancel, tv_ok; scrolloingText = dialog.findViewById(R.id.scrolloingText); tv_ok = dialog.findViewById(R.id.tv_ok); tv_cancel = dialog.findViewById(R.id.tv_cancel); scrolloingText.setSelected(true); scrolloingText.setMarqueeRepeatLimit(-1); tv_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); tv_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName))); } finish(); } }); } }
package rent.common.dtos; import rent.common.entity.AccountServiceEntity; import rent.common.entity.CalculationTypeEntity; import rent.common.entity.MeasurementUnitEntity; import rent.common.entity.TariffEntity; public class AccountServiceCalculationDto { private AccountServiceEntity accountService; private Double sum; private Double consumption; private TariffEntity tariff; private CalculationTypeEntity tariffCalculationType; private MeasurementUnitEntity tariffMeasurementUnit; private Double tariffValue; private Integer accountServiceDaysActive; public AccountServiceEntity getAccountService() { return accountService; } public void setAccountService(AccountServiceEntity accountService) { this.accountService = accountService; } public Double getSum() { return sum; } public void setSum(Double sum) { this.sum = sum; } public Double getConsumption() { return consumption; } public void setConsumption(Double consumption) { this.consumption = consumption; } public TariffEntity getTariff() { return tariff; } public void setTariff(TariffEntity tariff) { this.tariff = tariff; } public CalculationTypeEntity getTariffCalculationType() { return tariffCalculationType; } public void setTariffCalculationType(CalculationTypeEntity tariffCalculationType) { this.tariffCalculationType = tariffCalculationType; } public MeasurementUnitEntity getTariffMeasurementUnit() { return tariffMeasurementUnit; } public void setTariffMeasurementUnit(MeasurementUnitEntity tariffMeasurementUnit) { this.tariffMeasurementUnit = tariffMeasurementUnit; } public Double getTariffValue() { return tariffValue; } public void setTariffValue(Double tariffValue) { this.tariffValue = tariffValue; } public Integer getAccountServiceDaysActive() { return accountServiceDaysActive; } public void setAccountServiceDaysActive(Integer accountServiceDaysActive) { this.accountServiceDaysActive = accountServiceDaysActive; } }
package com.wb.bot.wbbot.beans; public class RemarkUser { /** * 用户uid */ private String uid; /** * 备注 */ private String remark; /** * 简写 */ private String jp; /** * 全拼 */ private String qp; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getJp() { return jp; } public void setJp(String jp) { this.jp = jp; } public String getQp() { return qp; } public void setQp(String qp) { this.qp = qp; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSession; import org.mvirtual.persistence.entity.Institution; import org.mvirtual.persistence.hibernate.IndustrialEstate; import org.hibernate.Session; import org.hibernate.Transaction; import mvirtual.catalog.SessionNames; /** * * @author Fabricio */ public class SessionListener implements HttpSessionListener { @Override public void sessionCreated (HttpSessionEvent event) { HttpSession httpSession = event.getSession(); httpSession.setAttribute ("version", "0.0.0.1"); } @Override public void sessionDestroyed (HttpSessionEvent event) { } }
package com.yunhe.core.numbersetting.factory; import java.text.SimpleDateFormat; import java.util.Date; /** * <per> * 借入归还单 XSD * 进货订单编号 JDD * 销售订单编号 XDD * 进货单编号 JHD * 供应商编号 GYS * 客户编号 KH * 商品编号 SP * 借出归还单 JCD * 商品模板 MB * 借入归还单 JRG * </per> * * @author 孔邹祥 * @date 2019年1月10日 */ public class NumberFactory { public static String data(Integer bh) { Date now = new Date(); SimpleDateFormat ft = new SimpleDateFormat("YYYYMMDD"); return ft.format(now) + sum(bh); } public static String sum(Integer i) { i++; if (i < 9) { return "00" + i; } else if (i < 99) { return "0" + i; } return "" + i; } }
package org.sbbs.demo.webapp.action; import javax.servlet.http.HttpServletRequest; import org.sbbs.base.webapp.action.BaseMaintainAction; import org.sbbs.demo.model.DemoEntity; import org.sbbs.demo.service.DemoEntityManager; public class DemoEntityMaintainAction extends BaseMaintainAction<DemoEntity, Long> { public String edit() { this.setEditType( EDITTYPE_EDIT ); this.setModel( this.demoEntityManager.find( this.getId() ) ); return this.SUCCESS; } public String add() { this.setEditType( EDITTYPE_EDIT ); this.setModel( new DemoEntity() ); return this.SUCCESS; } public String save() { try { HttpServletRequest req = this.getRequest(); boolean isNew = ( this.getEditType() == 1 ); this.getDemoEntityManager().save( this.getModel() ); this.setAjaxMessage( getText( ( isNew ) ? "demoEntity.added" : "demoEntity.updated", "no msg key found,save successed." ) ); this.setAjaxStatus( AJAX_STATUS_SUCCESS ); } catch ( Exception e ) { this.setAjaxMessage( getText( "error.saved", new String[] { e.getMessage() } ) ); this.setAjaxStatus( AJAX_STATUS_ERROR ); } return this.SUCCESS; } public String delete() { try { String[] sIds = this.getIds().split( "," ); Long[] lIds = new Long[sIds.length]; for ( int i = 0; i < sIds.length; i++ ) { lIds[i] = Long.parseLong( sIds[i] ); } this.demoEntityManager.removeByIds( lIds ); this.setAjaxMessage( getText( "demoEntity.deleted", "no msg key found,delete successed." ) ); this.setAjaxStatus( AJAX_STATUS_SUCCESS ); } catch ( Exception e ) { this.setAjaxMessage( getText( "error.deleted", new String[] { e.getMessage() } ) ); this.setAjaxStatus( AJAX_STATUS_ERROR ); } return this.SUCCESS; } public DemoEntityManager getDemoEntityManager() { return demoEntityManager; } public void setDemoEntityManager( DemoEntityManager demoEntityManager ) { this.demoEntityManager = demoEntityManager; } /* * public int getEditType() { return editType; } public void setEditType( int editType ) { this.editType = editType; * } public Long getId() { return id; } public void setId( Long id ) { this.id = id; } public String getIds() { * return ids; } public void setIds( String ids ) { this.ids = ids; } public DemoEntity getModel() { return model; } * public void setModel( DemoEntity demoEntity ) { this.model = demoEntity; } */ private DemoEntityManager demoEntityManager; /* * private DemoEntity model = null; private Long id; private String ids; private int editType; protected static * final int EDITTYPE_EDIT = 0; protected static final int EDITTYPE_ADD = 1; */ }
package com.groovybot.persistence; import com.groovybot.model.ScriptExecutionEntity; import com.groovybot.model.ScriptExecutionType; public interface ScriptExecutionEntityDao { ScriptExecutionEntity makePersistent(ScriptExecutionEntity entry); ScriptExecutionEntity createEntry(String participantId, String script, ScriptExecutionType type); }
package com.lupan.HeadFirstDesignMode.chapter7_adapterAndFacade.face; /** * TODO * * @author lupan * @version 2016/3/23 0023 */ public class Television { public void turnOn(){ System.out.println("开电视!"); } public void turnOff(){ System.out.println("关电视!"); } }
package com.ahf.antwerphasfallen.Helpers; /** * Created by Jorren on 27/10/2018. */ public interface Subscriber { void Update(); }
package com.tetris.pieces; public abstract class Piece { public int Ax; public int Ay; public int Bx; public int By; public int Cx; public int Cy; public int Dx; public int Dy; public int row = Ax; public int col = Ay; public Piece(int Ax, int Ay) { this.Ax = Ax; this.Ay = Ay; } public abstract void move(int MoveRow, int MoveCol); public abstract void rotate(int degree); }
package com.tencent.mm.plugin.appbrand.dynamic.d; import com.tencent.mm.ipcinvoker.extension.XIPCInvoker; import com.tencent.mm.model.u; import com.tencent.mm.plugin.appbrand.dynamic.d.a.a; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.u.b.b; import com.tencent.smtt.sdk.TbsListener$ErrorCode; import org.json.JSONObject; public final class h extends a { public h() { super("onTapCallback", TbsListener$ErrorCode.TEST_THROWABLE_ISNOT_NULL); } protected final void a(com.tencent.mm.u.c.a aVar, JSONObject jSONObject, b.a<JSONObject> aVar2) { u.b Da = aVar.Da(); b bVar = new b(); bVar.id = Da.getString("__page_view_id", ""); bVar.cca = jSONObject.optString("eventId", ""); bVar.fwf = jSONObject.optBoolean("hasHandler"); bVar.fwg = jSONObject.optBoolean("res"); XIPCInvoker.a(Da.getString("__process_name", ad.getProcessName()), bVar, a.class, new 1(this, aVar2)); } }
package Lista; public class ManipuladorDaLista<T> { private int top=-1,tamanho=15, gapAumento=5; private T vetor[]= (T[]) new Object[this.tamanho]; protected void aumenta(int tam){ T aux[] = (T[]) new Object[tam+1]; for(int i=0;i<vetor.length;i++){ aux[i]=vetor[i]; } this.tamanho=tam; vetor=aux; } public void push(T obj){ if(top + 1 >= tamanho) this.aumenta(gapAumento); top++; vetor[top]=obj; } public T peek(){ return vetor[top]; } public void inverte(){ T aux[]= (T[]) new Object[this.tamanho]; for(int i=this.getTamanho()-1, j = 0;i>=0;i--, j++){ aux[j] = vetor[i]; } } public T pop(){ T aux=vetor[top]; top--; return aux; } public boolean isEmpty(){ return top==-1; } public int getTamanho(){ int aux = 0; for(int i=0;i<this.tamanho;i++){ if(vetor[i]!= null) aux++; } return aux; } }
package com.framework.bean.common; public class FileInfo { private String name;//文件名称 private String path;//文件路径 private boolean isDirectory;//是否为目录 private boolean isFile;//是否为文件 public String getName() { return name; } public String getPath() { return path; } public boolean isDirectory() { return isDirectory; } public void setName(String name) { this.name = name; } public void setPath(String path) { this.path = path; } public void setDirectory(boolean isDirectory) { this.isDirectory = isDirectory; } public boolean isFile() { return isFile; } public void setFile(boolean isFile) { this.isFile = isFile; } }
import java.util.List; import java.util.ArrayList; import java.util.Scanner; import java.util.Arrays; import java.io.File; import java.io.FileWriter; public class Theatre implements TheatreInterface{ public final int NUM_ROWS = 10; public final int NUM_SEATS = 20; public Seat[][] seats; public int seatsTaken; public int seatingCurrentRow; public int nextSeat; public boolean right; public List<Reservation> reservations; public String fileName; public Theatre() { this.seats = new Seat[NUM_ROWS][NUM_SEATS]; for (int i = 0; i < seats.length; i++) { for (int j = 0; j < seats[0].length; j++) { seats[i][j] = new Seat(i, j); } } this.nextSeat = 0; this.seatingCurrentRow = this.seats.length - 1; this.reservations = new ArrayList<>(); this.right = true; this.seatsTaken = 0; } /** * Reads in input file and creates all the reservations for the Theatre * @input filename, absolute path to file containing reservation requests */ public void readFile(String filename) { try { File f = new File(filename); Scanner sc = new Scanner(f); String filenameWithExtension = f.getName(); this.fileName = filenameWithExtension.substring(0, filenameWithExtension.lastIndexOf('.')); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] request = line.split(" "); this.reservations.add(new Reservation(request[0], Integer.parseInt(request[1]))); } } catch (Exception e) { System.out.println(e); } } /** * Finds and assigns seats for each reservation and outputs result to output/ folder * @return the absolute path of the output file */ public String handleReservations() { String outputFilePath = System.getProperty("user.dir") + "\\output\\" + this.fileName + "_output.txt"; try { File output = new File(outputFilePath); output.createNewFile(); FileWriter writer = new FileWriter(output); for (Reservation r : this.reservations) { writer.write(this.requestSeats(r)); } writer.close(); } catch (Exception e) { System.out.println(e); } return outputFilePath; } /** * Finds the next available seats in the theatre and then reserves the seats * Will not reserve seats if the whole reservation cannot be completed * @input r, the reservation object containing the ID and # of seats requested * @return String containing the reservation ID as well as the seats assigned */ public String requestSeats(Reservation r) { if (r.seatsRequested <= 0) { return "Reservation " + r.id + " requested 0 or fewer tickets. Why did you do this?\n"; } if (r.seatsRequested > ((NUM_ROWS * NUM_SEATS) - seatsTaken)) { return "Reservation " + r.id + " was unable to be processed as" + " there weren't enough seats available\n"; } List<Seat> seatsToReserve = findAvailableSeats(r.seatsRequested); reserveSeats(seatsToReserve); return generateOutputString(r, seatsToReserve); } /** * Finds the group of next available seats * @input seatsRequested, the number of seats to find * @return returns a list of the next amount of free seats */ public List<Seat> findAvailableSeats(int seatsRequested) { List<Seat> res = new ArrayList<>(); while (res.size() < seatsRequested) { res.add(getNextSeat()); } return res; } /** * Marks the seats as occupied * @input seats, the list of seats assigned to a reservation */ public void reserveSeats(List<Seat> seats) { for (Seat seat : seats) { seat.reserve(); this.seatsTaken++; } } /** * Iterator for the seats in the theatre, goes from left to right, right to left, and so on * starts from the backmost row and works its way up * @return seat, the next available seat that is free */ public Seat getNextSeat(){ Seat res = this.seats[seatingCurrentRow][nextSeat]; if (this.right) { nextSeat++; if (this.nextSeat == seats[0].length) { seatingCurrentRow--; nextSeat = seats[0].length - 1; this.right = !this.right; } } else { nextSeat--; if (this.nextSeat == -1) { seatingCurrentRow--; nextSeat = 0; this.right = !this.right; } } return res; } public String generateOutputString(Reservation r, List<Seat> reservedSeats) { StringBuilder sb = new StringBuilder(); sb.append(r.id + " "); for (Seat seat : reservedSeats) { sb.append(seat); sb.append(","); } sb.deleteCharAt(sb.length() - 1); sb.append('\n'); return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < seats.length; i++) { for (int j = 0; j < seats[0].length; j++) { if (seats[i][j].occupied) { sb.append("1 "); } else { sb.append("0 "); } } sb.append("\n"); } return sb.toString(); } public static void main(String[] args) { Theatre t = new Theatre(); t.readFile(args[0]); System.out.println(t.handleReservations()); System.out.println(t.toString()); } }
package de.propra2.ausleiherino24.service; import de.propra2.ausleiherino24.data.UserRepository; import de.propra2.ausleiherino24.model.Person; import de.propra2.ausleiherino24.model.User; import java.security.Principal; import java.util.NoSuchElementException; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class); private final PersonService personService; private final UserRepository userRepository; @Autowired public UserService(final PersonService personService, final UserRepository userRepository) { this.personService = personService; this.userRepository = userRepository; } /** * Saves given user in database. */ private void saveUser(final User user, final String msg) { userRepository.save(user); LOGGER.info("{} user profile {} [ID={}]", msg, user.getUsername(), user.getId()); } /** * Saves newly created/updated user and person data to database. * * @param user User object to be saved to database. * @param person Person object to be saved to database. * @param msg String to be displayed in the Logger. */ public void saveUserWithProfile(final User user, final Person person, final String msg) { user.setRole("user"); saveUser(user, msg); person.setUser(user); personService.savePerson(person, msg); } /** * Saves User and Person in case the passwords are equal. * * @return status */ public String saveUserIfPasswordsAreEqual(final String username, final User user, final Person person, final String pw1, final String pw2) { if (!pw1.equals(pw2)) { return "PasswordNotEqual"; } final Optional<User> optionalUser = userRepository.findByUsername(username); if (!optionalUser.isPresent()) { return "UserNotFound"; } final User dbUser = optionalUser.get(); final Person dbPerson = dbUser.getPerson(); dbPerson.setFirstName(person.getFirstName()); dbPerson.setLastName(person.getLastName()); dbPerson.setAddress(person.getAddress()); dbUser.setPerson(person); dbUser.setEmail(user.getEmail()); dbUser.setPassword(pw1); this.saveUser(dbUser, "Save"); return "Success"; } /** * Finds user by its username. */ public User findUserByUsername(final String username) { final Optional<User> optionalUser = userRepository.findByUsername(username); if (!optionalUser.isPresent()) { LOGGER.warn("Couldn't find user {} in UserRepository.", username); throw new NoSuchElementException("Couldn't find current principal in UserRepository."); } return optionalUser.get(); } /** * Finds user by its principal. */ public User findUserByPrincipal(final Principal principal) { User user; if (principal == null) { return buildNewUser(); } try { user = findUserByUsername(principal.getName()); } catch (NoSuchElementException e) { user = buildNewUser(); } return user; } private User buildNewUser() { User user = new User(); user.setRole(""); user.setUsername(""); return user; } /** * Checks whether given username equals the given principal's name. */ public boolean isCurrentUser(final String username, final String currentPrincipalName) { return username.equals(currentPrincipalName); } }
package pro.eddiecache.kits.paxos; import java.util.HashSet; import java.util.Set; /** * @author eddie * use this class to track messages. * All data up to that tail index is stored and accepted. * */ public class MissingMessagesTracker { private long tail = 0; /** * have been received and store in. */ private final Set<Long> received = new HashSet<>(); public void received(long seqNo) { if (tail == seqNo) { tail++; advanceTail(); } else { received.add(seqNo); } } private void advanceTail() { while (!received.isEmpty()) { if (!received.contains(tail)) { return; } received.remove(tail); tail++; } } /** * 每收到一个新的消息, * 都试图去查询[tail, seqNo)这个区间内缺失的msg, * 并发送给leader进行补全 * * @param seqNo 新的消息的seqNo */ public Set<Long> getMissing(long seqNo) { Set<Long> missingSuccess = new HashSet<>(); for (long i = tail; i < seqNo; i++) { if (!received.contains(i)) { missingSuccess.add(i); } } return missingSuccess; } }
package com.sportingCenterWebApp.calendarservice.controller; import com.sportingCenterWebApp.calendarservice.model.Event; import com.sportingCenterWebApp.calendarservice.dto.User; import com.sportingCenterWebApp.calendarservice.repo.EventRepository; import com.sportingCenterWebApp.calendarservice.service.BookingService; import com.sportingCenterWebApp.calendarservice.service.EventService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/admin") public class EventController { @Autowired private BookingService bookingService; @Autowired private EventService eventService; @GetMapping("/events") public List<Event> getEvents() { return eventService.findAll(); } @PostMapping("/event") void addEvent(@RequestBody Event event){ eventService.save(event); } @PostMapping("/events/delete") void deleteEvent(@RequestBody Event event) { bookingService.deleteBookingsForEventId(event.getId()); eventService.delete(event); } @GetMapping("/getusers/{eventId}") public List<User> getUsersForEvent(@PathVariable("eventId") Long eventId) { return bookingService.getUsersForEvent(eventId); } @GetMapping("/getpresences/{eventId}") public List<User> getPresences(@PathVariable("eventId") Long eventId) { return bookingService.getPresences(eventId); } }
package net.minecraft.entity.monster; import java.util.UUID; import javax.annotation.Nullable; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.ai.EntityAIHurtByTarget; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.util.datafix.DataFixer; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; import net.minecraft.world.storage.loot.LootTableList; public class EntityPigZombie extends EntityZombie { private static final UUID ATTACK_SPEED_BOOST_MODIFIER_UUID = UUID.fromString("49455A49-7EC5-45BA-B886-3B90B23A1718"); private static final AttributeModifier ATTACK_SPEED_BOOST_MODIFIER = (new AttributeModifier(ATTACK_SPEED_BOOST_MODIFIER_UUID, "Attacking speed boost", 0.05D, 0)).setSaved(false); private int angerLevel; private int randomSoundDelay; private UUID angerTargetUUID; public EntityPigZombie(World worldIn) { super(worldIn); this.isImmuneToFire = true; } public void setRevengeTarget(@Nullable EntityLivingBase livingBase) { super.setRevengeTarget(livingBase); if (livingBase != null) this.angerTargetUUID = livingBase.getUniqueID(); } protected void applyEntityAI() { this.targetTasks.addTask(1, (EntityAIBase)new AIHurtByAggressor(this)); this.targetTasks.addTask(2, (EntityAIBase)new AITargetAggressor(this)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); getEntityAttribute(SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(0.0D); getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.23000000417232513D); getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(5.0D); } protected void updateAITasks() { IAttributeInstance iattributeinstance = getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED); if (isAngry()) { if (!isChild() && !iattributeinstance.hasModifier(ATTACK_SPEED_BOOST_MODIFIER)) iattributeinstance.applyModifier(ATTACK_SPEED_BOOST_MODIFIER); this.angerLevel--; } else if (iattributeinstance.hasModifier(ATTACK_SPEED_BOOST_MODIFIER)) { iattributeinstance.removeModifier(ATTACK_SPEED_BOOST_MODIFIER); } if (this.randomSoundDelay > 0 && --this.randomSoundDelay == 0) playSound(SoundEvents.ENTITY_ZOMBIE_PIG_ANGRY, getSoundVolume() * 2.0F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F) * 1.8F); if (this.angerLevel > 0 && this.angerTargetUUID != null && getAITarget() == null) { EntityPlayer entityplayer = this.world.getPlayerEntityByUUID(this.angerTargetUUID); setRevengeTarget((EntityLivingBase)entityplayer); this.attackingPlayer = entityplayer; this.recentlyHit = getRevengeTimer(); } super.updateAITasks(); } public boolean getCanSpawnHere() { return (this.world.getDifficulty() != EnumDifficulty.PEACEFUL); } public boolean isNotColliding() { return (this.world.checkNoEntityCollision(getEntityBoundingBox(), (Entity)this) && this.world.getCollisionBoxes((Entity)this, getEntityBoundingBox()).isEmpty() && !this.world.containsAnyLiquid(getEntityBoundingBox())); } public static void registerFixesPigZombie(DataFixer fixer) { EntityLiving.registerFixesMob(fixer, EntityPigZombie.class); } public void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); compound.setShort("Anger", (short)this.angerLevel); if (this.angerTargetUUID != null) { compound.setString("HurtBy", this.angerTargetUUID.toString()); } else { compound.setString("HurtBy", ""); } } public void readEntityFromNBT(NBTTagCompound compound) { super.readEntityFromNBT(compound); this.angerLevel = compound.getShort("Anger"); String s = compound.getString("HurtBy"); if (!s.isEmpty()) { this.angerTargetUUID = UUID.fromString(s); EntityPlayer entityplayer = this.world.getPlayerEntityByUUID(this.angerTargetUUID); setRevengeTarget((EntityLivingBase)entityplayer); if (entityplayer != null) { this.attackingPlayer = entityplayer; this.recentlyHit = getRevengeTimer(); } } } public boolean attackEntityFrom(DamageSource source, float amount) { if (isEntityInvulnerable(source)) return false; Entity entity = source.getEntity(); if (entity instanceof EntityPlayer) becomeAngryAt(entity); return super.attackEntityFrom(source, amount); } private void becomeAngryAt(Entity p_70835_1_) { this.angerLevel = 400 + this.rand.nextInt(400); this.randomSoundDelay = this.rand.nextInt(40); if (p_70835_1_ instanceof EntityLivingBase) setRevengeTarget((EntityLivingBase)p_70835_1_); } public boolean isAngry() { return (this.angerLevel > 0); } protected SoundEvent getAmbientSound() { return SoundEvents.ENTITY_ZOMBIE_PIG_AMBIENT; } protected SoundEvent getHurtSound(DamageSource p_184601_1_) { return SoundEvents.ENTITY_ZOMBIE_PIG_HURT; } protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_ZOMBIE_PIG_DEATH; } @Nullable protected ResourceLocation getLootTable() { return LootTableList.ENTITIES_ZOMBIE_PIGMAN; } public boolean processInteract(EntityPlayer player, EnumHand hand) { return false; } protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficulty) { setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(Items.GOLDEN_SWORD)); } protected ItemStack func_190732_dj() { return ItemStack.field_190927_a; } public boolean func_191990_c(EntityPlayer p_191990_1_) { return isAngry(); } static class AIHurtByAggressor extends EntityAIHurtByTarget { public AIHurtByAggressor(EntityPigZombie p_i45828_1_) { super(p_i45828_1_, true, new Class[0]); } protected void setEntityAttackTarget(EntityCreature creatureIn, EntityLivingBase entityLivingBaseIn) { super.setEntityAttackTarget(creatureIn, entityLivingBaseIn); if (creatureIn instanceof EntityPigZombie) ((EntityPigZombie)creatureIn).becomeAngryAt((Entity)entityLivingBaseIn); } } static class AITargetAggressor extends EntityAINearestAttackableTarget<EntityPlayer> { public AITargetAggressor(EntityPigZombie p_i45829_1_) { super(p_i45829_1_, EntityPlayer.class, true); } public boolean shouldExecute() { return (((EntityPigZombie)this.taskOwner).isAngry() && super.shouldExecute()); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\entity\monster\EntityPigZombie.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package alg.graph; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * 广搜 * * @author yang * */ public class BreadthFirstSearch { private boolean[] marked; private int[] edgeTo; private int s; public BreadthFirstSearch(Graph g, int s) { this.s = s; marked = new boolean[g.verticeNum()]; edgeTo = new int[g.verticeNum()]; bfs(g, s); } private void bfs(Graph g, int s) { Queue<Integer> queue = new LinkedList<>(); marked[s] = true; queue.offer(s); edgeTo[s] = -1; while (!queue.isEmpty()) { int u = queue.poll(); for (int v : g.adj(u)) { if (!marked[v]) { marked[v] = true; queue.offer(v); edgeTo[v] = u; } } } } public boolean hasPathTo(int v) { return marked[v]; } public Iterable<Integer> pathTo(int v) { List<Integer> path = new LinkedList<>(); for (; v != -1; v = edgeTo[v]) path.add(0, v); return path; } public int distTo(int v) { int len = 0; for (; v != s; v = edgeTo[v]) ++ len; return len; } }
package com.qgbase.netty; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.timeout.IdleStateHandler; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /* * * Netty 服务端过滤器 * @Author winner * @Date 下午 3:35 2019/5/11 0011 * @Description * @return **/ @Component public class NettyServerFilter extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline ph = ch.pipeline(); //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式 ph.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS)); /*ph.addLast(new MessageDecoder()); ph.addLast(new MessageEncoder());*/ ph.addLast(new StringDecoder()); ph.addLast(new StringEncoder()); //业务逻辑实现类 ph.addLast("nettyServerHandler", new NettyServerHandler()); } }
package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Category; import java.util.ArrayList; import java.util.List; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * DrivingLicence */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-04-02T16:04:50.980Z") public class DrivingLicence { @JsonProperty("1_surname") private String _1Surname = null; @JsonProperty("2_name") private String _2Name = null; @JsonProperty("3_dateOfBirth") private String _3DateOfBirth = null; @JsonProperty("4a_dateOfIssue") private String _4aDateOfIssue = null; @JsonProperty("4b_dateOfExpiry") private String _4bDateOfExpiry = null; @JsonProperty("4c_issuedBy") private String _4cIssuedBy = null; @JsonProperty("4d_personalNo") private Integer _4dPersonalNo = null; @JsonProperty("5_licenceNo") private Integer _5LicenceNo = null; @JsonProperty("categories") @Valid private List<Category> categories = null; public DrivingLicence _1Surname(String _1Surname) { this._1Surname = _1Surname; return this; } /** * Get _1Surname * @return _1Surname **/ @ApiModelProperty(example = "Pavardenis", value = "") public String get1Surname() { return _1Surname; } public void set1Surname(String _1Surname) { this._1Surname = _1Surname; } public DrivingLicence _2Name(String _2Name) { this._2Name = _2Name; return this; } /** * Get _2Name * @return _2Name **/ @ApiModelProperty(example = "Vardenis", value = "") public String get2Name() { return _2Name; } public void set2Name(String _2Name) { this._2Name = _2Name; } public DrivingLicence _3DateOfBirth(String _3DateOfBirth) { this._3DateOfBirth = _3DateOfBirth; return this; } /** * Get _3DateOfBirth * @return _3DateOfBirth **/ @ApiModelProperty(example = "01 01 1985", value = "") public String get3DateOfBirth() { return _3DateOfBirth; } public void set3DateOfBirth(String _3DateOfBirth) { this._3DateOfBirth = _3DateOfBirth; } public DrivingLicence _4aDateOfIssue(String _4aDateOfIssue) { this._4aDateOfIssue = _4aDateOfIssue; return this; } /** * Get _4aDateOfIssue * @return _4aDateOfIssue **/ @ApiModelProperty(example = "24 11 2016", value = "") public String get4aDateOfIssue() { return _4aDateOfIssue; } public void set4aDateOfIssue(String _4aDateOfIssue) { this._4aDateOfIssue = _4aDateOfIssue; } public DrivingLicence _4bDateOfExpiry(String _4bDateOfExpiry) { this._4bDateOfExpiry = _4bDateOfExpiry; return this; } /** * Get _4bDateOfExpiry * @return _4bDateOfExpiry **/ @ApiModelProperty(example = "24 11 2026", value = "") public String get4bDateOfExpiry() { return _4bDateOfExpiry; } public void set4bDateOfExpiry(String _4bDateOfExpiry) { this._4bDateOfExpiry = _4bDateOfExpiry; } public DrivingLicence _4cIssuedBy(String _4cIssuedBy) { this._4cIssuedBy = _4cIssuedBy; return this; } /** * Get _4cIssuedBy * @return _4cIssuedBy **/ @ApiModelProperty(example = "VĮ Regitra", value = "") public String get4cIssuedBy() { return _4cIssuedBy; } public void set4cIssuedBy(String _4cIssuedBy) { this._4cIssuedBy = _4cIssuedBy; } public DrivingLicence _4dPersonalNo(Integer _4dPersonalNo) { this._4dPersonalNo = _4dPersonalNo; return this; } /** * Get _4dPersonalNo * @return _4dPersonalNo **/ @ApiModelProperty(example = "31234567890", value = "") public Integer get4dPersonalNo() { return _4dPersonalNo; } public void set4dPersonalNo(Integer _4dPersonalNo) { this._4dPersonalNo = _4dPersonalNo; } public DrivingLicence _5LicenceNo(Integer _5LicenceNo) { this._5LicenceNo = _5LicenceNo; return this; } /** * Get _5LicenceNo * @return _5LicenceNo **/ @ApiModelProperty(example = "35983081", value = "") public Integer get5LicenceNo() { return _5LicenceNo; } public void set5LicenceNo(Integer _5LicenceNo) { this._5LicenceNo = _5LicenceNo; } public DrivingLicence categories(List<Category> categories) { this.categories = categories; return this; } public DrivingLicence addCategoriesItem(Category categoriesItem) { if (this.categories == null) { this.categories = new ArrayList<Category>(); } this.categories.add(categoriesItem); return this; } /** * Get categories * @return categories **/ @ApiModelProperty(value = "") @Valid public List<Category> getCategories() { return categories; } public void setCategories(List<Category> categories) { this.categories = categories; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DrivingLicence drivingLicence = (DrivingLicence) o; return Objects.equals(this._1Surname, drivingLicence._1Surname) && Objects.equals(this._2Name, drivingLicence._2Name) && Objects.equals(this._3DateOfBirth, drivingLicence._3DateOfBirth) && Objects.equals(this._4aDateOfIssue, drivingLicence._4aDateOfIssue) && Objects.equals(this._4bDateOfExpiry, drivingLicence._4bDateOfExpiry) && Objects.equals(this._4cIssuedBy, drivingLicence._4cIssuedBy) && Objects.equals(this._4dPersonalNo, drivingLicence._4dPersonalNo) && Objects.equals(this._5LicenceNo, drivingLicence._5LicenceNo) && Objects.equals(this.categories, drivingLicence.categories); } @Override public int hashCode() { return Objects.hash(_1Surname, _2Name, _3DateOfBirth, _4aDateOfIssue, _4bDateOfExpiry, _4cIssuedBy, _4dPersonalNo, _5LicenceNo, categories); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DrivingLicence {\n"); sb.append(" _1Surname: ").append(toIndentedString(_1Surname)).append("\n"); sb.append(" _2Name: ").append(toIndentedString(_2Name)).append("\n"); sb.append(" _3DateOfBirth: ").append(toIndentedString(_3DateOfBirth)).append("\n"); sb.append(" _4aDateOfIssue: ").append(toIndentedString(_4aDateOfIssue)).append("\n"); sb.append(" _4bDateOfExpiry: ").append(toIndentedString(_4bDateOfExpiry)).append("\n"); sb.append(" _4cIssuedBy: ").append(toIndentedString(_4cIssuedBy)).append("\n"); sb.append(" _4dPersonalNo: ").append(toIndentedString(_4dPersonalNo)).append("\n"); sb.append(" _5LicenceNo: ").append(toIndentedString(_5LicenceNo)).append("\n"); sb.append(" categories: ").append(toIndentedString(categories)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
// import java.math.BigInteger; public class Euler15 { static int size = 20; static long routes = 0; public static void main(String[] args) { move(0,0); System.out.println("routes: "+routes); } public static void move(int x, int y) { // bottom left corner ? if (x == size && y == size) { routes += 1; // another successful rout return; } // move right? if (x < size) move(x+1,y); // move down if (y<size) move(x,y+1); } }
package com.fernamuruthi.mkuki.decoration; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.View; import com.fernamuruthi.mkuki.R; import com.fernamuruthi.mkuki.adapter.PostsAdapter; /** * Created by 001590 on 2016-11-25. */ public class PostsItemDecoration extends RecyclerView.ItemDecoration { private Resources r; private Drawable mDivider; public PostsItemDecoration(Context context) { r = context.getResources(); mDivider = ContextCompat.getDrawable(context, R.drawable.divider_line); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { // Add top margin only for the first item to avoid double space between items if(parent.getChildAdapterPosition(view) == 0) outRect.top = getDp(8); int finalPosition = parent.getAdapter().getItemCount()-1; int position = parent.getChildAdapterPosition(view); int viewType = parent.getAdapter().getItemViewType(position); if(PostsAdapter.VIEW_TYPE_TRENDING==viewType){ outRect.left = getDp(8); outRect.right = getDp(8); outRect.bottom = getDp(8); } else if(viewType==0||viewType==PostsAdapter.VIEW_TYPE_PROGRESS_BAR){ outRect.top = getDp(16); outRect.left = getDp(16); outRect.right = getDp(16); outRect.bottom = getDp(16); }else if(position+1<=finalPosition){ int viewTypeNext = parent.getAdapter().getItemViewType(position+1); if(PostsAdapter.VIEW_TYPE_TRENDING==viewTypeNext){ outRect.bottom = getDp(8); } } if(parent.getChildAdapterPosition(view) == finalPosition && viewType!=PostsAdapter.VIEW_TYPE_PROGRESS_BAR) outRect.bottom = getDp(8); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { int finalPosition = parent.getAdapter().getItemCount()-1; int left = getDp(92); int right = parent.getWidth() - getDp(16); int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View view = parent.getChildAt(i); int position = parent.getChildAdapterPosition(view); int viewType = parent.getAdapter().getItemViewType(position); if(viewType==PostsAdapter.VIEW_TYPE_NORMAL&&position!=finalPosition){ RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams(); int top = view.getBottom() + params.bottomMargin; int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } } private int getDp(int dp){ return (int) (r.getDisplayMetrics().density * dp); } }
package io.glacier.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import io.glacier.exception.ServiceException; import io.glacier.model.Platform; import io.glacier.repository.PlatformRepository; @Service public class PlatformService { @Autowired private PlatformRepository platformRepository; //Fetch and return all platforms from database. public List<Platform> getAllPlatforms() { return platformRepository.findAll(); } //Find platform with given id in url.If platform is not found in database then errror code is sent back to client public Platform getPlatform(int id) throws ServiceException { Platform p=null; try { Optional<Platform> optinalEntity = platformRepository.findById(id); p = optinalEntity.get(); } catch(Exception e) { throw new ServiceException("platform not found"); } return p; } /*Find platform with given name in url.If platform is not found in database then error code is sent back to client. findByName() method is used as customised query to access mongo database. */ public List<Platform> getPlatformByName(String name) throws ServiceException { List<Platform> p=null; p=platformRepository.findByName(name); if(p.size()==0) throw new ServiceException("platform with given name not found"); return p; } //Add a platform in a database with data received from url. public String addPlatform(Platform platform) { platformRepository.save(platform); return "Created Platform id: "+ platform.getId(); } //Delete a platform from a database with id mentioned in url. public String deletePlatform(int id) { platformRepository.deleteById(id); return "Platform deleted having id: "+ id; } //Update a platform in a database having id equal to id provided in url. public String updatePlatform(@RequestBody Platform platform,@PathVariable int id) { platformRepository.save(platform); return "Platform updated having id: "+ id; } }
package com.spring1.Service; /** * com.spring1.Service * * @author jh * @date 2018/8/21 16:55 * description: */ public class UserServiceImpl implements UserService { @Override public void save() { //System.out.println ("打开事务"); System.out.println ("保存用户"); //throw new IllegalArgumentException ("aaaa"); //System.out.println ("提交事务"); } @Override public void delete() { System.out.println ("删除用户"); } @Override public void update() { System.out.println ("更新用户"); } @Override public void find() { System.out.println ("查找用户"); } }
package com.tencent.mm.plugin.wear.model.e; import android.os.Looper; import com.tencent.liteav.network.TXCStreamUploader; import com.tencent.mm.g.a.to; import com.tencent.mm.g.a.tq; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.s; import com.tencent.mm.plugin.messenger.a.g; import com.tencent.mm.plugin.wear.model.a; import com.tencent.mm.pluginsdk.f.h; import com.tencent.mm.protocal.c.brd; import com.tencent.mm.protocal.c.cec; import com.tencent.mm.protocal.c.cew; import com.tencent.mm.protocal.c.cex; import com.tencent.mm.protocal.c.cey; import com.tencent.mm.protocal.c.cez; import com.tencent.mm.protocal.c.cfd; import com.tencent.mm.protocal.c.cgd; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public final class m extends a { public final List<Integer> bSy() { List<Integer> arrayList = new ArrayList(); arrayList.add(Integer.valueOf(TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_OUT)); arrayList.add(Integer.valueOf(TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_USERLIST)); arrayList.add(Integer.valueOf(11025)); arrayList.add(Integer.valueOf(TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_NEED_REENTER)); arrayList.add(Integer.valueOf(11026)); arrayList.add(Integer.valueOf(11029)); return arrayList; } protected final boolean zE(int i) { switch (i) { case TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_USERLIST /*11023*/: case 11025: return true; default: return false; } } protected final byte[] p(int i, byte[] bArr) { switch (i) { case TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_OUT /*11022*/: cez cez = new cez(); try { cez.aG(bArr); } catch (IOException e) { } a.bSl().pIS.a(new a(cez)); a.bSl().pIO.PM(cez.szk); com.tencent.mm.plugin.wear.model.c.a.ee(2, cez.otY); com.tencent.mm.plugin.wear.model.c.a.zC(2); break; case TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_USERLIST /*11023*/: cey cey = new cey(); try { cey.aG(bArr); } catch (IOException e2) { } g.bcT().D(cey.szk, cey.rBM, s.hQ(cey.szk)); au.HU(); c.FW().Ys(cey.szk); com.tencent.mm.plugin.wear.model.c.a.ee(3, cey.otY); com.tencent.mm.plugin.wear.model.c.a.zC(5); break; case TXCStreamUploader.TXE_UPLOAD_INFO_ROOM_NEED_REENTER /*11024*/: cew cew = new cew(); try { cew.aG(bArr); } catch (IOException e3) { } ((com.tencent.mm.plugin.emoji.b.c) com.tencent.mm.kernel.g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().o(ad.getContext(), cew.szk, cew.rwt); au.HU(); c.FW().Ys(cew.szk); com.tencent.mm.plugin.wear.model.c.a.ee(7, cew.otY); com.tencent.mm.plugin.wear.model.c.a.zC(3); break; case 11025: cex cex = new cex(); try { cex.aG(bArr); } catch (IOException e4) { } g.bcT().D(cex.szk, cex.rBM, s.hQ(cex.szk)); ((com.tencent.mm.plugin.emoji.b.c) com.tencent.mm.kernel.g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().o(ad.getContext(), cex.szk, cex.rwt); au.HU(); c.FW().Ys(cex.szk); com.tencent.mm.plugin.wear.model.c.a.ee(8, cex.otY); com.tencent.mm.plugin.wear.model.c.a.zC(4); break; case 11026: cfd cfd = new cfd(); try { cfd.aG(bArr); } catch (IOException e5) { } a.bSl(); cec cec = a.bSl().pIM.pJd.pJT; if (cec != null) { x.i("MicroMsg.Wear.WearBizLogic", "receive step count %d | time %s", new Object[]{Integer.valueOf(cfd.szK), h.h("yyyy-MM-dd HH:mm:ss", cfd.szL / 1000)}); cgd cgd = new cgd(); brd brd = new brd(); brd.hcC = cfd.szK > 0 ? cfd.szK : 0; brd.rxy = (int) (cfd.szL / 1000); Calendar instance = Calendar.getInstance(); instance.setTimeInMillis(cfd.szL); brd.spm = instance.get(1); brd.spn = instance.get(2) + 1; brd.spo = instance.get(5); brd.spp = instance.get(11); brd.spq = instance.get(12); brd.spr = instance.get(13); cgd.sAC.add(brd); tq tqVar = new tq(); try { tqVar.cfq.data = cgd.toByteArray(); } catch (IOException e6) { } tqVar.cfq.bIH = 4; tqVar.cfq.byN = cec.szd; tqVar.cfq.bKv = "gh_43f2581f6fd6"; com.tencent.mm.sdk.b.a.sFg.m(tqVar); break; } x.e("MicroMsg.Wear.WearBizLogic", "logicRequest is null"); break; case 11029: if (a.bSl().pIM.bSq() && com.tencent.mm.k.g.AT().getInt("WearLuckyBlock", 0) == 0) { long j = 0; try { j = Long.valueOf(new String(bArr)).longValue(); } catch (Exception e7) { } to toVar = new to(); toVar.cfd.action = 1; toVar.cfd.bIZ = j; com.tencent.mm.sdk.b.a.sFg.a(toVar, Looper.getMainLooper()); com.tencent.mm.plugin.wear.model.c.a.ee(11, 0); com.tencent.mm.plugin.wear.model.c.a.zC(11); break; } return null; break; } return null; } }
/* * 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 dao; import dto.AttendanceDTO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * * @author Chamath */ public class AttendanceDAO { public int addAttendance(AttendanceDTO attendanceDTO,String date,Connection connection) throws SQLException{ Statement statement = connection.createStatement(); return statement.executeUpdate("insert into Attendance values('"+attendanceDTO.getId()+"','"+date+"','"+attendanceDTO.getTimeIn()+"','"+attendanceDTO.getTimeOut()+"','"+attendanceDTO.getEmpId()+"')"); } public String getLastId(Connection connection) throws SQLException{ String lastId = "ATN000"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select max(CONVERT(substring(Attendance_Id,4),UNSIGNED INTEGER)) from Attendance"); resultSet.beforeFirst(); if(resultSet.next()){ lastId = "ATN"+String.valueOf(resultSet.getInt(1)); } return lastId; } public boolean isDateExist(String date,Connection connection) throws SQLException{ Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select Attendance_Id from Attendance where date='"+date+"'"); resultSet.beforeFirst(); if(resultSet.next()){ return true; }else{ return false; } } }
package model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import config.OracleConfig; public class MemberDao { private static MemberDao instance = new MemberDao(); public MemberDao(){} public static MemberDao getInstance(){ return instance; } private void closeAll(PreparedStatement pstmt, Connection con) throws SQLException { if(pstmt!=null) pstmt.close(); if(con!=null) con.close(); } public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection con) throws SQLException{ if(rs!=null) rs.close(); closeAll(pstmt,con); } public void memberRegister(MemberVO vo) throws SQLException{ Connection con = null; PreparedStatement pstmt = null; try{ con = DriverManager.getConnection(OracleConfig.URL, OracleConfig.USER, OracleConfig.PASS); String sql = "insert into users(id, pw, gender, birth, user_no, location, interest, point) values(?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(sql); pstmt.setString(1, vo.getId()); pstmt.setString(2, vo.getPass()); pstmt.setString(3, vo.getGender()); pstmt.setString(4, vo.getBirth()); pstmt.setInt(5, vo.getUno()); pstmt.setString(6, vo.getLocal()); pstmt.setString(7, vo.getInterest()); pstmt.setInt(8, 5); pstmt.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); }finally{ closeAll(pstmt, con); } } public MemberVO memberLogin(String id, String pass) throws SQLException{ Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; MemberVO vo = null; try{ con = DriverManager.getConnection(OracleConfig.URL, OracleConfig.USER, OracleConfig.PASS); String sql = "select user_no, id, pw from users where id=? and pw=?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, id); pstmt.setString(2, pass); rs = pstmt.executeQuery(); while(rs.next()){ vo = new MemberVO(rs.getInt(1), rs.getString(2), rs.getString(3)); } }catch(SQLException e){ e.printStackTrace(); }finally{ closeAll(rs,pstmt,con); } return vo; } public int memberNum() throws SQLException{ Connection con=null; PreparedStatement pstmt=null; ResultSet rs=null; int uno=0; try{ con=DriverManager.getConnection(OracleConfig.URL,OracleConfig.USER,OracleConfig.PASS); String sql="select user_no.nextval from dual"; pstmt=con.prepareStatement(sql); rs=pstmt.executeQuery(); if(rs.next()){ uno=rs.getInt(1); } }finally{ closeAll(pstmt,con); } return uno; } }
package com.csc214.rvandyke.assignment6application; import android.os.Bundle; import android.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Rebecca Van Dyke * rvandyke@u.rochester.edu * CSC 214 Assignment 6 * TA:Julian Weiss */ public class BhangraListFragment extends Fragment { private RecyclerView mRecyclerview; public BhangraListFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_bhangra_list, container, false); mRecyclerview = (RecyclerView)view.findViewById(R.id.recycler_view_teams); mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity())); return inflater.inflate(R.layout.fragment_bhangra_list, container, false); } }
package com.faisal.evaly; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class EvalyApplication { public static void main(String[] args) { SpringApplication.run(EvalyApplication.class, args); } }
package ctci.TreesandGraphs; /** * Created by joetomjob on 8/20/19. */ public class MimimumBST { static TreeNode CreateMinBST(int[] array) { return CreateMinBST(array, 0, array.length-1); } static TreeNode CreateMinBST(int[] array, int start, int end) { if(end < start) { return null; } int mid = (end + start)/2; TreeNode n = new TreeNode(array[mid]); n.left = CreateMinBST(array, start, mid -1); n.right = CreateMinBST(array, mid+1, end); return n; } public static void main(String[] args) { int[] a = {1,2,3,4,5,6,7,8}; TreeNode n = CreateMinBST(a); System.out.println(n.val); } }
/** * */ package org.springangularexample; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; /** * @author manojkumar.m * */ public class SpringAngularExampleServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(SpringAngularExampleApplication.class); } }
package display; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.AffineTransform; import decision.UserControl; import environment.Environment; import platform.Agent; /** * A panel to display the agent's point of view * @author simon * */ public class ControlPanel extends EnvPanel implements MouseListener, KeyListener{ private static final long serialVersionUID = 1L; private boolean display=false; Agent agent; public ControlPanel(Agent a){ super(a); agent=a; addKeyListener(this); addMouseListener(this); setFocusable(true); } public void paintComponent(Graphics g){ // draw background g.setColor(Color.white); g.fillRect(0, 0, 600, 800); // draw surrounding environment Graphics2D g2d = (Graphics2D)g; AffineTransform init = g2d.getTransform(); if (display){ int ix=Math.round(agent.body.position[0]); int jy=Math.round(agent.body.position[1]); float x1=agent.body.position[0]; float y1=agent.body.position[1]; float delta_x=ix-x1; float delta_y=jy-y1; g2d.setColor(Environment.WALL1); g2d.rotate(agent.body.position[2]-Math.PI/2, 245, 175); for (int i=-1;i<=1;i++){ for (int j=-1;j<=1;j++){ if (agent.main.env.isWalkthroughable(x1+i,y1-j)) g2d.drawRect(245-100+200*i+(int)(200*delta_x), 175-100+200*j-(int)(200*delta_y), 200, 200); else g2d.fillRect(245-100+200*i+(int)(200*delta_x), 175-100+200*j-(int)(200*delta_y), 200, 200); } } } g2d.setTransform(init); // draw tactile feedback g.setColor(Color.black); g.drawOval(120, 50, 250, 250); g.drawOval(121, 51, 248, 248); // draw vibrators for (int v=0;v<UserControl.NB_VIBRATOR;v++){ float x=-(float)Math.sin(v*UserControl.ANGLE*Math.PI/180); float y=(float)Math.cos(v*UserControl.ANGLE*Math.PI/180); g.setColor(Color.black); float val=agent.decision.vibrators[v]*2; g.fillOval((int)(120+125+x*125-val/2),(int)( 50+125+y*125-val/2), (int)val, (int)val); if (agent.decision.direction_target[v]>0){ g.setColor(Color.blue); val=agent.decision.direction_target[v]*2; g.fillOval((int)(120+125+x*125-val/2),(int)( 50+125+y*125-val/2), (int)val, (int)val); } if (agent.decision.direction_path[v]>0){ g.setColor(Color.red); val=agent.decision.direction_path[v]*2; g.fillOval((int)(120+125+x*125-val/2),(int)( 50+125+y*125-val/2), (int)val, (int)val); } if (agent.decision.direction_goals[v]>0){ g.setColor(Color.green); val=agent.decision.direction_goals[v]*2; g.fillOval((int)(120+125+x*125-val/2),(int)( 50+125+y*125-val/2), (int)val, (int)val); } } if (display) g.setColor(Color.red); else g.setColor(Color.black); g.fillRect(10, 10, 20, 20); for (int i=0;i<agent.decision.data.length;i++){ if (agent.decision.data[i]) g.setColor(Color.red); else g.setColor(Color.black); g.fillRect(20+40*i, 600, 20, 20); } } @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyCode()); if (e.getKeyCode()==100) agent.decision.action[0] = true; if (e.getKeyCode()==102) agent.decision.action[1] = true; if (e.getKeyCode()==101) agent.decision.action[2] = true; if (e.getKeyCode()== 98) agent.decision.action[3] = true; if (e.getKeyCode()== 97) agent.decision.action[4] = true; if (e.getKeyCode()== 99) agent.decision.action[5] = true; } @Override public void keyReleased(KeyEvent e) { //System.out.println(" - "+e.getKeyCode()); if (e.getKeyCode()==100) agent.decision.action[0] = false; if (e.getKeyCode()==102) agent.decision.action[1] = false; if (e.getKeyCode()==101) agent.decision.action[2] = false; if (e.getKeyCode()== 98) agent.decision.action[3] = false; if (e.getKeyCode()== 97) agent.decision.action[4] = false; if (e.getKeyCode()== 99) agent.decision.action[5] = false; } public void keyTyped(KeyEvent arg0) {} public void mouseClicked(MouseEvent e) { if (e.getX()>=10 && e.getX()<=30 && e.getY()>=10 && e.getY()<=30) display=!display; for (int i=0;i<agent.decision.data.length;i++){ if (e.getX()>=20+i*40 && e.getX()<=40+i*40 && e.getY()>=600 && e.getY()<=620) agent.decision.data[i]=!agent.decision.data[i]; } } public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) { agent.started=true; } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems.impl; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.core.model.type.ComposedTypeModel; import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException; import de.hybris.platform.servicelayer.type.TypeService; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class DefaultItemTypePopulatorProviderTest { private static final String CHILD_TYPE = "CHILD_TYPE"; private static final String PARENT_TYPE = "PARENT_TYPE"; private static final String INVALID_TYPE = "INVALID_TYPE"; @Mock private TypeService typeService; @InjectMocks private DefaultItemTypePopulatorProvider itemTypePopulatorProvider; private Map<String, Populator<Map<String, Object>, ItemModel>> populatorsMap = new HashMap<>(); @Mock private ComposedTypeModel parentComposedType; @Mock private ComposedTypeModel childComposedType; @Mock private Populator<Map<String, Object>, ItemModel> childPopulator; @Mock private Populator<Map<String, Object>, ItemModel> parentPopulator; @Before public void setup() { when(childComposedType.getSuperType()).thenReturn(parentComposedType); when(childComposedType.getCode()).thenReturn(CHILD_TYPE); when(parentComposedType.getCode()).thenReturn(PARENT_TYPE); when(typeService.getComposedTypeForCode(PARENT_TYPE)).thenReturn(parentComposedType); when(typeService.getComposedTypeForCode(CHILD_TYPE)).thenReturn(childComposedType); when(typeService.getComposedTypeForCode(INVALID_TYPE)).thenThrow(UnknownIdentifierException.class); itemTypePopulatorProvider.setPopulatorsMap(populatorsMap); } @Test public void testWhenTypeCodeIsInvalid_shouldReturnEmptyPopulator() { final Optional<Populator<Map<String, Object>, ItemModel>> itemTypePopulator = itemTypePopulatorProvider .getItemTypePopulator(INVALID_TYPE); assertThat(itemTypePopulator.isPresent(), is(false)); } @Test public void testWhenChildTypeHasPopulator_shouldReturnChildPopulator() { populatorsMap.put(CHILD_TYPE, childPopulator); final Optional<Populator<Map<String, Object>, ItemModel>> itemTypePopulator = itemTypePopulatorProvider .getItemTypePopulator(CHILD_TYPE); assertThat(itemTypePopulator.isPresent(), is(true)); assertThat(itemTypePopulator.get(), is(childPopulator)); } @Test public void testWhenParentTypeHasPopulator_shouldReturnParentPopulator() { populatorsMap.put(PARENT_TYPE, parentPopulator); final Optional<Populator<Map<String, Object>, ItemModel>> itemTypePopulator = itemTypePopulatorProvider .getItemTypePopulator(CHILD_TYPE); assertThat(itemTypePopulator.isPresent(), is(true)); assertThat(itemTypePopulator.get(), is(parentPopulator)); } @Test public void testWhenNoPopulatorWasFound_shouldReturnEmptyPopulator() { final Optional<Populator<Map<String, Object>, ItemModel>> itemTypePopulator = itemTypePopulatorProvider .getItemTypePopulator(CHILD_TYPE); assertThat(itemTypePopulator.isPresent(), is(false)); } }
package com.WebServiceProduceCrud.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.WebServiceProduceCrud.model.Books; @Repository public interface BooksRepository extends CrudRepository<Books, Integer> { Iterable<Books> findByBookidAndBookname(int bookid,String bookname); public Books findByBookid(int bookid); }
package com.diozero.sampleapps; /*- * #%L * Organisation: diozero * Project: diozero - Sample applications * Filename: MotionTest.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import java.util.ArrayList; import java.util.List; import org.tinylog.Logger; import com.diozero.api.DigitalInputDevice; import com.diozero.api.GpioEventTrigger; import com.diozero.api.GpioPullUpDown; import com.diozero.devices.sandpit.MotionSensor; import com.diozero.util.SleepUtil; public class MotionTest implements AutoCloseable { public static void main(String[] args) { try (MotionTest test = new MotionTest(19, 26)) { Logger.info("Sleeping for 60s"); SleepUtil.sleepSeconds(60); } } private List<DigitalInputDevice> sensors; private MotionTest(int... pins) { sensors = new ArrayList<>(); for (int pin : pins) { //DigitalInputDevice sensor = new MotionSensor(pin); DigitalInputDevice sensor; if (pin == 26) { // Fudge for this strange type of PIR: // http://skpang.co.uk/catalog/pir-motion-sensor-p-796.html // Red (5V) / White (Ground) / Black (open collector Alarm) // The alarm pin is an open collector meaning you will need a pull up resistor on the alarm pin // Signal motion if there are 5 or more alarms in a 200ms period, check every 50ms sensor = new MotionSensor(pin, GpioPullUpDown.PULL_UP, 5, 200, 50); } else { sensor = new DigitalInputDevice(pin, GpioPullUpDown.PULL_DOWN, GpioEventTrigger.BOTH); } Logger.info("Created sensor on pin " + pin + " pud=" + sensor.getPullUpDown() + ", trigger=" + sensor.getTrigger()); sensor.whenActivated(nanoTime ->System.out.println("Pin " + pin + " activated")); sensor.whenDeactivated(nanoTime ->System.out.println("Pin " + pin + " deactivated")); sensors.add(sensor); } } @Override public void close() { for (DigitalInputDevice sensor : sensors) { sensor.close(); } } }
package com.erjiguan.apods.mvp.model.impl; import com.erjiguan.apods.base.OnLoadDataListener; import com.erjiguan.apods.mvp.model.IMainModel; import com.erjiguan.apods.mvp.model.bean.BluetoothStatusBean; public class MainModelImpl implements IMainModel { @Override public void registerBtStatusListner(final OnLoadDataListener<BluetoothStatusBean> listener) { // TODO 打开蓝牙(应该在presenter里面)、注册蓝牙监听、在监听里调用listener的方法进行响应,listner会回调到app去更新view,javabean,能不能判断是哪个成员变量改变了,仅去更新他对应的view } @Override public void unRegisterBtStatusListner(OnLoadDataListener<BluetoothStatusBean> listener) { } }
package com.dreamworks.example.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Created by mmonti on 4/20/17. */ @Data @ConfigurationProperties(prefix = "wfg.neo4j") public class Neo4jProperties { private String domainPackage; private String driverClassname; private String uri; private String username; private String password; }
package com.tencent.mm.wallet_core.ui.formview; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.wxpay.a.i; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; class a$9 implements OnClickListener { final /* synthetic */ MMActivity ixt; a$9(MMActivity mMActivity) { this.ixt = mMActivity; } public final void onClick(View view) { h.a(this.ixt, this.ixt.getString(i.wallet_card_name_illustraction_new_detail), this.ixt.getString(i.wallet_card_name_illustraction), this.ixt.getString(i.wallet_card_name_illustraction_new_chnage_name), this.ixt.getString(i.wallet_card_name_illustraction_new_i_know), new 1(this), new 2(this)); } }
package annotator; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FSIterator; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import annotation.Gene_lingpipe; import annotation.SentenceAnnotation; import com.aliasi.chunk.Chunk; import com.aliasi.chunk.Chunker; import com.aliasi.chunk.ConfidenceChunker; import com.aliasi.util.AbstractExternalizable; /** * Extract the gene and protein words via Lingpipe * * If the confidence is larger than the CONFIDENCE_THRESHOLD, then we believe it is right answer we * need, otherwise it is a wrong answer * * @author RuijianWang * */ public class GeneAnnotator_Lingpipe extends JCasAnnotator_ImplBase { static final double CONFIDENCE_THRESHOLD = 0.67; static final int WORD_MAX_LENGTH = 40; File dict = null; ConfidenceChunker chunker = null; /** * Intialize the dictionary file to utilize Lingpipe. */ public void initialize(UimaContext context) { System.out.println("start to load"); try { chunker = (ConfidenceChunker) AbstractExternalizable.readResourceObject( GeneAnnotator_Lingpipe.class, (String) context.getConfigParameterValue("dictionary_file")); System.out.println("dict loaded");// test whether the dict loaded successfully or not } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Extract the gene and protein words and their index info via Lingpipe and put them into CAS */ @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { // TODO Auto-generated method stub // JCas jcas = aJCas; FSIterator<Annotation> iter = aJCas.getAnnotationIndex(SentenceAnnotation.type).iterator(); while (iter.hasNext()) { SentenceAnnotation sen_ann = (SentenceAnnotation) iter.next(); String sentence = sen_ann.getSentence(); char[] temp = sentence.toCharArray(); Iterator<Chunk> gene_iter = chunker.nBestChunks(temp, 0, temp.length, WORD_MAX_LENGTH); while (gene_iter.hasNext()) { Chunk chunk = gene_iter.next(); /** * tune the confidence in order to achieve a better result */ double confidence = Math.pow(2.0, chunk.score()); if (confidence < CONFIDENCE_THRESHOLD) { break; } int begin = chunk.start(); int end = chunk.end(); String gene = sentence.substring(begin, end); begin = begin - space_counter(sentence.substring(0, begin)); end = begin + gene.length() - space_counter(gene) - 1; Gene_lingpipe gene_ann = new Gene_lingpipe(aJCas); gene_ann.setStart(begin); gene_ann.setEnd(end); gene_ann.setId(sen_ann.getId()); gene_ann.setGene(gene); gene_ann.addToIndexes(); } } } /** * Since the start and end index we output does not contain white space, so we need to calculate * how many spaces it have * * @param input * the string that have white spaces needs to be calculated * @return the number of white spaces the input has */ int space_counter(String input) { int counter = 0; for (int i = 0; i < input.length(); i++) { if (Character.isWhitespace(input.charAt(i))) { counter++; } } return counter; } }
public class BiggsDarklighter extends Character implements Pilot{ public BiggsDarklighter(){ super("Biggs Darklighter","Light Side","Rebel",false); } public boolean pilot(){ return true; } }
/* * Copyright (c) 2008-2019 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.addon.ldap.core; import com.haulmont.addon.ldap.core.dao.CubaUserDao; import com.haulmont.addon.ldap.core.dao.DaoHelper; import com.haulmont.addon.ldap.core.dao.MatchingRuleDao; import com.haulmont.addon.ldap.core.rule.LdapMatchingRuleContext; import com.haulmont.addon.ldap.core.rule.appliers.MatchingRuleApplier; import com.haulmont.addon.ldap.dto.LdapUser; import com.haulmont.addon.ldap.entity.*; import com.haulmont.addon.ldap.service.UserSynchronizationService; import com.haulmont.cuba.core.Persistence; import com.haulmont.cuba.core.Transaction; import com.haulmont.cuba.core.global.AppBeans; import com.haulmont.cuba.core.global.Metadata; import com.haulmont.cuba.security.entity.Group; import com.haulmont.cuba.security.entity.Role; import com.haulmont.cuba.security.entity.User; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.HashMap; import java.util.List; import static org.junit.Assert.assertEquals; public class MatchingRuleTest { @ClassRule public static LdapTestContainer cont = LdapTestContainer.Common.INSTANCE; private Metadata metadata; private Persistence persistence; private MatchingRuleDao matchingRuleDao; private DaoHelper daoHelper; private CubaUserDao cubaUserDao; private UserSynchronizationService userSynchronizationService; private MatchingRuleApplier matchingRuleApplier; @Before public void setUp() throws Exception { matchingRuleDao = AppBeans.get(MatchingRuleDao.class); metadata = AppBeans.get(Metadata.class); persistence = AppBeans.get(Persistence.class); daoHelper = AppBeans.get(DaoHelper.class); cubaUserDao = AppBeans.get(CubaUserDao.class); userSynchronizationService = AppBeans.get(UserSynchronizationService.class); matchingRuleApplier = AppBeans.get(MatchingRuleApplier.class); } @Test public void simpleRuleTest() { try (Transaction tx = persistence.createTransaction()) { prepareSimpleTest(); List<CommonMatchingRule> rules = matchingRuleDao.getMatchingRules(); assertEquals(4, rules.size()); assertEquals(MatchingRuleType.SIMPLE, rules.get(0).getRuleType()); assertEquals(MatchingRuleType.CUSTOM, rules.get(1).getRuleType()); assertEquals(MatchingRuleType.SCRIPTING, rules.get(2).getRuleType()); assertEquals(MatchingRuleType.DEFAULT, rules.get(3).getRuleType()); SimpleMatchingRule simpleMatchingRule = (SimpleMatchingRule) rules.get(0); assertEquals("login", simpleMatchingRule.getConditions().get(0).getAttribute()); } } @Test public void testDefaultRule() { try (Transaction tx = persistence.createTransaction()) { //Custom MatchingRuleOrder customOrder = metadata.create(MatchingRuleOrder.class); customOrder.setOrder(1); customOrder.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); MatchingRuleStatus customStatus = metadata.create(MatchingRuleStatus.class); customStatus.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); customStatus.setIsActive(true); daoHelper.persistOrMerge(customOrder); daoHelper.persistOrMerge(customStatus); Group testGroup = metadata.create(Group.class); testGroup.setName("Test group"); daoHelper.persistOrMerge(testGroup); User joes = cubaUserDao.getCubaUserByLogin("joes"); joes.setGroup(testGroup); joes.setLoginLowerCase("joes"); daoHelper.persistOrMerge(joes); Role simpleRole = metadata.create(Role.class); simpleRole.setName("Simple role"); MatchingRuleOrder simpleOrder = metadata.create(MatchingRuleOrder.class); simpleOrder.setOrder(2); MatchingRuleStatus simpleStatus = metadata.create(MatchingRuleStatus.class); simpleStatus.setIsActive(false); SimpleRuleCondition simpleRuleCondition = metadata.create(SimpleRuleCondition.class); simpleRuleCondition.setAttribute("uid"); simpleRuleCondition.setAttributeValue("joes"); SimpleMatchingRule simpleMatchingRule = metadata.create(SimpleMatchingRule.class); simpleMatchingRule.setStatus(simpleStatus); simpleMatchingRule.setOrder(simpleOrder); simpleRuleCondition.setSimpleMatchingRule(simpleMatchingRule); simpleMatchingRule.getConditions().add(simpleRuleCondition); simpleMatchingRule.setAccessGroup(testGroup); simpleMatchingRule.getRoles().add(simpleRole); daoHelper.persistOrMerge(simpleRole); daoHelper.persistOrMerge(simpleMatchingRule); persistence.getEntityManager().getDelegate().flush(); List<CommonMatchingRule> rules = matchingRuleDao.getMatchingRules(); assertEquals(3, rules.size()); LdapUser ldapUser = new LdapUser(new HashMap<>()); ldapUser.setLogin("joes"); LdapMatchingRuleContext ldapMatchingRuleContext = new LdapMatchingRuleContext(ldapUser, joes); matchingRuleApplier.applyMatchingRules(matchingRuleDao.getMatchingRules(), ldapMatchingRuleContext, joes); assertEquals(1, ldapMatchingRuleContext.getAppliedRules().size()); assertEquals(true, ldapMatchingRuleContext.getAppliedRules().stream().allMatch(mr -> MatchingRuleType.DEFAULT == mr.getRuleType())); cubaUserDao.saveCubaUser(joes, joes, ldapMatchingRuleContext); User updated = cubaUserDao.getCubaUserByLogin("joes"); assertEquals("Administrators", updated.getUserRoles().get(0).getRole().getName()); assertEquals("Company", updated.getGroup().getName()); } } @Test public void testTerminalAttribute() { try (Transaction tx = persistence.createTransaction()) { prepareTerminalAttributeTest(true, "joes", true); User joes = cubaUserDao.getCubaUserByLogin("joes"); LdapUser ldapUser = new LdapUser(new HashMap<>()); ldapUser.setLogin("joes"); LdapMatchingRuleContext ldapMatchingRuleContext = new LdapMatchingRuleContext(ldapUser, joes); matchingRuleApplier.applyMatchingRules(matchingRuleDao.getMatchingRules(), ldapMatchingRuleContext, joes); assertEquals(1, ldapMatchingRuleContext.getAppliedRules().size()); assertEquals(true, ldapMatchingRuleContext.getAppliedRules().stream().allMatch(mr -> MatchingRuleType.SCRIPTING == mr.getRuleType())); assertEquals("Test group", joes.getGroup().getName()); assertEquals(1, joes.getUserRoles().size()); assertEquals("Scripting role 1", joes.getUserRoles().get(0).getRole().getName()); assertEquals(true, ldapMatchingRuleContext.isTerminalRuleApply()); cubaUserDao.saveCubaUser(joes, joes, ldapMatchingRuleContext); prepareTerminalAttributeTest(false, "bena", false); User bena = cubaUserDao.getCubaUserByLogin("bena"); ldapUser = new LdapUser(new HashMap<>()); ldapUser.setLogin("bena"); ldapMatchingRuleContext = new LdapMatchingRuleContext(ldapUser, bena); matchingRuleApplier.applyMatchingRules(matchingRuleDao.getMatchingRules(), ldapMatchingRuleContext, bena); assertEquals(2, ldapMatchingRuleContext.getAppliedRules().size()); assertEquals(true, ldapMatchingRuleContext.getAppliedRules().stream().allMatch(mr -> MatchingRuleType.SCRIPTING == mr.getRuleType())); assertEquals("Test group", bena.getGroup().getName()); assertEquals(2, bena.getUserRoles().size()); assertEquals(true, bena.getUserRoles().stream().anyMatch(ur -> ur.getRole().getName().equals("Scripting role 1"))); assertEquals(true, bena.getUserRoles().stream().anyMatch(ur -> ur.getRole().getName().equals("Scripting role 2"))); assertEquals(false, ldapMatchingRuleContext.isTerminalRuleApply()); cubaUserDao.saveCubaUser(bena, bena, ldapMatchingRuleContext); } } @Test public void testOverrideAttribute() { try (Transaction tx = persistence.createTransaction()) { prepareOverrideAttributeTest(true, "joes", true); User joes = cubaUserDao.getCubaUserByLogin("joes"); LdapUser ldapUser = new LdapUser(new HashMap<>()); ldapUser.setLogin("joes"); LdapMatchingRuleContext ldapMatchingRuleContext = new LdapMatchingRuleContext(ldapUser, joes); matchingRuleApplier.applyMatchingRules(matchingRuleDao.getMatchingRules(), ldapMatchingRuleContext, joes); assertEquals(2, ldapMatchingRuleContext.getAppliedRules().size()); assertEquals(true, ldapMatchingRuleContext.getAppliedRules().stream().allMatch(mr -> MatchingRuleType.SCRIPTING == mr.getRuleType())); assertEquals("Test group 2", joes.getGroup().getName()); assertEquals(1, joes.getUserRoles().size()); assertEquals("Scripting role 2", joes.getUserRoles().get(0).getRole().getName()); cubaUserDao.saveCubaUser(joes, joes, ldapMatchingRuleContext); prepareOverrideAttributeTest(false, "bena", false); User bena = cubaUserDao.getCubaUserByLogin("bena"); ldapUser = new LdapUser(new HashMap<>()); ldapUser.setLogin("bena"); ldapMatchingRuleContext = new LdapMatchingRuleContext(ldapUser, bena); matchingRuleApplier.applyMatchingRules(matchingRuleDao.getMatchingRules(), ldapMatchingRuleContext, bena); assertEquals(2, ldapMatchingRuleContext.getAppliedRules().size()); assertEquals(true, ldapMatchingRuleContext.getAppliedRules().stream().allMatch(mr -> MatchingRuleType.SCRIPTING == mr.getRuleType())); assertEquals("Test group 1", bena.getGroup().getName()); assertEquals(2, bena.getUserRoles().size()); assertEquals(true, bena.getUserRoles().stream().anyMatch(ur -> ur.getRole().getName().equals("Scripting role 1"))); assertEquals(true, bena.getUserRoles().stream().anyMatch(ur -> ur.getRole().getName().equals("Scripting role 2"))); cubaUserDao.saveCubaUser(bena, bena, ldapMatchingRuleContext); } } private void prepareSimpleTest() { Group testGroup = metadata.create(Group.class); testGroup.setName("Test group"); daoHelper.persistOrMerge(testGroup); //Custom MatchingRuleOrder customOrder = metadata.create(MatchingRuleOrder.class); customOrder.setOrder(2); customOrder.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); MatchingRuleStatus customStatus = metadata.create(MatchingRuleStatus.class); customStatus.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); customStatus.setIsActive(true); daoHelper.persistOrMerge(customOrder); daoHelper.persistOrMerge(customStatus); //Simple Role simpleRole = metadata.create(Role.class); simpleRole.setName("Simple role"); MatchingRuleOrder simpleOrder = metadata.create(MatchingRuleOrder.class); simpleOrder.setOrder(1); MatchingRuleStatus simpleStatus = metadata.create(MatchingRuleStatus.class); simpleStatus.setIsActive(true); SimpleRuleCondition simpleRuleCondition = metadata.create(SimpleRuleCondition.class); simpleRuleCondition.setAttribute("login"); simpleRuleCondition.setAttributeValue("barts"); SimpleMatchingRule simpleMatchingRule = metadata.create(SimpleMatchingRule.class); simpleMatchingRule.setStatus(simpleStatus); simpleMatchingRule.setOrder(simpleOrder); simpleRuleCondition.setSimpleMatchingRule(simpleMatchingRule); simpleMatchingRule.getConditions().add(simpleRuleCondition); simpleMatchingRule.setAccessGroup(testGroup); simpleMatchingRule.getRoles().add(simpleRole); daoHelper.persistOrMerge(simpleRole); daoHelper.persistOrMerge(simpleMatchingRule); //Scripting Role scriptingRole = metadata.create(Role.class); scriptingRole.setName("Scripting role"); MatchingRuleOrder scriptingOrder = metadata.create(MatchingRuleOrder.class); scriptingOrder.setOrder(3); MatchingRuleStatus scriptingStatus = metadata.create(MatchingRuleStatus.class); scriptingStatus.setIsActive(false); ScriptingMatchingRule scriptingMatchingRule = metadata.create(ScriptingMatchingRule.class); scriptingMatchingRule.setAccessGroup(testGroup); scriptingMatchingRule.setStatus(scriptingStatus); scriptingMatchingRule.setOrder(scriptingOrder); scriptingMatchingRule.setScriptingCondition("{ldapContext}.ldapUser.login=='admin'"); scriptingMatchingRule.getRoles().add(scriptingRole); daoHelper.persistOrMerge(scriptingRole); daoHelper.persistOrMerge(scriptingMatchingRule); persistence.getEntityManager().flush(); persistence.getEntityManager().getDelegate().clear(); } private void prepareTerminalAttributeTest(boolean terminal, String login, boolean createCustom) { persistence.getEntityManager().getDelegate().clear(); Group testGroup = metadata.create(Group.class); testGroup.setName("Test group"); daoHelper.persistOrMerge(testGroup); //Custom if (createCustom) { MatchingRuleOrder customOrder = metadata.create(MatchingRuleOrder.class); customOrder.setOrder(1); customOrder.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); MatchingRuleStatus customStatus = metadata.create(MatchingRuleStatus.class); customStatus.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); customStatus.setIsActive(true); daoHelper.persistOrMerge(customOrder); daoHelper.persistOrMerge(customStatus); } //Scripting 1 Role scriptingRole1 = metadata.create(Role.class); scriptingRole1.setName("Scripting role 1"); MatchingRuleOrder scriptingOrder1 = metadata.create(MatchingRuleOrder.class); scriptingOrder1.setOrder(2); MatchingRuleStatus scriptingStatus1 = metadata.create(MatchingRuleStatus.class); scriptingStatus1.setIsActive(true); ScriptingMatchingRule scriptingMatchingRule1 = metadata.create(ScriptingMatchingRule.class); scriptingMatchingRule1.setAccessGroup(testGroup); scriptingMatchingRule1.setStatus(scriptingStatus1); scriptingMatchingRule1.setOrder(scriptingOrder1); scriptingMatchingRule1.setScriptingCondition("{ldapContext}.ldapUser.login=='" + login + "'"); scriptingMatchingRule1.getRoles().add(scriptingRole1); scriptingMatchingRule1.setIsTerminalRule(terminal); daoHelper.persistOrMerge(scriptingRole1); daoHelper.persistOrMerge(scriptingMatchingRule1); //Scripting 2 Role scriptingRole2 = metadata.create(Role.class); scriptingRole2.setName("Scripting role 2"); MatchingRuleOrder scriptingOrder2 = metadata.create(MatchingRuleOrder.class); scriptingOrder2.setOrder(3); MatchingRuleStatus scriptingStatus2 = metadata.create(MatchingRuleStatus.class); scriptingStatus2.setIsActive(true); ScriptingMatchingRule scriptingMatchingRule2 = metadata.create(ScriptingMatchingRule.class); scriptingMatchingRule2.setAccessGroup(testGroup); scriptingMatchingRule2.setStatus(scriptingStatus2); scriptingMatchingRule2.setOrder(scriptingOrder2); scriptingMatchingRule2.setScriptingCondition("{ldapContext}.ldapUser.login=='" + login + "'"); scriptingMatchingRule2.getRoles().add(scriptingRole2); daoHelper.persistOrMerge(scriptingRole2); daoHelper.persistOrMerge(scriptingMatchingRule2); persistence.getEntityManager().flush(); } private void prepareOverrideAttributeTest(boolean override, String login, boolean createCustom) { persistence.getEntityManager().getDelegate().clear(); Group testGroup1 = metadata.create(Group.class); testGroup1.setName("Test group 1"); daoHelper.persistOrMerge(testGroup1); Group testGroup2 = metadata.create(Group.class); testGroup2.setName("Test group 2"); daoHelper.persistOrMerge(testGroup2); //Custom if (createCustom) { MatchingRuleOrder customOrder = metadata.create(MatchingRuleOrder.class); customOrder.setOrder(1); customOrder.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); MatchingRuleStatus customStatus = metadata.create(MatchingRuleStatus.class); customStatus.setCustomMatchingRuleId("com.haulmont.addon.ldap.core.custom.TestCustomLdapRule"); customStatus.setIsActive(true); daoHelper.persistOrMerge(customOrder); daoHelper.persistOrMerge(customStatus); } //Scripting 1 Role scriptingRole1 = metadata.create(Role.class); scriptingRole1.setName("Scripting role 1"); MatchingRuleOrder scriptingOrder1 = metadata.create(MatchingRuleOrder.class); scriptingOrder1.setOrder(2); MatchingRuleStatus scriptingStatus1 = metadata.create(MatchingRuleStatus.class); scriptingStatus1.setIsActive(true); ScriptingMatchingRule scriptingMatchingRule1 = metadata.create(ScriptingMatchingRule.class); scriptingMatchingRule1.setAccessGroup(testGroup1); scriptingMatchingRule1.setStatus(scriptingStatus1); scriptingMatchingRule1.setOrder(scriptingOrder1); scriptingMatchingRule1.setScriptingCondition("{ldapContext}.ldapUser.login=='" + login + "'"); scriptingMatchingRule1.getRoles().add(scriptingRole1); scriptingMatchingRule1.setIsOverrideExistingAccessGroup(override); scriptingMatchingRule1.setIsOverrideExistingRoles(override); daoHelper.persistOrMerge(scriptingRole1); daoHelper.persistOrMerge(scriptingMatchingRule1); //Scripting 2 Role scriptingRole2 = metadata.create(Role.class); scriptingRole2.setName("Scripting role 2"); MatchingRuleOrder scriptingOrder2 = metadata.create(MatchingRuleOrder.class); scriptingOrder2.setOrder(3); MatchingRuleStatus scriptingStatus2 = metadata.create(MatchingRuleStatus.class); scriptingStatus2.setIsActive(true); ScriptingMatchingRule scriptingMatchingRule2 = metadata.create(ScriptingMatchingRule.class); scriptingMatchingRule2.setAccessGroup(testGroup2); scriptingMatchingRule2.setStatus(scriptingStatus2); scriptingMatchingRule2.setOrder(scriptingOrder2); scriptingMatchingRule2.setScriptingCondition("{ldapContext}.ldapUser.login=='" + login + "'"); scriptingMatchingRule2.getRoles().add(scriptingRole2); scriptingMatchingRule2.setIsOverrideExistingAccessGroup(override); scriptingMatchingRule2.setIsOverrideExistingRoles(override); daoHelper.persistOrMerge(scriptingRole2); daoHelper.persistOrMerge(scriptingMatchingRule2); persistence.getEntityManager().flush(); } }
package zystudio.cases.prepare; public class CaseForSortedHashMap { }
package com.demo.sorting; import java.util.Comparator; public class Employee /*implements Comparable<Employee>*/ { private int empId; private String empName; private int empAge; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpAge() { return empAge; } public void setEmpAge(int empAge) { this.empAge = empAge; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", empAge=" + empAge + "]"; } public Employee(int empId, String empName, int empAge) { super(); this.empId = empId; this.empName = empName; this.empAge = empAge; } public Employee() { super(); // TODO Auto-generated constructor stub } /* public int compareTo(Employee o) { // TODO Auto-generated method stub return this.empId-o.empId; //reverse //return -(this.empId-o.empId); } */ public static Comparator<Employee> EmpIdComparator=new Comparator<Employee>() { public int compare(Employee o1, Employee o2) { // TODO Auto-generated method stub return o1.empId-o2.empId; } }; public static Comparator<Employee> EmpNameComparator = new Comparator<Employee>() { public int compare(Employee o1, Employee o2) { // TODO Auto-generated method stub return o1.empName.compareTo(o2.empName); } }; }
package kr.ac.hansung.cst.recycleback.dao; import kr.ac.hansung.cst.recycleback.model.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface UserDao extends JpaRepository<User,String> { User findByUsername(String username); User findByEmail(String email); }
package com.tao.logger.log; import com.tao.logger.strategy.Strategy; import static com.tao.logger.utils.Utils.getStackTraceString; import static com.tao.logger.utils.Utils.isEmpty; /** * @project android_lib_logger * @class name:com.nj.baijiayun.logger.log * @describe * @anthor houyi QQ:1007362137 * @time 2019/4/29 5:50 PM * @change * @time * @describe */ class LoggerImpl implements ILogger { private final com.tao.logger.strategy.Strategy strategy; public LoggerImpl(Strategy formatStrategy) { strategy = formatStrategy; } @Override public void log(int priority, String message, Throwable t) { log(priority, null, message, t); } @Override public void log(int priority, String onceOnlyTag, String message, Throwable t) { if (t != null && message != null) { message += " : " + getStackTraceString(t); } if (t != null && message == null) { message = getStackTraceString(t); } if (isEmpty(message)) { message = "Empty/NULL log message"; } strategy.log(priority, onceOnlyTag, message); } }
package com.sharpower.beckhoff; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.sharpower.entity.Fun; import com.sharpower.entity.PlcType; import com.sharpower.entity.Variable; import com.sharpower.entity.VariableType; import com.sharpower.scada.exception.AdsException; import com.sharpower.service.PlcDataReader; import com.sharpower.service.PlcTypeService; import com.sharpower.service.VariableService; import com.sharpower.service.VariableTypeService; public class FunDataReadWriteBeckhoffService implements PlcDataReader{ private VariableTypeService variableTypeService; private VariableService variableService; private PlcTypeService plcTypeService; private Map<String, List<FunDataReadWriteBeckhoff>> funDataReaders=new HashMap<>(); public VariableTypeService getVariableTypeService() { return variableTypeService; } public void setVariableTypeService(VariableTypeService variableTypeService) { this.variableTypeService = variableTypeService; } public void setPlcTypeService(PlcTypeService plcTypeService) { this.plcTypeService = plcTypeService; } public VariableService getVariableService() { return variableService; } public void setVariableService(VariableService variableService) { this.variableService = variableService; } public Map<Variable,Object> readDataAll(Fun fun) throws AdsException { if (funDataReaders.isEmpty()) { List<VariableType> variableTypes = variableTypeService.findEntityByHQL("FROM VariableType"); List<PlcType> plcTypes = plcTypeService.findEntityByHQL("FROM PlcType p WHERE p.plcCommType.name='beckhoff'"); for (PlcType plcType : plcTypes){ List<FunDataReadWriteBeckhoff> funDataReader = new ArrayList<>(); for (VariableType variableType : variableTypes) { List<Variable> variables = variableService.findEntityByHQL("FROM Variable v where v.plcType.name=? and v.type.plcType=?", plcType.getName(), variableType.getPlcType()); if (variables==null){ continue; } variableType.setVals(variables); funDataReader.add(new FunDataReadWriteBeckhoff(variableType)); } funDataReaders.put(plcType.getName(), funDataReader); } } Map<Variable, Object> datas = new HashMap<>(); List<FunDataReadWriteBeckhoff> funDataReader= funDataReaders.get(fun.getPlcType().getName()); for (FunDataReadWriteBeckhoff funData : funDataReader) { datas.putAll(funData.readData(fun.getAddress())); } return datas; } }