text
stringlengths 10
2.72M
|
|---|
package org.point85.domain.email;
import org.point85.domain.messaging.ApplicationMessage;
/**
* Listener for events received via email
*
*/
public interface EmailMessageListener {
/**
* Perform processing of a received {@link ApplicationMessage}
*
* @param message ApplicationMessage
*/
void onEmailMessage(ApplicationMessage message);
}
|
package edu.school.masivi;
import java.util.Scanner;
public class Zadacha3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner k = new Scanner(System.in);
int n = k.nextInt();
int [] arr = new int[n];
for(int i=0; i<arr.length; i++) {
arr[i] = k.nextInt();
}
int m = k.nextInt();
int [] arr2 = new int[m];
for(int i=0; i<arr2.length; i++) {
arr2[i] = k.nextInt();
}
int j = 0;
for(int i=0; i<arr.length; i++) {
for(j=0; j<arr2.length; j++) {
if(arr[i] == arr2[j]) {
System.out.println(arr2[j]);
}
}
j=0;
}
}
}
|
package com.cts.bta.model;
public enum TransactionType {
INCOME,EXPENSE
}
|
package resource;
public class Feedback {
}
|
public class AsynchRequest {
//private static final int ARRAY_SIZE = 2100000000;
private static final int ARRAY_SIZE = 1300000000;
//private static final int ARRAY_SIZE = 1000000;
//private static final int ARRAY_SIZE = 700000;
private static final int NUMBER_OF_SERVERS = 4;
public static void main(String[] args)
{
/*
* Feld erzeugen, jeder 10. Wert = true
*/
boolean[] array = new boolean[ARRAY_SIZE];
for (int i = 0; i< ARRAY_SIZE; i++)
{
if (i % 10 == 0) // alternativ if (Math.random() < 0.1)
{
array[i] = true;
}
else
{
array[i] = false;
}
}
// Startzeit messen
long startTime = System.currentTimeMillis();
// Feld für Services und Thread erzeugen
Service[] service = new Service[NUMBER_OF_SERVERS];
Thread[] serverThread = new Thread[NUMBER_OF_SERVERS];
// Threads erzeugen
int start = 0;
int end;
int howMany = ARRAY_SIZE / NUMBER_OF_SERVERS;
for (int i= 0; i < NUMBER_OF_SERVERS; i++)
{
if (i < NUMBER_OF_SERVERS - 1)
{
end = start + howMany - 1;
}
else
{
end = ARRAY_SIZE -1;
}
service[i] = new Service(array, start, end);
serverThread[i] = new Thread(service[i]);
serverThread[i].start();
start = end + 1;
}
// Synchronisation mit Servern (auf Serverende warten)
for (int i = 0; i < NUMBER_OF_SERVERS; i++)
{
try
{
serverThread[i].join();
}
catch(InterruptedException e)
{
}
}
// Gesamtergebnis aus Teilergebnissen berechnen
int result = 0;
int h;
for (int i = 0; i <NUMBER_OF_SERVERS; i++)
{
h = service[i].getResult();
result += h;
service[i].getResult();
}
// Endzeit messen
long endTime = System.currentTimeMillis();
float time = ( endTime - startTime) / 1000.0f;
System.out.println("Rechenzeit: " + time);
// Ergebnis ausgeben
System.out.println("Ergebnis: " + result);
}
}
|
package DataSets;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
@Entity
@Table(name = "Answers")
public class AnswersDataSet {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, insertable = true, updatable = true)
@JsonProperty("id")
private int id;
@Column(name = "answer_text", nullable = false, length = 255)
@JsonProperty("answer_text")
private String answer_text;
@Column(name = "teacher_comment", length = 255)
@JsonProperty("teacher_comment")
private String teacher_comment;
@Column(name = "isRight", nullable = false)
@JsonProperty("isRight")
private boolean isRight;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "test_id")
@JsonIgnore
private TestsDataSet test_id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "question_id")
@JsonIgnore
private QuestionsDataSet question_id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="student_id")
@JsonIgnore
private StudentsDataSet student_id;
public AnswersDataSet() {
}
public AnswersDataSet(String answer_text, String teacher_comment, boolean right) {
this.answer_text = answer_text;
this.teacher_comment = teacher_comment;
this.isRight = right;
}
public AnswersDataSet(String answer_text, boolean right) {
this.answer_text = answer_text;
this.isRight = right;
}
public AnswersDataSet(String answer_text) {
this.answer_text = answer_text;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswer_text() {
return answer_text;
}
public void setAnswer_text(String answer_text) {
this.answer_text = answer_text;
}
public String getTeacher_comment() {
return teacher_comment;
}
public void setTeacher_comment(String teacher_comment) {
this.teacher_comment = teacher_comment;
}
public boolean isRight() {
return isRight;
}
public void setRight(boolean right) {
this.isRight = right;
}
public TestsDataSet getTest_id() {
return test_id;
}
public void setTest_id(TestsDataSet test_id) {
this.test_id = test_id;
}
public QuestionsDataSet getQuestion_id() {
return question_id;
}
public void setQuestion_id(QuestionsDataSet question_id) {
this.question_id = question_id;
}
public StudentsDataSet getStudent_id() {
return student_id;
}
public void setStudent_id(StudentsDataSet student_id) {
this.student_id = student_id;
}
}
|
package tema02;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.filechooser.FileNameExtensionFilter;
public class GestiuneInterface extends JFrame{
private String pathProd;
private String pathTax;
private String pathFact;
private boolean flag = false;
public GestiuneInterface () {
super("ShopFactory");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Gestiune g = Gestiune.getInstance();
JFileChooser fileChooser = new JFileChooser();
File project = new File(System.getProperty("user.dir"));
fileChooser.setCurrentDirectory(project);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
fileChooser.setAcceptAllFileFilterUsed(false);
JLabel prodLabel = new JLabel("Incarcati fisierul cu produsele: ");
JLabel taxLabel = new JLabel("Incarcati fisierul cu taxele: ");
JLabel factLabel = new JLabel("Incarcati fisierul cu facturile: ");
JButton prodButton = new JButton("Rasfoire");
JButton taxButton = new JButton("Rasfoire");
JButton factButton = new JButton("Rasfoire");
JButton outButton = new JButton("Creare Fisier");
JButton backButton = new JButton("Meniul Principal");
JLabel title = new JLabel("Pagina de creare a fisierului de output");
setLayout(new BorderLayout());
JPanel top = new JPanel(new FlowLayout());
JPanel center = new JPanel(new FlowLayout());
JPanel left = new JPanel(new GridLayout(2,1));
JPanel middle = new JPanel(new GridLayout(2,1));
JPanel right = new JPanel(new GridLayout(2,1));
JPanel bottom = new JPanel(new FlowLayout());
top.add(title);
bottom.add(outButton);
bottom.add(backButton);
left.add(prodLabel);
left.add(prodButton);
middle.add(taxLabel);
middle.add(taxButton);
right.add(factLabel);
right.add(factButton);
center.add(left);
center.add(middle);
center.add(right);
add(top, BorderLayout.NORTH);
add(center, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
prodButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == prodButton)
fileChooser.setDialogTitle("Deschideti fisierul cu produsele");
if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
pathProd = fileChooser.getSelectedFile().getAbsolutePath();
}
}
});
taxButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
fileChooser.setDialogTitle("Deschideti fisierul cu taxele");
if(e.getSource() == taxButton)
if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
pathTax = fileChooser.getSelectedFile().getAbsolutePath();
}
}
});
factButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == factButton){
fileChooser.setDialogTitle("Deschideti fisierul cu facturile");
if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
pathFact = fileChooser.getSelectedFile().getAbsolutePath();
g.setMagazin(pathProd, pathTax, pathFact);
}
}
}
});
outButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == outButton){
if(pathProd == null || pathTax == null || pathFact == null){
JOptionPane.showMessageDialog(null,
"Unul sau mai multe din cele 3 fisiere nu au fost selectate!","Eroare", JOptionPane.ERROR_MESSAGE);
} else if(!flag){
JOptionPane.showMessageDialog(null,
"Fisierul a fost creat cu succes!","Succes", JOptionPane.INFORMATION_MESSAGE);
g.scriereFisier();
flag = true;
try {
Desktop.getDesktop().open(new File("out.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null,
"Fisierul a fost deja creat!","Atentie", JOptionPane.WARNING_MESSAGE);
}
}
}
});
backButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == backButton){
StartPage start = new StartPage();
dispose();
}
}
});
setSize(600,200);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
}
|
package corpse.ui;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import utils.ImageTools;
import utils.Utils;
import corpse.CORPSE;
import corpse.Script;
import file.FileUtils;
public class Menus
{
private static final String ABOUT = "About";
private static final String EXIT = "Exit";
private static final String EXPORT = "Export";
private static final String HELP = "Help";
private static final String OPTIONS = "Options";
private static final String PROMPTS = "Prompts";
private static final String REFRESH = "Refresh";
public static final String ROLL = "Roll";
private static final String SEARCH = "Search";
private ActionListener buttonListener = new ButtonListener();
// private About about;
private Map<String, JComponent> invokers = new HashMap<String, JComponent>();
private CORPSE app;
private JMenuBar menus;
public Menus(final CORPSE app)
{
this.app = app;
menus = makeMenus();
}
public JMenuBar getMenus()
{
enable();
return menus;
}
private JMenuBar makeMenus()
{
JMenuBar menubar = new JMenuBar();
menubar.add(makeMainMenu());
menubar.add(makeHelpMenu());
return menubar;
}
private JMenu makeMainMenu()
{
JMenu menu = new JMenu("File");
menu.setMnemonic('F');
menu.add(makeMenuItem(SEARCH, 'S', "20/objects/Magnify.gif", "Search all data files for an entered pattern"));
menu.add(makeMenuItem(EXPORT, 'x', "20/documents/DocumentUse.gif", "Export the current view to a file"));
menu.add(makeMenuItem(REFRESH, 'R', "20/flow/Loop.gif", "Reload the data"));
menu.add(makeMenuItem(OPTIONS, 'O', "20/gui/Form.gif", "Edit configuration options"));
menu.add(makeCheckItem(PROMPTS, 'P', "20/objects/QueryChoose.gif", true, null, "Toggle interactive script prompts"));
menu.addSeparator();
menu.add(makeMenuItem(EXIT, 'E', "XRed.gif", "Exit this application"));
return menu;
}
private JMenu makeHelpMenu()
{
JMenu menu = new JMenu(HELP);
menu.setMnemonic('H');
menu.add(makeMenuItem(ABOUT, 'A', "20/markers/SignInformation.gif", "Show infomation about this application"));
menu.add(makeMenuItem(HELP, 'H', "20/gui/Help.gif", "How do I use this?"));
return menu;
}
private JMenuItem makeMenuItem(final String label, final char mnemonic, final String icon, final String tip)
{
JMenuItem mi = new JMenuItem(label);
mi.setMnemonic(mnemonic);
mi.setToolTipText(tip);
if (icon != null)
mi.setIcon(ImageTools.getIcon("icons/" + icon));
mi.addActionListener(buttonListener);
invokers.put(label, mi);
return mi;
}
private JCheckBoxMenuItem makeCheckItem(final String label, final char mnemonic, final String iconFile, final boolean state,
final ButtonGroup group, final String tipText)
{
JCheckBoxMenuItem mi;
ImageIcon icon = ImageTools.getIcon("icons/" + iconFile);
if (icon != null)
mi = new JCheckBoxMenuItem(label, icon, state);
else
mi = new JCheckBoxMenuItem(label, state);
mi.setHorizontalTextPosition(SwingConstants.RIGHT);
mi.setMnemonic(mnemonic);
mi.setActionCommand(label);
mi.setToolTipText(tipText);
mi.addActionListener(buttonListener);
if (group != null)
group.add(mi);
invokers.put(label, mi);
return mi;
}
public JButton makeButton(final String command, final String iconName, final String tip)
{
JButton button = new JButton();
if (iconName != null)
{
button.setIcon(ImageTools.getIcon(iconName));
button.setMargin(new Insets(0, 0, 0, 0));
}
else
button.setText(command);
button.setActionCommand(command);
button.setToolTipText(tip);
button.addActionListener(buttonListener);
invokers.put(command, button);
return button;
}
class ButtonListener implements ActionListener
{
@Override
public void actionPerformed(final ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals(ABOUT))
about();
else if (cmd.equals(EXIT))
System.exit(0);
else if (cmd.equals(EXPORT))
app.export();
else if (cmd.equals(HELP))
showFile("data/readme.txt", "CORPSE Quick Help");
else if (cmd.equals(OPTIONS))
setOptions();
else if (cmd.equals(PROMPTS))
Script.togglePrompts();
else if (cmd.equals(REFRESH))
app.refresh();
else if (cmd.equals(ROLL))
app.roll();
else if (cmd.equals(SEARCH))
app.search();
else
{
Toolkit.getDefaultToolkit().beep();
app.setText("Unsupported command: " + cmd);
}
}
}
private void enable()
{
// invokers.get (CLEAR_A).setEnabled (chars);
}
private void about()
{
JOptionPane.showMessageDialog(app.getMainPanel(), "Version 0.7 beta", "About CORPSE", JOptionPane.INFORMATION_MESSAGE);
/*
* if (about == null) about = new About ("data", "Splash.jpg");
*
* String title = "About CORPSE"; JFrame frame = (JFrame) app.mainPanel.getTopLevelAncestor(); JDialog window = new JDialog
* (frame, title, true); window.add (about); window.pack(); Utils.centerComponent (window); window.setVisible (true);
*/
}
private void setOptions()
{
// options.configure ((JFrame) app.mainPanel.getTopLevelAncestor());
enable();
}
private void showFile(final String file, final String title)
{
String s = FileUtils.getText(file);
JTextArea text = new JTextArea(s);
text.setEditable(false);
JPanel panel = new JPanel();
panel.setBorder(Utils.BORDER);
panel.add(text);
JOptionPane.showMessageDialog(app.getMainPanel(), panel, title, JOptionPane.INFORMATION_MESSAGE);
}
}
|
package business.model;
public class VacationDirector {
protected VacationBuilder vacBuilder;
public VacationDirector(VacationBuilder vacBuilder) {
this.vacBuilder = vacBuilder;
}
public void buildKindVacation() {
vacBuilder.buildKindVacation();
}
public Vacation getVacation() {
return vacBuilder.getVacation();
}
}
|
package ankang.springcloud.dashboard;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
/**
* @author: ankang
* @email: dreedisgood@qq.com
* @create: 2021-01-06
*/
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashBoardApplication9000 {
public static void main(String[] args) {
SpringApplication.run(HystrixDashBoardApplication9000.class , args);
}
}
|
package work;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamMain {
public static void main(String[] args) {
// creat a list and filter even all even numbers from list
List<Integer> list1 = new ArrayList<>();
list1.add(2);
list1.add(6);
list1.add(12);
list1.add(23);
List<Integer> list2 = Arrays.asList(23, 16, 34, 55, 98);
List<Integer> list3 = Arrays.asList(2, 4, 50, 21, 22, 67);
// list1
// without stream
List<Integer> listEven = new ArrayList<>();
for (Integer integer : list1) {
if (integer % 2 == 0) {
listEven.add(integer);
}
}
System.out.println(list1);
System.out.println(listEven);
// using streamAPI
List<Integer> newList = list1.stream().filter(num -> num % 2 == 0).collect(Collectors.toList());
System.out.println(newList);
// numbers > 10;
List<Integer> numList = list1.stream().filter(num -> num > 10).collect(Collectors.toList());
System.out.println(numList);
}
}
|
package DP;
/*
Leetcode 263: Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
Input: 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.
考点:数学知识
特别的,1可以是丑数
其他丑数需要满足,只能被2,3,5分解
那么,ugly = 2i3j5k
==> 解法:将丑数不断除以2,3,5,判断剩下的数是否为1即可
*/
public class UglyNumber {
public boolean isUgly(int num) {
if(num == 0) return false;
int[] factors = new int[]{2,3,5};
for(int factor : factors) {
while(num % factor == 0) {
num = num/factor;
}
}
if(num == 1) return true;
return false;
}
}
|
package uk.co.hexeption.thx.utils;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import org.lwjgl.opengl.GL11;
public class GLUtils {
public static void glColor(int color) {
GlStateManager.color((float) (color >> 16 & 255) / 255F, (float) (color >> 8 & 255) / 255F, (float) (color & 255) / 255F, (float) (color >> 24 & 255) / 255F);
}
public static void drawRect(float x, float y, float width, float height) {
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer vertexbuffer = tessellator.getBuffer();
GlStateManager.enableBlend();
GlStateManager.disableTexture2D();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
vertexbuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);
vertexbuffer.pos(x, height, 0.0D).endVertex();
vertexbuffer.pos(width, height, 0.0D).endVertex();
vertexbuffer.pos(width, y, 0.0D).endVertex();
vertexbuffer.pos(x, y, 0.0D).endVertex();
tessellator.draw();
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
}
}
|
package Problem_9084;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
long[] dp = new long[10001];
dp[0] = 1;
for(int t=1; t<=T; t++) {
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int M = Integer.parseInt(br.readLine());
int[] c = new int[N];
for(int i =0 ;i<N; i++) {
c[i] = Integer.parseInt(st.nextToken());
}
for(int i = 0; i<N; i++) {
for(int j = c[i]; j<=M;j++) {
dp[j] += dp[j-c[i]];
}
}
sb.append(dp[M]).append("\n");
Arrays.fill(dp, 0l);
dp[0] = 1;
}
System.out.print(sb.toString());
}
}
|
package com.gxtc.huchuan.ui.deal.leftMenu;
import com.gxtc.commlibrary.utils.ErrorCodeUtil;
import com.gxtc.commlibrary.utils.LogUtil;
import com.gxtc.huchuan.bean.WxResponse;
import com.gxtc.huchuan.data.WxRepository;
import com.gxtc.huchuan.data.WxSource;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.utils.MD5Util;
import java.util.HashMap;
/**
* Created by Steven on 17/3/24.
*/
public class WxLoginPresenter implements WxLoginContract.Presenter {
private WxLoginContract.View mView;
private WxSource mData;
public WxLoginPresenter(WxLoginContract.View mView) {
this.mView = mView;
this.mView.setPresenter(this);
mData = new WxRepository();
}
@Override
public void login(final String userName, String password, String ver) {
password = MD5Util.MD5Encode(password,"");
HashMap<String,String> map = new HashMap<>();
map.put("username",userName);
map.put("pwd",password);
map.put("imgcode",ver);
map.put("f","json");
mView.showLoad();
mData.login(map, new ApiCallBack<WxResponse>() {
@Override
public void onSuccess(WxResponse data) {
if(mView == null) return;
mView.showLoadFinish();
int code = data.getResp().getRet();
LogUtil.i("code : " + code);
String msg = "";
switch (code){
case -1:
msg = "系统错误,请稍候再试。";
break;
case 0:
mView.loginSuccess(data);
break;
case 200002:
msg = "服务器拒绝访问。";
break;
case 200007:
msg = "您目前处于访问受限状态。";
break;
case 200008:
msg = "请输入验证码。";
mView.showVerifcode(userName);
break;
case 200021:
msg = "不存在该帐户。";
break;
case 200023:
msg = "您输入的帐号或者密码不正确,请重新输入。";
break;
case 200025:
msg = "无法登录海外帐号。";
break;
case 200027:
msg = "您输入的验证码不正确,请重新输入。";
mView.showVerifcode(userName);
break;
case 200121:
msg = "该帐号属于微信开放平台。";
break;
}
mView.loginFailed(msg);
}
@Override
public void onError(String errorCode, String message) {
ErrorCodeUtil.handleErr(mView,errorCode,message);
}
});
}
@Override
public void start() {
}
@Override
public void destroy() {
mData.destroy();
mView = null;
}
}
|
package uno.iut.fr.uno;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.DataSetObserver;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import uno.iut.fr.uno.modele.Bluetooth.AcceptServerThread;
import uno.iut.fr.uno.modele.Bluetooth.ConnectClientThread;
import uno.iut.fr.uno.modele.Board;
import uno.iut.fr.uno.modele.Game;
import uno.iut.fr.uno.modele.IStrategyCommandeResolverServer;
import uno.iut.fr.uno.modele.Player;
import uno.iut.fr.uno.modele.carte.Carte;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener{
private Button b1;
public EditText t1;
private ListView l1;
private BluetoothAdapter ba;
private ArrayAdapter mArrayAdapter;
private ArrayList<BluetoothDevice>devices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName());
devices.add(device);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
t1 = (EditText)findViewById(R.id.editText);
l1 = (ListView)findViewById(R.id.listView);
ba = BluetoothAdapter.getDefaultAdapter();
// Register the BroadcastReceiver
mArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1);
devices = new ArrayList<>();
l1.setAdapter(mArrayAdapter);
t1.setText("marche pas");
l1.setOnItemClickListener(this);
AcceptServerThread ast = new AcceptServerThread("Max",ba, this);
ast.start();
}
@Override
public void onResume(){
super.onResume();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStop(){
unregisterReceiver(mReceiver);
super.onStop();
}
public void onClickButtonRecherche (View view){
//Verifier si le Bluetooth existe
t1.setText("hello");
if(ba == null){
Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_LONG).show();
t1.setText("Rien comprendre");
}
//Activer le bluetooth
if (!ba.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on"
, Toast.LENGTH_LONG).show();
t1.setText("block 2");
}
else{
Toast.makeText(getApplicationContext(),"Already on",
Toast.LENGTH_LONG).show();
t1.setText("block 3");
}
Set<BluetoothDevice> pairedDevices = ba.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Log.i("device", device.getUuids().toString());
devices.add(device);
Log.i("device", device.getBluetoothClass().toString());
Log.i("device", device.toString());
Log.i("device", "end");
}
Log.i("device master", UUID.fromString(AcceptServerThread.BT_SERVER_UUID_INSECURE).toString());
}
/*Player p1 = new Player("george");
Player p2 = new Player("charle");
Player p3 = new Player("alband");
Player p4 = new Player("Mark");
ArrayList<Player>players = new ArrayList<>();
players.add(p1);
players.add(p2);
players.add(p3);
players.add(p4);
Board.getInstance().setPlayers(players);
Board.getInstance().giveCarte();
t1.setText(Board.getInstance().toString());*/
}
public void onClickButton2 (View view){
/*Board.getInstance().changeOrderPlayer();
t1.setText(Board.getInstance().toString());*/
//Mettre le télephone visible
/*Intent getVisible = new Intent(BluetoothAdapter.
ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);*/
t1.setText(String.valueOf(mArrayAdapter.getCount()));
Intent intent = new Intent(this, Test.class);
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
ba.startDiscovery();
//startActivity(intent);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("On item click parent : ", parent.toString());
Log.i("On item click parent : ", String.valueOf(parent.getCount()));
Log.i("On item click parent : ", String.valueOf(position));
Log.i("On item click parent : ", parent.getItemAtPosition(position).toString());
Toast.makeText(this, parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
Log.i("Hello Device", "------------------------------");
Log.i("Hello Device", devices.get(position).getName());
Log.i("Hello Device", "------------------------------");
try {
ConnectClientThread cct = new ConnectClientThread(devices.get(position), this);
cct.start();
}catch (Exception e){
Log.e("Connection : ", "Connection echec avec le divice");
}
}
public void setText (Carte carte){
t1.setText(carte.toString());
}
public void onClickStart(View view){
Board.getInstance().setPlayers(IStrategyCommandeResolverServer.getPlayers());
Board.getInstance().giveCarte();
Log.i("En route", "en route");
Toast.makeText(this, Board.getInstance().toString(), Toast.LENGTH_LONG).show();
}
}
|
package com.example.qiyue.mvp_dragger.module;
import com.example.qiyue.mvp_dragger.iview.IView;
import com.example.qiyue.mvp_dragger.presenter.UserPresenter;
import dagger.Module;
import dagger.Provides;
/**
* Created by qiyue on 2016/11/14 0014.
*
* 用来提供依赖的,Presenter 创建时在这里完成的,但Presenter 参数变化我们只需要修改这个类即可
*
* 这里只提供presenter
*/
@Module
public class UserModule {
private IView mainView;
public UserModule(IView mainView){
this.mainView = mainView;
}
@Provides
public UserPresenter provideMyPresenter(){
return new UserPresenter(mainView);
}
}
|
package com.hcl.neo.eloader.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "transport_server_master")
public class TransportServerMaster {
@Id
public String id;
public Long serverId;
public String protocol;
public String host;
public int port;
public String userName;
public String password;
public String type;
public String dispNetworkLoc;
/**
* @return the serverId
*/
public long getServerId() {
return serverId;
}
/**
* @param serverId the serverId to set
*/
public void setServerId(long serverId) {
this.serverId = serverId;
}
/**
* @return the protocol
*/
public String getProtocol() {
return protocol;
}
/**
* @param protocol the protocol to set
*/
public void setProtocol(String protocol) {
this.protocol = protocol;
}
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(int port) {
this.port = port;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the dispNetworkLoc
*/
public String getDispNetworkLoc() {
return dispNetworkLoc;
}
/**
* @param dispNetworkLoc the dispNetworkLoc to set
*/
public void setDispNetworkLoc(String dispNetworkLoc) {
this.dispNetworkLoc = dispNetworkLoc;
}
public TransportServerType getTransportServerType(){
TransportServerType serverType = null;
if(null != this.type){
serverType = TransportServerType.valueFrom(this.type);
}
return serverType;
}
public TransportType getTransportType(){
TransportType xportType = null;
if(null != this.protocol){
xportType = TransportType.valueOf(protocol);
}
return xportType;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @param serverId the serverId to set
*/
public void setServerId(Long serverId) {
this.serverId = serverId;
}
@Override
public String toString() {
return "TransportServerMaster [id=" + id + ", serverId=" + serverId + ", protocol=" + protocol + ", host="
+ host + ", port=" + port + ", userName=" + userName + ", password=" + password + ", type=" + type
+ ", dispNetworkLoc=" + dispNetworkLoc + "]";
}
}
|
package deloitte.forecastsystem_bih.controller;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import deloitte.forecastsystem_bih.commandcenter.CommandCenter;
import deloitte.forecastsystem_bih.filestorage.CheckUploadService;
import deloitte.forecastsystem_bih.filestorage.CopyDataStatusEnum;
import deloitte.forecastsystem_bih.filestorage.CopyUploadToDbService;
import deloitte.forecastsystem_bih.filestorage.FileStorageService;
import deloitte.forecastsystem_bih.filestorage.FileUploadStatusRecord;
import deloitte.forecastsystem_bih.filestorage.ProcessingStatusEnum;
import deloitte.forecastsystem_bih.filestorage.UploadStatusEnum;
import deloitte.forecastsystem_bih.model.Country;
import deloitte.forecastsystem_bih.model.FileUploadTable;
import deloitte.forecastsystem_bih.service.CountryService;
import deloitte.forecastsystem_bih.service.FileUploadTableService;
import java.nio.file.Files;
import java.util.Calendar;
import java.util.Date;
@RestController
@RequestMapping("/upload")
public class FileController {
@Autowired
FileStorageService fileStorageService;
@Autowired
CheckUploadService checkUploadService;
@Autowired
CopyUploadToDbService copyUploadToDbService;
@Autowired
CommandCenter commandCenter;
@Autowired
FileUploadTableService fileUploadTableService;
@Autowired
CountryService countryService;
@PostMapping("/uploadDailyLoad")
public @ResponseBody Object uploadFile(@RequestParam("username") String username, @RequestParam("file") MultipartFile file) {
FileUploadStatusRecord resultRecord = new FileUploadStatusRecord();
System.out.println("Username: " + username);
System.out.println("File: " + file.getName());
System.out.println("Size: " + file.getSize());
System.out.println("File name original: " + file.getOriginalFilename());
fileStorageService.storeFile(file);
Country pCon = countryService.findById(2L);
Date maxDateFromSystem = commandCenter.getMaxLoadDate(pCon);
// cYesterday Date is maxDateFromSystem+1
Calendar cLoadDateYesterday = Calendar.getInstance();
cLoadDateYesterday.setTime(maxDateFromSystem);
cLoadDateYesterday.set(Calendar.HOUR_OF_DAY, 0);
cLoadDateYesterday.set(Calendar.MINUTE, 0);
cLoadDateYesterday.set(Calendar.SECOND, 0);
cLoadDateYesterday.set(Calendar.MILLISECOND, 0);
cLoadDateYesterday.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("-------------------");
checkUploadService.setFilename(file.getOriginalFilename());
checkUploadService.setLoadDate(cLoadDateYesterday.getTime());
checkUploadService.loadFileDate();
System.out.println("Loading values for: " + checkUploadService.getLoadDateFromFile());
if (maxDateFromSystem.compareTo(checkUploadService.getLoadDateFromFile())==0) {
System.out.println("DELETING OLD DATA FROM DATABASE. Import new data.");
commandCenter.runDeleteDataIfNecessery(maxDateFromSystem, pCon);
maxDateFromSystem = commandCenter.getMaxLoadDate(pCon);
}
cLoadDateYesterday.setTime(maxDateFromSystem);
cLoadDateYesterday.set(Calendar.HOUR_OF_DAY, 0);
cLoadDateYesterday.set(Calendar.MINUTE, 0);
cLoadDateYesterday.set(Calendar.SECOND, 0);
cLoadDateYesterday.set(Calendar.MILLISECOND, 0);
cLoadDateYesterday.add(Calendar.DAY_OF_MONTH, 1);
checkUploadService.setLoadDate(cLoadDateYesterday.getTime());
Calendar cLoadDateToday = Calendar.getInstance();
cLoadDateToday.setTime(maxDateFromSystem);
cLoadDateToday.set(Calendar.HOUR_OF_DAY, 0);
cLoadDateToday.set(Calendar.MINUTE, 0);
cLoadDateToday.set(Calendar.SECOND, 0);
cLoadDateToday.set(Calendar.MILLISECOND, 0);
cLoadDateToday.add(Calendar.DAY_OF_MONTH, 2);
UploadStatusEnum uploadStatus = checkUploadService.getStatus();
CopyDataStatusEnum copyStatus = CopyDataStatusEnum.CDS_WAITHING;
ProcessingStatusEnum result = ProcessingStatusEnum.PS_WAIT_FOR_PROCESSING;
if (uploadStatus == UploadStatusEnum.US_FILE_OK) {
System.out.println("File is OK...");
// coping file to DB
copyUploadToDbService.setFilename(file.getOriginalFilename());
copyUploadToDbService.setLoadDate(cLoadDateYesterday.getTime());
if (copyUploadToDbService.copyFileToDb()) {
System.out.println("File is copied to db...");
copyStatus = CopyDataStatusEnum.CDS_OK;
} else {
System.out.println("File is not copied to db...");
copyStatus = CopyDataStatusEnum.CDS_ERROR;
}
System.out.println("-- Weather History");
if (!commandCenter.isWeatherLoaded(checkUploadService.getLoadDateFromFile() , pCon)) { //cLoadDateYesterday.getTime()
if (!commandCenter.runWeatherHistoryService())
result = ProcessingStatusEnum.PS_ERROR_WATHER_HISTORY;
}
System.out.println("-- Weather Forecast");
if (!commandCenter.isWeatherForecastLoaded(cLoadDateToday.getTime(), pCon)) {
if (!commandCenter.runWeatherForecastService())
result = ProcessingStatusEnum.PS_ERROR_WEATHER_FORECAST;
}
// if (commandCenter.runWeatherHistoryService()) {
// // Ok, next
// if (commandCenter.runWeatherForecastService()) {
// // Ok, next
System.out.println("-- Partial InputDataHourly");
if (commandCenter.runPreparePartialInputDataHourlyStart()) {
// Ok, next
if (commandCenter.runPartialArimaService()) {
// Ok, next
if (commandCenter.runPartialSimilarDayService()) {
// Ok, next
if (commandCenter.runPreparePartialInputDataHourlyComplete()) {
// Ok, next
if (commandCenter.runArimaForecastService()) {
// Ok, next
if (commandCenter.runSimilarDayTodayService()) {
// Ok, next
if (commandCenter.runLoadForecastTodayService()) {
// Ok, next
if (commandCenter.runSimilarDayTomorrowService()) {
// Ok, next
if (commandCenter.runLoadForecastTomorrowService()) {
// Ok, next
result = ProcessingStatusEnum.PS_OK;
} else {
result = ProcessingStatusEnum.PS_ERROR_LF_TOMORROW;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_SD_TOMORROW;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_LF_TODAY;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_SD_TODAY;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_ARIMA_FORECAST;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_COMPLETING;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_PARTIAL_SD;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_PARTIAL_ARIMA;
}
} else {
result = ProcessingStatusEnum.PS_ERROR_PREPARING;
}
// }
// else {
// result = ProcessingStatusEnum.PS_ERROR_WEATHER_FORECAST;
// }
// } else {
// result = ProcessingStatusEnum.PS_ERROR_WATHER_HISTORY;
// }
//update file upload
FileUploadTable fut = new FileUploadTable();
fut.setId(0L);
fut.setFilename(file.getOriginalFilename());
fut.setFileLoadDate(cLoadDateYesterday.getTime());
fut.setUploadDatetime(new Date());
fut.setFileStatus(uploadStatus.value);
fut.setFileProcessingStatus(result.value);
fut.setUsername(username);
fut.setFileCopyStatus(copyStatus.value);
fileUploadTableService.save(fut);
} else {
System.out.println("Error : " + uploadStatus);
}
System.out.println("-------- END ------");
resultRecord.setFileStatus(uploadStatus.ordinal());
resultRecord.setFileCopyStatus(copyStatus.ordinal());
resultRecord.setFileProcessingStatus(result.ordinal());
return ResponseEntity.status(HttpStatus.OK).body(resultRecord);
}
}
|
package unnamedEntity;
import fileOperations.FileOperations;
import ioOperations.ConsoleDevice;
public class ApplicationStarter {
public static void start() {
String dataDirectory = null;
boolean verification, proceed = false;
ConsoleDevice con = new ConsoleDevice();
while(!proceed) {
con.println("Where is the data?");
dataDirectory = con.nextLine();
verification = FileOperations.exists(dataDirectory);
if(true == verification) {
proceed = true;
}
else {
con.println("Invalid Location. Lets keep trying . . .");
}
}
/* Perform Verification/Analysis Operations on the data in the given location */
Application.startQueryMode();
/*
* If there are other queries, or parameters required before the program starts,
* get them as input here.
*/
}
}
|
package com.easemob.model;
import lombok.Data;
@Data
public class Token {
private String str;
private String type;
public Token() {}
public Token(String str, String type) {
this.str = str;
this.type = type;
}
}
|
package com.zc.base.common.util.execl;
public class GeneralExcelCell {
private String beanField;
private boolean parse = true;
private boolean select = false;
private String[] selectValues;
private GeneralExcelValueHandler valueHandler;
private int startRow;
private int endRow;
private int startColumn;
private int endColumn;
public String getBeanField() {
return this.beanField;
}
public GeneralExcelCell setBeanField(String beanField) {
this.beanField = beanField;
return this;
}
protected boolean isParse() {
return this.parse;
}
public GeneralExcelCell setParse(boolean parse) {
this.parse = parse;
return this;
}
protected boolean isSelect() {
return this.select;
}
public GeneralExcelCell setSelect(boolean select) {
this.select = select;
return this;
}
protected String[] getSelectValues() {
return this.selectValues;
}
public GeneralExcelCell setSelectValues(String[] selectValues) {
this.selectValues = selectValues;
return this;
}
protected GeneralExcelValueHandler getValueHandler() {
return this.valueHandler;
}
public void setValueHandler(GeneralExcelValueHandler valueHandler) {
this.valueHandler = valueHandler;
if (this.valueHandler != null) {
this.valueHandler.setExcelCell(this);
}
}
protected int getStartRow() {
return this.startRow;
}
protected GeneralExcelCell setStartRow(int startRow) {
this.startRow = startRow;
return this;
}
protected int getEndRow() {
return this.endRow;
}
protected GeneralExcelCell setEndRow(int endRow) {
this.endRow = endRow;
return this;
}
protected int getStartColumn() {
return this.startColumn;
}
protected GeneralExcelCell setStartColumn(int startColumn) {
this.startColumn = startColumn;
return this;
}
protected int getEndColumn() {
return this.endColumn;
}
protected GeneralExcelCell setEndColumn(int endColumn) {
this.endColumn = endColumn;
return this;
}
}
|
package com.neu.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.neu.spring.pojo.UserAccount;
@Controller
public class LogoutController {
@RequestMapping(value = "/logout.htm",method = RequestMethod.GET)
public String initializeForm(HttpServletRequest request) {
System.out.println("logout form");
HttpSession session=request.getSession();
session.removeAttribute("userName");
session.removeAttribute("password");
session.invalidate();
return "loginform";
}
}
|
package com.beans;
// Generated Nov 4, 2012 12:07:46 AM by Hibernate Tools 3.2.1.GA
/**
* TblAdmin generated by hbm2java
*/
public class TblAdmin implements java.io.Serializable {
private int aid;
private TblQuestion tblQuestion;
private TblRole tblRole;
private String auserName;
private String apassword;
private String afullName;
private String aemail;
private String aphone;
private String aaddress;
private String abirthday;
private Byte agender;
private String aanswer;
private Byte astatus;
public TblAdmin() {
}
public TblAdmin(int aid) {
this.aid = aid;
}
public TblAdmin(int aid, TblQuestion tblQuestion, TblRole tblRole, String auserName, String apassword, String afullName, String aemail, String aphone, String aaddress, String abirthday, Byte agender, String aanswer, Byte astatus) {
this.aid = aid;
this.tblQuestion = tblQuestion;
this.tblRole = tblRole;
this.auserName = auserName;
this.apassword = apassword;
this.afullName = afullName;
this.aemail = aemail;
this.aphone = aphone;
this.aaddress = aaddress;
this.abirthday = abirthday;
this.agender = agender;
this.aanswer = aanswer;
this.astatus = astatus;
}
public int getAid() {
return this.aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public TblQuestion getTblQuestion() {
return this.tblQuestion;
}
public void setTblQuestion(TblQuestion tblQuestion) {
this.tblQuestion = tblQuestion;
}
public TblRole getTblRole() {
return this.tblRole;
}
public void setTblRole(TblRole tblRole) {
this.tblRole = tblRole;
}
public String getAuserName() {
return this.auserName;
}
public void setAuserName(String auserName) {
this.auserName = auserName;
}
public String getApassword() {
return this.apassword;
}
public void setApassword(String apassword) {
this.apassword = apassword;
}
public String getAfullName() {
return this.afullName;
}
public void setAfullName(String afullName) {
this.afullName = afullName;
}
public String getAemail() {
return this.aemail;
}
public void setAemail(String aemail) {
this.aemail = aemail;
}
public String getAphone() {
return this.aphone;
}
public void setAphone(String aphone) {
this.aphone = aphone;
}
public String getAaddress() {
return this.aaddress;
}
public void setAaddress(String aaddress) {
this.aaddress = aaddress;
}
public String getAbirthday() {
return this.abirthday;
}
public void setAbirthday(String abirthday) {
this.abirthday = abirthday;
}
public Byte getAgender() {
return this.agender;
}
public void setAgender(Byte agender) {
this.agender = agender;
}
public String getAanswer() {
return this.aanswer;
}
public void setAanswer(String aanswer) {
this.aanswer = aanswer;
}
public Byte getAstatus() {
return this.astatus;
}
public void setAstatus(Byte astatus) {
this.astatus = astatus;
}
}
|
package br.com.huegroup.salao.json;
public class Views {
public static class AssociationInfo {
}
public static class View implements Permission {
public static boolean getSuccess() {
return true;
}
@Override
public boolean isTokenRequired() {
return false;
}
}
public static class Success extends View {
}
public static class Error extends View {
public static boolean getSuccess() {
return false;
}
}
public static class PublicInfo extends Success implements Permission {
}
public static class DetailedInfo extends PublicInfo {
}
public static class AdminInfo extends DetailedInfo {
@Override
public boolean isTokenRequired() {
return true;
}
}
public static class DevInfo extends AdminInfo {
}
public static Class<? extends View> fromString(String permission) {
switch (permission.toUpperCase()) {
case "PBC":
return PublicInfo.class;
case "DTL":
return DetailedInfo.class;
case "ADM":
return AdminInfo.class;
case "DEV":
return DevInfo.class;
default:
throw new UnsupportedOperationException();
}
}
public static Permission getPermission(String permission) throws Exception {
Class<? extends Permission> clazz = fromString(permission);
return clazz.newInstance();
}
}
|
package com.metoo.modul.app.game.tree.dto;
/**
* <p>
* Title: GameMeterialReward.java
* </p>
*
* <p>
* Description: 免费领取参数
* </p>
*
* <author>
* HKK
* </author>
*
*/
public class GameMeterialRewardDto {
private String token;// 用户登录Token(后期优化)
private Long gameAward_id;// 奖品ID
private String userName;// 用户名
private String mobile;// 电话
private String email;// 邮箱
private Long address_id;// 用户地址ID
private Long area_id;// 区域
private String area_info;// 详细地址
public Long getGameAward_id() {
return gameAward_id;
}
public void setGameAward_id(Long gameAward_id) {
this.gameAward_id = gameAward_id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getArea_id() {
return area_id;
}
public void setArea_id(Long area_id) {
this.area_id = area_id;
}
public String getArea_info() {
return area_info;
}
public void setArea_info(String area_info) {
this.area_info = area_info;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Long getAddress_id() {
return address_id;
}
public void setAddress_id(Long address_id) {
this.address_id = address_id;
}
public GameMeterialRewardDto() {
super();
// TODO Auto-generated constructor stub
}
public GameMeterialRewardDto(String token, Long gameAward_id, String userName, String mobile, String email,
Long address_id, Long area_id, String area_info) {
super();
this.token = token;
this.gameAward_id = gameAward_id;
this.userName = userName;
this.mobile = mobile;
this.email = email;
this.address_id = address_id;
this.area_id = area_id;
this.area_info = area_info;
}
@Override
public String toString() {
return "GameMeterialRewardDto [token=" + token + ", gameAward_id=" + gameAward_id + ", userName=" + userName
+ ", mobile=" + mobile + ", email=" + email + ", address_id=" + address_id + ", area_id=" + area_id
+ ", area_info=" + area_info + "]";
}
}
|
/**
* https://icpcarchive.ecs.baylor.edu/index.php?option=onlinejudge&page=show_problem&problem=3803
* #trie #todo
*/
public class DiccionarioPortunol {
static final int MAX = 'z' - 'a' + 1;
static class TrieNode {
TrieNode[] children;
int countWord;
TrieNode() {
children = new TrieNode[MAX];
countWord = 0;
}
}
}
|
package com.staniul.util.collections;
import java.util.*;
import java.util.stream.Collectors;
/**
* Utility class for {@code Set} actions.
*/
public class SetUtil {
/**
* Produces {@code HashSet} that is intersection of 2 sets. The order does not matter.
*
* @param a First set.
* @param b Seconds set.
* @param <T> Type of objects contained in sets. Does not matter here, just for creation of a new set.
*
* @return {@code HashSet} that is intersection of 2 given sets.
*/
public static <T> HashSet<T> intersection(Set<T> a, Set<T> b) {
boolean isALarger = a.size() > b.size();
HashSet<T> result = new HashSet<>(isALarger ? b.size() : a.size());
if (isALarger) b.stream().filter(a::contains).forEach(result::add);
else a.stream().filter(b::contains).forEach(result::add);
return result;
}
/**
* Counts the size of intersection of 2 sets. Does not create a new set. Order of sets does not matter.
*
* @param a First set.
* @param b Second set.
*
* @return {@code Long} that is the size of intersection of 2 sets. New set is not created here so does not use more
* space.
*/
public static long countIntersection(Set<?> a, Set<?> b) {
boolean isALarger = a.size() > b.size();
if (isALarger) return b.stream().filter(a::contains).count();
else return a.stream().filter(b::contains).count();
}
/**
* Creates set from integers.
*
* @param ints Integers to be added to set.
*
* @return Set of Integers.
*/
public static Set<Integer> intSet(int... ints) {
HashSet<Integer> result = new HashSet<>();
Arrays.stream(ints).forEach(result::add);
return result;
}
/**
* Creates set from iterable content.
*
* @param iterable Iterable content.
* @param <T> Type of items in itarable content.
*
* @return Set of items from iterable content.
*/
public static <T> Set<T> form(Iterable<T> iterable) {
Set<T> set = new HashSet<>();
for (T item : iterable) set.add(item);
return set;
}
}
|
package com.uniinfo.common.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Object-基础工具类
* @author hongzhou.yi
*/
public class ObjUtil {
public static final String obj2Str(Object obj) {
return obj==null?"":obj+"";
}
public static final String obj2Str(Object obj, String def) {
return obj==null?def:obj+"";
}
public static final long obj2Long(Object obj) {
return obj==null?0:Long.valueOf(obj+"");
}
public static final int obj2Int(Object obj) {
return obj==null?0:Integer.valueOf(obj+"");
}
public static final Date obj2Date(Object obj) {
return (Date)obj;
}
public static final String int2Str(Integer I, String def) {
return I==null?def:I+"";
}
public static final String long2Str(Long L, String def) {
return L==null?def:L+"";
}
public static final String list2Str(List<String> list, String delimiter) {
StringBuffer sb=new StringBuffer();
for(String e: list){
if(sb.length()==0) sb.append(e);
else sb.append(delimiter + e);
}
return sb.toString();
}
public static final boolean strIsEmpty(String s) {
return s==null || "".equals(s);
}
public static final boolean strIsEmpty(String... params) {
for(String s : params) {
if(strIsEmpty(s)) return true;
}
return false;
}
public static final boolean strIsNotEmpty(String s) {
return !strIsEmpty(s);
}
public static final boolean strIsNotEmpty(String... params) {
return !strIsEmpty(params);
}
public static final String nvl(String str, String def){
if(str==null) return def;
else return str;
}
public static String replace(String str, int beginIndex, int endIndex, String replacement){
String resultStr=str.substring(0, beginIndex);
resultStr+=replacement;
resultStr+=str.substring(endIndex);
return resultStr;
}
public static String replace(String str, String beginStr, String endStr, String replacement){
int beginIndex=str.indexOf(beginStr)+beginStr.length();
int endIndex=str.indexOf(endStr, beginIndex);
return replace(str, beginIndex, endIndex, replacement);
}
public static String replaceIgnoreCase(String str, String beginStr, String endStr, String replacement){
String upperStr=str.toUpperCase();
int beginIndex=upperStr.indexOf(beginStr.toUpperCase())+beginStr.length();
int endIndex=upperStr.indexOf(endStr.toUpperCase(), beginIndex);
return replace(str, beginIndex, endIndex, replacement);
}
public static final String substring(String str, String beginStr, String endStr){
int beginIndex=str.indexOf(beginStr)+beginStr.length();
int endIndex=str.indexOf(endStr, beginIndex);
if(beginIndex<0 || endIndex<0 || endIndex<beginIndex) return "";
return str.substring(beginIndex, endIndex);
}
public static final String substringIgnoreCase(String str, String beginStr, String endStr){
String upperStr=str.toUpperCase();
int beginIndex=upperStr.indexOf(beginStr.toUpperCase())+beginStr.length();
int endIndex=upperStr.indexOf(endStr.toUpperCase(), beginIndex);
if(beginIndex<0 || endIndex<0 || endIndex<beginIndex) return "";
return str.substring(beginIndex, endIndex);
}
public static final String lastSubstring(String str, String beginStr, String endStr){
int beginIndex=str.lastIndexOf(beginStr)+beginStr.length();
int endIndex=str.lastIndexOf(endStr, beginIndex);
if(beginIndex<0 || endIndex<0 || endIndex<beginIndex) return "";
return str.substring(beginIndex, endIndex);
}
public static final String lastSubstringIgnoreCase(String str, String beginStr, String endStr){
String upperStr=str.toUpperCase();
int beginIndex=upperStr.lastIndexOf(beginStr.toUpperCase())+beginStr.length();
int endIndex=upperStr.lastIndexOf(endStr.toUpperCase(), beginIndex);
if(beginIndex<0 || endIndex<0 || endIndex<beginIndex) return "";
return str.substring(beginIndex, endIndex);
}
public static final String xmlTrim(String xml){
String regex="(?<=>)\\s+(?=<)";
return xml.replaceAll(regex, "");
}
public static final String findValueByKey(String s, String key, String def){
String regex="(?<="+key+"=)\\w*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
if(m.find()) return m.group();
else return def;
}
public static final String buildUUID(){
return UUID.randomUUID().toString().replace("-", "");
}
public static final String dateDiff(long endTime, long beginTime) {
long diffSecond = (endTime - beginTime) / 1000;
return String.format("%1$02d:%2$02d:%3$02d", diffSecond / 3600,
(diffSecond % 3600) / 60, diffSecond % 60);
}
public static final String dateFormat() {
return dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
}
public static final String dateFormat(Date date, String fmt) {
if (strIsEmpty(fmt)) fmt = "yyyy-MM-dd HH:mm:ss";
return (new SimpleDateFormat(fmt)).format(date);
}
public static final Date dateFormat(String date, String fmt) {
if (strIsEmpty(fmt)) fmt = "yyyy-MM-dd HH:mm:ss";
try {
return (new SimpleDateFormat(fmt)).parse(date);
} catch (ParseException e) {
return null;
}
}
public static final Date dateAdd(Date date, long timeMillis) {
return new Date(date.getTime() + timeMillis);
}
}
|
package com.jwebsite.daoimpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.jwebsite.dao.SiteClassDao;
import com.jwebsite.db.DbConn;
import com.jwebsite.pub.DAOFactory;
import com.jwebsite.pub.HashMapOperate;
import com.jwebsite.pub.ObjectType;
import com.jwebsite.vo.Admin;
import com.jwebsite.vo.SiteClass;
public class SiteClassDaoImpl implements SiteClassDao {
ObjectType ot=new ObjectType();
HashMapOperate ho=new HashMapOperate<SiteClass>();
// 根据ID删除分类
public void delClass(int classID) throws Exception {
String strSql="delete from siteclass where ClassID="+classID+"";
try {
DbConn.executeSQL(strSql);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("删除文章分类发生错误!");
System.out.println(e);
}
}
// 更新记录
public void updateClass(SiteClass sc) throws Exception {
DbConn.executeUpdate(sc, "ClassID");
}
// 添加分类
public void insertClass(SiteClass sc) throws Exception {
DbConn.executeInsert(sc);
}
// 根据ID查询一条记录
public SiteClass queryByID(int classID) throws Exception {
String sql="select * from siteclass o where o.ClassID="+classID;
HashMap<String, String> scm= DbConn.executeQueryOne(sql);
SiteClass sc=(SiteClass) ho.HashMapToPojo(scm, SiteClass.class);
return sc;
}
//查询顶级类 --只查询顶级类
public List<SiteClass> queryTopClassList() throws Exception{
ArrayList<SiteClass> sclist = new ArrayList<SiteClass>();
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
String strSql = "select ClassName,ClassID from siteclass where Depth=0";
scmlist=DbConn.executeQuery(strSql);
sclist=(ArrayList<SiteClass>) ho.HashMapToObjectList(scmlist, SiteClass.class);
return sclist;
}
// 显示顶级类
public List<SiteClass> queryAllTop(String parentID, String classID) throws Exception {
ArrayList<SiteClass> sclist = new ArrayList<SiteClass>();
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
String sql = "select * from siteclass where ParentID="+ parentID;
System.out.println(sql);
try {
scmlist =DbConn.executeQuery(sql);
for (HashMap<String, String> m:scmlist) {
SiteClass sc=(SiteClass) ho.HashMapToPojo(m, SiteClass.class);
sclist.add(sc);
queryAllChild(sc.getClassID().toString(),classID,sclist);
}
} catch (Exception ex) {
System.out.println("检索文章分类出错" + sql + ex.getMessage());
}
return sclist;
}
//显示所有子类
public ArrayList<SiteClass> queryAllChild(String parentID, String classID,ArrayList<SiteClass> sclist)throws Exception{
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
String sql = "select * from siteclass where ParentID="+ parentID;
System.out.println(sql);
try {
scmlist =DbConn.executeQuery(sql);
for (HashMap<String, String> m:scmlist) {
SiteClass sc=(SiteClass) ho.HashMapToPojo(m, SiteClass.class);
sclist.add(sc);
queryAllChild(sc.getClassID().toString(),classID,sclist);
}
} catch (Exception ex) {
System.out.println("检索子类出错" + sql + ex);
}
return sclist;
}
// 显示顶级类 根据 AdminID 超级管理员
public ArrayList<SiteClass> queryOneTop(int parentID,int AdminID) throws Exception {
ArrayList<SiteClass> sclist = new ArrayList<SiteClass>();
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
Admin admin=DAOFactory.getAdminDaoInstance().showAdmin(AdminID);
String strSql = "select * from siteclass where ParentID="+ parentID;
System.out.println("管理员:Purview"+admin.getPurview());
if(admin.getPurview()==1){
}else{
String[] inserts=admin.getArrClass_Input().split(",");
if(inserts.length>0&&admin.getPurview()!=1)
{
strSql+=" and ( 1=2 ";
strSql+=" or ( 1=2 ";
for(int i=0;i<inserts.length;i++)
{
strSql+=" or ClassID="+inserts[i];
}
strSql+=")";
}
System.out.println(" 查询文章栏目 "+strSql);
}
try {
scmlist =DbConn.executeQuery(strSql);
for (HashMap<String, String> m:scmlist) {
SiteClass sc=(SiteClass) ho.HashMapToPojo(m, SiteClass.class);
sclist.add(sc);
queryOneChild(m.get("ClassID"),sclist,AdminID);
}
} catch (Exception ex) {
System.out.println("检索文章分类出错" + strSql + ex.getMessage());
}
return sclist;
}
//显示所有子类 根据 adminid 没有ClassID
public ArrayList<SiteClass> queryOneChild(String parentID, ArrayList<SiteClass> sclist,int adminid)throws Exception{
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
Admin admin=DAOFactory.getAdminDaoInstance().showAdmin(adminid);
String[] inserts=admin.getArrClass_Input().split(",");
int i = 1;
String strSql = "select * from siteclass where ParentID="+ parentID + " ";
if(inserts.length>0&&admin.getPurview()!=1)
{
strSql+=" and ( 1=2 ";
//strSql+=" or ( 1=2 ";
for(int a=0;a<inserts.length;a++)
{
strSql+=" or ClassID="+inserts[a];
}
strSql+=")";
}
System.out.println("查询子栏目:"+strSql);
try {
scmlist =DbConn.executeQuery(strSql);
for (HashMap<String, String> m:scmlist) {
SiteClass sc=(SiteClass) ho.HashMapToPojo(m, SiteClass.class);
sclist.add(sc);
queryOneChild(m.get("ClassID"),sclist,adminid);
}
} catch (Exception ex) {
System.out.println("检索子类出错" + strSql + ex);
}
return sclist;
}
// 显示顶级类 根据 adminid ClassID
public ArrayList<SiteClass> queryAllTop(String parentID, String classID, String adminid)
throws Exception {
ArrayList<SiteClass> sclist = new ArrayList<SiteClass>();
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
Admin admin=DAOFactory.getAdminDaoInstance().showAdmin(Integer.parseInt(adminid));
String[] inserts=admin.getArrClass_Input().split(",");
String strSql = "select * from siteclass where ParentID="+ parentID;
if(inserts.length>0&&admin.getPurview()!=1)
{
strSql+=" and ( 1=2 ";
strSql+=" or ( 1=2 ";
for(int i=0;i<inserts.length;i++)
{
strSql+=" or ClassID="+inserts[i];
}
strSql+=")";
}
System.out.println(" 查询文章栏目 "+strSql);
try {
scmlist =DbConn.executeQuery(strSql);
for (HashMap<String, String> m:scmlist) {
SiteClass sc=(SiteClass) ho.HashMapToPojo(m, SiteClass.class);
sclist.add(sc);
sclist.addAll(queryAllChild(m.get("ClassID"), classID,sclist,adminid));
}
} catch (Exception ex) {
System.out.println("检索文章分类出错" + strSql + ex.getMessage());
}
return sclist;
}
//显示所有子类 根据 adminid 有ClassID
public ArrayList<SiteClass> queryAllChild(String parentID, String classID, ArrayList<SiteClass> sclist,String adminid)throws Exception{
ArrayList<HashMap<String, String>> scmlist=new ArrayList<HashMap<String,String>>();
Admin admin=DAOFactory.getAdminDaoInstance().showAdmin(Integer.parseInt(adminid));
String[] inserts=admin.getArrClass_Input().split(",");
int i = 1;
String strSql = "select * from siteclass where ParentID="+ parentID + " ";
if(inserts.length>0&&admin.getPurview()!=1)
{
strSql+=" and ( 1=2 ";
//strSql+=" or ( 1=2 ";
for(int a=0;a<inserts.length;a++)
{
strSql+=" or ClassID="+inserts[a];
}
strSql+=")";
}
System.out.println("查询子栏目:"+strSql);
try {
scmlist =DbConn.executeQuery(strSql);
for (HashMap<String, String> m:scmlist) {
SiteClass sc=(SiteClass) ho.HashMapToPojo(m, SiteClass.class);
sclist.add(sc);
sclist.addAll(queryAllChild(m.get("ClassID"), classID,sclist,adminid));
}
} catch (Exception ex) {
System.out.println("检索子类出错" + strSql + ex);
}
return sclist;
}
// 显示栏目名称
public String getClassName(int classID) throws Exception {
return null;
}
// 取得父类ID
public int getParentID(int classID) throws Exception {
return 0;
}
// 显示栏目名称
public String queryClassNameByID(int classID) throws Exception {
return null;
}
// 显示所有子类
public String queryChildClass(int parentID, String strNbsp,
String purview_View, String purview_Input, String purview_Check,
String purview_Manage) throws Exception {
return null;
}
}
|
package org.example.codingtest.a_real_test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DemoTest {
private static final DemoTest o = new DemoTest();
public static void main(String[] args) {
int[][] v = {{1,4},{3,4},{3,10}};
int[] solution = o.solution(v);
System.out.println(solution[0] + " / " +solution[1]);
}
public int[] solution(int[][] v) {
int[] answer = new int[v[0].length];
Map<Integer,Integer> sMap = new HashMap<>();
Map<Integer,Integer> eMap = new HashMap<>();
for (int i = 0; i < v.length; i++) {
if (sMap.containsKey(v[i][0])){
Integer integer = sMap.get(v[i][0]);
integer += 1;
sMap.put(v[i][0],integer);
} else {
sMap.put(v[i][0],1);
}
if (eMap.containsKey(v[i][1])){
Integer integer = eMap.get(v[i][1]);
integer += 1;
eMap.put(v[i][1],integer);
} else {
eMap.put(v[i][1],1);
}
}
Iterator<Map.Entry<Integer, Integer>> sItr = sMap.entrySet().iterator();
Iterator<Map.Entry<Integer, Integer>> eItr = eMap.entrySet().iterator();
while (sItr.hasNext()){
Map.Entry<Integer, Integer> next = sItr.next();
if (next.getValue()<2)
answer[0] = next.getKey();
}
while (eItr.hasNext()){
Map.Entry<Integer, Integer> next = eItr.next();
if (next.getValue()<2){
answer[1] = next.getKey();
}
}
return answer;
}
}
|
package com.wzh.crocodile.ex03_connector;
import com.wzh.crocodile.ex03_connector.connector.HttpConnector;
/**
* @Description: 启动类
* @Author: 吴智慧
* @Date: 2019/11/9 10:01
*/
public final class Bootstrap {
public static void main(String[] args) {
// 创建连接器
HttpConnector connnector = new HttpConnector();
// 启动连接器
connnector.start();
}
}
|
package com.example.hyunyoungpark.gridlistviewtest;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter{
private Context c;
//constructor
public ImageAdapter(Context c)
{
this.c = c;
}
//create an array for Images
private Integer[] mImages =
{
R.drawable.android_logo,
R.drawable.blackberry_logo,
R.drawable.ios_logo,
R.drawable.windowsmobile_logo,
R.drawable.android_logo,
R.drawable.blackberry_logo,
R.drawable.ios_logo,
R.drawable.windowsmobile_logo,
R.drawable.android_logo,
R.drawable.blackberry_logo,
R.drawable.ios_logo,
R.drawable.windowsmobile_logo
};
//gives you the count of item in your collection
@Override
public int getCount() {
return mImages.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
//Create a new Imageview for ech item referenced by adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv;
if(convertView==null){
iv = new ImageView(c);
iv.setLayoutParams(new GridView.LayoutParams(200,200));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setPadding(8,8,8,8);
}
else
{
iv = (ImageView) convertView;
}
iv.setImageResource(mImages[position]);
return iv;
}
}
|
package lithe.lithe;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import Lithe_Data.GateWay;
import Lithe_Data.User;
public class RegistrationActivity extends Activity {
private EditText Username;
private EditText Password;
private EditText ConfirmPassword;
private EditText LawrenceEmail;
private String username;
private String password;
private String confirm_password;
private String lawrence_email;
private RegistrationTask mAuthTask = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Username=(EditText) findViewById(R.id.username);
Password=(EditText) findViewById(R.id.password);
ConfirmPassword=(EditText) findViewById(R.id.confirm_password);
LawrenceEmail=(EditText) findViewById(R.id.lawrenc_email);
//Button mCancelButton = (Button) findViewById(R.id.CancelButton);
//mCancelButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// cancel();
// }
//});
Button mRegisterButton = (Button) findViewById(R.id.RegisterButton);
mRegisterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
registration();
}
});
}
public void registration(){
username=Username.getText().toString();
password=Password.getText().toString();
confirm_password=ConfirmPassword.getText().toString();
lawrence_email=LawrenceEmail.getText().toString();
boolean cancel=false;
if(!password.equals(confirm_password))
{ConfirmPassword.setError("please confirm password");
cancel=true;}
else if (password.equals("")) {
Password.setError("password is required");
cancel = true;}
else if (password.length()<4) {
Password.setError("password is not long enough");
cancel = true;}
if (username.equals("")) {
Username.setError("Username is required");
cancel = true;}
if (lawrence_email.equals("")) {
LawrenceEmail.setError("Lawrence Email is required");
cancel = true;}
else if (!lawrence_email.endsWith("@lawrence.edu")) {
LawrenceEmail.setError("please enter a lawrence e-mail");
cancel = true;}
if (!cancel){
mAuthTask = new RegistrationTask(username,password,lawrence_email);
mAuthTask.execute((Void) null);
}
}
//public void cancel()
//{ onBackPressed(); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_registration, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class RegistrationTask extends AsyncTask<Void, Void, Integer> {
private final String username;
private final String password;
private final String lawrence_email;
private final GateWay test;
RegistrationTask(String inputUsername, String inputPassword,String input_lawrence_email) {
test = new GateWay();
username = inputUsername;
password = inputPassword;
lawrence_email= input_lawrence_email;
}
@Override
protected Integer doInBackground(Void... params) {
test.ConnectToServer(username);
User user = new User(test);
int x=user.CreateAccount(username,password,lawrence_email);
MainActivity.setUser(user);
user.setUser(username);
user.GetListing();
try { test.end(); } catch (IOException e) { e.printStackTrace(); }
return x;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(final Integer success) {
mAuthTask = null;
//showProgress(false);
switch (success) {
case 2:Username.setError("account already exist");
Username.requestFocus();break;
case 1: finish();break;
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
//showProgress(false);
}}
public void finish()
{
Intent intent = new Intent(this, HomeScreenActivity.class);
startActivity(intent);
}
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.jet.beam.transforms.pardo;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.coders.VarIntCoder;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.View;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.transforms.windowing.SlidingWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TimestampedValue;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.MutableDateTime;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
/* "Inspired" by org.apache.beam.sdk.transforms.ParDoTest.MultipleInputsAndOutputTests */
public class MultipleInputsAndOutputParDoTest extends AbstractParDoTest {
@Test
public void testParDoWithTaggedOutput() {
List<Integer> inputs = Arrays.asList(3, -42, 666);
TupleTag<String> mainOutputTag = new TupleTag<String>("main") {};
TupleTag<String> additionalOutputTag1 = new TupleTag<String>("additional1") {};
TupleTag<String> additionalOutputTag2 = new TupleTag<String>("additional2") {};
TupleTag<String> additionalOutputTag3 = new TupleTag<String>("additional3") {};
TupleTag<String> additionalOutputTagUnwritten = new TupleTag<String>("unwrittenOutput") {};
PCollectionTuple outputs =
pipeline
.apply(Create.of(inputs))
.apply(
ParDo.of(
new TestDoFn(
Arrays.asList(),
Arrays.asList(
additionalOutputTag1,
additionalOutputTag2,
additionalOutputTag3)))
.withOutputTags(
mainOutputTag,
TupleTagList.of(additionalOutputTag3)
.and(additionalOutputTag1)
.and(additionalOutputTagUnwritten)
.and(additionalOutputTag2)));
PAssert.that(outputs.get(mainOutputTag))
.satisfies(HasExpectedOutput.forInput(inputs));
PAssert.that(outputs.get(additionalOutputTag1))
.satisfies(HasExpectedOutput.forInput(inputs).fromOutput(additionalOutputTag1));
PAssert.that(outputs.get(additionalOutputTag2))
.satisfies(HasExpectedOutput.forInput(inputs).fromOutput(additionalOutputTag2));
PAssert.that(outputs.get(additionalOutputTag3))
.satisfies(HasExpectedOutput.forInput(inputs).fromOutput(additionalOutputTag3));
PAssert.that(outputs.get(additionalOutputTagUnwritten)).empty();
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testParDoEmptyWithTaggedOutput() {
TupleTag<String> mainOutputTag = new TupleTag<String>("main") {};
TupleTag<String> additionalOutputTag1 = new TupleTag<String>("additional1") {};
TupleTag<String> additionalOutputTag2 = new TupleTag<String>("additional2") {};
TupleTag<String> additionalOutputTag3 = new TupleTag<String>("additional3") {};
TupleTag<String> additionalOutputTagUnwritten = new TupleTag<String>("unwrittenOutput") {};
PCollectionTuple outputs =
pipeline
.apply(Create.empty(VarIntCoder.of()))
.apply(
ParDo.of(
new TestDoFn(
Arrays.asList(),
Arrays.asList(
additionalOutputTag1,
additionalOutputTag2,
additionalOutputTag3)))
.withOutputTags(
mainOutputTag,
TupleTagList.of(additionalOutputTag3)
.and(additionalOutputTag1)
.and(additionalOutputTagUnwritten)
.and(additionalOutputTag2)));
List<Integer> inputs = Collections.emptyList();
PAssert.that(outputs.get(mainOutputTag))
.satisfies(HasExpectedOutput.forInput(inputs));
PAssert.that(outputs.get(additionalOutputTag1))
.satisfies(HasExpectedOutput.forInput(inputs).fromOutput(additionalOutputTag1));
PAssert.that(outputs.get(additionalOutputTag2))
.satisfies(HasExpectedOutput.forInput(inputs).fromOutput(additionalOutputTag2));
PAssert.that(outputs.get(additionalOutputTag3))
.satisfies(HasExpectedOutput.forInput(inputs).fromOutput(additionalOutputTag3));
PAssert.that(outputs.get(additionalOutputTagUnwritten)).empty();
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testParDoWithEmptyTaggedOutput() {
TupleTag<String> mainOutputTag = new TupleTag<String>("main") {};
TupleTag<String> additionalOutputTag1 = new TupleTag<String>("additional1") {};
TupleTag<String> additionalOutputTag2 = new TupleTag<String>("additional2") {};
PCollectionTuple outputs =
pipeline
.apply(Create.empty(VarIntCoder.of()))
.apply(
ParDo.of(new TestNoOutputDoFn())
.withOutputTags(
mainOutputTag,
TupleTagList.of(additionalOutputTag1).and(additionalOutputTag2)));
PAssert.that(outputs.get(mainOutputTag)).empty();
PAssert.that(outputs.get(additionalOutputTag1)).empty();
PAssert.that(outputs.get(additionalOutputTag2)).empty();
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testParDoWithOnlyTaggedOutput() {
List<Integer> inputs = Arrays.asList(3, -42, 666);
final TupleTag<Void> mainOutputTag = new TupleTag<Void>("main") {};
final TupleTag<Integer> additionalOutputTag = new TupleTag<Integer>("additional") {};
PCollectionTuple outputs =
pipeline
.apply(Create.of(inputs))
.apply(
ParDo.of(
new DoFn<Integer, Void>() {
@ProcessElement
public void processElement(
@Element Integer element, MultiOutputReceiver r) {
r.get(additionalOutputTag).output(element);
}
})
.withOutputTags(mainOutputTag, TupleTagList.of(additionalOutputTag)));
PAssert.that(outputs.get(mainOutputTag)).empty();
PAssert.that(outputs.get(additionalOutputTag)).containsInAnyOrder(inputs);
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testParDoWithSideInputs() {
List<Integer> inputs = Arrays.asList(3, -42, 666);
PCollectionView<Integer> sideInput1 =
pipeline
.apply("CreateSideInput1", Create.of(11))
.apply("ViewSideInput1", View.asSingleton());
PCollectionView<Integer> sideInputUnread =
pipeline
.apply("CreateSideInputUnread", Create.of(-3333))
.apply("ViewSideInputUnread", View.asSingleton());
PCollectionView<Integer> sideInput2 =
pipeline
.apply("CreateSideInput2", Create.of(222))
.apply("ViewSideInput2", View.asSingleton());
PCollection<String> output =
pipeline
.apply(Create.of(inputs))
.apply(
ParDo.of(new TestDoFn(Arrays.asList(sideInput1, sideInput2), Arrays.asList()))
.withSideInputs(sideInput1, sideInputUnread, sideInput2));
PAssert.that(output)
.satisfies(HasExpectedOutput.forInput(inputs).andSideInputs(11, 222));
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testParDoWithSideInputsIsCumulative() {
List<Integer> inputs = Arrays.asList(3, -42, 666);
PCollectionView<Integer> sideInput1 =
pipeline
.apply("CreateSideInput1", Create.of(11))
.apply("ViewSideInput1", View.asSingleton());
PCollectionView<Integer> sideInputUnread =
pipeline
.apply("CreateSideInputUnread", Create.of(-3333))
.apply("ViewSideInputUnread", View.asSingleton());
PCollectionView<Integer> sideInput2 =
pipeline
.apply("CreateSideInput2", Create.of(222))
.apply("ViewSideInput2", View.asSingleton());
PCollection<String> output =
pipeline
.apply(Create.of(inputs))
.apply(
ParDo.of(new TestDoFn(Arrays.asList(sideInput1, sideInput2), Arrays.asList()))
.withSideInputs(sideInput1)
.withSideInputs(sideInputUnread)
.withSideInputs(sideInput2));
PAssert.that(output)
.satisfies(HasExpectedOutput.forInput(inputs).andSideInputs(11, 222));
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testMultiOutputParDoWithSideInputs() {
List<Integer> inputs = Arrays.asList(3, -42, 666);
final TupleTag<String> mainOutputTag = new TupleTag<String>("main") {};
final TupleTag<Void> additionalOutputTag = new TupleTag<Void>("output") {};
PCollectionView<Integer> sideInput1 =
pipeline
.apply("CreateSideInput1", Create.of(11))
.apply("ViewSideInput1", View.asSingleton());
PCollectionView<Integer> sideInputUnread =
pipeline
.apply("CreateSideInputUnread", Create.of(-3333))
.apply("ViewSideInputUnread", View.asSingleton());
PCollectionView<Integer> sideInput2 =
pipeline
.apply("CreateSideInput2", Create.of(222))
.apply("ViewSideInput2", View.asSingleton());
PCollectionTuple outputs =
pipeline
.apply(Create.of(inputs))
.apply(
ParDo.of(new TestDoFn(Arrays.asList(sideInput1, sideInput2), Arrays.asList()))
.withSideInputs(sideInput1)
.withSideInputs(sideInputUnread)
.withSideInputs(sideInput2)
.withOutputTags(mainOutputTag, TupleTagList.of(additionalOutputTag)));
PAssert.that(outputs.get(mainOutputTag))
.satisfies(HasExpectedOutput.forInput(inputs).andSideInputs(11, 222));
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testMultiOutputParDoWithSideInputsIsCumulative() {
List<Integer> inputs = Arrays.asList(3, -42, 666);
final TupleTag<String> mainOutputTag = new TupleTag<String>("main") {};
final TupleTag<Void> additionalOutputTag = new TupleTag<Void>("output") {};
PCollectionView<Integer> sideInput1 =
pipeline
.apply("CreateSideInput1", Create.of(11))
.apply("ViewSideInput1", View.asSingleton());
PCollectionView<Integer> sideInputUnread =
pipeline
.apply("CreateSideInputUnread", Create.of(-3333))
.apply("ViewSideInputUnread", View.asSingleton());
PCollectionView<Integer> sideInput2 =
pipeline
.apply("CreateSideInput2", Create.of(222))
.apply("ViewSideInput2", View.asSingleton());
PCollectionTuple outputs =
pipeline
.apply(Create.of(inputs))
.apply(
ParDo.of(new TestDoFn(Arrays.asList(sideInput1, sideInput2), Arrays.asList()))
.withSideInputs(sideInput1)
.withSideInputs(sideInputUnread)
.withSideInputs(sideInput2)
.withOutputTags(mainOutputTag, TupleTagList.of(additionalOutputTag)));
PAssert.that(outputs.get(mainOutputTag))
.satisfies(HasExpectedOutput.forInput(inputs).andSideInputs(11, 222));
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
@Test
public void testSideInputsWithMultipleWindows() {
// Tests that the runner can safely run a DoFn that uses side inputs
// on an input where the element is in multiple windows. The complication is
// that side inputs are per-window, so the runner has to make sure
// to process each window individually.
MutableDateTime mutableNow = Instant.now().toMutableDateTime();
mutableNow.setMillisOfSecond(0);
Instant now = mutableNow.toInstant();
SlidingWindows windowFn = SlidingWindows.of(Duration.standardSeconds(5)).every(Duration.standardSeconds(1));
PCollectionView<Integer> view = pipeline.apply(Create.of(1)).apply(View.asSingleton());
PCollection<String> res =
pipeline
.apply(Create.timestamped(TimestampedValue.of("a", now)))
.apply(Window.into(windowFn))
.apply(ParDo.of(new FnWithSideInputs(view)).withSideInputs(view));
for (int i = 0; i < 4; ++i) {
Instant base = now.minus(Duration.standardSeconds(i));
IntervalWindow window = new IntervalWindow(base, base.plus(Duration.standardSeconds(5)));
PAssert.that(res).inWindow(window).containsInAnyOrder("a:1");
}
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
}
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DeleteOrder extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String delete=request.getParameter("delete");
String query ="delete from orderbycostomers where TableNo="+delete;
Connection cn=MySqlConnector.getConnection();
String url="jdbc:mysql://localhost:3306/fooddatabase";
String con="com.mysql.jdbc.Driver";
try{
Class.forName(con);
cn=DriverManager.getConnection(url,"root","");
try{
Statement stat = cn.createStatement();
stat.executeUpdate(query);
out.println("TABLE NUMBER:" +delete);
out.println("DELETED SUCESSFULLY");
}
catch(Exception e)
{
out.println("errrrror"+e.getMessage());
}
}catch(Exception e){
out.println("ERRORRRR"+e.getMessage());
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.sara.entitys;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author P-LAPULGAR
*/
@Entity
@Table(name = "EDCARGUEMULTIFUNCIONAL")
@NamedQueries( {
@NamedQuery(
name = "Edcarguemultifuncional.registroUnico",
query = "select object(edc) from Edcarguemultifuncional edc where edc.idedccargue = :idedccargue"),
// Busqueda de un registro por cajero y ciclo utilizadopor el proceso de carga
@NamedQuery(
name = "Edcarguemultifuncional.CicloSnError",
query = "select object(edc) from Edcarguemultifuncional edc where edc.ciclo = :ciclo and edc.error=0"),
@NamedQuery(
name = "Edcarguemultifuncional.todos",
query = "select object(edc) from Edcarguemultifuncional edc order by edc.idedccargue"),
@NamedQuery(
name = "Edcarguemultifuncional.RangoFecha",
query = "select object(edc) from Edcarguemultifuncional edc " +
" where edc.fechaedccargue between :fechaInicial and :fechaFinal order by edc.ciclo,edc.error") ,
@NamedQuery(
name = "Edcarguemultifuncional.Archivo",
query = "select object(edc) from Edcarguemultifuncional edc " +
" where edc.nombrearchivo = :nombrearchivo")
})
public class Edcarguemultifuncional implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "IDEDCCARGUE", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IdEdcCargueMulti_SEQ")
@SequenceGenerator(name = "IdEdcCargueMulti_SEQ", sequenceName = "SEQ_IDEDCCARGUEMULTI" ,allocationSize=1 )
private Long idedccargue;
@Column(name = "CODIGOCAJERO", nullable = false)
private Integer codigocajero;
@Column(name = "ESTADOPROCESO")
private Short estadoproceso;
@Column(name = "ULTIMASECUENCIA", nullable = false)
private Integer ultimasecuencia;
@Column(name = "CICLO", nullable = false)
private Integer ciclo;
@Column(name = "ERROR")
private Integer error;
@Column(name = "VERSION")
private Integer version;
@Column(name = "NOMBREARCHIVO", nullable = false)
private String nombrearchivo;
@Column(name = "FECHAEDCCARGUE", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date fechaedccargue;
@Column(name = "DESCRIPCIONERROR")
private String descripcionerror;
public Edcarguemultifuncional() {
}
public Edcarguemultifuncional(Long idedccargue) {
this.idedccargue = idedccargue;
}
public Edcarguemultifuncional(Long idedccargue, Integer codigocajero, Integer ultimasecuencia, Integer ciclo, String nombrearchivo, Date fechaedccargue) {
this.idedccargue = idedccargue;
this.codigocajero = codigocajero;
this.ultimasecuencia = ultimasecuencia;
this.ciclo = ciclo;
this.nombrearchivo = nombrearchivo;
this.fechaedccargue = fechaedccargue;
}
public Long getIdedccargue() {
return idedccargue;
}
public void setIdedccargue(Long idedccargue) {
this.idedccargue = idedccargue;
}
public Short getEstadoproceso() {
return estadoproceso;
}
public void setEstadoproceso(Short estadoproceso) {
this.estadoproceso = estadoproceso;
}
public String getNombrearchivo() {
return nombrearchivo;
}
public void setNombrearchivo(String nombrearchivo) {
this.nombrearchivo = nombrearchivo;
}
public Date getFechaedccargue() {
return fechaedccargue;
}
public void setFechaedccargue(Date fechaedccargue) {
this.fechaedccargue = fechaedccargue;
}
public Integer getCiclo() {
return ciclo;
}
public void setCiclo(Integer ciclo) {
this.ciclo = ciclo;
}
public Integer getCodigocajero() {
return codigocajero;
}
public void setCodigocajero(Integer codigocajero) {
this.codigocajero = codigocajero;
}
public Integer getError() {
return error;
}
public void setError(Integer error) {
this.error = error;
}
public Integer getUltimasecuencia() {
return ultimasecuencia;
}
public void setUltimasecuencia(Integer ultimasecuencia) {
this.ultimasecuencia = ultimasecuencia;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getDescripcionerror() {
return descripcionerror;
}
public void setDescripcionerror(String descripcionerror) {
this.descripcionerror = descripcionerror;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idedccargue != null ? idedccargue.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Edcarguemultifuncional)) {
return false;
}
Edcarguemultifuncional other = (Edcarguemultifuncional) object;
if ((this.idedccargue == null && other.idedccargue != null) || (this.idedccargue != null && !this.idedccargue.equals(other.idedccargue))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.davivienda.sara.entitys.Edcarguemultifuncional[idedccargue=" + idedccargue + "]";
}
public Edcarguemultifuncional actualizarEntity(Edcarguemultifuncional obj) {
setCodigocajero(obj.codigocajero);
setEstadoproceso(obj.estadoproceso);
setUltimasecuencia(obj.ultimasecuencia);
setCiclo(obj.ciclo);
setError(obj.error);
setVersion(obj.version);
setNombrearchivo(obj.nombrearchivo);
setFechaedccargue(obj.fechaedccargue);
setDescripcionerror(obj.descripcionerror);
return this;
}
}
|
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 dk.sidereal.lumm.components.particlesystem;
import java.util.Random;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector2;
import dk.sidereal.lumm.architecture.Lumm;
import dk.sidereal.lumm.architecture.LummScene;
import dk.sidereal.lumm.architecture.concrete.ConcreteLummObject;
import dk.sidereal.lumm.components.renderer.Renderer;
import dk.sidereal.lumm.components.renderer.sprite.SpriteBuilder;
/**
* GameObjects resembling individual particles. They are made based on
* {@link ParticleSpriteLayout}.
*
* @author Claudiu
*/
public class ParticleSpriteObject extends ConcreteLummObject {
// region fields
public Renderer renderable;
public Random rand;
/** Overall time that the particle lives */
public float timeToLive;
public float timeRemaining;
public Sprite sprite;
public String spritePath;
/** Size of the sprite, will center the sprite based on size */
public Vector2 size;
public Vector2 trajectory;
public float rotation;
public float speed;
/** between -1 and 1, falling down at 1 */
public float gravity;
public float currGravity;
public ParticleSpriteLayout particleSprite;
public ParticleEmitter emitterParent;
public ParticleEmitter emitterChild;
// endregion fields
// region constructors
public ParticleSpriteObject(LummScene scene, ParticleEmitter emitter) {
super(scene);
if (emitter.renderFirst)
this.position.setRelative(0, 0, -1);
else
this.position.setRelative(0, 0, 1);
rand = new Random();
this.emitterParent = emitter;
// speed
this.speed = emitter.speed + rand.nextFloat() * emitter.speedRandomRange - emitter.speedRandomRange / 2;
// trajectory
this.trajectory = new Vector2();
trajectory.x = emitter.trajectory.x + rand.nextFloat() * emitter.trajectoryRandomRange.x
- emitter.trajectoryRandomRange.x / 2;
trajectory.y = emitter.trajectory.x + rand.nextFloat() * emitter.trajectoryRandomRange.x
- emitter.trajectoryRandomRange.x / 2;
// gravity
this.gravity = emitter.gravity + rand.nextFloat() * emitter.gravityRandomRange - emitter.gravityRandomRange / 2;
this.currGravity = 0;
this.position.set(emitter.owner.position.getX() + emitter.offsetPosition.x
+ rand.nextFloat() * emitter.offsetPositionRandomRange.x - emitter.offsetPositionRandomRange.x / 2,
emitter.owner.position.getY() + emitter.offsetPosition.y
+ rand.nextFloat() * emitter.offsetPositionRandomRange.y
- emitter.offsetPositionRandomRange.y / 2,
emitter.owner.position.getZ());
particleSprite = emitter.particleSources.get(rand.nextInt(emitter.particleSources.size()));
this.spritePath = particleSprite.sprite;
this.size = particleSprite.size;
if (particleSprite.sizeRandomRange != null) {
float sizeRandomizer = rand.nextFloat();
this.size.x += sizeRandomizer * this.particleSprite.sizeRandomRange.x
- particleSprite.sizeRandomRange.x / 2;
this.size.y += sizeRandomizer * this.particleSprite.sizeRandomRange.y
- particleSprite.sizeRandomRange.y / 2;
}
if (particleSprite.emitter != null) {
emitterChild = particleSprite.emitter;
emitterChild.setOwner(this);
}
this.timeRemaining = emitter.particleTime + rand.nextFloat() * emitter.particleTimeRandomRange
- emitter.particleTimeRandomRange / 2;
this.timeToLive = this.timeRemaining;
handleRenderable();
}
@Override
public void onCreate(Object... params) {
setName("Particle " + System.currentTimeMillis());
}
// endregion constructors
// region methods
@Override
public void onUpdate() {
this.timeRemaining -= Lumm.time.getDeltaTime();
if (timeRemaining <= 0) {
getScene().removeobject(this);
return;
}
particleSprite.progressionEvent.run(this);
}
public void handleRenderable() {
renderable = new Renderer(this);
SpriteBuilder builder = new SpriteBuilder(spritePath).setSize(size.x, size.y)
.setOffsetPosition(-size.x / 2f, -size.y / 2).setRotation((float) Math.random() * 360)
.setColor(particleSprite.tintColor);
renderable.addDrawer("Main", builder);
}
// endregion methods
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.event;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Predicate;
import org.springframework.aot.hint.annotation.Reflective;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.annotation.AliasFor;
/**
* Annotation that marks a method as a listener for application events.
*
* <p>If an annotated method supports a single event type, the method may
* declare a single parameter that reflects the event type to listen to.
* If an annotated method supports multiple event types, this annotation
* may refer to one or more supported event types using the {@code classes}
* attribute. See the {@link #classes} javadoc for further details.
*
* <p>Events can be {@link ApplicationEvent} instances as well as arbitrary
* objects.
*
* <p>Processing of {@code @EventListener} annotations is performed via
* the internal {@link EventListenerMethodProcessor} bean which gets
* registered automatically when using Java config or manually via the
* {@code <context:annotation-config/>} or {@code <context:component-scan/>}
* element when using XML config.
*
* <p>Annotated methods may have a non-{@code void} return type. When they
* do, the result of the method invocation is sent as a new event. If the
* return type is either an array or a collection, each element is sent
* as a new individual event.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em>.
*
* <h3>Exception Handling</h3>
* <p>While it is possible for an event listener to declare that it
* throws arbitrary exception types, any checked exceptions thrown
* from an event listener will be wrapped in an
* {@link java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException}
* since the event publisher can only handle runtime exceptions.
*
* <h3>Asynchronous Listeners</h3>
* <p>If you want a particular listener to process events asynchronously, you
* can use Spring's {@link org.springframework.scheduling.annotation.Async @Async}
* support, but be aware of the following limitations when using asynchronous events.
*
* <ul>
* <li>If an asynchronous event listener throws an exception, it is not propagated
* to the caller. See {@link org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
* AsyncUncaughtExceptionHandler} for more details.</li>
* <li>Asynchronous event listener methods cannot publish a subsequent event by returning a
* value. If you need to publish another event as the result of the processing, inject an
* {@link org.springframework.context.ApplicationEventPublisher ApplicationEventPublisher}
* to publish the event manually.</li>
* </ul>
*
* <h3>Ordering Listeners</h3>
* <p>It is also possible to define the order in which listeners for a
* certain event are to be invoked. To do so, add Spring's common
* {@link org.springframework.core.annotation.Order @Order} annotation
* alongside this event listener annotation.
*
* @author Stephane Nicoll
* @author Sam Brannen
* @since 4.2
* @see EventListenerMethodProcessor
* @see org.springframework.transaction.event.TransactionalEventListener
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Reflective
public @interface EventListener {
/**
* Alias for {@link #classes}.
*/
@AliasFor("classes")
Class<?>[] value() default {};
/**
* The event classes that this listener handles.
* <p>If this attribute is specified with a single value, the
* annotated method may optionally accept a single parameter.
* However, if this attribute is specified with multiple values,
* the annotated method must <em>not</em> declare any parameters.
*/
@AliasFor("value")
Class<?>[] classes() default {};
/**
* Spring Expression Language (SpEL) expression used for making the event
* handling conditional.
* <p>The event will be handled if the expression evaluates to boolean
* {@code true} or one of the following strings: {@code "true"}, {@code "on"},
* {@code "yes"}, or {@code "1"}.
* <p>The default expression is {@code ""}, meaning the event is always handled.
* <p>The SpEL expression will be evaluated against a dedicated context that
* provides the following metadata:
* <ul>
* <li>{@code #root.event} or {@code event} for references to the
* {@link ApplicationEvent}</li>
* <li>{@code #root.args} or {@code args} for references to the method
* arguments array</li>
* <li>Method arguments can be accessed by index. For example, the first
* argument can be accessed via {@code #root.args[0]}, {@code args[0]},
* {@code #a0}, or {@code #p0}.</li>
* <li>Method arguments can be accessed by name (with a preceding hash tag)
* if parameter names are available in the compiled byte code.</li>
* </ul>
*/
String condition() default "";
/**
* An optional identifier for the listener, defaulting to the fully-qualified
* signature of the declaring method (e.g. "mypackage.MyClass.myMethod()").
* @since 5.3.5
* @see SmartApplicationListener#getListenerId()
* @see ApplicationEventMulticaster#removeApplicationListeners(Predicate)
*/
String id() default "";
}
|
package com.practicejava2;
abstract class Coffee {
void waitCoffee() {
System.out.println("Please, wait a minute for coffee");
}
public void makeLatte() {
}
public void makeAmericano() {
}
public void makeTea() {
}
}
|
package com.courses.dao;
import com.courses.exc.DaoException;
import com.courses.model.Course;
import org.sql2o.Query;
import java.util.List;
public interface CourseDao {
void add(Course course) throws DaoException;
List<Course> findALl();
Course findById(int id);
}
|
/*
* 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 buscadordenumeros;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
/**
*
* @author user
*/
public class BuscadorDeNumeros {
//Timer timer = new Timer();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Timer timer = new Timer();
//s'ha de crear un llista amb numeros ordenats
Scanner lc = new Scanner(System.in);
ArrayList<Integer> llista = new ArrayList<>();
for (int i = 0; i <= 500000; i++) {
llista.add(i);
//System.out.println(i);
}
System.out.println("Introdueix numero a buscar: ");
int num = lc.nextInt();
long start = System.currentTimeMillis();
if (llista.contains(num)) {
//guardem el temps actual a la variable end.
long end = System.currentTimeMillis();
System.out.println("Trobat en : " + ((end - start)) + "milliseconds");
}else{
System.out.println("No s'ha trobat el numero.");
}
}
}
|
package io.ceph.rgw.client.model.notification;
import io.ceph.rgw.client.model.Response;
/**
* A response of an <a href="https://docs.ceph.com/docs/master/radosgw/pubsub-module/">subscribe operation</a>.
*
* @author zhuangshuo
* Created by zhuangshuo on 2020/8/24.
* @see SubscribeRequest
* @see io.ceph.rgw.client.SubscribeClient
*/
public interface SubscribeResponse extends Response {
}
|
package main;
import entity.Hotel;
import java.util.Scanner;
import controller.Program;
/**
*
* @author Peter
*/
public class Main {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Program p = new Program();
p.welcome();
}
}
|
package paketmalimslovima;
import java.util.Scanner;
public class Zadatak_1_15082019 {
// Napisati program - meni - za izracunavanje i ispis povrsina
// geometrijskih tela (kocke, kvadra, valjka, lopte). Koristiti
// do while petlju i switch grananje. Za izlaz koristiti nulu (0).
public static void main(String[] args) {
Scanner ulaz = new Scanner(System.in);
double a, b, c, r, p;
int izbor;
do {
System.out.println("Izaberite geometrijesko telo ciju povrsinu zelite da izracunate: ");
System.out.println(" 1 - kocka");
System.out.println(" 2 - kvadar");
System.out.println(" 3 - valjak");
System.out.println(" 4 - lopta");
System.out.println(" 0 - izlaz iz programa");
izbor = ulaz.nextInt();
switch(izbor) {
case 1:
System.out.println("Unesite dimenziju stranica kocke u cm2: ");
a = ulaz.nextDouble();
p = a*a*6;
System.out.println("Povrsina Vase kocke iznosi: " + p + " cm2.");
System.out.println();
break;
case 2:
System.out.println("Unesite dimenzije stranica kvadra 'a', 'b' i 'c' u cm2: ");
a = ulaz.nextDouble();
b = ulaz.nextDouble();
c = ulaz.nextDouble();
p = a*b*2 + b*c*2 + a*c*2;
System.out.println("Povrsina Vaseg kvadra iznosi: " + p + " cm2.");
System.out.println();
break;
case 3:
System.out.println("Unesite dimenzije visine i poluprecnika Vaseg valjka u cm2: ");
a = ulaz.nextDouble();
r = ulaz.nextDouble();
p = r*r*3.14 + a*2*r*3.14;
System.out.println("Povrsina Vase kocke iznosi: " + p + " cm2.");
System.out.println();
break;
case 4:
System.out.println("Unesite dimenziju poluprecnika Vaseg kruga u cm2: ");
r = ulaz.nextDouble();
p = 4*r*r*3.14;
System.out.println("Povrsina Vaseg kruga iznosi: " + p + " cm2.");
System.out.println();
break;
default:
System.out.println("Pogresan unos.");
System.out.println();
break;
case 0:
System.out.println("Izlazak iz programa.");
}
} while (izbor != 0);
}
}
|
package cn.test.equals;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Created by xiaoni on 2019/3/25.
*/
@Data
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class User2 {
String name;
String sex;
String idCard;
}
|
package pp;
import hlp.MyHttpClient;
import pp.model.AModel;
import pp.model.xml.CGlad;
import pp.service.GlRuService;
import pp.service.GlRuServiceImpl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GetHostelGlads {
public static void main(String[] args) {
MyHttpClient client = new MyHttpClient();
client.appendInitialCookie("cookie_lang_3", "rus", Settings.getServer());
GlRuService service = new GlRuServiceImpl(client, new GlRuParser(), Settings.getServer());
try {
service.login(Settings.getUser(), Settings.getPassw());
service.visitMyGladiators();
Utils.sout("Hostel glads:\n");
for (AModel hostelGladId : service.getHostelGlads().values()) {
Utils.sout(hostelGladId.getId() + "\n");
}
for (AModel hostelGladId : service.getHostelGlads().values()) {
service.takeFromHostel(hostelGladId.getId());
Utils.sleep(500);
}
System.out.println("Done.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package pop3.command;
import pop3.Mailbox;
import pop3.Server;
import pop3.SessionState;
import static pop3.command.POP3Command.STAT;
public class STATCommandExecutor implements CommandExecutor {
@Override
public ServerResponse execute(Session session, Server server) {
CommandValidatorUtils.validateState(STAT.getCommand(), session, SessionState.TRANSACTION);
Mailbox mail = server.getUserMailbox(session.getUser());
return new ServerResponse(true, mail.getMessageCount() + " " + mail.getMailSize());
}
}
|
package org.maple.mr1;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
/**
* @Author Mapleins
* @Date 2019-04-16 22:35
* @Description
*/
/**
* TableMapper<KEYOUT, VALUEOUT> extends Mapper<ImmutableBytesWritable, Result, KEYOUT, VALUEOUT>
* 这里的前两个参数是写死的
* ImmutableBytesWritable:是rowkey
* Result:是值
* 所以我们 map 阶段可以直接输出同样的keyout
*/
public class FruitMapper extends TableMapper<ImmutableBytesWritable, Put> {
@Override
protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {
// 构建put对象
Put put = new Put(key.get());
Cell[] cells = value.rawCells();
for (Cell cell : cells) {
if("name".equals(Bytes.toString(CellUtil.cloneQualifier(cell)))){
put.add(cell);
}
}
context.write(key,put);
}
}
|
package com.harshitJaiswal.Patterns;
import java.util.Scanner;
public class Pattern12 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int lines = n;
int nst = 1;
int nsp = n-1;
for (int i = 0; i < lines; i++) {
for (int j = 0; j < nsp; j++) {
System.out.print("\t");
}
for (int j = 0; j < nst; j++) {
if ( j % 2 == 0) {
System.out.print("*\t");
} else {
System.out.print("!\t");
}
}
System.out.println();
nst += 2;
nsp -= 1;
}
}
}
|
package slimeknights.tconstruct.world.entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.storage.loot.LootTableList;
import javax.annotation.Nonnull;
import slimeknights.tconstruct.library.Util;
import slimeknights.tconstruct.shared.TinkerCommons;
import slimeknights.tconstruct.shared.block.BlockLiquidSlime;
import slimeknights.tconstruct.world.TinkerWorld;
public class EntityBlueSlime extends EntitySlime {
public static final ResourceLocation LOOT_TABLE = Util.getResource("entities/blueslime");
public EntityBlueSlime(World worldIn) {
super(worldIn);
}
// we're using this instead of getDropItem because we need the metadata
@Override
public EntityItem dropItemWithOffset(@Nonnull Item itemIn, int size, float offsetY) {
ItemStack stack = TinkerCommons.matSlimeBallBlue.copy();
stack.setCount(size);
return this.entityDropItem(stack, offsetY);
}
@Override
protected ResourceLocation getLootTable() {
return this.getSlimeSize() == 1 ? LOOT_TABLE : LootTableList.EMPTY;
}
@Nonnull
@Override
protected EntitySlime createInstance() {
return new EntityBlueSlime(this.getEntityWorld());
}
@Override
public boolean getCanSpawnHere() {
if(this.getEntityWorld().getBlockState(this.getPosition()).getBlock() instanceof BlockLiquidSlime) {
return true;
}
return this.getEntityWorld().getBlockState(this.getPosition().down()).getBlock() == TinkerWorld.slimeGrass;
}
@Override
protected boolean spawnCustomParticles() {
if(this.getEntityWorld().isRemote) {
int i = this.getSlimeSize();
for(int j = 0; j < i * 8; ++j) {
float f = this.rand.nextFloat() * (float) Math.PI * 2.0F;
float f1 = this.rand.nextFloat() * 0.5F + 0.5F;
float f2 = MathHelper.sin(f) * (float) i * 0.5F * f1;
float f3 = MathHelper.cos(f) * (float) i * 0.5F * f1;
double d0 = this.posX + (double) f2;
double d1 = this.posZ + (double) f3;
double d2 = this.getEntityBoundingBox().minY;
TinkerWorld.proxy.spawnSlimeParticle(this.getEntityWorld(), d0, d2, d1);
}
}
return true;
}
}
|
package algorithms.chap1;
public class test {
public static void main(String[] args) {
// ResizableArrayStack<String> stack = new ResizableArrayStack<String>();
LinkedListStack<String> stack = new LinkedListStack<>();
stack.push("Kaka");
stack.pop();
// stack.pop();
// stack.pop();
stack.push("Kaka1");
stack.push("Kaka2");
// stack.pop();
stack.push("Kaka3");
stack.push("Kaka4");
// stack.pop();
stack.push("Kaka5");
// stack.push("Kaka6");
// stack.list();
// System.out.println(stack.size());
// for (String s:stack ) {
// System.out.println(s);
// }
LinkedListQueue<Integer> queue = new LinkedListQueue<Integer>();
queue.push(1);
queue.pop();
queue.push(3);
queue.push(5);
queue.push(7);
queue.pop();
queue.push(9);
// queue.pop();
// System.out.println(queue.size());
for (Integer i:queue) {
System.out.println(i);
}
}
}
|
package org.celllife.stock.domain.alert;
import java.util.List;
import javax.persistence.QueryHint;
import org.celllife.stock.domain.drug.Drug;
import org.celllife.stock.domain.user.User;
import org.celllife.stock.framework.logging.LogLevel;
import org.celllife.stock.framework.logging.Loggable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.repository.annotation.RestResource;
@Loggable(LogLevel.DEBUG)
@RestResource(path = "alerts")
public interface AlertRepository extends PagingAndSortingRepository<Alert, Long> {
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
@Query("SELECT a FROM Alert a WHERE a.user = :user AND drug = :drug AND (status = 'NEW' OR status = 'SENT' OR status = 'RESOLVED')")
Alert findOneLatestByUserAndDrug(@Param("user") User user, @Param("drug") Drug drug);
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
@Query("SELECT a FROM Alert a WHERE a.user = :user AND (status = 'NEW' OR status = 'SENT')")
List<Alert> findOpenByUser(@Param("user") User user);
@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value ="true") })
@Query("SELECT a FROM Alert a WHERE a.user = :user AND status = 'NEW'")
List<Alert> findNewByUser(@Param("user") User user);
@Query("select new org.celllife.stock.domain.alert.AlertSummaryDto("
+ "u.msisdn, u.clinicCode, u.clinicName, u.coordinates, "
+ "(select count(*) from Alert a1 where a1.user = u.id and a1.status in ('NEW','SENT') and a1.level = 1), "
+ "(select count(*) from Alert a2 where a2.user = u.id and a2.status in ('NEW','SENT') and a2.level = 2), "
+ "(select count(*) from Alert a3 where a3.user = u.id and a3.status in ('NEW','SENT') and a3.level = 3)"
+ ") "
+ "from User u "
+ "group by u.msisdn, u.clinicCode, u.clinicName")
List<AlertSummaryDto> calculateAlertSummary();
}
|
package nettydemo.provider;
import nettydemo.publicInterface.HelloService;
public class HelloServiceImpl implements HelloService {
@Override
public String hello(String msg) {
return msg != null ? msg + "------------------>>>>> get Message" : " get Message";
}
}
|
package com.binarysprite.evemat.page.character;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import com.beimin.eveapi.core.ApiAuthorization;
import com.beimin.eveapi.core.ApiException;
import com.beimin.eveapi.eve.character.CharacterInfoParser;
import com.beimin.eveapi.eve.character.CharacterInfoResponse;
import com.binarysprite.evemat.Constants;
import com.binarysprite.evemat.component.ExternalImage;
import com.binarysprite.evemat.entity.AccountCharacter;
import com.binarysprite.evemat.page.FramePage;
import com.binarysprite.evemat.page.character.data.CharacterPortrait;
import com.binarysprite.evemat.util.EveImageService;
import com.google.inject.Inject;
@SuppressWarnings("serial")
public class CharacterPage extends FramePage {
/**
* ポートレイトリストのモデルです。
*/
private final IModel<List<CharacterPortrait>> portraitModel = new LoadableDetachableModel<List<CharacterPortrait>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<CharacterPortrait> load() {
final List<AccountCharacter> accountCharacters = characterPageService.get();
final List<CharacterPortrait> characterPortraits = new ArrayList<CharacterPortrait>();
for (AccountCharacter accountCharacter : accountCharacters) {
ApiAuthorization apiAuthorization = new ApiAuthorization(accountCharacter.getApiId(),
accountCharacter.getCharacterId(), accountCharacter.getApiVerificationCode());
try {
CharacterInfoResponse characterInfoResponse = CharacterInfoParser.getInstance().getResponse(
apiAuthorization);
characterPortraits.add(new CharacterPortrait(EveImageService.getCharacterPortrait(
accountCharacter.getCharacterId(), EveImageService.CharacterPortraitSize.PIXEL_256),
characterInfoResponse.getCharacterName(), characterInfoResponse.getCorporation(),
characterInfoResponse.getLastKnownLocation(), characterInfoResponse.getShipTypeName(),
Constants.QUANTITY_FORMAT.format(characterInfoResponse.getSkillPoints().longValue()),
Constants.PRICE_FORMAT.format(characterInfoResponse.getAccountBalance()),
Constants.SECURITY_FORMAT.format(characterInfoResponse.getSecurityStatus())));
} catch (ApiException e) {
e.printStackTrace();
}
}
return characterPortraits;
}
};
/**
* ポートレイトリストです。
*/
private final ListView<CharacterPortrait> listView = new ListView<CharacterPortrait>("portraits", portraitModel) {
protected void populateItem(ListItem<CharacterPortrait> item) {
final CharacterPortrait portrait = (CharacterPortrait) item.getModelObject();
item.add(new ExternalImage("picture", portrait.picture));
item.add(new Label("name", portrait.name));
item.add(new Label("corporation", portrait.corporation));
item.add(new Label("location", portrait.location));
item.add(new Label("activeShip", portrait.activeShip));
item.add(new Label("skills", portrait.skills));
item.add(new Label("wealth", portrait.wealth));
item.add(new Label("securityStatus", portrait.securityStatus));
}
};
/**
*
*/
@Inject
private CharacterPageService characterPageService;
/**
* キャラクターページのコンストラクタです。
*/
public CharacterPage() {
super();
/*
* コンポーネントの生成
*/
final Label title = new Label(WICKET_ID_PAGE_TITLE_LABEL, "Character");
/*
* コンポーネントの追加
*/
this.add(title);
this.add(listView);
}
}
|
package cn.novelweb.tool.upload.fastdfs.client;
import cn.novelweb.tool.upload.fastdfs.model.GroupState;
import cn.novelweb.tool.upload.fastdfs.model.StorageNode;
import cn.novelweb.tool.upload.fastdfs.model.StorageNodeInfo;
import cn.novelweb.tool.upload.fastdfs.model.StorageState;
import java.util.List;
/**
* <p>目录服务(Tracker)客户端接口</p>
* <p>2020-02-03 17:29</p>
*
* @author LiZW
**/
public interface TrackerClient {
/**
* 获取一个存储节点信息
*
* @return 存储节点信息
*/
StorageNode getStorageNode();
/**
* 根据组名称获取一个Group下面的一个存储节点名称
*
* @param groupName 组名称
* @return 存储节点信息, 不存在返回null
*/
StorageNode getStorageNode(String groupName);
/**
* 获取文件存储的源存储节信息
*
* @param groupName 组名称
* @param filename 文件路径
* @return 源存储节点信息
*/
StorageNodeInfo getFetchStorage(String groupName, String filename);
/**
* 获取文件存储的源存储节信息(toUpdate=true)
*
* @param groupName 组名称
* @param filename 文件路径
* @return 源存储节点信息
*/
StorageNodeInfo getFetchStorageAndUpdate(String groupName, String filename);
/**
* 获取存储组的状态
*
* @return 存储组状态集合,不存在返回空集合
*/
List<GroupState> getGroupStates();
/**
* 获取一个存储组里的所有存储服务节点状态信息
*
* @param groupName 组名称
* @return 存储节点状态信息集合,不存在返回空集合
*/
List<StorageState> getStorageStates(String groupName);
/**
* 获取一个存储组里的某个存储服务节点状态信息
*
* @param groupName 组名称
* @param storageIp 储服节点IP地址
* @return 存储节点状态信息,不存在返回null
*/
StorageState getStorageState(String groupName, String storageIp);
/**
* 把存储节点踢出到集群之外(此存储节点必须已关闭才能进行此操作,不然操作会失败)
*
* @param groupName 组名称
* @param storageIp 储服节点IP地址
* @return 返回true表示操作成功
*/
boolean deleteStorage(String groupName, String storageIp);
}
|
package com.oracle.handler;
import com.oracle.vo.Item;
import com.oracle.vo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("order")
public class OrderHandler {
static int count=0;
//可以 远程调用,调用其它服务的controller
@Autowired
RestTemplate restTemplate;
//不要导错包,org.springframework.cloud.client.discovery.DiscoveryClient;
//0624负载均衡不用这个了
// @Autowired
// DiscoveryClient discoveryClient;
//生成订单
//@PostMapping("make")
@GetMapping("make")
public Order make(String name,String items){
//获得商品号,
String[] ids=items.split(",");
Order order=new Order();
order.setOrderNo(++count);
order.setUserName(name);
List<Item> list=new ArrayList<Item>();
//0624加了负载均衡后下面的四行都不用了,即使只有一个服务器也可以,但是别忘了配置@LoadBalance。
//获取当前应用发布的实例,0620 provider的名,!!!!,有几个实例就返回几个。
// List<ServiceInstance> services=discoveryClient.getInstances("EUREKA-PROVIDER");
// System.out.println("EUREKA-PROVIDER此服务的size:"+services.size());
// //只有一个,调第一个,以后如果再注册了一个叫EUREKA-PROVIDER的服务,就可以 轮询 了,高可用,
// String url=services.get(0).getUri().toString();//主机+ip
// System.out.println("url:"+url);
//远程调用商品微服务,
for (String id : ids) {
Integer itemNo=Integer.valueOf(id);
//对方的方法是get的哦
//改了这里!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//Item item=restTemplate.getForObject("http://localhost:8001/item/get?itemNo={itemNo}", Item.class,itemNo );
//调用另一个微服务的controller ,后面这个是固定的,但是前面的有可能变化,!!!!!!!!(多个eureka)
//Item item=restTemplate.getForObject(url+"/item/get?itemNo={itemNo}",Item.class,itemNo);
//0624 ribbon配置负载均衡后,负载均衡的 不用discoveryClient的那个url了,直接写服务名就行了!!!!!!!!!!!!(多个服务了)
Item item=restTemplate.getForObject("http://EUREKA-PROVIDER/item/get?itemNo={itemNo}",Item.class,itemNo);
System.out.println("从商品微服务中获得数据:"+item);
list.add(item);
}
order.setItems(list);
System.out.println("生成的订单是"+order);
return order;
}
//远程调用 添加商品
@PostMapping("saveItem")
public Item save(Item item){
Map<String,Object> map=new HashMap<String, Object>();
map.put("itemNo", item.getItemNo());
map.put("name", item.getName());
map.put("price", item.getPrice());
map.put("count", item.getCount());
//对方的方法是post的哦
restTemplate.postForObject("http://localhost:8001/item/save", map, Item.class);
System.out.println("8002添加成功了:"+item);
return item;
}
}
|
package com.example.elasticsearch.demo.document;
import lombok.Data;
@Data
public class ProfileDocument {
private String id;
private String name;
}
|
package com.jeeconf.kafka.embedded;
import com.netflix.config.ConfigurationManager;
import org.apache.camel.CamelContext;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.util.*;
@Configuration
@ConditionalOnProperty(prefix = "embedded.kafka", name = "enabled", havingValue = "true", matchIfMissing = true)
@AutoConfigureBefore(CamelAutoConfiguration.class)
public class EmbeddedKafkaAutoConfiguration {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean
public EmbeddedZookeeper embeddedZookeeper() {
int zookeeperPort = TestUtils.getAvailablePort();
EmbeddedZookeeper embeddedZookeeper = new EmbeddedZookeeper(zookeeperPort);
try {
embeddedZookeeper.startup();
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return embeddedZookeeper;
}
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean
public EmbeddedKafkaCluster embeddedKafkaCluster(EmbeddedZookeeper embeddedZookeeper) {
List<Integer> kafkaPorts = new ArrayList<Integer>();
// -1 for any available port
// number of ports == number of brokers
kafkaPorts.add(TestUtils.getAvailablePort());
EmbeddedKafkaCluster embeddedKafkaCluster = new EmbeddedKafkaCluster(embeddedZookeeper.getConnection(),
new Properties(), kafkaPorts);
logger.debug("Embedded Zookeeper connection: " + embeddedZookeeper.getConnection());
embeddedKafkaCluster.startup();
logger.debug("Embedded Kafka cluster broker list: " + embeddedKafkaCluster.getBrokerList());
return embeddedKafkaCluster;
}
@Configuration
@ConditionalOnClass(ConfigurationManager.class)
public static class ConfigSettingsSetup {
@Bean
public EmbeddedKafkaInfo embeddedKafkaInfo(EmbeddedKafkaCluster embeddedKafkaCluster) {
ConfigurationManager.getConfigInstance().setProperty("kafka.brokerList", embeddedKafkaCluster.getBrokerList());
return new EmbeddedKafkaInfo(embeddedKafkaCluster.getBrokerList(), embeddedKafkaCluster.getZkConnection());
}
public static class EmbeddedKafkaInfo {
public final String brokerList;
public final String zookeeperConnect;
public EmbeddedKafkaInfo(String brokerList, String zookeeperConnect) {
this.brokerList = brokerList;
this.zookeeperConnect = zookeeperConnect;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("EmbeddedKafkaInfo{");
sb.append("brokerList='").append(brokerList).append('\'');
sb.append(", zookeeperConnect='").append(zookeeperConnect).append('\'');
sb.append('}');
return sb.toString();
}
}
}
/**
* Additional configuration to ensure that {@link org.apache.camel.CamelContext} beans
* depend-on the embedded kafka bean and configuration was setup into archaius.
*/
@Configuration
@ConditionalOnClass({CamelContext.class, ConfigurationManager.class})
protected static class KafkaCamelDependencyConfiguration
implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
List<String> camelContexts = Arrays.asList(beanFactory
.getBeanNamesForType(CamelContext.class, true, true));
camelContexts.stream().forEach(
beanName -> setupDependsOn(beanFactory, beanName)
);
}
private void setupDependsOn(ConfigurableListableBeanFactory beanFactory, String beanName) {
BeanDefinition bean = beanFactory.getBeanDefinition(beanName);
Set<String> dependsOn = new LinkedHashSet<String>(asList(bean.getDependsOn()));
dependsOn.add("embeddedKafkaInfo");
bean.setDependsOn(dependsOn.toArray(new String[dependsOn.size()]));
}
private List<String> asList(String[] array) {
return (array == null ? Collections.<String>emptyList() : Arrays.asList(array));
}
}
}
|
/**
* Description: Unicodes characters
* @Author Elena Villalon
* email:evillalon@iq.harvard.edu
*
*/
package edu.harvard.iq.vdcnet;
public enum Ucnt {
dot('\u002E'), //decimal separator "."
plus('\u002b'),//"+" sign
min('\u002d'),//"-"
e('\u0065'), //"e"
percntg('\u0025'),//"%"
pndsgn('\u0023'), //"#"
zero('\u0030'), //'0'
s('\u0073'),//"s"
nil('\u0000'), //'\0' for null terminator
frmfeed('\u000C'), //form feed
ls('\u2028'),//line separator
nel('\u0085'),//next line
psxendln('\n'); //posix end-of-line
private final char ucode;
Ucnt(char c){
this.ucode = c;
}
public char getUcode(){return ucode;}
}
|
/* $Id$ */
package djudge.judge.executor;
import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import org.apache.log4j.Logger;
import utils.FileTools;
import djudge.common.Deployment;
import djudge.common.JudgeDirs;
import djudge.judge.dcompiler.DistributedFileset;
public class LocalExecutor implements ExecutorLinuxExitCodes
{
private final static Logger log = Logger.getLogger(LocalExecutor.class);
public final static String standardErrorFileName = "stderr.txt";
public final static String standardOutputFileName = "stdout.txt";
private void executeWindowsNT(ExecutorTask task, String workDir, ExecutionResult res)
{
// preparing `crutch`
FileTools.copyFile(workDir + "invoke.dll", JudgeDirs.getToolsDir() + "winnt/invoke.dll");
FileTools.copyFile(workDir + "run.exe", JudgeDirs.getToolsDir() + "winnt/run.exe");
FileTools.copyFile(workDir + "crutch.exe", JudgeDirs.getToolsDir() + "winnt/crutch.exe");
ExecutorFiles files = task.files;
ExecutorLimits limits = task.limits;
ExecutorProgram pr = task.program;
// Building command line
StringBuffer cmd = new StringBuffer();
cmd.append(" -Xifce ");
//if (limits.fCreateSubprocess)
//FIXME - Security bug: allows all runned programs create child processes
cmd.append(" -Xacp ");
// if (files.rootDirectory != null && files.rootDirectory != "")
// cmd.append(" -d \"" + files.rootDirectory.replace('/', '\\') + "\" ");
if (limits.timeLimit > 0)
{
cmd.append(" -t " + limits.timeLimit + "ms ");
// Idleness
cmd.append(" -y " + (2 * limits.timeLimit) + "ms ");
}
if (limits.memoryLimit > 0)
cmd.append(" -m " + limits.memoryLimit + " ");
if (files.inputFilename != null && files.inputFilename != "")
cmd.append(" -i \"" + files.inputFilename + "\" ");
if (files.outputFilename != null && files.outputFilename != "")
cmd.append(" -o \"" + files.outputFilename + "\" ");
else
cmd.append(" -o \"" + standardOutputFileName + "\" ");
if (files.errorFilename != null && files.errorFilename != "")
cmd.append(" -e \"" + files.errorFilename + "\" ");
else
cmd.append(" -e \"" + standardErrorFileName + "\" ");
// FIXME
cmd = new StringBuffer("run.exe " + cmd + " \"" + pr.getCommand(workDir) + "\"");
cmd = new StringBuffer(workDir + "crutch.exe " + workDir + " " + cmd);
log.debug("Executing " + cmd);
try
{
Process process = Runtime.getRuntime().exec(cmd.toString());
try
{
process.waitFor();
}
catch (Exception exc)
{
System.out.println("!!! Exception catched (while waiting for external runner): " + exc);
}
int retValue = process.exitValue();
long mem = 0, time = 0, cnt = 0, output = 0;
if (files.outputFilename != null)
{
output = new File(files.outputFilename).length();
}
// Return values of external runner
switch (retValue)
{
case 0: res.result = ExecutionResultEnum.OK; break;
case -1: res.result = ExecutionResultEnum.TimeLimitExceeeded; break;
case -2: res.result = ExecutionResultEnum.MemoryLimitExceeded; break;
case -3: res.result = ExecutionResultEnum.TimeLimitExceeeded; break;
case -4: res.result = ExecutionResultEnum.RuntimeErrorGeneral; break;
// FIXME
default: res.result = ExecutionResultEnum.RuntimeErrorGeneral;
}
// Parsing runner's output
try
{
BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String runnerOut = "";
while ((line = out.readLine()) != null)
{
runnerOut += line + "\n";
cnt++;
// exit code
if (cnt == 3 && res.result == ExecutionResultEnum.OK)
{
try
{
String token = line.substring(line.lastIndexOf(" ") + 1, line.length());
retValue = Integer.parseInt(token);
if (retValue != 0)
{
res.result = ExecutionResultEnum.NonZeroExitCode;
}
}
catch (Exception ex){ };
}
// time
if (cnt == 4 && res.result == ExecutionResultEnum.OK)
{
try
{
String token = line.substring(line.indexOf(':') + 1, line.lastIndexOf("of") - 1);
Double val = Double.parseDouble(token);
time = (long)Math.round(val * 1000.0);
}
catch (Exception ex){ }
}
//memory
else if (cnt == 6 && res.result == ExecutionResultEnum.OK)
{
try
{
String token = line.substring(line.lastIndexOf(" ") + 2, line.lastIndexOf("of") - 1);
mem = Integer.parseInt(token);
}
catch (Exception ex){ }
}
res.runnerOutput = runnerOut;
}
out.close();
}
catch (Exception exc)
{
System.out.println("!!! IOException catched (while parsing runner's stdout): " + exc);
}
// Cleaning crutch
FileTools.deleteFile(workDir + "invoke.dll");
FileTools.deleteFile(workDir + "run.exe");
FileTools.deleteFile(workDir + "crutch.exe");
res.exitCode = retValue;
res.memoryConsumed = mem;
res.outputGenerated = output;
res.timeConsumed = time;
if (files.outputFilename != null && files.outputFilename != "")
{
res.outputGenerated = new File(workDir + files.outputFilename).length();
}
else
{
res.outputGenerated = new File(workDir + standardOutputFileName).length();
}
if (task.returnDirectoryContent)
{
res.files = new DistributedFileset();
res.files.readDirectory(workDir);
}
}
catch (IOException exc)
{
System.out.println("!!! IOException catched: " + exc);
}
FileTools.saveToFile(cmd.toString() + "\n\n" + res.runnerOutput, workDir + "runner.data");
}
private String quote(String param)
{
return param.contains(" ") ? "\"" + param + "\"" : param;
}
private void executeLinux(ExecutorTask task, String workDir, ExecutionResult res)
{
ExecutorFiles files = task.files;
ExecutorLimits limits = task.limits;
ExecutorProgram pr = task.program;
/* Building command line */
// single-line params
StringBuffer cmd = new StringBuffer();
// vector<string> of params
Vector<String> params = new Vector<String>();
// setting time limit
if (limits.timeLimit > 0)
{
cmd.append(" -c " + limits.timeLimit + "ms ");
// Idleness
cmd.append(" -r " + (2 * limits.timeLimit) + "ms ");
params.add("-c");
params.add("" + limits.timeLimit + "ms");
params.add("-r");
params.add("" + (2 * limits.timeLimit) + "ms");
}
//if (!task.program.command.startsWith("/"))
{
cmd.append(" -d " + quote(FileTools.getAbsolutePath(workDir)));
params.add("-d");
params.add(FileTools.getAbsolutePath(workDir));
}
// verbose param (for debug)
// cmd.append(" -v ");
// params.add("-v");
// setting memory limit
if (limits.memoryLimit > 0)
{
cmd.append(" -m " + limits.memoryLimit + " ");
params.add("-m");
params.add("" + limits.memoryLimit);
// for java
params.add("-p");
}
/* Redirecting I/O stream */
if (files.inputFilename != null && files.inputFilename != "")
{
cmd.append(" -I " + quote(files.inputFilename));
params.add("-I");
params.add(files.inputFilename);
}
if (files.outputFilename != null && files.outputFilename != "")
{
cmd.append(" -O " + quote(files.outputFilename));
params.add("-O");
params.add(files.outputFilename);
}
else
{
cmd.append(" -O " + quote(standardOutputFileName));
params.add("-O");
params.add(standardOutputFileName);
}
if (files.errorFilename != null && files.errorFilename != "")
{
cmd.append(" -E " + quote(files.errorFilename));
params.add("-E");
params.add(files.errorFilename);
}
else
{
cmd.append(" -E " + quote(standardErrorFileName));
params.add("-E");
params.add(standardErrorFileName);
}
// FIXME
cmd = new StringBuffer(workDir + "runner " + cmd + " " + quote(pr.getCommand(workDir)));
params.add(pr.getCommand(workDir));
// adding runner as first param
params.add(0, JudgeDirs.getToolsDir() + "linux/runner");
try
{
Process process = Runtime.getRuntime().exec(params.toArray(new String[0]));
try
{
process.waitFor();
}
catch (Exception exc)
{
log.fatal("Unknown exception catched (while waiting for external runner)", exc);
}
int retValue = process.exitValue();
long mem = 0, time = 0, cnt = 0, output = 0;
if (files.outputFilename != null)
{
output = new File(files.outputFilename).length();
}
// Return values of external runner
switch (retValue)
{
case EXIT_OK: res.result = ExecutionResultEnum.OK; break;
case EXIT_TLE: res.result = ExecutionResultEnum.TimeLimitExceeeded; break;
case EXIT_MLE: res.result = ExecutionResultEnum.MemoryLimitExceeded; break;
case EXIT_RE: res.result = ExecutionResultEnum.RuntimeErrorGeneral; break;
case EXIT_OLE: res.result = ExecutionResultEnum.OutputLimitExceeded; break;
case EXIT_IE: res.result = ExecutionResultEnum.InternalError; break;
case EXIT_SIGNAL_SIGKILL: res.result = ExecutionResultEnum.TimeLimitExceeeded; break;
default: res.result = ExecutionResultEnum.Other;
}
// Parsing runner's output
try
{
BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String runnerOut = "";
while ((line = out.readLine()) != null)
{
runnerOut += line + "\n";
cnt++;
// exit code
if (cnt == 6)
{
try
{
String token = line.substring(line.lastIndexOf("\t") + 1);
retValue = Integer.parseInt(token);
if (retValue != 0)
{
res.result = ExecutionResultEnum.NonZeroExitCode;
}
}
catch (Exception ex){ };
}
// time
if (cnt == 2)
{
try
{
String token = line.substring(line.lastIndexOf("\t") + 1);
long val = Long.parseLong(token);
time = val;
if (limits.timeLimit > 0 && limits.timeLimit < time)
{
res.result = ExecutionResultEnum.TimeLimitExceeeded;
}
}
catch (Exception ex){ ex.printStackTrace(); }
}
//memory
else if (cnt == 4)
{
try
{
String token = line.substring(line.lastIndexOf("\t") + 1);
long val = Long.parseLong(token);
mem = val;
if (limits.memoryLimit > 0 && limits.memoryLimit < mem)
{
res.result = ExecutionResultEnum.MemoryLimitExceeded;
}
}
catch (Exception ex){ }
}
res.runnerOutput = runnerOut;
}
out.close();
}
catch (IOException ex)
{
log.error("IOException catched (while parsing runner's stdout)", ex);
}
res.exitCode = retValue;
res.memoryConsumed = mem;
res.outputGenerated = output;
res.timeConsumed = time;
if (files.outputFilename != null && files.outputFilename != "")
{
res.outputGenerated = new File(workDir + files.outputFilename).length();
}
else
{
res.outputGenerated = new File(workDir + standardOutputFileName).length();
}
if (task.returnDirectoryContent)
{
res.files = new DistributedFileset();
res.files.readDirectory(workDir);
}
}
catch (Exception ex)
{
log.error("IOException catched (while parsing runner's stdout)", ex);
}
FileTools.saveToFile("Executed command:\n" + cmd.toString() + "\n\n" + res.runnerOutput, workDir + "/runner.data");
log.info("Command: " + cmd.toString());
log.info("Result: " + res.getResult() + " exit code: " + res.getExitCode());
}
public ExecutionResult execute(ExecutorTask task, String workDir)
{
ExecutionResult res = new ExecutionResult();
/* If no working directory is set */
if (null == workDir)
{
/* Generating name for working directory */
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS");
String id = dateFormat.format(new Date()) + "_ex";
workDir = JudgeDirs.getWorkDir() + id + "/";
}
else
{
// linux porting issue (under code review - issue #13)
if (Deployment.isOSWinNT())
{
if (!workDir.endsWith("\\"))
workDir = workDir + "\\";
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS");
String id = dateFormat.format(new Date());
workDir = workDir.substring(0, workDir.length() - 1) + id + "/";
}
log.trace("Executing " + task + " in `" + workDir + "'");
new File(workDir).mkdirs();
res.tempDir = workDir;
/* Unpacking files to execute (if any) to the working directory */
task.program.files.unpack(workDir);
if (Deployment.isOSWinNT())
{
executeWindowsNT(task, workDir, res);
}
else if (Deployment.isOSLinux())
{
executeLinux(task, workDir, res);
}
else
{
log.fatal("Your OS is not supported");
}
// TODO: probable enable this in release version
//FileWorks.deleteDirectory(workDir);
return res;
}
public ExecutionResult execute(ExecutorTask task)
{
return execute(task, null);
}
}
|
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import com.example.myapplication.adduser.addUserFragment;
import com.example.myapplication.show_Task.showTaskFragment;
public class MainActivity extends AppCompatActivity {
private FrameLayout frameLayout;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = findViewById(R.id.frameLayout);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,new addUserFragment(),null).commit();
}
});
}
}
|
package com.example.Haegertime_diego_spring.services;
import com.example.Haegertime_diego_spring.exceptions.UserAlreadyExistsException;
import com.example.Haegertime_diego_spring.exceptions.UserNotFoundException;
import com.example.Haegertime_diego_spring.model.Employee;
import com.example.Haegertime_diego_spring.repositories.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeService {
private final EmployeeRepository employeeRepository;
@Autowired
public EmployeeService(EmployeeRepository employeeRepository){
this.employeeRepository = employeeRepository;
}
public List<Employee> showAllEmployees(){
return employeeRepository.findAll();
}
public Employee showEmployee(Long id) throws UserNotFoundException {
Optional<Employee> employee = employeeRepository.findById(id);
if(employee.isPresent()){
return employee.get();
}
else
{
throw new UserNotFoundException("Employee with id " + id +
" does not exist");
}
}
public String deleteEmployee(Long id) throws UserNotFoundException {
Optional<Employee> employee = employeeRepository.findById(id);
if(employee.isPresent()){
employeeRepository.deleteById(id);
return "The user with id " + id + " was deleted";
}
else
{
throw new UserNotFoundException("Employee with id " + id +
" does not exist");
}
}
public Employee createEmployee(Employee employee) throws UserAlreadyExistsException {
Optional<Employee> foundEmployee = employeeRepository.findEmployeeByUsername(employee.getUsername());
if(foundEmployee.isPresent()){
throw new UserAlreadyExistsException("The user with username " + employee.getUsername() + " already exists");
}
return employeeRepository.save(employee);
}
public Employee updateEmployeeData(Employee employee) throws UserNotFoundException {
Employee employeeOriginal = employeeRepository.findById(employee.getEmployeeID()).orElseThrow(() ->
new UserNotFoundException("Employee with id " + employee.getEmployeeID() +
" does not exist"));
employeeOriginal.setPersonalData(employee.getPersonalData());
return employeeRepository.save(employeeOriginal);
}
public Employee updateEmployeeActive(Employee employee) throws UserNotFoundException {
Employee employeeOriginal = employeeRepository.findById(employee.getEmployeeID()).orElseThrow(() ->
new UserNotFoundException("Employee with id " + employee.getEmployeeID() +
" does not exist"));
employeeOriginal.setActive(employee.getActive());
return employeeRepository.save(employeeOriginal);
}
public Employee updateEmployeeUsername(Employee employee) throws UserNotFoundException, UserAlreadyExistsException {
Optional<Employee> foundEmployee = employeeRepository.findEmployeeByUsername(employee.getUsername());
if(foundEmployee.isPresent()){
throw new UserAlreadyExistsException("The user with username " + employee.getUsername() + " already exists");
}
Employee employeeOriginal = employeeRepository.findById(employee.getEmployeeID()).orElseThrow(() ->
new UserNotFoundException("Employee with id " + employee.getEmployeeID() +
" does not exist"));
employeeOriginal.setUsername(employee.getUsername());
return employeeRepository.save(employeeOriginal);
}
public Employee updateEmployeeRole(Employee employee) throws UserNotFoundException {
Employee employeeOriginal = employeeRepository.findById(employee.getEmployeeID()).orElseThrow(() ->
new UserNotFoundException("Employee with id " + employee.getEmployeeID() +
" does not exist"));
employeeOriginal.setRole(employee.getRole());
return employeeRepository.save(employeeOriginal);
}
}
|
package is.ru.aaad.RemindMe;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import is.ru.aaad.RemindMe.Helpers.LocationUtils;
import is.ru.aaad.RemindMe.Models.Location;
/**
* Created by Johannes Gunnar Heidarsson on 6.11.2014.
*/
public class LocationFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.location_detail, container, false);
return view;
}
public void changeLocation(Location location){
Log.d("LocationFragment", "changeLocation() called");
EditText name = (EditText) getView().findViewById(R.id.location_name);
name.setText(location.getName());
EditText radius = (EditText) getView().findViewById(R.id.location_radius);
radius.setText(location.getRadius().toString());
}
}
|
package com.example.borno;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
public class Alphabets extends AppCompatActivity {
Button a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alphabets);
final MediaPlayer vd1= MediaPlayer.create(this, R.raw.vd1);
final MediaPlayer vd2= MediaPlayer.create(this, R.raw.vd2);
final MediaPlayer vd3= MediaPlayer.create(this, R.raw.vd3);
final MediaPlayer vd4= MediaPlayer.create(this, R.raw.vd4);
final MediaPlayer vd5= MediaPlayer.create(this, R.raw.vd5);
final MediaPlayer vd6= MediaPlayer.create(this, R.raw.vd6);
final MediaPlayer vd7= MediaPlayer.create(this, R.raw.vd7);
final MediaPlayer vd8= MediaPlayer.create(this, R.raw.vd8);
final MediaPlayer vd9= MediaPlayer.create(this, R.raw.vd9);
final MediaPlayer vd10= MediaPlayer.create(this, R.raw.vd10);
final MediaPlayer vd11= MediaPlayer.create(this, R.raw.vd11);
final MediaPlayer vd12= MediaPlayer.create(this, R.raw.vd12);
final MediaPlayer vd13= MediaPlayer.create(this, R.raw.vd13);
final MediaPlayer vd14= MediaPlayer.create(this, R.raw.vd14);
final MediaPlayer vd15= MediaPlayer.create(this, R.raw.vd15);
final MediaPlayer vd16= MediaPlayer.create(this, R.raw.vd16);
final MediaPlayer vd17= MediaPlayer.create(this, R.raw.vd17);
final MediaPlayer vd18= MediaPlayer.create(this, R.raw.vd18);
final MediaPlayer vd19= MediaPlayer.create(this, R.raw.vd19);
final MediaPlayer vd20= MediaPlayer.create(this, R.raw.vd20);
final MediaPlayer vd21= MediaPlayer.create(this, R.raw.vd21);
final MediaPlayer vd22= MediaPlayer.create(this, R.raw.vd22);
final MediaPlayer vd23= MediaPlayer.create(this, R.raw.vd23);
final MediaPlayer vd24= MediaPlayer.create(this, R.raw.vd24);
final MediaPlayer vd25= MediaPlayer.create(this, R.raw.vd25);
final MediaPlayer vd26= MediaPlayer.create(this, R.raw.vd26);
a1=(Button)findViewById(R.id.a1);
a1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd1.start();
}
});
a2=(Button)findViewById(R.id.a2);
a2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd2.start();
}
});
a3=(Button)findViewById(R.id.a3);
a3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd3.start();
}
});
a4=(Button)findViewById(R.id.a4);
a4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd4.start();
}
});
a5=(Button)findViewById(R.id.a5);
a5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd5.start();
}
});
a6=(Button)findViewById(R.id.a6);
a6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd6.start();
}
});
a7=(Button)findViewById(R.id.a7);
a7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd7.start();
}
});
a8=(Button)findViewById(R.id.a8);
a8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd8.start();
}
});
a9=(Button)findViewById(R.id.a9);
a9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd9.start();
}
});
a10=(Button)findViewById(R.id.a10);
a10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd10.start();
}
});
a11=(Button)findViewById(R.id.a11);
a11.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd11.start();
}
});
a12=(Button)findViewById(R.id.a12);
a12.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd12.start();
}
});
a13=(Button)findViewById(R.id.a13);
a13.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd13.start();
}
});
a14=(Button)findViewById(R.id.a14);
a14.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd14.start();
}
});
a15=(Button)findViewById(R.id.a15);
a15.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd15.start();
}
});
a16=(Button)findViewById(R.id.a16);
a16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd16.start();
}
});
a17=(Button)findViewById(R.id.a17);
a17.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd17.start();
}
});
a18=(Button)findViewById(R.id.a18);
a18.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd18.start();
}
});
a19=(Button)findViewById(R.id.a19);
a19.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd19.start();
}
});
a20=(Button)findViewById(R.id.a20);
a20.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd20.start();
}
});
a21=(Button)findViewById(R.id.a21);
a21.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd21.start();
}
});
a22=(Button)findViewById(R.id.a22);
a22.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd22.start();
}
});
a23=(Button)findViewById(R.id.a23);
a23.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd23.start();
}
});
a24=(Button)findViewById(R.id.a24);
a24.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd24.start();
}
});
a25=(Button)findViewById(R.id.a25);
a25.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd25.start();
}
});
a26=(Button)findViewById(R.id.a26);
a26.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vd26.start();
}
});
}
}
|
package boisson;
public class Deca extends Boisson {
public Deca() {
description="Deca";
}
@Override
public double cout() {
return 9;
}
}
|
package com.example.vehicleapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class UpdateActivity extends AppCompatActivity {
public String model,make,licenseNumber,colour,transmission,fuelType,bodyStyle,condition,notes,year,numberDoors,mileage,engineSize,price;
public String Nmodel,Nmake,NlicenseNumber,Ncolour,Ntransmission,NfuelType,NbodyStyle,Ncondition,Nnotes,Nyear,NnumberDoors,Nmileage,NengineSize,Nprice;
public EditText modelText,yearText,makeText,priceText,licenseText,colourText,numberDoorsText,transmissionText,mileageText,fuelTypeText,engineSizeText,bodyStyleText,conditionText,notesText;
public int conYear,conPrice,conNumberDoors,conMileage,conEngineSize;
String URL = "http://10.0.2.2:8080/update_vehicle_json";
final HashMap<String,String> postValues = new HashMap<>();
public String apiKey;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
Intent intent = getIntent();
modelText = findViewById(R.id.vehicleModelEd2);
yearText = findViewById(R.id.vehicleYearEdit2);
makeText = findViewById(R.id.vehicleMakeEdit2);
priceText = findViewById(R.id.vehiclePriceEdit2);
licenseText = findViewById(R.id.vehicleLicenseEdit2);
colourText = findViewById(R.id.vehicleColourEdit2);
numberDoorsText = findViewById(R.id.vehicleNumberDoorsEdit2);
transmissionText = findViewById(R.id.vehicleTransmissionEdit2);
mileageText = findViewById(R.id.vehicleMileageEdit2);
fuelTypeText = findViewById(R.id.vehicleFuelType2);
engineSizeText = findViewById(R.id.vehicleEngineSizeEdit2);
bodyStyleText = findViewById(R.id.vehicleBodyStyleEdit2);
conditionText = findViewById(R.id.vehicleConditionEdit2);
notesText = findViewById(R.id.vehicleNotesEdit2);
model = intent.getStringExtra("model");
year = intent.getStringExtra("year");
make = intent.getStringExtra("make");
price = intent.getStringExtra("price");
licenseNumber = intent.getStringExtra("licenseNumber");
colour = intent.getStringExtra("colour");
numberDoors = intent.getStringExtra("numberDoors");
transmission = intent.getStringExtra("transmission");
mileage = intent.getStringExtra("mileage");
fuelType = intent.getStringExtra("fuelType");
engineSize = intent.getStringExtra("engineSize");
bodyStyle = intent.getStringExtra("bodyStyle");
condition = intent.getStringExtra("condition");
notes = intent.getStringExtra("notes");
apiKey = intent.getStringExtra("apiKey");
modelText.setText(model);
yearText.setText(year);
makeText.setText(make);
priceText.setText(price);
licenseText.setText(licenseNumber);
colourText.setText(colour);
numberDoorsText.setText(numberDoors);
transmissionText.setText(transmission);
mileageText.setText(mileage);
fuelTypeText.setText(fuelType);
engineSizeText.setText(engineSize);
bodyStyleText.setText(bodyStyle);
conditionText.setText(condition);
notesText.setText(notes);
conYear = Integer.parseInt(year);
conPrice = Integer.parseInt(price);
conNumberDoors = Integer.parseInt(numberDoors);
conMileage = Integer.parseInt(mileage);
conEngineSize = Integer.parseInt(engineSize);
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.updatemenu,menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.sendVehicle){
AlertDialog.Builder altdial = new AlertDialog.Builder(UpdateActivity.this);
altdial.setMessage("Are you sure you want to update this vehicle?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startAsyncUpdate();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("Dialog Header");
alert.show();
}
else if(id == R.id.vehicleLogo){
Intent homeIntent = new Intent(UpdateActivity.this,MainActivity.class);
startActivity(homeIntent);
}
return super.onOptionsItemSelected(item);
}
public void startAsyncUpdate()
{
updateAsyncTask update = new updateAsyncTask();
update.execute();
}
public class updateAsyncTask extends AsyncTask<Void,Void,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
modelText = findViewById(R.id.vehicleModelEd2);
yearText = findViewById(R.id.vehicleYearEdit2);
makeText = findViewById(R.id.vehicleMakeEdit2);
priceText = findViewById(R.id.vehiclePriceEdit2);
licenseText = findViewById(R.id.vehicleLicenseEdit2);
colourText = findViewById(R.id.vehicleColourEdit2);
numberDoorsText = findViewById(R.id.vehicleNumberDoorsEdit2);
transmissionText = findViewById(R.id.vehicleTransmissionEdit2);
mileageText = findViewById(R.id.vehicleMileageEdit2);
fuelTypeText = findViewById(R.id.vehicleFuelType2);
engineSizeText = findViewById(R.id.vehicleEngineSizeEdit2);
bodyStyleText = findViewById(R.id.vehicleBodyStyleEdit2);
conditionText = findViewById(R.id.vehicleConditionEdit2);
notesText = findViewById(R.id.vehicleNotesEdit2);
model = modelText.getText().toString();
make = makeText.getText().toString();
licenseNumber = licenseText.getText().toString();
colour = colourText.getText().toString();
transmission = transmissionText.getText().toString();
fuelType = fuelTypeText.getText().toString();
bodyStyle = bodyStyleText.getText().toString();
condition = conditionText.getText().toString();
notes = notesText.getText().toString();
//ints
year = (yearText.getText().toString());
price = (priceText.getText().toString());
numberDoors = (numberDoorsText.getText().toString());
mileage = (mileageText.getText().toString());
engineSize = (engineSizeText.getText().toString());
Gson gson = new Gson();
Vehicles veh = new Vehicles(model,conYear,make,conPrice,licenseNumber,colour,conNumberDoors,transmission,conMileage,fuelType,conEngineSize,bodyStyle,condition,notes,1);
String vehicleJson = gson.toJson(veh);
postValues.put("json",vehicleJson);
postValues.put("apiKey",apiKey);
String response ="";
URL url;
try {
url = new URL(URL);
//create connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writ = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
writ.write(getPostDataString(postValues));
writ.flush();
writ.close();
os.close();
int responseCode = conn.getResponseCode();
System.out.println("response " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK){
Toast.makeText(UpdateActivity.this,"Vehicle Deleted !",Toast.LENGTH_LONG).show();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((line= br.readLine())!=null){
response+=line;
}
}
else{
Toast.makeText(UpdateActivity.this,"Error on updating vehicle ",Toast.LENGTH_LONG).show();
response="";
}
}
catch(Exception e){
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
private String getPostDataString(HashMap<String,String>params)throws UnsupportedEncodingException {
StringBuilder res = new StringBuilder();
boolean first = true;
for(Map.Entry<String,String>entry:params.entrySet()){
if(first) {
first = false;
}
else {
res.append("&");
}
res.append(URLEncoder.encode(entry.getKey(),"UTF-8"));
res.append("=");
res.append(URLEncoder.encode(entry.getValue(),"UTF-8"));
}
return res.toString();
}
}
|
package com.ledungcobra.entites;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "EDUCATION_TYPE")
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
public class EducationType extends BaseEntity
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EDUCATION_TYPE_ID")
@EqualsAndHashCode.Include
private Long id;
public EducationType(String name)
{
this.name = name;
}
@Column(name = "NAME")
private String name;
@Override
public String toString()
{
return name;
}
}
|
/**
* Package for junior.pack2.p5.ch7 control.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-06-27
*/
package ru.job4j.control;
|
package kredivation.mrchai.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import kredivation.mrchai.R;
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
int quantity;
public CustomListAdapter(Activity context, String[] itemname, Integer[] imgid) {
super(context, R.layout.fragment_icedteafragment_list, itemname);
// TODO Auto-generated constructor stub
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_icedteafragment_list, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.product_list_name);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img_product);
TextView extratxt = (TextView) rowView.findViewById(R.id.price);
final TextView cart_product_quantity_tv = (TextView) rowView.findViewById(R.id.cart_product_quantity_tv);
ImageView cart_minus_img = (ImageView) rowView.findViewById(R.id.cart_minus_img);
ImageView cart_plus_img = (ImageView) rowView.findViewById(R.id.cart_plus_img);
cart_plus_img.setClickable(true);
cart_minus_img.setClickable(true);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("RS. " + 155);
cart_plus_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quantity++;
cart_product_quantity_tv.setText(quantity + "");
}
});
cart_minus_img.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
quantity--;
cart_product_quantity_tv.setText(quantity + "");
}
});
return rowView;
}
}
|
package coffee.command.payment;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import coffee.bean.ProductDataBean;
import coffee.commad.inter.CommandProcess;
public class GetChartList implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
request.setCharacterEncoding("utf-8");
ProductDataBean pl = ProductDataBean.getINSTANCE();
JSONArray jsonArray1 = new JSONArray();
jsonArray1 = pl.checkMonthSum();
request.setAttribute("mlist", jsonArray1);
return "/ajaxCome/test.jsp";
}
}
|
package com.pidgin4android.libraries;
public class ndkLib
{
static
{
System.loadLibrary("ndkLib");
}
public native String invokeNativeFunction();
}
|
package com.wxt.designpattern.abstractfactory.nodp;
/**
* @Auther: weixiaotao
* @ClassName Client
* @Date: 2018/10/22 20:54
* @Description:
*/
public class Client {
public static void main(String[] args) {
//创建装机工程师对象
ComputerEngineer engineer = new ComputerEngineer();
//告诉装机工程师自己选择的配件,让装机工程师组装电脑
engineer.makeComputer(1,1);
}
}
|
package com.pda.pda_android.activity.apps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.pda.pda_android.R;
import com.pda.pda_android.activity.UsersListActivity;
import com.pda.pda_android.activity.apps.detail.SsxxInfomationActivity;
import com.pda.pda_android.base.BaseActivity;
import com.pda.pda_android.bean.ScanUserBean;
import com.pda.pda_android.base.others.ContentUrl;
import com.pda.pda_android.db.Entry.UserBean;
import com.pda.pda_android.db.dbutil.UserDaoOpe;
import java.util.List;
/**
* 梁佳霖创建于:2018/10/29 10:16
* 功能:手术信息
*/
public class SSXXActivity extends BaseActivity {
private TextView tv_top_title;
private String title; //顶部title
private ImageView user_all;
private SsxxBroadcastReceiver ssxxBroadcastReceiver;
private IntentFilter intentFilter;
@Override
public int setLayoutId() {
return R.layout.activity_ssxx;
}
@Override
public void initView() {
intentFilter = new IntentFilter(ContentUrl.ACTION); // 设置广播接收器的信息过滤器,
ssxxBroadcastReceiver = new SsxxBroadcastReceiver();
registerReceiver(ssxxBroadcastReceiver, intentFilter);
title = getIntent().getStringExtra("title");
setTitle(title);
user_all = findViewById(R.id.users_all);
}
@Override
public void initData() {
user_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UsersListActivity.go_UsersListActivity(SSXXActivity.this,"SSXX");
}
});
}
/**
* 接收PDA扫描的广播
*/
class SsxxBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("data");
Gson gson = new Gson();
ScanUserBean scanUserBean = gson.fromJson(name,ScanUserBean.class);
List<UserBean> userBeans = UserDaoOpe.queryRecord_no(SSXXActivity.this,scanUserBean.getRecord_no());
UserBean userBean = userBeans.get(0);
Intent intent2 = new Intent(SSXXActivity.this,SsxxInfomationActivity.class);
intent2.putExtra("userBean",userBean);
startActivity(intent2);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(ssxxBroadcastReceiver);
}
}
|
package com.arthur.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @program: leetcode
* @description: 扑克牌中的顺子
* @title: JZoffer61
* @Author hengmingji
* @Date: 2022/1/1 18:32
* @Version 1.0
*/
public class JZoffer61 {
public boolean isStraight(int[] nums) {
Arrays.sort(nums);
int i = 0;
int n = 0;
while (nums[i] == 0) {
i++;
n++;
}
while (i < nums.length - 1) {
if (nums[i] >= nums[i + 1]) {
return false;
} else if (nums[i] + 1 != nums[i + 1]) {
if (n >= nums[i + 1] - nums[i] - 1) {
n -= (nums[i + 1] - nums[i] - 1);
} else {
return false;
}
}
i++;
}
return true;
}
public static void main(String[] args) {
new JZoffer61().isStraight(new int[]{11,8,12,8,10});
}
}
|
package com.example.android.inventory;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class InventoryDbHelper extends SQLiteOpenHelper
{
private static final String LOG_TAG = "InventoryDbHelper";
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "Inventory.db";
private static final String TEXT_TYPE = " TEXT";
private static final String INTEGER_TYPE = " INTEGER";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + InventoryContract.ProductEntry.TABLE_NAME
+ " ("
+ InventoryContract.ProductEntry.COLUMN_ID + " INTEGER PRIMARY KEY,"
+ InventoryContract.ProductEntry.COLUMN_NAME + TEXT_TYPE + COMMA_SEP
+ InventoryContract.ProductEntry.COLUMN_PRICE + TEXT_TYPE + COMMA_SEP
+ InventoryContract.ProductEntry.COLUMN_QUANTITY + INTEGER_TYPE + COMMA_SEP
+ InventoryContract.ProductEntry.COLUMN_IMAGEPATH + TEXT_TYPE
+ " )";
private Context mContext;
public InventoryDbHelper(Context aContext)
{
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
mContext = aContext;
Log.d(LOG_TAG, "Created database:" + getDatabaseName());
}
@Override
public void onCreate(SQLiteDatabase db)
{
Log.i(LOG_TAG, "Creating table!");
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + InventoryContract.ProductEntry.TABLE_NAME);
db.execSQL(SQL_CREATE_ENTRIES);
}
public void deleteDatabase()
{
mContext.deleteDatabase(DATABASE_NAME);
}
}
|
package projekt33.kamkk.exception.base;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
@JsonIgnoreProperties({ "suppressed", "stackTrace", "cause" })
public class BaseException extends RuntimeException {
@Getter
private String errorCode;
public BaseException(String errorCode) {
this(errorCode, null, null);
}
public BaseException(String errorCode, String errorMessage) {
this(errorCode, errorMessage, null);
}
public BaseException(String errorCode, Throwable t) {
this(errorCode, null, t);
}
public BaseException(String errorCode, String errorMessage, Throwable t) {
super(errorMessage, t);
this.errorCode = errorCode;
}
}
|
package nl.jasperNiels.twitter;
import nl.jasperNiels.twitter.model.TwitterModel;
import android.app.Application;
/** Application class to make sure there is one instance of the model. */
public class TwitterApplication extends Application {
private TwitterModel model = new TwitterModel();
public TwitterModel getModel() {
return model;
}
}
|
/*
* Created on Mar 2, 2007
*
*/
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import com.citibank.ods.persistence.util.CitiStatement;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.dataset.ResultSetDataSet;
import com.citibank.ods.common.exception.NoRowsReturnedException;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.entity.pl.BaseTplClassCmplcEntity;
import com.citibank.ods.entity.pl.TplClassCmplcEntity;
import com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
/**
* @author gerson.a.rodrigues
*
*/
public class OracleTplClassCmplcDAO extends BaseOracleTplClassCmplcDAO
implements TplClassCmplcDAO
{
private static final String C_TPL_CLASS_CMPLC = C_PL_SCHEMA + "TPL_CLASS_CMPLC";
private ArrayList instantiateFromResultSet( ResultSet resultSet_ )
{
TplClassCmplcEntity tplClassCmplcEntity;
ArrayList oracleTplClassCmplcEntities = new ArrayList();
try
{
while ( resultSet_.next() )
{
tplClassCmplcEntity = new TplClassCmplcEntity();
tplClassCmplcEntity.getData().setLastUpdDate(
resultSet_.getDate( this.C_LAST_UPD_DATE ) );
tplClassCmplcEntity.getData().setLastUpdUserId(
resultSet_.getString( this.C_LAST_UPD_USER_ID ) );
tplClassCmplcEntity.getData().setClassCmplcCode(
new BigInteger(
resultSet_.getString( this.C_CLASS_CMPLC_CODE ) ) );
tplClassCmplcEntity.getData().setClassCmplcText(
resultSet_.getString( this.C_CLASS_CMPLC_TEXT ) );
tplClassCmplcEntity.getData().setSensInd(
resultSet_.getString( this.C_SENS_IND ) );
tplClassCmplcEntity.getData().setRecStatCode(
resultSet_.getString( this.C_REC_STAT_CODE ) );
oracleTplClassCmplcEntities.add( tplClassCmplcEntity );
}
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_INSTANTIATE_FROM_RESULT_SET, e );
}
return oracleTplClassCmplcEntities;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.BaseClassCmplcDAO#find(com.citibank.ods.entity.pl.BaseTplClassCmplcEntity)
*/
public BaseTplClassCmplcEntity find( BaseTplClassCmplcEntity classCmplcEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuffer query = new StringBuffer();
ArrayList tplClassCmplcEntities;
BaseTplClassCmplcEntity classCmplcEntity = null;
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT " );
query.append( C_CLASS_CMPLC_CODE + ", " );
query.append( C_CLASS_CMPLC_TEXT + ", " );
query.append( C_SENS_IND + ", " );
query.append( C_LAST_UPD_DATE + ", " );
query.append( C_LAST_UPD_USER_ID + ", " );
query.append( C_REC_STAT_CODE + " " );
query.append( " FROM " );
query.append( C_TPL_CLASS_CMPLC );
query.append( " WHERE " );
query.append( C_CLASS_CMPLC_CODE + " = ?" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
preparedStatement.setLong(
1,
classCmplcEntity_.getData().getClassCmplcCode().longValue() );
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
tplClassCmplcEntities = instantiateFromResultSet( resultSet );
if ( tplClassCmplcEntities.size() == 0 )
{
throw new NoRowsReturnedException();
}
else if ( tplClassCmplcEntities.size() > 1 )
{
throw new UnexpectedException( C_ERROR_TOO_MANY_ROWS_RETURNED );
}
else
{
classCmplcEntity = ( BaseTplClassCmplcEntity ) tplClassCmplcEntities.get( 0 );
}
return classCmplcEntity;
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO#list(java.math.BigInteger,
* java.lang.String)
*/
public DataSet list( BigInteger classCmplcCode_, String classCmplcText_,
String sensInd_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT " );
query.append( C_CLASS_CMPLC_CODE + ", " );
query.append( C_CLASS_CMPLC_TEXT + ", " );
query.append( C_SENS_IND + ", " );
query.append( C_LAST_UPD_DATE + ", " );
query.append( C_LAST_UPD_USER_ID + ", " );
query.append( C_REC_STAT_CODE + " " );
query.append( " FROM " );
query.append( C_TPL_CLASS_CMPLC );
query.append( " WHERE " );
String criteria = "";
criteria = criteria + C_REC_STAT_CODE + " != '"
+ BaseTplClassCmplcEntity.C_REC_STAT_CODE_INACTIVE + "'"
+ " AND ";
if ( classCmplcCode_ != null && classCmplcCode_.longValue() != 0 )
{
criteria = criteria + C_CLASS_CMPLC_CODE + " = ? AND ";
}
if ( classCmplcText_ != null && classCmplcText_ != "" )
{
criteria = criteria + "UPPER(\"" + C_CLASS_CMPLC_TEXT
+ "\") like ? AND ";
}
if ( sensInd_ != null && sensInd_ != "" )
{
criteria = criteria + "UPPER(\"" + C_SENS_IND + "\") like ? AND ";
}
if ( criteria.length() > 0 )
{
criteria = criteria.substring( 0, criteria.length() - 5 );
criteria = criteria + " ORDER BY " + C_CLASS_CMPLC_TEXT;
query.append( criteria );
}
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( classCmplcCode_ != null && classCmplcCode_.longValue() != 0 )
{
preparedStatement.setLong( count++, classCmplcCode_.longValue() );
}
if ( classCmplcText_ != null && classCmplcText_ != "" )
{
preparedStatement.setString( count++, "%" + classCmplcText_.toUpperCase() + "%" );
}
if ( sensInd_ != null && sensInd_ != "" )
{
preparedStatement.setString( count++, "%" + sensInd_.toUpperCase() + "%" );
}
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO#update(com.citibank.ods.entity.pl.TplOfficerCmplEntity)
*/
public void update( TplClassCmplcEntity classCmplcCurrentEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "UPDATE " + C_TPL_CLASS_CMPLC + " SET " );
query.append( C_CLASS_CMPLC_CODE + " = ?, " );
query.append( C_CLASS_CMPLC_TEXT + " = ?, " );
query.append( C_SENS_IND + " = ?, " );
query.append( C_LAST_UPD_DATE + " = ?, " );
query.append( C_LAST_UPD_USER_ID + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( classCmplcCurrentEntity_.getData().getClassCmplcCode() != null
&& classCmplcCurrentEntity_.getData().getClassCmplcCode().longValue() != 0 )
{
preparedStatement.setLong(
count++,
classCmplcCurrentEntity_.getData().getClassCmplcCode().longValue() );
}
if ( classCmplcCurrentEntity_.getData().getClassCmplcText() != null
&& classCmplcCurrentEntity_.getData().getClassCmplcText() != "" )
{
preparedStatement.setString(
count++,
classCmplcCurrentEntity_.getData().getClassCmplcText() );
}
if ( classCmplcCurrentEntity_.getData().getSensInd() != null )
{
preparedStatement.setString( count++,
classCmplcCurrentEntity_.getData().getSensInd() );
}
if ( classCmplcCurrentEntity_.getData().getLastUpdDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
classCmplcCurrentEntity_.getData().getLastUpdDate().getTime() ) );
}
if ( classCmplcCurrentEntity_.getData().getLastUpdUserId() != null
&& classCmplcCurrentEntity_.getData().getLastUpdUserId() != "" )
{
preparedStatement.setString(
count++,
classCmplcCurrentEntity_.getData().getLastUpdUserId() );
}
preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO#delete(com.citibank.ods.entity.pl.TplOfficerCmplEntity)
*/
public void delete( TplClassCmplcEntity classCmplcEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "UPDATE " + C_TPL_CLASS_CMPLC );
query.append( " SET " + C_REC_STAT_CODE + " = ? " );
query.append( " WHERE " );
query.append( C_CLASS_CMPLC_CODE + " = ?" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( classCmplcEntity_.getData().getRecStatCode() != null
&& classCmplcEntity_.getData().getRecStatCode() != "" )
{
preparedStatement.setString( count++,
classCmplcEntity_.getData().getRecStatCode() );
}
if ( classCmplcEntity_.getData().getClassCmplcCode() != null
&& classCmplcEntity_.getData().getClassCmplcCode().longValue() > 0 )
{
preparedStatement.setLong(
count++,
classCmplcEntity_.getData().getClassCmplcCode().longValue() );
}
preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO#insert(com.citibank.ods.entity.pl.TplOfficerCmplEntity)
*/
public TplClassCmplcEntity insert( TplClassCmplcEntity classCmplcEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "INSERT INTO " + C_TPL_CLASS_CMPLC + " (" );
query.append( C_CLASS_CMPLC_CODE + ", " );
query.append( C_CLASS_CMPLC_TEXT + ", " );
query.append( C_SENS_IND + ", " );
query.append( C_LAST_UPD_DATE + ", " );
query.append( C_LAST_UPD_USER_ID + ", " );
query.append( C_REC_STAT_CODE + " ) " );
query.append( " VALUES ( " );
query.append( " ?," );
query.append( " ?," );
query.append( " ?," );
query.append( " ?," );
query.append( " ?," );
query.append( " ? )" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( classCmplcEntity_.getData().getClassCmplcCode() != null
&& classCmplcEntity_.getData().getClassCmplcCode().longValue() != 0 )
{
preparedStatement.setLong(
count++,
classCmplcEntity_.getData().getClassCmplcCode().longValue() );
}
else
{
preparedStatement.setLong( count++, 0 );
}
if ( classCmplcEntity_.getData().getClassCmplcText() != null
&& classCmplcEntity_.getData().getClassCmplcText() != "" )
{
preparedStatement.setString( count++,
classCmplcEntity_.getData().getClassCmplcText() );
}
else
{
preparedStatement.setString( count++, "" );
}
if ( classCmplcEntity_.getData().getSensInd() != null )
{
preparedStatement.setString( count++, classCmplcEntity_.getData().getSensInd() );
}
else
{
preparedStatement.setString( count++, "" );
}
if ( classCmplcEntity_.getData().getLastUpdDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
classCmplcEntity_.getData().getLastUpdDate().getTime() ) );
}
else
{
preparedStatement.setTimestamp( count++, null );
}
if ( classCmplcEntity_.getData().getLastUpdUserId() != null
&& classCmplcEntity_.getData().getLastUpdUserId() != "" )
{
preparedStatement.setString( count++,
classCmplcEntity_.getData().getLastUpdUserId() );
}
else
{
preparedStatement.setString( count++, "" );
}
if ( classCmplcEntity_.getData().getRecStatCode() != null
&& classCmplcEntity_.getData().getRecStatCode() != "" )
{
preparedStatement.setString( count++,
classCmplcEntity_.getData().getRecStatCode() );
}
else
{
preparedStatement.setString( count++, "" );
}
preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return classCmplcEntity_;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO#loadDomain()
*/
public DataSet loadDomain()
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT " );
query.append( C_CLASS_CMPLC_CODE + ", " );
query.append( C_CLASS_CMPLC_TEXT + " " );
query.append( " FROM " );
query.append( C_TPL_CLASS_CMPLC );
query.append( " WHERE " );
query.append( C_REC_STAT_CODE + " <> ?" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
preparedStatement.setString( count++, C_STATUS_INATIVO );
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO#exists(com.citibank.ods.entity.pl.TplClassCmplcEntity)
*/
public boolean exists( TplClassCmplcEntity classCmplcEntity_ )
{
boolean exists = true;
try
{
this.find( classCmplcEntity_ );
}
catch ( NoRowsReturnedException e )
{
exists = false;
}
return exists;
}
}
|
package projecteuler;
import java.io.IOException;
public class DiaphontineEquation {
public static void main(String args[]) throws IOException {
int[] nums = { 2, 3, 5, 6, 7 };
int max = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 1; j < 10; j++) {
for (int k = 1; k < 10; k++) {
if (Math.pow(j, 2) - i * Math.pow(k, 2) == 1) {
if (j > max) {
max = j;
}
}
}
}
}
System.out.println("Max is " + max);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.parquet.filter2.compat;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import me.yongshang.cbfm.CBFM;
import me.yongshang.cbfm.CMDBF;
import me.yongshang.cbfm.FullBitmapIndex;
import me.yongshang.cbfm.MDBF;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.filter2.compat.FilterCompat.Filter;
import org.apache.parquet.filter2.compat.FilterCompat.NoOpFilter;
import org.apache.parquet.filter2.compat.FilterCompat.Visitor;
import org.apache.parquet.filter2.dictionarylevel.DictionaryFilter;
import org.apache.parquet.filter2.predicate.FilterPredicate;
import org.apache.parquet.filter2.predicate.Operators;
import org.apache.parquet.filter2.predicate.SchemaCompatibilityValidator;
import org.apache.parquet.filter2.statisticslevel.StatisticsFilter;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.hadoop.ParquetFileWriter;
import org.apache.parquet.hadoop.metadata.BlockMetaData;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.schema.MessageType;
import org.apache.spark.SparkContext;
import org.apache.spark.SparkEnv;
import org.apache.spark.TaskContext;
import org.apache.spark.TaskContext$;
import org.apache.spark.deploy.SparkHadoopUtil;
import static org.apache.parquet.Preconditions.checkNotNull;
/**
* Given a {@link Filter} applies it to a list of BlockMetaData (row groups)
* If the Filter is an {@link org.apache.parquet.filter.UnboundRecordFilter} or the no op filter,
* no filtering will be performed.
*/
public class RowGroupFilter implements Visitor<List<BlockMetaData>> {
private final List<BlockMetaData> blocks;
private final MessageType schema;
private final List<FilterLevel> levels;
private final ParquetFileReader reader;
public static String getIndex(){ return FullBitmapIndex.ON ? "cbfm":(MDBF.ON ? "mdbf": CMDBF.ON ? "cmdbf" : "off"); }
public static String filePath = "hdfs://tina:9000/record/"+getIndex()+"/";
public static String query;
public enum FilterLevel {
STATISTICS,
DICTIONARY
}
public static List<BlockMetaData> filterRowGroupsByVector(Filter filter, List<BlockMetaData> blocks){
List<BlockMetaData> candidateBlocks = new ArrayList<>();
for (BlockMetaData block : blocks) {
if(block.vector.equals(null)){
candidateBlocks.add(block);
}
}
return candidateBlocks;
}
public static List<BlockMetaData> filterRowGroupsByCBFM(Filter filter, List<BlockMetaData> blocks, MessageType schema){
if(blocks.isEmpty()) return blocks;
if(!(CBFM.ON || FullBitmapIndex.ON || MDBF.ON || CMDBF.ON)) return blocks;
// Only applying filters on indexed table
if (CBFM.ON && blocks.get(0).getIndexTableStr() == null) return blocks;
if (FullBitmapIndex.ON && (blocks.get(0).index == null)) return blocks;
if (MDBF.ON && (blocks.get(0).mdbfIndex == null)) return blocks;
if (CMDBF.ON && (blocks.get(0).cmdbfIndex == null)) return blocks;
List<BlockMetaData> cadidateBlocks = new ArrayList<>();
if (filter instanceof FilterCompat.FilterPredicateCompat) {
// only deal with FilterPredicateCompat
FilterCompat.FilterPredicateCompat filterPredicateCompat = (FilterCompat.FilterPredicateCompat) filter;
FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate();
List<Operators.Eq> eqFilters = new ArrayList<>();
extractEqFilter(filterPredicate, eqFilters);
String[] indexedColumns = null;
if (CBFM.ON) indexedColumns = CBFM.indexedColumns;
else if (FullBitmapIndex.ON) indexedColumns = FullBitmapIndex.dimensions;
else if (MDBF.ON) indexedColumns = MDBF.dimensions;
else if (CMDBF.ON) indexedColumns = CMDBF.dimensions;
String[] currentComb = new String[eqFilters.size()];
byte[][] indexedColumnBytes = new byte[eqFilters.size()][];
for (int j = 0; j < eqFilters.size(); ++j) {
Operators.Eq eqFilter = eqFilters.get(j);
String[] columnPath = eqFilter.getColumn().getColumnPath().toArray();
String columnName = columnPath[columnPath.length - 1];
currentComb[j] = columnName;
for (int i = 0; i < indexedColumns.length; ++i) {
if (indexedColumns[i].equals(columnName)) {
Comparable value = eqFilter.getValue();
if (value instanceof Binary) {
indexedColumnBytes[j] = ((Binary) value).getBytes();
} else if (value instanceof Integer) {
indexedColumnBytes[j] = ByteBuffer.allocate(4).putInt((Integer) value).array();
ArrayUtils.reverse(indexedColumnBytes[j]);
} else if (value instanceof Long) {
indexedColumnBytes[j] = ByteBuffer.allocate(8).putLong((Long) value).array();
ArrayUtils.reverse(indexedColumnBytes[j]);
} else if (value instanceof Float) {
indexedColumnBytes[j] = ByteBuffer.allocate(4).putFloat((Float) value).array();
ArrayUtils.reverse(indexedColumnBytes[j]);
} else if (value instanceof Double) {
indexedColumnBytes[j] = ByteBuffer.allocate(8).putDouble((Double) value).array();
ArrayUtils.reverse(indexedColumnBytes[j]);
}
}
}
}
int blockHitCount = 0;
long rowScanned = 0;
long rowSkipped = 0;
for (BlockMetaData block : blocks) {
if (CBFM.ON) {
try {
Path cbfmFile = new Path(block.getIndexTableStr());
FileSystem fs = cbfmFile.getFileSystem(new Configuration());
// TODO better way? Or is this right? escape the temp folder
cbfmFile = new Path(cbfmFile.getParent().getParent().getParent().getParent().getParent(), cbfmFile.getName());
FSDataInputStream in = fs.open(cbfmFile);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String indexTableStr = br.readLine();
br.close();
in.close();
in = null;
br.close();
br = null;
CBFM cbfm = new CBFM(indexTableStr);
ArrayList<Long> searchIndex = cbfm.calculateIdxsForSearch(indexedColumnBytes);
if (cbfm.contains(searchIndex)) {
blockHitCount++;
cadidateBlocks.add(block);
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (FullBitmapIndex.ON) {
FullBitmapIndex index = block.index;
if (index.contains(currentComb, indexedColumnBytes)) {
blockHitCount++;
cadidateBlocks.add(block);
rowScanned += block.getRowCount();
} else {
rowSkipped += block.getRowCount();
}
} else if (MDBF.ON) {
MDBF index = block.mdbfIndex;
if (index.contains(currentComb, indexedColumnBytes)) {
blockHitCount++;
cadidateBlocks.add(block);
rowScanned += block.getRowCount();
} else {
rowSkipped += block.getRowCount();
}
} else if (CMDBF.ON){
CMDBF index = block.cmdbfIndex;
if (index.contains(currentComb, indexedColumnBytes)){
blockHitCount++;
cadidateBlocks.add(block);
rowScanned += block.getRowCount();
}else{
rowSkipped += block.getRowCount();
}
}
}
int skippedCount = blocks.size() - blockHitCount;
if (checkIndexed(currentComb)) {
writeSkipResults(skippedCount, blocks.size(), rowScanned, rowSkipped);
}
}
return cadidateBlocks;
}
public static boolean checkIndexed(String[] columns){
String[] indexedColumns = null;
if(FullBitmapIndex.ON){
indexedColumns = FullBitmapIndex.dimensions;
}else if(MDBF.ON){
indexedColumns = MDBF.dimensions;
}else if(CMDBF.ON){
indexedColumns = CMDBF.dimensions;
}else{
return false;
}
for (String column : columns) {
for (String indexedColumn : indexedColumns) {
if(column.equals(indexedColumn)) return true;
}
}
return false;
}
public static boolean checkIndexed(List<ColumnDescriptor> columnList){
String[] columns = new String[columnList.size()];
for (int i = 0; i < columnList.size(); i++) {
columns[i] = columnList.get(i).getPath()[0];
}
return RowGroupFilter.checkIndexed(columns);
}
private static void writeSkipResults(int skippedCount, int totalCount, long rows, long rowSkipped){
try {
// FileSystem fs = ParquetFileWriter.getFS();
// Path path = new Path(filePath+"skip");
// FSDataOutputStream recordOut = fs.exists(path) ? fs.append(path) : fs.create(path);
// PrintWriter pw = new PrintWriter(recordOut);
File localFile = new File("/opt/record/"+RowGroupFilter.getIndex()+"/skip");
if(!localFile.exists()) localFile.createNewFile();
PrintWriter pw = new PrintWriter(new FileWriter(localFile, true));
pw.write("Task "+TaskContext.get().taskAttemptId()
+": total "+totalCount+" blocks, "+skippedCount+" blocks skipped; "
+rows+" rows scanned, "+rowSkipped+" rows skipped.\n");
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void extractEqFilter(FilterPredicate filterPredicate, List<Operators.Eq> list){
if(filterPredicate instanceof Operators.And){
Operators.And andFilter = (Operators.And) filterPredicate;
extractEqFilter(andFilter.getLeft(), list);
extractEqFilter(andFilter.getRight(), list);
}else if(filterPredicate instanceof Operators.Eq){
list.add((Operators.Eq)filterPredicate);
}
}
public static List<BlockMetaData> filterRowGroups(Filter filter, List<BlockMetaData> blocks, MessageType schema) {
checkNotNull(filter, "filter");
return filter.accept(new RowGroupFilter(blocks, schema));
}
public static List<BlockMetaData> filterRowGroups(List<FilterLevel> levels, Filter filter, List<BlockMetaData> blocks, ParquetFileReader reader) {
checkNotNull(filter, "filter");
return filter.accept(new RowGroupFilter(levels, blocks, reader));
}
@Deprecated
private RowGroupFilter(List<BlockMetaData> blocks, MessageType schema) {
this.blocks = checkNotNull(blocks, "blocks");
this.schema = checkNotNull(schema, "schema");
this.levels = Collections.singletonList(FilterLevel.STATISTICS);
this.reader = null;
}
private RowGroupFilter(List<FilterLevel> levels, List<BlockMetaData> blocks, ParquetFileReader reader) {
this.blocks = checkNotNull(blocks, "blocks");
this.reader = checkNotNull(reader, "reader");
this.schema = reader.getFileMetaData().getSchema();
this.levels = levels;
}
@Override
public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) {
FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate();
// check that the schema of the filter matches the schema of the file
SchemaCompatibilityValidator.validate(filterPredicate, schema);
List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>();
for (BlockMetaData block : blocks) {
boolean drop = false;
if(levels.contains(FilterLevel.STATISTICS)) {
drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns());
}
if(!drop && levels.contains(FilterLevel.DICTIONARY)) {
drop = DictionaryFilter.canDrop(filterPredicate, block.getColumns(), reader.getDictionaryReader(block));
}
if(!drop) {
filteredBlocks.add(block);
}
}
return filteredBlocks;
}
@Override
public List<BlockMetaData> visit(FilterCompat.UnboundRecordFilterCompat unboundRecordFilterCompat) {
return blocks;
}
@Override
public List<BlockMetaData> visit(NoOpFilter noOpFilter) {
return blocks;
}
}
|
package repeticao;
import javax.swing.JOptionPane;
public class DesafioSlide77Exer3 {
public static void main(String[] args) {
int cont = 0;
int idade_idoso=0;
int idade_jovem=0;
int idade = 0;
int maiores = 0;
int somaidade = 0;
String idoso=" ";
String jovem=" ";
do {
String nome = JOptionPane.showInputDialog("Digite o nome");
idade = Integer.parseInt(JOptionPane.showInputDialog("Idade: "));
cont++;
somaidade = somaidade+idade;
if (idade >= 18) {
maiores++;
}
if (idade > idade_idoso) {
idade_idoso = idade;
idoso=nome;
}
if (idade < idade_jovem || cont==1) {
idade_jovem = idade;
jovem=nome;
}
}while(JOptionPane.showConfirmDialog(null, "Continuar?", "Pergunta", JOptionPane.YES_NO_OPTION)==0);
JOptionPane.showMessageDialog(null, "Maiores de idade: "+(maiores)+"\nMedia idades: "+(somaidade/cont)+"\nMais Velho(a): "+idoso+ " com "+idade_idoso+" anos\n"+"Mais Jovem: "+jovem+" com "+idade_jovem+" anos");
}
}
|
package com.example.RPSGame;
public enum Throw {
ROCK, SCISSORS, PAPER
}
|
package cmc.vn.ejbca.RA.controller;
import cmc.vn.ejbca.RA.dto.request.*;
import cmc.vn.ejbca.RA.dto.respond.KeysDto;
import cmc.vn.ejbca.RA.dto.respond.TextRespondHttpClientDto;
import cmc.vn.ejbca.RA.dto.respond.VersionDto;
import cmc.vn.ejbca.RA.response.ResponseObject;
import cmc.vn.ejbca.RA.response.ResponseStatus;
import cmc.vn.ejbca.RA.service.UserService;
import cmc.vn.ejbca.RA.service.WebClientService;
import cmc.vn.ejbca.RA.service.WebService;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.ejbca.core.protocol.ws.client.gen.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.security.KeyPair;
import java.util.Base64;
import java.util.List;
@RestController
@CrossOrigin
@RequestMapping(path = "/")
@Validated
public class WebServiceController {
/**
* Connect to functions: WebServiceConnection, WebClient, User
**/
WebService connection = new WebService();
WebClientService client = new WebClientService();
UserService user = new UserService();
// Declare UserDataVOWS of EJBCA
UserDataVOWS userDataVOWS = new UserDataVOWS();
//Server connect
private static final String ipAddress = "http://localhost:4200/";
EjbcaWS ejbcaWS = null;
/**
* Connect EJBCA RA
* <p>
* Connect to server virtual machine with URL (Change in host file)
* Select trustsstore.jks & superadmin.p12
* Follow: https://download.primekey.com/docs/EJBCA-Enterprise/6_15_2/Web_Service_Interface.html
**/
public EjbcaWS connectEJBCA(EjbcaWS ejbcaWS) {
this.ejbcaWS = ejbcaWS;
return this.ejbcaWS;
}
public EjbcaWS ejbcaraws() throws Exception {
String urlstr = "https://caadmin.cmc.vn:8443/ejbca/ejbcaws/ejbcaws?wsdl";
return connection.connectService(
urlstr,
connection.pathFileTrustStore,
connection.passwordTrustStore,
connection.pathFileP12,
connection.passwordP12);
}
/**
* API for RA server connect to CA server
* <p>
* Test Postman POST body form-data
* fileP12 : file : superadmin.p12
* passwordP12 : text : ******
* fileTrustStore : file : truststore.jks
* passwordTrustStore : text : ******
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping(value = "/connect",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> connect(
@RequestBody MultipartFile fileP12, //Transmission file p12: superadmin.p12
String passwordP12, //Transmission password for file superadmin.p12
@RequestBody MultipartFile fileTrustStore, //Transmission file trustStore: truststore.jks
String passwordTrustStore //Transmission password for file truststore.jks
) throws Exception {
ResponseObject<?> res;
ResponseObject<?> saveFile = connection.connectRAtoCAServer(
fileP12,
passwordP12,
fileTrustStore,
passwordTrustStore);
if (saveFile.getResult()) {
try {
connectEJBCA(ejbcaraws());
res = connection.getAvailableCA(ejbcaWS);
} catch (Exception e) {
res = new ResponseObject<>(false, cmc.vn.ejbca.RA.response.ResponseStatus.UNHANDLED_ERROR, e.getMessage());
}
} else {
res = saveFile;
}
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* API for RA server connect to CA server
* <p>
* Test Postman POST body form-data
* fileP12 : file : superadmin.p12
* passwordP12 : text : ******
* fileTrustStore : file : truststore.jks
* passwordTrustStore : text : ******
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@GetMapping(value = "/disconnect")
public ResponseEntity<?> disconnect() throws Exception {
ResponseObject<?> res = connection.disConnectRAtoCAServer();
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Get version
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@GetMapping("/version")
public ResponseEntity<?> version() throws Exception {
ResponseObject<VersionDto> res = new ResponseObject<>(true, cmc.vn.ejbca.RA.response.ResponseStatus.DO_SERVICE_SUCCESSFUL);
try {
res.setData(new VersionDto(ejbcaWS.getEjbcaVersion()));
} catch (Exception e) {
res = new ResponseObject<>(false, ResponseStatus.UNHANDLED_ERROR, e.getMessage());
}
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Get end entity
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@GetMapping("/endentity")
public ResponseEntity<?> endentity(
) throws Exception {
ResponseObject<?> res = connection.getEndEntity(ejbcaWS);
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Get profile By Id
*
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@GetMapping("/profile")
public ResponseEntity<?> profileById(
@RequestParam String id,
@RequestParam(defaultValue = "cp") String type
) throws Exception {
ResponseObject<?> res = connection.getProfileById(ejbcaWS, id, type);
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Get available CA
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@GetMapping("/availableCA")
public ResponseEntity<?> availableCA(
) throws Exception {
ResponseObject<?> res = connection.getAvailableCA(ejbcaWS);
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Add User
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName": "ngmduc4",
"password": "1",
"clearPwd": false,
"subjectDN": "CN=ngmduc4, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"CaName": "ServerCA",
"tokenType": "USERGENERATED",
"status": 40,
"email": null,
"subjectAltName": null,
"endEntityProfileName": "EndEntityProfile",
"certificateProfileName": "EndEntityCertificateProfile",
"startTime": null
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/addOrEditUser")
public ResponseEntity<?> addOrEditUser(@RequestBody RequestOfUserAPIDto newUserAPI) throws Exception {
ResponseObject<?> res = user.addOrEditUser(userDataVOWS, ejbcaWS, newUserAPI);
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Find users
* <p>
* Test Posman POST body raw JSON
*
* MATCH_WITH_USERNAME = 0;
* MATCH_WITH_EMAIL = 1;
* MATCH_WITH_STATUS = 2;
* MATCH_WITH_ENDENTITYPROFILE = 3;
* MATCH_WITH_CERTIFICATEPROFILE = 4;
* MATCH_WITH_CA = 5;
* MATCH_WITH_TOKEN = 6;
* MATCH_WITH_DN = 7;
* MATCH_WITH_UID = 100;
* MATCH_WITH_COMMONNAME = 101;
* MATCH_WITH_DNSERIALNUMBER = 102;
* MATCH_WITH_GIVENNAME = 103;
* MATCH_WITH_INITIALS = 104;
* MATCH_WITH_SURNAME = 105;
* MATCH_WITH_TITLE = 106;
* MATCH_WITH_ORGANIZATIONALUNIT = 107;
* MATCH_WITH_ORGANIZATION = 108;
* MATCH_WITH_LOCALITY = 109;
* MATCH_WITH_STATEORPROVINCE = 110;
* MATCH_WITH_DOMAINCOMPONENT = 111;
* MATCH_WITH_COUNTRY = 112;
* MATCH_TYPE_EQUALS = 0;
* MATCH_TYPE_BEGINSWITH = 1;
* MATCH_TYPE_CONTAINS = 2;
*
*
* Get status of User after get data
* (Example: EndEntityConstants.STATUS_NEW)
* STATUS_NEW = 10; New user
* STATUS_FAILED = 11; Generation of user certificate failed
* STATUS_INITIALIZED = 20; User has been initialized
* STATUS_INPROCESS = 30; Generation of user certificate in process
* STATUS_GENERATED = 40; A certificate has been generated for the user
* STATUS_REVOKED = 50; The user has been revoked and should not have any more certificates issued
* STATUS_HISTORICAL = 60; The user is old and archived
* STATUS_KEYRECOVERY = 70; The user is should use key recovery functions in next certificate generation.
*
*
* TOKEN_TYPE_USERGENERATED = "USERGENERATED";
* TOKEN_TYPE_JKS = "JKS";
* TOKEN_TYPE_PEM = "PEM";
* TOKEN_TYPE_P12 = "P12";
*/
/*
{
"search" : "ServerCA",
"usermatch" : [5]
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/findUsers")
public ResponseEntity<?> findUsers(@RequestBody RequestOfFindUsersDto findUsers) throws Exception {
ResponseObject<?> res = user.findUsers(ejbcaWS, findUsers);
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Delete user
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName" : "nmduc16",
"reason" : 6,
"decision" : true
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/revokeUser")
public ResponseEntity<?> revokeUserService(@RequestBody RequestOfRevokeUserDto deleteUser) throws Exception {
ResponseObject<?> res = user.revokeUserService(ejbcaWS, deleteUser);
return new ResponseEntity<>(res, HttpStatus.OK);
}
/**
* Create Certificate Respond from File
* <p>
* Test Postman POST body form-data
* fileRequest : file : selectedFile.csr (ngmduc4.csr)
* userName : text : ngmduc4
* requestType : text : 0
* hardTokenSN : text :
* responseType : text : CERTIFICATE
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping(value = "/respondCertificate",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public TextRespondHttpClientDto respondCertificate(
@RequestBody MultipartFile fileRequest,
String userName,
String requestType,
String hardTokenSN,
String responseType
) throws Exception {
CertificateResponse certificateResponse = connection.certificateRequestFromFile(
ejbcaWS,
fileRequest,
user.findUserByUserName(ejbcaWS, userName), //Find the user
Integer.parseInt(requestType),
hardTokenSN,
responseType);
//change certificate Respone Data to Base64 string
return new TextRespondHttpClientDto(Base64.getEncoder().encodeToString(certificateResponse.getData()));
}
/**
* Find certificate
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName" : "ngmduc4",
"onlyValid" : false
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/findCerts")
public List<Certificate> listCerts(@RequestBody RequestOfFindCertsDto findCerts) throws Exception {
return connection.findCerts(ejbcaWS, findCerts.getUserName(), findCerts.isOnlyValid());
}
/**
* Revoke Certificate
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName" : "ngmduc4",
"onlyValid" : false,
"idCert" : 40,
"reason" : 0
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/revokeCertificate")
public Boolean revokeCertificate(@RequestBody RequestOfRevokeCertificateDto revoke) throws Exception {
return connection.revokeCertificate(
ejbcaWS,
// Find the Certificate that want to revoke
connection.findCerts(ejbcaWS, revoke.getUserName(), revoke.isOnlyValid()).get(revoke.getIdCert()),
revoke.getReason());
}
/**
* Check Revokation
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName" : "ngmduc4",
"onlyValid" : false,
"idCert" : 41
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/checkRevokation")
public RevokeStatus checkRevokation(@RequestBody RequestOfCheckRevokationDto check) throws Exception {
return connection.checkRevokation(
ejbcaWS,
connection.findCerts(ejbcaWS, check.getUserName(), check.isOnlyValid()).get(check.getIdCert()));
}
/**
* Add User
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName": "client2",
"password": "1",
"clearPwd": false,
"subjectDN": "CN=client2, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"CaName": "ServerCA",
"tokenType": "P12",
"status": 10,
"email": null,
"subjectAltName": null,
"endEntityProfileName": "EndEntityProfile",
"certificateProfileName": "EndEntityCertificateProfile",
"startTime": null
}
*/
/**
* Generate P12 KeyStore Request
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName": "client2",
"password": "1",
"hardTokenSN": null,
"keyspec": "2048",
"keyalg": "RSA"
}
**/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/p12Req")
public KeyStore p12Req(@RequestBody RequestOfPKCS12ReqAPIDto pkcs12) throws Exception {
return connection.pkcs12Req(
ejbcaWS,
pkcs12.getUsername(),
pkcs12.getPassword(),
pkcs12.getHardTokenSN(),
pkcs12.getKeyspec(),
pkcs12.getKeyalg());
}
/**
* Add User
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName": "client2",
"password": "1",
"clearPwd": false,
"subjectDN": "CN=client2, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"CaName": "ServerCA",
"tokenType": "P12",
"status": 10,
"email": null,
"subjectAltName": null,
"endEntityProfileName": "EndEntityProfile",
"certificateProfileName": "EndEntityCertificateProfile",
"startTime": null
}
*/
/**
* Generate Certificate from P12
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName": "client2",
"password": "1",
"hardTokenSN": null,
"keyspec": "2048",
"keyalg": "RSA"
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/certificateFromP12")
public TextRespondHttpClientDto certificateFromP12(@RequestBody RequestOfPKCS12ReqAPIDto pkcs12) throws Exception {
java.security.cert.Certificate certificate = connection.certificateFromP12(
// Below is Generation P12 KeyStore Request
connection.pkcs12Req(ejbcaWS, pkcs12.getUsername(), pkcs12.getPassword(), pkcs12.getHardTokenSN(), pkcs12.getKeyspec(), pkcs12.getKeyalg()),
"PKCS12",
pkcs12.getPassword());
//change certificate Data to Base64 string
return new TextRespondHttpClientDto(Base64.getEncoder().encodeToString(certificate.getEncoded()));
}
/**
* Soft Token Request
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"userName": "client5",
"password": "1",
"clearPwd": true , //have to setup default password
"subjectDN": "CN=client5, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"CaName": "ServerCA",
"tokenType": "P12", //have to setup P12
"status": 10, //have to setup NEW
"email": null,
"subjectAltName": null,
"endEntityProfileName": "EndEntityProfile",
"certificateProfileName": "EndEntityCertificateProfile",
"startTime": null,
"hardTokenS" : null,
"keyspec" : "2048",
"keyalg" : "RSA"
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/softTokenRequest")
public KeyStore softTokenRequest(@RequestBody RequestOfSoftTokenRequestDto softTokenRequest) throws Exception {
return connection.softTokenRequest(ejbcaWS, user.setUser(
userDataVOWS,
ejbcaWS,
softTokenRequest.getUserName(),
softTokenRequest.getPassword(),
softTokenRequest.isClearPwd(),
softTokenRequest.getSubjectDN(),
softTokenRequest.getCaName(),
softTokenRequest.getTokenType(),
softTokenRequest.getStatus(),
softTokenRequest.getEmail(),
softTokenRequest.getSubjectAltName(),
softTokenRequest.getEndEntityProfileName(),
softTokenRequest.getCertificateProfileName(),
softTokenRequest.getStartTime()
), softTokenRequest.getHardTokenS(), softTokenRequest.getKeyspec(), softTokenRequest.getKeyalg());
}
/**
* Generate Keys
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"keySpec" : "2048",
"keyalgorithmRsa" : "RSA"
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/generateKeys")
public KeysDto generateKeys(@RequestBody RequestOfGenerateKeysDto keys) throws Exception {
KeyPair keyPair = connection.generateKeys(keys.getKeySpec(), keys.getKeyalgorithmRsa());
return new KeysDto(
Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()), //change Public key Data to Base64 string
Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));//change Public key Data to Base64 string
}
/**
* Add User
*
* Test Posman POST body raw JSON
*/
/*
{
"userName": "client6",
"password": "1",
"clearPwd": false,
"subjectDN": "CN=client6, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"CaName": "ServerCA",
"tokenType": "USERGENERATED",
"status": 10,
"email": null,
"subjectAltName": null,
"endEntityProfileName": "EndEntityProfile",
"certificateProfileName": "EndEntityCertificateProfile",
"startTime": null
}
*/
/**
* Generate Request PKCS10
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"keySpec": "2048",
"keyalgorithmRsa": "RSA",
"signatureAlgorithm": "SHA1WithRSA",
"dn": "CN=client6, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN"
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/pkcs10CertificationRequest")
public TextRespondHttpClientDto pkcs10CertificationRequest(@RequestBody RequestOfPKCS10CertificationDto pkcs10) throws Exception {
//Generate Keys
KeyPair keys = connection.generateKeys(pkcs10.getKeySpec(), pkcs10.getKeyalgorithmRsa());
//change pkcs10 Certification Request Data to Base64 string
return new TextRespondHttpClientDto(Base64.getEncoder().encodeToString(client.pkcs10CertificationRequest(pkcs10.getSignatureAlgorithm(), pkcs10.getDn(), keys).getEncoded()));
}
/**
* Add User
*
* Test Posman POST body raw JSON **/
/*
{
"userName": "client6",
"password": "1",
"clearPwd": false,
"subjectDN": "CN=client6, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"CaName": "ServerCA",
"tokenType": "USERGENERATED",
"status": 10,
"email": null,
"subjectAltName": null,
"endEntityProfileName": "EndEntityProfile",
"certificateProfileName": "EndEntityCertificateProfile",
"startTime": null
}
*/
/**
* Get certificate respond from pkcs 10 request
* <p>
* Test Posman POST body raw JSON
*/
/*
{
"keySpec": "2048",
"keyalgorithmRsa": "RSA",
"signatureAlgorithm": "SHA1WithRSA",
"dn": "CN=client6, OU=CMC, O=CMC company, L=ha noi, ST=cau giay, C=VN",
"userName": "client6",
"password": "1",
"hardTokenSN": null,
"responseType": "CERTIFICATE"
}
*/
@CrossOrigin(origins = ipAddress) //For accept to connect to this url
@PostMapping("/certificateRequestFromP10")
public TextRespondHttpClientDto certificateRequestFromP10(@RequestBody RequestOfCertificateRequestFromP10Dto cert) throws Exception {
//Generate Keys
KeyPair keys = connection.generateKeys(cert.getKeySpec(), cert.getKeyalgorithmRsa());
//Generate pkcs10 Certification Request
PKCS10CertificationRequest pkcs10Cert = client.pkcs10CertificationRequest(cert.getSignatureAlgorithm(), cert.getDn(), keys);
//Generate Certificate Response
CertificateResponse certenv = connection.certificateRequestFromP10(
ejbcaWS,
pkcs10Cert,
cert.getUserName(),
cert.getPassword(),
cert.getHardTokenSN(),
cert.getResponseType());
//Change Certificate Response data to Base64 sring
return new TextRespondHttpClientDto(Base64.getEncoder().encodeToString(certenv.getData()));
}
}
|
package io.breen.socrates.submission;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger;
/**
* Class representing immutable objects storing information about a single file found on the file
* system that represents one part of a student's submission.
*/
public class SubmittedFile {
private static Logger logger = Logger.getLogger(SubmittedFile.class.getName());
/**
* This file's location on the file system.
*/
public final Path fullPath;
/**
* This file's location relative to the submission directory. This path should match the path
* specified in a criteria file, if this SubmittedFile is indeed relevant to grading.
*/
public final Path localPath;
/**
* This file's size in bytes.
*/
public final long size;
/**
* This file's receipt, storing the submission timestamps. If there was no receipt for this
* file, this is null.
*/
public final Receipt receipt;
public SubmittedFile(Path fullPath, Path localPath) throws IOException {
this.fullPath = fullPath;
this.localPath = localPath;
this.size = Files.size(fullPath);
this.receipt = null;
}
public SubmittedFile(Path fullPath, Path localPath, Path receipt)
throws IOException, ReceiptFormatException
{
this.fullPath = fullPath;
this.localPath = localPath;
this.size = Files.size(fullPath);
Receipt r = null;
if (receipt != null) {
r = Receipt.fromReceiptFile(receipt);
}
this.receipt = r;
}
public String toString() {
return "SubmittedFile(" +
"path=" + localPath + ", " +
"receipt=" + receipt +
")";
}
public String getContentsMixedUTF8() throws IOException {
FileInputStream inStream = new FileInputStream(fullPath.toFile());
StringBuilder builder = new StringBuilder();
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
byte[] buffer = new byte[1];
ByteBuffer wrapped = ByteBuffer.wrap(buffer);
while (true) {
if (inStream.read(buffer) == -1) break;
wrapped.rewind();
try {
CharBuffer cbuf = decoder.decode(wrapped);
builder.append(cbuf.charAt(0));
} catch (MalformedInputException | UnmappableCharacterException x) {
builder.append("�");
}
}
return builder.toString();
}
public String getContentsUTF8() throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader reader = Files.newBufferedReader(fullPath, StandardCharsets.UTF_8);
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
return builder.toString();
}
public String getContents() throws IOException {
try {
return getContentsUTF8();
} catch (IOException ignored) {}
return getContentsMixedUTF8();
}
}
|
package com.ylz.dao;
import com.ylz.entity.Seckill;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface SeckillMapper {
int deleteByPrimaryKey(Integer seckillId);
int insertSelective(Seckill record);
Seckill selectByPrimaryKey(Integer seckillId);
//分页查询
List<Seckill> selectByPage(
@Param("begin") int begin,
@Param("offset") int offset,
@Param("sort") int sort,
@Param("order") String order
);
//查询秒杀产品的总记录条数
int selectTotalCount(@Param("sort")int sort);
int updateByPrimaryKeySelective(Seckill record);
//更新库存
int updateSeckillNumber(int seckilId);
}
|
package com.example.churchapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AdminAsignStudentClass extends AppCompatActivity {
Spinner spinner;
TextView showname, showClass,showClassesStudent;
String Querry;
DbHandler mydb;
SQLiteDatabase db ;
Intent intent;
Button assignButton , unassignButton;
String StudentName;
List<String> arraySpinner;
List<String> arrayClasses;
String selecClass;
LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_asign_student_class);
StudentName = getIntent().getStringExtra("Student_Name");
showname=(TextView) findViewById(R.id.showStudentName);
showClass=(TextView) findViewById(R.id.showStudentClass);
String showNameString="Assign Class to "+StudentName;
showname.setText(showNameString);
linearLayout= (LinearLayout) findViewById(R.id.linearAddClass);
mydb = new DbHandler(this);
db = mydb.getReadableDatabase();
spinner=(Spinner) findViewById(R.id.spinneridStudent);
arraySpinner = new ArrayList<String>();
arrayClasses = new ArrayList<String>();
showTeacherClass();
fetchClasses();
// fetchAvailableClasses();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySpinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selecClass = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView <?> parent) {
}
});
assignButton=(Button) findViewById(R.id.assignclassStudent);
assignButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
int check= checkClassStudent();
if(check!=1){
mydb.insertStudentClass(StudentName, selecClass, db);
// String showNameString="Student is currently assign to :"+selecClass;
// showClass.setText(showNameString);
showTeacherClass();
}
else{
Toast.makeText(getApplicationContext(),"Already enroll in this class",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"Enter Valid Credentials",Toast.LENGTH_SHORT).show();
}
}
});
unassignButton =(Button) findViewById(R.id.unassignclassStudent);
unassignButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
int check= checkClassStudent();
if(check==1){
db.execSQL(" DELETE FROM STUDENTCLASS WHERE SNAME='"+StudentName+"' AND CNAME ='"+selecClass+"'");
Toast.makeText(getApplicationContext(),selecClass +" Un assigned Successfuly",Toast.LENGTH_SHORT).show();
showTeacherClass();
}
else{
Toast.makeText(getApplicationContext(),"Class is already not assign",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"Enter Valid Credentials",Toast.LENGTH_SHORT).show();
}
}
});
}
private int checkClassStudent(){
try {
Cursor cursor = db.rawQuery("SELECT SNAME ,CNAME FROM StudentCLASS WHERE SNAME='"+StudentName+"' AND CNAME='"+selecClass+"'", null);
if(cursor!=null) {
cursor.moveToFirst();
do {
String cname= cursor.getString(1);
return 1;
} while (cursor.moveToNext());
}
else{
Toast.makeText(getApplicationContext(),"No Student avialable in database",Toast.LENGTH_SHORT).show();
return 0;
}
}
catch (Exception e){
// Toast.makeText(getApplicationContext(),"Added",Toast.LENGTH_SHORT).show();
return 0;
}
// return 0;
}
private void addStudentClass (String name){
showClassesStudent = new TextView(this);
showClassesStudent.setText(name);
// Dbutton.setOnClickListener(getOnClickDoSomething(Dbutton));
linearLayout.addView(showClassesStudent);
}
private void showTeacherClass(){
try{
if(((LinearLayout) linearLayout).getChildCount() > 0)
((LinearLayout) linearLayout).removeAllViews();
Cursor cursor = db.rawQuery("SELECT SNAME ,CNAME FROM StudentCLASS WHERE SNAME='"+StudentName+"'", null);
if(cursor!=null) {
cursor.moveToFirst();
do {
String cname=cursor.getString(1);
String showNameString="Student is currently assign to :";
showClass.setText(showNameString);
addStudentClass(cname);
// Toast.makeText(getApplicationContext(),cname,Toast.LENGTH_SHORT).show();
} while (cursor.moveToNext());
}
else{
Toast.makeText(getApplicationContext(),"No Student avialable in database",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
// Toast.makeText(getApplicationContext(),"Enter Valid Credentials",Toast.LENGTH_SHORT).show();
}
}
// @Override
// protected void onStart() {
// super.onStart();
// for (int i=0;i<arrayClasses.size();i++)
// {
//// Toast.makeText(getApplicationContext(),arrayClasses.get(i),Toast.LENGTH_SHORT).show();
// arraySpinner.remove(arrayClasses.get(i));
// }
// }
private void fetchClasses(){
try{
Cursor cursor = db.rawQuery("SELECT CNAME FROM CLASSES", null);
if(cursor!=null) {
cursor.moveToFirst();
do {
arraySpinner.add(cursor.getString(0));
// addClass(tname);
// buffer.append("name = " + tname);
} while (cursor.moveToNext());
// Toast.makeText(getApplicationContext(),buffer,Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"No Teacher avialable in database",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Toast.makeText(getApplicationContext(),"Enter Valid Credentials",Toast.LENGTH_SHORT).show();
}
}
// private void fetchAvailableClasses(){
// try{
// Cursor cursor = db.rawQuery("SELECT CNAME FROM TEACHERCLASS", null);
// if(cursor!=null) {
// cursor.moveToFirst();
// do {
// arrayClasses.add(cursor.getString(0));
//// addClass(tname);
//// buffer.append("name = " + tname);
// } while (cursor.moveToNext());
//// Toast.makeText(getApplicationContext(),buffer,Toast.LENGTH_SHORT).show();
// }
// else{
// Toast.makeText(getApplicationContext(),"No Teacher avialable in database",Toast.LENGTH_SHORT).show();
// }
// }
// catch(Exception e){
// Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
// }
// }
}
|
/*
* WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized
* by MyEclipse Hibernate tool integration.
*
* Created Thu Nov 18 09:42:06 CST 2004 by MyEclipse Hibernate Tool.
*/
package com.aof.component.helpdesk;
import java.io.Serializable;
import com.aof.component.domain.party.UserLogin;
/**
* A class that represents a row in the Attachment table.
* You can customize the behavior of this class by editing the class, {@link Attachment()}.
* WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized * by MyEclipse Hibernate tool integration.
*/
public abstract class AbstractAttachment
implements Serializable
{
private boolean deleted;
/** The cached hash code value for this instance. Settting to 0 triggers re-calculation. */
private int hashValue = 0;
/** The composite primary key value. */
private java.lang.Integer id;
/** The value of the simple groupid property. */
private java.lang.String groupid;
/** The value of the simple name property. */
private java.lang.String name;
/** The value of the simple mime property. */
private java.lang.String mime;
/** The value of the simple size property. */
private java.lang.Integer size;
/** The value of the simple attachContent property. */
//private java.lang.String attachContent;
/** The value of the simple attachCuser property. */
// private java.lang.String attachCuser;
private UserLogin createUser;
/** The value of the simple createDate property. */
private java.util.Date createDate;
private String title;
/**
* @return Returns the title.
*/
public String getTitle() {
return title;
}
/**
* @param title The title to set.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Simple constructor of AbstractAttachment instances.
*/
public AbstractAttachment()
{
}
/**
* Constructor of AbstractAttachment instances given a simple primary key.
* @param id
*/
public AbstractAttachment(java.lang.Integer attachId)
{
this.setId(attachId);
}
/**
* Return the simple primary key value that identifies this object.
* @return java.lang.Integer
*/
public java.lang.Integer getId()
{
return id;
}
/**
* Set the simple primary key value that identifies this object.
* @param id
*/
public void setId(java.lang.Integer attachId)
{
this.hashValue = 0;
this.id = attachId;
}
/**
* Return the value of the Attach_GroupID column.
* @return java.lang.String
*/
public java.lang.String getGroupid()
{
return this.groupid;
}
/**
* Set the value of the Attach_GroupID column.
* @param groupid
*/
public void setGroupid(java.lang.String attachGroupid)
{
this.groupid = attachGroupid;
}
/**
* Return the value of the Attach_Name column.
* @return java.lang.String
*/
public java.lang.String getName()
{
return this.name;
}
/**
* Set the value of the Attach_Name column.
* @param name
*/
public void setName(java.lang.String attachName)
{
this.name = attachName;
}
/**
* Return the value of the Attach_MIME column.
* @return java.lang.String
*/
public java.lang.String getMime()
{
return this.mime;
}
/**
* Set the value of the Attach_MIME column.
* @param mime
*/
public void setMime(java.lang.String attachMime)
{
this.mime = attachMime;
}
/**
* Return the value of the Attach_Size column.
* @return java.lang.Integer
*/
public java.lang.Integer getSize()
{
return this.size;
}
/**
* Set the value of the Attach_Size column.
* @param size
*/
public void setSize(java.lang.Integer attachSize)
{
this.size = attachSize;
}
/**
* Return the value of the Attach_Content column.
* @return java.lang.String
*/
/*public java.lang.String getAttachContent()
{
return this.attachContent;
}*/
/**
* Set the value of the Attach_Content column.
* @param attachContent
*/
/*public void setAttachContent(java.lang.String attachContent)
{
this.attachContent = attachContent;
}*/
/**
* Return the value of the Attach_CDate column.
* @return java.util.Date
*/
public java.util.Date getCreateDate()
{
return this.createDate;
}
/**
* Set the value of the Attach_CDate column.
* @param createDate
*/
public void setCreateDate(java.util.Date attachCdate)
{
this.createDate = attachCdate;
}
/**
* Implementation of the equals comparison on the basis of equality of the primary key values.
* @param rhs
* @return boolean
*/
public boolean equals(Object rhs)
{
if (rhs == null)
return false;
if (! (rhs instanceof Attachment))
return false;
Attachment that = (Attachment) rhs;
if (this.getId() != null && that.getId() != null)
{
if (! this.getId().equals(that.getId()))
{
return false;
}
}
return true;
}
/**
* Implementation of the hashCode method conforming to the Bloch pattern with
* the exception of array properties (these are very unlikely primary key types).
* @return int
*/
public int hashCode()
{
if (this.hashValue == 0)
{
int result = 17;
int attachIdValue = this.getId() == null ? 0 : this.getId().hashCode();
result = result * 37 + attachIdValue;
this.hashValue = result;
}
return this.hashValue;
}
/**
* @return Returns the createUser.
*/
public UserLogin getCreateUser() {
return createUser;
}
/**
* @param createUser The createUser to set.
*/
public void setCreateUser(UserLogin createUser) {
this.createUser = createUser;
}
/**
* @return Returns the deleted.
*/
public boolean isDeleted() {
return deleted;
}
/**
* @param deleted The deleted to set.
*/
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ChessLeague.ChessLib;
/**
*
* @author D3zmodos
*/
public interface ChessListener {
public void chessEvent(ChessEvent evt);
}
|
/*
* @project: webdemo
* @package: com.jeeframework.logicframework.util.server
* @title: JeeFrameWorkServer.java
*
* Copyright (c) 2016 JeeFrameWork Limited, Inc.
* All rights reserved.
*/
package com.jeeframework.logicframework.util.server;
import com.jeeframework.core.context.support.SpringContextHolder;
import com.jeeframework.logicframework.util.server.http.HttpServer;
import com.jeeframework.logicframework.util.server.tcp.BaseNetController;
import com.jeeframework.logicframework.util.server.tcp.MinaTcpServer;
import com.jeeframework.logicframework.util.server.tcp.protocol.ProtocolParser;
import com.jeeframework.util.properties.JeeProperties;
import com.jeeframework.util.resource.ResolverUtil;
import com.jeeframework.util.string.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 基础服务类启动类
*
* @author lance
* @version 1.0 2016-03-08 18:49
*/
public class JeeFrameWorkServer {
private static final Logger Log = LoggerFactory.getLogger(HttpServer.class);
public static final String SERVER_CONFIG_FILE = "server.ini";
private static JeeProperties serverProperties = null;
public static final String NET_CONTROLLER_PACKAGES = "net.controller.packages";
private HttpServer httpServer;
private MinaTcpServer minaTcpServer;
private ApplicationContext applicationContext = null;//全局applicationContext
private static JeeFrameWorkServer instance = new JeeFrameWorkServer();
public static JeeFrameWorkServer getInstance() {
return instance;
}
private JeeFrameWorkServer() {
}
public HttpServer getHttpServer() {
return httpServer;
}
public JeeProperties getServerProperties() {
return serverProperties;
}
public void start() {
serverProperties = new JeeProperties(SERVER_CONFIG_FILE, false);
httpServer = new HttpServer();
httpServer.start();
String webroot = httpServer.getWebroot();
//根据webroot 获取 class、配置文件等
MinaTcpServer minaTcpServer = new MinaTcpServer();
minaTcpServer.start();
applicationContext = SpringContextHolder.getApplicationContext();
if (applicationContext != null) {
try {
scanAndRegistActionClass(applicationContext);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 从配置文件获得netserver的配置。
* 扫描配置的路径,并把继承NetBusiness类的Action注入容器。
*
* @param context 容器池
* @throws Exception
*/
protected static void scanAndRegistActionClass(ApplicationContext context) throws Exception {
String packages = serverProperties.getProperty(NET_CONTROLLER_PACKAGES);
;
Set<Class> actionClassesSet = new HashSet<Class>(); // 装载
// action的class
// 集合
// 扫描需要找的的action类
if (packages != null) {
// String[] names = packages.split("\\s*[,]\\s*");
// lanceyan 增加解析各个包路径,包括通配符
String[] names = StringUtils.tokenizeToStringArray(packages, ",; \t\n", true, true);
// Initialize the classloader scanner with the configured
// packages
List<String> allPackagePath = new ArrayList<String>();
if (names.length > 0) {
for (String name : names) {
name = name.replace('.', '/');
String[] resourceNames = null;
PathMatchingResourcePatternResolverWrapper resourceLoader = new PathMatchingResourcePatternResolverWrapper();
try {
// 获取根路径 modify bylanceyan ,增加获取jar包和classpath路径的方法
Resource[] actionResources = ((ResourcePatternResolver) resourceLoader)
.getResources("classpath*:" + name);
if (actionResources != null) {
resourceNames = new String[actionResources.length];
for (int i = 0; i < actionResources.length; i++) {
// 得到相对路径,然后替换为包的命名方式
resourceNames[i] = resourceLoader.getRelativeResourcesPath(actionResources[i]);
}
}
} catch (IOException e) {
Log.debug("Loaded action configuration from:getAllResource()");
}
// String[] resourceNames = PathMatchingResourcePatternResolverWrapper.getAllResource(name);
if (resourceNames != null && resourceNames.length > 0) {
for (String resourceName : resourceNames) {
allPackagePath.add(resourceName);
}
}
}
loadActionClass(actionClassesSet, allPackagePath.toArray(new String[0]));
}
}
// 注册扫描到的action
for (Object obj : actionClassesSet) {
Class cls = (Class) obj;
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
RootBeanDefinition def = new RootBeanDefinition();
def.setBeanClass(cls);
def.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME);
String beanName = StringUtils.uncapitalize(cls.getSimpleName());
System.out.println("beanName " + beanName + " loaded in context! ");
beanFactory.registerBeanDefinition(beanName, def);
}
}
/**
* 从扫描得到的action集合把继承NetBusiness的类加载到容器池。
*
* @param actionClassesSet action class集合
* @param pkgs 容器池
*/
protected static void loadActionClass(Set<Class> actionClassesSet, String[] pkgs) {
ResolverUtil<Class> resolver = new ResolverUtil<Class>();
resolver.find(new ResolverUtil.Test() {
// 回调函数,用于校验类是否是继承NetBusiness
public boolean matches(Class type) {
// TODO: should also find annotated classes
return (BaseNetController.class.isAssignableFrom(type));
}
}, pkgs);
Set<? extends Class<? extends Class>> actionClasses = resolver.getClasses();
for (Object obj : actionClasses) {
Class cls = (Class) obj;
if (!Modifier.isAbstract(cls.getModifiers())) {
// ClassPathXmlApplicationContext context1;
// context1.
actionClassesSet.add(cls);
ProtocolParser.registerNetControllerClazz(cls); // 在服务器里注册加了annotation的方法
// 比如: @Protocol(cmdId = 0x26211803, desc = "根据角色获取留言", export =
// true)
}
}
}
public static void main(String[] args) {
JeeFrameWorkServer jeeFrameWorkServer = JeeFrameWorkServer.getInstance();
jeeFrameWorkServer.start();
}
}
|
package org.rekdev.shapes;
public interface Named {
public void setName(String name);
public String getName();
}
|
package de.cuuky.varo.preset;
import java.io.File;
import java.io.IOException;
import com.google.common.io.Files;
public class PresetLoader {
private File file;
public PresetLoader(String name) {
this.file = new File("plugins/Varo/presets/" + name);
}
public void copyCurrentSettingsTo() {
if(!file.exists())
file.mkdirs();
for(File config : new File("plugins/Varo/").listFiles()) {
if(!config.isFile())
continue;
try {
Files.copy(config, new File(file.getPath() + "/" + config.getName()));
} catch(IOException e) {
e.printStackTrace();
}
}
}
public void loadSettings() {
if(!file.exists())
file.mkdirs();
for(File config : file.listFiles()) {
if(!config.isFile())
continue;
try {
Files.copy(config, new File("plugins/Varo/" + config.getName()));
} catch(IOException e) {
e.printStackTrace();
}
}
}
public File getFile() {
return file;
}
}
|
package com.clc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.clc.entity.EmployeeBean;
import com.clc.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
EmployeeService service;
@RequestMapping(value = "emps/", method = RequestMethod.GET)
public String listOfEmployee(Model model) {
// int i=10/0;
model.addAttribute("empob", new EmployeeBean());
model.addAttribute("listOfEmployy", this.service.getAllEmps());
return "empinfo";
}
@RequestMapping(value= "/addemp/", method = RequestMethod.POST)
public String saveEmpInfo(@ModelAttribute("empob") EmployeeBean p){
System.out.println("inside controller...." +p);
if(p.getId() == 0){
//new person, add it
this.service.addEmp(p);
}else{
//existing person, call update
this.service.updateEmp(p);
}
return "redirect:/emps/";
}
@RequestMapping("/remove/{id}")
public String removeEmp(@PathVariable("id") int id){
this.service.deleteEmp(id);
return "redirect:/emps/";
}
@RequestMapping("/edit/{id}")
public String editEmp(@PathVariable("id") int id, Model model){
model.addAttribute("empob", this.service.getEmp(id));
model.addAttribute("listemps", this.service.getAllEmps());
return "empinfo";
}
@ExceptionHandler(Exception.class)
public void exceptionHandle(){
System.out.println("Runtime Exception");
}
}
|
package webuters.com.geet_uttarakhand20aprilpro.activity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Created by sunil on 26-08-2016.
*/
public class StartReciever2 extends BroadcastReceiver {
Context context;
Notificationn2 nn;
@Override
public void onReceive(Context context, Intent intent) {
this.context=context;
String action = intent.getStringExtra("DO");
if(action.equalsIgnoreCase("close")){
try {
NotificationManager nMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
BluredMediaPlayer2.mediaPlayer.stop();
BluredMediaPlayer2.bm2.finish();
AppConstant.setsavedmusicplaying(context,false);
AppConstant.setmainmusicplaying(context,false);
AppConstant.setfavmusicplaying(context,false);
}
catch (Exception e){
Log.d("sunil",e.toString());
}
}
else {
if (action.equalsIgnoreCase("pause")) {
PlayPauseMethod();
}
else{
if(action.equalsIgnoreCase("next")){
nextSong();
}
else{
if(action.equalsIgnoreCase("prev")){
if(BluredMediaPlayer2.currentsongindex!=0){
BluredMediaPlayer2.startTime=0;
BluredMediaPlayer2.song_pathvalue=Setting_event.albumSongResultPOJOS.get(BluredMediaPlayer2.currentsongindex-1).getSongPath();
playMusic(BluredMediaPlayer2.song_pathvalue);
BluredMediaPlayer2.myHandler.postDelayed(BluredMediaPlayer2.UpdateSongTime, 1000);
}
}
}
}
}
//
// Intent oi = new Intent("broadCastName");
// oi.putExtra("message",action);
// context.sendBroadcast(oi);
}
public void PlayPauseMethod(){
try {
// BluredMediaPlayer2.mediaPlayer.pause();
if((BluredMediaPlayer2.mediaPlayer!=null)){
if(BluredMediaPlayer2.mediaPlayer.isPlaying()){
BluredMediaPlayer2.play_pause_button.setChecked(true);
BluredMediaPlayer2.mediaPlayer.pause();
AppConstant.setIsPlaying(context,false);
Notificationn2.changeImageView2();
}
else{
BluredMediaPlayer2.play_pause_button.setChecked(false);
BluredMediaPlayer2.mediaPlayer.start();
AppConstant.setIsPlaying(context,true);
Notificationn2.changeImageView1();
}
}else {
BluredMediaPlayer2.broad=false;
}
Log.d("sunil", "pausing2");
} catch (Exception e) {
Log.d("sunil", e.toString());
}
}
public void nextSong(){
if((BluredMediaPlayer2.currentsongindex+1)!=Setting_event.albumSongResultPOJOS.size()){
BluredMediaPlayer2.startTime=0;
BluredMediaPlayer2.song_pathvalue=Setting_event.albumSongResultPOJOS.get(BluredMediaPlayer2.currentsongindex+1).getSongPath();
playMusic(BluredMediaPlayer2.song_pathvalue);
BluredMediaPlayer2.myHandler.postDelayed(BluredMediaPlayer2.UpdateSongTime, 1000);
}
}
public void showNotification(){
//Notificationn.ctx = BlurMediaPlayer.this;
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion>= Build.VERSION_CODES.JELLY_BEAN) {
if(AppConstant.getFavMusicPref(context)){
AppConstant.SetSaveMusicpref(context,false);
AppConstant.SetmainMusicpref(context,false);
AppConstant.SetfavMusicPref(context,true);
}
else {
AppConstant.SetSaveMusicpref(context, false);
AppConstant.SetmainMusicpref(context, false);
AppConstant.SetfavMusicPref(context, true);
AppConstant.setMainCallStatus(context, false);
AppConstant.setCallStatus(context, false);
AppConstant.setSavedCallStatus(context, false);
AppConstant.setIdlePref(context, true);
AppConstant.setoffhookPref(context, true);
AppConstant.setRecievePref(context, true);
try{
NotificationManager nMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
}
catch (Exception e){
Log.d("sunil",e.toString());
}
try{
SavedSongNotification.clearNotification();
}
catch (Exception e){
}
try{
Notificationn2.clearNotification();
}
catch (Exception e){
}
try{
Notificationn.clearNotification();
}
catch (Exception e){
}
try{
BlurMediaPlayer1.mediaPlayer.stop();
}
catch (Exception e){
}
try{
BlurMediaPlayer1.bmp1.finish();
}
catch (Exception e){
}
try{
SavedSongsMusicPlayer.mediaPlayer.stop();
}
catch (Exception e){
}
try{
SavedSongsMusicPlayer.ssmp.finish();
}
catch (Exception e){
}
}
nn = new Notificationn2(context);
}
else{
new AlertDialog.Builder(context)
.setTitle("Update your phone")
.setMessage("Your phone is outdated. You may not be able to use some features. Please update your phone.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
dialog.cancel();
}
})
.show();
}
}
public void playMusic(String idUrl){
try{
if(BluredMediaPlayer2.mediaPlayer!=null)
BluredMediaPlayer2.mediaPlayer.release();
}
catch (Exception e){
}
BluredMediaPlayer2.mediaPlayer = new MediaPlayer();
showNotification();
BluredMediaPlayer2.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
//(Environment.getExternalStorageDirectory().getPath()+"/term.mp3")
BluredMediaPlayer2.mediaPlayer.setDataSource((idUrl));
} catch (IllegalArgumentException e) {
Toast.makeText(context.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(context.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(context.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
BluredMediaPlayer2.mediaPlayer.prepare();
BluredMediaPlayer2.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
nextSong();
Log.d("sunil","song completed");
}
});
BluredMediaPlayer2.mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.d("khogenprep","prepared music");
Toast.makeText(context.getApplicationContext(),"prepared",Toast.LENGTH_SHORT).show();
BluredMediaPlayer2.mediaPlayer.start();
AppConstant.setIsPlaying(context,true);
BluredMediaPlayer2.blur_linear.setVisibility(View.VISIBLE);
BluredMediaPlayer2.pb_ll.setVisibility(View.GONE);
BluredMediaPlayer2.finalTime = BluredMediaPlayer2.mediaPlayer.getDuration();
BluredMediaPlayer2.play_pause_button.setChecked(false);
BluredMediaPlayer2.total_song_time_text.setText(String.format("%d : %d ",
TimeUnit.MILLISECONDS.toMinutes((long) BluredMediaPlayer2.finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) BluredMediaPlayer2.finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) BluredMediaPlayer2.finalTime)))
);
for(int i = 0; i< Setting_event.albumSongResultPOJOS.size(); i++){
if(BluredMediaPlayer2.song_pathvalue.equals(Setting_event.albumSongResultPOJOS.get(i).getSongPath())){
BluredMediaPlayer2.currentsongindex=i;
Log.d("sunil","current_song_index:-"+BluredMediaPlayer2.currentsongindex);
}
}
AppConstant.setsavedmusicplaying(context,false);
AppConstant.setmainmusicplaying(context,false);
AppConstant.setfavmusicplaying(context,true);
BluredMediaPlayer2.myHandler.postDelayed(BluredMediaPlayer2.UpdateSongTime, 1000);
}
});
} catch (IllegalStateException e) {
Toast.makeText(context.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}catch(IOException t){
}
}
}
|
/*
* 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 excepcion;
/**
*
* @author mati
*/
public class Ej3Salida {
//Este ejercicio lanza dos excepciones desde el mismo método.
//Pero una es procesada desde le mismo método y la otra desde el método principal
}
|
package org.androware.androbeans;
import android.app.Activity;
import android.content.ContextWrapper;
import org.androware.androbeans.utils.Utils;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by jkirkley on 6/24/16.
*/
public class ObjectWriterFactory {
ContextWrapper contextWrapper;
private static ObjectWriterFactory ourInstance = null;
public static ObjectWriterFactory getInstance() {
return getInstance(null);
}
public static ObjectWriterFactory getInstance(ContextWrapper contextWrapper) {
if(ourInstance == null) {
if(contextWrapper == null) {
throw new IllegalArgumentException("Must intialize ObjectReaderFactory with an contextWrapper reference. ");
}
ourInstance = new ObjectWriterFactory(contextWrapper);
}
return ourInstance;
}
private ObjectWriterFactory(ContextWrapper contextWrapper) {
this.contextWrapper = contextWrapper;
}
public JsonObjectWriter makeJsonObjectWriter(FileOutputStream fos) throws ObjectWriteException {
try {
return new JsonObjectWriter(fos);
} catch( IOException e) {
throw new ObjectWriteException(e);
}
}
public void writeJsonObject(FileOutputStream fos, Object value) throws ObjectWriteException {
try {
JsonObjectWriter jsonObjectWriter = makeJsonObjectWriter(fos);
jsonObjectWriter.write(value);
jsonObjectWriter.close();
} catch( IOException e) {
throw new ObjectWriteException(e);
}
}
public void writeJsonObjectToExternalFile(String path, Object value) throws ObjectWriteException {
try {
FileOutputStream fos = Utils.getExternalFileOutputStream(contextWrapper, null, "", path);
writeJsonObject(fos, value);
} catch( IOException e) {
throw new ObjectWriteException(e);
}
}
public void writeJsonObjectToInternalFile(String path, Object value) throws ObjectWriteException {
try {
FileOutputStream fos = Utils.getInternalFileOutputStream(contextWrapper, path);
writeJsonObject(fos, value);
} catch( IOException e) {
throw new ObjectWriteException(e);
}
}
}
|
package com.nantian.foo.web.auth.service;
import com.nantian.foo.web.auth.entity.RoleInfo;
import com.nantian.foo.web.auth.vo.RoleBean;
import com.nantian.foo.web.util.ServiceException;
import com.nantian.foo.web.util.vo.CheckTreeNode;
import com.nantian.foo.web.util.vo.LoginBean;
import org.springframework.data.domain.Page;
public interface RoleInfoService {
/**
* 通过角色id查询
*
* @param roleId
* @return RoleBean
* @throws ServiceException
*/
public RoleBean findById(Long roleId) throws ServiceException;
/**
* 添加角色,并关联添加role_auth
*
* @param roleBean
* @return RoleBean
* @throws ServiceException
*/
public RoleBean addRoleInfo(RoleBean roleBean, LoginBean loginBean) throws ServiceException;
/**
* 更新角色信息
*
* @param roleBean
* @return RoleBean
* @throws ServiceException
*/
public RoleBean updateRoleInfo(RoleBean roleBean) throws ServiceException;
/**
* 删除角色
*
* @param roleBean
* @throws ServiceException
*/
public void delRoleInfo(RoleBean roleBean) throws ServiceException;
/**
* 根据条件分页查询角色信息
*
* @param page int
* @param size int
* @param roleBean RoleBean
* @param loginBean LoginBean
* @return Page<RoleInfo>
* @throws ServiceException ServiceException
*/
public Page<RoleInfo> findByCondition(int page, int size, RoleBean roleBean, LoginBean loginBean) throws ServiceException;
/**
* 获取角色对应编辑的权限树
* @param roleId 角色ID
* @return CheckTreeNode 权限树
*/
public CheckTreeNode loadAuthorityCheckTree(LoginBean loginBean, Long roleId) throws ServiceException;
/**
* 角色编辑前,查询授权和获取角色信息
*
* @param roleId 角色ID
* @param loginBean 编辑者信息
* @return RoleBean
*/
public RoleBean beforeUpdateRole(LoginBean loginBean, Long roleId) throws ServiceException;
/**
* 判断是否可以删除角色
* @param roleBean RoleBean 角色信息
* @param loginBean LoginBean 编辑者信息
*/
public void checkCanRemoveRole(RoleBean roleBean, LoginBean loginBean) throws ServiceException;
public void findIsExitRoleByCreator(String userName) throws ServiceException, com.nantian.foo.web.util.ServiceException;
}
|
package com.soa.zad1;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.Properties;
public class CurrencyUtil {
public static Double covert(Double value, String in, String out) {
String propertyKey = in + "." + out;
Double propertyValue = Double.valueOf(Objects.requireNonNull(getProperty(propertyKey)));
return new BigDecimal(value * propertyValue).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
private static String getProperty(String key) {
try {
Properties properties = new Properties();
properties.load(CurrencyUtil.class.getClassLoader().getResourceAsStream("currency.properties"));
return properties.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
package com.cs.job.player;
import com.cs.payment.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author Omid Alaepour
*/
@Component
public class ResetPlayerMonthlyTurnoverJob implements Job {
private PaymentService paymentService;
@Autowired
public void setPaymentService(final PaymentService paymentService) {
this.paymentService = paymentService;
}
@Override
public void execute(final JobExecutionContext context)
throws JobExecutionException {
paymentService.resetMonthlyTurnover();
}
}
|
package collections;
import java.util.Comparator;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
class Produto {
int id;
String nome;
int qtd;
public Produto(int id, String nome, int qtd) {
super();
this.id = id;
this.nome = nome;
this.qtd = qtd;
}
}
class ComparadorProdutoByQtd implements Comparator {
public int compare(Object o1, Object o2) {
Produto pThis = (Produto) o1;
Produto p = (Produto) o2;
if (p.qtd == pThis.qtd) {
return 0;
} else if (p.qtd > pThis.qtd) {
return -1;
} else {
return +1;
}
}
}
class ComparacaoProdutoByNome implements Comparator {
public int compare(Object o1, Object o2) {
Produto pThis = (Produto) o1;
Produto p = (Produto) o2;
if (p.nome.equals(pThis.nome)) {
return 0;
} else {
return pThis.nome.compareTo(p.nome);
}
}
}
public class Test_SortedSet {
public static void main(String[] args) {
//ComparadorProdutoByQtd comparacao = new ComparadorProdutoByQtd();
ComparacaoProdutoByNome comparacao = new ComparacaoProdutoByNome();
SortedSet ordenacao = new TreeSet(comparacao);
Produto p1 = new Produto(1, "TV", 2);
Produto p2 = new Produto(2, "Apostila", 3);
Produto p3 = new Produto(3, "CD", 1);
Produto p4 = new Produto(4, "Carro", 0);
ordenacao.add(p1);
ordenacao.add(p2);
ordenacao.add(p3);
ordenacao.add(p4);
for (Object obj : ordenacao) {
Produto py = (Produto) obj;
System.out.println(py.nome + " - " + py.qtd);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.