text
stringlengths 10
2.72M
|
|---|
package com.online.spring.web.model;
public class Suppliers_Address {
int supplierID;
String companyName;
String contactName;
String contactJobTitle;
String username;
String password;
int addsupplierID;
String address;
String city;
String state;
String country;
int postalcode;
String phoneoffice;
String fax;
String email;
public Suppliers_Address() {
}
public Suppliers_Address(int supplierID, String companyName, String contactName, String contactJobTitle,
String username, String password, int addsupplierID, String address, String city, String state,
String country, int postalcode, String phoneoffice, String fax, String email) {
this.supplierID = supplierID;
this.companyName = companyName;
this.contactName = contactName;
this.contactJobTitle = contactJobTitle;
this.username = username;
this.password = password;
this.addsupplierID = addsupplierID;
this.address = address;
this.city = city;
this.state = state;
this.country = country;
this.postalcode = postalcode;
this.phoneoffice = phoneoffice;
this.fax = fax;
this.email = email;
}
public int getSupplierID() {
return supplierID;
}
public void setSupplierID(int supplierID) {
this.supplierID = supplierID;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactJobTitle() {
return contactJobTitle;
}
public void setContactJobTitle(String contactJobTitle) {
this.contactJobTitle = contactJobTitle;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAddsupplierID() {
return addsupplierID;
}
public void setAddsupplierID(int addsupplierID) {
this.addsupplierID = addsupplierID;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getPostalcode() {
return postalcode;
}
public void setPostalcode(int postalcode) {
this.postalcode = postalcode;
}
public String getPhoneoffice() {
return phoneoffice;
}
public void setPhoneoffice(String phoneoffice) {
this.phoneoffice = phoneoffice;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Suppliers_Address [supplierID=" + supplierID + ", companyName=" + companyName + ", contactName="
+ contactName + ", contactJobTitle=" + contactJobTitle + ", username=" + username + ", password="
+ password + ", addsupplierID=" + addsupplierID + ", address=" + address + ", city=" + city + ", state="
+ state + ", country=" + country + ", postalcode=" + postalcode + ", phoneoffice=" + phoneoffice
+ ", fax=" + fax + ", email=" + email + "]";
}
}
|
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
/**
* Created by dobatake on 4/25/16.
*/
public class WordAnalyzer {
private HashMap<String, Integer> wordCount;
private ArrayList<Path> docStoreList;
private Path docStore;
public WordAnalyzer(){
this.docStore = Paths.get("").toAbsolutePath();
this.docStore = Paths.get(this.docStore.toString(), "output");
this.wordCount = new HashMap<>();
this.docStoreList = DirectoryIterator.getTextFiles(this.docStore);
}
public void parseHTMLDocument(Path htmldoc){
File currentPage = new File(htmldoc.toString());
try {
Document doc = Jsoup.parse(currentPage, "UTF-8");
Elements elements = doc.body().select("*");
for (Element element : elements) {
// Remove all punctuation, convert to lowercase then split on the whitespace
String [] words = element.ownText().replaceAll("\\p{P}", "").toLowerCase().split("\\s+");
for(String w : words){
Integer count = this.wordCount.get(w);
if (count == null) {
wordCount.put(w, 1);
}
else {
wordCount.put(w, count + 1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void parseTextDocument(Path textDoc){
Charset charset = Charset.forName("UTF-8");
try (BufferedReader reader = Files.newBufferedReader(textDoc, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
String [] words = line.replaceAll("\\p{P}", "").toLowerCase().split("\\s+");
for(String w : words){
Integer count = this.wordCount.get(w);
if (count == null) {
wordCount.put(w, 1);
}
else {
wordCount.put(w, count + 1);
}
}
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
// Sorting a hashmap based on values; creates a descending list
// http://stackoverflow.com/a/11648106
public static <K,V extends Comparable<? super V>>
List<Map.Entry<K, V>> entriesSortedByValues(Map<K,V> map) {
List<Map.Entry<K,V>> sortedEntries = new ArrayList<Map.Entry<K,V>>(map.entrySet());
Collections.sort(sortedEntries,
new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
return e2.getValue().compareTo(e1.getValue());
}
}
);
return sortedEntries;
}
public int getWordCount(){
int wordCount = 0;
for(Map.Entry<String, Integer> entry : this.wordCount.entrySet()) {
if(entry.getKey().isEmpty())
continue;
Integer value = entry.getValue();
wordCount += value;
}
return wordCount;
}
// Output .csv file w/ text statistics
public void writeStatistics(int totalWordCount){
int rank = 1;
List<Map.Entry<String, Integer>> wordList = entriesSortedByValues(wordCount);
for(Map.Entry<String, Integer> entry : wordList) {
String key = entry.getKey();
// ignore empty string that gets added from splitting
if(key.isEmpty())
continue;
Integer value = entry.getValue();
float probability = (float) value/ (float) totalWordCount;
float zipf = rank * probability;
String output = key + ", " + rank + ", " + value + ", " + zipf + ",\n";
rank++;
Path statfile = Paths.get(this.docStore.toString(), "..", "stats.csv").normalize();
try (BufferedWriter writer = Files.newBufferedWriter(statfile, Charset.forName("UTF-8"),
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
writer.write(output, 0, output.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
}
public void run(){
for(Path p : docStoreList){
parseTextDocument(Paths.get(this.docStore.toString(), p.toString()));
}
writeStatistics(getWordCount());
}
public static void main(String[] args) {
WordAnalyzer wa = new WordAnalyzer();
wa.run();
}
}
|
package com.eshop.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.eshop.dao.UserDAO;
@Controller
public class EmailAvailabilityController {
@RequestMapping(value = "/emailAvailability", method = RequestMethod.POST)
@ResponseBody
public String emailAvailability(HttpServletRequest request){
try {
boolean result = new UserDAO().isAvailable(request.getParameter("email"));
if(result == true || !minLength(request.getParameter("email"))){
return "true";
}else{
return "false";
}
} catch (SQLException e) {
e.printStackTrace();
}
return "false";
}
private boolean minLength(String email){
int length = 0;
for (int index = 0; index < email.length(); index++) {
if(email.charAt(index) != '@'){
length++;
}else{
break;
}
}
return length >= 3 ? true : false;
}
}
|
package com.example.shucheng_fu.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.shucheng_fu.calculator.R;
import java.text.DecimalFormat;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private TextView _screen;
private String display = "";
private String currentOperator="";
private String currentOpint="";
double result;
String formatResult;
String updateResult;
boolean clickOp = false;
boolean clickPoint = false;
String add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_screen = (TextView)findViewById(R.id.myTextView1);
_screen.setText(display);
}
public void onClickNumber(View v){
Button b = (Button) v;
display = display + b.getText();
_screen.setText(display);
clickOp = true;
clickPoint = true;
if(currentOpint.length() ==1){
clickPoint =false;
}
//display = display + updateResult;
if (currentOperator.length() < 1){
return;
}else {
if(updateResult == null) { // display=updateResult + display;
String[] operation = display.split(Pattern.quote(currentOperator));
//get first one value:
result = operateArithmetic(operation[0], operation[1], currentOperator);
if(result == (int)result) {
DecimalFormat decimalFormat = new DecimalFormat("#.#");
formatResult = decimalFormat.format(result);
_screen.setText(display + "\n" + String.valueOf(formatResult));
updateResult = String.valueOf(formatResult);
}else {
_screen.setText(display + "\n" + String.valueOf(result));
updateResult = String.valueOf(result);
System.out.println(updateResult);
}
}else {
String[] operation = display.split(Pattern.quote(currentOperator));
System.out.println(currentOperator);
System.out.println(display);
//get value:
result = operateArithmetic(operation[0], operation[1], currentOperator);
System.out.println(result);
if(result == (int)result) {
DecimalFormat decimalFormat = new DecimalFormat("#.#");
formatResult = decimalFormat.format(result);
System.out.println(formatResult);
//updateResult = String.valueOf(result);
_screen.setText(display + "\n" + String.valueOf(formatResult));
//updateResult = String.valueOf(result);
updateResult = String.valueOf(formatResult);
}else {
_screen.setText(display + "\n" + String.valueOf(result));
updateResult = String.valueOf(result);
System.out.println(updateResult);
}
}
}
}
public void onClickPoint(View v){
Button b = (Button) v;
if(display == ""){
return;
}else {
if(clickPoint) {
display += b.getText();
currentOpint = b.getText().toString();
_screen.setText(display);
clickPoint = false;
}
}
}
public void onClickOperator (View v) {
Button b = (Button) v;
if (display == "") {
return;
}
else{
if (updateResult == null) {
if(clickOp) {
display = display + b.getText();
currentOperator = b.getText().toString();
_screen.setText(display);
clickOp =false;
currentOpint = "";
}
}
else {
//modify
//clickOp =false;
display = updateResult + b.getText();
currentOperator = b.getText().toString();
_screen.setText(display);
//clickOp =false;
}
}
}
private double operateArithmetic (String a ,String b ,String op){
switch (op) {
case "+":
return (Double.valueOf(a) + Double.valueOf(b));
case "-":
return (Double.valueOf(a) - Double.valueOf(b));
case "*":
return (Double.valueOf(a) * Double.valueOf(b));
case "/":
return (Double.valueOf(a) / Double.valueOf(b));
}
return -1;
}
public void onClickEqual (View v){
_screen.setText(updateResult);
// String[] operation = display.split(Pattern.quote(currentOperator));
// if (currentOperator.length() < 1){
// return;
// }else {
// //get value:
// result = operateArithmetic(operation[0] , operation[1] ,currentOperator);
// //_screen.setText(display + "\n" + String.valueOf(result));
// _screen.setText(display + "\n" + String.valueOf(result));
// updateResult = String.valueOf(result);
//
// }
}
private void clear (){
//display.substring(0,display.length()-1);
display = "";
currentOperator = "";
updateResult = null;
currentOpint ="";
_screen.setText(updateResult);
}
// public void onClickClear (View v){
// clear();
// }
public boolean onLongClick(View v){
clear();
//String a;
//String str = new String();
//str = str.substring(0,display.length() - 1);
return true;
}
}
|
/** An interface to indicate what shapes are regular polygons and to
* provide the formula for calculating the area
*/
public interface RegularPolygon {
/** Returns the number of angles of the polygon */
int getNumberAngles();
/** Returns the length of a side */
double getSideLength();
/** One way to implement the area of a regular polygon code in an interface:
* As a static method
* area = 1/4 (numAngles) * (sideLength)^2 * cot(pi/numAngles)
*/
public static double areaOfRegularPolygon(RegularPolygon p) {
return (p.getNumberAngles() * p.getSideLength() * p.getSideLength()) /
(4 * Math.tan(Math.PI / p.getNumberAngles()));
}
/** A second way to implement the area of a regular polygon code in an interface:
* As the default body for an abstract instance method
* area = 1/4 (numAngles) * (sideLength)^2 * cot(pi/numAngles)
*/
default double areaOfRegularPolygon() {
return (this.getNumberAngles() * this.getSideLength() * this.getSideLength()) /
(4 * Math.tan(Math.PI / this.getNumberAngles()));
}
}
|
package org.vanilladb.comm.protocols.rb;
import org.vanilladb.comm.protocols.beb.Broadcast;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.Session;
public class ReliableBroadcast extends Broadcast {
// We must provide a public constructor for TcpCompleteSession
// in order to reconstruct this on the other side
public ReliableBroadcast() {
super();
}
public ReliableBroadcast(Channel channel, int direction, Session source)
throws AppiaEventException {
super(channel, direction, source);
}
}
|
package com.git.cloud.resmgt.common.dao;
import java.util.List;
import java.util.Map;
import com.git.cloud.cloudservice.model.po.CloudServicePo;
import com.git.cloud.common.dao.ICommonDAO;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.common.model.po.RmHostResPo;
import com.git.cloud.resmgt.common.model.po.RmPlatformPo;
import com.git.cloud.resmgt.common.model.po.RmVirtualTypePo;
import com.git.cloud.resmgt.compute.model.po.RmCdpPo;
import com.git.cloud.resmgt.network.model.po.RmNwCclassPo;
public interface IRmPlatformDAO extends ICommonDAO{
public void savaRmPlatform(RmPlatformPo rmPlatformPo) throws RollbackableBizException;
public void updateRmPlatform(RmPlatformPo rmPlatformPo) throws RollbackableBizException;
public RmPlatformPo selectRmPlatform(String platformId) throws RollbackableBizException;
public List<Map<String, Object>> selectRmPlatformSel() throws RollbackableBizException;
public void deleteRmPlatform(String string) throws RollbackableBizException;
public List<RmHostResPo> selectRmHostResByPlatformId(String id) throws RollbackableBizException;
public List<RmCdpPo> selectRmCdpByPlatformId(String id) throws RollbackableBizException;
public List<RmNwCclassPo> selectRmNwCclassByPlatformId(String id) throws RollbackableBizException;
public List<CloudServicePo> selectRmCloudServiceByPlatformId(String id) throws RollbackableBizException;
public RmPlatformPo selectRmPlatformForTrim(String platformId) throws RollbackableBizException;
public void savaVirtualType(RmVirtualTypePo rmVirtualTypePo) throws RollbackableBizException;
public RmVirtualTypePo selectRmVirtualTypeForTrim(String virtualTypeCode) throws RollbackableBizException;
public RmVirtualTypePo selectRmVirtualType(String virtualTypeId) throws RollbackableBizException;
public List<Map<String, Object>> selectRmVirtualTypeSel(String platformId) throws RollbackableBizException;
public void updateRmVirtualType(RmVirtualTypePo rmVirtualTypePo) throws RollbackableBizException;
//public List<RmHostResPo> selectRmHostResByvirtualTypeId(String virtualTypeId) throws RollbackableBizException;
public List<RmCdpPo> selectRmCdpByvirtualTypeId(String virtualTypeId) throws RollbackableBizException;
public List<CloudServicePo> selectRmCloudServiceByvirtualTypeId(String virtualTypeId) throws RollbackableBizException;
public void deleteVirtualType(String virtualTypeId) throws RollbackableBizException;
public List<RmVirtualTypePo> selectRmVirtualTypeByPlatformId(String id) throws RollbackableBizException;
public RmPlatformPo selectRmPlatformNameForTrim(String platformName) throws RollbackableBizException;
}
|
//Считывает адрес файла и выводит его содержимое на экран
package Tasks;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Task56 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
FileInputStream inStream = new FileInputStream(reader.readLine());
Scanner scanner = new Scanner(inStream);
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine()).append("\n");
}
System.out.print(builder.toString());
scanner.close();
reader.close();
}
}
|
package cn.bjfu.beans;
import lombok.*;
/**
* Created by jxy on 2021/4/22 0022 10:08
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
public class MarketingUserBehavior {
private Long userId;
private String behavior;
private String channel;
private Long timeStamp;
}
|
/*
* 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 File;
import Module.SessionLogin;
import Module.koneksi;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
*
* @author LENOVO
*/
public class FrmLogin extends javax.swing.JFrame {
SessionLogin sesi = new SessionLogin();
public Timer time;
int loading;
public final static int FOUR_SECONDS = 10;
/**
* Creates new form FrmLogin
*/
public FrmLogin() {
initComponents();
pb.setVisible(false);
}
class TimerListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
loading++; //Mulai Progress Bar
jButton2.requestFocusInWindow();
pb.setValue(loading);
pb.setString("Logging In");
if (loading == 1) {
}
if (loading >= 37) {
if (loading == 37) {
}
pb.setForeground(Color.YELLOW);
pb.setString("Authenticating");
}
if (loading >= 75) {
if (loading == 75) {
}
pb.setForeground(Color.GREEN);
pb.setString("Login Berhasil");
}
if (loading == 131) {
time.stop(); //Berhenti Progress Bar
dispose();
MainMenu a = new MainMenu();
a.setVisible(true);
}
}
}
private void login(){
String username = txtuser.getText();
String password = txtpass.getText();
try{
String SQL = "select id,nama,username,level,status,alamat,password,telepon from user where username='"+username+"' and "
+ "password=sha1('"+password+"')";
ResultSet rs = koneksi.ExecuteQuery(SQL);
if(rs.next()){
if(rs.getString(5).equals("1")){
pb.setVisible(true);
pb.setStringPainted(true);
pb.setFont(new Font("sans serif",Font.BOLD,16));
loading = -1;
time = new Timer(FOUR_SECONDS, new TimerListener());
time.start();
sesi.setNama(rs.getString(2));
sesi.setUsername(rs.getString(3));
sesi.setLevel(rs.getString(4));
sesi.setIdUser(rs.getString(1));
// this.dispose();
}else{
JOptionPane.showMessageDialog(rootPane, "Akun anda dinon-aktifkan/nHubungi admin untuk mengaktifkan");
}
}else{
JOptionPane.showMessageDialog(rootPane, "Mohon periksa kembali username dan password anda!");
}
}catch(Exception e){
System.out.println(e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
txtpass = new javax.swing.JPasswordField();
txtuser = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
btnLogin = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
pb = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(0, 153, 153));
jPanel3.setBackground(new java.awt.Color(0, 102, 102));
jPanel2.setBackground(new java.awt.Color(0, 153, 153));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/icons8_Close_Window_32px.png"))); // NOI18N
jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel3MouseClicked(evt);
}
});
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/listrik.png"))); // NOI18N
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("System Login");
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Aplikasi Pembayaran Listrik");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addGap(12, 12, 12))
.addComponent(jLabel4)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(0, 102, 102));
jPanel5.setBackground(new java.awt.Color(0, 153, 153));
txtpass.setBackground(new java.awt.Color(0, 153, 153));
txtpass.setForeground(new java.awt.Color(255, 255, 255));
txtpass.setBorder(null);
txtpass.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtpassActionPerformed(evt);
}
});
txtuser.setBackground(new java.awt.Color(0, 153, 153));
txtuser.setForeground(new java.awt.Color(255, 255, 255));
txtuser.setBorder(null);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Username :");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Password :");
btnLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/16/logout.png"))); // NOI18N
btnLogin.setText("Masuk");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/16/close.png"))); // NOI18N
jButton2.setText("Batal");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jSeparator1.setBackground(new java.awt.Color(0, 102, 102));
jSeparator1.setForeground(new java.awt.Color(0, 0, 0));
jSeparator2.setBackground(new java.awt.Color(0, 102, 102));
jSeparator2.setForeground(new java.awt.Color(0, 0, 0));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(btnLogin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))
.addComponent(txtpass)
.addComponent(txtuser)
.addComponent(jSeparator1))
.addContainerGap(55, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtuser, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtpass, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel2)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLogin)
.addComponent(jButton2))
.addGap(19, 19, 19))
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(23, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
// TODO add your handling code here:
if(JOptionPane.showConfirmDialog(rootPane, "Apakah anda akan keluar?","Informasi",JOptionPane.CANCEL_OPTION,
JOptionPane.OK_OPTION)==JOptionPane.YES_OPTION){
System.exit(0);
}
}//GEN-LAST:event_jLabel3MouseClicked
private void txtpassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtpassActionPerformed
// TODO add your handling code here:
login();
}//GEN-LAST:event_txtpassActionPerformed
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
// TODO add your handling code here:
login();
}//GEN-LAST:event_btnLoginActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
if(JOptionPane.showConfirmDialog(rootPane, "Apakah anda akan membatalkannya?","Informasi",JOptionPane.CANCEL_OPTION,
JOptionPane.OK_OPTION)==JOptionPane.YES_OPTION){
System.exit(0);
}
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmLogin().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnLogin;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JProgressBar pb;
private javax.swing.JPasswordField txtpass;
private javax.swing.JTextField txtuser;
// End of variables declaration//GEN-END:variables
}
|
package com.ngocdt.tttn.service.impl;
import com.ngocdt.tttn.dto.DiscountDTO;
import com.ngocdt.tttn.dto.DiscountDetailDTO;
import com.ngocdt.tttn.dto.ProductDTO;
import com.ngocdt.tttn.entity.Discount;
import com.ngocdt.tttn.entity.DiscountDetail;
import com.ngocdt.tttn.entity.DiscountDetailKey;
import com.ngocdt.tttn.entity.Product;
import com.ngocdt.tttn.exception.BadRequestException;
import com.ngocdt.tttn.exception.NotFoundException;
import com.ngocdt.tttn.repository.AccountRepository;
import com.ngocdt.tttn.repository.DiscountDetailRepository;
import com.ngocdt.tttn.repository.DiscountRepository;
import com.ngocdt.tttn.repository.ProductRepository;
import com.ngocdt.tttn.service.DiscountService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.readers.operation.ResponseMessagesReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@Service
public class DiscountServiceImpl implements DiscountService {
private final DiscountRepository discountRepo;
private final DiscountDetailRepository discountDetailRepo;
private final AccountRepository accountRepo;
private final ProductRepository productRepo;
@Override
public List<DiscountDTO> showAll() {
return discountRepo.findAll().stream().map(DiscountDTO::toDTO).collect(Collectors.toList());
}
@Override
public DiscountDTO showOne(Integer id) {
return DiscountDTO.toDTO(discountRepo.findById(id).orElse(null));
}
@Override
public DiscountDTO update(DiscountDTO dto) {
if (!discountRepo.existsById(dto.getDiscountID()))
throw new BadRequestException("Bad request.");
Discount discount = discountRepo.findById(dto.getDiscountID())
.orElseThrow(() -> new NotFoundException("Discount not found."));
if(dto.getStartTime().compareTo(dto.getEndTime()) >0)
throw new BadRequestException("End time must be greater than start time.");
List<Integer> ids = new ArrayList<>();
ids.add(dto.getDiscountID());
List<Discount> discounts = discountRepo.findAllByDiscountIDNotIn(ids);
for (Discount d : discounts) {
if ((dto.getStartTime().compareTo(d.getStartTime()) >=0 && dto.getStartTime().compareTo(d.getEndTime()) <=0) ||
(dto.getStartTime().compareTo(d.getStartTime()) <=0 && dto.getEndTime().compareTo(d.getStartTime()) >=0)) {
for (DiscountDetail p : discount.getDiscountDetails()) {
DiscountDetail discountDetail = discountDetailRepo
.findByProductIDAndTime(p.getProductID(), dto.getStartTime()).orElse(null);
if (discountDetail != null)
throw new BadRequestException("Can not update discount at now.");
}
}
}
discount.setName(dto.getName());
discount.setEndTime(dto.getEndTime());
discount.setStartTime(dto.getStartTime());
return DiscountDTO.toDTO(discountRepo.save(discount));
}
@Override
@Transactional
public DiscountDTO create(DiscountDTO dto) {
Discount discount = new Discount();
discount.setEndTime(dto.getEndTime());
discount.setStartTime(dto.getStartTime());
discount.setName(dto.getName());
discount.setDiscountID(0);
;
return DiscountDTO.toDTO(discountRepo.save(discount));
}
@Override
public void delete(Integer id) {
if (!discountRepo.existsById(id))
throw new BadRequestException("Bad request.");
discountRepo.deleteById(id);
}
@Override
public DiscountDetailDTO createDetail(DiscountDetailDTO dto) {
Product pp = productRepo.findById(dto.getProductID()).orElse(null);
if (pp == null)
throw new BadRequestException("Product not found.");
if (dto.getDiscountPercent() <= 0)
throw new BadRequestException("Discount percent must be greater than 0.");
List<Product> products = productRepo.findAllByDiscount();
Discount d = discountRepo.findById(dto.getDiscountID()).orElseThrow(() -> new NotFoundException("Discount not found."));
for (Product p : products) {
if (p.getProductID() == dto.getProductID()) {
DiscountDetail discountDetail = discountDetailRepo
.findByProductIDAndTime(dto.getProductID(), d.getStartTime()).orElse(null);
if (discountDetail != null)
throw new BadRequestException("Can not create discount at now.");
}
}
DiscountDetail dd = DiscountDetailDTO.toEntity(dto);
dd.setProduct(pp);
return DiscountDetailDTO.toDTO(discountDetailRepo.save(dd));
}
@Override
public DiscountDetailDTO updateDetail(DiscountDetailDTO dto) {
DiscountDetailKey key = new DiscountDetailKey();
key.setDiscountID(dto.getDiscountID());
key.setProductID(dto.getProductID());
DiscountDetail dd = discountDetailRepo.findById(key).orElse(null);
if (dd == null)
throw new BadRequestException("Discount detail not found.");
if (dto.getDiscountPercent() == 0) {
discountDetailRepo.delete(dd);
return null;
}
dd.setDiscountPercent(dto.getDiscountPercent());
return DiscountDetailDTO.toDTO(discountDetailRepo.save(dd));
}
}
|
package com.maliang.core.expression;
import com.mongodb.BasicDBObject;
public interface Expression {
public BasicDBObject generateQuery();
}
|
package com.minipig.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexCon {
private static Logger logger = Logger.getLogger(IndexCon.class);
@RequestMapping("/index")
public String index() {
logger.info("this is index");
return "index";
}
public String weChat() {
logger.info(" The request message from webChat ");
return "The message from miniPig";
}
}
|
package com.aliam3.polyvilleactive.model.user;
import com.aliam3.polyvilleactive.model.gamification.Badge;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.minidev.json.annotate.JsonIgnore;
import java.util.ArrayList;
import java.util.List;
/**
* Classe qui represente le profil d'un utilisateur de l'application.
* On peut retrouver la progression actuelle(gamification) de cette personne ainsi que d'autres informations
* @author vivian
*
*/
public class User {
@JsonProperty("id")
private long id;
@JsonIgnore
private UserRole role;
/**
* le score global, utilise pour debloquer les badges
*/
@JsonProperty("score")
private int score;
/**
* utilise pour les reductions et autres
*/
@JsonProperty("points")
private int points;
@JsonProperty("badges")
List<Badge> badges;
@JsonProperty("username")
private String username;
@JsonProperty("password")
private String password;
@JsonProperty("email")
private String email;
public User(int id, String username, String password, String email){
this.id=id;
this.username=username;
this.password=password;
this.email=email;
this.role=UserRole.CITOYEN;
this.score=0;
this.points=0;
this.badges= new ArrayList<>();
}
public User(){
this.score=0;
this.points=0;
this.badges= new ArrayList<>();
}
@Override
public String toString() {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "";
}
@JsonIgnore
public boolean isNameEmpty(){
return username.isEmpty();
}
@JsonIgnore
public boolean isPasswordEmpty(){
return password.isEmpty();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPoints() {
return points;
}
public void addBadge(Badge badge){
if(badge!=null){
this.badges.add(badge);
}
}
public int getScore() {
return score;
}
public List<Badge> getBadges() {
return badges;
}
/**
* le nombre que l'on veut ajouter au score actuel
* @param number
*/
public void addScore(int number) {
score+=number;
updatePoint(number);
}
public void setBadges(List<Badge> badges) {
System.out.println(badges);
this.badges = badges;
}
/**
* le nombre de point que l'on veut enlever ou ajouter
* @param number
*/
public void updatePoint(int number) {
points+=number;
}
}
|
package state3;
/**
* Main
* @author Ali
*/
public class StateDesignPattern {
public static void main(String[] args) {
ProjectCurrentState chain = new ProjectCurrentState();
/**
* Afiseaza starea curenta
*/
chain.pull();
/**
* Schimbarea starii
*/
chain.set_state(new DesignStage());
/**
* Afiseaza starea curenta
*/
chain.pull();
}
}
|
package org.izv.pgc.firebaserealtimedatabase.connectivity;
public interface ResponseConnectivityListener {
void onResponse(boolean resultado);
}
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Task3 {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
String temp;
try {
FileReader fileReader = new FileReader("src/task3/main/resources/task3.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((temp = bufferedReader.readLine()) != null) {
strings.add(temp);
}
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer sentences = new StringBuffer();
for (int i = 0; i < strings.size(); i++) {
sentences.append(strings.get(i));
}
Pattern pattern = Pattern.compile("[A-ZА-Я][^.?!]+[.?!]");
Matcher matcher = pattern.matcher(sentences);
StringBuffer stringBuffer = new StringBuffer();
while (matcher.find()) {
stringBuffer.append(matcher.group() + " ");
}
System.out.println(stringBuffer.reverse());
}
}
|
package com.imdongh.mvpdemo01.base;
public interface CallBack<T> {
/**
* 数据请求成功
* @param data
*/
void onSucc(T data);
/**
* 使用网络API接口请求方式时,虽然请求成功但由于 message 的原因无法正常返回数据
* @param message
*/
void onFail(String message);
/**
* 请求数据失败,指在请求网络API时,出现网络连接,缺少权限,内存泄漏等问题导致无法连接到请求数据源
* @param error
*/
void onError(String error);
/**
* 当请求数据结束时,无论请求是成功,失败还是抛出异常都会执行此方法给用户处理
* 通常做网络请求时可以在此处隐藏"正在加载"等显示控件
*/
void onComplete();
}
|
package com.alibaba.druid;
import com.alibaba.druid.util.FnvHash;
public enum DbType {
other(1 << 0),
jtds(1 << 1),
hsql(1 << 2),
db2(1 << 3),
postgresql(1 << 4),
sqlserver(1 << 5),
oracle(1 << 6),
mysql(1 << 7),
mariadb(1 << 8),
derby(1 << 9),
hive(1 << 10),
h2(1 << 11),
dm(1 << 12), // dm.jdbc.driver.DmDriver
kingbase(1 << 13),
gbase(1 << 14),
oceanbase(1 << 15),
informix(1 << 16),
odps(1 << 17),
teradata(1 << 18),
phoenix(1 << 19),
edb(1 << 20),
kylin(1 << 21), // org.apache.kylin.jdbc.Driver
sqlite(1 << 22),
ads(1 << 23),
presto(1 << 24),
elastic_search(1 << 25), // com.alibaba.xdriver.elastic.jdbc.ElasticDriver
hbase(1 << 26),
drds(1 << 27),
clickhouse(1 << 28),
blink(1 << 29),
antspark(1 << 30),
oceanbase_oracle(1 << 31),
polardb(1L << 32),
ali_oracle(1L << 33),
mock(1L << 34),
sybase(1L << 35),
highgo(1L << 36),
/**
* 非常成熟的开源mpp数据库
*/
greenplum(1L << 37),
/**
* 华为的mpp数据库
*/
gaussdb(1L << 38),
trino(1L << 39),
oscar(1L << 40),
tidb(1L << 41),
tydb(1L << 42),
ingres(0),
cloudscape(0),
timesten(0),
as400(0),
sapdb(0),
kdb(0),
log4jdbc(0),
xugu(0),
firebirdsql(0),
JSQLConnect(0),
JTurbo(0),
interbase(0),
pointbase(0),
edbc(0),
mimer(0);
public final long mask;
public final long hashCode64;
private DbType(long mask) {
this.mask = mask;
this.hashCode64 = FnvHash.hashCode64(name());
}
public static long of(DbType... types) {
long value = 0;
for (DbType type : types) {
value |= type.mask;
}
return value;
}
public static DbType of(String name) {
if (name == null || name.isEmpty()) {
return null;
}
if ("aliyun_ads".equalsIgnoreCase(name)) {
return ads;
}
try {
return valueOf(name);
} catch (Exception e) {
return null;
}
}
public final boolean equals(String other) {
return this == of(other);
}
}
|
package three_CustomEvent_using_Asynchronous;
import org.springframework.context.ApplicationEvent;
public class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source){
super(source);
System.out.println("Custom event contructor is called");
}
@Override
public String toString() {
return "employee event occured";
}
}
|
package org.didierdominguez.controller;
import org.didierdominguez.bean.Account;
import org.didierdominguez.bean.Customer;
import org.didierdominguez.bean.Deposit;
import org.didierdominguez.bean.MonetaryAccount;
import org.didierdominguez.util.Verifications;
public class ControllerDeposit {
private static ControllerDeposit instance;
private Deposit[] deposits = new Deposit[100];
private int id;
private ControllerDeposit(){
id = 0;
}
public static ControllerDeposit getInstance() {
if (instance == null) {
instance = new ControllerDeposit();
}
return instance;
}
public void createDeposit(String noAccount, Double amount, Object depositType, Customer customer) {
for (int i = 0; i < deposits.length; i++) {
if (deposits[i] == null) {
id++;
Object account;
if (ControllerAccount.getInstance().searchAccount(noAccount) != null) {
account = ControllerAccount.getInstance().searchAccount(noAccount);
ControllerAccount.getInstance().updateAccount(((Account) account).getId(), amount);
} else {
account = ControllerMonetaryAccount.getInstance().searchAccount(noAccount);
ControllerMonetaryAccount.getInstance().updateAccount(((MonetaryAccount) account).getId(), amount, false);
}
deposits[i] = new Deposit(id, account, amount, Verifications.getInstance().getDate(), depositType);
ControllerCustomer.getInstance().updateTransactionsCarriedOut(customer.getId());
ControllerCustomer.getInstance().updateBalance(customer.getId(), amount);
System.out.println("Deposit added successfully");
break;
}
}
}
}
|
package kr.co.wisenut.editor.service;
import kr.co.wisenut.editor.model.FormVO;
public interface EditorService {
public int getMaxRuntime() throws Exception;
public int saveSceneInfo(FormVO vo) throws Exception;
public int deleteSceneInfo(FormVO vo) throws Exception;
public int getNewScnId() throws Exception;
public String getVideoListAsJson(FormVO vo) throws Exception;
public String getVideoFilePath(FormVO vo) throws Exception;
public int scenePersonMapping(FormVO vo) throws Exception;
public int deletePersonFromMapping(FormVO vo) throws Exception;
}
|
package com.twins.designpattern.singleton.hungry;
/**
* Created on 2019/3/10
*/
public class HungrySingletonTest {
public static void main(String[] args) {
Thread t1 = new Thread(new ExecutorThread());
Thread t2 = new Thread(new ExecutorThread());
t1.start();
t2.start();
System.out.println("Executor End");
}
static class ExecutorThread implements Runnable {
public void run() {
HungrySingleton instance = HungrySingleton.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
}
}
}
|
package com.sirma.itt.javacourse.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.sirma.itt.javacourse.MathUtil;
/**
* @author simeon
*/
public class TestMathUtil {
/**
* Test method for
* {@link com.sirma.itt.javacourse.MathUtil#generateRandomNumberWithRange(int, int)}.
*/
@Test
public void testGenerateRandomNumberWithRange() {
assertEquals(5, MathUtil.generateRandomNumberWithRange(5, 5));
}
/**
* Test the get getGreatestCommonDivisor of MathUtil class.
*/
@Test
public void getGreatestCommonDivisor() {
assertEquals(5, com.sirma.itt.javacourse.MathUtil.getGreatestCommonDivisor(10, 5));
}
/**
* Test the getLeastCommonDenominator of MathUtil class.
*/
@Test
public void getLeastCommonDenominator() {
assertEquals(21, com.sirma.itt.javacourse.MathUtil.getLeastCommonDenominator(3, 7));
}
}
|
package se.kth.iv1350.amazingpos.integration;
import se.kth.iv1350.amazingpos.model.*;
import java.util.ArrayList;
import java.util.List;
/**
* This dummy implementation of external inventory system.
*
* Contains all calls to the data store with performed sales;
*/
public class InventorySystem {
private List<ItemDescription> inventoryItems = new ArrayList<>();
/**
* Creates a new instance of a fake inventory system that contains
* available items to sell.
*/
InventorySystem(){
addItems();
}
/**
* Updates the quantity of available items in the inventory.
*
* @param sale Will be used to get quantity of sold items to
* update inventory
*/
public void updateInventory(Sale sale){
List<ItemDescription> soldItems = sale.getSortedListOfSoldItems();
for (ItemDescription soldItem: soldItems) {
for (ItemDescription inventoryItem : inventoryItems)
if (inventoryItem.getItemId().equals(soldItem.getItemId()));{
decreaseQuantityOfItem(soldItem);
soldItem.setQuantity(0);
}
}
}
/**
* Decreases the quantity of one specific item that
* is available in the inventory.
*
* @param soldItem representing one specific sold
* item that must be subtracted from inventory.
*/
private void decreaseQuantityOfItem(ItemDescription soldItem){
for (ItemDescription inventoryItem : inventoryItems)
if (inventoryItem.getItemId().equals(soldItem.getItemId()))
inventoryItem.setQuantity(decreaseQuantity(inventoryItem, soldItem));
}
/**
* Will perform the decreasing of quantity for available tem in inventory
*
* @param inventoryItem Will be decreased by sold item's quantity
* @param soldItem Will be subtracted from inventory's item
* @return The difference of available quantity after subtraction operation
*/
private int decreaseQuantity(ItemDescription inventoryItem, ItemDescription soldItem ){
if ((inventoryItem.getQuantity()-soldItem.getQuantity()) < 0 )
return 0;
return(inventoryItem.getQuantity()-soldItem.getQuantity());
}
/**
* Simulates available items in inventory that
*/
private void addItems() {
inventoryItems.add(new ItemDescription("apple", 1000, 1, 1 ));
inventoryItems.add(new ItemDescription("milk", 1000, 1, 1 ));
inventoryItems.add(new ItemDescription("juice", 1000, 1, 1 ));
inventoryItems.add(new ItemDescription("banana", 1000, 1, 1 ));
inventoryItems.add(new ItemDescription("Bread", 1000, 1, 1 ));
inventoryItems.add(new ItemDescription("chocolate", 1000, 1, 1));
}
public List<ItemDescription> getInventoryItems(){
return this.inventoryItems;
}
}
|
package net.skoumal.forceupdate.provider;
import android.app.Application;
/**
* Created by gingo on 26.9.2016.
*/
public class CarretoVersionProvider extends JsonHttpVersionProvider {
private static final String URL_ADDRESS = "http://carreto.pt/tools/android-store-version/?package=";
public CarretoVersionProvider(Application gApplication) {
super(URL_ADDRESS + gApplication.getApplicationContext().getPackageName(),
"version", "last_version_description");
}
}
|
package utils;
public class Utils {
/*
* Gets the current time system time
*/
public long time() {
return System.currentTimeMillis();
}
}
|
package com.spring.models;
import com.spring.models.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import org.modelmapper.ModelMapper;
public class UserDTO {
private String username;
private String email;
private String token;
private List<Roles> roles;
public static UserDTO create(User user, String token) {
ModelMapper modelMapper = new ModelMapper();
UserDTO dto = modelMapper.map(user, UserDTO.class);
dto.token = token;
return dto;
}
public String toJson() throws JsonProcessingException {
ObjectMapper m = new ObjectMapper();
return m.writeValueAsString(this);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
}
|
package com.sciencepie.mm.activity;
import com.sciencepie.mm.R;
import com.sciencepie.mm.fragment.CommonFragmentPagerAdapter;
import com.sciencepie.mm.fragment.TestFragment;
import com.sciencepie.mm.listener.CommonCallback;
import com.sciencepie.mm.view.MyScrollHeaderView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
public class InformationActivity extends FragmentActivity{
private MyScrollHeaderView mScrollHeader;
private ViewPager mViewPager;
private FragmentManager mFm;
private CommonFragmentPagerAdapter mPagerAdapter;
@Override
public void onCreate( Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fragment_information);
mScrollHeader = (MyScrollHeaderView) findViewById(R.id.information_scroll_header);
mScrollHeader.addScrollHeaderItem(this,getResources().getStringArray(R.array.news_header_strings));
mViewPager = (ViewPager) findViewById(R.id.fragment_viewpager);
mFm = this.getSupportFragmentManager();
TestFragment test1 = new TestFragment();
TestFragment test2 = new TestFragment();
TestFragment test3 = new TestFragment();
TestFragment test4 = new TestFragment();
TestFragment test5 = new TestFragment();
mPagerAdapter = new CommonFragmentPagerAdapter (mFm,new Fragment[]{test1,test2,test3,test4,test5});
mViewPager.setAdapter(mPagerAdapter);
mViewPager.setCurrentItem(0);
mScrollHeader.setMyScrollCallback(new CommonCallback(){
@Override
public void callback(Object obj) {
// TODO Auto-generated method stub
int id = (Integer) obj;
mViewPager.setCurrentItem(id);
}
});
mScrollHeader.setCurrentTab(0);
mViewPager.setOnPageChangeListener(new OnPageChangeListener(){
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
mScrollHeader.setCurrentTab(position);
}
});
}
}
|
/**
* Diese Datei gehört zum Android/Java Framework zur Veranstaltung "Computergrafik für
* Augmented Reality" von Prof. Dr. Philipp Jenke an der Hochschule für Angewandte
* Wissenschaften (HAW) Hamburg. Weder Teile der Software noch das Framework als Ganzes dürfen
* ohne die Einwilligung von Philipp Jenke außerhalb von Forschungs- und Lehrprojekten an der HAW
* Hamburg verwendet werden.
* <p>
* This file is part of the Android/Java framework for the course "Computer graphics for augmented
* reality" by Prof. Dr. Philipp Jenke at the University of Applied (UAS) Sciences Hamburg. Neither
* parts of the framework nor the complete framework may be used outside of research or student
* projects at the UAS Hamburg.
*/
package edu.hawhamburg.shared.misc;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import edu.hawhamburg.shared.datastructures.mesh.ITriangleMesh;
import edu.hawhamburg.shared.datastructures.mesh.ObjReader;
import edu.hawhamburg.shared.datastructures.mesh.TriangleMeshTools;
import edu.hawhamburg.shared.datastructures.particle.Particle;
import edu.hawhamburg.shared.math.CollisionHelper;
import edu.hawhamburg.shared.math.Vector;
import edu.hawhamburg.shared.scenegraph.INode;
import edu.hawhamburg.shared.scenegraph.InnerNode;
import edu.hawhamburg.shared.scenegraph.ScaleNode;
import edu.hawhamburg.shared.scenegraph.SphereNode;
import edu.hawhamburg.shared.scenegraph.TransformationNode;
import edu.hawhamburg.shared.scenegraph.TranslationNode;
import edu.hawhamburg.shared.scenegraph.TriangleMeshNode;
import platform.vuforia.VuforiaMarkerNode;
import static edu.hawhamburg.shared.scenegraph.TriangleMeshNode.RenderNormals.PER_TRIANGLE_NORMAL;
public class CannonDefaultScene extends Scene {
private static final double TICK_MOVE = 0.01;
private static final double PROJECTILE_RADIUS = 0.05;
private TriangleMeshNode target;
private ScaleNode targetScale;
private TriangleMeshNode cannon;
private VuforiaMarkerNode cannonMarker;
private List<Projectile> projectiles = Collections.synchronizedList(new ArrayList<Projectile>());
public CannonDefaultScene() {
super(100, INode.RenderMode.REGULAR);
}
@Override
public void onSetup(InnerNode rootNode) {
try {
Button button = new Button("kanone_abfeuern.png",
-0.7, -0.7, 0.2, new ButtonHandler() {
@Override
public void handle() {
shoot();
}
});
addButton(button);
// Cannon
cannonMarker = new VuforiaMarkerNode("elphi");
rootNode.addChild(cannonMarker);
ObjReader reader = new ObjReader();
List<ITriangleMesh> triangleMeshes = reader.read("meshes/cannon.obj");
TriangleMeshTools.fitToUnitBox(triangleMeshes);
TriangleMeshTools.placeOnXZPlane(triangleMeshes);
ITriangleMesh cannonMesh = TriangleMeshTools.unite(triangleMeshes);
cannon = new TriangleMeshNode(cannonMesh);
cannon.setRenderNormals(PER_TRIANGLE_NORMAL);
cannonMarker.addChild(cannon);
// Target
VuforiaMarkerNode targetMarker = new VuforiaMarkerNode("campus");
rootNode.addChild(targetMarker);
triangleMeshes = reader.read("meshes/tree01.obj");
TriangleMeshTools.fitToUnitBox(triangleMeshes);
TriangleMeshTools.placeOnXZPlane(triangleMeshes);
ITriangleMesh targetMesh = TriangleMeshTools.unite(triangleMeshes);
target = new TriangleMeshNode(targetMesh);
target.setRenderNormals(PER_TRIANGLE_NORMAL);
targetScale = new ScaleNode(1);
targetScale.addChild(target);
targetMarker.addChild(targetScale);
} catch (Throwable t) {
Log.e("DEBUG", "" + t.getMessage(), t);
}
}
@Override
public void onTimerTick(int counter) {
try {
boolean hit = false;
for (int i = projectiles.size() - 1; i >= 0; i--) {
Projectile p = projectiles.get(i);
p.translationNode.setTranslation(p.particle.update(TICK_MOVE));
if (CollisionHelper.collide(p.bullet.getBoundingBox(), p.bullet.getTransformation(), target.getBoundingBox(), target.getTransformation())) {
hit = true;
projectiles.remove(i);
cannonMarker.removeChild(p.translationNode);
} else if (p.t > 1000) {
projectiles.remove(i);
cannonMarker.removeChild(p.translationNode);
} else {
p.t += TICK_MOVE;
}
}
if (hit) {
targetScale.setScale(0.3);
} else {
targetScale.setScale(1.0);
}
} catch (Throwable t) {
Log.e("DEBUG", "" + t.getMessage(), t);
}
}
@Override
public void onSceneRedraw() {
}
private void shoot() {
try {
Vector initialPosition = cannon.getBoundingBox().getCenter()
.add(new Vector(0, -0.06, -0.2));
Vector initialVelocity = new Vector(0, 1, -5);
Particle particle = new Particle(initialPosition, initialVelocity, 1);
SphereNode bullet = new SphereNode(PROJECTILE_RADIUS, 100);
TranslationNode initialTranslation = new TranslationNode(initialPosition);
initialTranslation.addChild(bullet);
TranslationNode bulletTranslation = new TranslationNode(initialPosition);
bulletTranslation.addChild(initialTranslation);
cannonMarker.addChild(bulletTranslation);
projectiles.add(new Projectile(particle, bulletTranslation, bullet));
} catch (Throwable t) {
Log.e("DEBUG", "" + t.getMessage(), t);
}
}
private static class Projectile {
private final Particle particle;
private final TranslationNode translationNode;
private final SphereNode bullet;
private double t = 0;
private Projectile(Particle particle, TranslationNode translationNode, SphereNode bullet) {
this.particle = particle;
this.translationNode = translationNode;
this.bullet = bullet;
}
}
}
|
package com.example.demo.adapter;
import java.util.List;
import java.util.ArrayList;
public class DispatcherServlet {
public static List<HandlerAdapter> handlerAdapters = new ArrayList<HandlerAdapter>();
//objlkdfla fldfjadfd33eearfafafafafdfssssSS
public DispatcherServlet() {
handlerAdapters.add(new AnnotationHandlerAdapter());
handlerAdapters.add(new SimpleHandlerAdapter());
handlerAdapters.add(new HttpHandlerAdapter());
}
public void doDispatch() {
//HttpController controller = new HttpController();
SimpleController controller=new SimpleController();
HandlerAdapter adapter=getHandler(controller);
adapter.handle(controller);
}
public HandlerAdapter getHandler(Controller controller) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(controller)) {
return adapter;
}
}
return null;
}
public static void main(String[] args) {
new DispatcherServlet().doDispatch();
}
}
|
package de.pqrent.jpa.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
class ItemCount {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private double amount;
@ManyToOne
private Inventory inventory;
@ManyToOne
private Item item;
ItemCount() {
}
ItemCount(Inventory inventory, Item item) {
this.inventory = inventory;
this.item = item;
item.addItemCount(this);
inventory.addItemCount(this);
inventory.addItemCount(this);
}
public void increaseAmount(double amount) {
this.amount += amount;
}
public Inventory getInventory() {
return inventory;
}
void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public double getAmount() {
return amount;
}
public Item getItem() {
return item;
}
void setItem(Item item) {
this.item = item;
}
void setAmount(double amount) {
this.amount = amount;
}
}
|
package ejercicio08;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Javier
*/
public class Ejercicio08 {
public static void rellenar(ArrayList <Integer> numeros) {
Scanner entrada = new Scanner(System.in);
for (int i = 0; i < 8; i++) {
System.out.print("Introduzca el valor de la posición " +i+ ": ");
numeros.add(entrada.nextInt());
}
}
public static void mostrar(ArrayList <Integer> numeros) {
for (int i = 0; i < numeros.size(); i++) {
System.out.print(numeros.get(i) + " ");
}
}
public static int mayorPar(ArrayList <Integer> numeros) {
int mayorPar = numeros.get(0);
for (int i = 0; i < numeros.size(); i++) {
if(numeros.get(i) > numeros.get(mayorPar) & numeros.get(i) %2 == 0) mayorPar = i;
}
return mayorPar;
}
public static int menorImpar(ArrayList <Integer> numeros) {
int menorImpar = numeros.get(0);
for (int i = 0; i < numeros.size(); i++) {
if(numeros.get(i) < numeros.get(menorImpar) & numeros.get(i) %2 != 0) menorImpar = i;
}
return menorImpar;
}
public static void intercambiar(ArrayList <Integer> numeros, int mayorPar, int menorImpar) {
int buffer = numeros.get(mayorPar);
numeros.set(mayorPar, menorImpar);
numeros.set(menorImpar, buffer);
}
public static void main(String[] args) {
ArrayList <Integer> numeros = new ArrayList <Integer>();
rellenar(numeros);
int mayorPar = mayorPar(numeros);
System.out.println("Mayor número par: " +numeros.get(mayorPar));
int menorImpar = menorImpar(numeros);
System.out.println("Menor número impar: " +numeros.get(menorImpar));
intercambiar(numeros, mayorPar, menorImpar);
mostrar(numeros);
}
}
|
package com.evature.evasdk.evaapis.crossplatform.flow;
import com.evature.evasdk.evaapis.crossplatform.EvaLocation;
import com.evature.evasdk.util.DLog;
import java.io.Serializable;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
public class FlightFlowElement extends FlowElement implements Serializable {
private static final String TAG = "FlightFlowElement";
public String RoundTripSayit;
public int ActionIndex;
public FlightFlowElement(JSONObject jFlowElement, List<String> parseErrors,
EvaLocation[] locations) {
super(jFlowElement, parseErrors, locations);
if (jFlowElement.has("ReturnTrip")) {
try {
JSONObject jElement = jFlowElement.getJSONObject("ReturnTrip");
RoundTripSayit = jElement.getString("SayIt");
ActionIndex = jElement.getInt("ActionIndex");
} catch (JSONException e) {
DLog.e(TAG, "Bad EVA reply! exception processing flight flow Element", e);
parseErrors.add("Exception during parsing: "+e.getMessage());
}
}
}
public String getSayIt() {
if (RoundTripSayit != null) {
return RoundTripSayit;
}
return super.getSayIt();
}
}
|
public class solve {
final static private String GOAL_STATE = "012345678";
public static void main(String[] args) {
String initailState = "103245678";
long startTime = System.currentTimeMillis();
SearchTree search = new SearchTree(new Node(initailState), GOAL_STATE);
// search.aStar(1);
search.aStar(2);
// search.BFS();
// search.DFS();
long finishTime = System.currentTimeMillis();
long totalTime = finishTime - startTime;
System.out.println("Running time :" + totalTime + " msec");
}
}
|
package no.nav.vedtak.felles.integrasjon.person;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
import java.net.URI;
import java.util.List;
import com.kobylynskyi.graphql.codegen.model.graphql.GraphQLError;
import no.nav.vedtak.exception.IntegrasjonException;
public class PdlException extends IntegrasjonException {
private final int status;
private final URI uri;
private final PDLExceptionExtension extension;
public PdlException(String kode, List<GraphQLError> errors, PDLExceptionExtension extension, int status, URI uri) {
super(kode, format("Feil %s ved GraphQL oppslag mot %s", errors.stream().map(GraphQLError::getMessage).collect(joining(",")), uri));
this.extension = extension;
this.status = status;
this.uri = uri;
}
public PDLExceptionDetails getDetails() {
return extension.details();
}
public String getCode() {
return extension.code();
}
public int getStatus() {
return status;
}
@Override
public String toString() {
return getClass().getSimpleName() + " [status=" + status + ", details=" + getDetails() + "uri=" + uri + "]";
}
}
|
package com.example.rihaf.diabetesdietexpert;
/**
* Created by rihaf on 12/15/2016.
*/
public class DataProvider {
private Double tb;
private Double bb;
private Double imt;
private String kategori;
private Integer umur;
private String jk;
private String aktivitas;
public Double getTb() {
return tb;
}
public void setTb(Double tb) {
this.tb = tb;
}
public Double getBb() {
return bb;
}
public void setBb(Double bb) {
this.bb = bb;
}
public Double getImt() {
return imt;
}
public void setImt(Double imt) {
this.imt = imt;
}
public String getKategori() {
return kategori;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public Integer getUmur() {
return umur;
}
public void setUmur(Integer umur) {
this.umur = umur;
}
public String getJk() {
return jk;
}
public void setJk(String jk) {
this.jk = jk;
}
public String getAktivitas() {
return aktivitas;
}
public void setAktivitas(String aktivitas) {
this.aktivitas = aktivitas;
}
public DataProvider(Double tb, Double bb, Double imt, String kategori, Integer umur, String jk, String aktivitas)
{
this.tb =tb;
this.bb =bb;
this.imt =imt;
this.kategori =kategori;
this.umur =umur;
this.jk =jk;
this.aktivitas =aktivitas;
}
}
|
import java.util.Scanner;
public class AnoBissexto {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Digite o ano: ");
int ano = input.nextInt();
if (ano < 0){
System.out.println(ano+" nao e um ano valido");
} else {
if ((ano%4==0) && ((ano%100!=0) || (ano%100==0) && (ano%400==0))){
System.out.println(ano+" e bissexto");
} else {
System.out.println(ano+" nao e bissexto");
}
}
}
}
|
package com.nishanth.asian_countries;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
public class fetchdata extends AsyncTask<Void, Void, Void> {
ArrayList<Country> countriesinfthdta=new ArrayList<>();
String data="";
@Override
protected Void doInBackground(Void... voids) {
try {
URL url=new URL("https://restcountries.eu/rest/v2/region/asia");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
InputStream inputStream=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while(line!=null)
{
line=reader.readLine();
data=data+line;
}
JSONArray ja=new JSONArray(data);
for(int i=0;i<ja.length();i++)
{
JSONObject object=(JSONObject)ja.get(i);
String name= (String) object.get("name");
String capital= (String) object.get("capital");
String flag= (String) object.get("flag");
String region= (String) object.get("region");
String subregion=(String) object.get("subregion");
String population =String.valueOf(object.get("population"));
ArrayList<String> borders= new ArrayList<>();
JSONArray bordersja= (JSONArray) object.get("borders");
for(int j=0;j<bordersja.length();j++)
{
borders.add((String) bordersja.get(j));
}
ArrayList<String> languages=new ArrayList<>();
JSONArray languagesja=(JSONArray) object.get("languages");
for(int j=0;j<languagesja.length();j++)
{
JSONObject languagesjo=(JSONObject)languagesja.get(i);
languages.add((String) languagesjo.get("name"));
}
Country country=new Country(name, capital, flag, region, subregion, population, borders, languages);
countriesinfthdta.add(country);
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.setCountries(countriesinfthdta);
}
}
|
package com.application.swplanetsapi.infrastructure.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import com.mongodb.DB;
@Configuration
public class MongoConfig {
private final MongoDbFactory mongo;
@Autowired
public MongoConfig(MongoDbFactory mongo) {
this.mongo = mongo;
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.sql.PreparedStatement;
/**
* Class to Create and Manage a SQLite Database
*/
public class Database {
protected Connection connection;
protected Statement statement;
private String url = "jdbc:sqlite:"; //The Database URL, Can Be a File Path
public Database(String databaseLocation) {
url += databaseLocation;
startConnection(databaseLocation);
}
private void startConnection(String databaseLocation) {
try {
connection = DriverManager.getConnection(url); //Open Connection
statement = connection.createStatement();
System.out.println("Connection Successful, Path: "+url.substring(12, url.length()));
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
public void startConnection() {
startConnection(url);
}
public void closeConnection() {
try {
connection.close();
System.out.println("Connection Closed");
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* This only needs to be called one to set up the database, if a database is already made then there is no need to run it
*/
public void makeTables() {
String dataByLap = "CREATE TABLE IF NOT EXISTS dataByLap (\n"
+ " Lap_Number integer PRIMARY KEY,\n" //first value is col name second is data type third is col constraint
+ " Lap_Time real,\n"
+ " Lap_Distance real,\n"
+ " State_of_Charge real,\n"
+ " Miles_Remaining real\n"
+ ") WITHOUT ROWID;";
String dataByTime = "CREATE TABLE IF NOT EXISTS dataByTime (\n"
+ " Time TEXT PRIMARY KEY,\n" //first value is col name second is data type third is col constraint
+ " Speed real,\n"
+ " State_of_Charge real,\n"
+ " Power_Draw real,\n"
+ " Acclrm_X real,\n"
+ " Acclrm_Y real,\n"
+ " Acclrm_Z real,\n"
+ " Miles_Travled real\n"
+ " Miles_Remaining real\n"
+ " Cabin_Temperature real\n"
+ " Driver_Heart_Rate real\n"
+ ") WITHOUT ROWID;";
try{
statement.execute(dataByLap);
System.out.println("dataByLap table made successfully");
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
try{
statement.execute(dataByTime);
System.out.println("dataByTime table made successfully");
}
catch(SQLException e) {
e.printStackTrace();
}
}
public void addDataByLap(int Lap_Number, double Lap_Time, double Lap_Distance, double State_of_Charge, double Miles_Remaining) {
String insertStatement = "INSERT INTO dataByLap(Lap_Number,Lap_Time,Lap_Distance,State_of_Charge,Miles_Remaining)"
+ "VALUES(?,?,?,?,?)";
try {
PreparedStatement insertDataStatement = connection.prepareStatement(insertStatement);
insertDataStatement.setInt(1,Lap_Number);
insertDataStatement.setDouble(2,Lap_Time);
insertDataStatement.setDouble(3,Lap_Distance);
insertDataStatement.setDouble(4,State_of_Charge);
insertDataStatement.setDouble(5,Miles_Remaining);
insertDataStatement.executeUpdate();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
public Connection getConnection() {
return connection;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.rsocket.service;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.util.MimeType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.aot.hint.predicate.RuntimeHintsPredicates.reflection;
/**
* Tests for {@link RSocketExchangeReflectiveProcessor}.
*
* @author Sebastien Deleuze
* @author Olga Maciaszek-Sharma
* @since 6.0.5
*/
class RSocketExchangeReflectiveProcessorTests {
private final RSocketExchangeReflectiveProcessor processor = new RSocketExchangeReflectiveProcessor();
private final RuntimeHints hints = new RuntimeHints();
@Test
void shouldRegisterReflectionHintsForMethod() throws NoSuchMethodException {
Method method = SampleService.class.getDeclaredMethod("get", Request.class, Variable.class,
Metadata.class, MimeType.class);
processor.registerReflectionHints(hints.reflection(), method);
assertThat(reflection().onType(SampleService.class)).accepts(hints);
assertThat(reflection().onMethod(SampleService.class, "get")).accepts(hints);
assertThat(reflection().onType(Response.class)).accepts(hints);
assertThat(reflection().onMethod(Response.class, "getMessage")).accepts(hints);
assertThat(reflection().onMethod(Response.class, "setMessage")).accepts(hints);
assertThat(reflection().onType(Request.class)).accepts(hints);
assertThat(reflection().onMethod(Request.class, "getMessage")).accepts(hints);
assertThat(reflection().onMethod(Request.class, "setMessage")).accepts(hints);
assertThat(reflection().onType(Variable.class)).accepts(hints);
assertThat(reflection().onMethod(Variable.class, "getValue")).accepts(hints);
assertThat(reflection().onMethod(Variable.class, "setValue")).accepts(hints);
assertThat(reflection().onType(Metadata.class)).accepts(hints);
assertThat(reflection().onMethod(Metadata.class, "getValue")).accepts(hints);
assertThat(reflection().onMethod(Metadata.class, "setValue")).accepts(hints);
}
interface SampleService {
@RSocketExchange
Response get(@Payload Request request, @DestinationVariable Variable variable,
Metadata metadata, MimeType mimeType);
}
static class Request {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
static class Response {
private String message;
public Response(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
static class Variable {
private String value;
public Variable(String value) {
this.value = value;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
static class Metadata {
private String value;
public Metadata(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
|
package by.bytechs.xfs.deviceStatus.pinStatus;
import at.o2xfs.xfs.pin.PINEncStat;
import by.bytechs.xml.entity.deviceStatus.ComponentXml;
/**
* @author Romanovich Andrei
*/
public enum PINEncryptStatus {
WFS_PIN_ENCREADY(1, "Крипто-модуль PIN готов к работе"),
WFS_PIN_ENCNOTREADY(1, "Крипто-модуль PIN не готов к работе"),
WFS_PIN_ENCNOTINITIALIZED(2, "Крипто-модуль PIN не проинициализирован"),
WFS_PIN_ENCBUSY(0, "Крипто-модуль PIN работает"),
WFS_PIN_ENCUNDEFINED(3, "Не удалось определить состояние крипто-модуля PIN"),
WFS_PIN_ENCINITIALIZED(4, "Крипто-модуль PIN проинициализирован"),
WFS_PIN_ENCPINTAMPERED(5, "Вмешательство в работу крипто-модуля PIN"),
UNKNOWN_STATUS(150, "Неизвестное сотояние устройства");
final int code;
final String description;
PINEncryptStatus(final int code, final String description) {
this.code = code;
this.description = description;
}
public static ComponentXml getDescription(PINEncStat encryptStatus) {
if (encryptStatus != null) {
for (PINEncryptStatus status : PINEncryptStatus.values()) {
if (status.name().equals(encryptStatus.name())) {
return new ComponentXml(status.code, status.description, "media");
}
}
}
return new ComponentXml(UNKNOWN_STATUS.code, UNKNOWN_STATUS.description, "media");
}
}
|
package de.trispeedys.resourceplanning.delegate.requesthelp;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import de.trispeedys.resourceplanning.execution.BpmVariables;
import de.trispeedys.resourceplanning.util.exception.ResourcePlanningException;
public class CheckPreconditionsDelegate implements JavaDelegate
{
public void execute(DelegateExecution execution) throws Exception
{
// (1) check if business key is set
if (execution.getBusinessKey() == null)
{
throw new ResourcePlanningException("can not start request help process without a business key!!");
}
// (2) check if helper id is set
if (execution.getVariable(BpmVariables.RequestHelpHelper.VAR_HELPER_ID) == null)
{
throw new ResourcePlanningException("can not start request help process without a helper id set!!");
}
// (3) check if event id is set
if (execution.getVariable(BpmVariables.RequestHelpHelper.VAR_EVENT_ID) == null)
{
throw new ResourcePlanningException("can not start request help process without a event id set!!");
}
}
}
|
package sorcier.dao.hibernate4;
import static org.junit.Assert.*;
//import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import sorcier.dao.SorcererDao;
import sorcier.domain.Sorcerer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DaoTestConfig.class)
public class SorcererDaoTest {
@Autowired
SorcererDao sorcererDao;
@Test
@Transactional
public void findByUsername() {
assertSorcerer(0, sorcererDao.findByUsername("habuma"));
assertSorcerer(1, sorcererDao.findByUsername("mwalls"));
assertSorcerer(2, sorcererDao.findByUsername("chuck"));
assertSorcerer(3, sorcererDao.findByUsername("artnames"));
}
private static void assertSorcerer(int expectedSorcererIndex, Sorcerer actual) {
assertSorcerer(expectedSorcererIndex, actual, "Newbie");
}
private static void assertSorcerer(int expectedSorcererIndex, Sorcerer actual,
String expectedStatus) {
Sorcerer expected = SORCERERS[expectedSorcererIndex];
assertEquals(expected.getId(), actual.getId());
assertEquals(expected.getUsername(), actual.getUsername());
assertEquals(expected.getPassword(), actual.getPassword());
assertEquals(expected.getFullName(), actual.getFullName());
assertEquals(expected.getEmail(), actual.getEmail());
assertEquals(expected.isUpdateByEmail(), actual.isUpdateByEmail());
}
private static Sorcerer[] SORCERERS = new Sorcerer[6];
@BeforeClass
public static void before() {
SORCERERS[0] = new Sorcerer(1L, "habuma", "password", "Craig Walls",
"craig@habuma.com", false);
SORCERERS[1] = new Sorcerer(2L, "mwalls", "password", "Michael Walls",
"mwalls@habuma.com", true);
SORCERERS[2] = new Sorcerer(3L, "chuck", "password", "Chuck Wagon",
"chuck@habuma.com", false);
SORCERERS[3] = new Sorcerer(4L, "artnames", "password", "Art Names",
"art@habuma.com", true);
SORCERERS[4] = new Sorcerer(5L, "newbee", "letmein", "New Bee",
"newbee@habuma.com", true);
SORCERERS[5] = new Sorcerer(4L, "arthur", "letmein", "Arthur Names",
"arthur@habuma.com", false);
}
}
|
package com.witness.view.explosion_view;
import android.graphics.Bitmap;
import android.graphics.Rect;
public class FallingParticleFactory extends ParticleFactory {
public static final int PART_WH = 8;
@Override
public Particle[][] generateParticles(Bitmap bitmap, Rect rect) {
int w = rect.width();
int h = rect.height();
int partW_Count = w/PART_WH;//横向个数(列数)
int partH_Count = h/PART_WH;//竖向个数(行数)
//判断个数不能小于0
partW_Count = partW_Count > 0 ? partW_Count : 1;
partH_Count = partH_Count > 0 ? partH_Count : 1;
int bitmap_part_w = bitmap.getWidth() / partW_Count;
int bitmap_part_h = bitmap.getHeight() / partH_Count;
Particle[][] particles = new Particle[partH_Count][partW_Count];
for (int row = 0; row < partH_Count; row++) {
//行
for (int column = 0; column < partW_Count; column++) {
//列
//取得当前粒子所在的位置颜色
int color = bitmap.getPixel(column * bitmap_part_w, row * bitmap_part_h);
float x = rect.left + PART_WH * column;
float y = rect.top + PART_WH * row;
particles[row][column] = new FallingParticle(color, x, y, rect);
}
}
return particles;
}
}
|
package cn.v5cn.v5cms.front.controller;
import cn.v5cn.v5cms.entity.Column;
import cn.v5cn.v5cms.entity.Site;
import cn.v5cn.v5cms.service.ColumnService;
import cn.v5cn.v5cms.util.SystemConstant;
import cn.v5cn.v5cms.util.SystemUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* Created by ZXF-PC1 on 2015/7/29.
*/
@Controller
@RequestMapping("/nav")
public class FrontColumnController {
@Autowired
private ColumnService columnService;
@RequestMapping(value = "/{navId}.htm")
public String columnList(@PathVariable Long navId,HttpServletRequest request,ModelMap modelMap){
Site site = (Site)request.getSession().getAttribute(SystemConstant.FRONT_SITE_SESSION_KEY);
Column column = columnService.findOne(navId);
modelMap.addAttribute(column);
String coltpl = FilenameUtils.removeExtension(SystemUtils.formatUri(column.getColumnType().getColtpl()));
return site.getThemeName() + "/" + coltpl;
}
}
|
package com.sunjob.yudioj_springboot_framemark.service;
import com.sunjob.yudioj_springboot_framemark.mapper.Role2UserMapper;
import com.sunjob.yudioj_springboot_framemark.vo.Role2User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class Role2UserServiceImpl implements Role2UserService{
@Autowired
Role2UserMapper role2UserMapper;
@Override
public List<Role2User> findAllRole2UserWithout() {
return role2UserMapper.findAllRole2UserWithout();
}
@Override
public boolean modifyUserRole(Role2User role2User) {
role2User.setModifyTime(new Date());
return role2UserMapper.modifyUserRole(role2User);
}
@Override
public Role2User findRole2UserById(String id) {
return role2UserMapper.findRole2UserById(id);
}
@Override
public List<Role2User> findAllRole2User() {
return role2UserMapper.findAllRole2User();
}
@Override
public boolean freezeRole2User(String id) {
return role2UserMapper.freezeRole2User(id,new Date());
}
@Override
public boolean addUserRole(Role2User role2User) {
Date date = new Date();
role2User.setModifyTime(date);
role2User.setCreateTime(date);
role2User.setId(System.currentTimeMillis()+"");
return role2UserMapper.addUserRole(role2User);
}
}
|
package co.qingmei.pm.biz;
import co.qingmei.pm.dao.TaskMapper;
import co.qingmei.pm.entity.Task;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TaskBiz {
@Autowired
private TaskMapper tm;
public Task getTaskById(int pid) {
return this.tm.selectByPrimaryKey(pid);
}
public void saveTask(Task ttt) {
if (ttt.getId() != null )
this.tm.updateByPrimaryKeySelective(ttt);
else
this.tm.insertSelective( ttt);
}
public List<Task> getTaskList(String taskName, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum,pageSize);
return this.tm.getTaskListByTaskName(taskName);
}
public void deleteTaskById(int tid) {
this.tm.deleteByPrimaryKey(tid);
}
}
|
package ru.yandex.artists;
import android.os.IBinder;
import android.support.test.espresso.Root;
import android.support.test.espresso.ViewInteraction;
import android.support.test.espresso.matcher.BoundedMatcher;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static org.hamcrest.core.Is.is;
/**
* Created by druger on 11.04.2016.
*/
public class TestUtils {
public static ViewInteraction matchToolbarTitle(CharSequence title) {
return onView(isAssignableFrom(Toolbar.class))
.check(matches(withToolbarTitle(is(title))));
}
private static Matcher<Object> withToolbarTitle(final Matcher<CharSequence> textMatcher) {
return new BoundedMatcher<Object, Toolbar>(Toolbar.class) {
@Override
public void describeTo(Description description) {
description.appendText("with toolbar title: ");
textMatcher.describeTo(description);
}
@Override
protected boolean matchesSafely(Toolbar item) {
return textMatcher.matches(item.getTitle());
}
};
}
public static BoundedMatcher<View, ImageView> hasDrawable() {
return new BoundedMatcher<View, ImageView>(ImageView.class) {
@Override
protected boolean matchesSafely(ImageView item) {
return item.getDrawable() != null;
}
@Override
public void describeTo(Description description) {
description.appendText("has drawable");
}
};
}
public static Matcher<Root> isToast() {
return new TypeSafeMatcher<Root>() {
@Override
protected boolean matchesSafely(Root root) {
int type = root.getWindowLayoutParams().get().type;
if (type == WindowManager.LayoutParams.TYPE_TOAST) {
IBinder windowToken = root.getDecorView().getWindowToken();
IBinder appToken = root.getDecorView().getApplicationWindowToken();
if (windowToken == appToken) {
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("is toast");
}
};
}
}
|
package by.pvt.herzhot.loader;
import by.pvt.herzhot.dao.exceptions.DaoException;
import by.pvt.herzhot.dao.impl.DaoImpl;
import by.pvt.herzhot.managers.CommandManager;
import by.pvt.herzhot.managers.EntityManager;
import by.pvt.herzhot.pojos.Entity;
import by.pvt.herzhot.services.exceptions.ServiceException;
import by.pvt.herzhot.services.impl.DepartmentServiceImpl;
import by.pvt.herzhot.services.impl.MeetingServiceImpl;
import by.pvt.herzhot.services.impl.TeacherServiceImpl;
import by.pvt.herzhot.utils.InputValueValidator;
import java.util.List;
import java.util.Scanner;
import static by.pvt.herzhot.managers.CommandManager.*;
import static java.lang.System.in;
import static java.lang.System.out;
/**
* @author Herzhot
* @version 1.0
* 30.05.2016
*/
public class MainLoader {
public static void main(String[] args) {
CommandManager commandManager = INSTANCE;
EntityManager entityManager = EntityManager.INSTANCE;
InputValueValidator inputValueValidator = InputValueValidator.INSTANCE;
DaoImpl<Entity> dao = DaoImpl.getInstance();
TeacherServiceImpl teacherService = TeacherServiceImpl.INSTANCE;
MeetingServiceImpl meetingService = MeetingServiceImpl.INSTANCE;
DepartmentServiceImpl departmentService = DepartmentServiceImpl.INSTANCE;
Scanner scanner = new Scanner(in);
boolean isLaunched = true;
Integer selectedItem = 0;
while (isLaunched) {
commandManager.getMenuCommands();
selectedItem = inputValueValidator.validate(selectedItem.TYPE);
switch (selectedItem) {
case DELETE_ENTITY_COMMAND: {
out.println("You choose - " + selectedItem);
commandManager.getMenuEntities();
selectedItem = commandManager.getSelectedItem();
Entity entity = (Entity) commandManager.getEntities().get(selectedItem-1);
out.println("Please select ID for deleting:");
try {
int id = Integer.valueOf(scanner.nextLine().trim());
out.println("Operation is successful: " + dao.delete(entity, id));
}
catch (DaoException | NullPointerException e) {
out.println("Deleted " + entity.getClass().getSimpleName()+ " isn't found!");
}
break;
}
case FIND_ENTITY_COMMAND: {
out.println("You choose - " + selectedItem);
commandManager.getMenuEntities();
selectedItem = commandManager.getSelectedItem();
Entity entity = (Entity) commandManager.getEntities().get(selectedItem-1);
out.println("Please select ID:");
try {
int id = Integer.valueOf(scanner.nextLine().trim());
Entity receivedEntity = dao.find(entity, id);
out.println(receivedEntity.getClass().getSimpleName() + " is found:");
out.println(receivedEntity.toString());
}
catch (DaoException | NullPointerException e) {
out.println(entity.getClass().getSimpleName() + " isn't found!");
}
break;
}
case FIND_ALL_ENTITIES_COMMAND: {
out.println("You choose - " + selectedItem);
commandManager.getMenuEntities();
selectedItem = commandManager.getSelectedItem();
Entity entity = (Entity) commandManager.getEntities().get(selectedItem-1);
out.println("List of " + entity.getClass().getSimpleName() + ":");
List<Entity> entities;
try {
entities = dao.findAll(entity);
for (Object object : entities) {
out.println(object.toString());
}
}
catch (DaoException e) {
out.println(entity.getClass().getSimpleName() + "(e)s isn't found!");
}
break;
}
case SAVE_OR_UPDATE_ENTITY_COMMAND: {
out.println("You choose - " + selectedItem);
commandManager.getMenuEntities();
selectedItem = commandManager.getSelectedItem();
Entity entity = (Entity) commandManager.getEntities().get(selectedItem - 1);
Entity receivedEntity = entityManager.buildEntity(entity);
try {
out.println("Operation is successful: " + dao.saveOrUpdate(receivedEntity));
} catch (DaoException | NullPointerException e) {
out.println("Operation failed. DAO error!");
}
break;
}
case SAVE_OR_UPDATE_THEACHER: {
out.println("You choose - " + selectedItem);
try {
out.println("Operation is successful: " + teacherService.saveOrUpdate());
} catch (ServiceException | NullPointerException e) {
out.println("Operation failed. Service error!");
}
break;
}
case SAVE_OR_UPDATE_DEPARTMENT: {
out.println("You choose - " + selectedItem);
try {
out.println("Operation is successful: " + departmentService.saveOrUpdate());
} catch (ServiceException | NullPointerException e) {
out.println("Operation failed. Service error!");
}
break;
}
case SAVE_OR_UPDATE_MEETING: {
out.println("You choose - " + selectedItem);
try {
out.println("Operation is successful: " + meetingService.saveOrUpdate());
} catch (ServiceException | NullPointerException e) {
out.println("Operation failed. Service error!");
}
break;
}
case EXIT_COMMAND: {
out.println("You choose - " + selectedItem);
out.println("Good-bye!");
isLaunched = false;
break;
}
default: {
out.println("You choose wrong command!");
}
}
}
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.explorer.client.toolbar;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.GXT;
import com.sencha.gxt.core.client.resources.ThemeStyles;
import com.sencha.gxt.core.client.util.DelayedTask;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Status;
import com.sencha.gxt.widget.core.client.Status.BoxStatusAppearance;
import com.sencha.gxt.widget.core.client.Status.StatusAppearance;
import com.sencha.gxt.widget.core.client.container.SimpleContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.toolbar.FillToolItem;
import com.sencha.gxt.widget.core.client.toolbar.LabelToolItem;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
@Detail(name = "Status ToolBar", icon = "statustoolbar", category = "ToolBar & Menu")
public class StatusToolBarExample implements IsWidget, EntryPoint {
private DelayedTask task = new DelayedTask() {
@Override
public void onExecute() {
status.clearStatus("Not writing");
}
};
private Status charCount;
private Status wordCount;
private Status status;
public Widget asWidget() {
ToolBar toolBar = new ToolBar();
toolBar.addStyleName(ThemeStyles.getStyle().borderTop());
status = new Status();
status.setText("Not writing");
status.setWidth(150);
toolBar.add(status);
toolBar.add(new FillToolItem());
charCount = new Status(GWT.<StatusAppearance> create(BoxStatusAppearance.class));
charCount.setWidth(100);
charCount.setText("0 Chars");
toolBar.add(charCount);
toolBar.add(new LabelToolItem(" "));
wordCount = new Status(GWT.<StatusAppearance> create(BoxStatusAppearance.class));
wordCount.setWidth(100);
wordCount.setText("0 Words");
toolBar.add(wordCount);
ContentPanel panel = new ContentPanel();
panel.setHeadingText("Status Toolbar");
panel.setPixelSize(450, 300);
panel.addStyleName("margin-10");
VerticalLayoutContainer form = new VerticalLayoutContainer();
panel.add(form);
TextArea textArea = new TextArea();
textArea.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
status.setBusy("writing...");
TextArea t = (TextArea) event.getSource();
String value = t.getCurrentValue();
int length = value != null ? value.length() : 0;
charCount.setText(length + (length == 1 ? " Char" : " Chars"));
if (value != null) {
int wc = getWordCount(value);
wordCount.setText(wc + (wc == 1 ? " Word" : " Words"));
}
task.delay(1000);
}
});
VerticalLayoutData data = new VerticalLayoutData(1, 1);
data.setMargins(new Margins(5));
textArea.setLayoutData(data);
Widget w = textArea;
// TODO investigate IE bug where text area is floating out of view
if (GXT.isIE6()) {
SimpleContainer s = new SimpleContainer();
s.setWidget(textArea);
w = s;
}
form.add(w, new VerticalLayoutData(1, 1, new Margins(5)));
toolBar.setLayoutData(new VerticalLayoutData(1, -1));
form.add(toolBar);
return panel;
}
public native int getWordCount(String v) /*-{
if (v) {
var wc = v.match(/\b/g);
return wc ? wc.length / 2 : 0;
}
return 0;
}-*/;
public void onModuleLoad() {
RootPanel.get().add(asWidget());
}
}
|
package com.test3;
import java.io.*;
import javax.sound.sampled.*;
public class TestAudio {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AePlayWave apw=new AePlayWave("d:\\111.wav");
Thread t=new Thread(apw);
t.start();
}
}
class AePlayWave implements Runnable
{
private String filename;
public AePlayWave(String wavfile)
{
filename=wavfile;
}
@Override
public void run() {
// TODO Auto-generated method stub
File soundfile=new File(filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream=AudioSystem.getAudioInputStream(soundfile);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
return;
}
AudioFormat format=audioInputStream.getFormat();
SourceDataLine auline=null;
DataLine.Info info=new DataLine.Info(SourceDataLine.class, format);
try {
auline=(SourceDataLine)AudioSystem.getLine(info);
auline.open(format);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
return;
}
auline.start();
int nBytesRead=0;
byte [] abData=new byte[1024];
try {
while(nBytesRead!=-1)
{
nBytesRead=audioInputStream.read(abData,0,abData.length);
if(nBytesRead>0)
{
auline.write(abData, 0, nBytesRead);
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally
{
auline.drain();
auline.close();
}
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.core.diagram.providers;
import java.lang.ref.WeakReference;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;
import org.eclipse.gmf.runtime.common.core.service.IOperation;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.services.editpart.AbstractEditPartProvider;
import org.eclipse.gmf.runtime.diagram.ui.services.editpart.CreateGraphicEditPartOperation;
import org.eclipse.gmf.runtime.diagram.ui.services.editpart.IEditPartOperation;
import org.eclipse.gmf.runtime.notation.View;
import org.neuro4j.studio.core.diagram.edit.parts.NetworkEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.Neuro4jEditPartFactory;
import org.neuro4j.studio.core.diagram.part.Neuro4jVisualIDRegistry;
/**
* @generated
*/
public class Neuro4jEditPartProvider extends AbstractEditPartProvider {
/**
* @generated
*/
private EditPartFactory factory;
/**
* @generated
*/
private boolean allowCaching;
/**
* @generated
*/
private WeakReference cachedPart;
/**
* @generated
*/
private WeakReference cachedView;
/**
* @generated
*/
public Neuro4jEditPartProvider() {
setFactory(new Neuro4jEditPartFactory());
setAllowCaching(true);
}
/**
* @generated
*/
public final EditPartFactory getFactory() {
return factory;
}
/**
* @generated
*/
protected void setFactory(EditPartFactory factory) {
this.factory = factory;
}
/**
* @generated
*/
public final boolean isAllowCaching() {
return allowCaching;
}
/**
* @generated
*/
protected synchronized void setAllowCaching(boolean allowCaching) {
this.allowCaching = allowCaching;
if (!allowCaching) {
cachedPart = null;
cachedView = null;
}
}
/**
* @generated
*/
protected IGraphicalEditPart createEditPart(View view) {
EditPart part = factory.createEditPart(null, view);
if (part instanceof IGraphicalEditPart) {
return (IGraphicalEditPart) part;
}
return null;
}
/**
* @generated
*/
protected IGraphicalEditPart getCachedPart(View view) {
if (cachedView != null && cachedView.get() == view) {
return (IGraphicalEditPart) cachedPart.get();
}
return null;
}
/**
* @generated
*/
public synchronized IGraphicalEditPart createGraphicEditPart(View view) {
if (isAllowCaching()) {
IGraphicalEditPart part = getCachedPart(view);
cachedPart = null;
cachedView = null;
if (part != null) {
return part;
}
}
return createEditPart(view);
}
/**
* @generated
*/
public synchronized boolean provides(IOperation operation) {
if (operation instanceof CreateGraphicEditPartOperation) {
View view = ((IEditPartOperation) operation).getView();
if (!NetworkEditPart.MODEL_ID.equals(Neuro4jVisualIDRegistry
.getModelID(view))) {
return false;
}
if (isAllowCaching() && getCachedPart(view) != null) {
return true;
}
IGraphicalEditPart part = createEditPart(view);
if (part != null) {
if (isAllowCaching()) {
cachedPart = new WeakReference(part);
cachedView = new WeakReference(view);
}
return true;
}
}
return false;
}
}
|
package at.sync.model;
import java.util.UUID;
/**
* POI - Point of Interest
* Represents a Building, Station, Place,..
*/
public class POI extends Entity implements IExternalReferenceable {
private UUID id;
private String name;
private POIType poiType;
private double radius;
private String extRef;
private double latitude;
private double longitude;
private String transportationType;
public POI() {
}
public POI(UUID id, String name, double radius, String ext_ref, POIType poiType) {
this.id = id;
this.name = name;
this.radius = radius;
this.extRef = ext_ref;
this.poiType = poiType;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getExtRef() {
return extRef;
}
public void setExtRef(String extRef) {
this.extRef = extRef;
}
public POIType getPoiType() {
return poiType;
}
public void setPoiType(POIType poiType) {
this.poiType = poiType;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getTransportationType() {
return transportationType;
}
public void setTransportationType(String transportationType) {
this.transportationType = transportationType;
}
}
|
import java.util.Scanner;
public class main{
float promedio;
String grado;
float costo;
int reprobadas;
public int getReprobadas() {
return reprobadas;
}
public void setReprobadas(int reprobadas) {
this.reprobadas = reprobadas;
}
public float getCosto() {
return costo;
}
public float getPromedio() {
return promedio;
}
public void setPromedio(float promedio) {
this.promedio = promedio;
}
public String getGrado() {
return grado;
}
public void setGrado(String grado) {
this.grado = grado;
}
public void estimulo(){
float x=180/5,y=300/5;
if(grado=="b"){
if(promedio>=9.5){
costo=55*x;
costo*=.75;
}else{
if(promedio>9){
costo=50*x;
costo*=.90;
}else{
if(promedio>7){
costo=x*50;
}else{
if((promedio<=7)&&(reprobadas<4)){
costo=45*x;
}else{
if((promedio<=7)&&(reprobadas>3)){
costo=40*x;
}
}
}
}
}
}else{
if(promedio>=9.5){
costo=55*y;
costo*=.80;
}else{
costo=55*y;
}
}
}
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
main o=new main();
System.out.println("Dime tu grado (p/b)");
o.setGrado(sc.next());
System.out.println("Dime tu promedio ");
o.setPromedio(sc.nextFloat());
System.out.println("Dime tu numero de materias reprobadas ");
o.setReprobadas(sc.nextInt());
o.estimulo();
System.out.println("Tu colegiatura es de: "+o.getCosto());
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.buffer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.NoSuchElementException;
import java.util.function.IntPredicate;
import io.netty5.buffer.Buffer;
import io.netty5.buffer.BufferComponent;
import io.netty5.buffer.ComponentIterator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* Implementation of the {@code DataBuffer} interface that wraps a Netty 5
* {@link Buffer}. Typically constructed with {@link Netty5DataBufferFactory}.
*
* @author Violeta Georgieva
* @author Arjen Poutsma
* @since 6.0
*/
public final class Netty5DataBuffer implements CloseableDataBuffer, TouchableDataBuffer {
private final Buffer buffer;
private final Netty5DataBufferFactory dataBufferFactory;
/**
* Create a new {@code Netty5DataBuffer} based on the given {@code Buffer}.
* @param buffer the buffer to base this buffer on
*/
Netty5DataBuffer(Buffer buffer, Netty5DataBufferFactory dataBufferFactory) {
Assert.notNull(buffer, "Buffer must not be null");
Assert.notNull(dataBufferFactory, "Netty5DataBufferFactory must not be null");
this.buffer = buffer;
this.dataBufferFactory = dataBufferFactory;
}
/**
* Directly exposes the native {@code Buffer} that this buffer is based on.
* @return the wrapped buffer
*/
public Buffer getNativeBuffer() {
return this.buffer;
}
@Override
public DataBufferFactory factory() {
return this.dataBufferFactory;
}
@Override
public int indexOf(IntPredicate predicate, int fromIndex) {
Assert.notNull(predicate, "IntPredicate must not be null");
if (fromIndex < 0) {
fromIndex = 0;
}
else if (fromIndex >= this.buffer.writerOffset()) {
return -1;
}
int length = this.buffer.writerOffset() - fromIndex;
int bytes = this.buffer.openCursor(fromIndex, length).process(predicate.negate()::test);
return bytes == -1 ? -1 : fromIndex + bytes;
}
@Override
public int lastIndexOf(IntPredicate predicate, int fromIndex) {
Assert.notNull(predicate, "IntPredicate must not be null");
if (fromIndex < 0) {
return -1;
}
fromIndex = Math.min(fromIndex, this.buffer.writerOffset() - 1);
return this.buffer.openCursor(0, fromIndex + 1).process(predicate.negate()::test);
}
@Override
public int readableByteCount() {
return this.buffer.readableBytes();
}
@Override
public int writableByteCount() {
return this.buffer.writableBytes();
}
@Override
public int readPosition() {
return this.buffer.readerOffset();
}
@Override
public Netty5DataBuffer readPosition(int readPosition) {
this.buffer.readerOffset(readPosition);
return this;
}
@Override
public int writePosition() {
return this.buffer.writerOffset();
}
@Override
public Netty5DataBuffer writePosition(int writePosition) {
this.buffer.writerOffset(writePosition);
return this;
}
@Override
public byte getByte(int index) {
return this.buffer.getByte(index);
}
@Override
public int capacity() {
return this.buffer.capacity();
}
@Override
@Deprecated
public Netty5DataBuffer capacity(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException(String.format("'newCapacity' %d must be higher than 0", capacity));
}
int diff = capacity - capacity();
if (diff > 0) {
this.buffer.ensureWritable(this.buffer.writableBytes() + diff);
}
return this;
}
@Override
public DataBuffer ensureWritable(int capacity) {
Assert.isTrue(capacity >= 0, "Capacity must be >= 0");
this.buffer.ensureWritable(capacity);
return this;
}
@Override
public byte read() {
return this.buffer.readByte();
}
@Override
public Netty5DataBuffer read(byte[] destination) {
return read(destination, 0, destination.length);
}
@Override
public Netty5DataBuffer read(byte[] destination, int offset, int length) {
this.buffer.readBytes(destination, offset, length);
return this;
}
@Override
public Netty5DataBuffer write(byte b) {
this.buffer.writeByte(b);
return this;
}
@Override
public Netty5DataBuffer write(byte[] source) {
this.buffer.writeBytes(source);
return this;
}
@Override
public Netty5DataBuffer write(byte[] source, int offset, int length) {
this.buffer.writeBytes(source, offset, length);
return this;
}
@Override
public Netty5DataBuffer write(DataBuffer... dataBuffers) {
if (!ObjectUtils.isEmpty(dataBuffers)) {
if (hasNetty5DataBuffers(dataBuffers)) {
Buffer[] nativeBuffers = new Buffer[dataBuffers.length];
for (int i = 0; i < dataBuffers.length; i++) {
nativeBuffers[i] = ((Netty5DataBuffer) dataBuffers[i]).getNativeBuffer();
}
return write(nativeBuffers);
}
else {
ByteBuffer[] byteBuffers = new ByteBuffer[dataBuffers.length];
for (int i = 0; i < dataBuffers.length; i++) {
byteBuffers[i] = ByteBuffer.allocate(dataBuffers[i].readableByteCount());
dataBuffers[i].toByteBuffer(byteBuffers[i]);
}
return write(byteBuffers);
}
}
return this;
}
private static boolean hasNetty5DataBuffers(DataBuffer[] buffers) {
for (DataBuffer buffer : buffers) {
if (!(buffer instanceof Netty5DataBuffer)) {
return false;
}
}
return true;
}
@Override
public Netty5DataBuffer write(ByteBuffer... buffers) {
if (!ObjectUtils.isEmpty(buffers)) {
for (ByteBuffer buffer : buffers) {
this.buffer.writeBytes(buffer);
}
}
return this;
}
/**
* Writes one or more Netty 5 {@link Buffer Buffers} to this buffer,
* starting at the current writing position.
* @param buffers the buffers to write into this buffer
* @return this buffer
*/
public Netty5DataBuffer write(Buffer... buffers) {
if (!ObjectUtils.isEmpty(buffers)) {
for (Buffer buffer : buffers) {
this.buffer.writeBytes(buffer);
}
}
return this;
}
@Override
public DataBuffer write(CharSequence charSequence, Charset charset) {
Assert.notNull(charSequence, "CharSequence must not be null");
Assert.notNull(charset, "Charset must not be null");
this.buffer.writeCharSequence(charSequence, charset);
return this;
}
/**
* {@inheritDoc}
* <p><strong>Note</strong> that due to the lack of a {@code slice} method
* in Netty 5's {@link Buffer}, this implementation returns a copy that
* does <strong>not</strong> share its contents with this buffer.
*/
@Override
@Deprecated
public DataBuffer slice(int index, int length) {
Buffer copy = this.buffer.copy(index, length);
return new Netty5DataBuffer(copy, this.dataBufferFactory);
}
@Override
public DataBuffer split(int index) {
Buffer split = this.buffer.split(index);
return new Netty5DataBuffer(split, this.dataBufferFactory);
}
@Override
@Deprecated
public ByteBuffer asByteBuffer() {
return toByteBuffer();
}
@Override
@Deprecated
public ByteBuffer asByteBuffer(int index, int length) {
return toByteBuffer(index, length);
}
@Override
@Deprecated
public ByteBuffer toByteBuffer(int index, int length) {
ByteBuffer copy = this.buffer.isDirect() ?
ByteBuffer.allocateDirect(length) :
ByteBuffer.allocate(length);
this.buffer.copyInto(index, copy, 0, length);
return copy;
}
@Override
public void toByteBuffer(int srcPos, ByteBuffer dest, int destPos, int length) {
this.buffer.copyInto(srcPos, dest, destPos, length);
}
@Override
public ByteBufferIterator readableByteBuffers() {
return new BufferComponentIterator<>(this.buffer.forEachComponent(), true);
}
@Override
public ByteBufferIterator writableByteBuffers() {
return new BufferComponentIterator<>(this.buffer.forEachComponent(), false);
}
@Override
public String toString(Charset charset) {
Assert.notNull(charset, "Charset must not be null");
return this.buffer.toString(charset);
}
@Override
public String toString(int index, int length, Charset charset) {
Assert.notNull(charset, "Charset must not be null");
byte[] data = new byte[length];
this.buffer.copyInto(index, data, 0, length);
return new String(data, 0, length, charset);
}
@Override
public Netty5DataBuffer touch(Object hint) {
this.buffer.touch(hint);
return this;
}
@Override
public void close() {
this.buffer.close();
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof Netty5DataBuffer that && this.buffer.equals(that.buffer)));
}
@Override
public int hashCode() {
return this.buffer.hashCode();
}
@Override
public String toString() {
return this.buffer.toString();
}
private static final class BufferComponentIterator<T extends BufferComponent & ComponentIterator.Next>
implements ByteBufferIterator {
private final ComponentIterator<T> delegate;
private final boolean readable;
@Nullable
private T next;
public BufferComponentIterator(ComponentIterator<T> delegate, boolean readable) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
this.readable = readable;
this.next = readable ? this.delegate.firstReadable() : this.delegate.firstWritable();
}
@Override
public boolean hasNext() {
return this.next != null;
}
@Override
public ByteBuffer next() {
if (this.next != null) {
ByteBuffer result;
if (this.readable) {
result = this.next.readableBuffer();
this.next = this.next.nextReadable();
}
else {
result = this.next.writableBuffer();
this.next = this.next.nextWritable();
}
return result;
}
else {
throw new NoSuchElementException();
}
}
@Override
public void close() {
this.delegate.close();
}
}
}
|
package com.example.jordi.printerpartner.activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.jordi.printerpartner.R;
import com.unforce.imagen.collection.PrinterStatus;
public class PrinterErrorActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_printer_error);
//Get extra's from intent
Intent intent = getIntent();
String warning = intent.getStringExtra("warning");
String printer = intent.getStringExtra("printer");
String details = intent.getStringExtra("details");
//Get UI elements
TextView tvInfotext = (TextView)findViewById(R.id.lblInfotext);
TextView tvPrinter = (TextView)findViewById(R.id.lblPrinter);
TextView tvDetailsText = (TextView)findViewById(R.id.lblDetailstext);
ImageView ivPrinterIcon = (ImageView)findViewById(R.id.imageView);
//Fill UI elements
tvInfotext.setText(warning);
tvPrinter.setText(printer);
tvDetailsText.setText(details);
//Set printer icon
/* if (warning.equals(PrinterStatus.BUSY) || warning.equals(PrinterStatus.IDLE)){
ivPrinterIcon.setImageResource(R.drawable.printericon);
}
else if (warning.equals(PrinterStatus.ERROR)){
ivPrinterIcon.setImageResource(R.drawable.printericon_rood);
}
else if(warning.equals(PrinterStatus.OFF)){
ivPrinterIcon.setImageResource(R.drawable.printericon_grijs);
}
else if(warning.equals(PrinterStatus.WARNING)){
ivPrinterIcon.setImageResource(R.drawable.printericon_oranje);
}*/
}
}
|
package com.lmz;
public class ListTest {
public static void main(String[]args){
//通过循环将0~4 之间的5 个数放到的数组data[]中
int[]data=new int[5];
for(int i=1;i<5;i++){
data[i]=i;
System.out.println(data[i]);
}
String[]str=new String[3];
str[0]="小明";
str[1]="小红";
str[2]="小黄";
for(int j=0;j<=2;j++) {
System.out.println(str[j]);
}
//直接为定义的数组分配元素的方式更为简便
String[]str2={"bananas","apples","pears","oranges"};
for (int k=0;k<str2.length;k++){
System.out.println(str2[k]);
}
}
}
|
package Lecture3;
import jdk.dynalink.beans.StaticClass;
import java.util.Scanner;
import java.util.Random;
public class Homework {
public static void main(String[] args) {
//Question 1
/*
Scanner userInput = new Scanner(System.in);
System.out.println("Is the temperature high, low, or humid?");
String temp = userInput.nextLine();
System.out.println(" ");
switch (temp) {
case "high":
System.out.println("Sunblock may be needed");
case "low":
System.out.println("A coat may be needed");
case "humid":
System.out.println("It's muggy");
}
*/
/*
//Question 2
int rand1 = (int) (Math.random() * 12) + 1;
String month;
switch (rand1) {
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
default:
month = "Invalid month";
}
System.out.println(month);
}
*/
/*
//Question 3
String firstName = "Christopher";
//use substring method on firstName to extract and print Chris
firstName.substring(0,5);
String name = firstName.substring(0,5);
System.out.println(name);
//use method to compare 2 strings
firstName.compareTo(name);
int compareStr = firstName.compareTo(name);
System.out.println("The diffence in length is " + compareStr + " Characters");
//use stringbuilder to append 2 strings
StringBuilder string = new StringBuilder();
string.append(name).append("topher");
System.out.println(string);
*/
/*
//Question 4
for(int x = 10; x > 0; x--) {
System.out.println(x);
if(x == 5) {
continue;
}
}
*/
/*
int x = 10;
while(x > 0) {
System.out.println(x);
x--;
}
*/
/*
for(int x = 1; x < 6; x++) {
System.out.println(x);
if(x == 3) {
break;
}
*/
}
}
|
package oop;
public class Bathroom {
private int walls;
private int toilets;
private int showers;
private int baths;
private int mirror;
private Area area;
public int getWalls() {
return walls;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public void setWalls(int walls) {
this.walls = walls;
}
public int getToilets() {
return toilets;
}
public void setToilets(int toilets) {
this.toilets = toilets;
}
public int getShowers() {
return showers;
}
public void setShowers(int showers) {
this.showers = showers;
}
public int getBaths() {
return baths;
}
public void setBaths(int baths) {
this.baths = baths;
}
public int getMirror() {
return mirror;
}
public void setMirror(int mirror) {
this.mirror = mirror;
}
public Bathroom(int walls, int toilets, int showers, int baths, int mirror,Area area) {
super();
this.walls = walls;
this.toilets = toilets;
this.showers = showers;
this.baths = baths;
this.mirror = mirror;
this.area=area;
}
public void flushtoilet(){
System.out.println("flush the toilet flush flush flush");
}
}
|
package com.dmtrdev.monsters.utils;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.utils.Disposable;
import com.dmtrdev.monsters.DefenderOfNature;
public class MusicManager implements Disposable {
private Music mMusic;
private final Options mOptions;
public MusicManager(final Options pOptions) {
mOptions = pOptions;
mMusic = getGameMenuMusic();
play();
}
public void setVolume(final float pVolume){
mMusic.setVolume(pVolume);
}
public void changeMusic(final boolean pFlag) {
stop();
if (pFlag) {
mMusic = getGameMusic();
} else {
mMusic = getGameMenuMusic();
}
play();
}
public void stop() {
mMusic.stop();
}
public void pause(){
mMusic.pause();
}
public void play() {
if (mOptions.getMusicCheck()) {
mMusic.setLooping(true);
mMusic.setVolume(mOptions.getMusicVolume());
mMusic.play();
}
}
public static Music getGameMenuMusic() {
return DefenderOfNature.manager.get("music/game_menu_music.mp3", Music.class);
}
public static Music getGameMusic() {
return DefenderOfNature.manager.get("music/game_music.mp3", Music.class);
}
@Override
public void dispose() {
mMusic.dispose();
}
}
|
package com.union.express.web.stowagecore.stowage.service;
import com.union.express.commons.query.BaseJpaService;
import com.union.express.web.stowagecore.stowage.jpa.dao.IStowageRepository;
import com.union.express.web.stowagecore.stowage.model.Stowage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by wq on 2016/10/22.
*/
@Service
@Transactional
public class StowageService extends BaseJpaService<Stowage,IStowageRepository> {
}
|
package hibernate_test;
import hibernate_test.entity.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;
/** Класс для получения списка работников, удовлетворяющих запросу.
* Для примера я получал список всех работников с именем "Timur" и
* зарплатой больше 1000. Таких работников в таблице 2, в результате
* работы метода main на экран выводятся 2 работника, удовлетворяющие
* параметрам запроса*/
public class GetEmpsQuery {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
try {
Session session = factory.getCurrentSession();
session.beginTransaction();
List<Employee> emps = session.createQuery("from Employee " +
"where name= 'Timur' AND salary > 1000")
.getResultList();
for (Employee e: emps) {
System.out.println(e);
}
session.getTransaction().commit();
System.out.println("DONE!");
}
finally {
factory.close();
}
}
}
|
package com.codingchili.instance.model.skills;
import com.codingchili.core.context.CoreRuntimeException;
/**
* @author Robin Duda
*/
public class SkillNotLearnedException extends CoreRuntimeException {
public SkillNotLearnedException(SkillType skill) {
super("Skill not learned " + skill.name());
}
}
|
package cn.mccreefei.web.config;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.util.Properties;
/**
* @author MccreeFei
* @create 2018-01-19 16:10
*/
@Configuration
@Slf4j
@MapperScan(basePackages = "cn.mccreefei.zhihu.dao.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class MybatisConfig {
private Environment env;
@Bean
public DataSource dataSource() throws Exception {
Properties properties = new Properties();
properties.setProperty(DruidDataSourceFactory.PROP_DRIVERCLASSNAME,
env.getProperty("spring.datasource.driver-class-name"));
properties.setProperty(DruidDataSourceFactory.PROP_URL,
env.getProperty("spring.datasource.url"));
properties.setProperty(DruidDataSourceFactory.PROP_USERNAME,
env.getProperty("spring.datasource.username"));
properties.setProperty(DruidDataSourceFactory.PROP_PASSWORD,
env.getProperty("spring.datasource.password"));
return DruidDataSourceFactory.createDataSource(properties);
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource){
try {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(env.getProperty("mybatis.mapperLocations")));
sessionFactory.setConfigLocation(new DefaultResourceLoader()
.getResource(env.getProperty("mybatis.configLocation")));
return sessionFactory.getObject();
}catch (Exception e){
log.error("初始化sqlSessionFactory失败!", e);
return null;
}
}
@Autowired
public void setEnvironment(Environment environment) {
this.env = environment;
}
}
|
package com.qumla.service.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import com.qumla.domain.image.Image;
import com.qumla.service.impl.ImageDaoMapper;
public class ImageDaoTest extends AbstractTest {
@Before
public void before() {
super.before(ImageDaoMapper.class);
}
@Test
public void createImage(){
ImageDaoMapper mapper=(ImageDaoMapper)getMapper(ImageDaoMapper.class);
Image q=new Image();
q.setPath("/image.png");
q.setTitle("én nevem");
q.setDominant("#fffffff");
q.setType(2);
q.setStatus(2);
mapper.insertImage(q);
Image retImg=mapper.findOne(q.getId());
assertNotNull(retImg);
assertNotNull(retImg.getId());
assertNotNull(retImg.getDominant());
assertNotNull(retImg.getPath());
assertEquals("én nevem", retImg.getTitle());
assertNotNull(retImg.getType());
assertNotNull(retImg.getStatus());
retImg.setStatus(1);
mapper.updateImage(retImg);
Image retImg2=mapper.findOne(retImg.getId());
assertEquals((Integer)1, retImg2.getStatus());
}
}
|
package net.lvcy.card.entity.number;
public interface BlackCard extends NumberCard{
}
|
package calculator.parser;
import calculator.MathContext.EvaluationContext;
abstract public class AbstractParser implements MathExpressionParser {
protected void skipTransparentCharacters(EvaluationContext context) {
context.skipWhitespaces();
}
protected boolean confirm(EvaluationContext context, String symbolRepresentation) {
skipTransparentCharacters(context);
final String current = context.getMathExpression().substring(context.getCurrentPosition());
if (current.startsWith(symbolRepresentation)) {
context.setCurrentPosition(context.getCurrentPosition() + symbolRepresentation.length());
return true;
}
return false;
}
}
|
package buttley.nyc.esteban.magicbeans.entitysystem.components;
/**
* Created by Tara on 3/1/2015.
*/
public class Component {
}
|
package controller;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import model.Employee;
import service.EmployeeService;
import service.EmployeeServiceImpl;
@ManagedBean
@SessionScoped
public class EmployeeController {
private String name;
private String surname;
private int salary;
private List<Employee> employees=new ArrayList<>();
public void addEmployee() {
EmployeeService employeeService=new EmployeeServiceImpl();
Employee employee=new Employee(name, surname, salary);
employeeService.save(employee);
employees=employeeService.findAll();
}
public void deleteEmployee(int id) {
EmployeeService employeeService=new EmployeeServiceImpl();
employeeService.remove(id);
employees=employeeService.findAll();
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
|
package com.neuedu.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.neuedu.pojo.Boys;
import java.util.List;
public interface BoyMapper extends BaseMapper<Boys> {
List<Boys> selectList();
}
|
/**
* Contains mock request and response types for the imperative HTTP client
*/
@NonNullApi
@NonNullFields
package org.springframework.web.testfixture.http.client;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
/*
* Copyright 2014 Victor Melnik <annimon119@gmail.com>, and
* individual contributors as indicated by the @authors tag.
*
* 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.annimon.jecp.me;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
/**
* Load and save preferences to the record store.
* @author aNNiMON
*/
public final class Prefs {
private static final String RMS_NAME = "jecp_prefs";
private static RecordStore rmsStore;
public static byte[] load() {
try {
rmsStore = RecordStore.openRecordStore(RMS_NAME, true);
return rmsStore.getRecord(1);
} catch (RecordStoreException ex) {
rmsStore = null;
}
return null;
}
public static void save(byte[] data) {
try {
rmsStore = RecordStore.openRecordStore(RMS_NAME, true);
rmsStore.setRecord(1, data, 0, data.length);
} catch (InvalidRecordIDException ridex) {
try {
rmsStore.addRecord(data, 0, data.length);
} catch (RecordStoreException ex) { }
} catch (RecordStoreException ex) {
}
if (rmsStore != null) {
try {
rmsStore.closeRecordStore();
rmsStore = null;
} catch (RecordStoreException ex) { }
}
}
}
|
/**
*
* @author Matthew Clayton
* @version January 3, 2015
* @assign.ment Shopping Cart
* @descrip.tion This class represents a shopping cart,
* containing varying items of different names and prices
* associated with ItemV2MC objects. This class allows the user
* to continue adding items as he or she sees fit, and then prints
* a subtotal when the user elects to be done.
*
*
*/
import java.util.Arrays;
import java.util.Scanner;
public class ShoppingCartV2MC {
int capacity;
double subtotal;
ItemV2MC[] cart;
public ShoppingCartV2MC() { // constructor for class ShoppingCartV2MC
capacity = 10;
subtotal = 0.00;
cart = new ItemV2MC[capacity];
}
public static void main(String[] args) {
ShoppingCartV2MC shopCart = new ShoppingCartV2MC(); // new object
// declare variables for ItemV2MC object assignments
String curItemName;
double curItemPrice;
int curItemQuantity;
Scanner scan = new Scanner(System.in); // scanner for user input
int cartLocation = 0; // track placement in array cart
int cartStart = 0; // for holding start position for loop argument
boolean keepShopping = true; // conditional on shopping loop
String keepGoing; // whether or not to keep shopping
System.out.println("Welcome to shopping.");
System.out.println("For each item, please input the name, "
+ "price in dollars, and quantity on separate lines.\n");
while (keepShopping == true) {
// get current item values
System.out.print("Please give the name of the item: ");
curItemName = scan.nextLine();
System.out.print("Please enter the item price "
+ "in the format xx.xx: $");
curItemPrice = scan.nextDouble();
System.out.print("Please enter a whole number value "
+ "for the quantity of the item: ");
curItemQuantity = scan.nextInt();
// loop through each individual item
for (int i = cartLocation; i < curItemQuantity + cartStart; i++) {
try { // check for space in cart
shopCart.cart[cartLocation] = new ItemV2MC(curItemName,
curItemPrice);
} catch (ArrayIndexOutOfBoundsException e) {
shopCart.increaseSize();
shopCart.cart[cartLocation] = new ItemV2MC(curItemName,
curItemPrice);
}
cartLocation++; // advance to next position in cart
}
cartStart = cartLocation; // start position for loop adding items
System.out.print("If you would like to quit shopping, "
+ "enter 'q', otherwise enter any other key to continue: ");
keepGoing = scan.nextLine();
keepGoing = scan.nextLine();
if (keepGoing.equalsIgnoreCase("q")) // if wants to quit
keepShopping = false; // avoid continuation of loop
else
System.out.println(); // blank line before next item
}
scan.close(); // close scanner resource
// add together item prices
for (int i = 0; i < shopCart.cart.length; i++) {
try { // check that there is an item
shopCart.subtotal += shopCart.cart[i].getPrice();
} catch (NullPointerException e) { // if no item, end loop
break;
}
}
// print price to nearest whole cent
System.out.printf("\nPlease pay $" + "%.2f", shopCart.subtotal);
}
// ---------------------------------------------------------
// Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
public void increaseSize() {
cart = Arrays.copyOf(cart, cart.length + 3); // copy array to new array
// of current size + 3
capacity += 3; // add three spaces
}
}
|
package dao;
import java.util.List;
import vo.deptVO;
public interface myDAO {
public String getDeptName(int deptno);
public List<deptVO> getList();
public int dataCount();
public deptVO getData(int deptno);
}
|
package com.cpro.rxjavaretrofit.entity;
/**
* Created by lx on 2016/6/20.
*/
public class TaskDetailFormEntity {
// 任务ID
private Integer taskId;
// 当前角色ID
private String memberRoleId;
// 是否是我参与的
private String isMine;
// 任务类型
private String taskType;
// 图片前缀
private String httpUrl;
// 任务成员列表ID
private Integer taskMemberId;
// 领取状态 0,未领取;1,已领取
private String getStatus;
// 当前角色
private String memberRole;
public Integer getTaskId() {
return taskId;
}
public void setTaskId(Integer taskId) {
this.taskId = taskId;
}
public String getMemberRoleId() {
return memberRoleId;
}
public void setMemberRoleId(String memberRoleId) {
this.memberRoleId = memberRoleId;
}
public String getIsMine() {
return isMine;
}
public void setIsMine(String isMine) {
this.isMine = isMine;
}
public String getTaskType() {
return taskType;
}
public void setTaskType(String taskType) {
this.taskType = taskType;
}
public String getHttpUrl() {
return httpUrl;
}
public void setHttpUrl(String httpUrl) {
this.httpUrl = httpUrl;
}
public Integer getTaskMemberId() {
return taskMemberId;
}
public void setTaskMemberId(Integer taskMemberId) {
this.taskMemberId = taskMemberId;
}
public String getGetStatus() {
return getStatus;
}
public void setGetStatus(String getStatus) {
this.getStatus = getStatus;
}
public String getMemberRole() {
return memberRole;
}
public void setMemberRole(String memberRole) {
this.memberRole = memberRole;
}
}
|
package mod3wk1hw2;
import java.util.*;
public class HashsetToArray {
public static void main(String[] args) {
HashSet<String> hash = new HashSet<String>();
hash.add("alex");
hash.add("ben");
hash.add("caesar");
hash.add("dillon");
hash.add("eunice");
System.out.println("HashSet has: "+ hash);
//converting to array
String[] arr = new String[hash.size()];
hash.toArray(arr);
// Displaying Array elements
System.out.println("Array elements: ");
for(String temp : arr){
System.out.println(temp);
}
}
}
|
package com.cs.devcode;
import com.cs.payment.Currency;
import com.cs.payment.DCEventType;
import com.cs.payment.DCPaymentTransaction;
import com.cs.payment.Money;
import com.google.common.base.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.math.BigDecimal;
import java.util.Date;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
/**
* @author Hadi Movaghar
*/
@XmlRootElement
@XmlAccessorType(FIELD)
public class CancelRequest {
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.userId.notNull")
private String userId;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.authCode.notNull")
private String authCode;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.txAmount.notNull")
private BigDecimal txAmount;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.txCurrency.notNull")
private String txAmountCy;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.txId.notNull")
private String txId;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.txTypeId.notNull")
private Integer txTypeId;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.txName.notNull")
private String txName;
@XmlElement
@Nonnull
@NotNull(message = "cancelRequest.provider.notNull")
private String provider;
@XmlElement
@Nullable
private String accountId;
@XmlElement
@Nullable
private String maskedAccount;
@XmlElement
@Nullable
private String statusCode;
@XmlElement
@Nullable
private String pspStatusCode;
@XmlElement
@Nullable
private Attributes attributes;
public CancelRequest() {
}
@Nonnull
public String getUserId() {
return userId;
}
public DCPaymentTransaction getDCPaymentTransaction() {
final DCPaymentTransaction dcPaymentTransaction = new DCPaymentTransaction();
dcPaymentTransaction.setDcEventType(DCEventType.CANCEL);
dcPaymentTransaction.setAuthorizationCode(authCode);
dcPaymentTransaction.setAmount(new Money(txAmount));
dcPaymentTransaction.setCurrency(Currency.valueOf(txAmountCy));
dcPaymentTransaction.setTransactionId(txId);
dcPaymentTransaction.setTransactionType(txTypeId);
dcPaymentTransaction.setTransactionName(txName);
dcPaymentTransaction.setTransactionProvider(provider);
dcPaymentTransaction.setAccountId(accountId);
dcPaymentTransaction.setMaskedAccount(maskedAccount);
dcPaymentTransaction.setStatusCode(statusCode);
dcPaymentTransaction.setPspStatusCode(pspStatusCode);
dcPaymentTransaction.setAttributes(attributes != null ? attributes.getAllAttributes() : null);
dcPaymentTransaction.setCreatedDate(new Date());
dcPaymentTransaction.setSuccess(true);
return dcPaymentTransaction;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("userId", userId)
.add("authCode", authCode)
.add("txAmount", txAmount)
.add("txCurrency", txAmountCy)
.add("txId", txId)
.add("txTypeId", txTypeId)
.add("txName", txName)
.add("provider", provider)
.add("accountId", accountId)
.add("maskedAccount", maskedAccount)
.add("statusCode", statusCode)
.add("pspStatusCode", pspStatusCode)
.add("attributes", attributes)
.toString();
}
}
|
public class DebitCard implements Payment {
@Override
public void paymentmethod() {
System.out.println(" Payment Through dabitCard");
}
}
|
package com.tu.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* @Description
* @Classname RedisApplication redis 服务的启动类
* @Date 2019/4/28 14:05
* @Created by tuyongjian
*/
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class,args);
}
}
|
package nxpense.controller;
import nxpense.domain.Tag;
import nxpense.dto.TagDTO;
import nxpense.dto.TagResponseDTO;
import nxpense.exception.CustomErrorCode;
import nxpense.exception.RequestCannotCompleteException;
import nxpense.helper.TagConverter;
import nxpense.message.CustomResponseHeader;
import nxpense.service.api.TagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaOptimisticLockingFailureException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping("/tag")
public class TagController {
private static final Logger LOGGER = LoggerFactory.getLogger(TagController.class);
@Autowired
private TagService tagService;
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<TagResponseDTO> createTag(@RequestBody TagDTO tagDto) {
try {
Tag persistedTag = tagService.createNewTag(tagDto);
TagResponseDTO tagResponseDto = TagConverter.entityToResponseDto(persistedTag);
return new ResponseEntity<TagResponseDTO>(tagResponseDto, HttpStatus.CREATED);
} catch (RequestCannotCompleteException taee) {
LOGGER.error("Tag already exists for current user", taee);
HttpHeaders customHeaders = new HttpHeaders();
customHeaders.put(CustomResponseHeader.SERVERSIDE_VALIDATION_ERROR_MSG.name(), Arrays.asList(taee.getMessage()));
return new ResponseEntity<TagResponseDTO>(customHeaders, HttpStatus.CONFLICT);
}
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<TagResponseDTO>> getCurrentUserTags() {
List<Tag> currentUserTags = tagService.getCurrentUserTags();
List<TagResponseDTO> responseTags = new ArrayList<TagResponseDTO>();
for(Tag tag : currentUserTags) {
responseTags.add(TagConverter.entityToResponseDto(tag));
}
return new ResponseEntity(responseTags, HttpStatus.OK);
}
@RequestMapping(value = "/{tagId}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<Void> deleteTag(@PathVariable Integer tagId) {
tagService.deleteTag(tagId);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
@RequestMapping(value = "/{tagId}", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<TagResponseDTO> updateTag(@PathVariable Integer tagId, @RequestBody TagDTO tagBody) {
Tag updatedTag = tagService.updateTag(tagId, tagBody);
TagResponseDTO tagResponseDTO = TagConverter.entityToResponseDto(updatedTag);
return new ResponseEntity(tagResponseDTO, HttpStatus.OK);
}
@ExceptionHandler(value = {JpaOptimisticLockingFailureException.class})
public void translateExceptionFromEclipseLink(HttpServletResponse response) {
response.setStatus(CustomErrorCode.ENTITY_OUT_OF_SYNC.getHttpStatus());
try {
PrintWriter writer = response.getWriter()
.append("The tag item you working on has been updated/deleted by another session. Please reload tags and retry...");
writer.flush();
writer.close();
} catch (IOException e) {
LOGGER.error("An error occurred when writing custom HTTP error code to HTTP response", e);
}
}
}
|
package samples;
import gui.Gradient;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
public class HeatMapDemo extends JFrame implements ItemListener, FocusListener
{
private HeatMap panel;
private JCheckBox drawLegend;
private JCheckBox drawTitle;
private JCheckBox drawXTitle;
private JCheckBox drawXTicks;
private JCheckBox drawYTitle;
private JCheckBox drawYTicks;
private JTextField textTitle;
private JTextField textXTitle;
private JTextField textYTitle;
private JTextField textXMin;
private JTextField textXMax;
private JTextField textYMin;
private JTextField textYMax;
private JTextField textFGColor;
private JTextField textBGColor;
private JComboBox gradientComboBox;
private ImageIcon[] icons;
private String[] names =
{
"GRADIENT_BLACK_TO_WHITE", "GRADIENT_BLUE_TO_RED",
"GRADIENT_GREEN_YELLOW_ORANGE_RED", "GRADIENT_HEAT", "GRADIENT_HOT",
"GRADIENT_RAINBOW", "GRADIENT_RED_TO_GREEN"
};
private Color[][] gradients =
{
Gradient.BLACK_TO_WHITE, Gradient.BLUE_TO_RED,
Gradient.GREEN_YELLOW_ORANGE_RED, Gradient.HEAT, Gradient.HOT,
Gradient.RAINBOW, Gradient.RED_TO_GREEN
};
public HeatMapDemo() throws Exception
{
super ("Heat Map Demo");
// gui stuff to demonstrate options
JPanel listPane = new JPanel ();
listPane.setLayout (new GridBagLayout ());
listPane.setBorder (BorderFactory.createTitledBorder ("Heat Map Demo"));
GridBagConstraints gbc;
gbc = new GridBagConstraints ();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets (2, 1, 0, 0);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START;
drawTitle = new JCheckBox ("Draw Title");
drawTitle.setSelected (true);
drawTitle.addItemListener (this);
listPane.add (drawTitle, gbc);
gbc.gridy = GridBagConstraints.RELATIVE;
drawLegend = new JCheckBox ("Draw Legend");
drawLegend.setSelected (true);
drawLegend.addItemListener (this);
listPane.add (drawLegend, gbc);
drawXTitle = new JCheckBox ("Draw X-Axis Title");
drawXTitle.setSelected (true);
drawXTitle.addItemListener (this);
listPane.add (drawXTitle, gbc);
drawXTicks = new JCheckBox ("Draw X-Axis Ticks");
drawXTicks.setSelected (true);
drawXTicks.addItemListener (this);
listPane.add (drawXTicks, gbc);
drawYTitle = new JCheckBox ("Draw Y-Axis Title");
drawYTitle.setSelected (true);
drawYTitle.addItemListener (this);
listPane.add (drawYTitle, gbc);
drawYTicks = new JCheckBox ("Draw Y-Axis Ticks");
drawYTicks.setSelected (true);
drawYTicks.addItemListener (this);
listPane.add (drawYTicks, gbc);
listPane.add (Box.createVerticalStrut (30), gbc);
JLabel label = new JLabel ("Title:");
listPane.add (label, gbc);
textTitle = new JTextField ();
textTitle.addFocusListener (this);
listPane.add (textTitle, gbc);
label = new JLabel ("X-Axis Title:");
listPane.add (label, gbc);
textXTitle = new JTextField ();
textXTitle.addFocusListener (this);
listPane.add (textXTitle, gbc);
label = new JLabel ("Y-Axis Title:");
listPane.add (label, gbc);
textYTitle = new JTextField ();
textYTitle.addFocusListener (this);
listPane.add (textYTitle, gbc);
listPane.add (Box.createVerticalStrut (30), gbc);
// 14 is next row number
gbc.gridwidth = 1;
gbc.weightx = 1.0;
label = new JLabel ("X min:");
gbc.gridx = 0;
gbc.gridy = 14;
listPane.add (label, gbc);
textXMin = new JTextField ();
textXMin.addFocusListener (this);
gbc.gridy = 15;
listPane.add (textXMin, gbc);
label = new JLabel ("X max:");
gbc.gridx = 1;
gbc.gridy = 14;
listPane.add (label, gbc);
textXMax = new JTextField ();
textXMax.addFocusListener (this);
gbc.gridy = 15;
listPane.add (textXMax, gbc);
label = new JLabel ("Y min:");
gbc.gridx = 2;
gbc.gridy = 14;
listPane.add (label, gbc);
textYMin = new JTextField ();
textYMin.addFocusListener (this);
gbc.gridy = 15;
listPane.add (textYMin, gbc);
label = new JLabel ("Y max:");
gbc.gridx = 3;
gbc.gridy = 14;
listPane.add (label, gbc);
textYMax = new JTextField ();
textYMax.addFocusListener (this);
gbc.gridy = 15;
listPane.add (textYMax, gbc);
gbc.gridx = 0;
gbc.gridy = 16;
gbc.gridwidth = GridBagConstraints.REMAINDER;
listPane.add (Box.createVerticalStrut (30), gbc);
label = new JLabel ("FG Color:");
gbc.gridx = 0;
gbc.gridy = 17;
gbc.gridwidth = 2;
listPane.add (label, gbc);
textFGColor = new JTextField ();
textFGColor.addFocusListener (this);
gbc.gridy = 18;
listPane.add (textFGColor, gbc);
label = new JLabel ("BG Color:");
gbc.gridx = 2;
gbc.gridy = 17;
listPane.add (label, gbc);
textBGColor = new JTextField ();
textBGColor.addFocusListener (this);
gbc.gridy = 18;
listPane.add (textBGColor, gbc);
gbc.gridx = 0;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.weightx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
listPane.add (Box.createVerticalStrut (30), gbc);
// ----------------------------------------------------------------------
label = new JLabel ("Gradient:");
listPane.add (label, gbc);
icons = new ImageIcon[names.length];
Integer[] intArray = new Integer[names.length];
for (int i = 0; i < names.length; i++)
{
intArray[i] = Integer.valueOf (i);
icons[i] = createImageIcon ("images/" + names[i] + ".gif");
}
gradientComboBox = new JComboBox (intArray);
ComboBoxRenderer renderer = new ComboBoxRenderer ();
gradientComboBox.setRenderer (renderer);
gradientComboBox.addItemListener (this);
listPane.add (gradientComboBox, gbc);
// ----------------------------------------------------------------------
double[][] data = HeatMap.generateSinCosData (201);
// you can use a pre-defined gradient:
panel = new HeatMap (data, Gradient.BLACK_TO_WHITE);
gradientComboBox.setSelectedIndex (0);
// set miscellaneous settings
panel.setDrawLegend (true);
panel.setTitle ("Height");
textTitle.setText ("Height");
panel.setDrawTitle (true);
panel.setXAxisTitle ("X-Distance (m)");
textXTitle.setText ("X-DIstance (m)");
panel.setDrawXAxisTitle (true);
panel.setYAxisTitle ("Y-Distance (m)");
textYTitle.setText ("Y-DIstance (m)");
panel.setDrawYAxisTitle (true);
panel.setCoordinateBounds (0, 6.28, 0, 6.28);
textXMin.setText ("0");
textXMax.setText ("6.28");
textYMin.setText ("0");
textYMax.setText ("6.28");
panel.setDrawXTicks (true);
panel.setDrawYTicks (true);
panel.setColorForeground (Color.black);
textFGColor.setText ("000000");
panel.setColorBackground (Color.white);
textBGColor.setText ("FFFFFF");
this.getContentPane ().add (listPane, BorderLayout.EAST);
this.getContentPane ().add (panel, BorderLayout.CENTER);
}
public void focusGained (final FocusEvent e)
{
}
public void focusLost (final FocusEvent e)
{
Object source = e.getSource ();
if (source == textTitle)
{
panel.setTitle (textTitle.getText ());
}
else if (source == textXTitle)
{
panel.setXAxisTitle (textXTitle.getText ());
}
else if (source == textYTitle)
{
panel.setYAxisTitle (textYTitle.getText ());
}
else if (source == textXMin)
{
double d;
try
{
d = Double.parseDouble (textXMin.getText ());
panel.setXMinCoordinateBounds (d);
}
catch (Exception ex)
{
}
}
else if (source == textXMax)
{
double d;
try
{
d = Double.parseDouble (textXMax.getText ());
panel.setXMaxCoordinateBounds (d);
}
catch (Exception ex)
{
}
}
else if (source == textYMin)
{
double d;
try
{
d = Double.parseDouble (textYMin.getText ());
panel.setYMinCoordinateBounds (d);
}
catch (Exception ex)
{
}
}
else if (source == textYMax)
{
double d;
try
{
d = Double.parseDouble (textYMax.getText ());
panel.setYMaxCoordinateBounds (d);
}
catch (Exception ex)
{
}
}
else if (source == textFGColor)
{
String c = textFGColor.getText ();
if (c.length () != 6)
return;
Color color = colorFromHex (c);
if (color == null)
return;
panel.setColorForeground (color);
}
else if (source == textBGColor)
{
String c = textBGColor.getText ();
if (c.length () != 6)
return;
Color color = colorFromHex (c);
if (color == null)
return;
panel.setColorBackground (color);
}
}
private Color colorFromHex (final String c)
{
try
{
int r = Integer.parseInt (c.substring (0, 2), 16);
int g = Integer.parseInt (c.substring (2, 4), 16);
int b = Integer.parseInt (c.substring (4, 6), 16);
float rd = r / 255.0f;
float gd = g / 255.0f;
float bd = b / 255.0f;
return new Color (rd, gd, bd);
}
catch (Exception e)
{
return null;
}
}
public void itemStateChanged (final ItemEvent e)
{
Object source = e.getItemSelectable ();
if (source == drawLegend)
{
panel.setDrawLegend (e.getStateChange () == ItemEvent.SELECTED);
}
else if (source == drawTitle)
{
panel.setDrawTitle (e.getStateChange () == ItemEvent.SELECTED);
}
else if (source == drawXTitle)
{
panel.setDrawXAxisTitle (e.getStateChange () == ItemEvent.SELECTED);
}
else if (source == drawXTicks)
{
panel.setDrawXTicks (e.getStateChange () == ItemEvent.SELECTED);
}
else if (source == drawYTitle)
{
panel.setDrawYAxisTitle (e.getStateChange () == ItemEvent.SELECTED);
}
else if (source == drawYTicks)
{
panel.setDrawYTicks (e.getStateChange () == ItemEvent.SELECTED);
}
else
{
// must be from the combo box
Integer ix = (Integer) e.getItem ();
if (e.getStateChange () == ItemEvent.SELECTED)
{
panel.updateGradient (gradients[ix]);
}
}
}
// this function will be run from the EDT
private static void createAndShowGUI () throws Exception
{
HeatMapDemo hmd = new HeatMapDemo ();
hmd.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
hmd.setSize (800, 600);
hmd.setVisible (true);
}
public static void main (final String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
try
{
createAndShowGUI ();
}
catch (Exception e)
{
System.err.println (e);
e.printStackTrace ();
}
}
});
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon (final String path)
{
// java.net.URL imgURL = getClass().getResource (path);
// if (imgURL != null)
// return new ImageIcon (imgURL);
if (new File (path).exists())
return new ImageIcon (path);
System.err.println ("Couldn't find file: " + path);
return null;
}
class ComboBoxRenderer extends JLabel implements ListCellRenderer
{
public ComboBoxRenderer ()
{
setOpaque (true);
setHorizontalAlignment (LEFT);
setVerticalAlignment (CENTER);
}
public Component getListCellRendererComponent (final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus)
{
int selectedIndex = ((Integer) value).intValue ();
if (isSelected)
{
setBackground (list.getSelectionBackground ());
setForeground (list.getSelectionForeground ());
}
else
{
setBackground (list.getBackground ());
setForeground (list.getForeground ());
}
ImageIcon icon = icons[selectedIndex];
setIcon (icon);
setText (names[selectedIndex].substring (9));
return this;
}
}
}
|
/*
* 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 io.github.minhaz1217.onlineadvising.models;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
*
* @author Minhaz
*/
@Document(collection = "Student")
public class Student {
@Id @GeneratedValue
private String id;
private String firstName;
private String lastName;
private String email;
private String studentId;
private ArrayList<CourseExtended> taken;
private ArrayList<CourseDescription> advising;
private Student(){
taken = new ArrayList<>();
advising = new ArrayList<>();
}
public Student(String firstName, String lastName, String email, String studentId, ArrayList<CourseExtended> taken) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.studentId = studentId;
this.taken = taken;
advising = new ArrayList<>();
}
public Student(String firstName, String lastName, String email, String studentId, ArrayList<CourseExtended> taken, ArrayList<CourseDescription> advising) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.studentId = studentId;
this.taken = taken;
this.advising = advising;
}
public ArrayList<CourseDescription> getAdvising() {
return advising;
}
public void setAdvising(ArrayList<CourseDescription> advising) {
this.advising = advising;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public ArrayList<CourseExtended> getTaken() {
return taken;
}
public void setTaken(ArrayList<CourseExtended> taken) {
this.taken = taken;
}
}
|
package mx.com.gm.sga.servicio;
import datos.ClienteDao;
import dominio.Cliente;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
public class ClienteServiceImpl implements ClienteServiceRemote, ClienteService{
@Inject
private ClienteDao clienteDao;
@Override
public List<Cliente> listarClientes() {
return clienteDao.findAllClientes();
}
@Override
public Cliente encontrarClientePorId(Cliente cliente) {
return clienteDao.findClienteById(cliente);
}
@Override
public Cliente encontrarClientePorEmail(Cliente cliente) {
return clienteDao.findClienteByEmail(cliente);
}
@Override
public void registrarCliente(Cliente cliente) {
clienteDao.insertCliente(cliente);
}
@Override
public void modificarCliente(Cliente cliente) {
clienteDao.updateCliente(cliente);
}
@Override
public void eliminarCliente(Cliente cliente) {
clienteDao.deleteCliente(cliente);
}
@Override
public List<Cliente> listarCliente() {
return clienteDao.listar();
}
}
|
package edu.vt.jsonviewgenerator.factory;
import android.content.Context;
import android.content.Intent;
import android.graphics.RectF;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import com.mobsandgeeks.saripaar.Validator;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import edu.vt.datawidgets.calendar.WeekView;
import edu.vt.datawidgets.calendar.WeekViewEvent;
import edu.vt.jsonviewgenerator.R;
import edu.vt.jsonviewgenerator.activities.CalendarDetailActivity;
import edu.vt.jsonviewgenerator.common.interfaces.ActionHandler;
import edu.vt.jsonviewgenerator.common.interfaces.WidgetFactory;
import edu.vt.jsonviewgenerator.util.HTTPCmd;
/**
* Created by Juzer on 10/27/2015.
*/
public class CalendarFactory implements WidgetFactory {
@Override
public View generateWidget(final Context context, JSONObject jsonObject, Validator validator, ActionHandler actionHandler) throws JSONException {
String size = jsonObject.getString("size");
View layout;
int layoutId = -1;
switch (size){
case "full":
{
layoutId = R.layout.layout_calendar_full;
break;
}
case "half":
{
// TODO: load half screen xml layout
break;
}
default:
throw new UnsupportedOperationException("invalid size parameter");
}
layout = LayoutInflater.from(context).inflate(layoutId, null);
WeekView weekView = (WeekView) layout.findViewById(R.id.weekView);
weekView.setId(View.generateViewId());
weekView.setTag(jsonObject.getString("key"));
/**
* Right now it is done on the local thread.
* TODO: I hope to move all data rendering to a separate worker thread later
*/
JSONObject events = HTTPCmd.getJsonResults(Uri.parse(jsonObject.getString("event-src")));
if(events != null) weekView.setJsonEvents(events);
weekView.setOnEventClickListener(new WeekView.EventClickListener(){
@Override
public void onEventClick(WeekViewEvent weekViewEvent, RectF rectF) {
Intent intent = new Intent(context, CalendarDetailActivity.class);
intent.putExtra(CalendarDetailActivity.EXTRA_DESCRIPTION, weekViewEvent.getDescription());
context.startActivity(intent);
}
});
return layout;
}
@Override
public void setAdditionalParams(Pair<String, Object>... pairs) {
}
}
|
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Fibbonaci {
private static int seeds;
public static void main(String[] args) throws IOException {
File input = new File("C:\\Users\\Carlos\\Desktop\\fibonacci_hard.in");
FileReader in = new FileReader(input);
BufferedReader buf = new BufferedReader(in);
int numLines = Integer.parseInt(buf.readLine());
ArrayList[] lines = new ArrayList[numLines];
for (int i = 0; i < numLines ; i++) {
lines[i] = new ArrayList<String>();
lines[i].add(buf.readLine());
String[] s;
s = lines[i].toString().split(" ");
String[] str = new String[s.length];
for (int j = 0; j < s.length; j++) {
str[j] = s[j];
str[j] = str[j].replace("[", "");
str[j] = str[j].replace("]", "");
}
int[] a = new int[str.length];
ArrayList<Integer> AL= new ArrayList<Integer>();
for (int j = 0; j < a.length; j++) {
int n = Integer.parseInt(str[j]);
AL.add(n);
}
int x = 0;
x = makeSequence(AL);
System.out.println(x);
}
}
public static int makeSequence(ArrayList<Integer> a){
//
int max = (int) Math.pow(2,30);
int newNum;
int sum = 0;
seeds = a.size();
for (int i = 0; i < seeds; i++) {
//sum += a.get(i);
sum = (a.get(i)+ sum) % max;
}
for (int i = seeds - 1; i < 99999; i++) {
newNum = 0;
for (int j = 0; j < seeds; j++){
//newNum += a.get(i - j);
newNum = (newNum + a.get(i - j)) % max;
}
a.add(newNum);
//sum += newNum;
sum = (sum + newNum) % max;
}
return sum;
}
}
|
/* Group.java
Purpose:
Description:
History:
2001/10/23 23:50:54, Create, Tom M. Yeh.
Copyright (C) 2001 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.idom;
import java.util.List;
import java.util.Set;
import java.util.Collection;
/**
* Represents an item might have children. Group is also a item.
* Developers usually extend new classes from
* {@link org.zkoss.idom.impl.AbstractGroup}, rather than
* implement this interface directly.
*
* <p>Design consideration: we don't support removeChildren and setChild
* or alike, because they can be done easily with List's methods and
* getAttributeIndex.
*
* @author tomyeh
* @see Item
* @see Attributable
* @see Namespaceable
* @see Binable
*/
public interface Group extends Item {
/**
* Gets all children.
*
* <p>The returned list is "live". Any modification to it affects
* the node. On the other hand, {@link #getElements(String)} returns
* a copy.
*
* <p>Unlike JDOM, it won't coalesce adjacent children automatically
* since it might violate the caller's expection about List.
* Rather, we provide coalesce to let caller do the merging
* explicity.
* Note: when building a iDOM tree from a source
* (SAXBuilder.build), coalesce() will be inovked automatically.
*
* <p>Note: not all items supports children. If this item doesn't,
* it returns an empty list. And, if any invocation tries to add
* vertices to the returned list will cause UnsupportOperationException.
*/
public List getChildren();
/** Detaches all children and returns them in a list.
*
* <p>Note: you cannot add children to anther Group by doing
* <code>group.addAll(e.getChildren())</code>, because you have to detach
* them first. Then, you could use this method:<br>
* <code>group.addAll(e.detachChildren());</code>
*/
public List detachChildren();
/**
* Coalesces children if they are siblings with the same type
* instances of Textual, Textual.isCoalesceable returns true.
*
* <p>SAXBuilder.build will do the merging automatically.
*
* @param recursive true to coalesce all descendants;
* false to coalesce only the direct children
*/
public int coalesce(boolean recursive);
/**
* Gets the index of the Element-type first child that match the specified
* criteria.
*
* <p>Note: only Element-type children are returned, since others
* have no name.
*
* @param indexFrom the index to start searching from; 0 for beginning
* @param namespace the namspace URI if FIND_BY_PREFIX is not specified;
* the namespace prefix if FIND_BY_PREFIX specified; null to ingore
* @param name the local name if FIND_BY_TAGNAME is not sepcified;
* the tag name if FIND_BY_TAGNAME specified; null to ignore
* @param mode the serach mode; zero or any combination of
* Item.FIND_xxx, except FIND_RECURSIVE
* @return the index if found; -1 if not found
*/
public int
getElementIndex(int indexFrom, String namespace, String name, int mode);
/**
* Gets the index of the first Element-type child with the specified name.
*
* <p>Note: only Element-type children are returned, since others
* have no name.
*
* <p><code><pre>getChildren().add(getElementIndex(0, "pre:name"),
* new Element("pre:another"));</pre></code>
*
* @param indexFrom the index to start searching from; 0 for beginning
* @param tname the tag name (i.e., Namespaceable.getName)
* @return the index if found; -1 if not found
*/
public int getElementIndex(int indexFrom, String tname);
/**
* Gets the value of the first Element-type child that matches
* the giving criteria, with a trimming option.
*
* @param namespace the namspace URI if FIND_BY_PREFIX is not specified;
* the namespace prefix if FIND_BY_PREFIX specified; null to ingore
* @param name the local name if FIND_BY_TAGNAME is not sepcified;
* the tag name if FIND_BY_TAGNAME specified; null to ignore
* @return the value of the first Element-type child ; null if not found
*/
public String
getElementValue(String namespace, String name, int mode, boolean trim);
/**
* Gets the text of the first Element-type child with the tag name,
* with a trimming option.
*
* @param tname the tag name (i.e., Namespaceable.getName)
* @return the text of the first Element-type child with
* the tag name; null if not found
*/
public String getElementValue(String tname, boolean trim);
/**
* Gets the first Element-type child that matches the giving criteria.
*
* <p>Note: only Element-type children are returned. Depending on
* the mode, the searching is usually linear -- take O(n) to complete.
*
* @param namespace the namspace URI if FIND_BY_PREFIX is not specified;
* the namespace prefix if FIND_BY_PREFIX specified; null to ingore
* @param name the local name if FIND_BY_TAGNAME is not sepcified;
* the tag name if FIND_BY_TAGNAME specified; null to ignore
* @param mode the search mode; zero or any combination of FIND_xxx.
* @return the found element; null if not found or not supported
*/
public Element getElement(String namespace, String name, int mode);
/**
* Gets the first Element-type child with the tag name.
* It is the same as childOf(nsURI, lname, null, 0).
*
* <p>Note: only Element-type children are returned. Also, we did some
* optimization for this method so its access time is nearly constant.
*
* @param tname the tag name (i.e., Namespaceable.getName)
* @return the found element; null if not found or not supported
*/
public Element getElement(String tname);
/**
* Gets a readonly list of Element-type children that match the giving
* criteria.
*
* <p>Unlike {@link Element#getElementsByTagName}, this method only
* returns child elements, excluding grand children and other descedants.
*
* <p>The returned list is a 'live-facade' of the real ones, so
* the performance is good, and any modification to {@link #getChildren}
* will affect it.
*
* <p>Note: only Element-type children are returned. Depending on
* the mode, the searching is usually linear -- take O(n) to complete.
*
* @param namespace the namspace URI if FIND_BY_PREFIX is not specified;
* the namespace prefix if FIND_BY_PREFIX specified; null to ingore
* @param name the local name if FIND_BY_TAGNAME is not sepcified;
* the tag name if FIND_BY_TAGNAME specified; null to ignore
* @param mode the search mode; zero or any combination of FIND_xxx.
* @return a read-only list containing all matched children;
* an empty list if not found or not supported
*/
public List getElements(String namespace, String name, int mode);
/**
* Gets a readonly list of children with the tag name.
*
* <p>Unlike {@link Element#getElementsByTagName}, this method only
* returns child elements, excluding grand children and other descedants.
*
* <p>The returned list is a 'live-facade' of the real ones, so
* the performance is good, and any modification to {@link #getChildren}
* will affect it.
*
* <p>Note: only Element-type children are returned. Also, we did some
* optimization for this method so its access time is nearly constant.
*
* @param tname the tag name (i.e., Namespaceable.getName)
*/
public List getElements(String tname);
/** Returns a readonly set of names of element children.
* Then, you could use {@link #getElements} to get elements.
*
* <p>The returned list is a 'live-facade' of the real ones, so
* the performance is good, and any modification to {@link #getChildren}
* will affect it.
*
* @see #getElements()
*/
public Set getElementNames();
/** Returns a cloned copy of all element childrens
*
* <p>Unlike {@link #getChildren} and {@link #getElementNames},
* the returned list is NOT a 'live-facade' of the real ones.
*
* @see #getElementNames()
*/
public List getElements();
}
|
package br.com.infoCenter.excecao;
public class ProdutoException extends Exception {
private static final long serialVersionUID = 1L;
public ProdutoException() {
super();
}
public ProdutoException(String mensagem) {
super(mensagem);
}
}
|
package com.project.services;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.project.entities.Product;
import com.project.entities.Review;
import com.project.entities.User;
import com.project.repos.ReviewRepository;
import com.project.services.interfaces.ReviewServiceI;
//service class that wraps the data access for review
//and provides application logic
@Service
public class ReviewService implements ReviewServiceI {
@Autowired
private ReviewRepository revRepo;
@Override
public List<Review> getAllActiveForProduct(Product product) {
if (product == null)
return null;
return revRepo.findByProductId(product.getId());
}
@Override
public Review saveReview(Review review) {
if (review == null)
return null;
review.setDate(new Date());
return revRepo.save(review);
}
@Override
public Review updateReview(Review review) {
if (review == null)
return null;
Review found = revRepo.findById(review.getId()).orElse(null);
if (found == null)
return null;
found.setDetails(review.getDetails());
found.setMark(review.getMark());
found.setDate(new Date());
return revRepo.save(found);
}
@Override
public Review findCustomerReview(User user, List<Review> reviews) {
for (Review r : reviews)
if (r.getReviewerUsername().equals(user.getUsername()))
return r;
return null;
}
@Override
public Review getById(Review review) {
return revRepo.findById(review.getId()).orElse(null);
}
@Override
public Review deleteReview(Review review) {
if (review == null)
return null;
revRepo.delete(review);
return review;
}
@Override
public List<Review> getAll() {
return revRepo.findAll();
}
}
|
package com.esum.framework.core.resource;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
public class BaseTestCase extends AbstractDependencyInjectionSpringContextTests {
protected String[] getConfigLocations() {
return new String[] { "classpath:/context/resource_context.xml" };
}
public BaseTestCase(String method) {
super(method);
}
public void testResource() {
System.out.println("test");
}
}
|
package com.example.consumer.entity;
public class MessageTest {
private String messageNo;
private String messageName;
private String messageNumber;
private String messageContext;
public MessageTest() {
}
public MessageTest(String messageNo, String messageName, String messageNumber, String messageContext) {
this.messageNo = messageNo;
this.messageName = messageName;
this.messageNumber = messageNumber;
this.messageContext = messageContext;
}
@Override
public String toString() {
return "MessageTest{" +
"messageNo='" + messageNo + '\'' +
", messageName='" + messageName + '\'' +
", messageNumber='" + messageNumber + '\'' +
", messageContext='" + messageContext + '\'' +
'}';
}
public String getMessageNo() {
return messageNo;
}
public void setMessageNo(String messageNo) {
this.messageNo = messageNo;
}
public String getMessageName() {
return messageName;
}
public void setMessageName(String messageName) {
this.messageName = messageName;
}
public String getMessageNumber() {
return messageNumber;
}
public void setMessageNumber(String messageNumber) {
this.messageNumber = messageNumber;
}
public String getMessageContext() {
return messageContext;
}
public void setMessageContext(String messageContext) {
this.messageContext = messageContext;
}
}
|
package com.huaxiao47.just4fun.ui.home.live;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class HomeLiveViewModel extends ViewModel {
// TODO: Implement the ViewModel
}
|
package com.chandlerobaker.alcchallenge.android.journalapp;
import com.chandlerobaker.alcchallenge.android.journalapp.utilities.Utils;
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.assertEquals;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class UtilsUnitTest {
@Test
public void formatDate_isCorrect() {
Date date = new Date();
assertEquals(date.getHours()+":"+date.getMinutes(), Utils.formatDate(date));
}
@Test
public void contractString_isCorrect() {
assertEquals("Test completed successfully", Utils.contractString("Test completed successfully"));
assertEquals("This project was about to create an android app which can permit users to write theirs diaries. So I thought it like...", Utils.contractString("This project was about to create an android app which can permit users to write theirs diaries. So I thought it like a numeric intima journal where people can easily write their thoughts (stories, moto, etc.). For that to also make a difference between this app and the other ones I add something called mood. There is up to now 6 different moods in the app (happy, angry, love, sad, tired, sick). So a user has the possibility to specify how he feels when writing his thought or what this new diary entry is related to."));
}
}
|
package com.myspring.service;
import java.util.List;
import com.myspring.bean.Job;
public interface JobService {
/**
* 获取所有的job数量
* @return
*/
int getCountJobs();
/**
* 获取所有job信息
* @Title: getJobs
* @Description: TODO(方法简要描述,必须以句号为结束)
* @author: Administrator
* @since: (开始使用的版本)
* @return
*/
List<Job> getJobs();
}
|
package strategy;
//Concrete strategy
public class Rooster implements Animal {
public String attack(String target) {
return "To peck " + target + "!!!";
}
}
|
package com.tibco.as.util.convert.impl;
import java.nio.ByteBuffer;
public class BytesToInteger extends AbstractBlobConverter<Integer> {
@Override
protected Integer convert(ByteBuffer buffer) {
return buffer.getInt();
}
}
|
package msip.go.kr.cop.web;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import msip.go.kr.common.entity.Tree;
import msip.go.kr.cop.entity.CopMaster;
import msip.go.kr.cop.entity.CopMenu;
import msip.go.kr.cop.service.CopMasterService;
import msip.go.kr.cop.service.CopMenuService;
/**
* 협업룸 메뉴 Controller
* @author junho
*
*/
@Controller
public class CopMenuController {
@Resource(name = "copMenuService")
private CopMenuService copMenuService;
@Resource(name = "copMasterService")
private CopMasterService copMasterService;
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
@RequestMapping(value = "/cop/menu/regist", method = RequestMethod.POST)
@ResponseBody
public String regist(CopMenu entity, Model model) throws Exception {
String message = egovMessageSource.getMessage("success.common.insert");
try {
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
CopMaster master = copMasterService.findById(entity.getCopId());
master.checkOwner(loginVO.getUniqId());
entity.setRegistInfo(loginVO);
entity.setIsuse(true);
entity.setCategory(CopMenu.CTGR_BOARD);
copMenuService.persist(entity);
} catch(Exception e) {
message = egovMessageSource.getMessage("fail.common.insert");
}
return message;
}
@RequestMapping(value = "/cop/menu/update", method = RequestMethod.POST)
@ResponseBody
public String update(CopMenu entity, Model model) throws Exception {
String message = egovMessageSource.getMessage("success.common.update");
try {
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
CopMaster master = copMasterService.findById(entity.getCopId());
master.checkOwner(loginVO.getUniqId());
CopMenu server = copMenuService.findById(entity.getId());
server.setMenuNm(entity.getMenuNm());
server.setOrderSeq(entity.getOrderSeq());
copMenuService.merge(server);
} catch(Exception e) {
message = egovMessageSource.getMessage("fail.common.update");
}
return message;
}
@RequestMapping(value = "/cop/menu/delete/{copId}/{id}", method = RequestMethod.POST)
@ResponseBody
public String delete(@PathVariable Long copId, @PathVariable Long id, Model model) throws Exception {
String message = egovMessageSource.getMessage("success.common.delete");
try {
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
CopMaster master = copMasterService.findById(copId);
master.checkOwner(loginVO.getUniqId());
CopMenu server = copMenuService.findById(id);
server.setIsuse(false);
copMenuService.merge(server);
} catch(Exception e) {
message = egovMessageSource.getMessage("fail.common.delete");
}
return message;
}
/**
* 협업룸 메뉴 관리 페이지로 이동
* @param copId 협업룸 일련번호
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/cop/menu/{copId}")
public String manage(@PathVariable Long copId, Model model) throws Exception {
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
CopMaster cop = copMasterService.findById(copId);
if(loginVO.getUniqId().equals(cop.getRegId())) {
return "msip/cop/menu";
} else {
model.addAttribute("copId", copId);
return "egovframework/com/sec/accessDenied";
}
}
/**
* 협업룸 메뉴 관리 페이지로 이동
* @param copId 협업룸 일련번호
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/cop/menu/find/{id}", method = RequestMethod.GET)
@ResponseBody
public CopMenu find(@PathVariable Long id, Model model) throws Exception {
CopMenu menu = copMenuService.findById(id);
return menu;
}
@RequestMapping(value = "/cop/menu/tree/{copId}", method = RequestMethod.GET)
@ResponseBody
public List<Tree> tree(@PathVariable Long copId, Model model) throws Exception {
List<Tree> treeList = new ArrayList<Tree>();
List<CopMenu> list = copMenuService.FindByCopId(copId);
for(CopMenu entity : list) {
Tree t = new Tree();
t.setId(entity.getId().toString());
t.setParent("#");
t.setText(entity.getMenuNm());
treeList.add(t);
}
return treeList;
}
}
|
package jp.ac.kyushu_u.csce.modeltool.dictionary.dict.column;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import jp.ac.kyushu_u.csce.modeltool.base.dialog.MultiInputDialog2;
import jp.ac.kyushu_u.csce.modeltool.dictionary.Messages;
import jp.ac.kyushu_u.csce.modeltool.dictionary.ModelToolDictionaryPlugin;
import jp.ac.kyushu_u.csce.modeltool.dictionary.constant.DictionaryConstants;
import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.Entry;
import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.TableTab;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* 辞書ビュー 非形式的定義カラムクラス
*
* @author KBK yoshimura
*/
public class InformalColumn extends AbstractColumn {
/** 列番号 */
private int index;
/**
* コンストラクタ
* @param tab
*/
public InformalColumn(TableTab tab, int index) {
super(tab);
this.index = index;
text = Messages.InformalColumn_0 ;
width = 100;
activate = ACTIVATE_TRUE;
}
/**
* カラムIDの取得
*/
public int getId() {
return DictionaryConstants.DIC_COL_ID_INFORMAL;
}
/**
* ヘッダテキストの取得
* @return ヘッダテキスト
*/
public String getHeaderText() {
String langCd = ""; //$NON-NLS-1$
String langName = ""; //$NON-NLS-1$
List<String> languages = tab.getDictionary().getDictionaryClass().languages;
if (index < languages.size()) {
langCd = languages.get(index);
if (StringUtils.isNotBlank(langCd)) {
langName = ModelToolDictionaryPlugin.getLanguageUtil().getLanguageMap().get(langCd);
}
}
if (StringUtils.isNotBlank(langName)) {
return MessageFormat.format(Messages.InformalColumn_2, langName);
} else {
return Messages.InformalColumn_0;
}
}
/**
* セルエディターの取得
* @see org.eclipse.jface.viewers.EditingSupport#getCellEditor(java.lang.Object)
*/
protected CellEditor getCellEditor(final Object element) {
if (editor == null) {
// ダイアログ
editor = new DialogCellEditor(getTableViewer().getTable()) {
/**
* ダイアログを開く
*/
protected Object openDialogBox(Control cellEditorWindow) {
// 編集前の値を退避
preEditValue = getValue();
// 複数行入力ダイアログを開く
MultiInputDialog2 dialog = new MultiInputDialog2(cellEditorWindow.getShell(),
MessageFormat.format(Messages.InformalColumn_1, text),
preEditValue.toString(), 10) {
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
// 未登録モデルの場合、OKボタン不可
if (!isRegisteredModel()) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
}
};
if (dialog.open() == Dialog.OK) {
// // 変更があればdirtyに
// if (preEditValue.equals(dialog.getValue()) == false) {
// tab.setDirty(true);
// }
return dialog.getValue();
} else {
return preEditValue;
}
}
};
// リスナーの追加
// ※DialogCellEditorだと追加されないけど、ほかのカラムと処理を合わせるため入れておく
setCellEditorListener(editor, element);
}
return editor;
}
/**
* 表示テキストの取得
* @see jp.ac.kyushu_u.csce.modeltool.dictionary.dict.column.IColumn#getColumnText(java.lang.Object)
*/
public String getColumnText(Object element) {
// return ((Entry)element).getInformal();
List<String> informals = ((Entry)element).getInformals();
int size = informals.size();
if (size <= this.index) {
for (int i=0; i<=this.index-size; i++) {
informals.add(""); //$NON-NLS-1$
}
}
return informals.get(this.index);
}
/**
* 値の取得
* @see jp.ac.kyushu_u.csce.modeltool.dictionary.dict.column.AbstractColumn#getValue(java.lang.Object)
*/
public Object getValue(Object element) {
// return ((Entry)element).getInformal();
return getColumnText(element);
}
/**
* 値の設定
* @see jp.ac.kyushu_u.csce.modeltool.dictionary.dict.column.AbstractColumn#doSetValue(java.lang.Object, java.lang.Object)
*/
protected void doSetValue(Object element, Object value) {
// ((Entry)element).setInformal((String)value);
List<String> informals = ((Entry)element).getInformals();
// 変更前リストの退避
List<String> oldInformals = new ArrayList<String>(informals);
int size = informals.size();
if (size <= this.index) {
for (int i=0; i<=this.index-size; i++) {
informals.add(""); //$NON-NLS-1$
}
}
informals.set(this.index, (String)value);
// Undoヒストリの追加
// tab.getHistoryManager().add(new History(
// History.TYPE_CELL,
// getId(),
// DictionaryUtil.getMode(),
// tab.getDictionary().indexOf((Entry)element),
// oldInformals,
// new ArrayList<String>(informals),
// tab.isDirty(),
// true));
tab.getHistoryHelper().addCellHisotry(
tab.getDictionary().indexOf((Entry)element), getId(), oldInformals, new ArrayList<String>(informals));
}
/**
* 編集可否の判定
* @see jp.ac.kyushu_u.csce.modeltool.dictionary.dict.column.AbstractColumn#canEdit(java.lang.Object)
*/
protected boolean canEdit(Object element) {
// 編集カラムがチェックされている場合は、編集不可
return ((Entry)element).isEdit()? false : super.canEdit(element);
}
/**
* 複数カラム
* @see jp.ac.kyushu_u.csce.modeltool.dictionary.dict.column.IColumn#multiple()
*/
public boolean multiple() {
return true;
}
}
|
package org.test.ht;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class DFS {
private static class Graph {
int val;
List<Graph> children;
public Graph(int val) {
this.val = val;
}
}
public static void dfs(Graph graph) {
for (Graph g : graph.children) {
process(g.val);
dfs(g);
}
}
public static void process(Integer value) {
System.out.println(value);
}
public static void main(String[] args) {
Graph graph = new Graph(1);
Graph graph1 = new Graph(2);
Graph graph2 = new Graph(3);
Graph graph3 = new Graph(4);
Graph graph4 = new Graph(5);
Graph graph5 = new Graph(6);
Graph graph6 = new Graph(7);
Graph graph7 = new Graph(8);
Graph graph8 = new Graph(9);
Graph graph9 = new Graph(10);
Graph graph10 = new Graph(11);
graph.children.addAll(Arrays.asList(graph1, graph2, graph3));
graph1.children.addAll(Arrays.asList(graph4, graph5));
graph2.children.addAll(Arrays.asList(graph6, graph7, graph8));
graph4.children.addAll(Arrays.asList(graph9, graph10));
dfs(graph);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.